@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
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The retry ladder and its two attempts (context-compaction-v3 W2 + W4).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHY IT IS NOT IN `compactor.ts`. The orchestrator's job is the ORDER of the
7
+ * stages (cut, prune, digest, summarize, validate, apply) and the record that
8
+ * ends them. Asking, classifying and asking again is a different job with its own
9
+ * two ceilings, and it was pushing the orchestrator past the 1000-line cap the
10
+ * project draws (`CLAUDE.md`). Everything here is reachable through
11
+ * `SummarizeLadderDeps`, so the ladder is driven by a scripted transport in tests
12
+ * without an `Agent`, a registry or a network.
13
+ *
14
+ * TWO PATHS, ONE ENTRY. `summarize()` asks `attemptSummary()`, which routes to the
15
+ * multi-turn agent (W4) when one is wired, and to the single JSON call otherwise
16
+ * (D-14) - the path a model without tool support still takes. Both return a REASON
17
+ * rather than throwing, because what a failure MEANS is the table's decision
18
+ * (`retry-plan.ts`) and that decision is the whole of W2.
19
+ */
20
+ import { type ModelInfo, type ModelRef, type TokenUsage } from '@aragon-agent/core';
21
+ import type { ModelRole } from '@aragon-agent/tui/model/config/model-profiles';
22
+ import type { CompactionEvent } from '@aragon-agent/tui/model/compaction/types';
23
+ import { type DigestResult } from './digest.js';
24
+ import { type CompactionMemory } from './memory.js';
25
+ import type { PreparedMemoryInput } from './memory-input.js';
26
+ import type { CompactionBudget } from './budget.js';
27
+ import { type AgentTurn, type AgentTurnRequest } from './memory-agent.js';
28
+ /** The summarizer the next attempt would use. */
29
+ export interface SummarizerChoice {
30
+ role: ModelRole;
31
+ ref: ModelRef;
32
+ /** Whether the fast tier supplied it, for `/compact status` and the card. */
33
+ fromFastTier: boolean;
34
+ }
35
+ /**
36
+ * What the ladder needs of the staged operation.
37
+ *
38
+ * STRUCTURAL ON PURPOSE: declaring the compactor's whole `StagedOperation` here
39
+ * would put a runtime import of the orchestrator inside its own helper.
40
+ */
41
+ export interface LadderState {
42
+ operation: {
43
+ signal: AbortSignal;
44
+ /** The operation's wall clock, so the agent loop can bound itself under it. */
45
+ deadline: number;
46
+ /** The local race that ends a turn whose provider ignores the abort signal. */
47
+ run: <T>(call: () => Promise<T>, timeoutMs: number) => Promise<T>;
48
+ };
49
+ budget: CompactionBudget;
50
+ /** Filled in here: the effort the record and the card disclose. */
51
+ agent?: {
52
+ turns: number;
53
+ toolCalls: number;
54
+ submissions: number;
55
+ fallback?: 'single-shot';
56
+ };
57
+ /** The model that actually ran, which may not be the one the card announced. */
58
+ model: string;
59
+ /** Set when the budget, not a failure, ended the operation. */
60
+ stoppedBy?: 'budget_tokens' | 'budget_usd' | 'turn_limit' | 'timeout' | 'cancel';
61
+ }
62
+ /** What one attempt answers: a usable memory, or the reason it is not usable. */
63
+ export type AttemptOutcome = {
64
+ ok: true;
65
+ memory: CompactionMemory;
66
+ } | {
67
+ ok: false;
68
+ reason: string;
69
+ };
70
+ /** Everything the ladder borrows from its owner, all of it already resolved. */
71
+ export interface SummarizeLadderDeps {
72
+ /** Configured AND wired: a tool-less model still compacts, one rung lower. */
73
+ isAgentic: () => boolean;
74
+ runAgentTurn: (request: AgentTurnRequest) => Promise<AgentTurn>;
75
+ getModelInfoFor: (ref: Pick<ModelRef, 'providerId' | 'modelId' | 'baseUrl'>) => ModelInfo;
76
+ emit: (event: CompactionEvent) => void;
77
+ noteUsage: (ref: ModelRef, usage: TokenUsage) => void;
78
+ log: {
79
+ info: (msg: string, data?: Record<string, unknown>) => void;
80
+ };
81
+ callOnce: (state: LadderState, choice: SummarizerChoice, request: {
82
+ digest: string;
83
+ hasPriorSummary: boolean;
84
+ instructions?: string;
85
+ validationError?: string;
86
+ }) => Promise<string>;
87
+ mainChoice: () => SummarizerChoice;
88
+ }
89
+ export declare class SummarizeLadder {
90
+ private readonly deps;
91
+ constructor(deps: SummarizeLadderDeps);
92
+ /**
93
+ * The retry ladder (W2): ask, classify, act - bounded by the table.
94
+ *
95
+ * TWO CEILINGS ACT AT ONCE, and both are checked before every request: the
96
+ * attempt count (`attemptsTotal`) and the operation's ledger. A failure the
97
+ * table calls `stop` ends here with that code, which is what keeps "an unusable
98
+ * delta" from silently meaning "retry forever".
99
+ */
100
+ summarize(state: LadderState, input: PreparedMemoryInput, selected: {
101
+ choice: SummarizerChoice;
102
+ digest: DigestResult;
103
+ }, instructions?: string): Promise<CompactionMemory>;
104
+ /**
105
+ * The digest, and the window projection for whichever path will actually send it.
106
+ *
107
+ * THE PROJECTION IS PATH-DEPENDENT (P1-4). `agentic` sends an opening of three
108
+ * lines and then pulls what it needs, so projecting the WHOLE digest would
109
+ * refuse a request the agent never makes - and every token the multi-turn
110
+ * design saves would be spent on a phantom. The full-digest projection is kept
111
+ * for the single-shot path, where it is exactly right.
112
+ *
113
+ * `shrink` (< 1) is `retry-shrink`: the digest is rebuilt against a smaller
114
+ * effective window, which is what makes a window failure recoverable instead of
115
+ * terminal.
116
+ */
117
+ digestFor(input: PreparedMemoryInput, choice: SummarizerChoice, instructions?: string, shrink?: number): DigestResult;
118
+ /**
119
+ * The window gate's projection: what the request BODY costs, path by path.
120
+ *
121
+ * UNCHANGED FROM THE PRE-v3 ARITHMETIC on purpose - the single-shot path added
122
+ * its output allowance here before this feature existed, the agentic path had
123
+ * none - so tightening this gate is not something a refactor may do quietly.
124
+ */
125
+ private windowProjection;
126
+ /**
127
+ * The budget gate's projection: the WHOLE next request, output included (§4.5).
128
+ *
129
+ * NOT A FIXED NUMBER. Charging every attempt the same `digestMaxChars / 4`
130
+ * would refuse the first, small request of the agentic path against any ceiling
131
+ * below ~31k tokens - a budget that never lets the feature start is not a
132
+ * budget. The projection is the request that is about to be sent.
133
+ */
134
+ private requestProjection;
135
+ /** The first agent turn's input: three lines plus the outline allowance (P1-4). */
136
+ private agentOpeningTokens;
137
+ /** The single-shot request's input size, without its output allowance. */
138
+ private singleShotInputTokens;
139
+ /** The token projection the budget gate checks before a request is sent. */
140
+ private budgetWouldExceed;
141
+ /** Whether `choice` reaches the same endpoint as the main model (D-6). */
142
+ private sameEndpoint;
143
+ /** One attempt: the agent when it is available, the single JSON call otherwise. */
144
+ private attemptSummary;
145
+ /** The multi-turn path (W4). */
146
+ private agentAttempt;
147
+ /** The last rung (D-14): one JSON request, exactly as before this feature. */
148
+ private singleShot;
149
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * The retry ladder and its two attempts (context-compaction-v3 W2 + W4).
3
+ *
4
+ * ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
5
+ *
6
+ * WHY IT IS NOT IN `compactor.ts`. The orchestrator's job is the ORDER of the
7
+ * stages (cut, prune, digest, summarize, validate, apply) and the record that
8
+ * ends them. Asking, classifying and asking again is a different job with its own
9
+ * two ceilings, and it was pushing the orchestrator past the 1000-line cap the
10
+ * project draws (`CLAUDE.md`). Everything here is reachable through
11
+ * `SummarizeLadderDeps`, so the ladder is driven by a scripted transport in tests
12
+ * without an `Agent`, a registry or a network.
13
+ *
14
+ * TWO PATHS, ONE ENTRY. `summarize()` asks `attemptSummary()`, which routes to the
15
+ * multi-turn agent (W4) when one is wired, and to the single JSON call otherwise
16
+ * (D-14) - the path a model without tool support still takes. Both return a REASON
17
+ * rather than throwing, because what a failure MEANS is the table's decision
18
+ * (`retry-plan.ts`) and that decision is the whole of W2.
19
+ */
20
+ import { CONTEXT_SAFETY_MARGIN_TOKENS, estimatePromptTokens, } from '@aragon-agent/core';
21
+ import { COMPACTION_LIMITS } from '@aragon-agent/tui/model/compaction/limits';
22
+ import { buildDigest } from './digest.js';
23
+ import { buildSummarizeRequest, describeTransportFailure, errorText, } from './summarize-call.js';
24
+ import { mergeMemory, parseMemoryDelta } from './memory.js';
25
+ import { validateMemoryDelta } from './memory-validation.js';
26
+ import { planRetry } from './retry-plan.js';
27
+ import { memoryFromDelta, projectAgentOpeningTokens, runMemoryAgent, } from './memory-agent.js';
28
+ export class SummarizeLadder {
29
+ deps;
30
+ constructor(deps) {
31
+ this.deps = deps;
32
+ }
33
+ /**
34
+ * The retry ladder (W2): ask, classify, act - bounded by the table.
35
+ *
36
+ * TWO CEILINGS ACT AT ONCE, and both are checked before every request: the
37
+ * attempt count (`attemptsTotal`) and the operation's ledger. A failure the
38
+ * table calls `stop` ends here with that code, which is what keeps "an unusable
39
+ * delta" from silently meaning "retry forever".
40
+ */
41
+ async summarize(state, input, selected, instructions) {
42
+ let choice = selected.choice;
43
+ let digest = selected.digest;
44
+ let shrink = 1;
45
+ let repairHint;
46
+ let repairs = 0;
47
+ let shrinks = 0;
48
+ let last = 'invalid_memory_delta';
49
+ for (let attempt = 1; attempt <= COMPACTION_LIMITS.attemptsTotal; attempt += 1) {
50
+ if (state.operation.signal.aborted)
51
+ throw new Error('aborted');
52
+ if (state.budget.exhausted !== undefined) {
53
+ state.stoppedBy = state.budget.exhausted;
54
+ this.deps.log.info('compaction_budget_stop', { stop: state.budget.exhausted, attempt });
55
+ throw new Error('budget_exhausted');
56
+ }
57
+ if (this.budgetWouldExceed(state, input, choice, digest, instructions)) {
58
+ state.stoppedBy = 'budget_tokens';
59
+ throw new Error('budget_exhausted');
60
+ }
61
+ const outcome = await this.attemptSummary(state, input, choice, digest, instructions, repairHint);
62
+ if (outcome.ok)
63
+ return outcome.memory;
64
+ // A CANCELLATION IS NOT A RETRY DECISION (V-9): the engine or the user stopped
65
+ // this operation while the request was in flight, so the answer - and any
66
+ // reason derived from it - is meaningless.
67
+ if (state.operation.signal.aborted)
68
+ throw new Error('aborted');
69
+ last = outcome.reason;
70
+ const action = planRetry(outcome.reason, {
71
+ attempt,
72
+ sameEndpoint: this.sameEndpoint(choice),
73
+ repairs,
74
+ shrinks,
75
+ turnsLeft: COMPACTION_LIMITS.attemptsTotal - attempt,
76
+ budgetLeft: state.budget.exhausted === undefined ? 0 : -1,
77
+ });
78
+ if (action.kind === 'stop')
79
+ break;
80
+ this.deps.log.info('compaction_retry', {
81
+ attempt, reason: action.kind, code: last.slice(0, 60),
82
+ });
83
+ if (action.kind === 'escalate-main' || action.kind === 'retry-shrink') {
84
+ if (action.kind === 'escalate-main') {
85
+ choice = this.deps.mainChoice();
86
+ repairs = 0;
87
+ shrinks = 0;
88
+ }
89
+ else {
90
+ shrink *= action.factor;
91
+ shrinks += 1;
92
+ }
93
+ digest = this.digestFor(input, choice, instructions, shrink);
94
+ }
95
+ if (action.kind === 'retry-repair') {
96
+ repairHint = action.hint;
97
+ repairs += 1;
98
+ }
99
+ }
100
+ throw new Error(last);
101
+ }
102
+ /**
103
+ * The digest, and the window projection for whichever path will actually send it.
104
+ *
105
+ * THE PROJECTION IS PATH-DEPENDENT (P1-4). `agentic` sends an opening of three
106
+ * lines and then pulls what it needs, so projecting the WHOLE digest would
107
+ * refuse a request the agent never makes - and every token the multi-turn
108
+ * design saves would be spent on a phantom. The full-digest projection is kept
109
+ * for the single-shot path, where it is exactly right.
110
+ *
111
+ * `shrink` (< 1) is `retry-shrink`: the digest is rebuilt against a smaller
112
+ * effective window, which is what makes a window failure recoverable instead of
113
+ * terminal.
114
+ */
115
+ digestFor(input, choice, instructions, shrink = 1) {
116
+ const window = this.deps.getModelInfoFor(choice.ref).contextWindow;
117
+ const effective = shrink >= 1
118
+ ? window
119
+ : Math.max(COMPACTION_LIMITS.summarizerReserveTokens + 1, Math.floor(window * shrink));
120
+ const digest = buildDigest({ head: input.head, anchor: input.anchor,
121
+ generation: input.generation,
122
+ startIndex: input.headStartIndex, summarizerWindow: effective,
123
+ ...(input.prior ? { priorMemory: input.prior } : {}),
124
+ ...(input.legacySummary ? { legacySummary: input.legacySummary } : {}) });
125
+ if (this.windowProjection(input, choice, digest, instructions) +
126
+ CONTEXT_SAFETY_MARGIN_TOKENS >= window) {
127
+ // A DIFFERENT GATE FROM THE DIGEST'S LENGTH BUDGET, and it keeps a different
128
+ // reason code on purpose (A1). This one is the REAL ceiling - the actual
129
+ // request does not fit the summarizer's window - so it must still refuse.
130
+ // Giving it the length budget's name would send the retry ladder and every
131
+ // log reader after the wrong cause.
132
+ throw new Error('summarizer_window_exceeded');
133
+ }
134
+ return digest;
135
+ }
136
+ /**
137
+ * The window gate's projection: what the request BODY costs, path by path.
138
+ *
139
+ * UNCHANGED FROM THE PRE-v3 ARITHMETIC on purpose - the single-shot path added
140
+ * its output allowance here before this feature existed, the agentic path had
141
+ * none - so tightening this gate is not something a refactor may do quietly.
142
+ */
143
+ windowProjection(input, choice, digest, instructions) {
144
+ if (this.deps.isAgentic())
145
+ return this.agentOpeningTokens(input, digest, instructions);
146
+ return this.singleShotInputTokens(input, choice, digest, instructions)
147
+ + COMPACTION_LIMITS.summaryOutputTokens;
148
+ }
149
+ /**
150
+ * The budget gate's projection: the WHOLE next request, output included (§4.5).
151
+ *
152
+ * NOT A FIXED NUMBER. Charging every attempt the same `digestMaxChars / 4`
153
+ * would refuse the first, small request of the agentic path against any ceiling
154
+ * below ~31k tokens - a budget that never lets the feature start is not a
155
+ * budget. The projection is the request that is about to be sent.
156
+ */
157
+ requestProjection(input, choice, digest, instructions) {
158
+ if (this.deps.isAgentic()) {
159
+ return this.agentOpeningTokens(input, digest, instructions)
160
+ + COMPACTION_LIMITS.agentTurnOutputTokens;
161
+ }
162
+ return this.singleShotInputTokens(input, choice, digest, instructions)
163
+ + COMPACTION_LIMITS.summaryOutputTokens;
164
+ }
165
+ /** The first agent turn's input: three lines plus the outline allowance (P1-4). */
166
+ agentOpeningTokens(input, digest, instructions) {
167
+ return projectAgentOpeningTokens({
168
+ band: input, digest, ...(instructions ? { instructions } : {}),
169
+ });
170
+ }
171
+ /** The single-shot request's input size, without its output allowance. */
172
+ singleShotInputTokens(input, choice, digest, instructions) {
173
+ const request = buildSummarizeRequest({ ref: choice.ref, apiKey: '', digest: digest.text,
174
+ hasPriorSummary: !!input.prior, signal: new AbortController().signal, now: 0,
175
+ ...(instructions ? { instructions } : {}) });
176
+ return estimatePromptTokens(request.messages, request.systemPrompt);
177
+ }
178
+ /** The token projection the budget gate checks before a request is sent. */
179
+ budgetWouldExceed(state, input, choice, digest, instructions) {
180
+ return state.budget.wouldExceed(this.requestProjection(input, choice, digest, instructions));
181
+ }
182
+ /** Whether `choice` reaches the same endpoint as the main model (D-6). */
183
+ sameEndpoint(choice) {
184
+ const main = this.deps.mainChoice();
185
+ return choice.ref.providerId === main.ref.providerId
186
+ && (choice.ref.baseUrl ?? '') === (main.ref.baseUrl ?? '');
187
+ }
188
+ /** One attempt: the agent when it is available, the single JSON call otherwise. */
189
+ async attemptSummary(state, input, choice, digest, instructions, repairHint) {
190
+ if (this.deps.isAgentic()) {
191
+ return this.agentAttempt(state, input, choice, digest, instructions, repairHint);
192
+ }
193
+ return this.singleShot(state, input, choice, digest, instructions, repairHint);
194
+ }
195
+ /** The multi-turn path (W4). */
196
+ async agentAttempt(state, input, choice, digest, instructions, repairHint) {
197
+ const result = await runMemoryAgent({
198
+ band: input,
199
+ digest,
200
+ choice: { ref: choice.ref, role: choice.role },
201
+ ...(instructions ? { instructions } : {}),
202
+ ...(repairHint ? { repairHint } : {}),
203
+ }, {
204
+ // EVERY TURN IS BOUNDED LOCALLY, exactly like `callOnce` (the lesson of
205
+ // `CompactionOperation`: a provider that ignores the abort signal cannot be
206
+ // allowed to hold the whole compaction open). The race settles on Esc or on
207
+ // `callTimeoutMs`, whichever comes first, and aborts the operation so the
208
+ // next turn is never started.
209
+ runTurn: (request) => state.operation.run(() => this.deps.runAgentTurn(request), COMPACTION_LIMITS.callTimeoutMs),
210
+ }, {
211
+ budget: state.budget,
212
+ operation: state.operation,
213
+ emit: (event) => this.deps.emit(event),
214
+ onUsage: (usage) => this.deps.noteUsage(choice.ref, usage),
215
+ now: () => Date.now(),
216
+ });
217
+ // A SUCCESS WITH NO SUBMISSION IS THE SINGLE-SHOT FALLBACK (D-14): the model
218
+ // answered the first turn with a parsable delta and never called a tool, which
219
+ // is exactly the path a tool-less model takes. Recorded, not hidden - the card
220
+ // and `/compact status` say `(one-shot)`.
221
+ state.agent = {
222
+ turns: (state.agent?.turns ?? 0) + result.turns,
223
+ toolCalls: (state.agent?.toolCalls ?? 0) + result.toolCalls,
224
+ submissions: state.agent?.submissions ?? (result.ok ? result.submissions : 0),
225
+ ...(result.ok && result.submissions === 0 ? { fallback: 'single-shot' } : {}),
226
+ };
227
+ // THE DURABLE TRACE OF WHAT THE AGENT DID. A card scrolls away and `/compact
228
+ // status` reports only the last operation; this line is what a behaviour report
229
+ // three months from now can grep for.
230
+ this.deps.log.info('compaction_agent_summary', {
231
+ ok: result.ok, turns: result.turns, toolCalls: result.toolCalls,
232
+ ...(result.ok ? { submissions: result.submissions } : {
233
+ reason: result.reason.slice(0, 120),
234
+ }),
235
+ });
236
+ if (!result.ok)
237
+ return { ok: false, reason: result.reason };
238
+ state.model = choice.ref.modelId;
239
+ try {
240
+ return { ok: true, memory: memoryFromDelta(input, digest, result.delta) };
241
+ }
242
+ catch (error) {
243
+ return { ok: false, reason: errorText(error) };
244
+ }
245
+ }
246
+ /** The last rung (D-14): one JSON request, exactly as before this feature. */
247
+ async singleShot(state, input, choice, digest, instructions, repairHint) {
248
+ let text;
249
+ try {
250
+ text = await this.deps.callOnce(state, choice, {
251
+ digest: digest.text, hasPriorSummary: !!input.prior,
252
+ ...(instructions ? { instructions } : {}),
253
+ ...(repairHint ? { validationError: repairHint } : {}),
254
+ });
255
+ }
256
+ catch (error) {
257
+ const transport = describeTransportFailure(error, state.operation.signal);
258
+ return { ok: false, reason: transport ?? errorText(error) };
259
+ }
260
+ state.agent = { turns: 1, toolCalls: 0, submissions: 1, fallback: 'single-shot' };
261
+ try {
262
+ const delta = parseMemoryDelta(text);
263
+ validateMemoryDelta(delta, { sourceMap: digest.sourceMap, prior: input.prior,
264
+ hasSummarizableMessages: digest.coverage.summarizedMessages > 0 });
265
+ return { ok: true, memory: mergeMemory({
266
+ input, delta, sourceMap: digest.sourceMap, coverage: digest.coverage,
267
+ }) };
268
+ }
269
+ catch (error) {
270
+ return { ok: false, reason: errorText(error) };
271
+ }
272
+ }
273
+ }
@@ -262,6 +262,17 @@ export declare class CompactionWiring {
262
262
  * registry and registers no adapters.
263
263
  */
264
264
  private getRegistry;
265
+ /**
266
+ * One agent turn (W4 / P1-6): assemble, stream, consume, project.
267
+ *
268
+ * THE PROJECTION IS THE WHOLE ADAPTER. `AssistantMessage.content` is a block
269
+ * list (`text` / `thinking` / `tool_call`); the agent loop wants the concatenated
270
+ * text plus the calls - exactly the two things `digest.ts` already reads off a
271
+ * message. Usage is forwarded as the provider reported it and defaults to zeros,
272
+ * because a `computeCost`-able object must exist even when an adapter forgets the
273
+ * field (the fast tier's RV-11 lesson).
274
+ */
275
+ private runAgentTurn;
265
276
  private onCompactorEvent;
266
277
  private onAgentEvent;
267
278
  /**
@@ -291,6 +302,14 @@ export declare class CompactionWiring {
291
302
  private archive;
292
303
  /** This run's archive key, for `/compact history` and `/compact show`. */
293
304
  archiveRunId(): string;
305
+ /**
306
+ * The archive's `prune` section, built from the compactor's settled plan.
307
+ *
308
+ * THE DETAIL COMES FROM THE PLAN, NOT FROM THE RECORD. The record carries counts
309
+ * so the card can state them; `/compact show` and a human audit need the message
310
+ * indices and the kept copies, and those only exist in the plan.
311
+ */
312
+ private pruneSection;
294
313
  /**
295
314
  * The minimum a card needs to settle when the compactor's own record has not
296
315
  * arrived (see `open`). `null` when no card was ever opened — the
@@ -1,9 +1,10 @@
1
1
  import { shouldCompactAt } from '@aragon-agent/tui/model/compaction/pressure';
2
- import { DEFAULT_RETRY_POLICY, estimatePromptTokens, initProviders, validateHistory, } from '@aragon-agent/core';
2
+ import { DEFAULT_RETRY_POLICY, consumeStream, estimatePromptTokens, initProviders, validateHistory, } from '@aragon-agent/core';
3
3
  import { getLogger } from '../logging/logger.js';
4
4
  import { mintRunId, writeArchive } from './archive.js';
5
5
  import { createChildContextManager } from './child.js';
6
6
  import { Compactor } from './compactor.js';
7
+ import { assistantText, usageOf } from './summarize-call.js';
7
8
  import { ContextMeter } from '@aragon-agent/tui/model/compaction/meter';
8
9
  /**
9
10
  * At most three retries inside 18 s - bounded, and not the user's ten (D-10).
@@ -138,6 +139,11 @@ export class CompactionWiring {
138
139
  getMessages: deps.getMessages,
139
140
  getSystemPrompt: deps.getSystemPrompt,
140
141
  complete: (providerId, request) => this.getRegistry().complete(providerId, request),
142
+ // THE AGENT'S TRANSPORT IS THE SAME REGISTRY WITHOUT A STREAMING CONSUMER
143
+ // (P1-6): one request in, text + tool calls + usage out. Core's `withRetry`
144
+ // still sits underneath, which is the ONE place a transport retry belongs
145
+ // (D-6) - adding another here would multiply the quota a 429 sees.
146
+ runAgentTurn: (request) => this.runAgentTurn(request),
141
147
  emit: (event) => this.onCompactorEvent(event),
142
148
  notify: deps.notify,
143
149
  // ONE METER PER PROCESS. The compactor must not build its own fallback
@@ -400,6 +406,12 @@ export class CompactionWiring {
400
406
  selfDisabled: totals.selfDisabled,
401
407
  ...(totals.selfDisabledReason ? { selfDisabledReason: totals.selfDisabledReason } : {}),
402
408
  generation: totals.generation,
409
+ // THE THREE v3 SURFACES (W1 / W3 / W4), all optional: a session that has not
410
+ // compacted yet carries none of them, so `/compact status` and the settings
411
+ // page render exactly what they rendered before this feature.
412
+ prune: totals.prune,
413
+ ...(totals.budget ? { budget: totals.budget } : {}),
414
+ ...(totals.agent ? { agent: totals.agent } : {}),
403
415
  pressure,
404
416
  };
405
417
  }
@@ -443,6 +455,43 @@ export class CompactionWiring {
443
455
  }
444
456
  return this.registry;
445
457
  }
458
+ /**
459
+ * One agent turn (W4 / P1-6): assemble, stream, consume, project.
460
+ *
461
+ * THE PROJECTION IS THE WHOLE ADAPTER. `AssistantMessage.content` is a block
462
+ * list (`text` / `thinking` / `tool_call`); the agent loop wants the concatenated
463
+ * text plus the calls - exactly the two things `digest.ts` already reads off a
464
+ * message. Usage is forwarded as the provider reported it and defaults to zeros,
465
+ * because a `computeCost`-able object must exist even when an adapter forgets the
466
+ * field (the fast tier's RV-11 lesson).
467
+ */
468
+ async runAgentTurn(request) {
469
+ const apiKey = this.deps.getApiKey(request.ref.providerId, request.role);
470
+ if (!apiKey)
471
+ throw new Error('no_api_key');
472
+ const llm = {
473
+ model: request.ref.modelId,
474
+ ...(request.ref.baseUrl ? { baseUrl: request.ref.baseUrl } : {}),
475
+ apiKey,
476
+ systemPrompt: request.systemPrompt,
477
+ messages: [...request.messages],
478
+ tools: request.tools,
479
+ maxTokens: request.maxTokens,
480
+ // PAIRED WITH `temperature: 0` for the same reason the single-shot call is:
481
+ // the Anthropic adapter deletes one when the other is set.
482
+ thinkingLevel: 'off',
483
+ temperature: 0,
484
+ signal: request.signal,
485
+ };
486
+ const message = await consumeStream(this.getRegistry().stream(request.ref.providerId, llm));
487
+ return {
488
+ text: assistantText(message),
489
+ toolCalls: message.content.flatMap((block) => block.type === 'tool_call'
490
+ ? [{ toolCallId: block.toolCallId, toolName: block.toolName, args: block.args ?? {} }]
491
+ : []),
492
+ usage: usageOf(message),
493
+ };
494
+ }
446
495
  onCompactorEvent(event) {
447
496
  if (event.type === 'compaction_start') {
448
497
  this.open = { index: event.index, trigger: event.trigger, model: event.model };
@@ -613,6 +662,11 @@ export class CompactionWiring {
613
662
  messagesAfter: record.messagesAfter,
614
663
  ...(record.summary !== undefined ? { summary: record.summary } : {}),
615
664
  ...(record.tailRelief ? { tailRelief: record.tailRelief } : {}),
665
+ // THE THREE v3 SECTIONS TRAVEL WITH THE RECORD, never re-derived here
666
+ // (P0-3: the archive schema grows additively, `version` stays 1).
667
+ ...(record.prune && record.prune.actions > 0 ? { prune: this.pruneSection() } : {}),
668
+ ...(record.budget ? { budget: record.budget } : {}),
669
+ ...(record.agent ? { agent: record.agent } : {}),
616
670
  dropped: dropped ?? [],
617
671
  ...(this.deps.archiveDir ? { dir: this.deps.archiveDir } : {}),
618
672
  });
@@ -621,6 +675,16 @@ export class CompactionWiring {
621
675
  archiveRunId() {
622
676
  return this.runId;
623
677
  }
678
+ /**
679
+ * The archive's `prune` section, built from the compactor's settled plan.
680
+ *
681
+ * THE DETAIL COMES FROM THE PLAN, NOT FROM THE RECORD. The record carries counts
682
+ * so the card can state them; `/compact show` and a human audit need the message
683
+ * indices and the kept copies, and those only exist in the plan.
684
+ */
685
+ pruneSection() {
686
+ return { actions: this.compactor.lastPruneActions() };
687
+ }
624
688
  /**
625
689
  * The minimum a card needs to settle when the compactor's own record has not
626
690
  * arrived (see `open`). `null` when no card was ever opened — the
@@ -95,7 +95,7 @@ export declare const UPDATE_CONFIG_SET_KEYS: readonly ["update.mode", "update.ch
95
95
  * while the key is visibly listed one command over. Manual-test row 9 — the
96
96
  * persisted-off-survives-a-flagless-run check — runs exactly that command.
97
97
  */
98
- export declare const COMPACTION_CONFIG_SET_KEYS: readonly ["compaction.enabled", "compaction.threshold", "compaction.warnThreshold", "compaction.keepRecentTurns", "compaction.useFastTier", "compaction.onFailure", "compaction.subagents", "compaction.archive"];
98
+ export declare const COMPACTION_CONFIG_SET_KEYS: readonly ["compaction.enabled", "compaction.threshold", "compaction.warnThreshold", "compaction.keepRecentTurns", "compaction.useFastTier", "compaction.onFailure", "compaction.subagents", "compaction.archive", "compaction.prune", "compaction.agentic", "compaction.budgetTokens", "compaction.budgetUsd"];
99
99
  /**
100
100
  * Config keys under `governance.` that `aragon config set` accepts (governance-mode 11.1).
101
101
  * Every key is writable and ONE level deep, so `runConfigGet`'s single-dot split resolves it.
@@ -166,6 +166,14 @@ export const COMPACTION_CONFIG_SET_KEYS = [
166
166
  'compaction.onFailure',
167
167
  'compaction.subagents',
168
168
  'compaction.archive',
169
+ // THE FOUR v3 KEYS (context-compaction-v3 §4.6). Listed for the reason this
170
+ // block records: `config list` shows every key dynamically and `config set`
171
+ // refuses what is not here, so a budget a script cannot set is a budget the
172
+ // feature does not really have.
173
+ 'compaction.prune',
174
+ 'compaction.agentic',
175
+ 'compaction.budgetTokens',
176
+ 'compaction.budgetUsd',
169
177
  ];
170
178
  /**
171
179
  * Config keys under `governance.` that `aragon config set` accepts (governance-mode 11.1).
@@ -627,6 +635,14 @@ export function applyCompactionConfigSet(key, value) {
627
635
  return patch(clampOne('subagents', isTrue(value)));
628
636
  case 'compaction.archive':
629
637
  return patch(clampOne('archive', isTrue(value)));
638
+ case 'compaction.prune':
639
+ return patch(clampOne('prune', isTrue(value)));
640
+ case 'compaction.agentic':
641
+ return patch(clampOne('agentic', isTrue(value)));
642
+ case 'compaction.budgetTokens':
643
+ return patch(clampOne('budgetTokens', Number(value)));
644
+ case 'compaction.budgetUsd':
645
+ return patch(clampOne('budgetUsd', Number(value)));
630
646
  default:
631
647
  return null;
632
648
  }
@@ -18,7 +18,9 @@
18
18
  * ARAGON_UPDATE,
19
19
  * ARAGON_COMPACTION, ARAGON_COMPACTION_THRESHOLD,
20
20
  * ARAGON_COMPACTION_KEEP_TURNS, ARAGON_COMPACTION_SUBAGENTS,
21
- * ARAGON_COMPACTION_ARCHIVE,
21
+ * ARAGON_COMPACTION_ARCHIVE, ARAGON_COMPACTION_AGENTIC,
22
+ * ARAGON_COMPACTION_PRUNE, ARAGON_COMPACTION_BUDGET_TOKENS,
23
+ * ARAGON_COMPACTION_BUDGET_USD,
22
24
  * ARAGON_JOBS_ENABLED, ARAGON_JOBS_WAIT_SECONDS, ARAGON_JOBS_STALL_SECONDS,
23
25
  * ARAGON_JOBS_PERSIST_LOG, ARAGON_JOBS_NOTICE_STEER,
24
26
  * ARAGON_PROMPTS (the quick-prompt library's `enabled` switch, and only that),