@aragon-agent/cli 0.6.64 → 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.
package/dist/app/App.js CHANGED
@@ -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';
@@ -882,6 +883,23 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
882
883
  * twenty lines up.
883
884
  */
884
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);
885
903
  /**
886
904
  * THE SINGLE SETTLE PATH for a human request. Idempotent per entry, and it
887
905
  * clears the overlay as its last act.
@@ -995,6 +1013,29 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
995
1013
  // Without it, an aborted run leaves a plan card on screen whose `a` key
996
1014
  // silently flips the session to build, with no visible cause.
997
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
+ }
998
1039
  // --- Follow-through (todo-plan-followthrough §3.4). ------------------
999
1040
  //
1000
1041
  // Round 1 printed one notice here and stopped, under a good argument
@@ -2258,6 +2299,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2258
2299
  resetInterrupt();
2259
2300
  cancelFollowThrough();
2260
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;
2261
2306
  if (wasStarting) {
2262
2307
  dispatch({ type: 'abortMark' });
2263
2308
  dispatch({ type: 'runEnd' });
@@ -2433,6 +2478,27 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2433
2478
  : undefined;
2434
2479
  const shown = card?.commandLine ?? message;
2435
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
+ }
2436
2502
  try {
2437
2503
  const queueId = controller.queueUserMessage(message);
2438
2504
  dispatch({ type: 'steerQueued', queueId, text: shown, ...(card ? { invocation: card } : {}) });
@@ -3369,6 +3435,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3369
3435
  resetInterrupt();
3370
3436
  autoContinuationRef.current = false;
3371
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;
3372
3442
  if (next.action === 'force-stop')
3373
3443
  controller.forceStop();
3374
3444
  else
@@ -3723,7 +3793,10 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3723
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 }),
3724
3794
  // Read from `cfg` (render scope, re-read every frame), so `/retry off`
3725
3795
  // 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' ? (
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' ? (
3727
3800
  // THE BRANCH AND THE `Overlay` MEMBER SHIP TOGETHER (R-11): a missing branch is not
3728
3801
  // a type error, it is a SILENT BLANK FRAME, because `active={overlay === null}` has
3729
3802
  // already disabled the transcript underneath.
@@ -3968,6 +4041,17 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3968
4041
  // what keeps the chip and the transcript card showing the same
3969
4042
  // number without either of them owning a second clock.
3970
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
+ : {}),
3971
4055
  },
3972
4056
  }
3973
4057
  : {}) }));
@@ -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)' },
@@ -0,0 +1,52 @@
1
+ /**
2
+ * `/retry` — the command BODY (tiered-reconnect §5.3 / P1-5).
3
+ *
4
+ * WHY THIS IS NOT IN `builtins.ts`: that file is ~1 600 lines, well past
5
+ * `CLAUDE.md`'s 1 000-line ceiling and already recorded as an exception, while its
6
+ * own `/compact` registration carries the sentence "the body lives in
7
+ * `compaction/command.ts` because this file is already past the 1000-line
8
+ * guideline". The six tier keys would have added ~90 lines there; they add none.
9
+ *
10
+ * TWO CALLS FOR EVERY MUTATION, IN THIS ORDER, and neither is optional:
11
+ *
12
+ * `setRetryConfig` replaces the policy on the live `ProviderRegistry`, so the
13
+ * change takes effect in THIS session — and, because
14
+ * `TeamRuntime` holds the same registry instance, for every
15
+ * child too. Without it `/retry off` reports success and
16
+ * changes nothing until the next launch.
17
+ * `persistConfig` is what survives the session.
18
+ *
19
+ * THE TIER KEYS DO NOT NEED THE FIRST CALL, and that asymmetry is worth knowing:
20
+ * the escalation policy is delivered by a CLOSURE the engine calls once per run
21
+ * (`AgentConfig.resolveEscalation`), so it is already live. `setRetryConfig` is
22
+ * still called for uniformity where the key overlaps with the fast policy, and the
23
+ * user-visible effect is the same either way: the next request uses the new shape.
24
+ */
25
+ import { type RetryConfig } from '@aragon-agent/tui/model/config/schema';
26
+ import type { CommandRegistry, CommandContext } from './registry.js';
27
+ /**
28
+ * The ladder summary line for `/retry show`.
29
+ *
30
+ * EVERY NUMBER IS READ FROM `cfg` (P2-6). A hardcoded `budget 240s` would become a
31
+ * lie the moment someone ran `/retry max 3`, and this line exists precisely to tell
32
+ * a user what their CURRENT configuration will do.
33
+ */
34
+ export declare function reconnectSummary(cfg: RetryConfig, opts: {
35
+ headless: boolean;
36
+ }): string;
37
+ /**
38
+ * The one-line ladder shape for a READ-ONLY surface (`10 + 10x1m + every 5m`).
39
+ *
40
+ * `reconnectSummary` is a sentence for `/retry show`, where a user asked how the
41
+ * ladder works and has room to read it. The settings screen prints this next to
42
+ * `API retries:` on a single truncated row, so it has to be a FORM, not prose - and
43
+ * it still reads every number from `cfg`, for the reason `reconnectSummary` does
44
+ * (P2-6, and AC-17's own wording).
45
+ */
46
+ export declare function retryLadderShape(cfg: RetryConfig, opts: {
47
+ headless: boolean;
48
+ }): string;
49
+ /** The `/retry` command body. Registered by `builtins.ts` with one line. */
50
+ export declare function runRetryCommand(ctx: CommandContext): void;
51
+ /** One-line registration, the `/compact` shape. */
52
+ export declare function registerRetryCommand(registry: CommandRegistry): void;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * `/retry` — the command BODY (tiered-reconnect §5.3 / P1-5).
3
+ *
4
+ * WHY THIS IS NOT IN `builtins.ts`: that file is ~1 600 lines, well past
5
+ * `CLAUDE.md`'s 1 000-line ceiling and already recorded as an exception, while its
6
+ * own `/compact` registration carries the sentence "the body lives in
7
+ * `compaction/command.ts` because this file is already past the 1000-line
8
+ * guideline". The six tier keys would have added ~90 lines there; they add none.
9
+ *
10
+ * TWO CALLS FOR EVERY MUTATION, IN THIS ORDER, and neither is optional:
11
+ *
12
+ * `setRetryConfig` replaces the policy on the live `ProviderRegistry`, so the
13
+ * change takes effect in THIS session — and, because
14
+ * `TeamRuntime` holds the same registry instance, for every
15
+ * child too. Without it `/retry off` reports success and
16
+ * changes nothing until the next launch.
17
+ * `persistConfig` is what survives the session.
18
+ *
19
+ * THE TIER KEYS DO NOT NEED THE FIRST CALL, and that asymmetry is worth knowing:
20
+ * the escalation policy is delivered by a CLOSURE the engine calls once per run
21
+ * (`AgentConfig.resolveEscalation`), so it is already live. `setRetryConfig` is
22
+ * still called for uniformity where the key overlaps with the fast policy, and the
23
+ * user-visible effect is the same either way: the next request uses the new shape.
24
+ */
25
+ import { clampRetryConfig, HARD_MAX_RETRIES, } from '@aragon-agent/tui/model/config/schema';
26
+ import { RECONNECT_MODES, isReconnectMode, resolveEscalationPolicy, } from '@aragon-agent/tui/model/config/reconnect';
27
+ /** `1s` / `30s` / `5m`: short, ASCII, and honest about the unit it dropped. */
28
+ function shortWait(ms) {
29
+ const seconds = Math.round(ms / 1000);
30
+ if (seconds < 60)
31
+ return `${seconds}s`;
32
+ const minutes = Math.floor(seconds / 60);
33
+ const rest = seconds % 60;
34
+ return rest === 0 ? `${minutes}m` : `${minutes}m${String(rest).padStart(2, '0')}s`;
35
+ }
36
+ /**
37
+ * The ladder summary line for `/retry show`.
38
+ *
39
+ * EVERY NUMBER IS READ FROM `cfg` (P2-6). A hardcoded `budget 240s` would become a
40
+ * lie the moment someone ran `/retry max 3`, and this line exists precisely to tell
41
+ * a user what their CURRENT configuration will do.
42
+ */
43
+ export function reconnectSummary(cfg, opts) {
44
+ const safe = clampRetryConfig(cfg);
45
+ if (!safe.enabled || safe.maxRetries <= 0)
46
+ return 'Reconnect: off (no fast retries configured).';
47
+ if (safe.reconnect === 'off') {
48
+ return `Reconnect: off (fast tier only).`;
49
+ }
50
+ const policy = resolveEscalationPolicy(safe, { headless: opts.headless });
51
+ if (!policy) {
52
+ return safe.slowAttempts === 0
53
+ ? 'Reconnect: off (slowAttempts 0).'
54
+ : 'Reconnect: off (no fast retries configured).';
55
+ }
56
+ const fast = `fast ${safe.maxRetries} (${shortWait(safe.initialDelayMs)}->${shortWait(safe.maxDelayMs)}, ` +
57
+ `budget ${shortWait(safe.maxElapsedMs)})`;
58
+ const slow = `then every ${shortWait(policy.slow.initialDelayMs)} x ${policy.slow.attempts}`;
59
+ // `bounded` has no hold tier, and saying "then every 5 minutes" there would be the
60
+ // same class of lie the notice avoids (P1-4).
61
+ const hold = policy.hold
62
+ ? `then every ${shortWait(policy.hold.initialDelayMs)} until it works`
63
+ : 'then it gives up';
64
+ const cap = policy.totalBudgetMs === undefined
65
+ ? 'no overall cap'
66
+ : `gives up entirely after ${shortWait(policy.totalBudgetMs)}`;
67
+ return `API reconnect: ${fast}, ${slow}, ${hold} (${cap}).`;
68
+ }
69
+ /**
70
+ * The one-line ladder shape for a READ-ONLY surface (`10 + 10x1m + every 5m`).
71
+ *
72
+ * `reconnectSummary` is a sentence for `/retry show`, where a user asked how the
73
+ * ladder works and has room to read it. The settings screen prints this next to
74
+ * `API retries:` on a single truncated row, so it has to be a FORM, not prose - and
75
+ * it still reads every number from `cfg`, for the reason `reconnectSummary` does
76
+ * (P2-6, and AC-17's own wording).
77
+ */
78
+ export function retryLadderShape(cfg, opts) {
79
+ const safe = clampRetryConfig(cfg);
80
+ if (!safe.enabled || safe.maxRetries <= 0)
81
+ return 'off';
82
+ const fast = String(safe.maxRetries);
83
+ const policy = resolveEscalationPolicy(safe, { headless: opts.headless });
84
+ if (!policy)
85
+ return `${fast} (no reconnect ladder)`;
86
+ const slow = `${policy.slow.attempts}x${shortWait(policy.slow.initialDelayMs)}`;
87
+ const hold = policy.hold
88
+ ? `every ${shortWait(policy.hold.initialDelayMs)}`
89
+ : 'stop';
90
+ const cap = policy.totalBudgetMs === undefined ? '' : `, cap ${shortWait(policy.totalBudgetMs)}`;
91
+ return `${fast} + ${slow} + ${hold}${cap}`;
92
+ }
93
+ function showReconnect(ctx) {
94
+ const cfg = ctx.controller.getRetryConfig();
95
+ ctx.notify('info', reconnectSummary(cfg, { headless: false }));
96
+ // The cost of an endless ladder is the one thing a user cannot infer from the
97
+ // shape, so it is said once, here, rather than only in the README (Q-5).
98
+ const policy = resolveEscalationPolicy(cfg, { headless: false });
99
+ if (policy?.hold) {
100
+ ctx.notify('info', 'Every attempt re-sends the request and is billed again; a long outage is charged ' +
101
+ 'close to full price (do not count on prompt caching). Set /retry hold 0 to cap it.');
102
+ }
103
+ }
104
+ /** `/retry hold <minutes>`; `0` = no cap, which is the documented "keep trying". */
105
+ function setHold(ctx, raw, cfg) {
106
+ const minutes = Number.parseInt(raw ?? '', 10);
107
+ if (!Number.isFinite(minutes) || minutes < 0) {
108
+ ctx.notify('warn', 'Usage: /retry hold <0-1440> (minutes; 0 = keep trying, no cap)');
109
+ return;
110
+ }
111
+ const applied = clampRetryConfig({ ...cfg, holdMaxMinutes: minutes });
112
+ ctx.controller.setRetryConfig({ holdMaxMinutes: applied.holdMaxMinutes });
113
+ ctx.persistConfig({ retry: { holdMaxMinutes: applied.holdMaxMinutes } });
114
+ ctx.toast('success', applied.holdMaxMinutes === 0
115
+ ? 'Reconnect: no overall cap - it keeps trying every 5 minutes.'
116
+ : `Reconnect: gives up entirely after ${applied.holdMaxMinutes} minutes ` +
117
+ '(including the first two tiers).');
118
+ }
119
+ /** `/retry slow <seconds>` and `/retry every <seconds>`: tier 2's interval. */
120
+ function setSlow(ctx, raw, cfg) {
121
+ const seconds = Number.parseInt(raw ?? '', 10);
122
+ if (!Number.isFinite(seconds) || seconds <= 0) {
123
+ ctx.notify('warn', 'Usage: /retry slow <15-900> (seconds between tier-2 attempts)');
124
+ return;
125
+ }
126
+ const applied = clampRetryConfig({ ...cfg, slowIntervalMs: seconds * 1000 });
127
+ ctx.controller.setRetryConfig({ slowIntervalMs: applied.slowIntervalMs });
128
+ ctx.persistConfig({ retry: { slowIntervalMs: applied.slowIntervalMs } });
129
+ ctx.toast('success', `Reconnect: one try every ${shortWait(applied.slowIntervalMs)}.`);
130
+ }
131
+ /** `/retry reconnect <auto|full|bounded|off>`. */
132
+ function setMode(ctx, raw, cfg) {
133
+ const value = (raw ?? '').toLowerCase();
134
+ if (!isReconnectMode(value)) {
135
+ ctx.notify('warn', `Usage: /retry reconnect <${RECONNECT_MODES.join('|')}>`);
136
+ return;
137
+ }
138
+ const applied = clampRetryConfig({ ...cfg, reconnect: value });
139
+ ctx.controller.setRetryConfig({ reconnect: applied.reconnect });
140
+ ctx.persistConfig({ retry: { reconnect: applied.reconnect } });
141
+ // `auto` is worth explaining rather than echoing: it is the only value whose
142
+ // meaning depends on who is running.
143
+ ctx.toast('success', applied.reconnect === 'auto'
144
+ ? 'Reconnect: auto (full ladder here, two tiers in -p / exec).'
145
+ : applied.reconnect === 'full'
146
+ ? 'Reconnect: full - fast, then every minute, then every 5 minutes until it works.'
147
+ : applied.reconnect === 'bounded'
148
+ ? 'Reconnect: bounded - fast, then every minute, then it stops.'
149
+ : 'Reconnect: off - fast retries only.');
150
+ }
151
+ /** The `/retry` command body. Registered by `builtins.ts` with one line. */
152
+ export function runRetryCommand(ctx) {
153
+ const arg = ctx.args.trim().toLowerCase();
154
+ const [verb, value] = arg.split(/\s+/, 2);
155
+ const controller = ctx.controller;
156
+ if (!verb || verb === 'show' || verb === 'status') {
157
+ const cfg = controller.getRetryConfig();
158
+ if (!cfg.enabled || cfg.maxRetries <= 0) {
159
+ ctx.notify('info', `API retry: off (maxRetries ${cfg.maxRetries}). Use /retry on or /retry max <n>.`);
160
+ return;
161
+ }
162
+ ctx.notify('info', `API retry: on. Up to ${cfg.maxRetries} retries, ${cfg.initialDelayMs}ms doubling to ` +
163
+ `${cfg.maxDelayMs}ms${cfg.jitter ? ' with jitter' : ''}, ` +
164
+ `giving up after ${Math.round(cfg.maxElapsedMs / 1000)}s. ` +
165
+ `Retry-After ${cfg.respectRetryAfter ? 'honoured' : 'ignored'}.`);
166
+ showReconnect(ctx);
167
+ return;
168
+ }
169
+ if (verb === 'on' || verb === 'off') {
170
+ const enabled = verb === 'on';
171
+ const applied = controller.setRetryConfig({ enabled });
172
+ // A PARTIAL `retry` section, safe only because `updatePersistedConfig`
173
+ // deep-merges it — the same contract `/team on` relies on.
174
+ ctx.persistConfig({ retry: { enabled } });
175
+ if (enabled && applied.maxRetries <= 0) {
176
+ // Honest rather than cheerful: `enabled` is on but the count is the
177
+ // kill switch, so nothing will actually retry.
178
+ ctx.notify('warn', 'API retry enabled, but maxRetries is 0 - use /retry max <n>.');
179
+ return;
180
+ }
181
+ ctx.toast('success', `API retry ${enabled ? 'on' : 'off'}.`);
182
+ return;
183
+ }
184
+ if (verb === 'max') {
185
+ // `Number.isFinite` and `>= 0`, NOT `> 0`: `0` is this key's documented floor
186
+ // and its kill switch, and rejecting it here would make `/retry max 0` the one
187
+ // documented control that does not work (R-16).
188
+ const n = Number.parseInt(value ?? '', 10);
189
+ if (!Number.isFinite(n) || n < 0) {
190
+ ctx.notify('warn', `Usage: /retry max <0-${HARD_MAX_RETRIES}> (0 turns retry off)`);
191
+ return;
192
+ }
193
+ const applied = controller.setRetryConfig({ maxRetries: n });
194
+ ctx.persistConfig({
195
+ retry: { maxRetries: applied.maxRetries },
196
+ });
197
+ ctx.toast('success', applied.maxRetries === 0
198
+ ? 'API retry off (maxRetries 0).'
199
+ : `API retry: up to ${applied.maxRetries} retries.`);
200
+ return;
201
+ }
202
+ const cfg = controller.getRetryConfig();
203
+ if (verb === 'reconnect') {
204
+ setMode(ctx, value, cfg);
205
+ return;
206
+ }
207
+ if (verb === 'slow' || verb === 'every') {
208
+ setSlow(ctx, value, cfg);
209
+ return;
210
+ }
211
+ if (verb === 'hold') {
212
+ setHold(ctx, value, cfg);
213
+ return;
214
+ }
215
+ ctx.notify('warn', `Unknown argument "${verb}" - use /retry [show|on|off|max <n>|` +
216
+ 'reconnect <auto|full|bounded|off>|slow <secs>|hold <minutes>].');
217
+ }
218
+ /** One-line registration, the `/compact` shape. */
219
+ export function registerRetryCommand(registry) {
220
+ registry.register({
221
+ name: 'retry',
222
+ description: 'API retry: show | on | off | max <n> | reconnect <mode> | slow <secs> | hold <minutes>',
223
+ run: (ctx) => runRetryCommand(ctx),
224
+ });
225
+ }
@@ -55,7 +55,7 @@ export declare const TASK_SUMMARY_CONFIG_SET_KEYS: readonly ["taskSummary.enable
55
55
  * switch falls through every case, writes nothing, and still prints
56
56
  * `Set retry.maxRetries = 0`.
57
57
  */
58
- export declare const RETRY_CONFIG_SET_KEYS: readonly ["retry.enabled", "retry.maxRetries", "retry.initialDelayMs", "retry.maxDelayMs", "retry.multiplier", "retry.jitter", "retry.respectRetryAfter", "retry.maxElapsedMs", "retry.onPartialStream", "retry.resumeRun", "retry.maxRunResumes", "retry.maxRunResumesPerPrompt"];
58
+ export declare const RETRY_CONFIG_SET_KEYS: readonly ["retry.enabled", "retry.maxRetries", "retry.initialDelayMs", "retry.maxDelayMs", "retry.multiplier", "retry.jitter", "retry.respectRetryAfter", "retry.maxElapsedMs", "retry.onPartialStream", "retry.resumeRun", "retry.maxRunResumes", "retry.maxRunResumesPerPrompt", "retry.reconnect", "retry.slowIntervalMs", "retry.slowAttempts", "retry.holdIntervalMs", "retry.holdMaxMinutes", "retry.stickyRung"];
59
59
  /**
60
60
  * Config keys under `fast.` that `aragon config set` accepts (fast-model-tier
61
61
  * §4.2).
@@ -104,6 +104,16 @@ export const RETRY_CONFIG_SET_KEYS = [
104
104
  'retry.resumeRun',
105
105
  'retry.maxRunResumes',
106
106
  'retry.maxRunResumesPerPrompt',
107
+ // TIERED RECONNECT (tiered-reconnect §5.2). Six keys, and §8.5's rule applies to
108
+ // all six: `retry-config.test.ts` asserts that EVERY key listed here can actually
109
+ // be patched into something non-empty, so declaring one without a `case` below is
110
+ // a red test rather than a key that silently writes nothing.
111
+ 'retry.reconnect',
112
+ 'retry.slowIntervalMs',
113
+ 'retry.slowAttempts',
114
+ 'retry.holdIntervalMs',
115
+ 'retry.holdMaxMinutes',
116
+ 'retry.stickyRung',
107
117
  ];
108
118
  /**
109
119
  * Config keys under `fast.` that `aragon config set` accepts (fast-model-tier
@@ -520,6 +530,24 @@ export function applyRetryConfigSet(key, value) {
520
530
  return patch(clampOne('maxRunResumes'));
521
531
  case 'retry.maxRunResumesPerPrompt':
522
532
  return patch(clampOne('maxRunResumesPerPrompt'));
533
+ // ---- tiered reconnect (§5.2) -----------------------------------------
534
+ // Every one of the six goes through `clampRetryConfig` for the reason this
535
+ // function's header records, and the two keys whose floor is 0 (`slowAttempts`,
536
+ // `holdMaxMinutes`) are exactly why `clampIntAllowingZero` exists: a plain
537
+ // `coercePositiveInt` would store "ten tries" for `slowAttempts 0` and "no cap"
538
+ // would become a cap.
539
+ case 'retry.reconnect':
540
+ return patch(clampOne('reconnect'));
541
+ case 'retry.slowIntervalMs':
542
+ return patch(clampOne('slowIntervalMs'));
543
+ case 'retry.slowAttempts':
544
+ return patch(clampOne('slowAttempts'));
545
+ case 'retry.holdIntervalMs':
546
+ return patch(clampOne('holdIntervalMs'));
547
+ case 'retry.holdMaxMinutes':
548
+ return patch(clampOne('holdMaxMinutes'));
549
+ case 'retry.stickyRung':
550
+ return patch({ stickyRung: isTrue(value) });
523
551
  default:
524
552
  return null;
525
553
  }
@@ -450,6 +450,18 @@ export interface ExecRetryEvent {
450
450
  maxRetries: number;
451
451
  errorType: string;
452
452
  delayMs: number;
453
+ /**
454
+ * Tiered reconnect (tiered-reconnect §5.4). THREE OPTIONAL FIELDS, and
455
+ * `EXEC_SCHEMA_VERSION` does not move: this file's rule is that adding a field or
456
+ * an event type never bumps it, and a consumer that ignores them sees exactly the
457
+ * payload it always saw.
458
+ *
459
+ * `attempt` keeps its PER-TIER meaning; `totalAttempts` is the cumulative one, so
460
+ * a machine consumer can report "13 retries" without knowing the ladder exists.
461
+ */
462
+ tier?: 1 | 2 | 3;
463
+ tierCount?: number;
464
+ totalAttempts?: number;
453
465
  }
454
466
  /**
455
467
  * The bridge control channel (headless-host-bridge §4.2.2).
@@ -1621,6 +1621,12 @@ export class ExecRunner {
1621
1621
  maxRetries: se.maxRetries,
1622
1622
  errorType: String(se.errorType),
1623
1623
  delayMs: se.delayMs,
1624
+ // Tiered reconnect (§5.4): pure pass-through, and absent when this host is
1625
+ // not escalating. `-p` / `exec` are bounded by default, so a machine
1626
+ // consumer here normally sees tiers 1 and 2 and never a 3.
1627
+ ...(se.tier !== undefined ? { tier: se.tier } : {}),
1628
+ ...(se.tierCount !== undefined ? { tierCount: se.tierCount } : {}),
1629
+ ...(se.totalAttempts !== undefined ? { totalAttempts: se.totalAttempts } : {}),
1624
1630
  });
1625
1631
  }
1626
1632
  }