@aragon-agent/cli 0.6.64 → 0.6.68

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 (63) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +79 -4
  3. package/dist/agent/controller.d.ts +75 -0
  4. package/dist/agent/controller.js +128 -1
  5. package/dist/agent/governance-wiring.js +2 -0
  6. package/dist/agent/headless.js +24 -3
  7. package/dist/agent/reconnect-memory.d.ts +68 -0
  8. package/dist/agent/reconnect-memory.js +82 -0
  9. package/dist/app/App.js +116 -3
  10. package/dist/app/use-governance-rounds.d.ts +44 -0
  11. package/dist/app/use-governance-rounds.js +71 -0
  12. package/dist/commands/builtins.js +8 -72
  13. package/dist/commands/catalog.js +1 -1
  14. package/dist/commands/governance-command.js +45 -3
  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 +2 -2
  18. package/dist/config/cli-commands.js +54 -0
  19. package/dist/exec/events.d.ts +12 -0
  20. package/dist/exec/runner.js +6 -0
  21. package/dist/gene/cli-commands.js +30 -1
  22. package/dist/gene/command-report.js +5 -1
  23. package/dist/gene/curator/budget.d.ts +24 -1
  24. package/dist/gene/curator/budget.js +67 -14
  25. package/dist/gene/curator/curator.d.ts +10 -0
  26. package/dist/gene/curator/curator.js +35 -5
  27. package/dist/gene/curator/task-context.d.ts +8 -0
  28. package/dist/gene/curator/task-context.js +10 -0
  29. package/dist/gene/curator/task-runner.js +16 -5
  30. package/dist/gene/hub.d.ts +10 -1
  31. package/dist/gene/hub.js +30 -7
  32. package/dist/gene/import-plan.js +8 -5
  33. package/dist/gene/learn/learner.js +7 -3
  34. package/dist/gene/queue.d.ts +8 -0
  35. package/dist/gene/queue.js +38 -2
  36. package/dist/governance/copy.d.ts +8 -0
  37. package/dist/governance/copy.js +16 -1
  38. package/dist/governance/engine/cards.js +9 -1
  39. package/dist/governance/engine/digest.js +6 -2
  40. package/dist/governance/engine/engine-core.d.ts +12 -0
  41. package/dist/governance/engine/engine-core.js +29 -0
  42. package/dist/governance/engine/engine.d.ts +1 -0
  43. package/dist/governance/engine/engine.js +4 -1
  44. package/dist/governance/engine/lifecycle.d.ts +36 -1
  45. package/dist/governance/engine/lifecycle.js +185 -2
  46. package/dist/governance/engine/report.d.ts +8 -0
  47. package/dist/governance/engine/report.js +17 -0
  48. package/dist/governance/engine/stage-runner.js +48 -3
  49. package/dist/governance/engine/state-machine.d.ts +27 -2
  50. package/dist/governance/engine/state-machine.js +146 -20
  51. package/dist/governance/prompts/orchestrator-block.d.ts +2 -0
  52. package/dist/governance/prompts/orchestrator-block.js +25 -0
  53. package/dist/governance/store/events-log.d.ts +4 -2
  54. package/dist/governance/store/events-log.js +4 -2
  55. package/dist/governance/tools/inspector-tools.js +4 -0
  56. package/dist/governance/tools/lead-tools.d.ts +1 -1
  57. package/dist/governance/tools/lead-tools.js +14 -2
  58. package/dist/host/controller-factory.js +6 -0
  59. package/dist/logging/install.d.ts +3 -0
  60. package/dist/logging/install.js +8 -0
  61. package/dist/session/persist.js +8 -1
  62. package/dist/session/validate-session.js +15 -5
  63. package/package.json +3 -3
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Sticky starting tier — remember the tier a request just recovered in
3
+ * (tiered-reconnect §4.9, step 8 of the implementation order).
4
+ *
5
+ * THE PROBLEM IT SOLVES, in one sentence: on a link that is down for twenty minutes,
6
+ * every NEW request would spend its first four minutes re-learning what the previous
7
+ * request already proved — that the fast ladder does not work right now. A turn can
8
+ * contain five requests, so that is twenty minutes of waiting for a fact we knew.
9
+ *
10
+ * PROCESS-LOCAL BY DESIGN. Nothing here is persisted and nothing is a `ViewState`
11
+ * field: a tier is a property of the network at this moment, and a stale one loaded
12
+ * from disk tomorrow would be worse than no memory at all (the same argument
13
+ * `RetryPolicy` makes about its own, non-persisted state).
14
+ *
15
+ * OFF BY DEFAULT (`retry.stickyRung: false`), and the switch is checked by the
16
+ * caller, so a session that never flips it is byte-identical to one built before
17
+ * this module existed.
18
+ *
19
+ * NO DEPENDENCIES, NO TIMERS, NO I/O: `now` is injected, exactly like `TodoStore`'s
20
+ * clock, so the window can be tested without waiting two minutes.
21
+ */
22
+ import type { RetryTierId } from '@aragon-agent/core';
23
+ /** How long a recovery keeps steering new requests at the slow tier. */
24
+ export declare const RECONNECT_MEMORY: {
25
+ /**
26
+ * TWO MINUTES. Long enough to cover the next request of the same turn and the
27
+ * user reading one answer; short enough that a network which came back from a
28
+ * lunch break does not silently skip the fast ladder.
29
+ */
30
+ readonly stickyMs: 120000;
31
+ };
32
+ /** Which provider/model a memory belongs to; a change invalidates it. */
33
+ export interface ReconnectRef {
34
+ providerId: string;
35
+ modelId: string;
36
+ }
37
+ /**
38
+ * One record, and the two questions asked of it.
39
+ *
40
+ * A CLASS rather than two module-level functions so a test — and, one day, a second
41
+ * controller in one process (the host spawns several) — cannot share state by
42
+ * accident. Mutable on purpose: this is a memo, and a "pure" version would have to
43
+ * thread a value through the request path, which is precisely where the escalation
44
+ * policy travels and where a second source of truth would be born.
45
+ */
46
+ export declare class ReconnectMemory {
47
+ private readonly now;
48
+ private last;
49
+ constructor(now?: () => number);
50
+ /**
51
+ * Record that a request that had retried at least once finally got its answer.
52
+ *
53
+ * `rung === 1` CLEARS the memory rather than storing tier 1: a recovery during the
54
+ * fast ladder is evidence that the network is fine, and leaving an older "we are
55
+ * in the slow tier" record in place would overrule the fresher evidence.
56
+ */
57
+ recordRecovery(ref: ReconnectRef, rung: RetryTierId): void;
58
+ /**
59
+ * The tier a new request should start from, or `undefined` for the default (1).
60
+ *
61
+ * Returns `undefined` for a different provider/model, for a record older than
62
+ * `stickyMs`, and for no record at all — every one of which means "behave exactly
63
+ * as you would without this feature".
64
+ */
65
+ startRungFor(ref: ReconnectRef): RetryTierId | undefined;
66
+ /** Forget everything (a new conversation, or a provider switch the user forced). */
67
+ reset(): void;
68
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Sticky starting tier — remember the tier a request just recovered in
3
+ * (tiered-reconnect §4.9, step 8 of the implementation order).
4
+ *
5
+ * THE PROBLEM IT SOLVES, in one sentence: on a link that is down for twenty minutes,
6
+ * every NEW request would spend its first four minutes re-learning what the previous
7
+ * request already proved — that the fast ladder does not work right now. A turn can
8
+ * contain five requests, so that is twenty minutes of waiting for a fact we knew.
9
+ *
10
+ * PROCESS-LOCAL BY DESIGN. Nothing here is persisted and nothing is a `ViewState`
11
+ * field: a tier is a property of the network at this moment, and a stale one loaded
12
+ * from disk tomorrow would be worse than no memory at all (the same argument
13
+ * `RetryPolicy` makes about its own, non-persisted state).
14
+ *
15
+ * OFF BY DEFAULT (`retry.stickyRung: false`), and the switch is checked by the
16
+ * caller, so a session that never flips it is byte-identical to one built before
17
+ * this module existed.
18
+ *
19
+ * NO DEPENDENCIES, NO TIMERS, NO I/O: `now` is injected, exactly like `TodoStore`'s
20
+ * clock, so the window can be tested without waiting two minutes.
21
+ */
22
+ /** How long a recovery keeps steering new requests at the slow tier. */
23
+ export const RECONNECT_MEMORY = {
24
+ /**
25
+ * TWO MINUTES. Long enough to cover the next request of the same turn and the
26
+ * user reading one answer; short enough that a network which came back from a
27
+ * lunch break does not silently skip the fast ladder.
28
+ */
29
+ stickyMs: 120_000,
30
+ };
31
+ /**
32
+ * One record, and the two questions asked of it.
33
+ *
34
+ * A CLASS rather than two module-level functions so a test — and, one day, a second
35
+ * controller in one process (the host spawns several) — cannot share state by
36
+ * accident. Mutable on purpose: this is a memo, and a "pure" version would have to
37
+ * thread a value through the request path, which is precisely where the escalation
38
+ * policy travels and where a second source of truth would be born.
39
+ */
40
+ export class ReconnectMemory {
41
+ now;
42
+ last = null;
43
+ constructor(now = Date.now) {
44
+ this.now = now;
45
+ }
46
+ /**
47
+ * Record that a request that had retried at least once finally got its answer.
48
+ *
49
+ * `rung === 1` CLEARS the memory rather than storing tier 1: a recovery during the
50
+ * fast ladder is evidence that the network is fine, and leaving an older "we are
51
+ * in the slow tier" record in place would overrule the fresher evidence.
52
+ */
53
+ recordRecovery(ref, rung) {
54
+ if (rung <= 1) {
55
+ this.last = null;
56
+ return;
57
+ }
58
+ this.last = { providerId: ref.providerId, modelId: ref.modelId, rung, at: this.now() };
59
+ }
60
+ /**
61
+ * The tier a new request should start from, or `undefined` for the default (1).
62
+ *
63
+ * Returns `undefined` for a different provider/model, for a record older than
64
+ * `stickyMs`, and for no record at all — every one of which means "behave exactly
65
+ * as you would without this feature".
66
+ */
67
+ startRungFor(ref) {
68
+ const memory = this.last;
69
+ if (!memory)
70
+ return undefined;
71
+ if (memory.providerId !== ref.providerId || memory.modelId !== ref.modelId) {
72
+ return undefined;
73
+ }
74
+ if (this.now() - memory.at > RECONNECT_MEMORY.stickyMs)
75
+ return undefined;
76
+ return memory.rung;
77
+ }
78
+ /** Forget everything (a new conversation, or a provider switch the user forced). */
79
+ reset() {
80
+ this.last = null;
81
+ }
82
+ }
package/dist/app/App.js CHANGED
@@ -64,6 +64,7 @@ import { advanceBudget, chargeResume, decideFollowThrough, emptyBudget, emptyRes
64
64
  // no policy. Imported beside the todo decision it shares one timer with.
65
65
  import { buildDispatchNudge, decideForcedDispatch, FORCED_NUDGE_NOTICE } from '../team/dispatch-gate.js';
66
66
  import { teamToastTtlMs, useTeamMode } from './use-team-mode.js';
67
+ import { useGovernanceRounds } from './use-governance-rounds.js';
67
68
  // THE RED TEAM SWITCH (red-team-security-mode 4.3 / 4.8): Ctrl+R, the waiver flow, the
68
69
  // deferred arming and the banner. Same adapter shape as `use-team-mode` above.
69
70
  import { redTeamToastTtlMs, useRedTeamMode, } from './use-redteam-mode.js';
@@ -121,6 +122,7 @@ import { PlanReviewOverlay } from '@aragon-agent/tui/ui/overlays/PlanReviewOverl
121
122
  import { parseSlashInput, runSlashInput, } from '../commands/registry.js';
122
123
  import { buildInvocationCard, invocationCardsEnabled } from '@aragon-agent/tui/model/agent/invocation-card';
123
124
  import { createCommandRegistry } from '../commands/create-registry.js';
125
+ import { retryLadderShape } from '../commands/retry-command.js';
124
126
  import { MODE_TOGGLE_KEYS } from '@aragon-agent/tui/model/agent/agent-mode';
125
127
  import { createClipboardCoordinator } from '@aragon-agent/tui/ui/clipboard-task';
126
128
  import { QueuePanel } from '@aragon-agent/tui/ui/QueuePanel';
@@ -701,6 +703,15 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
701
703
  });
702
704
  const teamKeysRef = useRef(teamKeys);
703
705
  teamKeysRef.current = teamKeys;
706
+ // THE ROUND BUDGET'S KEYS (governance-round-budget D-9): `Ctrl+Up / Ctrl+Down` in a
707
+ // governance posture with NO live run, otherwise team size. `planRoundKeyTarget` decides,
708
+ // and `handleKey` returns false for 'team', so the branch below runs unchanged.
709
+ const governanceRoundsKeys = useGovernanceRounds({
710
+ controller,
711
+ canAct: () => !stateRef.current.overlay,
712
+ persistConfig: (patch) => persistConfig(patch),
713
+ pushToast: (level, text) => dispatch({ type: 'pushToast', level, text, ttlMs: teamToastTtlMs(level) }),
714
+ });
704
715
  // THE RED TEAM SWITCH (red-team-security-mode): Ctrl+R, the waiver flow and the deferred
705
716
  // arming at `agent_end`. Same shape as `teamKeys` above, same reason: the controller owns the
706
717
  // state, this hook is the adapter, and `App` only routes keys and props.
@@ -882,6 +893,23 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
882
893
  * twenty lines up.
883
894
  */
884
895
  const submitRef = useRef(() => ({ accepted: false }));
896
+ /**
897
+ * A message that ARRIVED WHILE THE LADDER WAS WAITING IN TIER 2 OR 3
898
+ * (tiered-reconnect §4.7 / P1-7), parked here for the `afterAgentEnd` hook to
899
+ * send once the aborted run has finished unwinding.
900
+ *
901
+ * WHY A REF AND A TWO-STEP HAND-OFF: `submitMessage` cannot send while a request
902
+ * is in flight — it routes through `queueUserMessage` → `agent.steer`, which
903
+ * neither aborts nor delivers, and `acceptSteering` only drains at the TOP of a
904
+ * loop iteration. With a five-minute wait in progress that means the user's
905
+ * message would sit in the queue until they typed again. So the wait is aborted
906
+ * and the message is RE-SENT by `afterAgentEnd`, which is the one hook that runs
907
+ * exactly once per run and after the engine is idle.
908
+ *
909
+ * AT MOST ONE, and cleared before the re-send: a second `agent_end` must not
910
+ * deliver the same text twice (AC-23b).
911
+ */
912
+ const pendingAfterAbort = useRef(null);
885
913
  /**
886
914
  * THE SINGLE SETTLE PATH for a human request. Idempotent per entry, and it
887
915
  * clears the overlay as its last act.
@@ -995,6 +1023,29 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
995
1023
  // Without it, an aborted run leaves a plan card on screen whose `a` key
996
1024
  // silently flips the session to build, with no visible cause.
997
1025
  cancelPendingHuman();
1026
+ // THE MESSAGE THAT STOPPED THE WAIT GOES OUT HERE (§4.7 / P1-7). This is
1027
+ // the one hook that runs exactly once per run, after the engine is idle —
1028
+ // which is why the park-and-resend pair is the whole implementation, with
1029
+ // no second drain mechanism anywhere.
1030
+ //
1031
+ // CLEARED BEFORE THE RE-SEND, and the order matters: `submitMessage` below
1032
+ // can start a NEW run that eventually reaches this hook again, and a value
1033
+ // still in the ref would deliver the same text a second time (AC-23b).
1034
+ const parked = pendingAfterAbort.current;
1035
+ if (parked) {
1036
+ pendingAfterAbort.current = null;
1037
+ // `userInitiated: true` was forced at park time: the user typed this, so
1038
+ // it belongs in prompt history whether or not the re-send happens inside
1039
+ // a hook.
1040
+ submitRef.current(parked.text, parked.opts);
1041
+ // NOTHING BELOW APPLIES TO IT. The run that just ended was aborted by this
1042
+ // very message, and every branch from here down (follow-through, the
1043
+ // forced-dispatch gate, a resume) would be talking about a turn the user
1044
+ // already replaced. No bookkeeping is needed for the same reason: the
1045
+ // re-send above went through `submitMessage`, which resets
1046
+ // `endReasonRef` and refills the resume counters itself.
1047
+ return;
1048
+ }
998
1049
  // --- Follow-through (todo-plan-followthrough §3.4). ------------------
999
1050
  //
1000
1051
  // Round 1 printed one notice here and stopped, under a good argument
@@ -2258,6 +2309,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2258
2309
  resetInterrupt();
2259
2310
  cancelFollowThrough();
2260
2311
  autoContinuationRef.current = false;
2312
+ // A message parked behind an aborted tier-2/3 wait belongs to the
2313
+ // conversation that is ending here; delivering it into the next one would be
2314
+ // sending text the user never aimed at it.
2315
+ pendingAfterAbort.current = null;
2261
2316
  if (wasStarting) {
2262
2317
  dispatch({ type: 'abortMark' });
2263
2318
  dispatch({ type: 'runEnd' });
@@ -2433,6 +2488,27 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2433
2488
  : undefined;
2434
2489
  const shown = card?.commandLine ?? message;
2435
2490
  if (interactionPhase.current === 'running' || controller.isCompactionBusy?.()) {
2491
+ // TIER 2/3 WAIT: THE MESSAGE ENDS THE WAIT (§4.7 / D-14). Checked BEFORE the
2492
+ // steering branch because that branch does not deliver anything until the
2493
+ // next loop iteration — and the next iteration is up to five minutes away.
2494
+ //
2495
+ // TIER 1 IS DELIBERATELY EXCLUDED: its waits are seconds long, the steering
2496
+ // queue is exactly the right answer there, and changing that behaviour would
2497
+ // make an ordinary fast retry swallow the user's message.
2498
+ const live = stateRef.current.retry;
2499
+ if (live?.phase === 'waiting' && (live.tier ?? 1) >= 2) {
2500
+ pendingAfterAbort.current = { text: message, opts: { ...opts, userInitiated: true } };
2501
+ // The card, the notice and the transcript all read the SAME decision, so
2502
+ // the message is not "sent" twice: `afterAgentEnd` re-sends the parked text
2503
+ // and this notice is what tells the user it happened (Q-3).
2504
+ dispatch({
2505
+ type: 'notice',
2506
+ level: 'info',
2507
+ text: 'Stopped waiting for the provider to reconnect; sending your message now.',
2508
+ });
2509
+ controller.abort();
2510
+ return { accepted: true };
2511
+ }
2436
2512
  try {
2437
2513
  const queueId = controller.queueUserMessage(message);
2438
2514
  dispatch({ type: 'steerQueued', queueId, text: shown, ...(card ? { invocation: card } : {}) });
@@ -3122,6 +3198,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3122
3198
  // which had no overlay guard; and the help/plan/queue overlays consume Ctrl+Up/Down in
3123
3199
  // their own paging block earlier, which is the intended precedence. `PromptInput` ignores
3124
3200
  // both keys so a draft's history and a popup's highlight never also move (I-6).
3201
+ // Governance rounds outrank team size ONLY in a governance posture with no live run
3202
+ // (round-budget D-9); every other state answers 'team' and falls through to the line
3203
+ // below, so the team keys behave exactly as they always did.
3204
+ if (governanceRoundsKeys.handleKey(input, key))
3205
+ return;
3125
3206
  if (teamKeys.handleKey(input, key))
3126
3207
  return;
3127
3208
  // Ctrl+R IS THE RED TEAM SWITCH (red-team-security-mode D-1), and the repaint moved to
@@ -3369,6 +3450,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3369
3450
  resetInterrupt();
3370
3451
  autoContinuationRef.current = false;
3371
3452
  metrics.current = freezeRunMetrics(metrics.current, Date.now());
3453
+ // A forced stop DROPS the run: `afterAgentEnd` never fires for it, so a parked
3454
+ // message would be delivered at the end of some LATER run, saying "sending your
3455
+ // message now" about a turn the user already killed.
3456
+ pendingAfterAbort.current = null;
3372
3457
  if (next.action === 'force-stop')
3373
3458
  controller.forceStop();
3374
3459
  else
@@ -3657,7 +3742,14 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3657
3742
  // second scroll authority and no geometry change in `ScrollViewport`.
3658
3743
  overlay === 'shortcuts' ? (_jsx(ShortcutPanel, { isActive: !tooSmall, cols: viewCols, maxRows: overlayMaxRows, theme: theme, caps: caps, native: native, running: running,
3659
3744
  // Only the team-size row reads it: dim until team mode is on (team-mode-toggle-keys D-13).
3660
- team: { available: teamKeys.view.available, on: teamKeys.view.on }, query: shortcutQuery, task: taskSectionFrom({
3745
+ team: { available: teamKeys.view.available, on: teamKeys.view.on }, ...(typeof controller.isGovernanceAvailable === 'function'
3746
+ ? {
3747
+ governance: {
3748
+ available: controller.isGovernanceAvailable().ok,
3749
+ on: isGovernancePosture(controller.getPosture()),
3750
+ },
3751
+ }
3752
+ : {}), query: shortcutQuery, task: taskSectionFrom({
3661
3753
  view: state.taskSummary,
3662
3754
  pending: state.taskSummaryPending,
3663
3755
  enabled: cfg.taskSummary?.enabled !== false,
@@ -3723,7 +3815,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3723
3815
  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 }),
3724
3816
  // Read from `cfg` (render scope, re-read every frame), so `/retry off`
3725
3817
  // while the screen is open shows the new value on the next paint.
3726
- retrySummary: cfg.retry.enabled && cfg.retry.maxRetries > 0 ? String(cfg.retry.maxRetries) : 'off' })) : overlay === 'agents' ? (
3818
+ // THE LADDER IS PART OF THE ANSWER (AC-17): `API retries: 10` would keep
3819
+ // describing the old behaviour, and the six new keys are invisible there.
3820
+ // Every number still comes from `cfg`, so `/retry slow 30` repaints this row.
3821
+ retrySummary: retryLadderShape(cfg.retry, { headless: false }) })) : overlay === 'agents' ? (
3727
3822
  // THE BRANCH AND THE `Overlay` MEMBER SHIP TOGETHER (R-11): a missing branch is not
3728
3823
  // a type error, it is a SILENT BLANK FRAME, because `active={overlay === null}` has
3729
3824
  // already disabled the transcript underneath.
@@ -3927,7 +4022,14 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3927
4022
  // partially stale. The window and its `known` flag now travel INSIDE
3928
4023
  // it, resolved by the meter - which is what makes the user's
3929
4024
  // `contextWindow` override reach the bar.
3930
- context: state.context, status: state.status, elapsedMs: elapsedMs, thinkingLevel: cfg.thinkingLevel, tokPerSec: tokPerSec, theme: theme, caps: caps, scrolledLines: scrolledLines, redrawNonce: redrawNonce, agentMode: state.posture, pendingAgentMode: state.pendingPosture, governance: state.governance, ...(teamKeys.view.available ? { team: teamStatusFromView(teamKeys.view) } : {}), ecoRung: governor.rung, ...(state.team
4025
+ context: state.context, status: state.status, elapsedMs: elapsedMs, thinkingLevel: cfg.thinkingLevel, tokPerSec: tokPerSec, theme: theme, caps: caps, scrolledLines: scrolledLines, redrawNonce: redrawNonce, agentMode: state.posture, pendingAgentMode: state.pendingPosture, governance: state.governance, ...(typeof controller.getGovernanceConfig === 'function'
4026
+ ? {
4027
+ governanceRounds: {
4028
+ budget: controller.getGovernanceConfig().rounds,
4029
+ run: state.governance ? state.governance.rounds : null,
4030
+ },
4031
+ }
4032
+ : {}), ...(teamKeys.view.available ? { team: teamStatusFromView(teamKeys.view) } : {}), ecoRung: governor.rung, ...(state.team
3931
4033
  ? {
3932
4034
  // `rosterCounts`, NOT a fourth inline phase filter (A-1): the chip and
3933
4035
  // the roster header above it must never disagree.
@@ -3968,6 +4070,17 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3968
4070
  // what keeps the chip and the transcript card showing the same
3969
4071
  // number without either of them owning a second clock.
3970
4072
  secondsLeft: secondsLeft(state.retry.resumeAt, Date.now()),
4073
+ // Tiered reconnect (§4.6.5). All three are optional and absent in
4074
+ // a session that never escalates, so the label stays exactly what
4075
+ // it was. No new timer: this render already runs at 1 Hz while a
4076
+ // retry is waiting.
4077
+ ...(state.retry.tier !== undefined ? { tier: state.retry.tier } : {}),
4078
+ ...(state.retry.tierCount !== undefined
4079
+ ? { tierCount: state.retry.tierCount }
4080
+ : {}),
4081
+ ...(state.retry.totalAttempts !== undefined
4082
+ ? { totalAttempts: state.retry.totalAttempts }
4083
+ : {}),
3971
4084
  },
3972
4085
  }
3973
4086
  : {}) }));
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `useGovernanceRounds`: the terminal's half of `Ctrl+Up / Ctrl+Down` for the round budget
3
+ * (governance-round-budget 4.5b).
4
+ *
5
+ * ASCII ONLY (`app/` is inside the glyph scanner's scope).
6
+ *
7
+ * A THIN ADAPTER, EXACTLY LIKE `use-team-mode`. Every decision lives elsewhere: the pure
8
+ * `planRoundKeyTarget` says whose key this is, and `controller.stepGovernanceRounds` steps
9
+ * the ladder and clamps. This hook only recognises the two byte forms of the key, asks, and
10
+ * reports what the controller adopted - plus the one thing the controller must NOT do,
11
+ * writing the value to `config.json`.
12
+ *
13
+ * EVERY CONTROLLER MEMBER IS OPTIONAL, for the reason `use-team-mode` records: several App
14
+ * tests hand `App` a hand-written controller stub, and an unconditional call would throw
15
+ * `is not a function` at render. A controller without them reads as "no round budget here":
16
+ * the key is not consumed and `Ctrl+Up/Down` keeps meaning team size.
17
+ */
18
+ import { type RoundKeyTarget } from '@aragon-agent/tui/model/governance/rounds-keys';
19
+ import type { RoundBudget } from '@aragon-agent/tui/model/governance/types';
20
+ import type { GovernanceConfig } from '@aragon-agent/tui/model/config/governance-config';
21
+ import type { AgentController } from '../agent/controller.js';
22
+ import type { TeamKeyLike, TeamToastLevel } from './use-team-mode.js';
23
+ /** The slice of the controller this hook reads. Structural, so a stub may implement none. */
24
+ export type GovernanceRoundsControllerPort = Partial<Pick<AgentController, 'stepGovernanceRounds' | 'getGovernanceConfig' | 'getGovernanceRounds' | 'getGovernanceRunStatus' | 'getPostureState' | 'isGovernanceAvailable'>>;
25
+ /** What the persisted patch needs; `App` supplies `updatePersistedConfig`. */
26
+ export type PersistGovernanceConfig = (patch: {
27
+ governance: GovernanceConfig;
28
+ }) => void;
29
+ export interface UseGovernanceRoundsArgs {
30
+ controller: GovernanceRoundsControllerPort;
31
+ /** False while an overlay owns the keyboard, exactly like the team keys (I-7). */
32
+ canAct(): boolean;
33
+ persistConfig: PersistGovernanceConfig;
34
+ pushToast(level: TeamToastLevel, text: string): void;
35
+ }
36
+ export interface UseGovernanceRounds {
37
+ /** True when the key was the round budget's and has been consumed. */
38
+ handleKey(input: string, key: TeamKeyLike): boolean;
39
+ /** The arbitration for the CURRENT state, exposed for tests and for `/keys`. */
40
+ target(): RoundKeyTarget;
41
+ }
42
+ export declare function useGovernanceRounds(args: UseGovernanceRoundsArgs): UseGovernanceRounds;
43
+ /** The value a `/gov rounds` read prints when nothing runs: the live config, formatted. */
44
+ export type GovernanceRoundsValue = RoundBudget;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `useGovernanceRounds`: the terminal's half of `Ctrl+Up / Ctrl+Down` for the round budget
3
+ * (governance-round-budget 4.5b).
4
+ *
5
+ * ASCII ONLY (`app/` is inside the glyph scanner's scope).
6
+ *
7
+ * A THIN ADAPTER, EXACTLY LIKE `use-team-mode`. Every decision lives elsewhere: the pure
8
+ * `planRoundKeyTarget` says whose key this is, and `controller.stepGovernanceRounds` steps
9
+ * the ladder and clamps. This hook only recognises the two byte forms of the key, asks, and
10
+ * reports what the controller adopted - plus the one thing the controller must NOT do,
11
+ * writing the value to `config.json`.
12
+ *
13
+ * EVERY CONTROLLER MEMBER IS OPTIONAL, for the reason `use-team-mode` records: several App
14
+ * tests hand `App` a hand-written controller stub, and an unconditional call would throw
15
+ * `is not a function` at render. A controller without them reads as "no round budget here":
16
+ * the key is not consumed and `Ctrl+Up/Down` keeps meaning team size.
17
+ */
18
+ import { useCallback, useRef } from 'react';
19
+ import { planRoundKeyTarget, } from '@aragon-agent/tui/model/governance/rounds-keys';
20
+ /** The two legacy byte forms some terminals deliver for Ctrl+Up / Ctrl+Down. */
21
+ const RAW_UP = '\x1b[1;5A';
22
+ const RAW_DOWN = '\x1b[1;5B';
23
+ function isStepKey(input, key) {
24
+ if (!key.ctrl || key.meta || key.shift)
25
+ return null;
26
+ if (key.upArrow || input === RAW_UP)
27
+ return 1;
28
+ if (key.downArrow || input === RAW_DOWN)
29
+ return -1;
30
+ return null;
31
+ }
32
+ /** The live arbitration inputs, read fresh on every press (never mirrored into state). */
33
+ function currentTarget(controller) {
34
+ return planRoundKeyTarget({
35
+ posture: (controller.getPostureState?.().effective ?? 'build'),
36
+ governanceAvailable: controller.isGovernanceAvailable?.().ok === true,
37
+ runStatus: (controller.getGovernanceRunStatus?.() ?? null),
38
+ // `arrowRounds` is the user's opt-out; a controller without a governance config
39
+ // answers `undefined` here, which reads as "off" - the key stays the team's.
40
+ preferRounds: controller.getGovernanceConfig?.().arrowRounds === true,
41
+ });
42
+ }
43
+ export function useGovernanceRounds(args) {
44
+ const argsRef = useRef(args);
45
+ argsRef.current = args;
46
+ const target = useCallback(() => currentTarget(argsRef.current.controller), []);
47
+ const handleKey = useCallback((input, key) => {
48
+ const live = argsRef.current;
49
+ if (!live.canAct())
50
+ return false;
51
+ const delta = isStepKey(input, key);
52
+ if (delta === null)
53
+ return false;
54
+ if (!live.controller.stepGovernanceRounds)
55
+ return false;
56
+ // `'team'` means "not mine": return false WITHOUT consuming, so App's team branch runs
57
+ // exactly as it did before this feature existed.
58
+ if (currentTarget(live.controller) !== 'rounds')
59
+ return false;
60
+ const stepped = live.controller.stepGovernanceRounds(delta);
61
+ // BOTH CALLS, AND NEITHER MAY BE DROPPED (the `/fast` rule): the setter makes this
62
+ // session honour the value, the persist survives a restart.
63
+ const config = live.controller.getGovernanceConfig?.();
64
+ if (config !== undefined)
65
+ live.persistConfig({ governance: config });
66
+ if (stepped.toast !== '')
67
+ live.pushToast('info', stepped.toast);
68
+ return true;
69
+ }, []);
70
+ return { handleKey, target };
71
+ }
@@ -8,7 +8,7 @@ import { modelSettingsResultMessage } from '../agent/model-profile-settings.js';
8
8
  import { existsSync, statSync } from 'node:fs';
9
9
  import { isAbsolute, resolve } from 'node:path';
10
10
  import { resolveOutputTokens } from '@aragon-agent/core';
11
- import { clampThinkingLevel, clampTheme, isAdapterProvider, isThemeName, parseMaxTokensInput, ADAPTER_PROVIDERS, DEFAULT_MAX_TOKENS, HARD_MAX_RETRIES, LEGACY_DARK_THEME, THEME_NAMES, THINKING_LEVELS, } from '@aragon-agent/tui/model/config/schema';
11
+ import { clampThinkingLevel, clampTheme, isAdapterProvider, isThemeName, parseMaxTokensInput, ADAPTER_PROVIDERS, DEFAULT_MAX_TOKENS, LEGACY_DARK_THEME, THEME_NAMES, THINKING_LEVELS, } from '@aragon-agent/tui/model/config/schema';
12
12
  import { isTerminalStatus } from '@aragon-agent/tui/model/proc/types';
13
13
  import { computeCost, formatCost, formatDuration, formatTokens } from '@aragon-agent/tui/model/agent/usage';
14
14
  import { mergePendingEntries } from '@aragon-agent/tui/model/agent/queued-messages';
@@ -24,6 +24,7 @@ import { runSessionCommand } from './session-command.js';
24
24
  import { runBranchCommand } from './branch-command.js';
25
25
  import { getLogger } from '../logging/logger.js';
26
26
  import { registerQueueCommand } from './queue-command.js';
27
+ import { registerRetryCommand } from './retry-command.js';
27
28
  import { registerPromptCommands } from '../prompts/command.js';
28
29
  import { registerMemoryCommands } from '../memory/command.js';
29
30
  import { registerGeneCommands } from '../gene/command.js';
@@ -828,77 +829,6 @@ const COMMANDS = [
828
829
  'clear|continue].');
829
830
  },
830
831
  },
831
- {
832
- name: 'retry',
833
- description: 'API retry: show | on | off | max <n>',
834
- /**
835
- * TWO CALLS FOR EVERY MUTATION, IN THIS ORDER, and neither is optional
836
- * (llm-api-retry-backoff §6.9 / §6.3):
837
- *
838
- * `setRetryConfig` replaces the policy on the live `ProviderRegistry`, so
839
- * the change takes effect in THIS session — and, because
840
- * `TeamRuntime` holds the same registry instance, for every
841
- * child too. Without it `/retry off` reports success and
842
- * changes nothing until the next launch.
843
- * `persistConfig` is what survives the session.
844
- *
845
- * UNLIKE `/team on` AND `/todo on` there is no "off for this session" branch:
846
- * retry is not a tool, nothing is registered at construction, and there is
847
- * therefore no state a flag could have made unreachable. `--no-retry` is a
848
- * starting value, not a permanent verdict.
849
- */
850
- run: (ctx) => {
851
- const arg = ctx.args.trim().toLowerCase();
852
- const [verb, value] = arg.split(/\s+/, 2);
853
- const controller = ctx.controller;
854
- if (!verb || verb === 'show' || verb === 'status') {
855
- const cfg = controller.getRetryConfig();
856
- if (!cfg.enabled || cfg.maxRetries <= 0) {
857
- ctx.notify('info', `API retry: off (maxRetries ${cfg.maxRetries}). Use /retry on or /retry max <n>.`);
858
- return;
859
- }
860
- ctx.notify('info', `API retry: on. Up to ${cfg.maxRetries} retries, ${cfg.initialDelayMs}ms doubling to ` +
861
- `${cfg.maxDelayMs}ms${cfg.jitter ? ' with jitter' : ''}, ` +
862
- `giving up after ${Math.round(cfg.maxElapsedMs / 1000)}s. ` +
863
- `Retry-After ${cfg.respectRetryAfter ? 'honoured' : 'ignored'}.`);
864
- return;
865
- }
866
- if (verb === 'on' || verb === 'off') {
867
- const enabled = verb === 'on';
868
- const applied = controller.setRetryConfig({ enabled });
869
- // A PARTIAL `retry` section, safe only because `updatePersistedConfig`
870
- // deep-merges it — the same contract `/team on` relies on.
871
- ctx.persistConfig({ retry: { enabled } });
872
- if (enabled && applied.maxRetries <= 0) {
873
- // Honest rather than cheerful: `enabled` is on but the count is the
874
- // kill switch, so nothing will actually retry.
875
- ctx.notify('warn', 'API retry enabled, but maxRetries is 0 - use /retry max <n>.');
876
- return;
877
- }
878
- ctx.toast('success', `API retry ${enabled ? 'on' : 'off'}.`);
879
- return;
880
- }
881
- if (verb === 'max') {
882
- // `Number.isFinite` and `>= 0`, NOT `> 0`: `0` is this key's documented
883
- // floor and its kill switch, and rejecting it here would make `/retry max 0`
884
- // the one documented control that does not work (R-16).
885
- const n = Number.parseInt(value ?? '', 10);
886
- if (!Number.isFinite(n) || n < 0) {
887
- ctx.notify('warn', `Usage: /retry max <0-${HARD_MAX_RETRIES}> (0 turns retry off)`);
888
- return;
889
- }
890
- const applied = controller.setRetryConfig({ maxRetries: n });
891
- ctx.persistConfig({
892
- retry: { maxRetries: applied.maxRetries },
893
- });
894
- ctx.toast('success', applied.maxRetries === 0
895
- ? 'API retry off (maxRetries 0).'
896
- : `API retry: up to ${applied.maxRetries} retries.`);
897
- return;
898
- }
899
- ctx.notify('warn', `Unknown argument "${verb}" - use /retry [show|on|off|max <n>].`);
900
- },
901
- },
902
832
  {
903
833
  // REGISTRATION ONLY. The body lives in `compaction/command.ts` because this
904
834
  // file is already past the 1000-line guideline and `/compact` has six forms
@@ -1414,6 +1344,9 @@ export function registerBuiltinCommands(registry) {
1414
1344
  // where the mode cannot run (`--no-redteam`) is exactly the session where a user types
1415
1345
  // `/redteam status` to find out why, so registering it may not read the config or the waiver.
1416
1346
  registerRedTeamCommand(registry);
1347
+ // `/retry` (tiered-reconnect §5.3). Unconditional: the session where the ladder
1348
+ // is off is exactly where a user types `/retry show` to find out why.
1349
+ registerRetryCommand(registry);
1417
1350
  // The keyboard drawer (`Ctrl+G` / `/keys`) and the task label (`/task`). Two
1418
1351
  // registrations, no new mechanism: `/keys` sets the panel's pre-filter and opens
1419
1352
  // the same overlay `Ctrl+G` opens, and `/task` reports what the header cell says.
@@ -1436,6 +1369,9 @@ export const BUILTIN_COMMAND_NAMES = ['queue', 'prompts', 'agents', 'subagent',
1436
1369
  // `redteam` joins the list for the reason `team` above records: its body lives in
1437
1370
  // `commands/redteam-command.ts`, so only this array can document it to the tests.
1438
1371
  'redteam',
1372
+ // `retry` joins them for the same reason: its body moved to
1373
+ // `commands/retry-command.ts`, so the `flatMap` below no longer sees it.
1374
+ 'retry',
1439
1375
  'keys', 'task',
1440
1376
  ...COMMANDS.flatMap((c) => [
1441
1377
  c.name,
@@ -20,7 +20,7 @@ export const BUILTIN_COMMAND_CATALOG = [
20
20
  { name: 'fast', aliases: [], description: 'Fast model tier: status | on | off | model <id> | provider <id> | same | review <n|off> | budget <n>' },
21
21
  { name: 'update', aliases: [], description: 'Auto-update: status | now | skip | off' },
22
22
  { name: 'todo', aliases: [], description: 'Todo planning: status | on | off | panel on|off | follow <mode> | acceptance [on|off|reset] | clear | continue' },
23
- { name: 'retry', aliases: [], description: 'API retry: show | on | off | max <n>' },
23
+ { name: 'retry', aliases: [], description: 'API retry: show | on | off | max <n> | reconnect <mode> | slow <secs> | hold <minutes>' },
24
24
  { name: 'compact', aliases: [], description: 'Context compaction: status | spend | budget | agent | prune | threshold | keep | history | show | <instructions>' },
25
25
  { name: 'context', aliases: [], description: 'Show context occupancy, the window it is measured against, and session spend' },
26
26
  { name: 'expand', aliases: [], description: 'Expand / collapse a recent tool card (default: last)' },