@wjarka/cezarion 0.17.0-pr2017.3060 → 0.17.0-pr2017.3065

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.
@@ -1,7 +1,8 @@
1
- import { parseEffort } from '../contract/index.js';
2
- import { fileURLToPath } from 'node:url';
3
1
  import { dirname, resolve as resolvePath } from 'node:path';
4
- import { parseAskMarker } from './ask.js';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { parseEffort } from '../contract/index.js';
4
+ import { isRecord, parseRpcLine, piMessageText, ompRpcError as rpcError, string, toPiPrompt, truncate, waitForExit } from './pi-rpc-wire.js';
5
+ import { armEndWatchdog, emitPiToolResult, PiRpcInput, PiTextBlocks, recordPiToolCall } from './pi-rpc-turn.js';
5
6
  import { isSignalTerminationExit } from './agent-runner.js';
6
7
  import { ompRequestedTools } from './runner-tool-grants.js';
7
8
  import { signalSession, spawnSessionLeader } from './session-process.js';
@@ -10,9 +11,7 @@ import { cezarToolNames } from '../ci-wait/tools.js';
10
11
  import { readNdjson } from './ndjson.js';
11
12
  import { createOmpUiState, mapOmpRpcMessage, ompFlushProviderError, ompMessageUsage, ompProviderErrorMessage, ompTurnStarted, } from './omp-ui-mapper.js';
12
13
  import { summarizeRunnerStderr } from './runner-stderr.js';
13
- import { V1TextCoalescer } from './v1-text-coalescer.js';
14
- import { InputSubmissions } from './input-submissions.js';
15
- import { boundOutputDrainAfterExit, AUTO_END_DELAY_MS, DEFAULT_RUN_TIMEOUT_MS, KILL_GRACE_MS } from './runner-runtime.js';
14
+ import { boundOutputDrainAfterExit, DEFAULT_RUN_TIMEOUT_MS, KILL_GRACE_MS } from './runner-runtime.js';
16
15
  /**
17
16
  * OMP's built-in tool names at the pinned version (`src/tools/builtin-names.ts`, oh-my-pi
18
17
  * v18.4.11; the real binary lists the same 30 in its `--tools` rejection). `--tools` is an
@@ -262,33 +261,12 @@ export class OmpRunner {
262
261
  let open = true;
263
262
  let timedOut = false;
264
263
  let terminatedByCezar = false;
265
- let autoEndTimer;
266
- let killTimer;
264
+ let killWatchdog;
267
265
  let interruptKillTimer;
268
266
  let ompUi = createOmpUiState();
269
267
  const textChunks = [];
270
- /** One v1 `text` per complete block, never per token (pi-runner.ts, #902 / #2). */
271
- const textCoalescer = new V1TextCoalescer((text) => {
272
- textChunks.push(text);
273
- onEvent?.({ type: 'text', text });
274
- });
275
- /** `contentIndex` restarts at 0 on every assistant message (as Pi's); see pi-runner.ts. */
276
- let textBlockSeq = 0;
277
- const openTextBlockKeys = new Map();
278
- const textBlockKey = (contentIndex) => {
279
- if (typeof contentIndex !== 'number')
280
- return undefined;
281
- let key = openTextBlockKeys.get(contentIndex);
282
- if (!key) {
283
- key = `omp-text-${++textBlockSeq}`;
284
- openTextBlockKeys.set(contentIndex, key);
285
- }
286
- return key;
287
- };
288
- const flushText = () => {
289
- textCoalescer.flush();
290
- openTextBlockKeys.clear();
291
- };
268
+ const textBlocks = new PiTextBlocks('omp-text', textChunks, onEvent);
269
+ const flushText = () => textBlocks.flush();
292
270
  const toolCalls = [];
293
271
  let sessionId = spec.sessionId;
294
272
  let startupStateChecked = false;
@@ -339,7 +317,7 @@ export class OmpRunner {
339
317
  inputError = new Error(`omp input stream failed: ${error.message}`);
340
318
  open = false;
341
319
  outbox.length = 0;
342
- rejectAgentAck(inputError);
320
+ rpcInput.rejectAgentAck(inputError);
343
321
  onEvent?.({ type: 'error', message: inputError.message });
344
322
  emitUiEvent({ type: 'session.error', message: inputError.message, fatal: true });
345
323
  // The output loop owns bounded process cleanup. Retain the error even if the child
@@ -359,12 +337,24 @@ export class OmpRunner {
359
337
  }
360
338
  return writeNow(command);
361
339
  };
362
- let agentInputReady = false;
363
- let promptSerial = 0;
364
340
  let humanSerial = 0;
365
341
  // Every prompt carries an id: a local completion or failure ends the turn only when it
366
342
  // answers the prompt that opened it, never a steer (the mapper gates on this id).
367
343
  const humanAcks = new Set();
344
+ // Agent input readiness, the pending agent receipt, carried input, the turn-end step and
345
+ // auto-end live in the shared Pi-family core.
346
+ const rpcInput = new PiRpcInput({
347
+ cli: 'omp',
348
+ opts,
349
+ onEvent,
350
+ textChunks,
351
+ isOpen: () => open,
352
+ turnId: () => ompUi.turnId,
353
+ humanAcksPending: () => humanAcks.size > 0,
354
+ end: () => end(),
355
+ flushText,
356
+ emitLatchedProviderError,
357
+ });
368
358
  // Each human prompt stays held from its write until a normalized turn has it, because an
369
359
  // ack is not a turn boundary (hearsay-tools/cezarion#1112). Exits: its user message_start,
370
360
  // its ack while the turn it opened is still open, the first turn.started after its ack,
@@ -379,66 +369,15 @@ export class OmpRunner {
379
369
  if (held.acked)
380
370
  humanHeld.delete(id);
381
371
  }
382
- let agentAck;
383
- const rejectAgentAck = (error = new Error('omp closed before prompt acknowledgement')) => {
384
- const pending = agentAck;
385
- agentAck = undefined;
386
- pending?.reject(error);
387
- };
388
- const scheduleAutoEnd = () => {
389
- if (!opts.autoEndAfterFirstTurn || !open || autoEndTimer || agentAck || humanAcks.size)
390
- return;
391
- autoEndTimer = setTimeout(() => {
392
- autoEndTimer = undefined;
393
- if (opts.shouldAutoEnd?.() !== false)
394
- end();
395
- }, AUTO_END_DELAY_MS);
396
- autoEndTimer.unref?.();
397
- };
398
- // Same readiness rules as pi-runner.ts (#505): a refusal caused only by an outstanding
399
- // acknowledgement gets one readiness hint when it lands, even mid-turn.
400
- let refusedForAck = false;
401
- const readyAfterAck = () => {
402
- if (open && agentInputReady && !ompUi.turnId && !agentAck && !humanAcks.size) {
403
- refusedForAck = false;
404
- opts.onAgentInputReady?.();
405
- scheduleAutoEnd();
406
- }
407
- else if (refusedForAck && open && !agentAck && !humanAcks.size && !pendingMarkerAsk) {
408
- refusedForAck = false;
409
- opts.onAgentInputReady?.();
410
- }
411
- else if (open && !ompUi.turnId && !agentAck && !humanAcks.size && !pendingMarkerAsk) {
412
- // #486: a human ack drained with no turn open — re-settle the idle boundary.
413
- refusedForAck = false;
414
- opts.onAgentInputReady?.();
415
- }
416
- };
417
- let pendingMarkerAsk = false;
418
- let turnTextStart = 0;
419
- // Accepted agent prompts not yet seen as a user message_start (#505).
420
- const submissions = new InputSubmissions();
421
- // Submissions already queued when a turn began: that turn reads them. OMP reports an
422
- // admitted steer at the next terminal agent_end (rpc-prompt-results.ts), never drops it.
423
- let carried = new Set();
424
- const acked = new Set();
425
- let turnFailed = false;
426
372
  const sendMessage = (content, requestId, inputIds = []) => {
427
373
  if (!open)
428
374
  return false;
429
375
  // A steer joins the running turn; only an idle prompt opens one (#505).
430
376
  const opensTurn = !ompUi.turnId;
431
- agentInputReady = false;
432
- if (opensTurn) {
433
- pendingMarkerAsk = false;
434
- turnTextStart = textChunks.length;
435
- }
436
- const { message, images } = toOmpPrompt(content);
377
+ rpcInput.beginPrompt(opensTurn);
378
+ const { message, images } = toPiPrompt(content);
437
379
  const id = requestId ?? `cezar-prompt-${++humanSerial}`;
438
- if (autoEndTimer) {
439
- clearTimeout(autoEndTimer);
440
- autoEndTimer = undefined;
441
- }
380
+ rpcInput.cancelAutoEnd();
442
381
  if (!write({
443
382
  type: 'prompt',
444
383
  id,
@@ -449,7 +388,7 @@ export class OmpRunner {
449
388
  return false;
450
389
  }
451
390
  if (requestId)
452
- submissions.accept(requestId, inputIds, message);
391
+ rpcInput.submissions.accept(requestId, inputIds, message);
453
392
  if (!ompUi.turnId) {
454
393
  const mapped = ompTurnStarted(ompUi, id);
455
394
  ompUi = mapped.state;
@@ -468,23 +407,10 @@ export class OmpRunner {
468
407
  return;
469
408
  open = false;
470
409
  closedByCaller = true;
471
- rejectAgentAck();
410
+ rpcInput.rejectAgentAck();
472
411
  flushOutbox();
473
412
  child.stdin.end();
474
- killTimer = setTimeout(() => {
475
- if (child.exitCode !== null || child.signalCode !== null)
476
- return;
477
- terminatedByCezar = true;
478
- signalSession(child, 'SIGTERM');
479
- // An OMP that ignores SIGTERM would otherwise hold `result` open forever: the deadline's
480
- // interrupt() is a no-op once `open` is false.
481
- killTimer = setTimeout(() => {
482
- if (child.exitCode === null && child.signalCode === null)
483
- signalSession(child, 'SIGKILL');
484
- }, killGraceMs);
485
- killTimer.unref?.();
486
- }, killGraceMs);
487
- killTimer.unref?.();
413
+ killWatchdog = armEndWatchdog(() => child, killGraceMs, () => { terminatedByCezar = true; });
488
414
  };
489
415
  const interrupt = () => {
490
416
  if (!open)
@@ -493,7 +419,7 @@ export class OmpRunner {
493
419
  writeNow({ type: 'abort' });
494
420
  open = false;
495
421
  closedByCaller = true;
496
- rejectAgentAck();
422
+ rpcInput.rejectAgentAck();
497
423
  terminatedByCezar = true;
498
424
  signalSession(child, 'SIGTERM');
499
425
  interruptKillTimer = setTimeout(() => {
@@ -537,264 +463,216 @@ export class OmpRunner {
537
463
  // A refusal is only retried before any frame, once per class, and never after the caller or a
538
464
  // deadline ended the session; a spawn with nothing to drop has `uiHold` null.
539
465
  const retryPossible = () => !sawFrame && !(toolsRetried && flagsRetried) && !timedOut && !terminatedByCezar && !closedByCaller && uiHold !== null;
540
- const result = (async function runOmp() {
541
- try {
542
- for await (const line of readNdjson(child.stdout)) {
543
- if (!sawFrame) {
544
- sawFrame = true;
545
- releaseUiHold();
546
- flushOutbox();
547
- }
548
- let value;
549
- try {
550
- value = JSON.parse(line);
551
- }
552
- catch {
553
- onEvent?.({ type: 'note', message: `omp: skipped unparseable RPC line: ${truncate(line)}` });
554
- continue;
555
- }
556
- opts.onActivity?.();
557
- // Flush before message/tool/turn boundaries so v2 events never overtake a pending
558
- // block; never on prompt acks, which can land between text_deltas (pi-runner.ts).
559
- if (isRecord(value) &&
560
- (value.type === 'tool_execution_start' ||
561
- value.type === 'message_end' ||
562
- value.type === 'session_settled' ||
563
- value.type === 'prompt_result' ||
564
- value.type === 'turn_end' ||
565
- value.type === 'agent_end')) {
566
- flushText();
567
- }
568
- // A boundary only ends a turn that is open: OMP never settles an idle session, and a
569
- // second boundary for the same prompt must not end the next one.
570
- const turnOpen = ompUi.turnId !== null;
571
- emitUi(value);
572
- const usageReport = ompMessageUsage(value);
573
- if (usageReport) {
574
- const { input, output, cacheRead = 0, cacheWrite = 0 } = usageReport.usage;
575
- // v1 keeps its historical per-message weighted token convention; v2 exposes
576
- // the raw components of these same parent and child reports.
577
- tokensUsed += Math.round(input + output + cacheRead * 0.1 + cacheWrite * 1.25);
578
- onEvent?.({ type: 'token-usage', tokensUsed });
579
- if (usageReport.costUsd !== undefined)
580
- onEvent?.({ type: 'cost', usd: usageReport.costUsd });
581
- }
582
- // The mapper closed its turn on this frame: v1 ends the turn with it.
583
- const endsTurn = turnOpen && ompUi.turnId === null;
584
- if (!isRecord(value))
585
- continue;
586
- if (value.type === 'prompt_result')
587
- humanHeld.delete(string(value.id) ?? '');
588
- if (value.type === 'response' && value.command === 'get_state' && value.success === true && isRecord(value.data)) {
589
- const discovered = string(value.data.sessionId);
590
- if (discovered && discovered !== sessionId) {
591
- sessionId = discovered;
592
- onEvent?.({ type: 'session', sessionId: discovered });
593
- }
594
- // OMP v18.6.1 still has no fresh persistent-session flag. Its autoResume
595
- // setting can restore history without --resume (hearsay-tools/cezarion#832).
596
- // Only the startup query is evidence: later reads include our own messages.
597
- if (value.id === 'cezar-state' && !startupStateChecked) {
598
- startupStateChecked = true;
599
- const count = value.data.messageCount;
600
- if (!spec.resume && typeof count === 'number' && count > 0) {
601
- const message = `omp: unexpectedly restored a session with ${count} messages for a fresh step. Previous conversation context is active; check OMP's autoResume setting.`;
602
- onEvent?.({ type: 'note', message });
603
- emitUiEvent({ type: 'session.error', message, fatal: false });
604
- }
605
- }
606
- }
607
- else if (value.type === 'response' && string(value.command)?.startsWith('set_')) {
608
- if (value.success !== true) {
609
- onEvent?.({ type: 'note', message: `omp: ${string(value.command)} failed: ${rpcError(value)}` });
610
- }
611
- }
612
- else if (value.type === 'response' && value.command === 'prompt') {
613
- if (value.success === false) {
614
- // The turn-opening prompt rejected before admission gets no `prompt_result`, so it
615
- // is the turn's error here (Ruling 10). A failure after admission is reported by the
616
- // `prompt_result` that follows it (rpc-prompt-results.ts `fail`), and a steer's
617
- // failure leaves the turn running: both are only a note.
618
- const message = `omp: prompt failed: ${rpcError(value)}`;
619
- if (endsTurn) {
620
- onEvent?.({ type: 'error', message });
621
- turnFailed = true;
622
- }
623
- else {
624
- onEvent?.({ type: 'note', message });
625
- }
626
- }
627
- const pending = agentAck;
628
- const id = string(value.id);
629
- if (pending && id === pending.id) {
630
- agentAck = undefined;
631
- if (value.success === true) {
632
- acked.add(pending.id);
633
- pending.resolve();
634
- }
635
- else
636
- pending.reject(new Error(rpcError(value)));
637
- }
638
- else if (id) {
639
- // `agentInvoked: false` is a prompt OMP finished itself: no agent run follows.
640
- const runsAgent = !(isRecord(value.data) && value.data.agentInvoked === false);
641
- const held = humanHeld.get(id);
642
- if (humanAcks.delete(id) && held) {
643
- if (value.success === true && runsAgent && (!held.turnId || held.turnId !== ompUi.turnId))
644
- held.acked = true;
645
- else
646
- humanHeld.delete(id);
647
- }
648
- }
649
- readyAfterAck();
650
- }
651
- else if (value.type === 'response' && value.success === false) {
652
- onEvent?.({ type: 'error', message: rpcError(value) });
653
- }
654
- else if (value.type === 'prompt_result' && value.agentInvoked === false && value.status === 'error') {
655
- // The prompt failed before the agent ran: no settle follows, so the turn ends here
656
- // when it opened the turn. A steer failing mid-turn leaves it running.
657
- const error = isRecord(value.error) ? value.error : {};
658
- const message = ompProviderErrorMessage({ provider: error.provider, model: error.model, errorMessage: error.message });
659
- if (endsTurn) {
660
- onEvent?.({ type: 'error', message });
661
- turnFailed = true;
662
- }
663
- else {
664
- // v2 reports it as a session error whether or not a turn is open.
665
- onEvent?.({ type: 'note', message });
666
- }
667
- }
668
- else if (value.type === 'message_update' && isRecord(value.assistantMessageEvent)) {
669
- const update = value.assistantMessageEvent;
670
- const contentKey = textBlockKey(update.contentIndex);
671
- if (update.type === 'text_delta' && typeof update.delta === 'string') {
672
- textCoalescer.append(contentKey, update.delta);
673
- }
674
- else if (update.type === 'text_end') {
675
- const snapshot = typeof update.content === 'string' ? update.content : undefined;
676
- textCoalescer.complete(contentKey, snapshot);
677
- if (typeof update.contentIndex === 'number')
678
- openTextBlockKeys.delete(update.contentIndex);
679
- }
680
- }
681
- else if (value.type === 'message_end' && isRecord(value.message) && value.message.role === 'assistant') {
682
- flushText();
683
- // Latched until the turn ends, cleared by a later success: OMP retries past
684
- // provider flakes and a recovered retry must stay silent (#256, #316).
685
- if (string(value.message.stopReason) === 'error') {
686
- turnFailed = true;
687
- latchedProviderError = ompProviderErrorMessage(value.message);
688
- }
689
- else {
690
- latchedProviderError = undefined;
691
- }
692
- }
693
- else if (value.type === 'agent_start') {
694
- // Only a prompt OMP acknowledged before this agent_start can be in its turn (#505).
695
- carried = new Set(submissions.pendingIds().filter(id => acked.has(id)));
696
- turnFailed = false;
697
- }
698
- else if (value.type === 'message_start' && isRecord(value.message) && value.message.role === 'user') {
699
- // The model received this prompt now (#505).
700
- const text = ompMessageText(value.message);
701
- const ids = submissions.consumeOldestByText(text);
702
- if (ids.length)
703
- opts.onAgentInputConsumed?.(ids);
704
- else
705
- for (const [id, held] of humanHeld) {
706
- if (held.text !== text)
707
- continue;
708
- // Read with no normalized turn open: held until that turn.started (as pi-runner.ts).
709
- if (ompUi.turnId)
710
- humanHeld.delete(id);
711
- else
712
- held.acked = true;
713
- break;
714
- }
715
- }
716
- else if (value.type === 'tool_execution_start') {
717
- flushText();
718
- const id = string(value.toolCallId);
719
- const name = string(value.toolName);
720
- if (id && name) {
721
- toolCalls.push({ id, name, input: value.args });
722
- onEvent?.({ type: 'tool-call', id, tool: name, input: value.args });
723
- }
724
- }
725
- else if (value.type === 'tool_execution_end') {
726
- const id = string(value.toolCallId);
727
- if (id) {
728
- onEvent?.({
729
- type: 'tool-result',
730
- toolCallId: id,
731
- result: contentText(isRecord(value.result) ? value.result.content : undefined) ?? '',
732
- isError: value.isError === true,
733
- });
734
- emitImages(isRecord(value.result) ? value.result.content : undefined, onEvent);
735
- }
736
- }
737
- else if (value.type === 'extension_error') {
738
- onEvent?.({ type: 'note', message: string(value.error) ?? string(value.message) ?? 'omp extension error' });
739
- }
740
- else if (value.type === 'notice') {
741
- const message = string(value.message);
742
- if (message)
743
- onEvent?.({ type: 'note', message: `omp: ${message}` });
744
- }
745
- if (endsTurn) {
746
- flushText();
747
- emitLatchedProviderError();
748
- pendingMarkerAsk = parseAskMarker(textChunks.slice(turnTextStart).join('\n')) !== null;
749
- agentInputReady = true;
750
- // Input queued before this turn began was processed by it, even without a user
751
- // message_start (#505) — unless the turn failed and may never have reached the model.
752
- const read = turnFailed ? [] : [...carried].flatMap(id => submissions.consume(id));
753
- turnFailed = false;
754
- carried = new Set();
755
- if (read.length)
756
- opts.onAgentInputConsumed?.(read);
757
- onEvent?.({ type: 'turn-end' });
758
- scheduleAutoEnd();
759
- }
760
- }
466
+ const releaseFirstFrame = () => {
467
+ if (sawFrame)
468
+ return;
469
+ sawFrame = true;
470
+ releaseUiHold();
471
+ flushOutbox();
472
+ };
473
+ const reportUsage = (value) => {
474
+ const usageReport = ompMessageUsage(value);
475
+ if (!usageReport)
476
+ return;
477
+ const { input, output, cacheRead = 0, cacheWrite = 0 } = usageReport.usage;
478
+ // v1 keeps its historical per-message weighted token convention; v2 exposes
479
+ // the raw components of these same parent and child reports.
480
+ tokensUsed += Math.round(input + output + cacheRead * 0.1 + cacheWrite * 1.25);
481
+ onEvent?.({ type: 'token-usage', tokensUsed });
482
+ if (usageReport.costUsd !== undefined)
483
+ onEvent?.({ type: 'cost', usd: usageReport.costUsd });
484
+ };
485
+ const adoptState = (value, data) => {
486
+ const discovered = string(data.sessionId);
487
+ if (discovered && discovered !== sessionId) {
488
+ sessionId = discovered;
489
+ onEvent?.({ type: 'session', sessionId: discovered });
761
490
  }
762
- catch (error) {
763
- if (child.exitCode === null && child.signalCode === null) {
764
- // A live child whose stream failed is not a refusal: no respawn follows, so nothing
765
- // may still be accepted into the outbox.
766
- open = false;
767
- // The run is reported failed, so the CLI must not keep running tools in the worktree:
768
- // SIGTERM now, SIGKILL after the grace period (a timer `finally` does not clear).
769
- terminatedByCezar = true;
770
- signalSession(child, 'SIGTERM');
771
- const reap = setTimeout(() => {
772
- if (child.exitCode === null && child.signalCode === null)
773
- signalSession(child, 'SIGKILL');
774
- }, killGraceMs);
775
- reap.unref?.();
776
- throw error;
491
+ // OMP v18.6.1 still has no fresh persistent-session flag. Its autoResume
492
+ // setting can restore history without --resume (hearsay-tools/cezarion#832).
493
+ // Only the startup query is evidence: later reads include our own messages.
494
+ if (value.id !== 'cezar-state' || startupStateChecked)
495
+ return;
496
+ startupStateChecked = true;
497
+ const count = data.messageCount;
498
+ if (!spec.resume && typeof count === 'number' && count > 0) {
499
+ const message = `omp: unexpectedly restored a session with ${count} messages for a fresh step. Previous conversation context is active; check OMP's autoResume setting.`;
500
+ onEvent?.({ type: 'note', message });
501
+ emitUiEvent({ type: 'session.error', message, fatal: false });
502
+ }
503
+ };
504
+ /** A failure that ends the turn is its error; otherwise the turn keeps running and it is a note. */
505
+ const reportPromptFailure = (message, endsTurn) => {
506
+ if (endsTurn) {
507
+ onEvent?.({ type: 'error', message });
508
+ rpcInput.failTurn();
509
+ }
510
+ else {
511
+ onEvent?.({ type: 'note', message });
512
+ }
513
+ };
514
+ const settleHumanAck = (value, id) => {
515
+ // `agentInvoked: false` is a prompt OMP finished itself: no agent run follows.
516
+ const runsAgent = !(isRecord(value.data) && value.data.agentInvoked === false);
517
+ const held = humanHeld.get(id);
518
+ if (humanAcks.delete(id) && held) {
519
+ if (value.success === true && runsAgent && (!held.turnId || held.turnId !== ompUi.turnId))
520
+ held.acked = true;
521
+ else
522
+ humanHeld.delete(id);
523
+ }
524
+ };
525
+ const settlePromptResponse = (value, endsTurn) => {
526
+ // The turn-opening prompt rejected before admission gets no `prompt_result`, so it
527
+ // is the turn's error here (Ruling 10). A failure after admission is reported by the
528
+ // `prompt_result` that follows it (rpc-prompt-results.ts `fail`), and a steer's
529
+ // failure leaves the turn running: both are only a note.
530
+ if (value.success === false)
531
+ reportPromptFailure(`omp: prompt failed: ${rpcError(value)}`, endsTurn);
532
+ const id = string(value.id);
533
+ const pending = rpcInput.takeAgentAck(id);
534
+ if (pending) {
535
+ if (value.success === true)
536
+ rpcInput.acceptAgentAck(pending);
537
+ else
538
+ pending.reject(new Error(rpcError(value)));
539
+ }
540
+ else if (id) {
541
+ settleHumanAck(value, id);
542
+ }
543
+ rpcInput.readyAfterAck();
544
+ };
545
+ // A failed get_state has no branch of its own: it is reported like any other failed command.
546
+ const handleResponse = (value, endsTurn) => {
547
+ if (value.command === 'get_state' && value.success === true && isRecord(value.data)) {
548
+ adoptState(value, value.data);
549
+ }
550
+ else if (string(value.command)?.startsWith('set_')) {
551
+ if (value.success !== true) {
552
+ onEvent?.({ type: 'note', message: `omp: ${string(value.command)} failed: ${rpcError(value)}` });
777
553
  }
778
554
  }
779
- finally {
780
- if (deadline)
781
- clearTimeout(deadline);
782
- if (autoEndTimer)
783
- clearTimeout(autoEndTimer);
784
- if (killTimer)
785
- clearTimeout(killTimer);
786
- // A refused spawn may still be respawned: stay open so input accepted meanwhile is kept
787
- // for the new child instead of being refused in the gap.
788
- if (!retryPossible())
789
- open = false;
790
- rejectAgentAck();
555
+ else if (value.command === 'prompt') {
556
+ settlePromptResponse(value, endsTurn);
791
557
  }
558
+ else if (value.success === false) {
559
+ onEvent?.({ type: 'error', message: rpcError(value) });
560
+ }
561
+ };
562
+ /** The prompt failed before the agent ran: no settle follows, so the turn ends here when it
563
+ * opened the turn. A steer failing mid-turn leaves it running; v2 reports it as a session
564
+ * error whether or not a turn is open. Any other prompt_result is reported by the settle. */
565
+ const handlePromptResult = (value, endsTurn) => {
566
+ if (value.agentInvoked !== false || value.status !== 'error')
567
+ return;
568
+ const error = isRecord(value.error) ? value.error : {};
569
+ reportPromptFailure(ompProviderErrorMessage({ provider: error.provider, model: error.model, errorMessage: error.message }), endsTurn);
570
+ };
571
+ const handleAssistantMessageEnd = (value) => {
572
+ if (!isRecord(value.message) || value.message.role !== 'assistant')
573
+ return;
792
574
  flushText();
793
- emitLatchedProviderError();
794
- emitLatchedUiProviderError();
795
- const exitCode = await waitForExit(child);
796
- if (interruptKillTimer)
797
- clearTimeout(interruptKillTimer);
575
+ // Latched until the turn ends, cleared by a later success: OMP retries past
576
+ // provider flakes and a recovered retry must stay silent (#256, #316).
577
+ if (string(value.message.stopReason) === 'error') {
578
+ rpcInput.failTurn();
579
+ latchedProviderError = ompProviderErrorMessage(value.message);
580
+ }
581
+ else {
582
+ latchedProviderError = undefined;
583
+ }
584
+ };
585
+ const handleUserMessageStart = (value) => {
586
+ if (!isRecord(value.message) || value.message.role !== 'user')
587
+ return;
588
+ // The model received this prompt now (hearsay-tools/cezarion#505).
589
+ const text = piMessageText(value.message);
590
+ const ids = rpcInput.submissions.consumeOldestByText(text);
591
+ if (ids.length)
592
+ opts.onAgentInputConsumed?.(ids);
593
+ else
594
+ for (const [id, held] of humanHeld) {
595
+ if (held.text !== text)
596
+ continue;
597
+ // Read with no normalized turn open: held until that turn.started (as pi-runner.ts).
598
+ if (ompUi.turnId)
599
+ humanHeld.delete(id);
600
+ else
601
+ held.acked = true;
602
+ break;
603
+ }
604
+ };
605
+ // Each type has one case. A message its handler's guard refuses ends there, as it did
606
+ // when this was one if/else chain: no later case reads the same type.
607
+ const dispatchNative = (value, endsTurn) => {
608
+ switch (value.type) {
609
+ case 'response':
610
+ handleResponse(value, endsTurn);
611
+ break;
612
+ case 'prompt_result':
613
+ handlePromptResult(value, endsTurn);
614
+ break;
615
+ case 'message_update':
616
+ if (isRecord(value.assistantMessageEvent))
617
+ textBlocks.update(value.assistantMessageEvent);
618
+ break;
619
+ case 'message_end':
620
+ handleAssistantMessageEnd(value);
621
+ break;
622
+ case 'agent_start':
623
+ rpcInput.startTurn();
624
+ break;
625
+ case 'message_start':
626
+ handleUserMessageStart(value);
627
+ break;
628
+ case 'tool_execution_start':
629
+ flushText();
630
+ recordPiToolCall(value, toolCalls, onEvent);
631
+ break;
632
+ case 'tool_execution_end':
633
+ emitPiToolResult(value, onEvent);
634
+ break;
635
+ case 'extension_error':
636
+ onEvent?.({ type: 'note', message: string(value.error) ?? string(value.message) ?? 'omp extension error' });
637
+ break;
638
+ case 'notice': {
639
+ const message = string(value.message);
640
+ if (message)
641
+ onEvent?.({ type: 'note', message: `omp: ${message}` });
642
+ break;
643
+ }
644
+ }
645
+ };
646
+ const handleOutputLine = (line) => {
647
+ releaseFirstFrame();
648
+ const value = parseRpcLine(line);
649
+ if (value === undefined) {
650
+ onEvent?.({ type: 'note', message: `omp: skipped unparseable RPC line: ${truncate(line)}` });
651
+ return;
652
+ }
653
+ opts.onActivity?.();
654
+ // Flush before message/tool/turn boundaries so v2 events never overtake a pending
655
+ // block; never on prompt acks, which can land between text_deltas (pi-runner.ts).
656
+ if (isRecord(value) && OMP_TEXT_BOUNDARY_TYPES.has(value.type))
657
+ flushText();
658
+ // A boundary only ends a turn that is open: OMP never settles an idle session, and a
659
+ // second boundary for the same prompt must not end the next one.
660
+ const turnOpen = ompUi.turnId !== null;
661
+ emitUi(value);
662
+ reportUsage(value);
663
+ // The mapper closed its turn on this frame: v1 ends the turn with it.
664
+ const endsTurn = turnOpen && ompUi.turnId === null;
665
+ if (!isRecord(value))
666
+ return;
667
+ if (value.type === 'prompt_result')
668
+ humanHeld.delete(string(value.id) ?? '');
669
+ dispatchNative(value, endsTurn);
670
+ if (endsTurn)
671
+ rpcInput.settleTurn();
672
+ };
673
+ /** Notes the Ruling 13/20/22 refusal and returns the argv for one respawn, or null when the
674
+ * exit is not a refusal that may still be retried. */
675
+ const retryArgsAfterRefusal = (exitCode) => {
798
676
  // Ruling 13: exit 2 before any frame, naming tools the user's OMP settings disabled. Respawn
799
677
  // once without them: the list only narrows, so this never widens what the step granted.
800
678
  // Ruling 20 widens the same respawn to MCP names OMP did not register (a Claude spelling
@@ -806,47 +684,42 @@ export class OmpRunner {
806
684
  const refusal = canRetry && !droppedDirs && !toolsRetried
807
685
  ? refusedOmpTools(stderr.join(''), ompToolList(spawnArgs))
808
686
  : null;
809
- if (droppedDirs || refusal) {
810
- stderr.length = 0;
811
- if (droppedDirs) {
812
- flagsRetried = true;
813
- omitAddDir = true;
814
- onEvent?.({
815
- type: 'note',
816
- message: `omp: this omp CLI does not accept --add-dir (update OMP); ran without the additional directories: ${droppedDirs.join(', ')}`,
817
- });
818
- }
819
- if (refusal) {
820
- toolsRetried = true;
821
- refusedTools = [...refusal.disabled, ...refusal.mcp];
822
- const dropped = [
823
- ...(refusal.disabled.length > 0 ? [`tools disabled by your OMP settings were dropped: ${refusal.disabled.join(', ')}`] : []),
824
- ...(refusal.mcp.length > 0 ? [`MCP tools OMP has not registered were dropped: ${refusal.mcp.join(', ')}`] : []),
825
- ];
826
- onEvent?.({ type: 'note', message: `omp: ${dropped.join('; ')}` });
827
- }
828
- // Session state (mapper, held v2 events, ack sets) follows what was accepted, not the
829
- // child, and the outbox still holds every command accepted so far: the new child is
830
- // sent exactly those, once, when it speaks.
831
- spawnArgs = buildOmpArgs(spec, refusedTools, { omitAddDir });
832
- child = spawnOmp(spawnArgs);
833
- if (child.pid !== undefined)
834
- opts.onPidChange?.(child.pid);
835
- deadline = armDeadline();
836
- return runOmp();
687
+ if (!droppedDirs && !refusal)
688
+ return null;
689
+ stderr.length = 0;
690
+ if (droppedDirs) {
691
+ flagsRetried = true;
692
+ omitAddDir = true;
693
+ onEvent?.({
694
+ type: 'note',
695
+ message: `omp: this omp CLI does not accept --add-dir (update OMP); ran without the additional directories: ${droppedDirs.join(', ')}`,
696
+ });
837
697
  }
838
- open = false;
839
- releaseUiHold();
840
- if (spawnError)
841
- throw spawnError;
842
- if (inputError)
843
- throw inputError;
844
- if (timedOut) {
845
- const message = `omp CLI timed out after ${Math.round((limitMs / 60_000) * 10) / 10}m and was killed`;
846
- onEvent?.({ type: 'error', message });
847
- onEvent?.({ type: 'done' });
848
- return { text: textChunks.join('\n').trim(), toolCalls, tokensUsed, sessionId };
698
+ if (refusal) {
699
+ toolsRetried = true;
700
+ refusedTools = [...refusal.disabled, ...refusal.mcp];
701
+ const dropped = [
702
+ ...(refusal.disabled.length > 0 ? [`tools disabled by your OMP settings were dropped: ${refusal.disabled.join(', ')}`] : []),
703
+ ...(refusal.mcp.length > 0 ? [`MCP tools OMP has not registered were dropped: ${refusal.mcp.join(', ')}`] : []),
704
+ ];
705
+ onEvent?.({ type: 'note', message: `omp: ${dropped.join('; ')}` });
849
706
  }
707
+ // Session state (mapper, held v2 events, ack sets) follows what was accepted, not the
708
+ // child, and the outbox still holds every command accepted so far: the new child is
709
+ // sent exactly those, once, when it speaks.
710
+ return buildOmpArgs(spec, refusedTools, { omitAddDir });
711
+ };
712
+ const runResult = () => ({ text: textChunks.join('\n').trim(), toolCalls, tokensUsed, sessionId });
713
+ const exitFailure = (exitCode) => {
714
+ const diagnostic = stderr.join('');
715
+ if (diagnostic.trim())
716
+ onEvent?.({ type: 'note', message: `omp CLI stderr:\n${diagnostic}` });
717
+ const detail = ompStderrDetail(diagnostic);
718
+ const message = `omp CLI exited with code ${exitCode}${detail ? ` — ${detail}` : ''}`;
719
+ onEvent?.({ type: 'error', message });
720
+ return new Error(message);
721
+ };
722
+ const reportExit = (exitCode) => {
850
723
  // A signal we sent is teardown, not a second agent failure (#73).
851
724
  if (terminatedByCezar && (isSignalTerminationExit(exitCode) || (exitCode === null && child.signalCode !== null))) {
852
725
  onEvent?.({
@@ -861,45 +734,86 @@ export class OmpRunner {
861
734
  throw new Error(message);
862
735
  }
863
736
  else if (exitCode !== 0 && exitCode !== null) {
864
- const diagnostic = stderr.join('');
865
- if (diagnostic.trim())
866
- onEvent?.({ type: 'note', message: `omp CLI stderr:\n${diagnostic}` });
867
- const detail = ompStderrDetail(diagnostic);
868
- const message = `omp CLI exited with code ${exitCode}${detail ? ` — ${detail}` : ''}`;
737
+ throw exitFailure(exitCode);
738
+ }
739
+ };
740
+ const settleExit = (exitCode) => {
741
+ open = false;
742
+ releaseUiHold();
743
+ if (spawnError)
744
+ throw spawnError;
745
+ if (inputError)
746
+ throw inputError;
747
+ if (timedOut) {
748
+ const message = `omp CLI timed out after ${Math.round((limitMs / 60_000) * 10) / 10}m and was killed`;
869
749
  onEvent?.({ type: 'error', message });
870
- throw new Error(message);
750
+ onEvent?.({ type: 'done' });
751
+ return runResult();
871
752
  }
753
+ reportExit(exitCode);
872
754
  if (ompUi.turnId)
873
755
  onEvent?.({ type: 'note', message: 'omp RPC session ended before session_settled' });
874
756
  if (tokensUsed === 0)
875
757
  onEvent?.({ type: 'note', message: 'token usage not reported by omp CLI' });
876
758
  emitUiEvent({ type: 'session.ended', reason: ompUi.stopReason });
877
759
  onEvent?.({ type: 'done' });
878
- return { text: textChunks.join('\n').trim(), toolCalls, tokensUsed, sessionId };
760
+ return runResult();
761
+ };
762
+ const result = (async function runOmp() {
763
+ try {
764
+ for await (const line of readNdjson(child.stdout))
765
+ handleOutputLine(line);
766
+ }
767
+ catch (error) {
768
+ if (child.exitCode === null && child.signalCode === null) {
769
+ // A live child whose stream failed is not a refusal: no respawn follows, so nothing
770
+ // may still be accepted into the outbox.
771
+ open = false;
772
+ // The run is reported failed, so the CLI must not keep running tools in the worktree:
773
+ // SIGTERM now, SIGKILL after the grace period (a timer `finally` does not clear).
774
+ terminatedByCezar = true;
775
+ signalSession(child, 'SIGTERM');
776
+ const reap = setTimeout(() => {
777
+ if (child.exitCode === null && child.signalCode === null)
778
+ signalSession(child, 'SIGKILL');
779
+ }, killGraceMs);
780
+ reap.unref?.();
781
+ throw error;
782
+ }
783
+ }
784
+ finally {
785
+ if (deadline)
786
+ clearTimeout(deadline);
787
+ rpcInput.stopAutoEndTimer();
788
+ killWatchdog?.clear();
789
+ // A refused spawn may still be respawned: stay open so input accepted meanwhile is kept
790
+ // for the new child instead of being refused in the gap.
791
+ if (!retryPossible())
792
+ open = false;
793
+ rpcInput.rejectAgentAck();
794
+ }
795
+ flushText();
796
+ emitLatchedProviderError();
797
+ emitLatchedUiProviderError();
798
+ const exitCode = await waitForExit(child);
799
+ if (interruptKillTimer)
800
+ clearTimeout(interruptKillTimer);
801
+ const respawnArgs = retryArgsAfterRefusal(exitCode);
802
+ if (respawnArgs) {
803
+ spawnArgs = respawnArgs;
804
+ child = spawnOmp(spawnArgs);
805
+ if (child.pid !== undefined)
806
+ opts.onPidChange?.(child.pid);
807
+ deadline = armDeadline();
808
+ return runOmp();
809
+ }
810
+ return settleExit(exitCode);
879
811
  })();
880
812
  const session = {
881
813
  result,
882
814
  sendMessage,
883
- sendAgentMessage: (content, inputIds = [], options) => {
884
- // #505: a running turn is steered; only a pending CEZ:ASK (unless the caller delivers
885
- // beside it) or an unacknowledged prompt refuses.
886
- const askRefuses = pendingMarkerAsk && !options?.besideQuestion;
887
- if (open && !askRefuses && (agentAck || humanAcks.size)) {
888
- refusedForAck = true;
889
- return false;
890
- }
891
- if (!open || askRefuses)
892
- return false;
893
- const id = `cezar-agent-${++promptSerial}`;
894
- let resolve, reject;
895
- const acknowledged = new Promise((yes, no) => { resolve = yes; reject = no; });
896
- agentAck = { id, resolve, reject };
897
- if (!sendMessage(content, id, inputIds)) {
898
- agentAck = undefined;
899
- return false;
900
- }
901
- return acknowledged;
902
- },
815
+ // A failed write returns no receipt.
816
+ sendAgentMessage: (content, inputIds = [], options) => rpcInput.sendAgentMessage(content, inputIds, options, sendMessage, () => false),
903
817
  // A written prompt cannot be unwritten; only stop reporting an acknowledged one as held.
904
818
  discardQueuedMessages: () => { humanHeld.clear(); },
905
819
  holdsHumanInput: () => humanHeld.size > 0,
@@ -918,6 +832,10 @@ export class OmpRunner {
918
832
  return session;
919
833
  }
920
834
  }
835
+ /** Native message types that end a text block; a prompt or response ack is not one. */
836
+ const OMP_TEXT_BOUNDARY_TYPES = new Set([
837
+ 'tool_execution_start', 'message_end', 'session_settled', 'prompt_result', 'turn_end', 'agent_end',
838
+ ]);
921
839
  /**
922
840
  * The stderr line an exit error carries. OMP's "no usable model" exit prints its reason first
923
841
  * and setup hints after it, which the generic last-lines summary would keep instead.
@@ -969,62 +887,6 @@ function refusedOmpAddDir(stderr, args) {
969
887
  const dirs = args.flatMap((arg, i) => (arg === '--add-dir' ? [args[i + 1] ?? ''] : [])).filter(Boolean);
970
888
  return dirs.length > 0 ? dirs : null;
971
889
  }
972
- /** Same as pi-runner.ts `toPiPrompt`. */
973
- function toOmpPrompt(content) {
974
- const text = [];
975
- const images = [];
976
- for (const block of content) {
977
- if (block.type === 'text')
978
- text.push(block.text);
979
- else
980
- images.push({ type: 'image', data: block.source.data, mimeType: block.source.media_type });
981
- }
982
- return { message: text.join('\n'), images };
983
- }
984
- /** Same as pi-runner.ts `emitImages`. */
985
- function emitImages(value, onEvent) {
986
- if (!Array.isArray(value))
987
- return;
988
- for (const part of value) {
989
- if (isRecord(part) && part.type === 'image') {
990
- const data = string(part.data);
991
- const mediaType = string(part.mimeType);
992
- if (data && mediaType)
993
- onEvent?.({ type: 'image', data, mediaType });
994
- }
995
- }
996
- }
997
- /** Same as pi-runner.ts `piMessageText`. */
998
- function ompMessageText(message) {
999
- if (typeof message.content === 'string')
1000
- return message.content;
1001
- return Array.isArray(message.content)
1002
- ? message.content.flatMap(part => isRecord(part) && part.type === 'text' && typeof part.text === 'string' ? [part.text] : []).join('\n')
1003
- : '';
1004
- }
1005
- /** Same as pi-runner.ts `contentText`. */
1006
- function contentText(value) {
1007
- if (typeof value === 'string')
1008
- return value;
1009
- if (!Array.isArray(value))
1010
- return undefined;
1011
- const text = value
1012
- .map((part) => (isRecord(part) && part.type === 'text' ? string(part.text) : undefined))
1013
- .filter((part) => part !== undefined);
1014
- return text.length > 0 ? text.join('\n') : undefined;
1015
- }
1016
- /** OMP's failure response carries `error` as a string (rpc-mode.ts, v18.4.11). */
1017
- function rpcError(value) {
1018
- if (typeof value.error === 'string')
1019
- return value.error;
1020
- const error = isRecord(value.error) ? value.error : undefined;
1021
- return string(error?.message) ?? string(value.message) ?? `omp RPC command ${string(value.command) ?? 'unknown'} failed`;
1022
- }
1023
- function waitForExit(child) {
1024
- if (child.exitCode !== null || child.signalCode !== null)
1025
- return Promise.resolve(child.exitCode);
1026
- return new Promise((resolve) => child.once('close', resolve));
1027
- }
1028
890
  function wrapSpawnError(error, bin) {
1029
891
  if (error.code === 'ENOENT') {
1030
892
  return new Error(`\`${bin}\` not found on PATH: install OMP (https://omp.sh) and run \`omp login\``);
@@ -1037,13 +899,4 @@ function mockOmpPath() {
1037
899
  // here = <pkg>/dist/core (built) or <pkg>/src/core (tsx dev).
1038
900
  return resolvePath(here, '..', '..', 'scripts', 'mock-omp-rpc.mjs');
1039
901
  }
1040
- function truncate(value, max = 200) {
1041
- return value.length > max ? `${value.slice(0, max)}…` : value;
1042
- }
1043
- function isRecord(value) {
1044
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1045
- }
1046
- function string(value) {
1047
- return typeof value === 'string' ? value : undefined;
1048
- }
1049
902
  //# sourceMappingURL=omp-runner.js.map