-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdetect.go
More file actions
230 lines (219 loc) · 7.83 KB
/
Copy pathdetect.go
File metadata and controls
230 lines (219 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package agenthooks
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
)
// invocation is the parsed argv contract baked into generated configs:
//
// mybinary agenthooks run --provider=claude-code # stdin JSON
// mybinary agenthooks run --provider=cursor --argv-payload # legacy cursor CLI
// mybinary agenthooks notify --provider=codex # legacy codex notify (argv JSON)
// mybinary agenthooks serve --provider=opencode # NDJSON daemon for the shim
type invocation struct {
mode string // "run", "notify", "serve"
provider Provider
variant Variant
confidence DetectionConfidence
argvPayload bool
payload string
timeout time.Duration
filter *ToolMatcher
}
var validProviders = map[Provider]bool{
ProviderClaudeCode: true,
ProviderCursor: true,
ProviderCodex: true,
ProviderGemini: true,
ProviderOpenCode: true,
ProviderOpenClaw: true,
ProviderKimi: true,
ProviderCopilot: true,
}
func parseArgs(args []string) (*invocation, error) {
inv := &invocation{mode: "run"}
rest := args
// Generated configs put consumer-binary flags before the sentinel
// ("mybinary --config=x agenthooks serve --provider=opencode"), so the
// sentinel and mode are located anywhere in argv, not just at the front.
// Everything before the sentinel belongs to the consumer and is dropped
// from agenthooks parsing.
for i, a := range rest {
if a == "agenthooks" {
rest = rest[i+1:]
break
}
}
if len(rest) > 0 {
switch rest[0] {
case "run", "notify", "serve":
inv.mode = rest[0]
rest = rest[1:]
}
}
var positional []string
for _, a := range rest {
switch {
case a == "--argv-payload":
inv.argvPayload = true
case strings.HasPrefix(a, "--provider="):
p := Provider(strings.TrimPrefix(a, "--provider="))
if p == "kimi" {
p = ProviderKimi
}
if !validProviders[p] {
return nil, fmt.Errorf("agenthooks: unknown provider %q", p)
}
inv.provider = p
inv.confidence = DetectionConfig
case strings.HasPrefix(a, "--variant="):
inv.variant = Variant(strings.TrimPrefix(a, "--variant="))
case strings.HasPrefix(a, "--timeout="):
d, err := time.ParseDuration(strings.TrimPrefix(a, "--timeout="))
if err != nil {
return nil, fmt.Errorf("agenthooks: bad --timeout: %w", err)
}
inv.timeout = d
case strings.HasPrefix(a, "--filter="):
m, err := ParseToolMatcher(strings.TrimPrefix(a, "--filter="))
if err != nil {
return nil, err
}
inv.filter = &m
case strings.HasPrefix(a, "--"):
// Unknown flags are tolerated for forward compatibility with
// newer generated configs driving older library versions.
default:
positional = append(positional, a)
}
}
inv.payload = strings.Join(positional, " ")
return inv, nil
}
// detectProvider resolves the invoking provider. Flag-first is a hard rule:
// Codex and Cursor deliberately export CLAUDE_* compat vars (quirk #20), so
// env sniffing alone is insufficient. Shape sniffing is the last resort.
func detectProvider(inv *invocation, payload []byte) (Provider, DetectionConfidence) {
if inv.provider != "" {
return inv.provider, DetectionConfig
}
if p, ok := detectFromEnv(); ok {
return p, DetectionEnv
}
if p, ok := detectFromShape(payload); ok {
return p, DetectionShape
}
return "", ""
}
func detectFromEnv() (Provider, bool) {
// Provider-unique vars first; CLAUDE_* last because it is cross-set.
if os.Getenv("CURSOR_VERSION") != "" || os.Getenv("CURSOR_TRACE_ID") != "" || os.Getenv("CURSOR_AGENT") != "" {
return ProviderCursor, true
}
if os.Getenv("CODEX_HOME") != "" || os.Getenv("CODEX_SANDBOX") != "" {
return ProviderCodex, true
}
if os.Getenv("GEMINI_CWD") != "" || os.Getenv("GEMINI_CLI") != "" {
return ProviderGemini, true
}
if os.Getenv("OPENCODE_SERVER") != "" || os.Getenv("OPENCODE") != "" {
return ProviderOpenCode, true
}
// Copilot cross-sets CLAUDE_PLUGIN_ROOT/CLAUDE_PROJECT_DIR into hook
// processes (observed on CLI 1.0.80), so it must be checked before Claude.
if os.Getenv("COPILOT_CLI") != "" || os.Getenv("COPILOT_PLUGIN_ROOT") != "" || os.Getenv("COPILOT_PLUGIN_DATA") != "" {
return ProviderCopilot, true
}
if os.Getenv("CLAUDE_PROJECT_DIR") != "" || os.Getenv("CLAUDE_PLUGIN_ROOT") != "" {
return ProviderClaudeCode, true
}
return "", false
}
func detectFromShape(payload []byte) (Provider, bool) {
var probe struct {
HookEventName string `json:"hook_event_name"`
ConversationID string `json:"conversation_id"`
TurnID string `json:"turn_id"`
ToolCallID string `json:"tool_call_id"`
// Raw, not string: Copilot ships an epoch-ms NUMBER here and a typed
// mismatch would fail the whole probe, not just this field.
Timestamp json.RawMessage `json:"timestamp"`
SessionIDCamel string `json:"sessionId"`
Seq json.RawMessage `json:"seq"`
Hook string `json:"hook"`
Event json.RawMessage `json:"event"`
}
if err := json.Unmarshal(payload, &probe); err != nil {
return "", false
}
switch {
// Both shim dialects frame as {seq, hook, ...}; OpenClaw carries the
// payload under "event" (+"ctx"), OpenCode under "input"/"output".
case probe.Hook != "" && jsonPresent(probe.Seq) && jsonPresent(probe.Event):
return ProviderOpenClaw, true
case probe.Hook != "" && jsonPresent(probe.Seq):
return ProviderOpenCode, true
// Copilot is the only dialect keying the session on camelCase sessionId;
// its payloads carry no event-name field at all on most events, so this is
// the discriminator (verified against Copilot CLI 1.0.80).
case probe.SessionIDCamel != "":
return ProviderCopilot, true
case probe.ConversationID != "":
return ProviderCursor, true
case probe.HookEventName != "" && isCamel(probe.HookEventName):
return ProviderCursor, true
// A JSON null decodes into RawMessage as the 4-byte literal, so presence
// is len>0 AND not null — otherwise `"timestamp": null` would read as set.
case geminiKinds[probe.HookEventName] != "" && (jsonPresent(probe.Timestamp) || claudeKinds[probe.HookEventName] == ""):
return ProviderGemini, true
case probe.TurnID != "":
return ProviderCodex, true
// Kimi is Claude-shaped; the reliable discriminators are its tool_call_id
// key (Claude uses tool_use_id) and its Kimi-only event names.
case probe.HookEventName != "" && probe.ToolCallID != "":
return ProviderKimi, true
case kimiOnlyEvents[probe.HookEventName]:
return ProviderKimi, true
case probe.HookEventName != "":
return ProviderClaudeCode, true
}
return "", false
}
// kimiOnlyEvents are native event names Kimi fires that no Claude-shaped
// sibling dialect has.
var kimiOnlyEvents = map[string]bool{
"PermissionResult": true,
"StopFailure": true,
"Interrupt": true,
}
// jsonPresent reports whether a probe field was set to something other than
// null. Probe fields are json.RawMessage so a type mismatch cannot fail the
// whole unmarshal, and that also means an explicit null arrives as a non-empty
// 4-byte literal rather than as an absent field.
func jsonPresent(raw json.RawMessage) bool {
return len(raw) > 0 && string(raw) != "null"
}
func isCamel(s string) bool {
return s != "" && s[0] >= 'a' && s[0] <= 'z' && strings.ContainsFunc(s, func(r rune) bool { return r >= 'A' && r <= 'Z' })
}
// detectVariant encodes the runtime tricks that distinguish provider
// sub-flavors (§6). Best-effort by design; "" means unknown/default.
func detectVariant(p Provider) Variant {
switch p {
case ProviderClaudeCode:
if os.Getenv("CLAUDE_CODE_REMOTE") != "" {
return VariantRemote
}
// cowork: cmux-managed project dirs are the observable signature.
if dir := os.Getenv("CLAUDE_PROJECT_DIR"); strings.Contains(dir, "/cmux/") || strings.Contains(dir, "/cowork/") {
return VariantCowork
}
case ProviderCursor:
if os.Getenv("CURSOR_AGENT") != "" {
return VariantCLI
}
}
return VariantUnknown
}