@mainwave/cli 0.12.0 → 0.13.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,584 @@
1
+ #!/usr/bin/env node
2
+ // The codex-turns feature of the Mainwave hook dispatcher (mainwave-hook.mjs).
3
+ // It runs on Codex's UserPromptSubmit, Stop, Interrupt, PermissionRequest,
4
+ // PostToolUse, PreModelRequest, SubagentStart, SubagentStop and SessionStart
5
+ // events and turns them into closed spans that Developer Work reads for turn
6
+ // counts and the working / waiting / away split:
7
+ //
8
+ // - `mainwave.codex.turn`: one per prompt, from UserPromptSubmit to Stop or
9
+ // Interrupt (or to the last event the turn saw, when it is abandoned);
10
+ // - `mainwave.codex.permission_wait`: from a PermissionRequest to the next hook
11
+ // event of the same session and agent;
12
+ // - `mainwave.codex.subagent_turn`: from SubagentStart to SubagentStop.
13
+ //
14
+ // Codex's hook input carries no timestamp, and the collector pairs nothing
15
+ // across inserts, so each span is sent once, when it ends, with the times the
16
+ // hook process read. A small per-session state file under
17
+ // `~/.mainwave/state/codex-turns/` holds what is open between events; it is
18
+ // deleted once nothing is open.
19
+ //
20
+ // Sent: session, turn and agent ids, agent type, working directory, a tool
21
+ // name for a permission wait, and times. Never the prompt, the assistant
22
+ // message, a tool's input or output, the transcript path or token usage: this
23
+ // file reads only the fields named in `readInput`.
24
+ //
25
+ // Codex runs the Stop and Interrupt groups synchronously and every other
26
+ // group in the background (`markers.ts#hookShape`), so Codex waits briefly for
27
+ // this feature only when a turn ends.
28
+ //
29
+ // Fails open: any error sends nothing and never reaches the session.
30
+
31
+ import { createHash } from 'node:crypto'
32
+ import {
33
+ chmodSync,
34
+ closeSync,
35
+ mkdirSync,
36
+ openSync,
37
+ readFileSync,
38
+ readdirSync,
39
+ renameSync,
40
+ statSync,
41
+ unlinkSync,
42
+ writeFileSync,
43
+ } from 'node:fs'
44
+ import { homedir } from 'node:os'
45
+ import { isAbsolute, join } from 'node:path'
46
+
47
+ import {
48
+ emitMarker,
49
+ hookFlag,
50
+ loadOtelConfig,
51
+ markerLog,
52
+ markerResourceAttrs,
53
+ markerTool,
54
+ opaqueIdExact,
55
+ stringAttr,
56
+ } from './marker-core.mjs'
57
+ import {
58
+ ATTR_SUBAGENT_ID,
59
+ ATTR_CODEX_AGENT_TYPE,
60
+ ATTR_CODEX_CWD,
61
+ ATTR_CODEX_END_REASON,
62
+ ATTR_CODEX_PARENT_TURN_ID,
63
+ ATTR_CODEX_TOOL_NAME,
64
+ ATTR_CODEX_TURN_ID,
65
+ ATTR_CODEX_WAIT_END_EVENT,
66
+ CODEX_PERMISSION_WAIT,
67
+ CODEX_SUBAGENT_TURN,
68
+ CODEX_TURN,
69
+ CODEX_TURN_SERVICE,
70
+ CODEX_TURN_SOURCE,
71
+ } from './vocabulary.mjs'
72
+
73
+ /** The hook log this feature writes. */
74
+ export const CODEX_TURNS_LOG = 'codex-turns.log'
75
+
76
+ /** Files in the state directory untouched for this long are deleted. */
77
+ export const STATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
78
+
79
+ const LOCK_WAIT_MS = 1500
80
+ const LOCK_STALE_MS = 10_000
81
+
82
+ /** Codex runs the Stop and Interrupt groups synchronously (`codex exec` exits
83
+ * without waiting for an async hook), so it waits for this feature at the
84
+ * end of each turn. Each caps its lock wait and its post so the worst case
85
+ * fits its hook timeout: Stop's 1.5 s plus 1.2 s inside 5 s, Interrupt's
86
+ * 0.6 s plus 1 s inside 2 s. Setup writes those timeouts: Stop 5 s,
87
+ * Interrupt 2 s. */
88
+ export const SYNC_CAPS = Object.freeze({
89
+ Stop: Object.freeze({ lockWaitMs: LOCK_WAIT_MS, postTimeoutMs: 1200 }),
90
+ Interrupt: Object.freeze({ lockWaitMs: 600, postTimeoutMs: 1000 }),
91
+ })
92
+
93
+ /** The state directory: `--state-dir <path>` (tests), else `~/.mainwave/state/codex-turns`.
94
+ * Never the environment: a repository's env reaches the hook. */
95
+ export const stateDir = (argv) =>
96
+ hookFlag(argv, '--state-dir') || join(homedir(), '.mainwave', 'state', 'codex-turns')
97
+
98
+ // ── The state machine (pure) ─────────────────────────────────────────────────
99
+
100
+ /** `abandoned` is the last turn a new prompt or session start abandoned, kept
101
+ * so a Stop or Interrupt for it that locks late can still end it (§
102
+ * `applyEvent`). It does not keep the state file alive (§ `isEmptyState`). */
103
+ export const emptyState = () => ({ v: 1, turn: null, subagents: {}, waits: {}, abandoned: null })
104
+
105
+ /** A well-formed state read back from disk, else an empty one. */
106
+ export const parseState = (text) => {
107
+ try {
108
+ const s = JSON.parse(text)
109
+ if (s?.v !== 1 || typeof s.subagents !== 'object' || typeof s.waits !== 'object') {
110
+ return emptyState()
111
+ }
112
+ return {
113
+ v: 1,
114
+ turn: s.turn ?? null,
115
+ subagents: s.subagents ?? {},
116
+ waits: s.waits ?? {},
117
+ abandoned: s.abandoned ?? null,
118
+ }
119
+ } catch {
120
+ return emptyState()
121
+ }
122
+ }
123
+
124
+ const OPAQUE_NAME_RE = /^[A-Za-z0-9_.:/ -]{1,128}$/
125
+ const opaqueName = (v) => (typeof v === 'string' && OPAQUE_NAME_RE.test(v) ? v : undefined)
126
+
127
+ /** The only fields of the hook input this feature reads. */
128
+ export const readInput = (payload, event) => ({
129
+ event,
130
+ sessionId: opaqueIdExact(payload?.session_id),
131
+ turnId: opaqueIdExact(payload?.turn_id),
132
+ agentId: opaqueIdExact(payload?.agent_id),
133
+ agentType: opaqueName(payload?.agent_type),
134
+ toolName: opaqueName(payload?.tool_name),
135
+ cwd:
136
+ typeof payload?.cwd === 'string' && isAbsolute(payload.cwd) && payload.cwd.length <= 4096
137
+ ? payload.cwd
138
+ : undefined,
139
+ })
140
+
141
+ /**
142
+ * Apply one hook event at time `now` (ms) to `state`. Returns the next state
143
+ * and the spans the event closed, as plain records (§ `buildBody` makes the
144
+ * OTLP). Does not mutate `state`.
145
+ *
146
+ * What closes what (the contract with the collector):
147
+ *
148
+ * - Only an event with no `agent_id` opens or closes a main turn. A new
149
+ * UserPromptSubmit or a SessionStart finds a turn still open and abandons
150
+ * it, ending it at the last event it saw, so a killed Codex never stretches
151
+ * a turn across the developer's absence; one that saw no later event is
152
+ * dropped.
153
+ * - A permission wait ends at the first later PostToolUse, PreModelRequest,
154
+ * PermissionRequest, Stop, Interrupt, SubagentStop or SessionStart of the
155
+ * same session and agent (a main SessionStart ends a main wait by abandoning
156
+ * its turn). PreToolUse is not one: Codex runs it before the approval, so it
157
+ * never ends that call's wait. PostModelRequest is not one either, because
158
+ * the PreModelRequest before it already did.
159
+ * - A turn that ends takes its open waits (end = the turn's end) and any
160
+ * subagent still open (abandoned, end = its last event) with it.
161
+ * - Hooks read the clock before they take the state lock, so events can reach
162
+ * the state out of time order: `codex exec` fires SessionStart and
163
+ * UserPromptSubmit within milliseconds, Codex submits a queued
164
+ * prompt the moment a turn ends, so its UserPromptSubmit can lock before
165
+ * that turn's Stop. The reverse, an async UserPromptSubmit locking after its
166
+ * own synchronous Stop, needs a turn that finishes faster than Node starts.
167
+ * These guards cover the reorderings seen or reviewed, not every possible
168
+ * one: a SessionStart or UserPromptSubmit abandons only a turn or subagent
169
+ * that started earlier; a Stop or Interrupt without a turn id closes only a
170
+ * turn that started no later than itself; one whose turn id names the turn
171
+ * last abandoned sends that turn again with its real end reason and end (the
172
+ * span ids are the same, so the row replaces the abandoned one); a
173
+ * PermissionRequest or SubagentStart older than the open turn, or with none
174
+ * open, is dropped; and an event ends only a wait that started no later than
175
+ * itself, except that a turn's or subagent's own end takes its waits.
176
+ */
177
+ export const applyEvent = (state, input, now) => {
178
+ const st = structuredClone(state)
179
+ const out = []
180
+ const { event, sessionId, turnId, agentId, cwd } = input
181
+ const key = agentId ?? ''
182
+
183
+ // `owner` is true when the wait's turn or subagent is ending: then the wait
184
+ // ends too, whatever the clock says.
185
+ const closeWait = (waitKey, endMs, endEvent, owner = false) => {
186
+ const w = st.waits[waitKey]
187
+ if (w === undefined || (!owner && endMs < w.startMs)) return
188
+ delete st.waits[waitKey]
189
+ out.push({
190
+ kind: 'wait',
191
+ sessionId,
192
+ turnId: w.turnId,
193
+ mainTurnId: w.mainTurnId,
194
+ agentId: w.agentId,
195
+ toolName: w.toolName,
196
+ startMs: w.startMs,
197
+ endMs: Math.max(endMs, w.startMs),
198
+ endEvent,
199
+ })
200
+ }
201
+
202
+ const closeSubagent = (id, endMs, reason, endEvent) => {
203
+ const s = st.subagents[id]
204
+ if (s === undefined) return
205
+ delete st.subagents[id]
206
+ closeWait(id, endMs, endEvent, true)
207
+ // One that saw no event after its start has nothing to measure.
208
+ if (reason === 'abandoned' && s.lastMs <= s.startMs) return
209
+ out.push({
210
+ kind: 'subagent',
211
+ sessionId,
212
+ agentId: id,
213
+ agentType: s.agentType,
214
+ turnId: s.turnId,
215
+ parentTurnId: s.parentTurnId,
216
+ cwd: s.cwd,
217
+ startMs: s.startMs,
218
+ endMs: Math.max(endMs, s.startMs),
219
+ reason,
220
+ })
221
+ }
222
+
223
+ const closeTurn = (endMs, reason, endEvent) => {
224
+ const t = st.turn
225
+ if (t === null) return
226
+ for (const waitKey of Object.keys(st.waits)) closeWait(waitKey, endMs, endEvent, true)
227
+ for (const id of Object.keys(st.subagents)) {
228
+ closeSubagent(id, st.subagents[id].lastMs, 'abandoned', endEvent)
229
+ }
230
+ st.turn = null
231
+ if (reason === 'abandoned') {
232
+ st.abandoned = { turnId: t.turnId, startMs: t.startMs, cwd: t.cwd }
233
+ if (t.lastMs <= t.startMs) return
234
+ }
235
+ out.push({
236
+ kind: 'turn',
237
+ sessionId,
238
+ turnId: t.turnId,
239
+ cwd: t.cwd,
240
+ startMs: t.startMs,
241
+ endMs: Math.max(endMs, t.startMs),
242
+ reason,
243
+ })
244
+ }
245
+
246
+ // A subagent's event is also work inside the open main turn, so a turn
247
+ // abandoned after a kill ends at its subagents' last event too.
248
+ const touch = () => {
249
+ if (st.turn !== null) st.turn.lastMs = Math.max(st.turn.lastMs, now)
250
+ if (agentId !== undefined && st.subagents[agentId] !== undefined) {
251
+ st.subagents[agentId].lastMs = Math.max(st.subagents[agentId].lastMs, now)
252
+ }
253
+ }
254
+
255
+ switch (event) {
256
+ case 'UserPromptSubmit':
257
+ if (agentId !== undefined) {
258
+ touch()
259
+ break
260
+ }
261
+ if (st.turn !== null && st.turn.turnId === turnId) break
262
+ // An older prompt than the open turn's: the open turn is the newer one.
263
+ if (st.turn !== null && now < st.turn.startMs) break
264
+ closeTurn(st.turn?.lastMs ?? now, 'abandoned', event)
265
+ if (turnId !== undefined) st.turn = { turnId, startMs: now, lastMs: now, cwd }
266
+ break
267
+ case 'Stop':
268
+ case 'Interrupt':
269
+ // A subagent's own Stop or Interrupt ends that agent's wait, not the turn.
270
+ if (agentId !== undefined) {
271
+ touch()
272
+ closeWait(key, now, event)
273
+ break
274
+ }
275
+ {
276
+ const reason = event === 'Stop' ? 'stop' : 'interrupt'
277
+ const a = st.abandoned
278
+ if (st.turn !== null && st.turn.turnId === turnId) {
279
+ closeTurn(now, reason, event)
280
+ } else if (st.turn !== null && turnId === undefined) {
281
+ // With no turn id, only a turn that started no later than this event
282
+ // can be the one it ends.
283
+ if (st.turn.startMs <= now) closeTurn(now, reason, event)
284
+ } else if (a !== null && turnId === a.turnId && a.startMs <= now) {
285
+ // The turn a queued prompt abandoned before this event took the lock.
286
+ st.abandoned = null
287
+ out.push({
288
+ kind: 'turn',
289
+ sessionId,
290
+ turnId: a.turnId,
291
+ cwd: a.cwd,
292
+ startMs: a.startMs,
293
+ endMs: now,
294
+ reason,
295
+ })
296
+ }
297
+ }
298
+ break
299
+ case 'PermissionRequest':
300
+ touch()
301
+ // None open, or one that started after this request: the request
302
+ // belongs to an earlier turn.
303
+ if (st.turn === null || now < st.turn.startMs) break
304
+ if (st.waits[key] !== undefined && now < st.waits[key].startMs) break
305
+ closeWait(key, now, event)
306
+ st.waits[key] = {
307
+ startMs: now,
308
+ mainTurnId: st.turn.turnId,
309
+ turnId: turnId ?? st.turn.turnId,
310
+ agentId,
311
+ toolName: input.toolName,
312
+ }
313
+ break
314
+ case 'PostToolUse':
315
+ case 'PreModelRequest':
316
+ touch()
317
+ closeWait(key, now, event)
318
+ break
319
+ case 'SubagentStart':
320
+ if (agentId === undefined) break
321
+ // Its parent turn has already ended (or this start locked after the next
322
+ // prompt): registering it would leave it open with no parent, or the
323
+ // wrong one.
324
+ if (st.turn === null || now < st.turn.startMs) break
325
+ st.subagents[agentId] = {
326
+ startMs: now,
327
+ lastMs: now,
328
+ turnId,
329
+ parentTurnId: st.turn.turnId,
330
+ agentType: input.agentType,
331
+ cwd,
332
+ }
333
+ touch()
334
+ break
335
+ case 'SubagentStop': {
336
+ if (agentId === undefined) break
337
+ const s = st.subagents[agentId]
338
+ if (s !== undefined && turnId !== undefined) s.turnId = turnId
339
+ touch()
340
+ closeSubagent(agentId, now, 'subagent_stop', event)
341
+ break
342
+ }
343
+ case 'SessionStart':
344
+ // A subagent's own SessionStart ends that agent's wait and says nothing
345
+ // about the main turn.
346
+ if (agentId !== undefined) {
347
+ touch()
348
+ closeWait(key, now, event)
349
+ break
350
+ }
351
+ // Only what started before this SessionStart belongs to an earlier run.
352
+ if (st.turn !== null && st.turn.startMs < now) {
353
+ closeTurn(st.turn.lastMs, 'abandoned', event)
354
+ }
355
+ for (const id of Object.keys(st.subagents)) {
356
+ if (st.subagents[id].startMs < now) {
357
+ closeSubagent(id, st.subagents[id].lastMs, 'abandoned', event)
358
+ }
359
+ }
360
+ // Waits live only inside a turn; with none open, any left are stale.
361
+ if (st.turn === null) st.waits = {}
362
+ break
363
+ default:
364
+ break
365
+ }
366
+ return { state: st, closed: out }
367
+ }
368
+
369
+ // ── The spans ────────────────────────────────────────────────────────────────
370
+
371
+ const sha = (text, hexChars) => createHash('sha256').update(text).digest('hex').slice(0, hexChars)
372
+ const ns = (ms) => String(BigInt(Math.trunc(ms)) * 1_000_000n)
373
+
374
+ const turnTraceId = (sessionId, turnId) => sha(`codex-turn:${sessionId}:${turnId}`, 32)
375
+ const turnSpanId = (sessionId, turnId) => sha(`codex-turn-span:${sessionId}:${turnId}`, 16)
376
+
377
+ const attrs = (pairs) =>
378
+ pairs.filter(([, v]) => v !== undefined && v !== '').map(([k, v]) => stringAttr(k, String(v)))
379
+
380
+ /** One closed record (§ `applyEvent`) as an OTLP span, with the contract's
381
+ * deterministic ids so a re-send lands on the same row. */
382
+ export const buildSpan = (c) => {
383
+ const base = { kind: 1, startTimeUnixNano: ns(c.startMs), endTimeUnixNano: ns(c.endMs) }
384
+ if (c.kind === 'turn') {
385
+ return {
386
+ ...base,
387
+ traceId: turnTraceId(c.sessionId, c.turnId),
388
+ spanId: turnSpanId(c.sessionId, c.turnId),
389
+ name: CODEX_TURN,
390
+ attributes: attrs([
391
+ ['session.id', c.sessionId],
392
+ [ATTR_CODEX_TURN_ID, c.turnId],
393
+ [ATTR_CODEX_END_REASON, c.reason],
394
+ [ATTR_CODEX_CWD, c.cwd],
395
+ ]),
396
+ }
397
+ }
398
+ if (c.kind === 'wait') {
399
+ return {
400
+ ...base,
401
+ traceId: turnTraceId(c.sessionId, c.mainTurnId),
402
+ spanId: sha(`codex-wait:${c.sessionId}:${c.agentId ?? ''}:${c.turnId}:${ns(c.startMs)}`, 16),
403
+ parentSpanId: turnSpanId(c.sessionId, c.mainTurnId),
404
+ name: CODEX_PERMISSION_WAIT,
405
+ attributes: attrs([
406
+ ['session.id', c.sessionId],
407
+ [ATTR_CODEX_TURN_ID, c.turnId],
408
+ [ATTR_SUBAGENT_ID, c.agentId],
409
+ [ATTR_CODEX_TOOL_NAME, c.toolName],
410
+ [ATTR_CODEX_WAIT_END_EVENT, c.endEvent],
411
+ ]),
412
+ }
413
+ }
414
+ return {
415
+ ...base,
416
+ traceId: sha(`codex-subagent:${c.agentId}:${ns(c.startMs)}`, 32),
417
+ spanId: sha(`codex-subagent-span:${c.agentId}:${ns(c.startMs)}`, 16),
418
+ name: CODEX_SUBAGENT_TURN,
419
+ attributes: attrs([
420
+ ['session.id', c.sessionId],
421
+ [ATTR_SUBAGENT_ID, c.agentId],
422
+ [ATTR_CODEX_TURN_ID, c.turnId],
423
+ [ATTR_CODEX_PARENT_TURN_ID, c.parentTurnId],
424
+ [ATTR_CODEX_AGENT_TYPE, c.agentType],
425
+ [ATTR_CODEX_END_REASON, c.reason],
426
+ [ATTR_CODEX_CWD, c.cwd],
427
+ ]),
428
+ }
429
+ }
430
+
431
+ /** The OTLP body for the spans one event closed, under the Codex export's own
432
+ * source tag so they share its ucid derivation, with the email and ucid the
433
+ * Codex exporter sends (`resourceAttrs`). */
434
+ export const buildBody = (closed, resourceAttrs) => ({
435
+ resourceSpans: [
436
+ {
437
+ resource: {
438
+ attributes: Object.entries(
439
+ markerResourceAttrs(resourceAttrs, CODEX_TURN_SOURCE, CODEX_TURN_SERVICE, undefined),
440
+ ).map(([k, v]) => stringAttr(k, v)),
441
+ },
442
+ scopeSpans: [{ scope: { name: 'mainwave.codex-turns' }, spans: closed.map(buildSpan) }],
443
+ },
444
+ ],
445
+ })
446
+
447
+ // ── State on disk ────────────────────────────────────────────────────────────
448
+
449
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
450
+
451
+ const stateFile = (dir, sessionId) => join(dir, `${sha(sessionId, 32)}.json`)
452
+
453
+ /** Hold `<file>.lock` (created exclusively) while `fn` runs; false when it
454
+ * could not be taken in time. A lock older than LOCK_STALE_MS is a crashed
455
+ * hook's and is taken over. */
456
+ const withLock = async (file, fn, waitMs = LOCK_WAIT_MS) => {
457
+ const lock = `${file}.lock`
458
+ const deadline = Date.now() + waitMs
459
+ for (;;) {
460
+ try {
461
+ closeSync(openSync(lock, 'wx', 0o600))
462
+ break
463
+ } catch (e) {
464
+ if (e?.code !== 'EEXIST') return false
465
+ try {
466
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) unlinkSync(lock)
467
+ } catch {
468
+ // gone already
469
+ }
470
+ if (Date.now() > deadline) return false
471
+ await sleep(15)
472
+ }
473
+ }
474
+ try {
475
+ await fn()
476
+ return true
477
+ } finally {
478
+ try {
479
+ unlinkSync(lock)
480
+ } catch {
481
+ // best effort
482
+ }
483
+ }
484
+ }
485
+
486
+ const writeAtomic = (file, text) => {
487
+ const tmp = `${file}.${process.pid}.tmp`
488
+ writeFileSync(tmp, text, { mode: 0o600 })
489
+ renameSync(tmp, file)
490
+ }
491
+
492
+ /** Nothing open: the state file can go (no file reads back as this). */
493
+ export const isEmptyState = (s) =>
494
+ s.turn === null && Object.keys(s.subagents).length === 0 && Object.keys(s.waits).length === 0
495
+
496
+ /** Delete every state file nobody has touched for STATE_MAX_AGE_MS. */
497
+ export const sweepStale = (dir, nowMs) => {
498
+ let removed = 0
499
+ try {
500
+ for (const name of readdirSync(dir)) {
501
+ if (!/\.(json|lock|tmp)$/.test(name)) continue
502
+ const path = join(dir, name)
503
+ try {
504
+ if (nowMs - statSync(path).mtimeMs > STATE_MAX_AGE_MS) {
505
+ unlinkSync(path)
506
+ removed++
507
+ }
508
+ } catch {
509
+ // raced with another hook
510
+ }
511
+ }
512
+ } catch {
513
+ // no directory yet
514
+ }
515
+ return removed
516
+ }
517
+
518
+ /**
519
+ * The feature. `ctx.event` is the hook event the dispatcher was invoked for
520
+ * (else the input's `hook_event_name`); `ctx.argv` carries the hook command's
521
+ * flags and `--tool codex`; `ctx.emit` posts. `ctx.now` is the clock, in ms.
522
+ */
523
+ export const handle = async (
524
+ payload,
525
+ { argv = process.argv, emit = emitMarker, event, now = () => Date.now() } = {},
526
+ ) => {
527
+ const t = now()
528
+ const name = event ?? payload?.hook_event_name
529
+ const input = readInput(payload, name)
530
+ if (input.sessionId === undefined || typeof name !== 'string') return
531
+ const log = markerLog(argv, CODEX_TURNS_LOG)
532
+ const dir = stateDir(argv)
533
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
534
+ // mkdir's mode leaves an existing directory as it is; Windows has no modes.
535
+ if (process.platform !== 'win32') chmodSync(dir, 0o700)
536
+ const file = stateFile(dir, input.sessionId)
537
+
538
+ const sync = Object.hasOwn(SYNC_CAPS, name) ? SYNC_CAPS[name] : undefined
539
+ let closed = []
540
+ const locked = await withLock(
541
+ file,
542
+ () => {
543
+ let before
544
+ try {
545
+ before = parseState(readFileSync(file, 'utf8'))
546
+ } catch {
547
+ before = emptyState()
548
+ }
549
+ const next = applyEvent(before, input, t)
550
+ closed = next.closed
551
+ if (isEmptyState(next.state)) {
552
+ try {
553
+ unlinkSync(file)
554
+ } catch {
555
+ // none yet
556
+ }
557
+ } else if (JSON.stringify(next.state) !== JSON.stringify(before)) {
558
+ writeAtomic(file, JSON.stringify(next.state))
559
+ }
560
+ },
561
+ sync?.lockWaitMs,
562
+ )
563
+ if (!locked) {
564
+ log(`skip ${name}: state lock busy`)
565
+ return
566
+ }
567
+ if (name === 'SessionStart') sweepStale(dir, t)
568
+ if (closed.length === 0) return
569
+
570
+ const tool = markerTool(argv)
571
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(undefined, {}, tool)
572
+ if (!endpoint || !bearer) {
573
+ log(`skip ${closed.length} codex span(s): collector endpoint/bearer not found in config.toml`)
574
+ return
575
+ }
576
+ await emit({
577
+ endpoint,
578
+ bearer,
579
+ body: buildBody(closed, resourceAttrs),
580
+ label: `codex ${closed.map((c) => c.kind).join('+')} (${name})`,
581
+ log,
582
+ ...(sync ? { timeoutMs: sync.postTimeoutMs } : {}),
583
+ })
584
+ }
@@ -53,7 +53,9 @@ export const WATCHDOG_MS = 9000
53
53
  * Caps are each feature's own worst case plus 250 ms: the plan snapshot's
54
54
  * 4 s send; the PR marker's 5 s `gh pr view` and 3 s post; the MR marker's
55
55
  * 2.5 s lookup and 1.5 s post; the ticket markers' and the StopFailure
56
- * span's 3 s post; the commit marker's 5 s of git and 3 s post.
56
+ * span's 3 s post; the commit marker's 5 s of git and 3 s post; the Codex
57
+ * turn spans' 1.5 s for the state file's lock and 3 s post (a Stop waits 1.5 s
58
+ * and posts for 1.2 s, an Interrupt 0.6 s and 1 s; the other events post for 3 s).
57
59
  */
58
60
  export const FEATURES = Object.freeze({
59
61
  'plan-snapshot': { module: 'plan-snapshot.mjs', capMs: 4250, optOut: 'markers' },
@@ -63,6 +65,7 @@ export const FEATURES = Object.freeze({
63
65
  'linear-ticket-marker': { module: 'linear-ticket-marker.mjs', capMs: 3250, optOut: 'markers' },
64
66
  'jira-ticket-marker': { module: 'jira-ticket-marker.mjs', capMs: 3250, optOut: 'markers' },
65
67
  'stop-failure': { module: 'stop-failure.mjs', capMs: 3250, optOut: 'markers' },
68
+ 'codex-turns': { module: 'codex-turns.mjs', capMs: 4750, optOut: 'markers' },
66
69
  })
67
70
 
68
71
  /**
@@ -82,6 +85,15 @@ export const ROUTES = Object.freeze({
82
85
  'codex PostToolUse bash': ['github-pr-marker', 'glab-mr-marker', 'git-commit-marker'],
83
86
  'codex PostToolUse linear': ['linear-ticket-marker'],
84
87
  'codex PostToolUse jira': ['jira-ticket-marker'],
88
+ 'codex UserPromptSubmit turns': ['codex-turns'],
89
+ 'codex Stop turns': ['codex-turns'],
90
+ 'codex Interrupt turns': ['codex-turns'],
91
+ 'codex PermissionRequest turns': ['codex-turns'],
92
+ 'codex PostToolUse turns': ['codex-turns'],
93
+ 'codex PreModelRequest turns': ['codex-turns'],
94
+ 'codex SubagentStart turns': ['codex-turns'],
95
+ 'codex SubagentStop turns': ['codex-turns'],
96
+ 'codex SessionStart turns': ['codex-turns'],
85
97
  })
86
98
 
87
99
  /** `<host> <Event>[ <route>]` from argv: the positional arguments after the
@@ -263,7 +275,9 @@ export const dispatch = async (
263
275
  ? emitMarker({ ...args, body, redacted: false, redactionConfigDir })
264
276
  : Promise.resolve(undefined)
265
277
  }
266
- const run = Promise.resolve(mod.handle(payload, { argv: hookArgv, emit })).then(
278
+ const run = Promise.resolve(
279
+ mod.handle(payload, { argv: hookArgv, emit, event, route }),
280
+ ).then(
267
281
  () => 'done',
268
282
  () => 'failed',
269
283
  )
@@ -991,15 +991,19 @@ const opaqueIdOrUndefined = (v) => {
991
991
  * - `toolCallId` — the payload's `tool_use_id`, the value Claude Code's own
992
992
  * tool span carries as `gen_ai.tool.call.id`.
993
993
  * - `subagentId` — the payload's `agent_id`, present only when the hook runs
994
- * inside a subagent; Claude Code's own spans carry it as `agent_id`.
994
+ * inside a subagent; Claude Code's own spans carry it as `agent_id`. Codex
995
+ * sends the same field (the child's own conversation id), so a Codex-hosted
996
+ * marker carries it too.
995
997
  *
996
- * Claude Code only (`tool`, § `markerTool`): another host's hook environment is
997
- * inherited from the developer's shell, where a `TRACEPARENT` would name some
998
- * unrelated trace, and no other host's payload fields are known to mean the
999
- * same thing. Each field is read on its own, so a missing or malformed one
1000
- * drops only itself.
998
+ * `caller` and `toolCallId` are Claude Code only (`tool`, § `markerTool`): a
999
+ * Codex hook's environment is inherited from the developer's shell, where a
1000
+ * `TRACEPARENT` would name some unrelated trace, and Codex's `tool_use_id` is
1001
+ * not verified to equal the call id its own spans carry. Any other host yields
1002
+ * nothing. Each field is read on its own, so a missing or malformed one drops
1003
+ * only itself.
1001
1004
  */
1002
1005
  export const markerCallContext = (tool, payload, env = process.env) => {
1006
+ if (tool === 'codex') return { subagentId: opaqueIdOrUndefined(payload?.agent_id) }
1003
1007
  if (tool !== 'claude-code') return {}
1004
1008
  return {
1005
1009
  caller: parseTraceparent(env.TRACEPARENT),