@aragon-agent/cli 0.6.62 → 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.
- package/README.md +99 -7
- package/dist/agent/headless.js +18 -0
- package/dist/commands/builtins.js +2 -1
- package/dist/commands/catalog.js +1 -1
- package/dist/compaction/archive.d.ts +27 -1
- package/dist/compaction/archive.js +8 -0
- package/dist/compaction/budget.d.ts +73 -0
- package/dist/compaction/budget.js +89 -0
- package/dist/compaction/child.js +6 -1
- package/dist/compaction/command.js +147 -1
- package/dist/compaction/compactor.d.ts +132 -15
- package/dist/compaction/compactor.js +288 -95
- package/dist/compaction/context-command.js +21 -0
- package/dist/compaction/memory-agent-prompt.d.ts +32 -0
- package/dist/compaction/memory-agent-prompt.js +76 -0
- package/dist/compaction/memory-agent-tools.d.ts +88 -0
- package/dist/compaction/memory-agent-tools.js +338 -0
- package/dist/compaction/memory-agent.d.ts +114 -0
- package/dist/compaction/memory-agent.js +220 -0
- package/dist/compaction/prune.d.ts +129 -0
- package/dist/compaction/prune.js +386 -0
- package/dist/compaction/retry-plan.d.ts +103 -0
- package/dist/compaction/retry-plan.js +136 -0
- package/dist/compaction/summarize-ladder.d.ts +149 -0
- package/dist/compaction/summarize-ladder.js +273 -0
- package/dist/compaction/wiring.d.ts +19 -0
- package/dist/compaction/wiring.js +65 -1
- package/dist/config/cli-commands.d.ts +1 -1
- package/dist/config/cli-commands.js +16 -0
- package/dist/config/env.d.ts +3 -1
- package/dist/config/env.js +44 -2
- package/dist/exec/events.d.ts +30 -0
- package/dist/exec/runner.js +6 -0
- package/dist/logging/install.d.ts +27 -0
- package/dist/session/validate-session.js +11 -0
- 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
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
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
|
|
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.
|
|
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
|
package/dist/agent/headless.js
CHANGED
|
@@ -272,6 +272,24 @@ export async function runHeadless(controller, prompt, options = {}) {
|
|
|
272
272
|
`${r.tailRelief.messages === 1 ? 'result' : 'results'} in the retained turns ` +
|
|
273
273
|
`(${formatTokens(r.tailRelief.charsRemoved)} chars)\n`);
|
|
274
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
|
+
}
|
|
275
293
|
});
|
|
276
294
|
/**
|
|
277
295
|
* `[accept] <n>/<total> checked`, plus the failure count when there is one.
|
|
@@ -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 |
|
|
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
|
{
|
package/dist/commands/catalog.js
CHANGED
|
@@ -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 |
|
|
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
|
+
}
|
package/dist/compaction/child.js
CHANGED
|
@@ -131,7 +131,12 @@ export function createChildContextManager(req, deps) {
|
|
|
131
131
|
},
|
|
132
132
|
// MECHANISM B - the instance bound (RV-2 / DH-16). The SAME bound the
|
|
133
133
|
// lead's own manager runs under (main-agent parity).
|
|
134
|
-
|
|
134
|
+
//
|
|
135
|
+
// `agentic: false` IS THE THIRD BOUND (v3 §4.5). A child has no card and no
|
|
136
|
+
// `notify`, so a multi-turn compaction inside it is spend nobody can watch
|
|
137
|
+
// and turns nobody can see; prune and one JSON call are enough for a
|
|
138
|
+
// background worker.
|
|
139
|
+
{ maxPerRun: COMPACTION_LIMITS.maxPerRun, agentic: false });
|
|
135
140
|
return {
|
|
136
141
|
// THERE IS NO `/compact` FOR A CHILD, so nothing is ever queued and the
|
|
137
142
|
// manual branch of `shouldCompact` is unreachable by construction.
|
|
@@ -112,6 +112,21 @@ export function formatCompactionStatus(ctx) {
|
|
|
112
112
|
`(${formatTokens(relief.charsRemoved)} chars) in ` +
|
|
113
113
|
`${relief.compactions} ${relief.compactions === 1 ? 'compaction' : 'compactions'}`);
|
|
114
114
|
}
|
|
115
|
+
// THE v3 SURFACES (W1 / W3 / W4). Rendered only when they have something to say,
|
|
116
|
+
// so a session that has never compacted reads exactly as it did before.
|
|
117
|
+
const prune = snapshot.prune;
|
|
118
|
+
if (prune && prune.actions > 0) {
|
|
119
|
+
lines.push(` Prune: ${prune.actions} bodies, ${formatTokens(prune.chars)} chars rewritten`);
|
|
120
|
+
}
|
|
121
|
+
const budget = snapshot.budget;
|
|
122
|
+
if (budget) {
|
|
123
|
+
lines.push(` Budget: ${formatBudgetLine(budget)}`);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
lines.push(` Budget: ${budgetHeadline(config.budgetTokens, config.budgetUsd)}`);
|
|
127
|
+
}
|
|
128
|
+
lines.push(` Agentic: ${config.agentic ? 'on' : 'off'}` +
|
|
129
|
+
(snapshot.agent ? ` (${agentLine(snapshot.agent)})` : ''));
|
|
115
130
|
const archives = archiveSummary(ctx);
|
|
116
131
|
if (archives)
|
|
117
132
|
lines.push(` Archive ${archives}`);
|
|
@@ -252,6 +267,16 @@ function formatCompactionShow(ctx, raw) {
|
|
|
252
267
|
lines.push(` Clipped: ${entry.tailRelief.messages} tool results in the retained turns ` +
|
|
253
268
|
`(${formatTokens(entry.tailRelief.charsRemoved)} chars)`);
|
|
254
269
|
}
|
|
270
|
+
// THE v3 SECTIONS, printed only when this archive has them (W1 / W3 / W4).
|
|
271
|
+
// A v1 archive has none of the three and renders exactly as it did before.
|
|
272
|
+
if (entry.prune) {
|
|
273
|
+
lines.push(` Pruned: ${entry.prune.actions.length} bodies `
|
|
274
|
+
+ `(${formatTokens(entry.prune.actions.reduce((sum, a) => sum + a.removedChars, 0))} chars)`);
|
|
275
|
+
}
|
|
276
|
+
if (entry.budget)
|
|
277
|
+
lines.push(` Budget: ${formatBudgetLine(entry.budget)}`);
|
|
278
|
+
if (entry.agent)
|
|
279
|
+
lines.push(` Agent: ${agentLine(entry.agent)}`);
|
|
255
280
|
lines.push(` File: ${entry.path}`);
|
|
256
281
|
if (entry.summary) {
|
|
257
282
|
lines.push('');
|
|
@@ -259,7 +284,99 @@ function formatCompactionShow(ctx, raw) {
|
|
|
259
284
|
}
|
|
260
285
|
return lines.join('\n');
|
|
261
286
|
}
|
|
262
|
-
|
|
287
|
+
/**
|
|
288
|
+
* `/compact budget ...` (W3): `budget <tokens>`, `budget usd <amount>`, `off`.
|
|
289
|
+
*
|
|
290
|
+
* RETURNS THE TOAST TEXT, OR `null` AFTER PRINTING ITS OWN REFUSAL. The applied
|
|
291
|
+
* value is reported, never the requested one: `clampCompactionConfig` may move a
|
|
292
|
+
* number, and reporting what was typed would make the clamp invisible.
|
|
293
|
+
*/
|
|
294
|
+
function applyBudgetVerb(ctx, raw) {
|
|
295
|
+
const controller = ctx.controller;
|
|
296
|
+
const words = raw.split(/\s+/).filter(Boolean);
|
|
297
|
+
const usd = (words[0] ?? '').toLowerCase() === 'usd';
|
|
298
|
+
const amount = (usd ? words[1] : words[0]) ?? '';
|
|
299
|
+
const off = amount === '' || /^(0|off|none|unlimited)$/i.test(amount);
|
|
300
|
+
const parsed = off ? 0 : Number(amount.replace(/[$,]/g, ''));
|
|
301
|
+
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
302
|
+
ctx.notify('warn', 'Usage: /compact budget <tokens|off> | /compact budget usd <amount|off>');
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
const patch = usd
|
|
306
|
+
? { budgetUsd: parsed } : { budgetTokens: Math.round(parsed) };
|
|
307
|
+
const applied = controller.setCompactionConfig(patch);
|
|
308
|
+
ctx.persistConfig({ compaction: patch });
|
|
309
|
+
if (usd) {
|
|
310
|
+
return applied.budgetUsd > 0
|
|
311
|
+
? `Compaction budget: $${applied.budgetUsd.toFixed(2)} per operation.`
|
|
312
|
+
: 'Compaction USD budget: unlimited.';
|
|
313
|
+
}
|
|
314
|
+
return applied.budgetTokens > 0
|
|
315
|
+
? `Compaction budget: ${formatTokens(applied.budgetTokens)} tokens per operation.`
|
|
316
|
+
: 'Compaction token budget: unlimited.';
|
|
317
|
+
}
|
|
318
|
+
const USAGE = 'Usage: /compact [status | spend | budget [usd] <n|off> | agent on|off | prune on|off '
|
|
319
|
+
+ '| on | off | threshold <n> | keep <n> | history | show <n> | <instructions>]';
|
|
320
|
+
/** The `Budget:` value for a snapshot: spend against both ceilings (W3). */
|
|
321
|
+
function formatBudgetLine(budget) {
|
|
322
|
+
const tokens = budget.limitTokens > 0
|
|
323
|
+
? `${formatTokens(budget.spentTokens)} / ${formatTokens(budget.limitTokens)} tokens`
|
|
324
|
+
: `${formatTokens(budget.spentTokens)} tokens (no limit)`;
|
|
325
|
+
const usd = budget.limitUsd <= 0
|
|
326
|
+
? 'no USD limit'
|
|
327
|
+
: budget.priceUnknown
|
|
328
|
+
? `USD n/a (no price table for this model)`
|
|
329
|
+
: `${formatCost(budget.spentUsd)} / ${formatCost(budget.limitUsd)}`;
|
|
330
|
+
const stop = budget.stop === undefined ? '' : ` - stopped: ${budget.stop}`;
|
|
331
|
+
return `${tokens} - ${usd}${stop}`;
|
|
332
|
+
}
|
|
333
|
+
/** The `Budget:` value before the first compaction: what the NEXT one may spend. */
|
|
334
|
+
function budgetHeadline(tokens, usd) {
|
|
335
|
+
const parts = [
|
|
336
|
+
tokens > 0 ? `${formatTokens(tokens)} tokens per operation` : 'no token limit',
|
|
337
|
+
usd > 0 ? `${formatCost(usd)} per operation` : 'no USD limit',
|
|
338
|
+
];
|
|
339
|
+
return `${parts.join(' - ')} (nothing spent yet)`;
|
|
340
|
+
}
|
|
341
|
+
/** `4 turns, 9 tool calls` for the `Agentic:` row (W4). */
|
|
342
|
+
function agentLine(agent) {
|
|
343
|
+
const parts = [
|
|
344
|
+
`${agent.turns} ${agent.turns === 1 ? 'turn' : 'turns'}`,
|
|
345
|
+
`${agent.toolCalls} tool ${agent.toolCalls === 1 ? 'call' : 'calls'}`,
|
|
346
|
+
`${agent.submissions} ${agent.submissions === 1 ? 'submission' : 'submissions'}`,
|
|
347
|
+
];
|
|
348
|
+
return `last: ${parts.join(', ')}`;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* `/compact spend` - the session's cumulative spend and the last operation's ledger.
|
|
352
|
+
*
|
|
353
|
+
* TWO DIFFERENT QUESTIONS, and answering only the first is what made a budget
|
|
354
|
+
* feel like a black box: "what has compaction cost this session" (a total) and
|
|
355
|
+
* "what did the last one cost against its ceiling" (a snapshot).
|
|
356
|
+
*/
|
|
357
|
+
function formatCompactionSpend(ctx) {
|
|
358
|
+
const snapshot = ctx.controller.getCompactionSnapshot();
|
|
359
|
+
const config = ctx.controller.getCompactionConfig();
|
|
360
|
+
const pricing = snapshot.pricingUnknown
|
|
361
|
+
? `unknown (no price table for ${snapshot.model || 'the summarizer'})`
|
|
362
|
+
: formatCost(compactionCost(ctx));
|
|
363
|
+
const lines = [
|
|
364
|
+
'compaction spend (this session)',
|
|
365
|
+
` Tokens: ${formatTokens(snapshot.usage.inputTokens)} in / `
|
|
366
|
+
+ `${formatTokens(snapshot.usage.outputTokens)} out`,
|
|
367
|
+
` Cost: ${pricing}`,
|
|
368
|
+
` Calls: ${snapshot.compactions} ${snapshot.compactions === 1 ? 'attempt' : 'attempts'}`,
|
|
369
|
+
` Limits: ${budgetHeadline(config.budgetTokens, config.budgetUsd)}`,
|
|
370
|
+
];
|
|
371
|
+
if (snapshot.budget) {
|
|
372
|
+
lines.push(` Last: ${formatBudgetLine(snapshot.budget)}`);
|
|
373
|
+
}
|
|
374
|
+
if (snapshot.prune && snapshot.prune.actions > 0) {
|
|
375
|
+
lines.push(` Pruned: ${snapshot.prune.actions} bodies, `
|
|
376
|
+
+ `${formatTokens(snapshot.prune.chars)} chars (free)`);
|
|
377
|
+
}
|
|
378
|
+
return lines.join('\n');
|
|
379
|
+
}
|
|
263
380
|
/**
|
|
264
381
|
* The `/compact` handler.
|
|
265
382
|
*
|
|
@@ -324,6 +441,35 @@ export async function runCompactCommand(ctx) {
|
|
|
324
441
|
ctx.toast('success', `Keeping ${applied.keepRecentTurns} recent turns verbatim.`);
|
|
325
442
|
return;
|
|
326
443
|
}
|
|
444
|
+
// --- THE v3 VERBS, ALL BEFORE THE FREE-TEXT FALL-THROUGH (P1-2) -----------
|
|
445
|
+
// `/compact spend` used to reach the fall-through, which took the word "spend"
|
|
446
|
+
// as summarizer instructions and compacted the conversation. Every new verb is
|
|
447
|
+
// therefore handled here, above `// --- Compact now`.
|
|
448
|
+
if (verb === 'spend') {
|
|
449
|
+
ctx.notify('info', formatCompactionSpend(ctx));
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (verb === 'budget') {
|
|
453
|
+
const applied = applyBudgetVerb(ctx, arg.slice((rawVerb ?? '').length).trim());
|
|
454
|
+
if (applied !== null)
|
|
455
|
+
ctx.toast('success', applied);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
if (verb === 'agent' || verb === 'prune') {
|
|
459
|
+
const on = value === 'on' || value === 'true' || value === '1';
|
|
460
|
+
const off = value === 'off' || value === 'false' || value === '0';
|
|
461
|
+
if (!on && !off) {
|
|
462
|
+
ctx.notify('warn', `Usage: /compact ${verb} on|off`);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
const patch = verb === 'agent' ? { agentic: on } : { prune: on };
|
|
466
|
+
const applied = controller.setCompactionConfig(patch);
|
|
467
|
+
ctx.persistConfig({ compaction: patch });
|
|
468
|
+
ctx.toast('success', verb === 'agent'
|
|
469
|
+
? `Multi-turn compaction ${applied.agentic ? 'on' : 'off'}.`
|
|
470
|
+
: `Redundancy pruning ${applied.prune ? 'on' : 'off'}.`);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
327
473
|
// BEFORE THE FREE-TEXT FALL-THROUGH, so a user cannot accidentally summarize
|
|
328
474
|
// with the word "history".
|
|
329
475
|
if (verb === 'history') {
|