@cat-factory/executor-harness 1.31.10 → 1.32.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.
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process'
2
2
  import { mkdtemp, rm, writeFile } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
- import type { PiRunOutcome, PiRunStats, TodoProgress } from './pi.js'
5
+ import type { HarnessCallMetric, PiRunOutcome, PiRunStats, TodoProgress } from './pi.js'
6
6
  import { killChildProcess, spawnDetached } from './process.js'
7
7
  import { redact, secretsToRedact } from './redact.js'
8
8
 
@@ -64,6 +64,29 @@ function isObject(value: unknown): value is Record<string, unknown> {
64
64
  return typeof value === 'object' && value !== null
65
65
  }
66
66
 
67
+ /** Scrub any leased-credential occurrences from a telemetry body (no-op when none). */
68
+ function redactBody(text: string, secrets: string[]): string {
69
+ return secrets.length ? redact(text, secrets) : text
70
+ }
71
+
72
+ /**
73
+ * Fallback token attribution: if a CLI reported a cumulative total but no per-turn
74
+ * usage (so every captured call has zero tokens), pin the whole total onto the LAST
75
+ * call rather than dropping it — the run's tokens are still accounted, just not split
76
+ * per turn. A no-op when the calls already carry per-turn tokens.
77
+ */
78
+ function attributeCumulativeUsage(
79
+ calls: HarnessCallMetric[],
80
+ usage: { inputTokens: number; outputTokens: number } | undefined,
81
+ ): void {
82
+ if (!usage || calls.length === 0) return
83
+ const anyTokens = calls.some((c) => c.inputTokens > 0 || c.outputTokens > 0)
84
+ if (anyTokens) return
85
+ const last = calls[calls.length - 1]!
86
+ last.inputTokens = usage.inputTokens
87
+ last.outputTokens = usage.outputTokens
88
+ }
89
+
67
90
  /**
68
91
  * Drive one CLI subprocess to completion, streaming LF-framed JSONL from stdout
69
92
  * through `onEvent`. Mirrors `runPi`'s lifecycle: prompt over stdin (out-of-band,
@@ -184,25 +207,59 @@ export async function runClaudeCode(opts: SubscriptionRunOptions): Promise<PiRun
184
207
  let summary = ''
185
208
  let usage: { inputTokens: number; outputTokens: number } | undefined
186
209
 
210
+ // Reconstruct the full per-call request/response bodies for telemetry from the
211
+ // stream. `--output-format stream-json --verbose` emits each turn as a near-verbatim
212
+ // Anthropic Messages envelope, so `assistant` events carry the complete response
213
+ // (text + tool_use blocks + usage), and `user` events carry the tool_result blocks
214
+ // fed back — together the growing prompt transcript. We seed it with the two inputs
215
+ // the harness supplies (they never appear in the stream): the system + first user
216
+ // message. Bodies are credential-scrubbed (they can echo the leased token).
217
+ const secrets = opts.subscriptionToken ? secretsToRedact(opts.subscriptionToken) : []
218
+ const messages: Array<{ role: string; content: unknown }> = [
219
+ { role: 'system', content: opts.systemPrompt },
220
+ { role: 'user', content: opts.userPrompt },
221
+ ]
222
+ const calls: HarnessCallMetric[] = []
223
+
187
224
  const onEvent = (event: Record<string, unknown>): void => {
188
225
  const type = event.type
189
226
  if (type === 'assistant' && isObject(event.message)) {
190
- const content = (event.message as Record<string, unknown>).content
191
- if (Array.isArray(content)) {
192
- for (const block of content) {
193
- if (!isObject(block)) continue
194
- if (block.type === 'text' && typeof block.text === 'string') {
195
- stats.assistantChars += block.text.length
196
- }
197
- if (block.type === 'tool_use') {
198
- stats.toolCalls += 1
199
- if (block.name === 'TodoWrite' && opts.onProgress) {
200
- const progress = todosToProgress((block.input as Record<string, unknown>)?.todos)
201
- if (progress) opts.onProgress(progress)
202
- }
203
- }
227
+ const message = event.message as Record<string, unknown>
228
+ const content = Array.isArray(message.content) ? message.content : []
229
+ const { text, reasoning, toolUses } = claudeAssistantContent(content)
230
+ stats.assistantChars += text.length
231
+ stats.toolCalls += toolUses
232
+ for (const block of content) {
233
+ if (
234
+ isObject(block) &&
235
+ block.type === 'tool_use' &&
236
+ block.name === 'TodoWrite' &&
237
+ opts.onProgress
238
+ ) {
239
+ const progress = todosToProgress((block.input as Record<string, unknown>)?.todos)
240
+ if (progress) opts.onProgress(progress)
204
241
  }
205
242
  }
243
+ // Record this call BEFORE appending its turn: the prompt is the history that
244
+ // produced this response. The append-only array keeps each call's prompt a strict
245
+ // prefix of the next, so the backend's telemetry chain delta-compresses cleanly.
246
+ const u = claudeCallUsage(message.usage)
247
+ calls.push({
248
+ ...(typeof message.model === 'string' ? { model: message.model } : {}),
249
+ promptText: redactBody(JSON.stringify(messages), secrets),
250
+ messageCount: messages.length,
251
+ responseText: redactBody(text, secrets),
252
+ reasoningText: redactBody(reasoning, secrets),
253
+ inputTokens: u.inputTokens,
254
+ cachedInputTokens: u.cachedInputTokens,
255
+ outputTokens: u.outputTokens,
256
+ finishReason: typeof message.stop_reason === 'string' ? message.stop_reason : null,
257
+ })
258
+ messages.push({ role: 'assistant', content })
259
+ } else if (type === 'user' && isObject(event.message)) {
260
+ // tool_result blocks the harness fed back to the model — part of the next prompt.
261
+ const content = (event.message as Record<string, unknown>).content
262
+ if (Array.isArray(content)) messages.push({ role: 'tool', content })
206
263
  } else if (type === 'result') {
207
264
  if (typeof event.result === 'string') summary = event.result
208
265
  usage = claudeUsage(event.usage) ?? usage
@@ -282,7 +339,14 @@ export async function runClaudeCode(opts: SubscriptionRunOptions): Promise<PiRun
282
339
  onEvent,
283
340
  )
284
341
 
285
- return { summary, stats, stderrTail, ...(usage ? { usage } : {}) }
342
+ attributeCumulativeUsage(calls, usage)
343
+ return {
344
+ summary,
345
+ stats,
346
+ stderrTail,
347
+ ...(usage ? { usage } : {}),
348
+ ...(calls.length ? { callMetrics: calls } : {}),
349
+ }
286
350
  } finally {
287
351
  // Never leave the config dir (and any cached credential) on disk past the run.
288
352
  if (configHome) await rm(configHome, { recursive: true, force: true }).catch(() => {})
@@ -322,6 +386,44 @@ function claudeUsage(raw: unknown): { inputTokens: number; outputTokens: number
322
386
  return { inputTokens: input, outputTokens: output }
323
387
  }
324
388
 
389
+ /** Pull the text + reasoning out of a Claude `assistant` message's content blocks. */
390
+ function claudeAssistantContent(content: unknown[]): {
391
+ text: string
392
+ reasoning: string
393
+ toolUses: number
394
+ } {
395
+ let text = ''
396
+ let reasoning = ''
397
+ let toolUses = 0
398
+ for (const block of content) {
399
+ if (!isObject(block)) continue
400
+ if (block.type === 'text' && typeof block.text === 'string') text += block.text
401
+ else if (block.type === 'thinking' && typeof block.thinking === 'string')
402
+ reasoning += block.thinking
403
+ else if (block.type === 'tool_use') toolUses += 1
404
+ }
405
+ return { text, reasoning, toolUses }
406
+ }
407
+
408
+ /**
409
+ * Per-CALL token usage off a Claude `assistant` message's `usage` (this turn only, not
410
+ * the cumulative `result` total). `inputTokens` counts every billed input bucket (fresh
411
+ * + both cache buckets); `cachedInputTokens` is the cache share, surfaced separately.
412
+ */
413
+ function claudeCallUsage(raw: unknown): {
414
+ inputTokens: number
415
+ cachedInputTokens: number
416
+ outputTokens: number
417
+ } {
418
+ if (!isObject(raw)) return { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 }
419
+ const cached = numberOf(raw.cache_read_input_tokens) + numberOf(raw.cache_creation_input_tokens)
420
+ return {
421
+ inputTokens: numberOf(raw.input_tokens) + cached,
422
+ cachedInputTokens: cached,
423
+ outputTokens: numberOf(raw.output_tokens),
424
+ }
425
+ }
426
+
325
427
  // ---------------------------------------------------------------------------
326
428
  // Codex
327
429
  // ---------------------------------------------------------------------------
@@ -366,13 +468,33 @@ export async function runCodex(opts: SubscriptionRunOptions): Promise<PiRunOutco
366
468
  await writeFile(join(codexHome, 'config.toml'), 'cli_auth_credentials_store = "file"\n', 'utf8')
367
469
  }
368
470
 
471
+ // Codex has no system-prompt flag, so fold the composed role + best-practice
472
+ // context into the prompt itself (Claude Code instead rides --append-system-prompt).
473
+ const prompt = opts.systemPrompt
474
+ ? `${opts.systemPrompt}\n\n---\n\n${opts.userPrompt}`
475
+ : opts.userPrompt
476
+
477
+ // Codex's `exec --json` is far thinner than Claude Code's stream: it surfaces only
478
+ // flat assistant text and (on `token_count` events) the per-turn `last_token_usage`
479
+ // plus a cumulative total. It never exposes the request transcript or structured
480
+ // tool/command bodies, so the captured prompt is just the folded input — the response
481
+ // text + per-turn tokens are faithful; the request side is best-effort by design.
482
+ const secrets = opts.subscriptionToken ? secretsToRedact(opts.subscriptionToken) : []
483
+ const messages: Array<{ role: string; content: unknown }> = [{ role: 'user', content: prompt }]
484
+ const calls: HarnessCallMetric[] = []
485
+ let pendingText = ''
486
+
369
487
  const onEvent = (event: Record<string, unknown>): void => {
370
488
  const type = typeof event.type === 'string' ? event.type : ''
371
- if (type.includes('agent_message') || type === 'item.completed') {
489
+ if (
490
+ type.includes('agent_message') ||
491
+ (type === 'item.completed' && isCodexMessageItem(event))
492
+ ) {
372
493
  const text = extractText(event)
373
494
  if (text) {
374
495
  stats.assistantChars += text.length
375
496
  summary = text
497
+ pendingText = text
376
498
  }
377
499
  }
378
500
  if (type.includes('tool') || type.includes('command') || type.includes('exec')) {
@@ -382,14 +504,26 @@ export async function runCodex(opts: SubscriptionRunOptions): Promise<PiRunOutco
382
504
  if (progress && opts.onProgress) opts.onProgress(progress)
383
505
  const turnUsage = codexUsage(event)
384
506
  if (turnUsage) usage = turnUsage
507
+ // A `token_count` event closes a model turn: pair its per-turn usage with the
508
+ // assistant text seen since the previous turn as one telemetry call.
509
+ const perTurn = codexLastTurnUsage(event)
510
+ if (perTurn) {
511
+ calls.push({
512
+ model: opts.model,
513
+ promptText: redactBody(JSON.stringify(messages), secrets),
514
+ messageCount: messages.length,
515
+ responseText: redactBody(pendingText, secrets),
516
+ reasoningText: '',
517
+ inputTokens: perTurn.inputTokens,
518
+ cachedInputTokens: perTurn.cachedInputTokens,
519
+ outputTokens: perTurn.outputTokens,
520
+ finishReason: null,
521
+ })
522
+ if (pendingText) messages.push({ role: 'assistant', content: pendingText })
523
+ pendingText = ''
524
+ }
385
525
  }
386
526
 
387
- // Codex has no system-prompt flag, so fold the composed role + best-practice
388
- // context into the prompt itself (Claude Code instead rides --append-system-prompt).
389
- const prompt = opts.systemPrompt
390
- ? `${opts.systemPrompt}\n\n---\n\n${opts.userPrompt}`
391
- : opts.userPrompt
392
-
393
527
  try {
394
528
  const { stderrTail } = await streamCli(
395
529
  'codex',
@@ -411,13 +545,53 @@ export async function runCodex(opts: SubscriptionRunOptions): Promise<PiRunOutco
411
545
  onEvent,
412
546
  )
413
547
 
414
- return { summary, stats, stderrTail, ...(usage ? { usage } : {}) }
548
+ // Fallback for a CLI/version that never emits per-turn `last_token_usage`: record a
549
+ // single call from the cumulative total + final text so the run is still observable.
550
+ if (calls.length === 0 && (usage || summary)) {
551
+ calls.push({
552
+ model: opts.model,
553
+ promptText: redactBody(JSON.stringify(messages), secrets),
554
+ messageCount: messages.length,
555
+ responseText: redactBody(summary, secrets),
556
+ reasoningText: '',
557
+ inputTokens: usage?.inputTokens ?? 0,
558
+ cachedInputTokens: 0,
559
+ outputTokens: usage?.outputTokens ?? 0,
560
+ finishReason: null,
561
+ })
562
+ }
563
+ return {
564
+ summary,
565
+ stats,
566
+ stderrTail,
567
+ ...(usage ? { usage } : {}),
568
+ ...(calls.length ? { callMetrics: calls } : {}),
569
+ }
415
570
  } finally {
416
571
  // Never leave the decrypted credential on disk past the run.
417
572
  if (codexHome) await rm(codexHome, { recursive: true, force: true }).catch(() => {})
418
573
  }
419
574
  }
420
575
 
576
+ /**
577
+ * Whether a Codex `item.completed` event carries the model's ASSISTANT text (as
578
+ * opposed to a command/exec/tool/reasoning item, which also carry a `text` field —
579
+ * their command output or thinking — and must NOT be captured as the turn's response).
580
+ * A message item's kind contains `message` (`agent_message`/`assistant_message`); an
581
+ * item with no kind is treated as a message so older/simple shapes don't regress.
582
+ */
583
+ function isCodexMessageItem(event: Record<string, unknown>): boolean {
584
+ const item = isObject(event.item) ? (event.item as Record<string, unknown>) : undefined
585
+ if (!item) return false
586
+ const kind =
587
+ typeof item.item_type === 'string'
588
+ ? item.item_type
589
+ : typeof item.type === 'string'
590
+ ? item.type
591
+ : ''
592
+ return kind === '' || /message/i.test(kind)
593
+ }
594
+
421
595
  /** Best-effort: pull a textual message out of a Codex event. */
422
596
  function extractText(event: Record<string, unknown>): string | undefined {
423
597
  if (typeof event.message === 'string') return event.message
@@ -456,6 +630,8 @@ function codexPlanProgress(event: Record<string, unknown>): TodoProgress | undef
456
630
  * other shapes put it on `usage` / `info.usage` directly. We read the cumulative
457
631
  * total when present so the caller can simply overwrite (not sum) — summing
458
632
  * cumulative totals across events would multiply-count. Checked most-likely first.
633
+ * `input_tokens` is the TOTAL prompt count (OpenAI semantics: `cached_input_tokens`
634
+ * is a subset already inside it), so it is NOT summed with the cached share.
459
635
  */
460
636
  function codexUsage(
461
637
  event: Record<string, unknown>,
@@ -467,12 +643,36 @@ function codexUsage(
467
643
  (isObject(event.usage) ? event.usage : undefined) ??
468
644
  (info && isObject(info.usage) ? info.usage : undefined)
469
645
  if (!isObject(raw)) return undefined
470
- const input = numberOf(raw.input_tokens) + numberOf(raw.cached_input_tokens)
646
+ const input = numberOf(raw.input_tokens)
471
647
  const output = numberOf(raw.output_tokens)
472
648
  if (input === 0 && output === 0) return undefined
473
649
  return { inputTokens: input, outputTokens: output }
474
650
  }
475
651
 
652
+ /**
653
+ * Per-TURN Codex token usage off a `token_count` event's `info.last_token_usage` (the
654
+ * delta for the turn just completed, as opposed to `codexUsage`'s cumulative total).
655
+ * `input_tokens` is the total prompt count for the turn and already INCLUDES the cached
656
+ * share (OpenAI semantics), so `cachedInputTokens` is surfaced as the subset it is —
657
+ * NOT added on top (adding it would double-count every cached token).
658
+ */
659
+ function codexLastTurnUsage(event: Record<string, unknown>):
660
+ | {
661
+ inputTokens: number
662
+ cachedInputTokens: number
663
+ outputTokens: number
664
+ }
665
+ | undefined {
666
+ const info = isObject(event.info) ? (event.info as Record<string, unknown>) : undefined
667
+ const raw = info && isObject(info.last_token_usage) ? info.last_token_usage : undefined
668
+ if (!isObject(raw)) return undefined
669
+ const input = numberOf(raw.input_tokens)
670
+ const cached = numberOf(raw.cached_input_tokens)
671
+ const output = numberOf(raw.output_tokens)
672
+ if (input === 0 && output === 0) return undefined
673
+ return { inputTokens: input, cachedInputTokens: cached, outputTokens: output }
674
+ }
675
+
476
676
  function numberOf(value: unknown): number {
477
677
  return typeof value === 'number' && Number.isFinite(value) ? value : 0
478
678
  }
package/src/agent.ts CHANGED
@@ -421,6 +421,7 @@ async function runExploreMode(job: AgentJob, opts: RunOptions): Promise<AgentRes
421
421
  stats,
422
422
  stderrTail,
423
423
  usage,
424
+ callMetrics,
424
425
  diagnostics: runDiag,
425
426
  } = await runAgentInWorkspace(
426
427
  {
@@ -453,6 +454,7 @@ async function runExploreMode(job: AgentJob, opts: RunOptions): Promise<AgentRes
453
454
  error: noOutputReason(stats, stderrTail),
454
455
  failureCause: 'no-usable-output',
455
456
  ...(usage ? { usage } : {}),
457
+ ...(callMetrics ? { callMetrics } : {}),
456
458
  ...infraSetupFields,
457
459
  }
458
460
  }
@@ -470,6 +472,7 @@ async function runExploreMode(job: AgentJob, opts: RunOptions): Promise<AgentRes
470
472
  error: `the agent did not return a usable result: ${unusable}.${agentOutputTail(stderrTail, summary)}`,
471
473
  failureCause: 'no-usable-output',
472
474
  ...(usage ? { usage } : {}),
475
+ ...(callMetrics ? { callMetrics } : {}),
473
476
  ...infraSetupFields,
474
477
  }
475
478
  }
@@ -478,7 +481,13 @@ async function runExploreMode(job: AgentJob, opts: RunOptions): Promise<AgentRes
478
481
  // Prose: the summary IS the deliverable.
479
482
  if (job.output?.kind !== 'structured') {
480
483
  logger.info('agent(explore): done (prose)', { ...stats })
481
- return { summary, stats, ...(usage ? { usage } : {}), ...infraSetupFields }
484
+ return {
485
+ summary,
486
+ stats,
487
+ ...(usage ? { usage } : {}),
488
+ ...(callMetrics ? { callMetrics } : {}),
489
+ ...infraSetupFields,
490
+ }
482
491
  }
483
492
 
484
493
  // Structured: parse the agent's JSON. With repair enabled (default) a malformed
@@ -522,6 +531,7 @@ async function runExploreMode(job: AgentJob, opts: RunOptions): Promise<AgentRes
522
531
  error: noStructuredReason(stats, stderrTail, diagnostics),
523
532
  failureCause: 'no-usable-output',
524
533
  ...(usage ? { usage } : {}),
534
+ ...(callMetrics ? { callMetrics } : {}),
525
535
  ...infraSetupFields,
526
536
  }
527
537
  }
@@ -540,7 +550,14 @@ async function runExploreMode(job: AgentJob, opts: RunOptions): Promise<AgentRes
540
550
  ;(custom as Record<string, unknown>).environment = reportedEnvironment
541
551
  }
542
552
  logger.info('agent(explore): done (structured)', { ...stats })
543
- return { summary, custom, stats, ...(usage ? { usage } : {}), ...infraSetupFields }
553
+ return {
554
+ summary,
555
+ custom,
556
+ stats,
557
+ ...(usage ? { usage } : {}),
558
+ ...(callMetrics ? { callMetrics } : {}),
559
+ ...infraSetupFields,
560
+ }
544
561
  } finally {
545
562
  if (managed) await managed.cleanup()
546
563
  }
@@ -565,7 +582,7 @@ async function runCodingMode(job: AgentJob, opts: RunOptions): Promise<AgentResu
565
582
  if (job.mergeBase) return runConflictResolution(job, opts)
566
583
 
567
584
  const pushBranch = job.pushBranch ?? job.newBranch ?? job.branch
568
- const { summary, stats, stderrTail, pushed, usage } = await runCodingAgent(
585
+ const { summary, stats, stderrTail, pushed, usage, callMetrics } = await runCodingAgent(
569
586
  {
570
587
  kind: 'agent',
571
588
  jobId: job.jobId,
@@ -596,7 +613,14 @@ async function runCodingMode(job: AgentJob, opts: RunOptions): Promise<AgentResu
596
613
  if (!pushed) {
597
614
  // A no-op: a failure for the implementer, a clean non-event for the fixers.
598
615
  if (job.noChangesIsError === false) {
599
- return { pushed: false, branch: pushBranch, summary, stats, ...(usage ? { usage } : {}) }
616
+ return {
617
+ pushed: false,
618
+ branch: pushBranch,
619
+ summary,
620
+ stats,
621
+ ...(usage ? { usage } : {}),
622
+ ...(callMetrics ? { callMetrics } : {}),
623
+ }
600
624
  }
601
625
  return {
602
626
  pushed: false,
@@ -606,6 +630,7 @@ async function runCodingMode(job: AgentJob, opts: RunOptions): Promise<AgentResu
606
630
  error: noChangesReason('the agent produced no file changes', stats, stderrTail),
607
631
  failureCause: 'no-changes',
608
632
  ...(usage ? { usage } : {}),
633
+ ...(callMetrics ? { callMetrics } : {}),
609
634
  }
610
635
  }
611
636
 
@@ -632,7 +657,14 @@ async function runCodingMode(job: AgentJob, opts: RunOptions): Promise<AgentResu
632
657
  // this is the belt-and-suspenders path when the ahead-of-base check couldn't determine it.
633
658
  if (prUrl === null) {
634
659
  if (job.noChangesIsError === false) {
635
- return { pushed: false, branch: pushBranch, summary, stats, ...(usage ? { usage } : {}) }
660
+ return {
661
+ pushed: false,
662
+ branch: pushBranch,
663
+ summary,
664
+ stats,
665
+ ...(usage ? { usage } : {}),
666
+ ...(callMetrics ? { callMetrics } : {}),
667
+ }
636
668
  }
637
669
  return {
638
670
  pushed: false,
@@ -646,11 +678,27 @@ async function runCodingMode(job: AgentJob, opts: RunOptions): Promise<AgentResu
646
678
  ),
647
679
  failureCause: 'no-changes',
648
680
  ...(usage ? { usage } : {}),
681
+ ...(callMetrics ? { callMetrics } : {}),
649
682
  }
650
683
  }
651
- return { pushed: true, prUrl, branch: pushBranch, summary, stats, ...(usage ? { usage } : {}) }
684
+ return {
685
+ pushed: true,
686
+ prUrl,
687
+ branch: pushBranch,
688
+ summary,
689
+ stats,
690
+ ...(usage ? { usage } : {}),
691
+ ...(callMetrics ? { callMetrics } : {}),
692
+ }
693
+ }
694
+ return {
695
+ pushed: true,
696
+ branch: pushBranch,
697
+ summary,
698
+ stats,
699
+ ...(usage ? { usage } : {}),
700
+ ...(callMetrics ? { callMetrics } : {}),
652
701
  }
653
- return { pushed: true, branch: pushBranch, summary, stats, ...(usage ? { usage } : {}) }
654
702
  }
655
703
 
656
704
  /**
@@ -719,7 +767,7 @@ async function runConflictResolution(job: AgentJob, opts: RunOptions): Promise<A
719
767
  const diff = await conflictDiff(dir, conflicted, signal)
720
768
  const userPrompt = buildConflictPrompt(mergeBase, job.branch, conflicted, diff, job.userPrompt)
721
769
 
722
- const { summary, stats, stderrTail, usage } = await runAgentInWorkspace(
770
+ const { summary, stats, stderrTail, usage, callMetrics } = await runAgentInWorkspace(
723
771
  {
724
772
  dir,
725
773
  systemPrompt: job.systemPrompt,
@@ -752,6 +800,7 @@ async function runConflictResolution(job: AgentJob, opts: RunOptions): Promise<A
752
800
  error: unresolvedReason(unresolved, stats, stderrTail),
753
801
  failureCause: 'agent',
754
802
  ...(usage ? { usage } : {}),
803
+ ...(callMetrics ? { callMetrics } : {}),
755
804
  }
756
805
  }
757
806
  // Complete the merge commit with the agent's resolution staged, then push.
@@ -759,7 +808,14 @@ async function runConflictResolution(job: AgentJob, opts: RunOptions): Promise<A
759
808
  opts.onPhase?.('push')
760
809
  logger.info('agent(conflict): pushing resolved branch', { ...stats })
761
810
  await pushBranch(dir, job.branch, job.ghToken, signal)
762
- return { pushed: true, branch: job.branch, summary, stats, ...(usage ? { usage } : {}) }
811
+ return {
812
+ pushed: true,
813
+ branch: job.branch,
814
+ summary,
815
+ stats,
816
+ ...(usage ? { usage } : {}),
817
+ ...(callMetrics ? { callMetrics } : {}),
818
+ }
763
819
  })
764
820
  }
765
821
 
@@ -850,7 +906,7 @@ async function runBootstrap(job: AgentJob, opts: RunOptions): Promise<AgentResul
850
906
 
851
907
  opts.onPhase?.('agent')
852
908
  logger.info('agent(bootstrap): running agent')
853
- const { summary, stats, stderrTail, usage } = await runAgentInWorkspace(
909
+ const { summary, stats, stderrTail, usage, callMetrics } = await runAgentInWorkspace(
854
910
  {
855
911
  dir,
856
912
  systemPrompt: job.systemPrompt,
@@ -874,7 +930,14 @@ async function runBootstrap(job: AgentJob, opts: RunOptions): Promise<AgentResul
874
930
  if (!(await producedRepoContent(dir, !fromScratch, signal))) {
875
931
  const error = bootstrapNoOpReason(!fromScratch, stats, summary, stderrTail)
876
932
  logger.error('agent(bootstrap): agent produced no content, refusing to push', { ...stats })
877
- return { summary, stats, error, failureCause: 'agent', ...(usage ? { usage } : {}) }
933
+ return {
934
+ summary,
935
+ stats,
936
+ error,
937
+ failureCause: 'agent',
938
+ ...(usage ? { usage } : {}),
939
+ ...(callMetrics ? { callMetrics } : {}),
940
+ }
878
941
  }
879
942
 
880
943
  opts.onPhase?.('push')
@@ -890,7 +953,13 @@ async function runBootstrap(job: AgentJob, opts: RunOptions): Promise<AgentResul
890
953
  : `Bootstrap from ${job.repo.owner}/${job.repo.name}`,
891
954
  })
892
955
  logger.info('agent(bootstrap): complete', { defaultBranch: boot.target.defaultBranch })
893
- return { defaultBranch: boot.target.defaultBranch, summary, stats, ...(usage ? { usage } : {}) }
956
+ return {
957
+ defaultBranch: boot.target.defaultBranch,
958
+ summary,
959
+ stats,
960
+ ...(usage ? { usage } : {}),
961
+ ...(callMetrics ? { callMetrics } : {}),
962
+ }
894
963
  })
895
964
  }
896
965
 
@@ -17,7 +17,7 @@ import {
17
17
  remoteBranchExists,
18
18
  } from './git.js'
19
19
  import { FOLLOW_UPS_FILENAME, FollowUpTailer } from './follow-ups.js'
20
- import type { PiRunStats } from './pi.js'
20
+ import type { HarnessCallMetric, PiRunStats } from './pi.js'
21
21
  import {
22
22
  acquireRepoCheckout,
23
23
  agentNeverActed,
@@ -89,6 +89,8 @@ export interface CodingAgentOutcome {
89
89
  stderrTail?: string
90
90
  /** Token usage from a subscription harness's CLI stream (absent for Pi). */
91
91
  usage?: { inputTokens: number; outputTokens: number }
92
+ /** Per-model-call telemetry from a subscription harness's CLI stream (absent for Pi). */
93
+ callMetrics?: HarnessCallMetric[]
92
94
  }
93
95
 
94
96
  /**
@@ -296,7 +298,7 @@ export async function runCodingAgent(
296
298
  try {
297
299
  opts.onPhase?.('agent')
298
300
  logger.info('coding-agent: running agent', { serviceDirectory })
299
- const { summary, stats, stderrTail, usage } = await runAgentInWorkspace(
301
+ const { summary, stats, stderrTail, usage, callMetrics } = await runAgentInWorkspace(
300
302
  {
301
303
  dir: workDir,
302
304
  systemPrompt: spec.systemPrompt,
@@ -371,6 +373,7 @@ export async function runCodingAgent(
371
373
  stats,
372
374
  ...(stderrTail ? { stderrTail } : {}),
373
375
  ...(usage ? { usage } : {}),
376
+ ...(callMetrics ? { callMetrics } : {}),
374
377
  }
375
378
  } else {
376
379
  opts.onPhase?.('push')
@@ -383,6 +386,7 @@ export async function runCodingAgent(
383
386
  stats,
384
387
  ...(stderrTail ? { stderrTail } : {}),
385
388
  ...(usage ? { usage } : {}),
389
+ ...(callMetrics ? { callMetrics } : {}),
386
390
  }
387
391
  }
388
392
  } finally {
@@ -83,6 +83,9 @@ export async function standUpFrontend(
83
83
  ): Promise<FrontendStandUp> {
84
84
  const startedAt = Date.now()
85
85
  const processes: ChildProcess[] = []
86
+ // The frontend app's directory: the checkout root, or a monorepo subdirectory when the config
87
+ // named one. install/build/serve run here and `outputDir`/`mockMappingsPath` are relative to it.
88
+ const workDir = infra.directory ? join(dir, infra.directory) : dir
86
89
  // Keep the run's inactivity watchdog fed while the (activity-silent) install → build → serve
87
90
  // stand-up runs. A real frontend's `install` + `build` can exceed the harness inactivity
88
91
  // window (default 10 min, JOB_INACTIVITY_MS) — and unlike the Pi phase this stand-up emits
@@ -121,7 +124,7 @@ export async function standUpFrontend(
121
124
  const install = installCommand(infra)
122
125
  logger.info('agent(frontend): installing', { command: install.join(' ') })
123
126
  const installed = await exec(install[0]!, install.slice(1), {
124
- cwd: dir,
127
+ cwd: workDir,
125
128
  signal,
126
129
  timeout: 8 * 60_000,
127
130
  maxBuffer: 16 * 1024 * 1024,
@@ -133,7 +136,7 @@ export async function standUpFrontend(
133
136
  const buildScript = infra.buildScript ?? DEFAULTS.buildScript
134
137
  logger.info('agent(frontend): building', { buildScript })
135
138
  const built = await exec(pm, ['run', buildScript], {
136
- cwd: dir,
139
+ cwd: workDir,
137
140
  signal,
138
141
  timeout: 12 * 60_000,
139
142
  maxBuffer: 16 * 1024 * 1024,
@@ -158,7 +161,7 @@ export async function standUpFrontend(
158
161
  )
159
162
  }
160
163
  const shim = `window.env = ${JSON.stringify(infra.env)};\n`
161
- await writeFile(join(dir, outputDir, 'env.js'), shim, 'utf8').catch((err) => {
164
+ await writeFile(join(workDir, outputDir, 'env.js'), shim, 'utf8').catch((err) => {
162
165
  // Best-effort, but no longer silent: a missing/renamed output dir would drop the shim
163
166
  // and the app would read no URLs, so surface it in the log for diagnosis.
164
167
  logger.warn('agent(frontend): could not write runtime env shim', {
@@ -170,10 +173,10 @@ export async function standUpFrontend(
170
173
 
171
174
  // 3) WireMock for the mocked upstreams. Seeded from the FE repo's mappings dir when present;
172
175
  // otherwise it still binds the port (unmatched requests 404, gentler than ECONNREFUSED).
173
- processes.push(await startWireMock(dir, infra, wiremockPort, logger))
176
+ processes.push(await startWireMock(workDir, infra, wiremockPort, logger))
174
177
 
175
178
  // 4) Serve the built app.
176
- processes.push(startServe(dir, infra, servePort, outputDir, logger))
179
+ processes.push(startServe(workDir, infra, servePort, outputDir, logger))
177
180
 
178
181
  // 5) Health-check the served app AND WireMock before handing off, concurrently (WireMock is
179
182
  // a JVM that cold-starts slower than the static server). A dead WireMock would otherwise let