@wjarka/cezarion 0.17.0-pr2001.3020 → 0.17.0-pr2004.3026

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.
@@ -13,6 +13,7 @@ import { cezarToolEnvNames, cezarToolNames } from '../ci-wait/tools.js';
13
13
  import { costWeightedTokens } from './usage.js';
14
14
  import { readNdjson } from './ndjson.js';
15
15
  import { InputSubmissions } from './input-submissions.js';
16
+ import { claudeFrameDidWork, normalizeIntentionalTeardownResult, selectedModelRefusal, zeroClaudeModelUsage, zeroClaudeUsage, } from './claude-stream.js';
16
17
  import { claudeTurnStarted, createClaudeUiState, mapClaudeMessage, stringifyToolResultContent, toolResultImageBlocks, } from './claude-ui-mapper.js';
17
18
  /** Resolve discovery and execution through the same binary and dry-run precedence. */
18
19
  export function resolveClaudeExecutable(override) {
@@ -310,222 +311,246 @@ export class ClaudeCliRunner {
310
311
  }
311
312
  }
312
313
  };
313
- const result = (async () => {
314
- let outputFailure;
314
+ // ---- native message dispatch -------------------------------------------
315
+ // One stdout frame passes these steps in order (hearsay-tools/cezarion#1954).
316
+ // Returns undefined only for an unparseable line: JSON.parse never yields
317
+ // undefined, so a parsed `null` still reaches the reads below and fails
318
+ // the output loop as before.
319
+ const parseStreamLine = (line) => {
315
320
  try {
316
- for await (const line of readNdjson(child.stdout)) {
317
- if (timedOut)
318
- break;
319
- let msg;
320
- try {
321
- msg = JSON.parse(line);
322
- }
323
- catch {
324
- onEvent?.({ type: 'note', message: `claude: skipped unparseable stream line: ${truncate(line)}` });
325
- continue;
326
- }
327
- // Claude reports `error_during_execution` while reacting to our
328
- // teardown signal. Once cezar has signalled the child, that frame
329
- // describes the intentional stop rather than an agent failure.
330
- // Normalize only this precise wire shape so genuine result errors
331
- // (authentication, limits, malformed sessions) stay authoritative.
332
- if (queuedTurnPending && (msg.type === 'assistant' || msg.type === 'user' || msg.type === 'result')) {
333
- queuedTurnPending = false;
334
- emitUi(claudeTurnStarted);
335
- }
336
- // `--replay-user-messages` echoes a line when the model consumes it (#505).
337
- // Presentation-free: it is the user's own text, and it carries no tool_result.
338
- if (msg.type === 'user' && msg.isReplay === true) {
339
- if (typeof msg.uuid === 'string')
340
- humanUnsettled.delete(msg.uuid);
341
- const ids = typeof msg.uuid === 'string' ? submissions.consume(msg.uuid) : [];
342
- if (ids.length)
343
- opts.onAgentInputConsumed?.(ids);
344
- continue;
345
- }
346
- opts.onActivity?.();
347
- if (msg.type === 'system' && msg.subtype === 'init') {
348
- reportedModel = typeof msg.model === 'string' && msg.model !== '' ? msg.model : undefined;
349
- reportedSession = typeof msg.session_id === 'string' && msg.session_id !== '' ? msg.session_id : undefined;
350
- }
351
- // Background tasks and hooks can start work without assistant content
352
- // or token usage. Only init is known to be identity-only metadata.
353
- if ((msg.type === 'system' && msg.subtype !== 'init') || msg.type === 'tool_progress')
354
- attemptDidWork = true;
355
- if (msg.type === 'assistant' || msg.type === 'user') {
356
- // A refusal's own visible text is diagnostic, not model work. Any
357
- // other output, tool call/result, reasoning or nonzero usage forbids replay.
358
- if (msg.message?.usage && !zeroClaudeUsage(msg.message.usage))
359
- attemptDidWork = true;
360
- const content = msg.message?.content;
361
- if (content !== undefined && !Array.isArray(content))
362
- attemptDidWork = true;
363
- for (const block of Array.isArray(content) ? content : []) {
364
- if (!block || typeof block !== 'object') {
365
- attemptDidWork = true;
366
- continue;
367
- }
368
- const b = block;
369
- if (b.type !== 'text' || selectedModelRefusal(b.text) !== reportedModel || !reportedModel)
370
- attemptDidWork = true;
371
- }
372
- }
373
- const identity = reportedModel && reportedSession ? JSON.stringify([reportedSession, reportedModel]) : undefined;
374
- const retryable = !terminatedByCezar && stdinOpen && !attemptDidWork
375
- && msg.type === 'result' && msg.is_error === true
376
- && identity !== undefined && identity === successfulIdentity
377
- && selectedModelRefusal(msg.result) === reportedModel
378
- && zeroClaudeUsage(msg.usage)
379
- && zeroClaudeModelUsage(msg.modelUsage)
380
- && (msg.total_cost_usd === undefined || msg.total_cost_usd === 0)
381
- && unsettled.size === 1
382
- && (msg.user_message_uuids === undefined || (Array.isArray(msg.user_message_uuids) && msg.user_message_uuids.length === 1
383
- && msg.user_message_uuids[0] === [...unsettled][0]));
384
- const uuid = [...unsettled][0];
385
- const lineToRetry = uuid ? sentLines.get(uuid) : undefined;
386
- if (retryable && uuid && lineToRetry && (!refusalRetry || refusalRetry.attempts < 2)) {
387
- // Native attempts remain balanced, but a retryable result must not
388
- // emit v1 error/turn-end: those would fail or park the workflow.
389
- emitUi(state => mapClaudeMessage(msg, state));
390
- refusalRetry ??= { uuid, line: lineToRetry, message: msg.result, attempts: 0 };
391
- const retry = refusalRetry;
392
- const delay = retry.attempts++ === 0 ? 5000 : 15000;
393
- onEvent?.({ type: 'note', message: `Claude model refusal: ${retry.message}; retrying (${retry.attempts}/2) in ${delay / 1000}s` });
394
- refusalTimer = setTimeout(() => {
395
- refusalTimer = undefined;
396
- if (!stdinOpen || hasExited() || refusalRetry !== retry)
397
- return;
398
- const input = JSON.parse(retry.line);
399
- // A fresh native UUID, the same logical input IDs, and byte-for-byte
400
- // content. Already-observed consumption is never acknowledged twice.
401
- const ids = submissions.consume(retry.uuid);
402
- const human = humanUnsettled.delete(retry.uuid);
403
- unsettled.delete(retry.uuid);
404
- sentLines.delete(retry.uuid);
405
- if (!sendMessage(input.message.content, error => {
406
- if (!error || !stdinOpen)
407
- return;
408
- cancelRefusalRetry();
409
- onEvent?.({ type: 'error', message: retry.message });
410
- interrupt();
411
- }, ids, human, true)) {
412
- cancelRefusalRetry();
413
- onEvent?.({ type: 'error', message: retry.message });
414
- interrupt();
415
- return;
416
- }
417
- retry.uuid = [...unsettled][0];
418
- retry.line = sentLines.get(retry.uuid);
419
- }, delay);
420
- refusalTimer.unref?.();
421
- continue;
422
- }
423
- // Keep the original diagnosis on exhaustion, even if the final result
424
- // differs. Other errors outside a retry still use their native message.
425
- const originalRefusal = msg.type === 'result' && msg.is_error && refusalRetry?.message;
426
- const mappedMessage = normalizeIntentionalTeardownResult(originalRefusal ? { ...msg, result: originalRefusal } : msg, terminatedByCezar);
427
- emitUi((state) => mapClaudeMessage(mappedMessage, state));
428
- let delta = 0;
429
- try {
430
- delta = handleClaudeMessage(mappedMessage, { toolCalls, textChunks, onEvent });
431
- }
432
- catch (err) {
433
- const message = err instanceof Error ? err.message : String(err);
434
- onEvent?.({ type: 'note', message: `claude: skipped malformed event (${msg.type ?? 'unknown'}): ${message}` });
435
- continue;
436
- }
437
- if (delta > 0) {
438
- sawUsage = true;
439
- tokensUsed += delta;
440
- onEvent?.({ type: 'token-usage', tokensUsed });
441
- }
442
- if (msg.type === 'result') {
443
- if (msg.is_error !== true && msg.subtype === 'success' && costWeightedTokens(msg.usage) > 0)
444
- successfulIdentity = identity;
445
- const wasRetrying = refusalRetry !== undefined;
446
- cancelRefusalRetry();
447
- if (typeof msg.total_cost_usd === 'number' && Number.isFinite(msg.total_cost_usd) && msg.total_cost_usd >= 0) {
448
- onEvent?.({ type: 'cost', usd: msg.total_cost_usd });
449
- }
450
- pendingMarkerAsk = parseAskMarker(textChunks.slice(turnTextStart).join('\n')) !== null;
451
- // The named lines are exact; `queued_turn_count: 0` is only a fallback, because a
452
- // line still in the pipe when the CLI computed this result is not covered by it.
453
- const named = Array.isArray(msg.user_message_uuids) ? msg.user_message_uuids.map(String) : null;
454
- const settled = named ?? (msg.queued_turn_count === 0 ? [...unsettled] : [...unsettled].slice(0, 1));
455
- // A line this result covered was read even if its replay echo was missed.
456
- // An error result settles its lines but proves nothing reached the model: they
457
- // stay pending, so a closing session returns them to the queue (#505 review).
458
- // Fallback settlement must not clear humanUnsettled: a line may still be in the
459
- // pipe, and only a named UUID or a replay echo proves the model read it (#486).
460
- const covered = settled.flatMap(id => {
461
- unsettled.delete(id);
462
- sentLines.delete(id);
463
- if (named)
464
- humanUnsettled.delete(id);
465
- return msg.is_error === true ? [] : submissions.consume(id);
466
- });
467
- if (covered.length)
468
- opts.onAgentInputConsumed?.(covered);
469
- // A result is not idle if human stdin messages already queued later turns.
470
- agentInputReady = unsettled.size === 0;
471
- // A line written after this turn's last model call runs as the CLI's next
472
- // queued turn; its replay/result reports consumption then (#505). Announce
473
- // that turn when its first frame arrives, never speculatively: a line the
474
- // CLI never runs must not look like activity. Decided before the turn-end
475
- // callback, which may itself submit (and announce) the next prompt.
476
- queuedTurnPending = unsettled.size > 0;
477
- // Remaining inputs belong to the next turn. Clear the completed
478
- // turn's work before any queued frame (including system activity)
479
- // arrives; resetting at its first assistant frame would erase work.
480
- if (queuedTurnPending)
481
- attemptDidWork = false;
482
- onEvent?.({ type: 'turn-end' });
483
- // Drain later human input only after a successful logical turn.
484
- // Failed turns retain the hold until the workflow tears down.
485
- if (wasRetrying && msg.is_error !== true && stdinOpen) {
486
- for (const input of deferredHuman.splice(0)) {
487
- humanUnsettled.delete(input.id);
488
- sendMessage(input.content, undefined, [], true);
489
- }
490
- opts.onAgentInputReady?.();
491
- }
492
- scheduleAutoEnd();
493
- }
494
- }
321
+ return JSON.parse(line);
322
+ }
323
+ catch {
324
+ onEvent?.({ type: 'note', message: `claude: skipped unparseable stream line: ${truncate(line)}` });
325
+ return undefined;
326
+ }
327
+ };
328
+ const announceQueuedTurn = (msg) => {
329
+ if (queuedTurnPending && (msg.type === 'assistant' || msg.type === 'user' || msg.type === 'result')) {
330
+ queuedTurnPending = false;
331
+ emitUi(claudeTurnStarted);
332
+ }
333
+ };
334
+ // `--replay-user-messages` echoes a line when the model consumes it (#505).
335
+ // Presentation-free: it is the user's own text, and it carries no tool_result.
336
+ const consumeReplay = (msg) => {
337
+ if (msg.type !== 'user' || msg.isReplay !== true)
338
+ return false;
339
+ if (typeof msg.uuid === 'string')
340
+ humanUnsettled.delete(msg.uuid);
341
+ const ids = typeof msg.uuid === 'string' ? submissions.consume(msg.uuid) : [];
342
+ if (ids.length)
343
+ opts.onAgentInputConsumed?.(ids);
344
+ return true;
345
+ };
346
+ /** Record the reported model and session, mark attempt work, and return the identity. */
347
+ const observeFrame = (msg) => {
348
+ if (msg.type === 'system' && msg.subtype === 'init') {
349
+ reportedModel = typeof msg.model === 'string' && msg.model !== '' ? msg.model : undefined;
350
+ reportedSession = typeof msg.session_id === 'string' && msg.session_id !== '' ? msg.session_id : undefined;
351
+ }
352
+ if (claudeFrameDidWork(msg, reportedModel))
353
+ attemptDidWork = true;
354
+ return reportedModel && reportedSession ? JSON.stringify([reportedSession, reportedModel]) : undefined;
355
+ };
356
+ const retryableRefusal = (msg, identity) => !terminatedByCezar && stdinOpen && !attemptDidWork
357
+ && msg.type === 'result' && msg.is_error === true
358
+ && identity !== undefined && identity === successfulIdentity
359
+ && selectedModelRefusal(msg.result) === reportedModel
360
+ && zeroClaudeUsage(msg.usage)
361
+ && zeroClaudeModelUsage(msg.modelUsage)
362
+ && (msg.total_cost_usd === undefined || msg.total_cost_usd === 0)
363
+ && unsettled.size === 1
364
+ && (msg.user_message_uuids === undefined || (Array.isArray(msg.user_message_uuids) && msg.user_message_uuids.length === 1
365
+ && msg.user_message_uuids[0] === [...unsettled][0]));
366
+ const abandonRefusalRetry = (message) => {
367
+ cancelRefusalRetry();
368
+ onEvent?.({ type: 'error', message });
369
+ interrupt();
370
+ };
371
+ const replayRefusedInput = (retry) => {
372
+ refusalTimer = undefined;
373
+ if (!stdinOpen || hasExited() || refusalRetry !== retry)
374
+ return;
375
+ const input = JSON.parse(retry.line);
376
+ // A fresh native UUID, the same logical input IDs, and byte-for-byte
377
+ // content. Already-observed consumption is never acknowledged twice.
378
+ const ids = submissions.consume(retry.uuid);
379
+ const human = humanUnsettled.delete(retry.uuid);
380
+ unsettled.delete(retry.uuid);
381
+ sentLines.delete(retry.uuid);
382
+ if (!sendMessage(input.message.content, error => {
383
+ if (!error || !stdinOpen)
384
+ return;
385
+ abandonRefusalRetry(retry.message);
386
+ }, ids, human, true)) {
387
+ abandonRefusalRetry(retry.message);
388
+ return;
389
+ }
390
+ retry.uuid = [...unsettled][0];
391
+ retry.line = sentLines.get(retry.uuid);
392
+ };
393
+ /** Hold a retryable model refusal and arm its replay; true when the frame is consumed. */
394
+ const scheduleRefusalRetry = (msg, identity) => {
395
+ const retryable = retryableRefusal(msg, identity);
396
+ const uuid = [...unsettled][0];
397
+ const lineToRetry = uuid ? sentLines.get(uuid) : undefined;
398
+ if (!(retryable && uuid && lineToRetry && (!refusalRetry || refusalRetry.attempts < 2)))
399
+ return false;
400
+ // Native attempts remain balanced, but a retryable result must not
401
+ // emit v1 error/turn-end: those would fail or park the workflow.
402
+ emitUi(state => mapClaudeMessage(msg, state));
403
+ refusalRetry ??= { uuid, line: lineToRetry, message: msg.result, attempts: 0 };
404
+ const retry = refusalRetry;
405
+ const delay = retry.attempts++ === 0 ? 5000 : 15000;
406
+ onEvent?.({ type: 'note', message: `Claude model refusal: ${retry.message}; retrying (${retry.attempts}/2) in ${delay / 1000}s` });
407
+ refusalTimer = setTimeout(() => replayRefusedInput(retry), delay);
408
+ refusalTimer.unref?.();
409
+ return true;
410
+ };
411
+ /** Emit the frame's v1 and v2 events and count its usage; false for a malformed frame. */
412
+ const deliverFrame = (msg) => {
413
+ // Keep the original diagnosis on exhaustion, even if the final result
414
+ // differs. Other errors outside a retry still use their native message.
415
+ const originalRefusal = msg.type === 'result' && msg.is_error && refusalRetry?.message;
416
+ // Claude reports `error_during_execution` while reacting to our
417
+ // teardown signal. Once cezar has signalled the child, that frame
418
+ // describes the intentional stop rather than an agent failure.
419
+ // Normalize only this precise wire shape so genuine result errors
420
+ // (authentication, limits, malformed sessions) stay authoritative.
421
+ const mappedMessage = normalizeIntentionalTeardownResult(originalRefusal ? { ...msg, result: originalRefusal } : msg, terminatedByCezar);
422
+ emitUi((state) => mapClaudeMessage(mappedMessage, state));
423
+ let delta = 0;
424
+ try {
425
+ delta = handleClaudeMessage(mappedMessage, { toolCalls, textChunks, onEvent });
495
426
  }
496
427
  catch (err) {
497
- // Timeout teardown can close stdout. Any other live-child read failure
498
- // must stop the agent before result releases its execution capacity.
499
- if (!timedOut && !hasExited()) {
500
- outputFailure = { error: err };
501
- interrupt();
502
- }
428
+ const message = err instanceof Error ? err.message : String(err);
429
+ onEvent?.({ type: 'note', message: `claude: skipped malformed event (${msg.type ?? 'unknown'}): ${message}` });
430
+ return false;
503
431
  }
504
- finally {
505
- if (deadline)
506
- clearTimeout(deadline);
507
- if (autoEndTimer)
508
- clearTimeout(autoEndTimer);
509
- if (refusalRetry && stdinOpen && !terminatedByCezar && !timedOut) {
510
- onEvent?.({ type: 'error', message: refusalRetry.message });
511
- }
512
- stdinOpen = false;
513
- cancelRefusalRetry();
432
+ if (delta > 0) {
433
+ sawUsage = true;
434
+ tokensUsed += delta;
435
+ onEvent?.({ type: 'token-usage', tokensUsed });
514
436
  }
515
- await cleanupAfterEof();
516
- const exitCode = await waitForExit(child);
517
- // Draining/destroying stdout is not process exit. Keep timeout escalation
518
- // armed until the child has actually settled.
437
+ return true;
438
+ };
439
+ // ---- output settlement ---------------------------------------------------
440
+ const settleResultInputs = (msg) => {
441
+ // The named lines are exact; `queued_turn_count: 0` is only a fallback, because a
442
+ // line still in the pipe when the CLI computed this result is not covered by it.
443
+ const named = Array.isArray(msg.user_message_uuids) ? msg.user_message_uuids.map(String) : null;
444
+ const settled = named ?? (msg.queued_turn_count === 0 ? [...unsettled] : [...unsettled].slice(0, 1));
445
+ // A line this result covered was read even if its replay echo was missed.
446
+ // An error result settles its lines but proves nothing reached the model: they
447
+ // stay pending, so a closing session returns them to the queue (#505 review).
448
+ // Fallback settlement must not clear humanUnsettled: a line may still be in the
449
+ // pipe, and only a named UUID or a replay echo proves the model read it (#486).
450
+ const covered = settled.flatMap(id => {
451
+ unsettled.delete(id);
452
+ sentLines.delete(id);
453
+ if (named)
454
+ humanUnsettled.delete(id);
455
+ return msg.is_error === true ? [] : submissions.consume(id);
456
+ });
457
+ if (covered.length)
458
+ opts.onAgentInputConsumed?.(covered);
459
+ };
460
+ // Drain later human input only after a successful logical turn.
461
+ // Failed turns retain the hold until the workflow tears down.
462
+ const drainDeferredHumanInput = () => {
463
+ for (const input of deferredHuman.splice(0)) {
464
+ humanUnsettled.delete(input.id);
465
+ sendMessage(input.content, undefined, [], true);
466
+ }
467
+ opts.onAgentInputReady?.();
468
+ };
469
+ const settleResult = (msg, identity) => {
470
+ if (msg.is_error !== true && msg.subtype === 'success' && costWeightedTokens(msg.usage) > 0)
471
+ successfulIdentity = identity;
472
+ const wasRetrying = refusalRetry !== undefined;
473
+ cancelRefusalRetry();
474
+ if (typeof msg.total_cost_usd === 'number' && Number.isFinite(msg.total_cost_usd) && msg.total_cost_usd >= 0) {
475
+ onEvent?.({ type: 'cost', usd: msg.total_cost_usd });
476
+ }
477
+ pendingMarkerAsk = parseAskMarker(textChunks.slice(turnTextStart).join('\n')) !== null;
478
+ settleResultInputs(msg);
479
+ // A result is not idle if human stdin messages already queued later turns.
480
+ agentInputReady = unsettled.size === 0;
481
+ // A line written after this turn's last model call runs as the CLI's next
482
+ // queued turn; its replay/result reports consumption then (#505). Announce
483
+ // that turn when its first frame arrives, never speculatively: a line the
484
+ // CLI never runs must not look like activity. Decided before the turn-end
485
+ // callback, which may itself submit (and announce) the next prompt.
486
+ queuedTurnPending = unsettled.size > 0;
487
+ // Remaining inputs belong to the next turn. Clear the completed
488
+ // turn's work before any queued frame (including system activity)
489
+ // arrives; resetting at its first assistant frame would erase work.
490
+ if (queuedTurnPending)
491
+ attemptDidWork = false;
492
+ onEvent?.({ type: 'turn-end' });
493
+ if (wasRetrying && msg.is_error !== true && stdinOpen)
494
+ drainDeferredHumanInput();
495
+ scheduleAutoEnd();
496
+ };
497
+ const handleStreamLine = (line) => {
498
+ const msg = parseStreamLine(line);
499
+ if (msg === undefined)
500
+ return;
501
+ announceQueuedTurn(msg);
502
+ if (consumeReplay(msg))
503
+ return;
504
+ opts.onActivity?.();
505
+ const identity = observeFrame(msg);
506
+ if (scheduleRefusalRetry(msg, identity))
507
+ return;
508
+ if (!deliverFrame(msg))
509
+ return;
510
+ if (msg.type === 'result')
511
+ settleResult(msg, identity);
512
+ };
513
+ // ---- process cleanup -----------------------------------------------------
514
+ const closeOutput = () => {
515
+ if (deadline)
516
+ clearTimeout(deadline);
517
+ if (autoEndTimer)
518
+ clearTimeout(autoEndTimer);
519
+ if (refusalRetry && stdinOpen && !terminatedByCezar && !timedOut) {
520
+ onEvent?.({ type: 'error', message: refusalRetry.message });
521
+ }
522
+ stdinOpen = false;
523
+ cancelRefusalRetry();
524
+ };
525
+ // Draining/destroying stdout is not process exit. Keep timeout escalation
526
+ // armed until the child has actually settled.
527
+ const clearExitTimers = () => {
519
528
  if (killTimer)
520
529
  clearTimeout(killTimer);
521
530
  if (eofTermTimer)
522
531
  clearTimeout(eofTermTimer);
523
532
  if (eofKillTimer)
524
533
  clearTimeout(eofKillTimer);
525
- if (outputFailure)
526
- throw outputFailure.error;
527
- if (spawnFailed)
528
- throw spawnFailed;
534
+ };
535
+ /** An exit cezar did not cause: an outside signal or a non-zero code fails the run. */
536
+ const failAbnormalExit = (exitCode) => {
537
+ if (exitCode === null && child.signalCode !== null) {
538
+ const message = `claude CLI was killed by signal ${child.signalCode}`;
539
+ onEvent?.({ type: 'error', message });
540
+ throw new Error(message);
541
+ }
542
+ if (exitCode !== 0 && exitCode !== null) {
543
+ const stderr = stderrChunks.join('');
544
+ if (stderr.trim())
545
+ onEvent?.({ type: 'note', message: `claude CLI stderr:\n${stderr}` });
546
+ const summary = summarizeRunnerStderr(stderr);
547
+ const detail = summary ? ` — ${summary}` : '';
548
+ const msg = `claude CLI exited with code ${exitCode}${detail}`;
549
+ onEvent?.({ type: 'error', message: msg });
550
+ throw new Error(msg);
551
+ }
552
+ };
553
+ const settleExit = (exitCode) => {
529
554
  const text = textChunks.join('\n').trim();
530
555
  if (timedOut) {
531
556
  const mins = Math.round((limitMs / 60_000) * 10) / 10;
@@ -544,26 +569,41 @@ export class ClaudeCliRunner {
544
569
  onEvent?.({ type: 'done' });
545
570
  return { text, toolCalls, tokensUsed, sessionId: spec.sessionId };
546
571
  }
547
- if (exitCode === null && child.signalCode !== null) {
548
- const message = `claude CLI was killed by signal ${child.signalCode}`;
549
- onEvent?.({ type: 'error', message });
550
- throw new Error(message);
551
- }
552
- if (exitCode !== 0 && exitCode !== null) {
553
- const stderr = stderrChunks.join('');
554
- if (stderr.trim())
555
- onEvent?.({ type: 'note', message: `claude CLI stderr:\n${stderr}` });
556
- const summary = summarizeRunnerStderr(stderr);
557
- const detail = summary ? ` — ${summary}` : '';
558
- const msg = `claude CLI exited with code ${exitCode}${detail}`;
559
- onEvent?.({ type: 'error', message: msg });
560
- throw new Error(msg);
561
- }
572
+ failAbnormalExit(exitCode);
562
573
  if (!sawUsage) {
563
574
  onEvent?.({ type: 'note', message: 'token usage not reported by claude CLI' });
564
575
  }
565
576
  onEvent?.({ type: 'done' });
566
577
  return { text, toolCalls, tokensUsed, sessionId: spec.sessionId };
578
+ };
579
+ const result = (async () => {
580
+ let outputFailure;
581
+ try {
582
+ for await (const line of readNdjson(child.stdout)) {
583
+ if (timedOut)
584
+ break;
585
+ handleStreamLine(line);
586
+ }
587
+ }
588
+ catch (err) {
589
+ // Timeout teardown can close stdout. Any other live-child read failure
590
+ // must stop the agent before result releases its execution capacity.
591
+ if (!timedOut && !hasExited()) {
592
+ outputFailure = { error: err };
593
+ interrupt();
594
+ }
595
+ }
596
+ finally {
597
+ closeOutput();
598
+ }
599
+ await cleanupAfterEof();
600
+ const exitCode = await waitForExit(child);
601
+ clearExitTimers();
602
+ if (outputFailure)
603
+ throw outputFailure.error;
604
+ if (spawnFailed)
605
+ throw spawnFailed;
606
+ return settleExit(exitCode);
567
607
  })();
568
608
  const session = {
569
609
  result,
@@ -770,50 +810,6 @@ function mockClaudePath() {
770
810
  // here = <pkg>/dist/core (built) or <pkg>/src/core (tsx dev).
771
811
  return resolvePath(here, '..', '..', 'scripts', 'mock-claude.mjs');
772
812
  }
773
- /** Fail closed on absent/partial/invalid usage; include cache and nested counters. */
774
- function zeroClaudeUsage(usage) {
775
- if (!usage || typeof usage !== 'object' || Array.isArray(usage))
776
- return false;
777
- const record = usage;
778
- if (record.input_tokens !== 0 || record.output_tokens !== 0)
779
- return false;
780
- const zero = (value) => typeof value === 'number' ? value === 0
781
- : value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(zero);
782
- return Object.entries(record).every(([key, value]) =>
783
- // Claude includes this non-accounting metadata in some usage envelopes.
784
- (key === 'service_tier' && typeof value === 'string') || zero(value));
785
- }
786
- /** Per-model accounting must agree with the aggregate before replay is safe. */
787
- function zeroClaudeModelUsage(usage) {
788
- if (usage === undefined)
789
- return true;
790
- if (!usage || typeof usage !== 'object' || Array.isArray(usage))
791
- return false;
792
- return Object.values(usage).every(model => {
793
- if (!model || typeof model !== 'object' || Array.isArray(model))
794
- return false;
795
- const record = model;
796
- if (record.inputTokens !== 0 || record.outputTokens !== 0)
797
- return false;
798
- return Object.entries(record).every(([key, value]) => key === 'contextWindow' || key === 'maxOutputTokens'
799
- ? typeof value === 'number' && Number.isFinite(value) && value >= 0
800
- : value === 0);
801
- });
802
- }
803
- function selectedModelRefusal(text) {
804
- return typeof text === 'string'
805
- ? /^There's an issue with the selected model \(([^()]+)\)\. It may not exist or you may not have access to it\. Run --model to pick a different model\.$/.exec(text.trim())?.[1]
806
- : undefined;
807
- }
808
- function normalizeIntentionalTeardownResult(msg, terminatedByCezar) {
809
- if (terminatedByCezar
810
- && msg.type === 'result'
811
- && msg.is_error === true
812
- && msg.subtype === 'error_during_execution') {
813
- return { ...msg, subtype: 'success', is_error: false };
814
- }
815
- return msg;
816
- }
817
813
  function handleClaudeMessage(msg, ctx) {
818
814
  if (msg.type === 'assistant' && msg.message?.content) {
819
815
  for (const block of msg.message.content) {