@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.
- package/dist/core/claude-cli-runner.js +260 -264
- package/dist/core/claude-cli-runner.js.map +1 -1
- package/dist/core/claude-stream.d.ts +31 -0
- package/dist/core/claude-stream.js +68 -0
- package/dist/core/claude-stream.js.map +1 -0
- package/dist/delegation/transport.d.ts +66 -66
- package/dist/server/live-routes.d.ts +6 -6
- package/dist/server/server.d.ts +1225 -1225
- package/dist/voice/routes.d.ts +19 -19
- package/package.json +3 -3
|
@@ -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
|
-
|
|
314
|
-
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
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
|
-
|
|
498
|
-
|
|
499
|
-
|
|
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
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
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
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
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
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
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
|
-
|
|
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) {
|