@aragon-agent/cli 0.6.61 → 0.6.63

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 (44) hide show
  1. package/README.md +99 -7
  2. package/dist/agent/headless.js +67 -6
  3. package/dist/agent/prompt-options.d.ts +7 -0
  4. package/dist/app/App.js +37 -5
  5. package/dist/commands/builtins.js +2 -1
  6. package/dist/commands/catalog.js +1 -1
  7. package/dist/compaction/archive.d.ts +27 -1
  8. package/dist/compaction/archive.js +8 -0
  9. package/dist/compaction/budget.d.ts +73 -0
  10. package/dist/compaction/budget.js +89 -0
  11. package/dist/compaction/child.js +6 -1
  12. package/dist/compaction/command.js +147 -1
  13. package/dist/compaction/compactor.d.ts +132 -15
  14. package/dist/compaction/compactor.js +288 -95
  15. package/dist/compaction/context-command.js +21 -0
  16. package/dist/compaction/memory-agent-prompt.d.ts +32 -0
  17. package/dist/compaction/memory-agent-prompt.js +76 -0
  18. package/dist/compaction/memory-agent-tools.d.ts +88 -0
  19. package/dist/compaction/memory-agent-tools.js +338 -0
  20. package/dist/compaction/memory-agent.d.ts +114 -0
  21. package/dist/compaction/memory-agent.js +220 -0
  22. package/dist/compaction/prune.d.ts +129 -0
  23. package/dist/compaction/prune.js +386 -0
  24. package/dist/compaction/retry-plan.d.ts +103 -0
  25. package/dist/compaction/retry-plan.js +136 -0
  26. package/dist/compaction/summarize-ladder.d.ts +149 -0
  27. package/dist/compaction/summarize-ladder.js +273 -0
  28. package/dist/compaction/wiring.d.ts +19 -0
  29. package/dist/compaction/wiring.js +65 -1
  30. package/dist/config/cli-commands.d.ts +1 -1
  31. package/dist/config/cli-commands.js +16 -0
  32. package/dist/config/env.d.ts +3 -1
  33. package/dist/config/env.js +44 -2
  34. package/dist/exec/events.d.ts +30 -0
  35. package/dist/exec/runner.d.ts +9 -0
  36. package/dist/exec/runner.js +51 -2
  37. package/dist/host/controller-feed.d.ts +12 -3
  38. package/dist/host/controller-feed.js +1 -1
  39. package/dist/host/interaction.js +5 -2
  40. package/dist/logging/install.d.ts +38 -1
  41. package/dist/logging/install.js +12 -1
  42. package/dist/session/persist.js +21 -5
  43. package/dist/session/validate-session.js +18 -2
  44. package/package.json +3 -3
package/README.md CHANGED
@@ -3040,16 +3040,97 @@ the model is not in that table.
3040
3040
  To make it cheap, configure the fast tier (`/fast on`, `/fast model <cheap-id>`).
3041
3041
  The transcript card then names the cheap model.
3042
3042
 
3043
+ ### Redundancy is pruned before anything is paid for
3044
+
3045
+ The **first** stage of a compaction costs no tokens. `compaction.prune` (on by
3046
+ default) walks the band that is about to be replaced and rewrites bodies that say
3047
+ nothing new:
3048
+
3049
+ - identical `tool_result` bodies — the first and the last copy always survive, and
3050
+ only the repeats in between become `[pruned duplicate-tool-result ...]` stubs;
3051
+ - the same command re-run with the same arguments and the same output;
3052
+ - an earlier `read_file` of a path that was read again later;
3053
+ - empty and noise-only results (a blank line, an `ok`, a rule of separators);
3054
+ - a body over 60 000 characters keeps its head and its tail.
3055
+
3056
+ The rules are deliberately narrow, and one rule is about honesty rather than
3057
+ size: a message the existing task memory **quotes** is never rewritten, because
3058
+ its excerpt would stop being a substring of the message and every later
3059
+ submission would be refused for a reason the model could not see. When the pass
3060
+ alone drops the projection below the threshold, **no summarizer call happens at
3061
+ all** — the card says `pruned 12 redundant bodies (214,003 chars) - no summary
3062
+ needed`. `/compact on/off` is not the switch for this; `/compact prune on|off` is.
3063
+
3064
+ ### How the summary is produced now
3065
+
3066
+ `compaction.agentic` (on by default) turns the summary into a **multi-turn agent
3067
+ with tools** instead of one large JSON request. The prompt only *suggests* an
3068
+ order; the tools carry the hard rules, and a result is adopted only when it
3069
+ arrives through `compaction_submit`.
3070
+
3071
+ | tool | when it is available | what it does |
3072
+ |---|---|---|
3073
+ | `compaction_outline` | first request | maps the band: ids, roles, sizes, prior memory |
3074
+ | `compaction_submit` | first request | the only accepted result |
3075
+ | `compaction_read` | after `outline` | one contiguous range, verbatim and bounded |
3076
+ | `compaction_search` | after `outline` | bounded snippets with source ids |
3077
+ | `compaction_note` | after `outline` | stage one item, validated immediately |
3078
+
3079
+ That is **progressive disclosure** as a protocol rather than a request: the first
3080
+ request carries two schemas, and the other three appear only after the model has
3081
+ seen the map. A rejected submission comes back as a tool result with
3082
+ `{accepted:false, code, path, remainingSubmissions}`, so an unusable delta is
3083
+ repaired inside the same operation instead of ending it — which is exactly the
3084
+ failure this replaced (`the summarizer returned an unusable memory delta`).
3085
+ A model that cannot call tools still compacts: the first turn carries no
3086
+ `tool_call`, its text is parsed as the delta, and the card reports the one-shot
3087
+ fallback.
3088
+
3043
3089
  ### When it cannot summarize
3044
3090
 
3045
- Each compaction makes at most two summary attempts under one total deadline;
3046
- transport retries follow the provider's existing retry policy within that same
3047
- deadline. Invalid structured output may be retried once with validation feedback.
3048
- Cancellation, timeout, invalid data, missing credentials, budget overflow, or
3091
+ Failures are classified, and each class gets its own action instead of a blind
3092
+ second attempt:
3093
+
3094
+ | failure | action |
3095
+ |---|---|
3096
+ | invalid / empty delta (`semantic`) | retry with the validator's receipt, up to 3 times, then change model |
3097
+ | request does not fit the window (`window`) | shrink the digest and ask again, up to 2 times, then change model |
3098
+ | connection dropped (`transport`) | `stop` on the same endpoint (core's own `withRetry` already backs off there); escalate only to a different endpoint |
3099
+ | no key, no model, no safe cut (`structural`) | `stop` |
3100
+ | budget reached | `stop` |
3101
+ | cancelled | `stop` |
3102
+
3103
+ One compaction makes at most **5 real summary calls** under one total deadline,
3104
+ and the agent loop has its own shorter wall clock (100 s, below the engine's
3105
+ 120 s) so a slow compaction ends by itself and reports `agent_timeout` instead of
3106
+ being cut from outside with no wording. Nothing here is retried twice through two
3107
+ independent ladders: transport backoff exists in exactly one place.
3108
+
3109
+ Cancellation, timeout, invalid data, missing credentials, budget exhaustion, or
3049
3110
  failed adoption leave history unchanged. The command reports `History preserved`
3050
3111
  and the reason. `onFailure` now defaults to `stop`; legacy `truncate` values still
3051
3112
  load but preserve history as well, as `/compact status` explicitly explains.
3052
3113
 
3114
+ ### A budget you can set
3115
+
3116
+ `compaction.budgetTokens` and `compaction.budgetUsd` cap **one operation**, not
3117
+ the session — a session-wide cap turns the seventh compaction of a long run into
3118
+ an unexplained cliff. `0` (the default) means no ceiling.
3119
+
3120
+ ```
3121
+ /compact budget 200000 # 200k tokens for the next operation
3122
+ /compact budget usd 0.50 # 50 cents for the next operation
3123
+ /compact budget off # no token ceiling
3124
+ /compact spend # session total + the last operation's ledger
3125
+ ```
3126
+
3127
+ The ceiling is charged from the provider's **real usage**, and it is checked
3128
+ before a request is sent, so an obviously over-budget call is not made at all.
3129
+ When the summarizer's model has no price table the dollar ceiling is *explicitly
3130
+ inactive* (`priceUnknown`, rendered `n/a`) rather than silently ignored — a
3131
+ ceiling that is not enforced must not look enforced. `Settings > Context` has the
3132
+ same two rows.
3133
+
3053
3134
  ### It will not loop on your money
3054
3135
 
3055
3136
  Four independent guards: never two compactions on consecutive turns, never more
@@ -3066,7 +3147,10 @@ and replacing history invalidates late responses.
3066
3147
 
3067
3148
  ### What you see
3068
3149
 
3069
- Three surfaces, each answering something the others cannot:
3150
+ Three surfaces, each answering something the others cannot (the card also
3151
+ reports what pruning saved, how many turns and tool calls the agent used, and
3152
+ whether a ceiling stopped it — one muted line, and only when it has something to
3153
+ say):
3070
3154
 
3071
3155
  - **While it runs** — the activity row reads `Compacting context…`. It outranks
3072
3156
  the tool name and the rotating phrase, because compaction happens between
@@ -3107,7 +3191,11 @@ refusal is explained. Automatic tail clipping and failure truncation are disable
3107
3191
 
3108
3192
  Children compact their own history **under the lead's own policy**: the same
3109
3193
  `keepRecentTurns`, the same `onFailure`, the same archive setting, the same
3110
- per-run compaction bound, the fast tier preferred whenever it resolves. Each
3194
+ per-run compaction bound, the same pruning, the fast tier preferred whenever it
3195
+ resolves. The multi-turn agent is the one exception and it is forced **off** for
3196
+ children: a child has no card and no notice channel, so its turns would be cost
3197
+ nobody can watch while the bill joins your session. Prune plus one JSON call is
3198
+ everything a background worker needs. Each
3111
3199
  child owns its own context meter and counts compaction only after Core accepts
3112
3200
  the candidate. There is no transcript card for a
3113
3201
  child — the lead's transcript describes the lead's context. Turn it off with
@@ -3125,7 +3213,11 @@ After a splice is adopted, the dropped messages are written verbatim to
3125
3213
  `~/.aragon/compaction/` — metadata, the summary, and the messages themselves.
3126
3214
 
3127
3215
  `/compact history` lists **this run's** archives, newest first, with the path of
3128
- each. `/compact show <n>` prints one archive's metadata and its stored summary;
3216
+ each. Each document also carries the prune detail (`messageIndex`, `sourceId`,
3217
+ `keptIndex`, removed chars), the budget ledger and the agent's turn count — as
3218
+ **optional** sections, so archives written before this existed are still listed
3219
+ and still readable (`version` stays `1`; the reader treats a missing section as
3220
+ absent). `/compact show <n>` prints one archive's metadata and its stored summary;
3129
3221
  it never prints message bodies, because a single archive can be megabytes and the
3130
3222
  transcript is not a pager. The directory is shared by every `aragon` on the
3131
3223
  machine, so files carry a per-process run id: another terminal's compactions are
@@ -8,7 +8,14 @@ import { formatCost, formatTokens, formatDuration, computeCost } from '@aragon-a
8
8
  import { formatStreamError } from '@aragon-agent/tui/model/agent/reducer';
9
9
  import { runDurationMs } from '../team/report.js';
10
10
  import { derivePlanPhase } from '@aragon-agent/tui/model/todo/acceptance';
11
- import { advanceBudget, decideFollowThrough, emptyBudget, } from '@aragon-agent/tui/model/todo/follow-through';
11
+ import { advanceBudget, decideFollowThrough, emptyBudget, isTransientRunEnd, } from '@aragon-agent/tui/model/todo/follow-through';
12
+ /**
13
+ * Mark time. The only wait `-p` ever takes, and it exists for one caller: the
14
+ * recovery grace in the follow-through loop below (`errorGraceMs`).
15
+ */
16
+ function pauseMs(ms) {
17
+ return new Promise((resolve) => setTimeout(resolve, ms));
18
+ }
12
19
  /** Run a single prompt headlessly and resolve with the process exit code. */
13
20
  export async function runHeadless(controller, prompt, options = {}) {
14
21
  const out = options.stdout ?? process.stdout;
@@ -20,6 +27,15 @@ export async function runHeadless(controller, prompt, options = {}) {
20
27
  return 2;
21
28
  }
22
29
  let errored = false;
30
+ /**
31
+ * The last `agent_end`'s failure verdict, as the ENGINE reported it (D).
32
+ *
33
+ * Kept apart from `errored` on purpose: `errored` is `-p`'s own sticky
34
+ * "something went wrong, exit 1" bit, while these are the provider's own
35
+ * classification and are what tell a retryable transport failure apart from a
36
+ * missing key (`llm-network-error-dead-run` C).
37
+ */
38
+ let endFacts = {};
23
39
  let sawTurnEnd = false;
24
40
  let wroteText = false;
25
41
  const total = { inputTokens: 0, outputTokens: 0 };
@@ -69,6 +85,13 @@ export async function runHeadless(controller, prompt, options = {}) {
69
85
  break;
70
86
  case 'turn_end':
71
87
  sawTurnEnd = true;
88
+ // A COMPLETED TURN CLEARS `-p`'s FAILURE BIT (C). After a transient
89
+ // failure the loop below may have re-prompted and succeeded, and exiting 1
90
+ // on a process that produced its answer would tell every piped caller the
91
+ // opposite of what happened. A later iteration that fails again sets this
92
+ // back - a failed run still produces no `turn_end`.
93
+ errored = false;
94
+ endFacts = {};
72
95
  if (retryCount > 0) {
73
96
  err.write(`[retry] recovered after ${retryCount} ${retryCount === 1 ? 'retry' : 'retries'}\n`);
74
97
  retryCount = 0;
@@ -78,6 +101,12 @@ export async function runHeadless(controller, prompt, options = {}) {
78
101
  break;
79
102
  case 'agent_end':
80
103
  // A swallowed throw (missing key / empty stream) produces no turn_end.
104
+ endFacts = {
105
+ ...(event.errored !== undefined ? { errored: event.errored } : {}),
106
+ ...(event.errorType !== undefined ? { errorType: event.errorType } : {}),
107
+ ...(event.retryable !== undefined ? { retryable: event.retryable } : {}),
108
+ ...(event.reason !== undefined ? { reason: event.reason } : {}),
109
+ };
81
110
  if (!sawTurnEnd && !errored)
82
111
  errored = true;
83
112
  break;
@@ -243,6 +272,24 @@ export async function runHeadless(controller, prompt, options = {}) {
243
272
  `${r.tailRelief.messages === 1 ? 'result' : 'results'} in the retained turns ` +
244
273
  `(${formatTokens(r.tailRelief.charsRemoved)} chars)\n`);
245
274
  }
275
+ // THE v3 SURFACES (context-compaction-v3 W1 / W3 / W4), each only when it has
276
+ // something to say. A `-p` reader cannot open `/compact status`, so a pruned
277
+ // body count and an agent turn count that never reach this stream are
278
+ // invisible to the only audience that reads a machine log.
279
+ if (r.prune && r.prune.actions > 0) {
280
+ err.write(`[compaction] pruned ${r.prune.actions} redundant ` +
281
+ `${r.prune.actions === 1 ? 'tool result' : 'tool results'} ` +
282
+ `(${formatTokens(r.prune.removedChars)} chars)\n`);
283
+ }
284
+ if (r.agent) {
285
+ err.write(`[compaction] agent: ${r.agent.turns} turns, ${r.agent.toolCalls} tool calls` +
286
+ `${r.agent.fallback === 'single-shot' ? ' (single-shot fallback)' : ''}\n`);
287
+ }
288
+ if (r.budget && (r.budget.limitTokens > 0 || r.budget.limitUsd > 0)) {
289
+ err.write(`[compaction] budget: ${formatTokens(r.budget.spentTokens)} tokens` +
290
+ `${r.budget.priceUnknown ? ', cost n/a' : `, ${r.budget.spentUsd.toFixed(2)} USD`}` +
291
+ `${r.budget.stop ? ` - stopped: ${r.budget.stop}` : ''}\n`);
292
+ }
246
293
  });
247
294
  /**
248
295
  * `[accept] <n>/<total> checked`, plus the failure count when there is one.
@@ -274,9 +321,13 @@ export async function runHeadless(controller, prompt, options = {}) {
274
321
  for (;;) {
275
322
  // PER-ITERATION RESET (rule 1). `sawTurnEnd` is the silent-failure
276
323
  // detector; left sticky, a swallowed throw on iteration 2 is invisible
277
- // because iteration 1 set the flag. `errored` is deliberately NOT reset —
278
- // once a run has errored the exit code is 1 and the loop must stop.
324
+ // because iteration 1 set the flag. `endFacts` is reset for the same
325
+ // reason one field over: a transient verdict belongs to the turn that
326
+ // produced it, and inheriting it would let iteration 2 read iteration
327
+ // 1's failure. `errored` is NOT reset here; it is cleared by a completed
328
+ // `turn_end`, the only event that proves a recovery happened.
279
329
  sawTurnEnd = false;
330
+ endFacts = {};
280
331
  await controller.prompt(message);
281
332
  const snapshot = controller.getTodoSnapshot?.() ?? null;
282
333
  budget = advanceBudget(budget, snapshot, wasAutoContinuation);
@@ -286,9 +337,11 @@ export async function runHeadless(controller, prompt, options = {}) {
286
337
  snapshot,
287
338
  // `aborted` is STRUCTURALLY false here (C-2): `-p` has no Esc and
288
339
  // installs no signal handler that marks one, so there is nothing to
289
- // derive and nothing to plumb. An errored run takes the `notify` branch
290
- // below and ends the loop, which is what keeps exit code 1 reachable.
291
- runEnd: { aborted: false, errored },
340
+ // derive and nothing to plumb. `transient` comes from the ENGINE's own
341
+ // verdict on `agent_end` (C): a retryable transport failure resumes,
342
+ // everything else still takes the `notify` branch below and keeps exit
343
+ // code 1 reachable.
344
+ runEnd: { aborted: false, errored, transient: isTransientRunEnd(endFacts) },
292
345
  budget,
293
346
  interactive: false,
294
347
  });
@@ -307,6 +360,14 @@ export async function runHeadless(controller, prompt, options = {}) {
307
360
  wasAutoContinuation = true;
308
361
  if (!quiet)
309
362
  err.write(`\n[todo] ${decision.notice}\n`);
363
+ // THE ONE GRACE WINDOW `-p` HONOURS (C). An ordinary continuation is
364
+ // immediate here - there is no human to interrupt, so the 3 s courtesy wait
365
+ // buys nothing - but a RECOVERY arrives with `errorGraceMs` because what it
366
+ // waits out is the network that just killed the ladder. Re-prompting at 0 ms
367
+ // would spend a whole second ladder (up to `retry.maxElapsedMs`) against the
368
+ // same broken endpoint, and two of those hand the plan back for nothing.
369
+ if (decision.graceMs > 0)
370
+ await pauseMs(decision.graceMs);
310
371
  message = decision.message;
311
372
  }
312
373
  }
@@ -1,6 +1,7 @@
1
1
  import type { ContentPart } from '@aragon-agent/core';
2
2
  import type { InvocationCardInput } from '@aragon-agent/tui/model/agent/invocation-card';
3
3
  import type { AttachmentMeta } from '@aragon-agent/tui/model/agent/attachment-meta';
4
+ import type { ContextChipMeta } from '@aragon-agent/tui/model/agent/context-meta';
4
5
  /** Explicit TUI task boundary; omission retains legacy programmatic behavior. */
5
6
  export interface PromptOptions {
6
7
  todoPolicy?: 'new-task' | 'continue';
@@ -29,6 +30,12 @@ export interface SubmitMessageOptions extends PromptOptions {
29
30
  metas: AttachmentMeta[];
30
31
  displayText?: string;
31
32
  };
33
+ /**
34
+ * Code-context snapshots the user attached (ide-selection-context). METADATA ONLY - path and range -
35
+ * so the transcript can draw a pill and a reopened session can still say what was attached. The text
36
+ * the model reads is already part of `message`, and is never carried here.
37
+ */
38
+ contexts?: ContextChipMeta[];
32
39
  }
33
40
  /** Startup outcome only; engine events still describe the result of the run. */
34
41
  export type PromptOutcome = {
package/dist/app/App.js CHANGED
@@ -58,7 +58,7 @@ import { ScrollViewport } from '@aragon-agent/tui/ui/layout/ScrollViewport';
58
58
  import { acceptanceChip, acceptanceRung, buildTodoRailLayout } from '@aragon-agent/tui/ui/layout/todo-layout';
59
59
  import { buildTeamPanelLayout } from '@aragon-agent/tui/ui/layout/team-panel';
60
60
  import { isLiveTeamCard, lastTeamEntry, rosterCounts } from '@aragon-agent/tui/ui/team-status';
61
- import { advanceBudget, decideFollowThrough, emptyBudget, } from '@aragon-agent/tui/model/todo/follow-through';
61
+ import { advanceBudget, decideFollowThrough, emptyBudget, isTransientRunEnd, } from '@aragon-agent/tui/model/todo/follow-through';
62
62
  // THE THIRD LAYER OF FORCED TEAM MODE (team-command-forced-dispatch §3.7): the
63
63
  // decision and its two strings live in a pure module, so `App` gains wiring and
64
64
  // no policy. Imported beside the todo decision it shares one timer with.
@@ -595,10 +595,18 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
595
595
  *
596
596
  * So this ref is mutated in the SAME SYNCHRONOUS CALLBACK that dispatches the
597
597
  * corresponding action, and the reducer fields stay as the cross-check.
598
+ *
599
+ * `transient` IS A THIRD FACT, NOT A REFINEMENT OF `errored`
600
+ * (`llm-network-error-dead-run` C). `errored` answers "did something go wrong",
601
+ * which both a revoked key and an `ECONNRESET` burst answer yes to; `transient`
602
+ * answers "is another turn worth spending", and it is derived from the engine's
603
+ * own verdict (`errorType` + `retryable` on `agent_end`) rather than from how
604
+ * the failure was displayed.
598
605
  */
599
606
  const endReasonRef = useRef({
600
607
  aborted: false,
601
608
  errored: false,
609
+ transient: false,
602
610
  });
603
611
  const interruptTimer = useRef(null);
604
612
  const resetInterrupt = useCallback(() => {
@@ -905,7 +913,23 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
905
913
  dispatchAttemptedRef.current = true;
906
914
  }
907
915
  },
908
- afterAgentEnd() {
916
+ afterAgentEnd(end) {
917
+ // THE ENGINE'S OWN VERDICT, FIRST AND UNCONDITIONALLY (D). Everything
918
+ // below this line decides whether to continue, and until now `errored`
919
+ // was inferred from "a notice with level error was dispatched" - which
920
+ // misses the watchdog path (a bare console line, no `onAction`) and
921
+ // cannot tell a revoked key from a transport wobble.
922
+ //
923
+ // A USER ABORT OUTRANKS IT: `aborted` is set by Esc, and a run the user
924
+ // interrupted must stay quiet whatever the engine recorded while
925
+ // unwinding (`follow-through` returns `none` on `aborted` anyway; this
926
+ // keeps the forced-dispatch gate from reading a failed turn too).
927
+ if (!endReasonRef.current.aborted) {
928
+ if (end.errored === true)
929
+ endReasonRef.current.errored = true;
930
+ if (isTransientRunEnd(end))
931
+ endReasonRef.current.transient = true;
932
+ }
909
933
  // NO OVERLAY OUTLIVES ITS RUN (P1-4). `ctx.signal` already covers the
910
934
  // abort path, so this is DELIBERATE REDUNDANCY: it makes "the card cannot
911
935
  // survive the run that opened it" a property of the App's lifecycle
@@ -963,11 +987,14 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
963
987
  : decideFollowThrough({
964
988
  mode: controller.getTodoConfig().followThrough,
965
989
  snapshot: todos,
990
+ // `transient` RIDES THROUGH (C): without it the table cannot tell
991
+ // "the network dropped for 40 s" from "the key is wrong", and the
992
+ // whole point of the fix is that only the first one resumes.
966
993
  runEnd: { ...endReasonRef.current },
967
994
  budget: budgetRef.current,
968
995
  interactive: true,
969
996
  });
970
- endReasonRef.current = { aborted: false, errored: false };
997
+ endReasonRef.current = { aborted: false, errored: false, transient: false };
971
998
  if (decision.kind === 'notify') {
972
999
  dispatch({ type: 'notice', level: decision.level, text: decision.text });
973
1000
  }
@@ -1279,7 +1306,12 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1279
1306
  // Ink's own patchConsole writes straight to stdout, which shifts the fixed
1280
1307
  // frame by a row and breaks its line accounting for good.
1281
1308
  useEffect(() => {
1282
- return installConsoleBridge((level, text) => dispatch({ type: 'notice', level, text }));
1309
+ // `internal: true` IS LOAD-BEARING (llm-network-error-dead-run F): these lines
1310
+ // are the ENGINE talking, not a verdict the reducer derived from a provider
1311
+ // error, and that difference decides whether a live retry card may be settled
1312
+ // as "exhausted". The watchdog line used to arrive here and assert an
1313
+ // exhaustion that never happened, on a card the run had merely interrupted.
1314
+ return installConsoleBridge((level, text) => dispatch({ type: 'notice', level, text, internal: true }));
1283
1315
  }, []);
1284
1316
  // `enabled` is `mouseSource`, not `cfg.mouse`: a user whose terminal drops
1285
1317
  // the events must never be shown advice about a mode not in effect (§6.1).
@@ -2323,7 +2355,7 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2323
2355
  }
2324
2356
  // Mirrors where the reducer clears its own copies, in the same action
2325
2357
  // (C-11): a new turn's end reason must not inherit the previous one's.
2326
- endReasonRef.current = { aborted: false, errored: false };
2358
+ endReasonRef.current = { aborted: false, errored: false, transient: false };
2327
2359
  dispatch({ type: 'submit', text: shown, ...(card ? { invocation: card } : {}) });
2328
2360
  const pre = controller.preflight();
2329
2361
  if (!pre.ok) {
@@ -904,7 +904,8 @@ const COMMANDS = [
904
904
  // file is already past the 1000-line guideline and `/compact` has six forms
905
905
  // plus the longest status report in the package (C-16 / P1-12).
906
906
  name: 'compact',
907
- description: 'Context compaction: status | on | off | threshold <n> | keep <n> | <instructions>',
907
+ description: 'Context compaction: status | spend | budget | agent | prune | threshold ' +
908
+ '| keep | history | show | <instructions>',
908
909
  run: (ctx) => runCompactCommand(ctx),
909
910
  },
910
911
  {
@@ -21,7 +21,7 @@ export const BUILTIN_COMMAND_CATALOG = [
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
23
  { name: 'retry', aliases: [], description: 'API retry: show | on | off | max <n>' },
24
- { name: 'compact', aliases: [], description: 'Context compaction: status | on | off | threshold <n> | keep <n> | <instructions>' },
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)' },
27
27
  { name: 'tools', aliases: [], description: 'List active tools' },
@@ -19,7 +19,7 @@
19
19
  * it has no terminal, no theme and no glyphs.
20
20
  */
21
21
  import type { Message } from '@aragon-agent/core';
22
- import type { CompactionMode, CompactionUiTrigger } from '@aragon-agent/tui/model/compaction/types';
22
+ import type { ArchivePruneAction, CompactionMode, CompactionRecord, CompactionUiTrigger } from '@aragon-agent/tui/model/compaction/types';
23
23
  /** Bumped only when the SHAPE changes; the reader rejects anything else. */
24
24
  export declare const ARCHIVE_FORMAT_VERSION = 1;
25
25
  export interface CompactionArchive {
@@ -57,6 +57,20 @@ export interface CompactionArchive {
57
57
  messages: number;
58
58
  charsRemoved: number;
59
59
  };
60
+ /**
61
+ * THE THREE v3 SECTIONS, ALL OPTIONAL AND ALL ADDITIVE (P0-3).
62
+ *
63
+ * `version` STAYS 1 ON PURPOSE. The reader accepts a document only when
64
+ * `raw.version === ARCHIVE_FORMAT_VERSION` (strict equality), so bumping it
65
+ * would make every archive written before this feature invisible to
66
+ * `/compact history` and `/compact show` - the exact corruption R-13 records.
67
+ * A missing section is read as absent, the way `tailRelief` already is.
68
+ */
69
+ prune?: {
70
+ actions: ArchivePruneAction[];
71
+ };
72
+ budget?: CompactionRecord['budget'];
73
+ agent?: CompactionRecord['agent'];
60
74
  /** True when `dropped` was shortened to fit `archiveMaxBytes`. */
61
75
  clipped: boolean;
62
76
  /** THE ARRAY. Verbatim, oldest first. */
@@ -85,6 +99,12 @@ export interface ArchiveEntry {
85
99
  messages: number;
86
100
  charsRemoved: number;
87
101
  };
102
+ /** The prune tally, absent for every archive written before v3. */
103
+ prune?: {
104
+ actions: ArchivePruneAction[];
105
+ };
106
+ budget?: CompactionRecord['budget'];
107
+ agent?: CompactionRecord['agent'];
88
108
  clipped: boolean;
89
109
  }
90
110
  export interface ArchiveWriteInput {
@@ -103,6 +123,12 @@ export interface ArchiveWriteInput {
103
123
  messages: number;
104
124
  charsRemoved: number;
105
125
  };
126
+ /** The three optional v3 sections (P0-3: additive, never a version bump). */
127
+ prune?: {
128
+ actions: ArchivePruneAction[];
129
+ };
130
+ budget?: CompactionRecord['budget'];
131
+ agent?: CompactionRecord['agent'];
106
132
  dropped: Message[];
107
133
  /** Injected by the tests; production passes nothing. */
108
134
  dir?: string;
@@ -130,6 +130,9 @@ export function writeArchive(input) {
130
130
  droppedCount: input.dropped.length,
131
131
  ...(input.summary !== undefined ? { summary: input.summary } : {}),
132
132
  ...(input.tailRelief ? { tailRelief: input.tailRelief } : {}),
133
+ ...(input.prune ? { prune: input.prune } : {}),
134
+ ...(input.budget ? { budget: input.budget } : {}),
135
+ ...(input.agent ? { agent: input.agent } : {}),
133
136
  clipped: false,
134
137
  // agent-image-reading: the archive is the SECOND place messages reach the disk. A tool
135
138
  // picture is re-fetchable, so it is archived as its label and a note; verbatim pixels
@@ -258,6 +261,11 @@ function readArchiveEntry(path, fileName) {
258
261
  droppedCount: Number(raw.droppedCount ?? 0),
259
262
  ...(typeof raw.summary === 'string' ? { summary: raw.summary } : {}),
260
263
  ...(raw.tailRelief ? { tailRelief: raw.tailRelief } : {}),
264
+ // A MISSING SECTION IS ABSENT, NOT AN ERROR (P0-3): every archive written
265
+ // before this feature has none of the three, and all of them stay readable.
266
+ ...(raw.prune ? { prune: raw.prune } : {}),
267
+ ...(raw.budget ? { budget: raw.budget } : {}),
268
+ ...(raw.agent ? { agent: raw.agent } : {}),
261
269
  clipped: raw.clipped === true,
262
270
  };
263
271
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The per-operation spend ceiling (context-compaction-v3 W3).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHY PER OPERATION AND NOT PER SESSION (D-8). A session-level cap turns the
7
+ * seventh compaction of a long run into an unexplained cliff: the feature simply
8
+ * stops working, with nothing about the moment that explains it. Per-operation
9
+ * keeps every refusal local, visible on the card that caused it, and repeatable.
10
+ *
11
+ * TWO UNITS, TWO MECHANISMS:
12
+ *
13
+ * - TOKENS are charged from the provider's REAL `usage`, and the projection is
14
+ * used only to refuse a request that is obviously already over. Charging the
15
+ * projection would bill a request that never happened.
16
+ * - DOLLARS need a price table. When the summarizer model is not priced the
17
+ * dollar gate is switched off and says so (`priceUnknown`), because a
18
+ * fake `$0.00` on a feature that is spending money is the same class of lie
19
+ * the fast tier's RV-11 records (D-9).
20
+ *
21
+ * `0` MEANS UNLIMITED IN BOTH UNITS, and that is why the arithmetic never has to
22
+ * special-case "no budget": a zero limit is never reached by a growing total.
23
+ */
24
+ import type { TokenUsage } from '@aragon-agent/core';
25
+ export interface BudgetLimits {
26
+ /** Total tokens this operation may spend; `0` = unlimited. */
27
+ tokens: number;
28
+ /** Total dollars this operation may spend; `0` = unlimited. */
29
+ usd: number;
30
+ }
31
+ export interface BudgetSnapshot {
32
+ limitTokens: number;
33
+ spentTokens: number;
34
+ limitUsd: number;
35
+ spentUsd: number;
36
+ /** True when the dollar gate could not price the summarizer and is not in force. */
37
+ priceUnknown: boolean;
38
+ stop?: 'budget_tokens' | 'budget_usd';
39
+ }
40
+ export interface BudgetCharge {
41
+ usage: TokenUsage;
42
+ costUsd: number;
43
+ pricingUnknown: boolean;
44
+ }
45
+ /** Tokens a usage entry actually costs; cache reads and writes count as input. */
46
+ export declare function chargedTokens(usage: TokenUsage): number;
47
+ export declare class CompactionBudget {
48
+ private readonly limits;
49
+ private spentTokens;
50
+ private spentUsd;
51
+ private priceUnknown;
52
+ private stopped;
53
+ /**
54
+ * THE DEDUPE KEY IS THE USAGE OBJECT'S IDENTITY, not a turn counter.
55
+ *
56
+ * One `callOnce` can produce several REAL billable calls inside core's
57
+ * `withRetry`, and each of them hands back its own usage object. A counter
58
+ * would charge the retries as one; object identity charges what was spent and
59
+ * still refuses to charge the same object twice (the single-shot path forwards
60
+ * the same usage to two callbacks).
61
+ */
62
+ private readonly charged;
63
+ constructor(limits: BudgetLimits);
64
+ /** Whether a request of this projected size would cross the token ceiling. */
65
+ wouldExceed(projectedTokens: number): boolean;
66
+ /** Record what a real call cost. Never throws: a budget cannot fail a compaction. */
67
+ charge(input: BudgetCharge): void;
68
+ /** The ceiling that has been crossed, if any; `undefined` while work may continue. */
69
+ get exhausted(): 'budget_tokens' | 'budget_usd' | undefined;
70
+ snapshot(): BudgetSnapshot;
71
+ /** Both gates, in a fixed order, so one snapshot has one `stop` value. */
72
+ private evaluate;
73
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The per-operation spend ceiling (context-compaction-v3 W3).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHY PER OPERATION AND NOT PER SESSION (D-8). A session-level cap turns the
7
+ * seventh compaction of a long run into an unexplained cliff: the feature simply
8
+ * stops working, with nothing about the moment that explains it. Per-operation
9
+ * keeps every refusal local, visible on the card that caused it, and repeatable.
10
+ *
11
+ * TWO UNITS, TWO MECHANISMS:
12
+ *
13
+ * - TOKENS are charged from the provider's REAL `usage`, and the projection is
14
+ * used only to refuse a request that is obviously already over. Charging the
15
+ * projection would bill a request that never happened.
16
+ * - DOLLARS need a price table. When the summarizer model is not priced the
17
+ * dollar gate is switched off and says so (`priceUnknown`), because a
18
+ * fake `$0.00` on a feature that is spending money is the same class of lie
19
+ * the fast tier's RV-11 records (D-9).
20
+ *
21
+ * `0` MEANS UNLIMITED IN BOTH UNITS, and that is why the arithmetic never has to
22
+ * special-case "no budget": a zero limit is never reached by a growing total.
23
+ */
24
+ /** Tokens a usage entry actually costs; cache reads and writes count as input. */
25
+ export function chargedTokens(usage) {
26
+ return usage.inputTokens + usage.outputTokens
27
+ + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
28
+ }
29
+ export class CompactionBudget {
30
+ limits;
31
+ spentTokens = 0;
32
+ spentUsd = 0;
33
+ priceUnknown = false;
34
+ stopped;
35
+ /**
36
+ * THE DEDUPE KEY IS THE USAGE OBJECT'S IDENTITY, not a turn counter.
37
+ *
38
+ * One `callOnce` can produce several REAL billable calls inside core's
39
+ * `withRetry`, and each of them hands back its own usage object. A counter
40
+ * would charge the retries as one; object identity charges what was spent and
41
+ * still refuses to charge the same object twice (the single-shot path forwards
42
+ * the same usage to two callbacks).
43
+ */
44
+ charged = new WeakSet();
45
+ constructor(limits) {
46
+ this.limits = limits;
47
+ }
48
+ /** Whether a request of this projected size would cross the token ceiling. */
49
+ wouldExceed(projectedTokens) {
50
+ if (this.limits.tokens <= 0)
51
+ return false;
52
+ return this.spentTokens + Math.max(0, projectedTokens) > this.limits.tokens;
53
+ }
54
+ /** Record what a real call cost. Never throws: a budget cannot fail a compaction. */
55
+ charge(input) {
56
+ if (!this.charged.has(input.usage)) {
57
+ this.charged.add(input.usage);
58
+ this.spentTokens += chargedTokens(input.usage);
59
+ if (!input.pricingUnknown)
60
+ this.spentUsd += Math.max(0, input.costUsd);
61
+ }
62
+ if (input.pricingUnknown)
63
+ this.priceUnknown = true;
64
+ this.stopped = this.evaluate();
65
+ }
66
+ /** The ceiling that has been crossed, if any; `undefined` while work may continue. */
67
+ get exhausted() {
68
+ return this.evaluate();
69
+ }
70
+ snapshot() {
71
+ return {
72
+ limitTokens: this.limits.tokens,
73
+ spentTokens: this.spentTokens,
74
+ limitUsd: this.limits.usd,
75
+ spentUsd: Math.round(this.spentUsd * 10_000) / 10_000,
76
+ priceUnknown: this.priceUnknown,
77
+ ...(this.stopped === undefined ? {} : { stop: this.stopped }),
78
+ };
79
+ }
80
+ /** Both gates, in a fixed order, so one snapshot has one `stop` value. */
81
+ evaluate() {
82
+ if (this.limits.tokens > 0 && this.spentTokens >= this.limits.tokens)
83
+ return 'budget_tokens';
84
+ if (this.limits.usd > 0 && !this.priceUnknown && this.spentUsd >= this.limits.usd) {
85
+ return 'budget_usd';
86
+ }
87
+ return undefined;
88
+ }
89
+ }