@aragon-agent/cli 0.6.63 → 0.6.66

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.
Files changed (80) hide show
  1. package/CHANGELOG.md +131 -2
  2. package/README.md +98 -21
  3. package/dist/agent/controller.d.ts +119 -14
  4. package/dist/agent/controller.js +385 -82
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +68 -6
  7. package/dist/agent/reconnect-memory.d.ts +68 -0
  8. package/dist/agent/reconnect-memory.js +82 -0
  9. package/dist/agent/team-notices.d.ts +57 -7
  10. package/dist/agent/team-notices.js +93 -10
  11. package/dist/app/App.js +284 -78
  12. package/dist/cli.js +4 -1
  13. package/dist/commands/builtins.js +8 -72
  14. package/dist/commands/catalog.js +1 -1
  15. package/dist/commands/retry-command.d.ts +52 -0
  16. package/dist/commands/retry-command.js +225 -0
  17. package/dist/config/cli-commands.d.ts +1 -1
  18. package/dist/config/cli-commands.js +39 -0
  19. package/dist/exec/events.d.ts +12 -0
  20. package/dist/exec/index.js +2 -0
  21. package/dist/exec/runner.js +16 -1
  22. package/dist/gene/cli-commands.js +30 -1
  23. package/dist/gene/command-report.js +5 -1
  24. package/dist/gene/commit-prepare.js +27 -1
  25. package/dist/gene/curator/budget.d.ts +24 -1
  26. package/dist/gene/curator/budget.js +67 -14
  27. package/dist/gene/curator/curator.d.ts +25 -0
  28. package/dist/gene/curator/curator.js +61 -7
  29. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  30. package/dist/gene/curator/scripted-lane.js +101 -0
  31. package/dist/gene/curator/task-context.d.ts +29 -0
  32. package/dist/gene/curator/task-context.js +43 -0
  33. package/dist/gene/curator/task-runner.d.ts +10 -1
  34. package/dist/gene/curator/task-runner.js +52 -6
  35. package/dist/gene/curator/tool-support.js +11 -4
  36. package/dist/gene/curator/toolkit.d.ts +13 -0
  37. package/dist/gene/curator/toolkit.js +23 -1
  38. package/dist/gene/curator/tools-verify.js +2 -2
  39. package/dist/gene/curator/tools-write.js +6 -1
  40. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  41. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  42. package/dist/gene/curator/validate/knowledge.js +74 -11
  43. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  44. package/dist/gene/curator/validate/prompts.js +2 -2
  45. package/dist/gene/hub.js +5 -0
  46. package/dist/gene/import-plan.js +8 -5
  47. package/dist/gene/learn/draft-guard.d.ts +17 -0
  48. package/dist/gene/learn/draft-guard.js +113 -0
  49. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  50. package/dist/gene/learn/learn-prompt.js +27 -2
  51. package/dist/gene/learn/learner.js +27 -5
  52. package/dist/gene/queue.d.ts +24 -0
  53. package/dist/gene/queue.js +80 -1
  54. package/dist/governance/store/run-store.d.ts +20 -0
  55. package/dist/governance/store/run-store.js +54 -8
  56. package/dist/host/controller-factory.js +6 -0
  57. package/dist/host/index.d.ts +1 -0
  58. package/dist/host/index.js +1 -0
  59. package/dist/host/interaction.d.ts +8 -17
  60. package/dist/host/interaction.js +50 -72
  61. package/dist/host/team-wake-driver.d.ts +90 -0
  62. package/dist/host/team-wake-driver.js +114 -0
  63. package/dist/logging/install.d.ts +35 -1
  64. package/dist/logging/install.js +23 -0
  65. package/dist/session/persist.js +8 -1
  66. package/dist/session/validate-session.js +15 -5
  67. package/dist/team/console-tools.d.ts +12 -0
  68. package/dist/team/console-tools.js +20 -3
  69. package/dist/team/console-view.js +11 -1
  70. package/dist/team/notices.d.ts +81 -4
  71. package/dist/team/notices.js +187 -22
  72. package/dist/team/prompt.js +1 -1
  73. package/dist/team/runtime.d.ts +67 -24
  74. package/dist/team/runtime.js +250 -31
  75. package/dist/team/stall-watch.d.ts +54 -0
  76. package/dist/team/stall-watch.js +119 -0
  77. package/dist/team/task-tool.js +2 -2
  78. package/dist/team/wake.d.ts +176 -0
  79. package/dist/team/wake.js +444 -0
  80. package/package.json +81 -81
package/dist/app/App.js CHANGED
@@ -14,7 +14,7 @@ import { Text, useApp, useInput, useStdout } from 'ink';
14
14
  import { advanceInterruptGesture, INTERRUPT_CONFIRM_MS, cancelInterruptConfirmation, } from '@aragon-agent/tui/input/interrupt-gesture';
15
15
  import { initialViewState, viewReducer, } from '@aragon-agent/tui/model/agent/reducer';
16
16
  import { ActionCoalescer, attachAgentChannel, attachCompactionChannel, attachContextUsageChannel, attachFastChannel, attachGovernanceChannel, attachProcChannel, attachTeamChannel, attachTodosChannel, attachToolOutputChannel, attachWaitChannel, makePatchSource, } from '../host/controller-feed.js';
17
- import { parseMaxTokensInput, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, } from '@aragon-agent/tui/model/config/schema';
17
+ import { parseMaxTokensInput, toRunResumePolicy, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, } from '@aragon-agent/tui/model/config/schema';
18
18
  import { updatePersistedConfig } from '../config/store.js';
19
19
  import { appendPrompt, loadPromptHistory } from '../config/prompt-history.js';
20
20
  import { bumpSubmitCount, getGovernanceIntroSeen, setGovernanceIntroSeen, setMouseNoticeVersion, setPromptKeyNoticeVersion, setScrollModeNoticeVersion, setVtInputNoticeVersion, } from '../config/ui-state.js';
@@ -58,7 +58,7 @@ import { ScrollViewport } from '@aragon-agent/tui/ui/layout/ScrollViewport';
58
58
  import { acceptanceChip, acceptanceRung, buildTodoRailLayout } from '@aragon-agent/tui/ui/layout/todo-layout';
59
59
  import { buildTeamPanelLayout } from '@aragon-agent/tui/ui/layout/team-panel';
60
60
  import { isLiveTeamCard, lastTeamEntry, rosterCounts } from '@aragon-agent/tui/ui/team-status';
61
- import { advanceBudget, decideFollowThrough, emptyBudget, isTransientRunEnd, } from '@aragon-agent/tui/model/todo/follow-through';
61
+ import { advanceBudget, chargeResume, decideFollowThrough, emptyBudget, emptyResumeCounters, isTransientRunEnd, settleResumeCounters, } from '@aragon-agent/tui/model/todo/follow-through';
62
62
  // THE THIRD LAYER OF FORCED TEAM MODE (team-command-forced-dispatch §3.7): the
63
63
  // decision and its two strings live in a pure module, so `App` gains wiring and
64
64
  // no policy. Imported beside the todo decision it shares one timer with.
@@ -70,7 +70,7 @@ import { redTeamToastTtlMs, useRedTeamMode, } from './use-redteam-mode.js';
70
70
  import { RedTeamDisclaimerOverlay } from '@aragon-agent/tui/ui/overlays/RedTeamDisclaimerOverlay';
71
71
  import { teamStatusFromView } from '@aragon-agent/tui/model/team/team-mode';
72
72
  import { FORCED_NUDGE_GRACE_MS } from '@aragon-agent/tui/model/team/limits';
73
- import { planSettleContinuation } from '@aragon-agent/tui/model/team/settle-plan';
73
+ import { TeamWakeDriver } from '../host/team-wake-driver.js';
74
74
  import { formatDuration } from '@aragon-agent/tui/model/agent/usage';
75
75
  import { useTerminalSize } from '@aragon-agent/tui/ui/layout/useTerminalSize';
76
76
  import { useHeightStore } from '@aragon-agent/tui/ui/use-height-store';
@@ -121,6 +121,7 @@ import { PlanReviewOverlay } from '@aragon-agent/tui/ui/overlays/PlanReviewOverl
121
121
  import { parseSlashInput, runSlashInput, } from '../commands/registry.js';
122
122
  import { buildInvocationCard, invocationCardsEnabled } from '@aragon-agent/tui/model/agent/invocation-card';
123
123
  import { createCommandRegistry } from '../commands/create-registry.js';
124
+ import { retryLadderShape } from '../commands/retry-command.js';
124
125
  import { MODE_TOGGLE_KEYS } from '@aragon-agent/tui/model/agent/agent-mode';
125
126
  import { createClipboardCoordinator } from '@aragon-agent/tui/ui/clipboard-task';
126
127
  import { QueuePanel } from '@aragon-agent/tui/ui/QueuePanel';
@@ -546,7 +547,28 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
546
547
  */
547
548
  const updateToastPushed = useRef(false);
548
549
  const budgetRef = useRef(emptyBudget());
550
+ /**
551
+ * The two counters bounding a re-run of an engine-interrupted run
552
+ * (`team-idle-watchdog-dead-run` F3). A REF OF ITS OWN, NOT A FIELD OF
553
+ * `budgetRef`: that budget belongs to a PLAN LINEAGE and `advanceBudget` zeroes
554
+ * it the moment the plan is gone, whereas a stalled link has nothing to do with
555
+ * any plan - sharing it would hand the user a fresh allowance every time the
556
+ * model finished a todo list.
557
+ *
558
+ * `consecutive` is cleared by any run that ends without an error
559
+ * (`afterAgentEnd`); `total` ONLY by the user typing (`submitMessage`). It is
560
+ * deliberately NOT touched by `agent_start`: a recovery IS a new run, and
561
+ * clearing there would reset both counters on every recovery and make the bound
562
+ * unreachable.
563
+ */
564
+ const resumeRef = useRef(emptyResumeCounters());
549
565
  const followTimer = useRef(null);
566
+ /**
567
+ * The team wake driver (team-lead-wake-signals 4.10), mounted in an effect below. A
568
+ * ref because `cancelFollowThrough` - the one place every "the user did something"
569
+ * path already passes through - has to reach it without being re-created.
570
+ */
571
+ const teamWakeRef = useRef(null);
550
572
  /**
551
573
  * The forced-dispatch gate's three counters (team-command-forced-dispatch
552
574
  * §3.7). REFS, for the reason the follow-through block above records: every
@@ -739,79 +761,116 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
739
761
  *
740
762
  * ONE SLOT: `Esc`, `submitMessage`, the reset/restore port, the effect cleanup
741
763
  * and both follow-through arms (todo, then the gate) all cancel before arming.
764
+ *
765
+ * THE TEAM WAKE COUNTDOWN SITS IN THAT SAME SLOT (team-lead-wake-signals I-WK9), so
766
+ * cancelling it is the same act: the driver is told after the timer is cleared, and
767
+ * it only reacts when it actually holds a countdown (its own submit passes through
768
+ * `submitMessage` -> here and must find nothing to cancel).
742
769
  */
743
770
  const cancelFollowThrough = useCallback(() => {
744
771
  if (followTimer.current) {
745
772
  clearTimeout(followTimer.current);
746
773
  followTimer.current = null;
747
774
  }
775
+ teamWakeRef.current?.cancel();
748
776
  }, []);
749
777
  /**
750
- * Decide what, if anything, the settle of a dispatch earns (5.3.3).
751
- *
752
- * A PURE DECISION IN A PURE FILE (`planSettleContinuation`, in the tui package)
753
- * with an impure caller here: each host owns its timer, the truth table is
754
- * shared. That split is R9's mitigation - the desktop coordinator runs the same
755
- * function against its own timer.
778
+ * Re-run a run the ENGINE interrupted, after `graceMs`
779
+ * (`team-idle-watchdog-dead-run` F3). `decideFollowThrough` decided WHETHER; this
780
+ * is the host's half, and it deliberately reuses the one `followTimer` slot so
781
+ * "at most one armed continuation, ever" (I-3) stays true.
756
782
  *
757
- * DEFINED AFTER `cancelFollowThrough`, not before it: the callback closes over
758
- * it, and a `useCallback` whose deps array reads a `const` that is still in its
759
- * temporal dead zone throws during the very first render - which presents as a
760
- * blank tree, not as an error in the console.
783
+ * IT STARTS THE RUN WITH `controller.continue()`, NOT `submit()`. Nothing is
784
+ * appended to the history: the interrupted turn's input is already there and the
785
+ * half-written reply never was, so `continue()` just asks again. That is also why
786
+ * there is no card, no `userInitiated` bookkeeping and no prompt-history entry.
761
787
  *
762
- * `followThroughArmed` is PASSED IN rather than read here: the caller is the only
763
- * place that knows what the todo decision and the forced-dispatch gate did in
764
- * this very turn (I-9).
788
+ * A TEAM WAKE COUNTDOWN OUTRANKS IT. If the team already owes the lead a signal and
789
+ * its countdown is running, that wake starts a turn which redoes the interrupted
790
+ * work anyway (and delivers a real signal while doing it); arming here would cancel
791
+ * the wake (`cancelFollowThrough` -> `teamWakeRef.cancel()`) and spend an
792
+ * allowance to do the same thing worse. So this yields, silently, WITHOUT charging.
765
793
  */
766
- const armTeamSettle = useCallback((armed) => {
767
- // ABSENT MEANS "NO TEAM IN THIS HOST": a controller double without the team
768
- // surface simply never earns a continuation.
769
- const facts = controller.teamSettleFacts?.() ?? null;
770
- if (facts === null)
771
- return;
772
- // Same defence as the gate: a double without the team surface never reaches
773
- // this line, and one that has `teamSettleFacts` but no config still gets the
774
- // documented defaults rather than a crash inside an event handler.
775
- const teamConfig = controller.getTeamConfig?.() ?? {
776
- autoResume: 'auto',
777
- settleGraceMs: 3_000,
778
- detachDispatch: true,
779
- };
780
- const decision = planSettleContinuation({
781
- mode: teamConfig.autoResume,
782
- settled: facts.settled,
783
- settledInsideTurn: facts.settledInsideTurn,
784
- runEnd: { aborted: facts.aborted, errored: facts.errored },
785
- continuedThisDispatch: facts.continuedThisDispatch,
786
- userPending: controller.hasPendingUserMessages(),
787
- followThroughArmed: armed.followThroughArmed,
788
- graceMs: teamConfig.settleGraceMs,
789
- outcome: facts.outcome,
790
- });
791
- if (decision.kind === 'notice') {
792
- dispatch({ type: 'notice', level: decision.level, text: decision.text });
794
+ const armRunResume = (graceMs, notice) => {
795
+ if (teamWakeRef.current?.isCounting() === true) {
796
+ getLogger().debug('agent', 'run_resume_yield', { reason: 'team_wake_counting' });
793
797
  return;
794
798
  }
795
- if (decision.kind !== 'continue')
796
- return;
797
- dispatch({ type: 'notice', level: decision.level, text: decision.notice });
798
- cancelFollowThrough(); // I-9: at most one armed continuation, ever
799
+ dispatch({ type: 'notice', level: 'info', text: notice });
800
+ cancelFollowThrough(); // I-3: at most one armed continuation, ever
799
801
  followTimer.current = setTimeout(() => {
800
802
  followTimer.current = null;
801
- // The grace window is open to the user, so both facts are re-read at fire
802
- // time: they may have started a turn, or typed the very message the notice
803
- // was about.
804
- if (controller.isRunning() || controller.isCompactionBusy?.())
805
- return;
806
- if (controller.hasPendingUserMessages())
807
- return;
808
- // THE ID COMES FROM THE FACTS, never from `live()`: the dispatch has
809
- // already settled by the time this runs, so `live()` is null and the
810
- // continuation would never be charged (see `teamSettleFacts`).
811
- controller.markTeamContinued(facts.dispatchId);
812
- submitRef.current(decision.message, { userInitiated: false, todoPolicy: 'continue' });
813
- }, decision.graceMs);
814
- }, [controller, dispatch, cancelFollowThrough]);
803
+ void fireRunResume();
804
+ }, graceMs);
805
+ };
806
+ /**
807
+ * THE FIRE POINT. Every guard `drainCompactionQueue` applies to its own
808
+ * `controller.continue()` applies here, for the same reason: `Agent.continue()`
809
+ * THROWS while running, and the grace window is open to the user, who may have
810
+ * started typing at its very end. `submitMessage` -> `cancelFollowThrough()` already
811
+ * covers a message typed EARLIER in the window; what it cannot cover is a run that
812
+ * began in the same tick the timer fired, which `interactionPhase` does.
813
+ *
814
+ * ITS FAILURES ARE `warn`, NEVER `error`: the error level sets
815
+ * `endReasonRef.errored` (see the gate's note), and a failed START has no
816
+ * `agent_end` to clear it - the next, unrelated run would then be judged to have
817
+ * failed and recovered or reported for nothing.
818
+ */
819
+ const fireRunResume = async () => {
820
+ if (!mounted.current || switchingConversation.current
821
+ || controller.isCompactionBusy?.() || controller.isRunning()
822
+ || interactionPhase.current !== 'idle'
823
+ || controller.areModelSettingsBlocked?.() === true) {
824
+ getLogger().debug('agent', 'run_resume_skipped', { reason: 'host_busy' });
825
+ return;
826
+ }
827
+ const preflight = controller.preflight();
828
+ if (!preflight.ok) {
829
+ dispatch({ type: 'notice', level: 'warn', text: preflight.message ?? 'Configuration error.' });
830
+ return;
831
+ }
832
+ // CHARGED AT THE FIRE POINT, never at decision time: a recovery the user cancelled
833
+ // was never issued and must not spend their allowance.
834
+ resumeRef.current = chargeResume(resumeRef.current);
835
+ // COUNTS ONLY: no message body ever reaches this log.
836
+ getLogger().info('agent', 'run_resume', {
837
+ consecutive: resumeRef.current.consecutive,
838
+ total: resumeRef.current.total,
839
+ });
840
+ interactionPhase.current = 'starting';
841
+ try {
842
+ const outcome = await controller.continue();
843
+ if (outcome?.status === 'not-started' && outcome.reason !== 'cancelled') {
844
+ dispatch({
845
+ type: 'notice',
846
+ level: 'warn',
847
+ text: 'Could not retry the run automatically. Send any message to continue.',
848
+ });
849
+ }
850
+ }
851
+ catch (error) {
852
+ const reason = error instanceof Error ? error.message : String(error);
853
+ dispatch({
854
+ type: 'notice',
855
+ level: 'warn',
856
+ text: `Could not retry the run automatically (${reason}). Send any message to continue.`,
857
+ });
858
+ }
859
+ finally {
860
+ if (interactionPhase.current === 'starting')
861
+ interactionPhase.current = 'idle';
862
+ }
863
+ };
864
+ /**
865
+ * `armRunResume` as of the LATEST render, for the `afterAgentEnd` hook - the same
866
+ * reason `submitRef` exists just below: the subscription effect never re-runs, so a
867
+ * direct call would close over the mount render's binding forever. That binding
868
+ * would happen to be correct today because the function reads only refs and stable
869
+ * values, which is exactly the "happens to be correct" this file keeps having to
870
+ * unwind.
871
+ */
872
+ const armRunResumeRef = useRef(() => { });
873
+ armRunResumeRef.current = armRunResume;
815
874
  /**
816
875
  * `submitMessage` as of the LATEST render, for the grace timer.
817
876
  *
@@ -823,7 +882,24 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
823
882
  * (P1-1, P1-6). Assigned during render, the same discipline `stateRef` uses
824
883
  * twenty lines up.
825
884
  */
826
- const submitRef = useRef(() => { });
885
+ const submitRef = useRef(() => ({ accepted: false }));
886
+ /**
887
+ * A message that ARRIVED WHILE THE LADDER WAS WAITING IN TIER 2 OR 3
888
+ * (tiered-reconnect §4.7 / P1-7), parked here for the `afterAgentEnd` hook to
889
+ * send once the aborted run has finished unwinding.
890
+ *
891
+ * WHY A REF AND A TWO-STEP HAND-OFF: `submitMessage` cannot send while a request
892
+ * is in flight — it routes through `queueUserMessage` → `agent.steer`, which
893
+ * neither aborts nor delivers, and `acceptSteering` only drains at the TOP of a
894
+ * loop iteration. With a five-minute wait in progress that means the user's
895
+ * message would sit in the queue until they typed again. So the wait is aborted
896
+ * and the message is RE-SENT by `afterAgentEnd`, which is the one hook that runs
897
+ * exactly once per run and after the engine is idle.
898
+ *
899
+ * AT MOST ONE, and cleared before the re-send: a second `agent_end` must not
900
+ * deliver the same text twice (AC-23b).
901
+ */
902
+ const pendingAfterAbort = useRef(null);
827
903
  /**
828
904
  * THE SINGLE SETTLE PATH for a human request. Idempotent per entry, and it
829
905
  * clears the overlay as its last act.
@@ -937,6 +1013,29 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
937
1013
  // Without it, an aborted run leaves a plan card on screen whose `a` key
938
1014
  // silently flips the session to build, with no visible cause.
939
1015
  cancelPendingHuman();
1016
+ // THE MESSAGE THAT STOPPED THE WAIT GOES OUT HERE (§4.7 / P1-7). This is
1017
+ // the one hook that runs exactly once per run, after the engine is idle —
1018
+ // which is why the park-and-resend pair is the whole implementation, with
1019
+ // no second drain mechanism anywhere.
1020
+ //
1021
+ // CLEARED BEFORE THE RE-SEND, and the order matters: `submitMessage` below
1022
+ // can start a NEW run that eventually reaches this hook again, and a value
1023
+ // still in the ref would deliver the same text a second time (AC-23b).
1024
+ const parked = pendingAfterAbort.current;
1025
+ if (parked) {
1026
+ pendingAfterAbort.current = null;
1027
+ // `userInitiated: true` was forced at park time: the user typed this, so
1028
+ // it belongs in prompt history whether or not the re-send happens inside
1029
+ // a hook.
1030
+ submitRef.current(parked.text, parked.opts);
1031
+ // NOTHING BELOW APPLIES TO IT. The run that just ended was aborted by this
1032
+ // very message, and every branch from here down (follow-through, the
1033
+ // forced-dispatch gate, a resume) would be talking about a turn the user
1034
+ // already replaced. No bookkeeping is needed for the same reason: the
1035
+ // re-send above went through `submitMessage`, which resets
1036
+ // `endReasonRef` and refills the resume counters itself.
1037
+ return;
1038
+ }
940
1039
  // --- Follow-through (todo-plan-followthrough §3.4). ------------------
941
1040
  //
942
1041
  // Round 1 printed one notice here and stopped, under a good argument
@@ -948,6 +1047,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
948
1047
  const todos = controller.getTodoSnapshot();
949
1048
  budgetRef.current = advanceBudget(budgetRef.current, todos, autoContinuationRef.current);
950
1049
  autoContinuationRef.current = false;
1050
+ // A RUN THAT ENDED WITHOUT AN ERROR BREAKS THE CHAIN OF BACK-TO-BACK DEATHS
1051
+ // (F3). Read AFTER the engine's verdict was folded in at the top of this
1052
+ // hook and BEFORE `endReasonRef` is reset below, which is the only window in
1053
+ // which both facts are still true.
1054
+ resumeRef.current = settleResumeCounters(resumeRef.current, endReasonRef.current);
951
1055
  // --- Forced-dispatch gate (team-command-forced-dispatch §3.7). --------
952
1056
  //
953
1057
  // THE THIRD LAYER, AND THE ONLY MECHANICAL ONE: if a whole turn went by
@@ -993,11 +1097,24 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
993
1097
  runEnd: { ...endReasonRef.current },
994
1098
  budget: budgetRef.current,
995
1099
  interactive: true,
1100
+ // READ LIVE, like `followThrough` above: `/retry off` and `config set`
1101
+ // take effect on the very next death, not on relaunch.
1102
+ resume: {
1103
+ ...toRunResumePolicy(controller.getConfig().retry),
1104
+ consecutive: resumeRef.current.consecutive,
1105
+ total: resumeRef.current.total,
1106
+ // The engine's own verdict, for the WORDING only (`RunEndFacts` is a
1107
+ // structural subset of `AgentEndEvent`).
1108
+ cause: end,
1109
+ },
996
1110
  });
997
1111
  endReasonRef.current = { aborted: false, errored: false, transient: false };
998
1112
  if (decision.kind === 'notify') {
999
1113
  dispatch({ type: 'notice', level: decision.level, text: decision.text });
1000
1114
  }
1115
+ else if (decision.kind === 'resume') {
1116
+ armRunResumeRef.current(decision.graceMs, decision.notice);
1117
+ }
1001
1118
  else if (decision.kind === 'continue') {
1002
1119
  dispatch({ type: 'notice', level: 'info', text: decision.notice });
1003
1120
  // NO LIVE COUNTDOWN (D-10). The notice is written once and does not
@@ -1063,20 +1180,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1063
1180
  });
1064
1181
  }, FORCED_NUDGE_GRACE_MS);
1065
1182
  }
1066
- // --- The team's settle continuation (team-detached-dispatch 5.3.3) -----
1067
- //
1068
- // THE THIRD ARMER OF ONE TIMER, and the placement is the whole point: the
1069
- // forced-nudge branch above called `cancelFollowThrough()`, so a team
1070
- // decision written beside it would be silently cleared one line later. Here
1071
- // - after the nudge, before `onTurnEnd()` - nothing downstream cancels it.
1072
- //
1073
- // A dispatch that settled INSIDE this turn needs no new turn (its report
1074
- // already arrived as a steering message), and one that settled while the
1075
- // user was typing does not need one either (their turn carries it). Both
1076
- // are `planSettleContinuation`'s rules, not this block's.
1077
- armTeamSettle({
1078
- followThroughArmed: followTimer.current !== null || decision.kind === 'continue' || gated,
1079
- });
1183
+ // NO TEAM DECISION IS MADE HERE (team-lead-wake-signals). It used to be, once per
1184
+ // `agent_end`, and a dispatch that ends while the lead is idle never produces
1185
+ // one - so the team's report waited for the user to type. The controller's
1186
+ // governor now judges at every moment a signal could be collectable, and the
1187
+ // wake driver mounted below acts on its requests through this same timer slot.
1080
1188
  // A team-mode change asked for during the turn lands here, AFTER the gate above
1081
1189
  // read its basis (I-9). The posture lands next: a pending GOVERN entry that
1082
1190
  // arrives with it is reported by the same toast channel, not silently swallowed.
@@ -1136,6 +1244,51 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1136
1244
  controller.dispose();
1137
1245
  };
1138
1246
  }, [controller]);
1247
+ // --- The team wake driver (team-lead-wake-signals 4.10). ------------------
1248
+ //
1249
+ // THE TERMINAL'S HALF OF "THE TEAM NEEDS THE LEAD": the controller's governor decides
1250
+ // that a turn is owed; this starts it. The countdown lives in `followTimer` - the one
1251
+ // slot the todo follow-through and the forced nudge already share - so at most one
1252
+ // continuation is ever armed, and a wake that finds the slot taken answers `busy` and
1253
+ // is retried rather than stealing it or being dropped (I-WK9).
1254
+ useEffect(() => {
1255
+ const driver = new TeamWakeDriver({
1256
+ controller,
1257
+ timer: {
1258
+ set: (fn, ms) => {
1259
+ if (followTimer.current)
1260
+ clearTimeout(followTimer.current);
1261
+ followTimer.current = setTimeout(() => {
1262
+ followTimer.current = null;
1263
+ fn();
1264
+ }, ms);
1265
+ },
1266
+ clear: () => {
1267
+ if (followTimer.current)
1268
+ clearTimeout(followTimer.current);
1269
+ followTimer.current = null;
1270
+ },
1271
+ armed: () => followTimer.current !== null,
1272
+ },
1273
+ // The countdown is a transcript line (it does not tick - D-10), the cancellation a toast.
1274
+ announce: (level, text) => dispatch({ type: 'notice', level, text }),
1275
+ toast: (level, text) => dispatch({ type: 'pushToast', level, text }),
1276
+ // THROUGH `submitMessage`, so the wake gets the same card, phase bookkeeping and
1277
+ // `userInitiated: false` treatment as every other continuation. It is only ever
1278
+ // called with the lead idle (the driver re-checks in the same synchronous block),
1279
+ // so it can never take the "running -> queue as user steering" branch.
1280
+ submit: (text, invocation) => submitRef.current(text, { userInitiated: false, todoPolicy: 'continue', invocation })
1281
+ .accepted,
1282
+ cancelHint: () => 'Esc cancels',
1283
+ leadBusy: () => interactionPhase.current !== 'idle',
1284
+ });
1285
+ teamWakeRef.current = driver;
1286
+ const detach = driver.attach();
1287
+ return () => {
1288
+ detach();
1289
+ teamWakeRef.current = null;
1290
+ };
1291
+ }, [controller]);
1139
1292
  // --- Governance event stream (governance-mode 8.6 / 14.4). --------------
1140
1293
  //
1141
1294
  // ANOTHER CLI-LOCAL SUBSCRIPTION, for the reason the team one records: `GovernanceEvent`
@@ -2146,6 +2299,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2146
2299
  resetInterrupt();
2147
2300
  cancelFollowThrough();
2148
2301
  autoContinuationRef.current = false;
2302
+ // A message parked behind an aborted tier-2/3 wait belongs to the
2303
+ // conversation that is ending here; delivering it into the next one would be
2304
+ // sending text the user never aimed at it.
2305
+ pendingAfterAbort.current = null;
2149
2306
  if (wasStarting) {
2150
2307
  dispatch({ type: 'abortMark' });
2151
2308
  dispatch({ type: 'runEnd' });
@@ -2321,6 +2478,27 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2321
2478
  : undefined;
2322
2479
  const shown = card?.commandLine ?? message;
2323
2480
  if (interactionPhase.current === 'running' || controller.isCompactionBusy?.()) {
2481
+ // TIER 2/3 WAIT: THE MESSAGE ENDS THE WAIT (§4.7 / D-14). Checked BEFORE the
2482
+ // steering branch because that branch does not deliver anything until the
2483
+ // next loop iteration — and the next iteration is up to five minutes away.
2484
+ //
2485
+ // TIER 1 IS DELIBERATELY EXCLUDED: its waits are seconds long, the steering
2486
+ // queue is exactly the right answer there, and changing that behaviour would
2487
+ // make an ordinary fast retry swallow the user's message.
2488
+ const live = stateRef.current.retry;
2489
+ if (live?.phase === 'waiting' && (live.tier ?? 1) >= 2) {
2490
+ pendingAfterAbort.current = { text: message, opts: { ...opts, userInitiated: true } };
2491
+ // The card, the notice and the transcript all read the SAME decision, so
2492
+ // the message is not "sent" twice: `afterAgentEnd` re-sends the parked text
2493
+ // and this notice is what tells the user it happened (Q-3).
2494
+ dispatch({
2495
+ type: 'notice',
2496
+ level: 'info',
2497
+ text: 'Stopped waiting for the provider to reconnect; sending your message now.',
2498
+ });
2499
+ controller.abort();
2500
+ return { accepted: true };
2501
+ }
2324
2502
  try {
2325
2503
  const queueId = controller.queueUserMessage(message);
2326
2504
  dispatch({ type: 'steerQueued', queueId, text: shown, ...(card ? { invocation: card } : {}) });
@@ -2352,6 +2530,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2352
2530
  // nudge continuation arrives here with `userInitiated: false`, so it cannot
2353
2531
  // refill its own budget.
2354
2532
  nudgesRef.current = 0;
2533
+ // THE ONE PLACE THE PER-PROMPT RECOVERY CEILING IS REFILLED (F3), for the same
2534
+ // reason as the nudge budget: only a human may hand an automatic mechanism
2535
+ // another allowance, and a recovery or a todo continuation arrives here with
2536
+ // `userInitiated: false` and so cannot refill its own.
2537
+ resumeRef.current = emptyResumeCounters();
2355
2538
  }
2356
2539
  // Mirrors where the reducer clears its own copies, in the same action
2357
2540
  // (C-11): a new turn's end reason must not inherit the previous one's.
@@ -3172,8 +3355,13 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3172
3355
  // the pre-existing meaning of Esc here ("start nothing"), and a second rung
3173
3356
  // below it must not take that away.
3174
3357
  if (followTimer.current) {
3358
+ // A cancelled team wake says so itself ("Wake cancelled. The report goes with your
3359
+ // next message."); a second, generic toast would say the same thing twice.
3360
+ const wakeOwnsIt = teamWakeRef.current?.isCounting() === true;
3175
3361
  cancelFollowThrough();
3176
- dispatch({ type: 'pushToast', level: 'info', text: 'Auto-continue cancelled.' });
3362
+ if (!wakeOwnsIt) {
3363
+ dispatch({ type: 'pushToast', level: 'info', text: 'Auto-continue cancelled.' });
3364
+ }
3177
3365
  return;
3178
3366
  }
3179
3367
  // --- The team rung (team-detached-dispatch 5.6, I-DD11) -----------------
@@ -3247,6 +3435,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3247
3435
  resetInterrupt();
3248
3436
  autoContinuationRef.current = false;
3249
3437
  metrics.current = freezeRunMetrics(metrics.current, Date.now());
3438
+ // A forced stop DROPS the run: `afterAgentEnd` never fires for it, so a parked
3439
+ // message would be delivered at the end of some LATER run, saying "sending your
3440
+ // message now" about a turn the user already killed.
3441
+ pendingAfterAbort.current = null;
3250
3442
  if (next.action === 'force-stop')
3251
3443
  controller.forceStop();
3252
3444
  else
@@ -3601,7 +3793,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3601
3793
  teamRegistered: controller.isTeamRegistered(), governanceRegistered: controller.isGovernanceRegistered(), memoryRegistered: typeof controller.getMemoryService === 'function' && controller.getMemoryService() !== undefined, ...(terminal?.enhancedKeys === undefined ? {} : { enhancedKeys: terminal.enhancedKeys }), probe: probe, onProfileSave: handleProfileSave, onReload: () => controller.createModelSettingsDraft(), onClose: () => dispatch({ type: 'setOverlay', overlay: null }),
3602
3794
  // Read from `cfg` (render scope, re-read every frame), so `/retry off`
3603
3795
  // while the screen is open shows the new value on the next paint.
3604
- retrySummary: cfg.retry.enabled && cfg.retry.maxRetries > 0 ? String(cfg.retry.maxRetries) : 'off' })) : overlay === 'agents' ? (
3796
+ // THE LADDER IS PART OF THE ANSWER (AC-17): `API retries: 10` would keep
3797
+ // describing the old behaviour, and the six new keys are invisible there.
3798
+ // Every number still comes from `cfg`, so `/retry slow 30` repaints this row.
3799
+ retrySummary: retryLadderShape(cfg.retry, { headless: false }) })) : overlay === 'agents' ? (
3605
3800
  // THE BRANCH AND THE `Overlay` MEMBER SHIP TOGETHER (R-11): a missing branch is not
3606
3801
  // a type error, it is a SILENT BLANK FRAME, because `active={overlay === null}` has
3607
3802
  // already disabled the transcript underneath.
@@ -3846,6 +4041,17 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3846
4041
  // what keeps the chip and the transcript card showing the same
3847
4042
  // number without either of them owning a second clock.
3848
4043
  secondsLeft: secondsLeft(state.retry.resumeAt, Date.now()),
4044
+ // Tiered reconnect (§4.6.5). All three are optional and absent in
4045
+ // a session that never escalates, so the label stays exactly what
4046
+ // it was. No new timer: this render already runs at 1 Hz while a
4047
+ // retry is waiting.
4048
+ ...(state.retry.tier !== undefined ? { tier: state.retry.tier } : {}),
4049
+ ...(state.retry.tierCount !== undefined
4050
+ ? { tierCount: state.retry.tierCount }
4051
+ : {}),
4052
+ ...(state.retry.totalAttempts !== undefined
4053
+ ? { totalAttempts: state.retry.totalAttempts }
4054
+ : {}),
3849
4055
  },
3850
4056
  }
3851
4057
  : {}) }));
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ import { COMPACTION_CONFIG_SET_KEYS, FAST_CONFIG_SET_KEYS, LOG_CONFIG_SET_KEYS,
19
19
  import { attachAgentEvents, attachTeamEvents, installLogging, setScreenRestore, setSignalTerminator, } from './logging/install.js';
20
20
  import { getLogger } from './logging/logger.js';
21
21
  import { runLogsCommand } from './logging/cli-commands.js';
22
- import { ADAPTER_PROVIDERS, clampDensity, clampTheme, clampThinkingLevel, clampHumanTimeout, clampSkillsIntegrity, clampSkillsToolPolicy, clampContextWindow, clampMaxRenderInterval, clampScrollMode, clampScrollResumeMs, clampTranscriptRetain, clampTranscriptWindow, coercePositiveInt, isAdapterProvider, isAutoToken, parseMaxTokensInput, RETIRED_CONFIG_KEYS, DEFAULT_MAX_RENDER_INTERVAL_MS, DEFAULT_MAX_TOKENS, DEFAULT_PLAN_HUMAN_TIMEOUT_MS, DEFAULT_SCROLL_MODE, DEFAULT_SCROLL_RESUME_MS, DEFAULT_SKILLS_CONFIG, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, } from '@aragon-agent/tui/model/config/schema';
22
+ import { ADAPTER_PROVIDERS, clampDensity, clampTheme, clampThinkingLevel, clampHumanTimeout, clampSkillsIntegrity, clampSkillsToolPolicy, clampContextWindow, clampMaxRenderInterval, clampScrollMode, clampScrollResumeMs, clampTranscriptRetain, clampTranscriptWindow, coercePositiveInt, isAdapterProvider, isAutoToken, parseMaxTokensInput, RETIRED_CONFIG_KEYS, DEFAULT_MAX_RENDER_INTERVAL_MS, DEFAULT_MAX_TOKENS, DEFAULT_PLAN_HUMAN_TIMEOUT_MS, DEFAULT_SCROLL_MODE, DEFAULT_SCROLL_RESUME_MS, DEFAULT_SKILLS_CONFIG, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, toRunResumePolicy, } from '@aragon-agent/tui/model/config/schema';
23
23
  import { makeGetApiKey } from './config/load.js';
24
24
  import { runSkillsCommand } from './skills/cli-commands.js';
25
25
  import { runHeadless } from './agent/headless.js';
@@ -1344,6 +1344,9 @@ async function runOneShot(flags, prompt, quiet) {
1344
1344
  code = await runHeadless(controller, prompt, {
1345
1345
  quiet,
1346
1346
  followThrough: controller.getTodoConfig().followThrough,
1347
+ // ONE RECOVERY for a run the engine interrupted (team-idle-watchdog-dead-run F3);
1348
+ // `headless` is where that cap comes from.
1349
+ resume: toRunResumePolicy(controller.getConfig().retry, { headless: true }),
1347
1350
  });
1348
1351
  }
1349
1352
  finally {