@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
@@ -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"];
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).
@@ -101,6 +101,19 @@ export const RETRY_CONFIG_SET_KEYS = [
101
101
  'retry.respectRetryAfter',
102
102
  'retry.maxElapsedMs',
103
103
  'retry.onPartialStream',
104
+ 'retry.resumeRun',
105
+ 'retry.maxRunResumes',
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',
104
117
  ];
105
118
  /**
106
119
  * Config keys under `fast.` that `aragon config set` accepts (fast-model-tier
@@ -509,6 +522,32 @@ export function applyRetryConfigSet(key, value) {
509
522
  return patch(clampOne('maxElapsedMs'));
510
523
  case 'retry.onPartialStream':
511
524
  return patch({ onPartialStream: isTrue(value) });
525
+ case 'retry.resumeRun':
526
+ return patch({ resumeRun: isTrue(value) });
527
+ // Both counts go through the clamp, not `coercePositiveInt`: `0` is the kill
528
+ // switch and `coercePositiveInt(0)` would store the default instead.
529
+ case 'retry.maxRunResumes':
530
+ return patch(clampOne('maxRunResumes'));
531
+ case 'retry.maxRunResumesPerPrompt':
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) });
512
551
  default:
513
552
  return null;
514
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).
@@ -22,6 +22,7 @@ import { randomUUID } from 'node:crypto';
22
22
  import process from 'node:process';
23
23
  import { runHeadless } from '../agent/headless.js';
24
24
  import { computeCost } from '@aragon-agent/tui/model/agent/usage';
25
+ import { toRunResumePolicy } from '@aragon-agent/tui/model/config/schema';
25
26
  import { loadConfig } from '../config/load.js';
26
27
  import { latestSessionForCwd, readSessionFile, resolveSessionRef, resumedSessionId, sessionPathFor, tryAcquireSessionLock, writeSession, } from '../session/store.js';
27
28
  import { createEmitter } from './emitter.js';
@@ -689,6 +690,7 @@ async function drive(input, controller, runner) {
689
690
  const code = await runHeadless(controller, first, {
690
691
  quiet: options.quiet,
691
692
  followThrough: controller.getTodoConfig().followThrough,
693
+ resume: toRunResumePolicy(controller.getConfig().retry, { headless: true }),
692
694
  stdout: out,
693
695
  stderr: err,
694
696
  });
@@ -1165,7 +1165,16 @@ export class ExecRunner {
1165
1165
  budget,
1166
1166
  interactive: false,
1167
1167
  });
1168
- if (decision.kind === 'none')
1168
+ // `resume` IS NEVER REQUESTED HERE: this call passes no `resume` input, so the
1169
+ // table cannot return it. It is NOT wired on purpose
1170
+ // (team-idle-watchdog-dead-run, "issues found during implementation"): a death
1171
+ // with no assistant turn has already set `stopReason = 'error'` through
1172
+ // `recordError`, and the early `stopReason !== 'end_turn'` return above ends the
1173
+ // chain before this table is read - which also means the plan-driven recovery
1174
+ // below has never been reachable for such a death. Re-running from here would
1175
+ // first have to un-send the fatal `error` frame a failed stream has already
1176
+ // written, which is a change to the wire contract and not a host policy.
1177
+ if (decision.kind === 'none' || decision.kind === 'resume')
1169
1178
  return false;
1170
1179
  if (decision.kind === 'notify') {
1171
1180
  this.note(`[todo] ${decision.text}`);
@@ -1612,6 +1621,12 @@ export class ExecRunner {
1612
1621
  maxRetries: se.maxRetries,
1613
1622
  errorType: String(se.errorType),
1614
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 } : {}),
1615
1630
  });
1616
1631
  }
1617
1632
  }
@@ -186,9 +186,38 @@ async function listOrSearch(run, query) {
186
186
  const rows = await collectRows(run.manager, selection, ceiling);
187
187
  if (!rows.ok)
188
188
  return failed(run.io, rows);
189
- const text = rows.value.length === 0 ? 'No genes.' : rows.value.map((row) => row.line).join('\n');
189
+ const text = rows.value.length === 0 ? await emptyText(run, selection, query) : rows.value.map(rowText).join('\n');
190
190
  return print(run, { genes: rows.value.map(rowJson), total: rows.value.length }, text);
191
191
  }
192
+ /**
193
+ * A row's text line. `line` carries the markers but not the lifecycle status, so a rejected gene
194
+ * and a published one look the same under `--status all`; any status other than published is said.
195
+ */
196
+ function rowText(row) {
197
+ return row.status === 'published' ? row.line : `${row.line} (${row.status})`;
198
+ }
199
+ /**
200
+ * "No genes." is only true when the library has none. The default selection is this project's view,
201
+ * published only, so an empty answer may just mean the genes are elsewhere or not published; one
202
+ * more look at the whole library says which, and the text names the command that shows them.
203
+ */
204
+ async function emptyText(run, selection, query) {
205
+ // A search that found nothing says so; the hint below is for a plain listing.
206
+ if (query !== undefined)
207
+ return 'No genes.';
208
+ const { type } = selection.filter;
209
+ const whole = await run.manager.list({
210
+ target: { kind: 'allProjects' },
211
+ filter: type === undefined ? {} : { type },
212
+ limit: 1,
213
+ });
214
+ if (!whole.ok || whole.value.rows.length === 0)
215
+ return 'No genes.';
216
+ return [
217
+ 'No genes match, but the library holds others (in other projects, or not published).',
218
+ 'Show everything: aragon gene list --scope all --status all',
219
+ ].join('\n');
220
+ }
192
221
  function runList(run) {
193
222
  return listOrSearch(run);
194
223
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { describeGeneError, pausedReasonCopy, runEventLabel } from '@aragon-agent/tui/model/gene/copy';
13
13
  import { stripHiddenControls } from '@aragon-agent/tui/model/gene/escape';
14
+ import { isBudgetEnforced } from './curator/budget.js';
14
15
  export function clean(text) {
15
16
  return stripHiddenControls(text);
16
17
  }
@@ -76,7 +77,10 @@ export function statusLines(view, facts) {
76
77
  const lines = [switchLine(view), ...libraryLines(view), contextLine(view), ...workerLines(view)];
77
78
  if (facts.config !== undefined) {
78
79
  const budget = facts.config.dailyTokens;
79
- lines.push(`Tokens: ${facts.tokensToday} of ${budget} used in the last 24 hours.`);
80
+ // Metering is the default; the ceiling is only worth showing when it is real (enforced, or 0 = off).
81
+ lines.push(isBudgetEnforced() || budget <= 0
82
+ ? `Tokens: ${facts.tokensToday} of ${budget} used in the last 24 hours.`
83
+ : `Tokens: ${facts.tokensToday} used in the last 24 hours (no daily limit).`);
80
84
  lines.push(`Holdout: ${facts.config.holdoutPercent}% of runs deliberately skip the library.`);
81
85
  }
82
86
  if (view.last !== undefined) {
@@ -12,6 +12,30 @@ export function validateActorOf(actor) {
12
12
  return 'user';
13
13
  return actor.kind === 'curator' ? 'agent' : 'import';
14
14
  }
15
+ /** How many content issues one refusal lists, and how long the list may get. */
16
+ const MAX_LISTED_ISSUES = 6;
17
+ const MAX_LISTED_ISSUES_CHARS = 600;
18
+ /**
19
+ * Every content issue a draft has, as `path: reason; path: reason` (gene-bank-never-publishes-3, R-1).
20
+ *
21
+ * WHY ALL OF THEM. The refusal used to carry only the FIRST issue's category, so a skill draft
22
+ * missing four things was told "a required section is missing" four times in a row, one fix per
23
+ * round trip, and a curator task that spends a 9-call loop per attempt ran out of budget before it
24
+ * ran out of fixes. Listing them lets one rewrite satisfy the whole contract.
25
+ *
26
+ * WHAT IT MAY CARRY. Only `path` and the validators' own closed vocabulary: limits, section names,
27
+ * rule ids and gene ids. No `bad(...)` in `validate-*.ts` interpolates gene or evidence text, so
28
+ * the list is as safe as the single message it replaces (I-19); `no-body-in-logs.test.ts` and the
29
+ * `poison-untrusted` case keep it so.
30
+ */
31
+ function listContentIssues(issues) {
32
+ const lines = issues
33
+ .filter((i) => i.code === 'GENE_INVALID_CONTENT')
34
+ .slice(0, MAX_LISTED_ISSUES)
35
+ .map((i) => `${i.path}: ${i.message}`);
36
+ const joined = lines.join('; ');
37
+ return joined.length <= MAX_LISTED_ISSUES_CHARS ? joined : `${joined.slice(0, MAX_LISTED_ISSUES_CHARS - 3)}...`;
38
+ }
15
39
  /** A violation of the issue list that outranks the rest, then the first issue (11.3, 11.5). */
16
40
  export function issuesToFailure(issues) {
17
41
  const order = [
@@ -23,7 +47,9 @@ export function issuesToFailure(issues) {
23
47
  const chosen = outranking.find((i) => i !== undefined) ?? issues[0];
24
48
  if (chosen === undefined)
25
49
  return geneFail('GENE_INVALID_CONTENT', 'The content is not valid.');
26
- return geneFail(chosen.code, `${chosen.path}: ${chosen.message}`, chosen.detail);
50
+ // `code:detail` stays the FIRST issue's (every consumer keys on it); only the prose grows.
51
+ const message = chosen.code === 'GENE_INVALID_CONTENT' ? listContentIssues(issues) : `${chosen.path}: ${chosen.message}`;
52
+ return geneFail(chosen.code, message, chosen.detail);
27
53
  }
28
54
  /** Trimmed, English, length-bounded, secret-free (the `reason` of a version). */
29
55
  export function cleanReason(reason, knownSecrets) {