@mainwave/cli 0.6.1 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +97 -18
- package/dist/adapters/claude-code.js +258 -38
- package/dist/adapters/claude-code.js.map +1 -1
- package/dist/adapters/claude-desktop.js +0 -87
- package/dist/adapters/claude-desktop.js.map +1 -1
- package/dist/adapters/codex-cli.js +0 -65
- package/dist/adapters/codex-cli.js.map +1 -1
- package/dist/adapters/copilot-chat.js +7 -42
- package/dist/adapters/copilot-chat.js.map +1 -1
- package/dist/adapters/copilot-cli.js +7 -32
- package/dist/adapters/copilot-cli.js.map +1 -1
- package/dist/adapters/cursor-enterprise.js +4 -53
- package/dist/adapters/cursor-enterprise.js.map +1 -1
- package/dist/adapters/cursor.js +0 -62
- package/dist/adapters/cursor.js.map +1 -1
- package/dist/api/index.js +0 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/types.gen.js +0 -1
- package/dist/api/types.gen.js.map +1 -1
- package/dist/core/apply.js +73 -97
- package/dist/core/apply.js.map +1 -1
- package/dist/core/auth-commands.js +5 -20
- package/dist/core/auth-commands.js.map +1 -1
- package/dist/core/behaviour-hooks.js +0 -7
- package/dist/core/behaviour-hooks.js.map +1 -1
- package/dist/core/browser.js +0 -18
- package/dist/core/browser.js.map +1 -1
- package/dist/core/codecs/cursor-hooks-json.js +0 -8
- package/dist/core/codecs/cursor-hooks-json.js.map +1 -1
- package/dist/core/codecs/json-flat.js +0 -28
- package/dist/core/codecs/json-flat.js.map +1 -1
- package/dist/core/codecs/json-managed.js +0 -30
- package/dist/core/codecs/json-managed.js.map +1 -1
- package/dist/core/codecs/toml-otel.js +0 -39
- package/dist/core/codecs/toml-otel.js.map +1 -1
- package/dist/core/detect.js +0 -29
- package/dist/core/detect.js.map +1 -1
- package/dist/core/device-login.js +0 -22
- package/dist/core/device-login.js.map +1 -1
- package/dist/core/doctor.js +209 -48
- package/dist/core/doctor.js.map +1 -1
- package/dist/core/edit.js +18 -0
- package/dist/core/edit.js.map +1 -1
- package/dist/core/effective-settings.js +107 -10
- package/dist/core/effective-settings.js.map +1 -1
- package/dist/core/env-command.js +0 -9
- package/dist/core/env-command.js.map +1 -1
- package/dist/core/errors.js +0 -12
- package/dist/core/errors.js.map +1 -1
- package/dist/core/flags.js +0 -13
- package/dist/core/flags.js.map +1 -1
- package/dist/core/format.js +0 -56
- package/dist/core/format.js.map +1 -1
- package/dist/core/git.js +0 -9
- package/dist/core/git.js.map +1 -1
- package/dist/core/headers.js +4 -97
- package/dist/core/headers.js.map +1 -1
- package/dist/core/install-hooks.js +81 -0
- package/dist/core/install-hooks.js.map +1 -0
- package/dist/core/interview.js +25 -151
- package/dist/core/interview.js.map +1 -1
- package/dist/core/keys.js +0 -18
- package/dist/core/keys.js.map +1 -1
- package/dist/core/layer-policy.js +34 -0
- package/dist/core/layer-policy.js.map +1 -0
- package/dist/core/markers.js +220 -117
- package/dist/core/markers.js.map +1 -1
- package/dist/core/pinned-use-case.js +11 -0
- package/dist/core/pinned-use-case.js.map +1 -0
- package/dist/core/platform.js +5 -47
- package/dist/core/platform.js.map +1 -1
- package/dist/core/post-setup.js +7 -18
- package/dist/core/post-setup.js.map +1 -1
- package/dist/core/prompts.js +0 -59
- package/dist/core/prompts.js.map +1 -1
- package/dist/core/settings.js +20 -16
- package/dist/core/settings.js.map +1 -1
- package/dist/core/skills.js +0 -75
- package/dist/core/skills.js.map +1 -1
- package/dist/core/status.js +97 -45
- package/dist/core/status.js.map +1 -1
- package/dist/core/store.js +4 -34
- package/dist/core/store.js.map +1 -1
- package/dist/core/tty.js +0 -9
- package/dist/core/tty.js.map +1 -1
- package/dist/core/ucid.js +0 -13
- package/dist/core/ucid.js.map +1 -1
- package/dist/core/ui.js +0 -11
- package/dist/core/ui.js.map +1 -1
- package/dist/core/use-case.js +3 -49
- package/dist/core/use-case.js.map +1 -1
- package/dist/core/validate.js +0 -5
- package/dist/core/validate.js.map +1 -1
- package/dist/core/verify.js +51 -33
- package/dist/core/verify.js.map +1 -1
- package/dist/core/version.js +0 -3
- package/dist/core/version.js.map +1 -1
- package/dist/core/wizard.js +172 -128
- package/dist/core/wizard.js.map +1 -1
- package/dist/main.js +16 -38
- package/dist/main.js.map +1 -1
- package/hooks/cursor-otlp.mjs +4 -4
- package/hooks/github-pr-marker.mjs +31 -12
- package/hooks/jira-ticket-marker.mjs +46 -27
- package/hooks/linear-ticket-marker.mjs +58 -37
- package/hooks/marker-core.mjs +671 -59
- package/hooks/matchers.json +1 -1
- package/hooks/vocabulary.d.mts +9 -1
- package/hooks/vocabulary.mjs +73 -23
- package/package.json +3 -3
- package/skills/mainwave-instrument/SKILL.md +6 -5
- package/skills/mainwave-instrument/reference/frameworks.md +33 -22
- package/skills/mainwave-instrument/reference/troubleshooting.md +13 -4
- package/skills/mainwave-setup/SKILL.md +22 -6
package/hooks/marker-core.mjs
CHANGED
|
@@ -1,19 +1,28 @@
|
|
|
1
|
-
// Shared plumbing for the Mainwave PostToolUse marker hooks
|
|
1
|
+
// Shared plumbing for the Mainwave PostToolUse marker hooks.
|
|
2
2
|
//
|
|
3
3
|
// Both the Linear ticket-marker and the GitHub PR-marker hooks emit one small
|
|
4
4
|
// OTLP span to the same collector Claude Code already exports to, reading the
|
|
5
|
-
// endpoint / auth / ucid from the same
|
|
6
|
-
// (
|
|
7
|
-
// the half they share: config resolution, resource-attr neutralization
|
|
5
|
+
// endpoint / auth / ucid from the same settings `env` blocks Claude Code reads
|
|
6
|
+
// (it does not hand its OTLP env to hook subprocesses). This module is
|
|
7
|
+
// the half they share: config resolution, resource-attr neutralization,
|
|
8
8
|
// payload building, and the fail-open emit. Each hook keeps only its own
|
|
9
9
|
// extraction logic and `main()`.
|
|
10
10
|
|
|
11
11
|
import { randomBytes } from 'node:crypto'
|
|
12
|
-
import { appendFileSync, readFileSync } from 'node:fs'
|
|
12
|
+
import { appendFileSync, readFileSync, readdirSync } from 'node:fs'
|
|
13
13
|
import { homedir } from 'node:os'
|
|
14
|
-
import { join } from 'node:path'
|
|
14
|
+
import { dirname, join, resolve } from 'node:path'
|
|
15
15
|
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
ATTR_CALLER_SPAN_ID,
|
|
18
|
+
ATTR_CALLER_TRACE_ID,
|
|
19
|
+
ATTR_HOST_SOURCE,
|
|
20
|
+
ATTR_SCHEMA_VERSION,
|
|
21
|
+
ATTR_SUBAGENT_ID,
|
|
22
|
+
ATTR_TOOL_CALL_ID,
|
|
23
|
+
MARKER_HOST_SOURCES,
|
|
24
|
+
SCHEMA_VERSION,
|
|
25
|
+
} from './vocabulary.mjs'
|
|
17
26
|
|
|
18
27
|
const EMIT_TIMEOUT_MS = 3000
|
|
19
28
|
|
|
@@ -58,19 +67,73 @@ export const settingsEnv = (text) => {
|
|
|
58
67
|
}
|
|
59
68
|
}
|
|
60
69
|
|
|
70
|
+
/** The two OTLP keys that choose where a marker is sent and with what key.
|
|
71
|
+
* Claude Code 2.1.282+ ignores these in project and local settings, because a
|
|
72
|
+
* checked-out repository must not be able to redirect telemetry; the hooks
|
|
73
|
+
* apply the same rule so a repository can't redirect markers either. */
|
|
74
|
+
const EXPORTER_KEYS = ['OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS']
|
|
75
|
+
|
|
76
|
+
/** The keys Claude Code applies from managed settings as one unit — the
|
|
77
|
+
* highest managed source setting any of them supplies all of them. The CLI's
|
|
78
|
+
* own settings view uses the same set; keep the two in sync. */
|
|
79
|
+
const isManagedTelemetryUnitKey = (key) =>
|
|
80
|
+
key.startsWith('OTEL_EXPORTER_OTLP_') ||
|
|
81
|
+
key.startsWith('OTEL_LOG_') ||
|
|
82
|
+
key === 'OTEL_LOGS_EXPORTER' ||
|
|
83
|
+
key === 'ENABLE_BETA_TRACING_DETAILED' ||
|
|
84
|
+
key === 'BETA_TRACING_ENDPOINT'
|
|
85
|
+
|
|
86
|
+
/** Managed OTLP credentials. When managed settings set one, Claude Code
|
|
87
|
+
* removes every developer-set endpoint, so a developer's collector never gets
|
|
88
|
+
* the org's key; a managed endpoint alone keeps the developer's own key. The
|
|
89
|
+
* CLI's settings view applies the full rule; keep the two in sync.
|
|
90
|
+
* https://code.claude.com/docs/en/monitoring-usage#how-managed-settings-lock-the-otlp-destination */
|
|
91
|
+
const MANAGED_CREDENTIAL_KEYS = [
|
|
92
|
+
'OTEL_EXPORTER_OTLP_HEADERS',
|
|
93
|
+
'OTEL_EXPORTER_OTLP_CLIENT_KEY',
|
|
94
|
+
'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',
|
|
95
|
+
]
|
|
96
|
+
|
|
61
97
|
/**
|
|
62
|
-
* Merge
|
|
63
|
-
* top, and pull out the OTLP config the hooks need.
|
|
64
|
-
*
|
|
98
|
+
* Merge settings layers (lowest precedence first), overlay any real process env
|
|
99
|
+
* on top, and pull out the OTLP config the hooks need. A layer is
|
|
100
|
+
* `{ env, exporter, managed }`:
|
|
101
|
+
*
|
|
102
|
+
* - `exporter: false` layers (project and local settings) contribute only
|
|
103
|
+
* `OTEL_RESOURCE_ATTRIBUTES`, never the endpoint or key.
|
|
104
|
+
* - Across `managed` layers the telemetry unit travels together: its keys come
|
|
105
|
+
* from the highest managed source that sets any of them, never an endpoint
|
|
106
|
+
* from one source with a key from another. Other keys merge per key.
|
|
107
|
+
* - Over the developer's own layers, managed settings win key by key, and a
|
|
108
|
+
* managed credential also removes the developer's endpoint (§
|
|
109
|
+
* `MANAGED_CREDENTIAL_KEYS`).
|
|
110
|
+
*
|
|
111
|
+
* The process env overlay only matters for a hook run by hand — Claude Code
|
|
112
|
+
* removes `OTEL_*` variables from the environment it gives hooks.
|
|
65
113
|
*/
|
|
66
|
-
export const resolveOtelConfig = (
|
|
67
|
-
const
|
|
68
|
-
for (const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
114
|
+
export const resolveOtelConfig = (layers, processEnv) => {
|
|
115
|
+
const developer = {}
|
|
116
|
+
for (const { env, exporter, managed } of layers) {
|
|
117
|
+
if (managed) continue
|
|
118
|
+
for (const [k, v] of Object.entries(env ?? {})) {
|
|
119
|
+
if (exporter || !EXPORTER_KEYS.includes(k)) developer[k] = v
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const managedLayers = layers.filter(({ managed }) => managed)
|
|
123
|
+
const unitLayer = [...managedLayers]
|
|
124
|
+
.reverse()
|
|
125
|
+
.find(({ env }) => Object.keys(env ?? {}).some(isManagedTelemetryUnitKey))
|
|
126
|
+
const managedEnv = {}
|
|
127
|
+
for (const layer of managedLayers) {
|
|
128
|
+
for (const [k, v] of Object.entries(layer.env ?? {})) {
|
|
129
|
+
if (!isManagedTelemetryUnitKey(k) || layer === unitLayer) managedEnv[k] = v
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (MANAGED_CREDENTIAL_KEYS.some((k) => managedEnv[k])) {
|
|
133
|
+
delete developer.OTEL_EXPORTER_OTLP_ENDPOINT
|
|
134
|
+
}
|
|
135
|
+
const merged = { ...developer, ...managedEnv }
|
|
136
|
+
for (const k of [...EXPORTER_KEYS, 'OTEL_RESOURCE_ATTRIBUTES']) {
|
|
74
137
|
if (processEnv[k]) merged[k] = processEnv[k]
|
|
75
138
|
}
|
|
76
139
|
return {
|
|
@@ -88,13 +151,187 @@ const readFileSafe = (path) => {
|
|
|
88
151
|
}
|
|
89
152
|
}
|
|
90
153
|
|
|
91
|
-
/**
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
154
|
+
/** `CLAUDE_CONFIG_DIR`, ASCII-trimmed and resolved to an absolute path, or
|
|
155
|
+
* `undefined` when unset or blank — a whitespace-only value counts as unset.
|
|
156
|
+
* For the settings root (§ `claudeConfigDir`) only: the account cache is
|
|
157
|
+
* resolved from the raw value, exactly as Claude Code does
|
|
158
|
+
* (§ `claudeCodeOauthAccount`). */
|
|
159
|
+
const normalizedConfigDirEnv = (env) => {
|
|
160
|
+
const dir = env.CLAUDE_CONFIG_DIR?.trim()
|
|
161
|
+
return dir ? resolve(dir) : undefined
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Claude Code's user config root: `$CLAUDE_CONFIG_DIR` when set, else
|
|
165
|
+
* `~/.claude`. The hook runs as a Claude Code subprocess, so it sees
|
|
166
|
+
* the same variable the session resolved its own settings from, and the CLI
|
|
167
|
+
* resolves it the same way. A repository can't steer
|
|
168
|
+
* this through its project settings: Claude Code drops `CLAUDE_CONFIG_DIR`,
|
|
169
|
+
* `HOME` and the other directory variables from project and local `env`
|
|
170
|
+
* (since 2.1.251), so neither reaches the hook from there. */
|
|
171
|
+
export const claudeConfigDir = (env = process.env) =>
|
|
172
|
+
normalizedConfigDirEnv(env) ?? join(homedir(), '.claude')
|
|
173
|
+
|
|
174
|
+
/** A directory's `*.json` files, sorted, or `[]` when it is missing. */
|
|
175
|
+
const jsonFilesIn = (dir) => {
|
|
176
|
+
try {
|
|
177
|
+
return readdirSync(dir)
|
|
178
|
+
.filter((name) => name.endsWith('.json') && !name.startsWith('.'))
|
|
179
|
+
.sort()
|
|
180
|
+
.map((name) => join(dir, name))
|
|
181
|
+
} catch {
|
|
182
|
+
return []
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Claude Code's managed sources, lowest precedence first. The file-based tier —
|
|
188
|
+
* the OS `managed-settings.json`, then its `managed-settings.d/` drop-ins in
|
|
189
|
+
* alphabetical order, later files winning — is one source; the server-managed
|
|
190
|
+
* cache (`remote-settings.json` in the config dir), which Claude Code writes
|
|
191
|
+
* from the org's admin console, is another and outranks it. `managedDir`
|
|
192
|
+
* replaces the system directory (the hooks' `--managed-settings-dir` flag, for
|
|
193
|
+
* tests); `listDir` is overridable so a test never reads a real system directory.
|
|
194
|
+
* https://code.claude.com/docs/en/managed-settings#how-claude-code-combines-managed-sources
|
|
195
|
+
*/
|
|
196
|
+
export const managedSources = (
|
|
197
|
+
env = process.env,
|
|
198
|
+
listDir = jsonFilesIn,
|
|
199
|
+
managedDir,
|
|
200
|
+
bypassed = serverManagedBypassed(env),
|
|
201
|
+
) => {
|
|
202
|
+
const file = managedSettingsPath(managedDir)
|
|
203
|
+
return [
|
|
204
|
+
{ id: 'file', paths: [file, ...listDir(join(dirname(file), 'managed-settings.d'))] },
|
|
205
|
+
...(bypassed
|
|
206
|
+
? []
|
|
207
|
+
: [{ id: 'server', paths: [join(claudeConfigDir(env), 'remote-settings.json')] }]),
|
|
208
|
+
]
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Third-party provider selection flags. Claude Code treats them as booleans —
|
|
212
|
+
* only a truthy value (§ `isTruthyEnvValue`) selects the provider. A session
|
|
213
|
+
* on one authenticates with the provider's credentials, not Claude.ai OAuth,
|
|
214
|
+
* and skips server-managed settings.
|
|
215
|
+
* https://code.claude.com/docs/en/server-managed-settings#security-considerations */
|
|
216
|
+
const PROVIDER_FLAGS = [
|
|
217
|
+
'CLAUDE_CODE_USE_BEDROCK',
|
|
218
|
+
'CLAUDE_CODE_USE_VERTEX',
|
|
219
|
+
'CLAUDE_CODE_USE_FOUNDRY',
|
|
220
|
+
'CLAUDE_CODE_USE_MANTLE',
|
|
221
|
+
'CLAUDE_CODE_USE_ANTHROPIC_AWS',
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Whether Claude Code bypasses server-managed settings for this session: a
|
|
226
|
+
* third-party provider flag is on, or `ANTHROPIC_BASE_URL` points anywhere but
|
|
227
|
+
* the Anthropic API. Its cache (`remote-settings.json`) then doesn't apply, so
|
|
228
|
+
* the hooks mustn't read it either.
|
|
229
|
+
* https://code.claude.com/docs/en/server-managed-settings#platform-availability
|
|
230
|
+
*/
|
|
231
|
+
export const serverManagedBypassed = (env = process.env) => {
|
|
232
|
+
if (PROVIDER_FLAGS.some((k) => isTruthyEnvValue(env[k]))) return true
|
|
233
|
+
const base = trimAscii(String(env.ANTHROPIC_BASE_URL ?? ''))
|
|
234
|
+
if (!base) return false
|
|
235
|
+
try {
|
|
236
|
+
return new URL(base).host !== 'api.anthropic.com'
|
|
237
|
+
} catch {
|
|
238
|
+
return true
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Whether this session bypasses server-managed settings, judged as Claude Code
|
|
244
|
+
* judges it: on the shell environment with the user settings `env` over it.
|
|
245
|
+
* Claude Code applies the project, local and managed `env` blocks only after
|
|
246
|
+
* that check, but the hook inherits them, so a value one of them supplied is
|
|
247
|
+
* taken out of the hook's env first. Where one of them sets a variable, what
|
|
248
|
+
* the shell had for it can't be recovered, and it's taken as unset.
|
|
249
|
+
* https://code.claude.com/docs/en/server-managed-settings#platform-availability
|
|
250
|
+
*/
|
|
251
|
+
export const sessionBypassesServer = (
|
|
252
|
+
cwd,
|
|
253
|
+
env = process.env,
|
|
254
|
+
readFile = readFileSafe,
|
|
255
|
+
listDir = jsonFilesIn,
|
|
256
|
+
managedDir,
|
|
257
|
+
) => {
|
|
258
|
+
const appliedLater = [
|
|
95
259
|
join(cwd, '.claude', 'settings.json'),
|
|
96
260
|
join(cwd, '.claude', 'settings.local.json'),
|
|
97
|
-
|
|
261
|
+
...managedSources(env, listDir, managedDir, false).flatMap((source) => source.paths),
|
|
262
|
+
].map((p) => settingsEnv(readFile(p)))
|
|
263
|
+
const shell = { ...env }
|
|
264
|
+
for (const layerEnv of appliedLater) {
|
|
265
|
+
for (const [k, v] of Object.entries(layerEnv)) if (shell[k] === v) delete shell[k]
|
|
266
|
+
}
|
|
267
|
+
const user = settingsEnv(readFile(join(claudeConfigDir(env), 'settings.json')))
|
|
268
|
+
return serverManagedBypassed({ ...shell, ...user })
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Every managed settings file, lowest precedence first (§ `managedSources`). */
|
|
272
|
+
export const managedSettingsPaths = (env = process.env, listDir = jsonFilesIn, managedDir) =>
|
|
273
|
+
managedSources(env, listDir, managedDir).flatMap((source) => source.paths)
|
|
274
|
+
|
|
275
|
+
/** Top-level keys that don't make a managed file "deliver a policy". */
|
|
276
|
+
const NON_POLICY_KEYS = new Set(['wslInheritsWindowsSettings', 'managedSourcesBehavior'])
|
|
277
|
+
|
|
278
|
+
const hasPolicyKey = (text) => {
|
|
279
|
+
try {
|
|
280
|
+
const doc = JSON.parse(text)
|
|
281
|
+
return (
|
|
282
|
+
doc !== null &&
|
|
283
|
+
typeof doc === 'object' &&
|
|
284
|
+
Object.keys(doc).some((k) => !NON_POLICY_KEYS.has(k))
|
|
285
|
+
)
|
|
286
|
+
} catch {
|
|
287
|
+
return false
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The managed source whose non-`env` settings (hooks, `apiKeyHelper`) Claude
|
|
293
|
+
* Code uses: the first that sets any policy key, server-managed before the file
|
|
294
|
+
* tier. `env` is different — it merges per key across every managed source.
|
|
295
|
+
*/
|
|
296
|
+
export const selectedManagedPaths = (
|
|
297
|
+
env = process.env,
|
|
298
|
+
readFile = readFileSafe,
|
|
299
|
+
listDir = jsonFilesIn,
|
|
300
|
+
managedDir,
|
|
301
|
+
bypassed = serverManagedBypassed(env),
|
|
302
|
+
) => {
|
|
303
|
+
const sources = managedSources(env, listDir, managedDir, bypassed).reverse()
|
|
304
|
+
const selected = sources.find((source) => source.paths.some((p) => hasPolicyKey(readFile(p))))
|
|
305
|
+
return selected?.paths ?? []
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Settings layers Claude Code reads, lowest precedence first: user, project,
|
|
310
|
+
* local, then one layer per managed source (§ `managedSources`). Project and
|
|
311
|
+
* local layers are `exporter: false` (§ `resolveOtelConfig`). `readFile`,
|
|
312
|
+
* `listDir` and `managedDir` are overridable for tests.
|
|
313
|
+
*/
|
|
314
|
+
export const settingsLayers = (
|
|
315
|
+
cwd,
|
|
316
|
+
env = process.env,
|
|
317
|
+
readFile = readFileSafe,
|
|
318
|
+
listDir = jsonFilesIn,
|
|
319
|
+
managedDir,
|
|
320
|
+
) => [
|
|
321
|
+
{ env: settingsEnv(readFile(join(claudeConfigDir(env), 'settings.json'))), exporter: true },
|
|
322
|
+
{ env: settingsEnv(readFile(join(cwd, '.claude', 'settings.json'))), exporter: false },
|
|
323
|
+
{ env: settingsEnv(readFile(join(cwd, '.claude', 'settings.local.json'))), exporter: false },
|
|
324
|
+
...managedSources(
|
|
325
|
+
env,
|
|
326
|
+
listDir,
|
|
327
|
+
managedDir,
|
|
328
|
+
sessionBypassesServer(cwd, env, readFile, listDir, managedDir),
|
|
329
|
+
).map((source) => ({
|
|
330
|
+
env: Object.assign({}, ...source.paths.map((p) => settingsEnv(readFile(p)))),
|
|
331
|
+
exporter: true,
|
|
332
|
+
managed: true,
|
|
333
|
+
})),
|
|
334
|
+
]
|
|
98
335
|
|
|
99
336
|
/**
|
|
100
337
|
* Which tool's config format to resolve OTLP settings from, read off the
|
|
@@ -106,8 +343,222 @@ export const markerTool = (argv) => {
|
|
|
106
343
|
return i !== -1 && argv[i + 1] ? argv[i + 1] : 'claude-code'
|
|
107
344
|
}
|
|
108
345
|
|
|
109
|
-
/**
|
|
110
|
-
*
|
|
346
|
+
/** The registered `coding_agent.*` source tag of the tool hosting this marker,
|
|
347
|
+
* from the `--tool` selector (§ `markerTool`), or `undefined` for a tool with
|
|
348
|
+
* no entry in `MARKER_HOST_SOURCES` — an unknown host is omitted, never
|
|
349
|
+
* guessed. */
|
|
350
|
+
export const markerHostSource = (tool) =>
|
|
351
|
+
typeof tool === 'string' && Object.hasOwn(MARKER_HOST_SOURCES, tool)
|
|
352
|
+
? MARKER_HOST_SOURCES[tool]
|
|
353
|
+
: undefined
|
|
354
|
+
|
|
355
|
+
/** The ASCII whitespace trimmed from a marker value before it's compared or
|
|
356
|
+
* emitted: space, tab, LF, CR, vertical tab, form feed — matches the
|
|
357
|
+
* collector's own trim behavior (the same fixed ASCII set), not JS's
|
|
358
|
+
* `String.prototype.trim`, whose Unicode `WhiteSpace`/`LineTerminator`
|
|
359
|
+
* set also strips NBSP and other characters the collector would keep — so a
|
|
360
|
+
* value trimmed here matches byte-for-byte what the collector sees. */
|
|
361
|
+
const trimAscii = (s) => s.replace(/^[ \t\n\r\v\f]+|[ \t\n\r\v\f]+$/g, '')
|
|
362
|
+
|
|
363
|
+
/** A file's UTF-8 text, or `undefined` when it is missing or unreadable. */
|
|
364
|
+
const readOrUndefined = (path) => {
|
|
365
|
+
try {
|
|
366
|
+
return readFileSync(path, 'utf8')
|
|
367
|
+
} catch {
|
|
368
|
+
return undefined
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** A string field ASCII-trimmed (§ `trimAscii`), or `undefined` for a
|
|
373
|
+
* non-string or a value that trims to empty. */
|
|
374
|
+
const trimmedOrUndefined = (v) => (typeof v === 'string' ? trimAscii(v) || undefined : undefined)
|
|
375
|
+
|
|
376
|
+
/** `oauthAccount.emailAddress` and `oauthAccount.accountUuid` from one
|
|
377
|
+
* `.claude.json`'s text, parsed once, each ASCII-trimmed (§ `trimAscii`) and
|
|
378
|
+
* each independently `undefined` when missing, non-string, or blank. Both are
|
|
379
|
+
* `undefined` for unparseable JSON. */
|
|
380
|
+
const oauthAccountFromText = (text) => {
|
|
381
|
+
let account
|
|
382
|
+
try {
|
|
383
|
+
account = JSON.parse(text)?.oauthAccount
|
|
384
|
+
} catch {
|
|
385
|
+
return {}
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
email: trimmedOrUndefined(account?.emailAddress),
|
|
389
|
+
accountUuid: trimmedOrUndefined(account?.accountUuid),
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Claude Code's own account cache — `.claude.json` (a top-level dotfile,
|
|
395
|
+
* distinct from the `~/.claude/` settings directory) — written by its Claude.ai
|
|
396
|
+
* OAuth sign-in. Reads `oauthAccount.accountUuid` and
|
|
397
|
+
* `oauthAccount.emailAddress` (one parse), each ASCII-trimmed (§ `trimAscii`),
|
|
398
|
+
* so a marker span can carry the same `user.account_uuid` / `user.email` Claude
|
|
399
|
+
* Code natively stamps on its own spans, and so the collector derives the same
|
|
400
|
+
* ucid for both — from the account id, else the email (the org-wide-config
|
|
401
|
+
* migration this hook is part of drops `mainwave.ucid` from that config).
|
|
402
|
+
*
|
|
403
|
+
* Claude Code resolves the file as `join(CLAUDE_CONFIG_DIR || home,
|
|
404
|
+
* '.claude.json')`: the raw value — no trimming — with an empty or unset
|
|
405
|
+
* variable meaning the home directory, and no fallback to home when the
|
|
406
|
+
* variable is set. This resolves it identically, so the marker stamps the
|
|
407
|
+
* session's own sign-in and never another profile's (which would give the
|
|
408
|
+
* marker an identity, and a derived ucid, its session doesn't have). A
|
|
409
|
+
* relative value resolves against the process cwd, which for a hook is the
|
|
410
|
+
* session's. `mainwave-cli doctor` resolves it the same way.
|
|
411
|
+
*
|
|
412
|
+
* `configDir` is the session's raw `CLAUDE_CONFIG_DIR` (`undefined` or `''`
|
|
413
|
+
* = home; no default — the caller passes it, so a test never inherits the
|
|
414
|
+
* machine's). A whitespace-only value is a directory name, as it is to
|
|
415
|
+
* Claude Code.
|
|
416
|
+
*
|
|
417
|
+
* Returns `{ email, accountUuid }`. Fail-open: a missing file, unparseable
|
|
418
|
+
* JSON, or a missing/blank key yields `undefined` for that field rather than
|
|
419
|
+
* throwing — a marker must never fail to emit because the account cache moved
|
|
420
|
+
* or changed shape.
|
|
421
|
+
*/
|
|
422
|
+
export const claudeCodeOauthAccount = (home = homedir(), configDir) => {
|
|
423
|
+
const text = readOrUndefined(resolve(configDir || home, '.claude.json'))
|
|
424
|
+
return text === undefined ? {} : oauthAccountFromText(text)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Env vars whose mere non-blank presence (ASCII-trimmed, § `trimAscii`) means
|
|
428
|
+
* the Claude Code session does NOT authenticate through Claude.ai OAuth, so
|
|
429
|
+
* `.claude.json`'s `oauthAccount` — which survives a switch to any of these —
|
|
430
|
+
* is stale for this session:
|
|
431
|
+
* - `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` — a direct key/token session.
|
|
432
|
+
* - `CLAUDE_CODE_OAUTH_TOKEN` — a session run with a setup token (`claude
|
|
433
|
+
* setup-token`) authenticates as *that token's* account, not whatever
|
|
434
|
+
* `.claude.json` has cached from a prior interactive sign-in.
|
|
435
|
+
* Any non-blank value skips, including one that turns out to be declined or
|
|
436
|
+
* invalid at auth time: a declined key isn't distinguishable from a good one
|
|
437
|
+
* here, and stamping no identity beats stamping the wrong one. */
|
|
438
|
+
const NON_OAUTH_VALUE_ENV = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN']
|
|
439
|
+
|
|
440
|
+
const TRUTHY_ENV_VALUES = new Set(['1', 'true', 'yes', 'on'])
|
|
441
|
+
|
|
442
|
+
/** Whether an env var's raw value reads as "on": ASCII-trimmed (§ `trimAscii`),
|
|
443
|
+
* lower-cased, one of `1`/`true`/`yes`/`on`. `undefined`, `0`, `false`, and
|
|
444
|
+
* blank all read as off. */
|
|
445
|
+
const isTruthyEnvValue = (v) => TRUTHY_ENV_VALUES.has(trimAscii(String(v ?? '')).toLowerCase())
|
|
446
|
+
|
|
447
|
+
/** Whether `env` marks this as a non-OAuth session: a key/token var above is
|
|
448
|
+
* non-blank, or a provider flag (§ `PROVIDER_FLAGS`) is truthy — unlike the
|
|
449
|
+
* key/token vars, `0` / `false` / blank there doesn't gate the identity off.
|
|
450
|
+
* `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` strips those credentials from a hook's
|
|
451
|
+
* environment, so with it on the session's auth can't be told here, and no
|
|
452
|
+
* identity beats a wrong one.
|
|
453
|
+
* https://code.claude.com/docs/en/env-vars */
|
|
454
|
+
const isNonOauthEnv = (env) =>
|
|
455
|
+
NON_OAUTH_VALUE_ENV.some((k) => trimAscii(String(env[k] ?? '')) !== '') ||
|
|
456
|
+
PROVIDER_FLAGS.some((k) => isTruthyEnvValue(env[k])) ||
|
|
457
|
+
isTruthyEnvValue(env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB)
|
|
458
|
+
|
|
459
|
+
/** Managed-settings file path Claude Code reads for the org-policy tier
|
|
460
|
+
* (macOS / Linux — Windows registry/HKCU isn't file-based and isn't
|
|
461
|
+
* introspected here either). Hardcoded rather than imported: the hooks ship
|
|
462
|
+
* as raw `.mjs` and can't import the CLI's compiled code, which uses the
|
|
463
|
+
* same paths — keep the two in sync if that ever changes. `managedDir` replaces the system directory;
|
|
464
|
+
* it comes only from the hook's own `--managed-settings-dir` flag (§
|
|
465
|
+
* `markerManagedDir`), never from the environment, which a repository's
|
|
466
|
+
* project settings can set. */
|
|
467
|
+
const managedSettingsPath = (managedDir) => {
|
|
468
|
+
if (managedDir) return join(managedDir, 'managed-settings.json')
|
|
469
|
+
return process.platform === 'darwin'
|
|
470
|
+
? '/Library/Application Support/ClaudeCode/managed-settings.json'
|
|
471
|
+
: process.platform === 'win32'
|
|
472
|
+
? 'C:\\Program Files\\ClaudeCode\\managed-settings.json'
|
|
473
|
+
: '/etc/claude-code/managed-settings.json'
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** The `--managed-settings-dir <dir>` flag, or undefined. Neither setup nor the
|
|
477
|
+
* org-wide payload writes it; it lets tests point the hooks at a temp
|
|
478
|
+
* directory instead of the machine's real org policy. */
|
|
479
|
+
export const markerManagedDir = (argv) => {
|
|
480
|
+
const i = (argv ?? []).indexOf('--managed-settings-dir')
|
|
481
|
+
return i !== -1 && argv[i + 1] ? argv[i + 1] : undefined
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Whether a settings file's raw text sets a non-blank `apiKeyHelper` — an
|
|
485
|
+
* external script Claude Code invokes to resolve the API key. The hook can't
|
|
486
|
+
* see whether that script actually returns Claude.ai-OAuth credentials, so
|
|
487
|
+
* its mere presence is treated as non-OAuth. Unparseable/non-string/blank →
|
|
488
|
+
* `false`, never a throw. */
|
|
489
|
+
const textHasApiKeyHelper = (text) => {
|
|
490
|
+
let parsed
|
|
491
|
+
try {
|
|
492
|
+
parsed = JSON.parse(text)
|
|
493
|
+
} catch {
|
|
494
|
+
return false
|
|
495
|
+
}
|
|
496
|
+
return typeof parsed?.apiKeyHelper === 'string' && trimAscii(parsed.apiKeyHelper) !== ''
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Whether any Claude Code settings file sets a non-blank `apiKeyHelper`: the
|
|
501
|
+
* user settings via `claudeConfigDir`, project `.claude/settings.json`,
|
|
502
|
+
* `.claude/settings.local.json`, and the managed source Claude Code takes
|
|
503
|
+
* non-`env` settings from (§ `selectedManagedPaths`) — a superseded managed
|
|
504
|
+
* file's helper doesn't apply. Fail-open: a
|
|
505
|
+
* missing or unreadable file counts as no helper there, never a thrown error.
|
|
506
|
+
* `readFile` and `listDir` are overridable so a test can stub the managed tier
|
|
507
|
+
* without touching a real system directory.
|
|
508
|
+
*/
|
|
509
|
+
export const hasApiKeyHelper = (
|
|
510
|
+
cwd,
|
|
511
|
+
env = process.env,
|
|
512
|
+
readFile = readFileSafe,
|
|
513
|
+
listDir = jsonFilesIn,
|
|
514
|
+
managedDir,
|
|
515
|
+
) =>
|
|
516
|
+
[
|
|
517
|
+
join(claudeConfigDir(env), 'settings.json'),
|
|
518
|
+
join(cwd, '.claude', 'settings.json'),
|
|
519
|
+
join(cwd, '.claude', 'settings.local.json'),
|
|
520
|
+
...selectedManagedPaths(
|
|
521
|
+
env,
|
|
522
|
+
readFile,
|
|
523
|
+
listDir,
|
|
524
|
+
managedDir,
|
|
525
|
+
sessionBypassesServer(cwd, env, readFile, listDir, managedDir),
|
|
526
|
+
),
|
|
527
|
+
].some((p) => textHasApiKeyHelper(readFile(p)))
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* The OAuth identity to stamp on a marker span: `{ email, accountUuid }`, each
|
|
531
|
+
* `undefined` when unavailable (both when gated off below).
|
|
532
|
+
*
|
|
533
|
+
* - `tool` is the same `--tool` selector `loadOtelConfig` reads (§
|
|
534
|
+
* `markerTool`). Codex has no `.claude.json` account cache and carries its
|
|
535
|
+
* own identity story, so any tool other than `'claude-code'` returns `{}`
|
|
536
|
+
* without touching the filesystem.
|
|
537
|
+
* - Best-effort OAuth gate: `{}` when `env` (the hook's own env, which Claude
|
|
538
|
+
* Code passes through to hooks) marks a non-OAuth session (§ `isNonOauthEnv`
|
|
539
|
+
* — a key/token/setup-token var non-blank, or a provider flag truthy), or
|
|
540
|
+
* when any settings file in play sets `apiKeyHelper` (§ `hasApiKeyHelper`).
|
|
541
|
+
* Both are best-effort: a declined key or an apiKeyHelper script that
|
|
542
|
+
* itself resolves nothing still gates off, on the principle that no
|
|
543
|
+
* identity beats a wrong one.
|
|
544
|
+
*
|
|
545
|
+
* `opts`: `env` (default `process.env`), `home` (default `homedir()`), `cwd`
|
|
546
|
+
* (default `process.cwd()`, used for the project-local `apiKeyHelper` check),
|
|
547
|
+
* and `configDir` — when the key is present its value is used as-is
|
|
548
|
+
* (`undefined` = unset), otherwise `env.CLAUDE_CONFIG_DIR`, raw
|
|
549
|
+
* (§ `claudeCodeOauthAccount`).
|
|
550
|
+
*/
|
|
551
|
+
export const markerOauthAccount = (tool, opts = {}) => {
|
|
552
|
+
if (tool !== 'claude-code') return {}
|
|
553
|
+
const env = opts.env ?? process.env
|
|
554
|
+
if (isNonOauthEnv(env)) return {}
|
|
555
|
+
const cwd = opts.cwd ?? process.cwd()
|
|
556
|
+
if (hasApiKeyHelper(cwd, env, undefined, undefined, opts.managedDir)) return {}
|
|
557
|
+
const configDir = 'configDir' in opts ? opts.configDir : env.CLAUDE_CONFIG_DIR
|
|
558
|
+
return claudeCodeOauthAccount(opts.home, configDir)
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Last `key = "value"` match in TOML-ish text; last wins within the file. The key may
|
|
111
562
|
* be bare (`X-Mainwave-UCID = …`) or quoted (`"X-Mainwave-UCID" = …`), covering
|
|
112
563
|
* either TOML rendering. */
|
|
113
564
|
const lastTomlString = (text, key) => {
|
|
@@ -126,77 +577,228 @@ const stripSignalSuffix = (endpoint) =>
|
|
|
126
577
|
(endpoint ?? '').replace(/\/v1\/(logs|traces|metrics)\/?$/, '')
|
|
127
578
|
|
|
128
579
|
/**
|
|
129
|
-
* OTLP config from Codex's `config.toml
|
|
580
|
+
* OTLP config from Codex's global `config.toml`. Codex carries
|
|
130
581
|
* tenancy on HTTP headers rather than OTEL_RESOURCE_ATTRIBUTES, so the UCID is the
|
|
131
582
|
* `X-Mainwave-UCID` header value and the bearer is the `Authorization` header — the
|
|
132
583
|
* marker re-emits the UCID as a `mainwave.ucid` resource attr, which the collector
|
|
133
|
-
* reads the same as a header-promoted one.
|
|
134
|
-
*
|
|
584
|
+
* reads the same as a header-promoted one. A UCID is present only when the
|
|
585
|
+
* developer configured one explicitly; by default the collector derives it from
|
|
586
|
+
* the developer's email, so the `X-Mainwave-User-Email` header is re-emitted as
|
|
587
|
+
* the `mainwave.user_email` resource attr it promotes that header to — without
|
|
588
|
+
* it a Codex marker would carry no identity at all. Missing keys → undefined
|
|
589
|
+
* (the hook skips, fail-open), never a broken emit.
|
|
135
590
|
*/
|
|
136
|
-
export const codexOtelConfig = (
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
591
|
+
export const codexOtelConfig = (readFile = readFileSafe) => {
|
|
592
|
+
// Global config only: Codex 0.130+ drops `otel` keys from a project's
|
|
593
|
+
// `.codex/config.toml` itself, so a checked-out repository can't redirect
|
|
594
|
+
// its telemetry, and the markers follow the same rule.
|
|
595
|
+
const text = readFile(join(homedir(), '.codex', 'config.toml'))
|
|
141
596
|
const endpoint = stripSignalSuffix(lastTomlString(text, 'endpoint'))
|
|
142
597
|
const bearer = lastTomlString(text, 'Authorization')
|
|
143
598
|
const ucid = lastTomlString(text, 'X-Mainwave-UCID')
|
|
599
|
+
const userEmail = lastTomlString(text, 'X-Mainwave-User-Email')
|
|
144
600
|
return {
|
|
145
601
|
endpoint: endpoint || undefined,
|
|
146
602
|
bearer: bearer || undefined,
|
|
147
|
-
resourceAttrs:
|
|
603
|
+
resourceAttrs: {
|
|
604
|
+
...(ucid ? { 'mainwave.ucid': ucid } : {}),
|
|
605
|
+
...(userEmail ? { 'mainwave.user_email': userEmail } : {}),
|
|
606
|
+
},
|
|
148
607
|
}
|
|
149
608
|
}
|
|
150
609
|
|
|
151
610
|
/** Resolve OTLP config for the marker emit. `tool` selects the source format:
|
|
152
611
|
* 'codex' reads config.toml; the default reads Claude Code's settings.json env. */
|
|
153
|
-
export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code') =>
|
|
154
|
-
tool === 'codex'
|
|
612
|
+
export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir) =>
|
|
613
|
+
tool === 'codex'
|
|
614
|
+
? codexOtelConfig()
|
|
615
|
+
: resolveOtelConfig(
|
|
616
|
+
settingsLayers(cwd, processEnv, undefined, undefined, managedDir),
|
|
617
|
+
processEnv,
|
|
618
|
+
)
|
|
155
619
|
|
|
156
620
|
/**
|
|
157
621
|
* Keep the developer's identity attrs — above all `mainwave.ucid`, so the marker
|
|
158
622
|
* attributes to the same use case as the session — but override the two the
|
|
159
623
|
* collector reads to classify a span as a coding agent (`mainwave.source` and
|
|
160
|
-
* `service.name
|
|
161
|
-
*
|
|
162
|
-
* `
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
624
|
+
* `service.name`). The developer's own `OTEL_RESOURCE_ATTRIBUTES` carries the
|
|
625
|
+
* coding values (mainwave-cli sets `mainwave.source=coding_agent.claude_code`,
|
|
626
|
+
* `service.name=claude-code`); forwarding them verbatim would stamp the marker
|
|
627
|
+
* with a coding source, and the outcome-trend / activity segmentation would
|
|
628
|
+
* then miscount each marker as a phantom stretch. Each hook passes its own
|
|
629
|
+
* non-coding source/service.
|
|
630
|
+
*
|
|
631
|
+
* `hostSource` — the hosting tool's registered source tag (§ `markerHostSource`)
|
|
632
|
+
* — lands as `mainwave.host_source`. Absent → the key is omitted, and any value
|
|
633
|
+
* inherited from the developer's `OTEL_RESOURCE_ATTRIBUTES` is dropped too, so
|
|
634
|
+
* the attribute only ever carries what the hook itself resolved.
|
|
166
635
|
*/
|
|
167
|
-
export const markerResourceAttrs = (resourceAttrs, source, service) =>
|
|
168
|
-
...(resourceAttrs ?? {})
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
})
|
|
636
|
+
export const markerResourceAttrs = (resourceAttrs, source, service, hostSource) => {
|
|
637
|
+
const rest = { ...(resourceAttrs ?? {}) }
|
|
638
|
+
delete rest[ATTR_HOST_SOURCE]
|
|
639
|
+
return {
|
|
640
|
+
...rest,
|
|
641
|
+
'mainwave.source': source,
|
|
642
|
+
'service.name': service,
|
|
643
|
+
...(hostSource ? { [ATTR_HOST_SOURCE]: hostSource } : {}),
|
|
644
|
+
// The v2 contract stamp on every hook emission (marker + cursor), so the
|
|
645
|
+
// collector shim's lifetime can be measured against v1-vs-v2 traffic.
|
|
646
|
+
[ATTR_SCHEMA_VERSION]: SCHEMA_VERSION,
|
|
647
|
+
}
|
|
648
|
+
}
|
|
175
649
|
|
|
176
650
|
const attr = (key, stringValue) => ({ key, value: { stringValue } })
|
|
177
651
|
|
|
652
|
+
/** W3C `traceparent`, version `00`: `00-<32 hex trace id>-<16 hex span id>-<2
|
|
653
|
+
* hex flags>`, lowercase only — the spec rejects uppercase hex, and a later
|
|
654
|
+
* version may change the fields, so only `00` is read.
|
|
655
|
+
* https://www.w3.org/TR/trace-context/#traceparent-header-field-values */
|
|
656
|
+
const TRACEPARENT_RE = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/
|
|
657
|
+
const ALL_ZERO_RE = /^0+$/
|
|
658
|
+
|
|
659
|
+
/** `{ traceId, spanId }` from a `traceparent` value, or `undefined` for
|
|
660
|
+
* anything else — a non-string, a wrong length, non-hex or uppercase hex, a
|
|
661
|
+
* version other than `00`, or an all-zero trace or span id (the spec's
|
|
662
|
+
* invalid values). Surrounding ASCII whitespace is trimmed; nothing else is
|
|
663
|
+
* repaired, so a malformed value never yields half its fields. */
|
|
664
|
+
export const parseTraceparent = (raw) => {
|
|
665
|
+
if (typeof raw !== 'string') return undefined
|
|
666
|
+
const m = TRACEPARENT_RE.exec(trimAscii(raw))
|
|
667
|
+
if (!m || ALL_ZERO_RE.test(m[1]) || ALL_ZERO_RE.test(m[2])) return undefined
|
|
668
|
+
return { traceId: m[1], spanId: m[2] }
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** An opaque id from the hook payload — letters, digits and `_ . : -`, at most
|
|
672
|
+
* 256 characters (Claude Code's tool-use ids are `toolu_…`, its agent ids
|
|
673
|
+
* hex) — or `undefined`. The keys that carry these are ids-only, so a value
|
|
674
|
+
* that doesn't look like an id is dropped rather than emitted. */
|
|
675
|
+
const OPAQUE_ID_RE = /^[A-Za-z0-9_.:-]{1,256}$/
|
|
676
|
+
const opaqueIdOrUndefined = (v) => {
|
|
677
|
+
const s = trimmedOrUndefined(v)
|
|
678
|
+
return s !== undefined && OPAQUE_ID_RE.test(s) ? s : undefined
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* Where in the session this marker's tool call ran, so the marker can be tied
|
|
683
|
+
* to its turn exactly instead of by timestamp: `{ caller, toolCallId,
|
|
684
|
+
* subagentId }`, each `undefined` when unavailable.
|
|
685
|
+
*
|
|
686
|
+
* - `caller` — `{ traceId, spanId }` from the `TRACEPARENT` Claude Code puts in
|
|
687
|
+
* a hook's environment: the turn's interaction span on the main thread, the
|
|
688
|
+
* spawning Agent tool span inside a subagent (§ `parseTraceparent`).
|
|
689
|
+
* - `toolCallId` — the payload's `tool_use_id`, the value Claude Code's own
|
|
690
|
+
* tool span carries as `gen_ai.tool.call.id`.
|
|
691
|
+
* - `subagentId` — the payload's `agent_id`, present only when the hook runs
|
|
692
|
+
* inside a subagent; Claude Code's own spans carry it as `agent_id`.
|
|
693
|
+
*
|
|
694
|
+
* Claude Code only (`tool`, § `markerTool`): another host's hook environment is
|
|
695
|
+
* inherited from the developer's shell, where a `TRACEPARENT` would name some
|
|
696
|
+
* unrelated trace, and no other host's payload fields are known to mean the
|
|
697
|
+
* same thing. Each field is read on its own, so a missing or malformed one
|
|
698
|
+
* drops only itself.
|
|
699
|
+
*/
|
|
700
|
+
export const markerCallContext = (tool, payload, env = process.env) => {
|
|
701
|
+
if (tool !== 'claude-code') return {}
|
|
702
|
+
return {
|
|
703
|
+
caller: parseTraceparent(env.TRACEPARENT),
|
|
704
|
+
toolCallId: opaqueIdOrUndefined(payload?.tool_use_id),
|
|
705
|
+
subagentId: opaqueIdOrUndefined(payload?.agent_id),
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/** Whether an existing attribute value counts as "blank" for the identity
|
|
710
|
+
* keys — `user.email` / `user.account_uuid` — ASCII-whitespace-only (§
|
|
711
|
+
* `trimAscii`) counts as blank, not just the empty string. This mirrors the
|
|
712
|
+
* collector's own email resolution: a raw value it "picks" can still
|
|
713
|
+
* normalize to an empty string after the same ASCII trim, and when it does
|
|
714
|
+
* the collector treats the row as carrying no email at all rather than
|
|
715
|
+
* falling through to another source. So an
|
|
716
|
+
* attribute that would normalize to empty must not block the OAuth fallback
|
|
717
|
+
* either — a whitespace-only `user.email` here would otherwise suppress the
|
|
718
|
+
* OAuth email while itself resolving to nothing on the collector side,
|
|
719
|
+
* losing the ucid attribution entirely. Scoped to the identity keys only
|
|
720
|
+
* (§ `isBlankForAttr`) — a whitespace-only value on any other attribute
|
|
721
|
+
* (e.g. a PR/ticket title of spaces) is real content, not a stand-in for
|
|
722
|
+
* absence, and origin/master's exact-empty-string rule (§ `isBlankValue`)
|
|
723
|
+
* keeps emitting it unchanged. */
|
|
724
|
+
const isBlankAttr = (v) => v === undefined || v === null || trimAscii(String(v)) === ''
|
|
725
|
+
|
|
726
|
+
/** origin/master's general attribute-drop rule: only `undefined`, `null`, or
|
|
727
|
+
* the exact empty string count as blank. Everything else — including a
|
|
728
|
+
* whitespace-only string — is real content and is emitted as-is. */
|
|
729
|
+
const isBlankValue = (v) => v === undefined || v === null || v === ''
|
|
730
|
+
|
|
731
|
+
/** The two attribute keys `buildMarkerPayload` treats as identity, where
|
|
732
|
+
* `isBlankAttr`'s whitespace-aware rule applies instead of § `isBlankValue`. */
|
|
733
|
+
const IDENTITY_ATTR_KEYS = new Set(['user.email', 'user.account_uuid'])
|
|
734
|
+
|
|
735
|
+
/** Whether attribute `key`'s raw value `v` is blank for the purpose of the
|
|
736
|
+
* general attribute filter in `buildMarkerPayload`: the identity keys use
|
|
737
|
+
* § `isBlankAttr` (whitespace-only counts as blank — this is what lets the
|
|
738
|
+
* OAuth fallback below replace a whitespace-only raw value instead of
|
|
739
|
+
* leaving a duplicate `user.email` / `user.account_uuid` attribute behind);
|
|
740
|
+
* every other key uses § `isBlankValue`, origin/master's narrower rule. */
|
|
741
|
+
const isBlankForAttr = (key, v) => (IDENTITY_ATTR_KEYS.has(key) ? isBlankAttr(v) : isBlankValue(v))
|
|
742
|
+
|
|
743
|
+
/** The span attributes for a § `markerCallContext` result, each field that is
|
|
744
|
+
* present and none that isn't. */
|
|
745
|
+
const callContextAttrs = (callContext) => {
|
|
746
|
+
const { caller, toolCallId, subagentId } = callContext ?? {}
|
|
747
|
+
return [
|
|
748
|
+
...(caller
|
|
749
|
+
? [attr(ATTR_CALLER_TRACE_ID, caller.traceId), attr(ATTR_CALLER_SPAN_ID, caller.spanId)]
|
|
750
|
+
: []),
|
|
751
|
+
...(toolCallId ? [attr(ATTR_TOOL_CALL_ID, toolCallId)] : []),
|
|
752
|
+
...(subagentId ? [attr(ATTR_SUBAGENT_ID, subagentId)] : []),
|
|
753
|
+
]
|
|
754
|
+
}
|
|
755
|
+
|
|
178
756
|
/**
|
|
179
757
|
* Build an OTLP/JSON traces payload with a single marker span. `attributes` is a
|
|
180
|
-
* plain string→string map;
|
|
181
|
-
* absent optional attr like a PR title emits nothing
|
|
182
|
-
*
|
|
758
|
+
* plain string→string map; blank values are dropped per § `isBlankForAttr`
|
|
759
|
+
* (so an absent optional attr like a PR title emits nothing, while a
|
|
760
|
+
* whitespace-only PR/ticket title is kept as-is), `session.id` is appended
|
|
761
|
+
* when present, `userAccountUuid` is appended as `user.account_uuid` when
|
|
762
|
+
* present and `attributes` carries no non-blank (§ `isBlankAttr`)
|
|
763
|
+
* `user.account_uuid`, and `userEmail` as `user.email` under the same rule
|
|
764
|
+
* for `user.email` — each guarded independently. The collector derives the
|
|
765
|
+
* same ucid off these (account id first, email as fallback) that it derives
|
|
766
|
+
* for the session's own Claude Code spans, so the marker attributes to the
|
|
767
|
+
* same use case without a `mainwave.ucid` on either side. Only the
|
|
768
|
+
* same-named key guards each append: `mainwave.user_email` is read off the
|
|
769
|
+
* resource only, so a span attribute of that name neither identifies the row
|
|
770
|
+
* nor blocks this. Pure: the caller resolves `userEmail` / `userAccountUuid`
|
|
771
|
+
* (e.g. via `markerOauthAccount`) and passes them in — this function never
|
|
772
|
+
* touches the filesystem. `resourceAttrs` are neutralized via `markerResourceAttrs`,
|
|
773
|
+
* which also stamps `hostSource` (optional; the marker hooks pass
|
|
774
|
+
* § `markerHostSource`, the cursor behaviour hook passes nothing).
|
|
775
|
+
*
|
|
776
|
+
* `callContext` (§ `markerCallContext`; optional) appends each of its fields
|
|
777
|
+
* that is present as a span attribute. The span keeps its own random trace and
|
|
778
|
+
* span ids either way: the calling span is referenced, never joined, because a
|
|
779
|
+
* marker row's run is keyed on its trace id (§ the vocabulary's
|
|
780
|
+
* calling-span section).
|
|
183
781
|
*/
|
|
184
782
|
export const buildMarkerPayload = ({
|
|
185
783
|
spanName,
|
|
186
784
|
scopeName,
|
|
187
785
|
attributes,
|
|
188
786
|
sessionId,
|
|
787
|
+
userEmail,
|
|
788
|
+
userAccountUuid,
|
|
189
789
|
resourceAttrs,
|
|
190
790
|
source,
|
|
191
791
|
service,
|
|
792
|
+
hostSource,
|
|
793
|
+
callContext,
|
|
192
794
|
nowNs,
|
|
193
795
|
}) => ({
|
|
194
796
|
resourceSpans: [
|
|
195
797
|
{
|
|
196
798
|
resource: {
|
|
197
|
-
attributes: Object.entries(
|
|
198
|
-
(
|
|
199
|
-
),
|
|
799
|
+
attributes: Object.entries(
|
|
800
|
+
markerResourceAttrs(resourceAttrs, source, service, hostSource),
|
|
801
|
+
).map(([k, v]) => attr(k, v)),
|
|
200
802
|
},
|
|
201
803
|
scopeSpans: [
|
|
202
804
|
{
|
|
@@ -211,9 +813,19 @@ export const buildMarkerPayload = ({
|
|
|
211
813
|
endTimeUnixNano: String(nowNs),
|
|
212
814
|
attributes: [
|
|
213
815
|
...Object.entries(attributes)
|
|
214
|
-
.filter(([, v]) =>
|
|
816
|
+
.filter(([k, v]) => !isBlankForAttr(k, v))
|
|
215
817
|
.map(([k, v]) => attr(k, String(v))),
|
|
216
818
|
...(sessionId ? [attr('session.id', sessionId)] : []),
|
|
819
|
+
...callContextAttrs(callContext),
|
|
820
|
+
// isBlankAttr, not `in` or a truthy check: a key present but
|
|
821
|
+
// blank (empty, or ASCII-whitespace-only) must not suppress the
|
|
822
|
+
// OAuth value — see § isBlankAttr.
|
|
823
|
+
...(userEmail && isBlankAttr(attributes['user.email'])
|
|
824
|
+
? [attr('user.email', userEmail)]
|
|
825
|
+
: []),
|
|
826
|
+
...(userAccountUuid && isBlankAttr(attributes['user.account_uuid'])
|
|
827
|
+
? [attr('user.account_uuid', userAccountUuid)]
|
|
828
|
+
: []),
|
|
217
829
|
],
|
|
218
830
|
},
|
|
219
831
|
],
|
|
@@ -253,11 +865,11 @@ export const emitMarker = async ({
|
|
|
253
865
|
// most-current first. Claude Code v2.1.220 delivers it as `tool_output`; earlier
|
|
254
866
|
// and adjacent schemas used `tool_response` / `tool_result`. The hooks originally
|
|
255
867
|
// read only `tool_result`, which the runtime never populates, so every real call
|
|
256
|
-
// silently emitted nothing
|
|
868
|
+
// silently emitted nothing.
|
|
257
869
|
const OUTPUT_FIELDS = ['tool_output', 'tool_response', 'tool_result']
|
|
258
870
|
|
|
259
871
|
/** The tool's output from a PostToolUse payload, reading each known output field
|
|
260
|
-
* in turn so a field rename can't silently starve the markers again
|
|
872
|
+
* in turn so a field rename can't silently starve the markers again.
|
|
261
873
|
* The value shape (string, MCP content array, object) is left to the extractors. */
|
|
262
874
|
export const toolOutput = (payload) => {
|
|
263
875
|
for (const k of OUTPUT_FIELDS) {
|