@mainwave/cli 0.9.0 → 0.10.0

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.
@@ -0,0 +1,570 @@
1
+ #!/usr/bin/env node
2
+ // Kiro hook → OTLP session telemetry.
3
+ //
4
+ // Kiro (IDE 1.0+, and Kiro CLI 2.13+ in V3 mode) runs the command hooks in
5
+ // `~/.kiro/hooks/*.json` for every session. mainwave-cli registers THIS script
6
+ // in one file there, `mainwave.json`, once per trigger: SessionStart,
7
+ // UserPromptSubmit, PostToolUse, PostFileCreate / PostFileSave /
8
+ // PostFileDelete, Stop and SessionEnd. Kiro invokes it with a JSON payload on
9
+ // stdin (`hook_event_name`, `cwd`, `session_id`, plus `tool_name` /
10
+ // `tool_input` on tool events and `prompt` on prompt submit); the script maps
11
+ // the event to one small OTLP span and posts it to the collector.
12
+ //
13
+ // Kiro runs command hooks synchronously and treats their output as input:
14
+ // on exit 0 the command's stdout is added to the agent's context, and any
15
+ // other exit code BLOCKS a UserPromptSubmit or PreToolUse. So this script
16
+ // writes nothing to stdout, always exits 0, bounds every wait, and fails open:
17
+ // a telemetry hiccup must never block or steer the developer's session. It
18
+ // never waits on the network either: it reads the event, builds the span,
19
+ // hands it to a detached copy of itself (`--send <spool file>`) that does the
20
+ // POST, and exits.
21
+ //
22
+ // Like the Cursor hook, Kiro exposes no config file we can read the collector
23
+ // endpoint and key back out of, so setup writes a managed env file
24
+ // (`~/.mainwave/kiro.env`, mode 0600) and this script reads its OTLP target,
25
+ // the developer's email and the prompt-capture choice from there — only from
26
+ // there, never from the workspace or the environment, so a repository can't
27
+ // choose where the developer's key is sent. The hook never sends a use-case
28
+ // id: the collector derives one at ingest from the email.
29
+
30
+ import { spawn } from 'node:child_process'
31
+ import { randomBytes } from 'node:crypto'
32
+ import {
33
+ chmodSync,
34
+ mkdirSync,
35
+ readdirSync,
36
+ readFileSync,
37
+ realpathSync,
38
+ statSync,
39
+ unlinkSync,
40
+ writeFileSync,
41
+ } from 'node:fs'
42
+ import { homedir } from 'node:os'
43
+ import { dirname, join, resolve } from 'node:path'
44
+ import { fileURLToPath, pathToFileURL } from 'node:url'
45
+
46
+ import {
47
+ bearerFromHeaders,
48
+ buildMarkerPayload,
49
+ emitMarker,
50
+ ensureLogDir,
51
+ hookFlag,
52
+ isOkStatus,
53
+ markerLog,
54
+ markerLogPath,
55
+ parseEnvFile,
56
+ parseKv,
57
+ } from './marker-core.mjs'
58
+
59
+ const LOG_NAME = 'kiro.log'
60
+ const log = markerLog(process.argv, LOG_NAME)
61
+
62
+ export const SOURCE_IDE = 'coding_agent.kiro_ide'
63
+ export const SOURCE_CLI = 'coding_agent.kiro_cli'
64
+ const SOURCES = { ide: SOURCE_IDE, cli: SOURCE_CLI }
65
+ // The resource `service.name` per surface; the collector routes on it when
66
+ // `mainwave.source` is missing.
67
+ const SERVICES = { ide: 'kiro-ide', cli: 'kiro-cli' }
68
+ const SCOPE_NAME = 'mainwave.kiro-hook'
69
+
70
+ // Bounds. The hook Kiro waits on reads stdin for at most STDIN_TIMEOUT_MS and
71
+ // exits by HARD_EXIT_MS whatever happens; the detached sender has its own.
72
+ const STDIN_MAX_BYTES = 1024 * 1024
73
+ // Kept from an oversized payload, to recover the event's ids (§ `partialPayload`).
74
+ const STDIN_HEAD_BYTES = 64 * 1024
75
+ const STDIN_TIMEOUT_MS = 1500
76
+ const HARD_EXIT_MS = 2500
77
+ const POST_TIMEOUT_MS = 3000
78
+ const SENDER_EXIT_MS = 5000
79
+ // Spool hygiene: a span its sender never picked up (a crash, a kill) is
80
+ // deleted after SPOOL_MAX_AGE_MS, and past SPOOL_MAX_FILES pending spans new
81
+ // events are dropped rather than piling up behind a collector that is down.
82
+ const SPOOL_MAX_AGE_MS = 10 * 60 * 1000
83
+ export const SPOOL_MAX_FILES = 500
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Config — the managed env file setup writes.
87
+ // ---------------------------------------------------------------------------
88
+
89
+ export const kiroEnvPath = () => join(homedir(), '.mainwave', 'kiro.env')
90
+
91
+ /** Where a hook leaves a built span for its detached sender: owner-only. */
92
+ export const spoolDir = () => join(homedir(), '.mainwave', 'spool')
93
+
94
+ const readFileSafe = (path) => {
95
+ try {
96
+ return readFileSync(path, 'utf8')
97
+ } catch {
98
+ return ''
99
+ }
100
+ }
101
+
102
+ /**
103
+ * OTLP config from `~/.mainwave/kiro.env`: endpoint, bearer, the developer's
104
+ * email, which Kiro surfaces are set up (`MAINWAVE_KIRO_IDE` /
105
+ * `MAINWAVE_KIRO_CLI` = 1; a file from before those marks names one surface
106
+ * in its `X-Mainwave-Source`), which were removed while the other stayed (the
107
+ * same keys = 0, written by `--remove`) and the prompt-capture choice
108
+ * (`OTEL_LOG_USER_PROMPTS=1`, the same switch Claude Code reads). A
109
+ * `X-Mainwave-UCID` in the file is ignored: this hook never sends a use-case
110
+ * id. Missing values are undefined and the emit is skipped.
111
+ */
112
+ const markedSurfaces = (env, value) => [
113
+ ...(env.MAINWAVE_KIRO_IDE === value ? ['ide'] : []),
114
+ ...(env.MAINWAVE_KIRO_CLI === value ? ['cli'] : []),
115
+ ]
116
+
117
+ const installedSurfaces = (env, source) => {
118
+ const marked = markedSurfaces(env, '1')
119
+ if (marked.length > 0) return marked
120
+ return source === SOURCE_IDE ? ['ide'] : source === SOURCE_CLI ? ['cli'] : []
121
+ }
122
+
123
+ export const loadKiroConfig = (readFile = readFileSafe) => {
124
+ const env = parseEnvFile(readFile(kiroEnvPath()))
125
+ const headers = parseKv(env.OTEL_EXPORTER_OTLP_HEADERS)
126
+ const source = headers['X-Mainwave-Source']
127
+ return {
128
+ endpoint: env.OTEL_EXPORTER_OTLP_ENDPOINT || undefined,
129
+ bearer: bearerFromHeaders(env.OTEL_EXPORTER_OTLP_HEADERS),
130
+ userEmail: headers['X-Mainwave-User-Email'] || undefined,
131
+ surfaces: installedSurfaces(env, source),
132
+ removed: markedSurfaces(env, '0'),
133
+ capturePrompts: env.OTEL_LOG_USER_PROMPTS === '1',
134
+ }
135
+ }
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // Event mapping — Kiro payload → span name + attributes.
139
+ // ---------------------------------------------------------------------------
140
+
141
+ /** The registered trigger → span name. Setup registers exactly these. */
142
+ export const SPAN_NAME = {
143
+ SessionStart: 'kiro.session.start',
144
+ UserPromptSubmit: 'kiro.prompt.submit',
145
+ PostToolUse: 'kiro.tool.execution',
146
+ PostFileCreate: 'kiro.file.edit',
147
+ PostFileSave: 'kiro.file.edit',
148
+ PostFileDelete: 'kiro.file.edit',
149
+ Stop: 'kiro.turn.stop',
150
+ SessionEnd: 'kiro.session.end',
151
+ }
152
+
153
+ const FILE_OP = { PostFileCreate: 'create', PostFileSave: 'save', PostFileDelete: 'delete' }
154
+
155
+ // `hook_event_name` spellings Kiro documents besides the PascalCase trigger
156
+ // names: CLI 2.x camelCase names, which its documented sample payloads still
157
+ // carry, and the IDE 0.x file-event names. Keys are lower-cased.
158
+ const EVENT_ALIASES = {
159
+ agentspawn: 'SessionStart',
160
+ sessionstart: 'SessionStart',
161
+ userpromptsubmit: 'UserPromptSubmit',
162
+ posttooluse: 'PostToolUse',
163
+ filecreated: 'PostFileCreate',
164
+ postfilecreate: 'PostFileCreate',
165
+ fileedited: 'PostFileSave',
166
+ postfilesave: 'PostFileSave',
167
+ filedeleted: 'PostFileDelete',
168
+ postfiledelete: 'PostFileDelete',
169
+ agentstop: 'Stop',
170
+ stop: 'Stop',
171
+ sessionend: 'SessionEnd',
172
+ }
173
+
174
+ /**
175
+ * Which trigger fired. The `--trigger` flag setup bakes into each registered
176
+ * command wins: it names exactly the hook entry Kiro ran, whatever spelling
177
+ * the payload uses. Without it (a hand-run script), the payload's
178
+ * `hook_event_name` through the documented aliases. Undefined when neither
179
+ * names a trigger we map.
180
+ */
181
+ export const resolveTrigger = (argv, payload) => {
182
+ const flagged = hookFlag(argv, '--trigger')
183
+ if (flagged && SPAN_NAME[flagged]) return flagged
184
+ const name = payload?.hook_event_name
185
+ if (typeof name !== 'string') return undefined
186
+ return EVENT_ALIASES[name.toLowerCase()]
187
+ }
188
+
189
+ const nonEmpty = (v) => (typeof v === 'string' && v.trim() !== '' ? v : undefined)
190
+
191
+ const SESSION_ID_RE = /^[A-Za-z0-9_.:-]{1,256}$/
192
+
193
+ /**
194
+ * The Kiro session id: the payload's `session_id`, else `KIRO_SESSION_ID` from
195
+ * the hook's environment (early IDE 1.0 builds omit it from some payloads),
196
+ * else undefined — and then the event is dropped. Never fabricated: a made-up
197
+ * id would split one session into many.
198
+ */
199
+ export const resolveSessionId = (payload, env = process.env) => {
200
+ for (const v of [payload?.session_id, env.KIRO_SESSION_ID]) {
201
+ const s = nonEmpty(v)?.trim()
202
+ if (s !== undefined && SESSION_ID_RE.test(s)) return s
203
+ }
204
+ return undefined
205
+ }
206
+
207
+ const has = (env, key) => typeof env[key] === 'string' && env[key] !== ''
208
+
209
+ // Set in processes an Electron / VS Code-based editor (Kiro IDE is one)
210
+ // starts, including its terminals and the hooks it runs.
211
+ const EDITOR_VARS = ['VSCODE_PID', 'VSCODE_IPC_HOOK', 'VSCODE_NLS_CONFIG', 'ELECTRON_RUN_AS_NODE']
212
+
213
+ /**
214
+ * Which Kiro surface the hook's environment points at: 'ide', 'cli', or
215
+ * undefined when nothing here says. Only § `resolveSurface` acts on it.
216
+ *
217
+ * PROVISIONAL — inferred from documentation and from how VS Code-based editors
218
+ * launch child processes, not yet observed on a real Kiro install. Revisit
219
+ * once a capture of both surfaces' hook environments exists.
220
+ *
221
+ * - SessionEnd fires only in Kiro CLI V3: the CLI, for certain.
222
+ * - Editor variables point at the IDE, but only weakly: a Kiro CLI run in an
223
+ * editor's terminal (VS Code, Cursor, Kiro) inherits them too. They outrank
224
+ * terminal ones, since an IDE launched from a shell inherits TERM_PROGRAM.
225
+ * - Nothing else is CLI-specific in Kiro's documentation, so anything else is
226
+ * undetected.
227
+ */
228
+ export const detectSurface = (trigger, env = process.env) => {
229
+ if (trigger === 'SessionEnd') return 'cli'
230
+ if (EDITOR_VARS.some((k) => has(env, k))) return 'ide'
231
+ return undefined
232
+ }
233
+
234
+ /**
235
+ * The surface to report for an event, or undefined to send nothing. Every
236
+ * event of a session must land on one source, or one session splits across
237
+ * two sources (and two ucids). Both surfaces run the one hooks file, so the
238
+ * hook can't refuse a surface that was never set up — it can't tell it apart
239
+ * — but it drops one that was removed.
240
+ *
241
+ * - Nothing recorded (a hand-written kiro.env): the detected surface, as
242
+ * before the surface marks existed.
243
+ * - One surface set up and the other never was: that surface, whatever the
244
+ * editor variables say, since a CLI in an editor's terminal carries them
245
+ * too. The other surface's sessions report under it. Only SessionEnd
246
+ * overrides it: an IDE-only setup drops it.
247
+ * - Both set up, or one removed while the other stayed: the environment tells
248
+ * them apart, and an event with no editor variables is the terminal's (so a
249
+ * CLI session's events and its SessionEnd share one source). A removed
250
+ * surface's events are dropped, at the cost of a CLI run in an editor's
251
+ * terminal after `--remove kiro-ide`, which reads as the IDE.
252
+ */
253
+ export const resolveSurface = (trigger, env, { surfaces = [], removed = [] } = {}) => {
254
+ const detected = detectSurface(trigger, env)
255
+ if (surfaces.length === 0) return detected
256
+ const known = new Set([...surfaces, ...removed])
257
+ const surface =
258
+ known.size > 1 ? (detected ?? 'cli') : trigger === 'SessionEnd' ? 'cli' : surfaces[0]
259
+ return surfaces.includes(surface) ? surface : undefined
260
+ }
261
+
262
+ /** `hook_event_name` as sent when it looks like an event name, else the
263
+ * trigger: the attribute is an id, never free text. */
264
+ const eventName = (raw, trigger) =>
265
+ typeof raw === 'string' && /^[A-Za-z]{1,64}$/.test(raw) ? raw : trigger
266
+
267
+ /**
268
+ * The span for a Kiro hook payload, or undefined (with the reason) when it
269
+ * must not be sent: an unmapped trigger, no session id, or no surface set up
270
+ * for it (§ `resolveSurface`). `kiro.surface` is stamped only when the
271
+ * environment's surface is the one reported.
272
+ */
273
+ export const spanForPayload = (payload, config, { argv = [], env = process.env } = {}) => {
274
+ const trigger = resolveTrigger(argv, payload)
275
+ if (!trigger) return { skip: `unmapped event ${String(payload?.hook_event_name)}` }
276
+ const sessionId = resolveSessionId(payload, env)
277
+ if (!sessionId) return { skip: `${trigger}: no session id` }
278
+ const detected = detectSurface(trigger, env)
279
+ const effective = resolveSurface(trigger, env, config)
280
+ const source = SOURCES[effective]
281
+ if (!source) {
282
+ return {
283
+ skip:
284
+ (config.surfaces ?? []).length === 0
285
+ ? `${trigger}: surface unknown and none recorded in kiro.env`
286
+ : `${trigger}: from a Kiro surface not set up in kiro.env`,
287
+ }
288
+ }
289
+
290
+ const attributes = {
291
+ 'kiro.hook_event_name': eventName(payload?.hook_event_name, trigger),
292
+ 'kiro.surface': detected === effective ? detected : undefined,
293
+ }
294
+ if (trigger === 'PostToolUse') {
295
+ const tool = nonEmpty(payload?.tool_name)
296
+ attributes['kiro.tool_name'] = tool && tool.length <= 256 ? tool : undefined
297
+ }
298
+ if (FILE_OP[trigger]) attributes['kiro.file.op'] = FILE_OP[trigger]
299
+ if (trigger === 'UserPromptSubmit' && config.capturePrompts) {
300
+ attributes.prompt = nonEmpty(payload?.prompt) ?? nonEmpty(env.USER_PROMPT)
301
+ }
302
+
303
+ const resourceAttrs = {}
304
+ if (config.userEmail) resourceAttrs['mainwave.user_email'] = config.userEmail
305
+
306
+ return {
307
+ span: {
308
+ spanName: SPAN_NAME[trigger],
309
+ attributes,
310
+ resourceAttrs,
311
+ sessionId,
312
+ source,
313
+ service: SERVICES[effective],
314
+ },
315
+ }
316
+ }
317
+
318
+ /** The sidecar whose mtime is the last delivered span — doctor reads it. */
319
+ export const activityPath = (argv) => `${markerLogPath(argv, LOG_NAME)}.ok`
320
+
321
+ const markDelivered = (argv) => {
322
+ try {
323
+ const p = activityPath(argv)
324
+ ensureLogDir(p)
325
+ writeFileSync(p, `${new Date().toISOString()}\n`, { mode: 0o600 })
326
+ } catch {
327
+ // best-effort, like every log write
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Read stdin up to `max` bytes, keeping the first `head` bytes of a payload
333
+ * that runs over: `{ text, truncated }`, or undefined on a read error or
334
+ * when stdin doesn't close within `timeoutMs`.
335
+ */
336
+ export const readStdinBounded = (
337
+ { max = STDIN_MAX_BYTES, head = STDIN_HEAD_BYTES, timeoutMs = STDIN_TIMEOUT_MS } = {},
338
+ stream = process.stdin,
339
+ ) =>
340
+ new Promise((done) => {
341
+ const chunks = []
342
+ let size = 0
343
+ let settled = false
344
+ const settle = (v) => {
345
+ if (settled) return
346
+ settled = true
347
+ clearTimeout(timer)
348
+ done(v)
349
+ }
350
+ const timer = setTimeout(() => settle(undefined), timeoutMs)
351
+ timer.unref?.()
352
+ stream.on('data', (c) => {
353
+ if (settled) return
354
+ const buf = typeof c === 'string' ? Buffer.from(c) : c
355
+ size += buf.length
356
+ chunks.push(buf)
357
+ if (size > max) {
358
+ settle({ text: Buffer.concat(chunks).subarray(0, head).toString('utf8'), truncated: true })
359
+ stream.destroy?.()
360
+ }
361
+ })
362
+ stream.on('end', () =>
363
+ settle({ text: Buffer.concat(chunks).toString('utf8'), truncated: false }),
364
+ )
365
+ stream.on('error', () => settle(undefined))
366
+ })
367
+
368
+ const field = (text, key) => {
369
+ const m = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.){1,256})"`).exec(text)
370
+ if (!m) return undefined
371
+ try {
372
+ return JSON.parse(`"${m[1]}"`)
373
+ } catch {
374
+ return undefined
375
+ }
376
+ }
377
+
378
+ /**
379
+ * The ids from the head of a payload too big to parse (a tool call with a
380
+ * huge response): `hook_event_name`, `session_id` and `tool_name`, so the
381
+ * event still counts. Kiro puts them before `tool_input` / `tool_response` in
382
+ * its documented payloads; a field found nowhere in the head is left out.
383
+ */
384
+ export const partialPayload = (head) => {
385
+ const out = {}
386
+ for (const k of ['hook_event_name', 'session_id', 'tool_name']) {
387
+ const v = field(head, k)
388
+ if (v !== undefined) out[k] = v
389
+ }
390
+ return out
391
+ }
392
+
393
+ /**
394
+ * The OTLP body for this hook run, or undefined (logged) when there is
395
+ * nothing to send. Everything the hook does before handing off.
396
+ */
397
+ export const buildBody = async (argv = process.argv, env = process.env, stream = process.stdin) => {
398
+ const read = await readStdinBounded({}, stream)
399
+ if (read === undefined) {
400
+ log('skip: stdin unreadable or not closed in time')
401
+ return undefined
402
+ }
403
+ let payload
404
+ if (read.truncated) {
405
+ payload = partialPayload(read.text)
406
+ log(`stdin over ${STDIN_MAX_BYTES} bytes: sending the ids from its head`)
407
+ } else {
408
+ try {
409
+ payload = JSON.parse(read.text)
410
+ } catch {
411
+ log(`skip: unparseable stdin (${read.text.length} bytes)`)
412
+ return undefined
413
+ }
414
+ }
415
+ const config = loadKiroConfig()
416
+ if (!config.endpoint || !config.bearer) {
417
+ log('skip: no endpoint/auth in ~/.mainwave/kiro.env')
418
+ return undefined
419
+ }
420
+ const result = spanForPayload(payload, config, { argv, env })
421
+ if (!result.span) {
422
+ log(`skip: ${result.skip}`)
423
+ return undefined
424
+ }
425
+ const { span } = result
426
+ return {
427
+ label: span.spanName,
428
+ body: buildMarkerPayload({
429
+ spanName: span.spanName,
430
+ scopeName: SCOPE_NAME,
431
+ attributes: span.attributes,
432
+ sessionId: span.sessionId,
433
+ resourceAttrs: span.resourceAttrs,
434
+ source: span.source,
435
+ service: span.service,
436
+ nowNs: Date.now() * 1_000_000,
437
+ }),
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Leave the span in the spool and start a detached sender for it, so the
443
+ * hook Kiro waits on returns without touching the network. The sender gets
444
+ * only the spool file's path (and `--log-file`, if given): the key stays in
445
+ * kiro.env, never on a command line.
446
+ */
447
+ /**
448
+ * Delete spooled spans older than SPOOL_MAX_AGE_MS; return how many remain.
449
+ * Only `kiro-*.json` files are considered, and every error is ignored.
450
+ */
451
+ export const sweepSpool = (dir = spoolDir(), now = Date.now()) => {
452
+ let names
453
+ try {
454
+ names = readdirSync(dir).filter((n) => n.startsWith('kiro-') && n.endsWith('.json'))
455
+ } catch {
456
+ return 0
457
+ }
458
+ let left = 0
459
+ for (const name of names) {
460
+ const path = join(dir, name)
461
+ try {
462
+ if (now - statSync(path).mtimeMs > SPOOL_MAX_AGE_MS) unlinkSync(path)
463
+ else left++
464
+ } catch {
465
+ // gone already, or unreadable: not ours to count
466
+ }
467
+ }
468
+ return left
469
+ }
470
+
471
+ /** Logged once while the spool stays full, not on every dropped event. */
472
+ const FULL_MARK = '.full'
473
+
474
+ /** Create the spool owner-only, tightening one an earlier run left looser. */
475
+ const ensureSpool = () => {
476
+ const dir = spoolDir()
477
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
478
+ chmodSync(dir, 0o700)
479
+ return dir
480
+ }
481
+
482
+ export const handOff = (
483
+ { label, body },
484
+ argv = process.argv,
485
+ script = fileURLToPath(import.meta.url),
486
+ ) => {
487
+ const dir = ensureSpool()
488
+ const full = join(dir, FULL_MARK)
489
+ if (sweepSpool(dir) >= SPOOL_MAX_FILES) {
490
+ try {
491
+ writeFileSync(full, '', { flag: 'wx', mode: 0o600 })
492
+ log(
493
+ `skip: ${SPOOL_MAX_FILES} spans already waiting in ${dir}; dropping events until it drains`,
494
+ )
495
+ } catch {
496
+ // already logged for this full spell
497
+ }
498
+ return false
499
+ }
500
+ try {
501
+ unlinkSync(full)
502
+ } catch {
503
+ // not full before
504
+ }
505
+ const file = join(dir, `kiro-${Date.now()}-${randomBytes(6).toString('hex')}.json`)
506
+ writeFileSync(file, JSON.stringify({ label, body }), { mode: 0o600, flag: 'wx' })
507
+ const logFile = hookFlag(argv, '--log-file')
508
+ const child = spawn(
509
+ process.execPath,
510
+ [script, '--send', file, ...(logFile ? ['--log-file', logFile] : [])],
511
+ { detached: true, stdio: 'ignore', windowsHide: true },
512
+ )
513
+ child.on('error', () => {})
514
+ child.unref()
515
+ return true
516
+ }
517
+
518
+ /** The detached sender: POST one spooled span, then delete it. Reads only a
519
+ * file inside the spool directory. */
520
+ export const send = async (argv = process.argv) => {
521
+ const file = hookFlag(argv, '--send')
522
+ if (!file) return
523
+ // The file's real directory must be the spool's real directory, so neither
524
+ // a relative path nor a symlink reaches anything else.
525
+ try {
526
+ if (dirname(realpathSync(resolve(file))) !== realpathSync(spoolDir())) return
527
+ } catch {
528
+ return
529
+ }
530
+ let spooled
531
+ try {
532
+ spooled = JSON.parse(readFileSync(file, 'utf8'))
533
+ } catch {
534
+ return
535
+ } finally {
536
+ try {
537
+ unlinkSync(file)
538
+ } catch {
539
+ // already gone
540
+ }
541
+ }
542
+ const config = loadKiroConfig()
543
+ if (!config.endpoint || !config.bearer) return
544
+ const status = await emitMarker({
545
+ endpoint: config.endpoint,
546
+ bearer: config.bearer,
547
+ body: spooled.body,
548
+ label: spooled.label,
549
+ log,
550
+ timeoutMs: POST_TIMEOUT_MS,
551
+ logOk: false,
552
+ })
553
+ if (isOkStatus(status)) markDelivered(argv)
554
+ }
555
+
556
+ // Run only as a script, not when imported by tests.
557
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
558
+ const sender = hookFlag(process.argv, '--send') !== undefined
559
+ // Whatever happens, exit 0 in bounded time: for the hook, a non-zero exit
560
+ // would block the developer's prompt or tool call.
561
+ setTimeout(() => process.exit(0), sender ? SENDER_EXIT_MS : HARD_EXIT_MS).unref()
562
+ process.on('uncaughtException', () => process.exit(0))
563
+ process.on('unhandledRejection', () => process.exit(0))
564
+ const work = sender
565
+ ? send()
566
+ : buildBody().then((built) => {
567
+ if (built) handOff(built)
568
+ })
569
+ work.catch(() => {}).finally(() => process.exit(0))
570
+ }
@@ -23,10 +23,12 @@ import {
23
23
  } from 'node:fs'
24
24
  import { homedir } from 'node:os'
25
25
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
26
+ import { fileURLToPath } from 'node:url'
26
27
 
27
28
  import {
28
29
  ATTR_CALLER_SPAN_ID,
29
30
  ATTR_CALLER_TRACE_ID,
31
+ ATTR_CLI_VERSION,
30
32
  ATTR_HOST_SOURCE,
31
33
  ATTR_SCHEMA_VERSION,
32
34
  ATTR_SUBAGENT_ID,
@@ -140,6 +142,33 @@ export const parseKv = (raw) => {
140
142
  return out
141
143
  }
142
144
 
145
+ /** Reverse of the env-file codec's double-quoting (KEY="value" with \\ \" \n). */
146
+ const unquote = (raw) => {
147
+ const v = raw.trim()
148
+ if (v.startsWith('"') && v.endsWith('"') && v.length >= 2) {
149
+ return v.slice(1, -1).replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\')
150
+ }
151
+ if (v.startsWith("'") && v.endsWith("'") && v.length >= 2) return v.slice(1, -1)
152
+ return v
153
+ }
154
+
155
+ /** Parse a `KEY="value"` env file (the CLI's env-file codec output) into a flat record; {} on any error. */
156
+ export const parseEnvFile = (text) => {
157
+ const out = {}
158
+ for (const line of (text ?? '').split('\n')) {
159
+ const trimmed = line.trim()
160
+ if (trimmed === '' || trimmed.startsWith('#')) continue
161
+ let rest = trimmed
162
+ if (rest.startsWith('export ')) rest = rest.slice('export '.length).trimStart()
163
+ const eq = rest.indexOf('=')
164
+ if (eq < 0) continue
165
+ const key = rest.slice(0, eq).trim()
166
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue
167
+ out[key] = unquote(rest.slice(eq + 1))
168
+ }
169
+ return out
170
+ }
171
+
143
172
  /** The Bearer value from an `Authorization=Bearer xyz` OTEL header string. */
144
173
  export const bearerFromHeaders = (raw) => {
145
174
  for (const [k, v] of Object.entries(parseKv(raw))) {
@@ -815,6 +844,59 @@ export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir
815
844
  processEnv,
816
845
  )
817
846
 
847
+ /** A staged release directory's name: `<version>-<12 hex content hash>`, as
848
+ * the CLI's installer names it under the managed `versions/` directory. */
849
+ const STAGED_RELEASE_RE = /^(.+)-[0-9a-f]{12}$/
850
+ /** The `--managed-by` value setup writes into a hook command it owns,
851
+ * `@mainwave/cli@<version>`. A concrete semver only: a payload that names a
852
+ * dist-tag (`@latest`) says nothing about which release is installed. */
853
+ const MANAGED_BY_RE = /^@mainwave\/cli@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/
854
+
855
+ /**
856
+ * The `@mainwave/cli` release a hook script belongs to, or `undefined` when it
857
+ * can't tell, never a guess. Checked in order:
858
+ *
859
+ * 1. a release staged under the managed hooks directory: the directory's
860
+ * name, `…/versions/<version>-<hash>/`;
861
+ * 2. the package itself, `<package>/hooks/`: the package's own
862
+ * `package.json` one level up;
863
+ * 3. a flat copy (the Cursor and Kiro scripts under `~/.mainwave/hooks/`): the
864
+ * `--managed-by @mainwave/cli@<version>` flag on the hook command, which
865
+ * the setup run that copied the script wrote with the same version.
866
+ *
867
+ * The flag comes last: a first-generation managed command runs a staged
868
+ * release through `managed-entry.mjs` and still carries the version (or
869
+ * `@latest`) the payload was pasted with.
870
+ */
871
+ export const hookReleaseVersion = (dir, readFile = readFileSync, argv = []) => {
872
+ const staged = STAGED_RELEASE_RE.exec(basename(dir))
873
+ if (staged && basename(dirname(dir)) === 'versions') return staged[1]
874
+ try {
875
+ const pkg = JSON.parse(readFile(join(dir, '..', 'package.json'), 'utf8'))
876
+ if (pkg?.name === '@mainwave/cli' && typeof pkg.version === 'string' && pkg.version !== '') {
877
+ return pkg.version
878
+ }
879
+ } catch {
880
+ // no package beside it — not a release we can name from the files
881
+ }
882
+ return MANAGED_BY_RE.exec(hookFlag(argv, '--managed-by') ?? '')?.[1]
883
+ }
884
+
885
+ let ownVersionMemo
886
+ /** This script's own release (§ `hookReleaseVersion`), read once per process. */
887
+ const ownCliVersion = () => {
888
+ if (ownVersionMemo === undefined) {
889
+ ownVersionMemo = {
890
+ value: hookReleaseVersion(
891
+ dirname(fileURLToPath(import.meta.url)),
892
+ readFileSync,
893
+ process.argv,
894
+ ),
895
+ }
896
+ }
897
+ return ownVersionMemo.value
898
+ }
899
+
818
900
  /**
819
901
  * Keep the developer's identity attrs — above all `mainwave.ucid`, so the marker
820
902
  * attributes to the same use case as the session — but override the two the
@@ -830,15 +912,27 @@ export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir
830
912
  * — lands as `mainwave.host_source`. Absent → the key is omitted, and any value
831
913
  * inherited from the developer's `OTEL_RESOURCE_ATTRIBUTES` is dropped too, so
832
914
  * the attribute only ever carries what the hook itself resolved.
915
+ *
916
+ * `cliVersion` — the release this script belongs to, defaulting to its own
917
+ * (§ `hookReleaseVersion`) — lands as `mainwave.cli.version`, under the same
918
+ * rule: absent → omitted, and an inherited value is never forwarded.
833
919
  */
834
- export const markerResourceAttrs = (resourceAttrs, source, service, hostSource) => {
920
+ export const markerResourceAttrs = (
921
+ resourceAttrs,
922
+ source,
923
+ service,
924
+ hostSource,
925
+ cliVersion = ownCliVersion(),
926
+ ) => {
835
927
  const rest = { ...(resourceAttrs ?? {}) }
836
928
  delete rest[ATTR_HOST_SOURCE]
929
+ delete rest[ATTR_CLI_VERSION]
837
930
  return {
838
931
  ...rest,
839
932
  'mainwave.source': source,
840
933
  'service.name': service,
841
934
  ...(hostSource ? { [ATTR_HOST_SOURCE]: hostSource } : {}),
935
+ ...(cliVersion ? { [ATTR_CLI_VERSION]: cliVersion } : {}),
842
936
  // The v2 contract stamp on every hook emission (marker + cursor), so the
843
937
  // collector shim's lifetime can be measured against v1-vs-v2 traffic.
844
938
  [ATTR_SCHEMA_VERSION]: SCHEMA_VERSION,