@hncode/hncode 0.8.1 → 0.8.2

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.
@@ -1,327 +1,400 @@
1
- // Tool-result size control.
2
- //
3
- // Two separate problems, both of which used to be silent:
4
- //
5
- // 1. A SINGLE huge result. Per-tool caps exist (`MAX_OUTPUT_BYTES` in
6
- // tools/utils.js) but `Read` deliberately has none, and nothing bounded the
7
- // AGGREGATE of a step's results — a turn with four Reads could add half a
8
- // megabyte to a history that is then resent on every later request. Real
9
- // sessions in ~/.hncode/sessions reached 5 MB this way.
10
- // 2. OLD results that no longer matter. A file read forty turns ago is dead
11
- // weight, but the whole history is resent every request, so it is paid for
12
- // again and again until something compacts.
13
- //
14
- // The cap is applied where the result is BUILT (see `shapeToolResult`), and the
15
- // overflow is kept, not lost: it goes to a file under the session's own
16
- // directory and the model gets a bounded preview plus the path, so it can Read
17
- // the rest if it turns out to need it. This mirrors Claude Code's
18
- // `<persisted-output>` handling (src/utils/toolResultStorage.ts).
19
- //
20
- // The ages pass (stale-pass) is the cheap half of compaction: it clears the
21
- // BODY of old tool results while leaving the message — and therefore the
22
- // assistant/tool pairing and the exact prefix length — untouched, so it does not
23
- // disturb the message list shape the provider has already cached. Claude Code
24
- // does the same thing in microCompact.ts ("[Old tool result content cleared]").
25
-
26
- import fs from 'node:fs';
27
- import path from 'node:path';
28
-
29
- // Bytes of a single tool result that are kept inline. Above this the overflow is
30
- // written to disk. 50 KB is Claude Code's DEFAULT_MAX_RESULT_SIZE_CHARS and is
31
- // comfortably more than a whole source file's worth of lines.
32
- export const MAX_RESULT_BYTES = 50 * 1024;
33
-
34
- // Bytes of a spilled result that stay in the transcript as a preview.
35
- export const PREVIEW_BYTES = 2 * 1024;
36
-
37
- // Trigger ratio: trim once the request reaches this fraction of the model window.
38
- // 50% by default (`trim_threshold` / HNCODE_TRIM_THRESHOLD). Well below the
39
- // compaction trigger on purpose — this is the cheap pass that keeps the history
40
- // from ever getting near compaction in the first place.
41
- export const DEFAULT_TRIM_THRESHOLD = 0.5;
42
-
43
- // Fraction of the tool-result TEXT that survives a trim. 30% by default
44
- // (`trim_keep_ratio` / HNCODE_TRIM_KEEP_RATIO); the rest of the eligible tool text is
45
- // elided.
46
- //
47
- // A DIFFERENT denominator from `trim_threshold` above, on purpose. The threshold asks
48
- // whether the request is too big for the window (a share of the WINDOW); this asks how much
49
- // of the removable output stays (a share of the TOOL TEXT). Measuring this against the
50
- // request was tried and reverted — at a 1M window the budget then exceeded all the elidable
51
- // text, so `/trim 0.6` could not trim anything at all.
52
- //
53
- // The conversation is protected by the candidate filter in `planTrim`, not by a ratio:
54
- // only messages with `role === 'tool'` are ever elided.
55
- export const DEFAULT_TRIM_KEEP_RATIO = 0.3;
56
-
57
- // A tool result shorter than this is never worth eliding: the marker plus the
58
- // pointer would cost more than the text it replaces.
59
- export const MIN_TRIM_BYTES = 512;
60
-
61
- export const CLEARED_MARKER = '[Old tool result content cleared]';
62
- export const PERSISTED_TAG = 'persisted-output';
63
-
64
- // Directory for spilled results, beside the session file so it is cleaned up
65
- // with the session rather than accumulating in a temp dir.
66
- export function spillDir(sessionId) {
67
- const root = process.env.HNCODE_HOME || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.hncode');
68
- return path.join(root, 'tool-results', String(sessionId || 'unscoped'));
69
- }
70
-
71
- // Write `text` to disk and return the preview + path, or null when the write
72
- // fails (a read-only disk must not fail the tool call).
73
- export function spillResult(sessionId, toolCallId, text) {
74
- try {
75
- const dir = spillDir(sessionId);
76
- fs.mkdirSync(dir, { recursive: true });
77
- // The tool-call id is already a unique, filesystem-safe token from the
78
- // provider, so it needs no sanitizing beyond dropping path separators.
79
- const safe = String(toolCallId || 'result').replace(/[^A-Za-z0-9_.-]/g, '_');
80
- const file = path.join(dir, `${safe}.txt`);
81
- fs.writeFileSync(file, text, 'utf8');
82
- return { file, preview: previewOf(text, PREVIEW_BYTES), originalBytes: Buffer.byteLength(text, 'utf8') };
83
- } catch {
84
- return null;
85
- }
86
- }
87
-
88
- // A preview cut on a line boundary when one is close enough, so the model does
89
- // not receive half a line of code as its last visible detail.
90
- export function previewOf(text, maxBytes) {
91
- const s = String(text == null ? '' : text);
92
- if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;
93
- let cut = Buffer.from(s, 'utf8').subarray(0, maxBytes).toString('utf8');
94
- if (cut.endsWith('\uFFFD')) cut = cut.slice(0, -1);
95
- const nl = cut.lastIndexOf('\n');
96
- if (nl > maxBytes * 0.5) cut = cut.slice(0, nl);
97
- return cut;
98
- }
99
-
100
- // The message the model sees in place of an oversized result. It says what
101
- // happened, how big it was, where the rest is, and how to get it — an agent that
102
- // cannot tell why its output is missing retries the same call forever.
103
- export function spillNotice(spilled) {
104
- return [
105
- `Output too large (${fmtBytes(spilled.originalBytes)}). Full output saved to: ${spilled.file}`,
106
- '',
107
- `Preview (first ${fmtBytes(PREVIEW_BYTES)}):`,
108
- spilled.preview,
109
- '',
110
- `Read the file above to see the rest — use start_line / end_line to page through it.`,
111
- ].join('\n');
112
- }
113
-
114
- export function fmtBytes(n) {
115
- const b = Number(n) || 0;
116
- if (b < 1024) return `${b} B`;
117
- if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
118
- return `${(b / (1024 * 1024)).toFixed(1)} MB`;
119
- }
120
-
121
- // Shape ONE tool result for the model: pass small results through, spill big
122
- // ones. Returns { content, spilled } where `content` is what goes into the
123
- // message. `sessionId`/`toolCallId` identify the spill file.
124
- export function shapeToolResult(content, { sessionId, toolCallId, maxBytes = MAX_RESULT_BYTES } = {}) {
125
- if (typeof content !== 'string') return { content, spilled: false };
126
- if (Buffer.byteLength(content, 'utf8') <= maxBytes) return { content, spilled: false };
127
- const spilled = spillResult(sessionId, toolCallId, content);
128
- // The write failed: a normal-sized preview is still better than megabytes, and
129
- // the notice must not claim a path that does not exist.
130
- if (!spilled) {
131
- return {
132
- content: `${previewOf(content, PREVIEW_BYTES)}\n\n[Output truncated: ${fmtBytes(Buffer.byteLength(content, 'utf8'))} total; the full output could not be saved.]`,
133
- spilled: false,
134
- };
135
- }
136
- return { content: spillNotice(spilled), spilled: true };
137
- }
138
-
139
- // Which tool results to elide, and by how much.
140
- //
141
- // RULE (the user's): keep a FRACTION of the TOOL-RESULT TEXT, the newest part.
142
- // Walk the results from newest to oldest accumulating their size; once the total kept
143
- // exceeds `keepRatio` of ALL tool-result text, everything older is elided.
144
- //
145
- // THE DENOMINATOR IS THE TOOL TEXT, NOT THE REQUEST, and the two knobs deliberately use
146
- // different scales because they answer different questions:
147
- //
148
- // * `trimThreshold` asks "is the request too big for the window yet?" — a share of the
149
- // WINDOW.
150
- // * `keep` asks "of the output we are allowed to remove, how much stays?" — a share of
151
- // the TOOL TEXT.
152
- //
153
- // Measuring `keep` against the request was tried and reverted: at a 1M window with 270k of
154
- // tool text, `threshold` fires at 500k while `keep=0.6` asks to retain 300k — MORE than the
155
- // 270k that could ever be elided. So `/trim 0.6` reported "nothing to trim", and it did so
156
- // for every request above 450k. A knob whose behaviour depends on a total the user cannot
157
- // see is a knob nobody can predict; a share of the tool text behaves the same in a short
158
- // session and a long one.
159
- //
160
- // ONLY TOOL RESULTS ARE TOUCHED, whatever the ratio. The `role !== 'tool'` filter below is
161
- // the real protection for the conversation: user messages, assistant prose and the system
162
- // prompt are never candidates, so no ratio can reach them. (An earlier comment here claimed
163
- // the denominator was what protected the conversation. It never was — the filter is.)
164
- //
165
- // Walking newest-first is what makes this behave the way a person expects: the
166
- // results you were just working from are the ones that survive, and the material
167
- // from twenty turns ago goes first.
168
- //
169
- // Returns { keep: [indices], elide: [indices], totalBytes, keepBytes, elideBytes }.
170
- // `mustKeep` (an index) is never elided — the tool result belonging to the step
171
- // currently in flight, if the caller knows it.
172
- export function planTrim(messages, keepRatio, mustKeep) {
173
- const empty = { keep: [], elide: [], totalBytes: 0, keepBytes: 0, elideBytes: 0 };
174
- if (!Array.isArray(messages)) return empty;
175
- const ratio = Number.isFinite(keepRatio) ? Math.min(Math.max(keepRatio, 0), 1) : DEFAULT_TRIM_KEEP_RATIO;
176
-
177
- // Only string-bodied results can be elided; a media result carries content
178
- // blocks and clearing it would delete the image itself.
179
- const candidates = [];
180
- let totalBytes = 0;
181
- for (let i = 0; i < messages.length; i++) {
182
- const m = messages[i];
183
- if (!m || m.role !== 'tool') continue;
184
- if (typeof m.content !== 'string') continue;
185
- totalBytes += m.content.length;
186
- if (m.content === CLEARED_MARKER) continue;
187
- if (m.content.length < MIN_TRIM_BYTES) continue;
188
- candidates.push(i);
189
- }
190
- if (!candidates.length) return { ...empty, totalBytes };
191
-
192
- // A budget of 0 means "elide everything eligible"; a budget of 1 means "keep it
193
- // all", in which case we still elide the already-marked ones so a repeated call
194
- // is a no-op rather than a growing patch.
195
- // The share of the ELIGIBLE text to keep, not of `totalBytes`. `totalBytes` counts the
196
- // pointers left by earlier passes, so after a few passes it mostly describes text that can no
197
- // longer be elided — and a budget drawn from it stops constraining the loop.
198
- const eligibleBytes = candidates.reduce((n, i) => n + messages[i].content.length, 0);
199
- const budget = eligibleBytes * ratio;
200
- const keep = new Set();
201
- let keepBytes = 0;
202
- for (let k = candidates.length - 1; k >= 0; k--) {
203
- const i = candidates[k];
204
- if (i === mustKeep) { keep.add(i); keepBytes += messages[i].content.length; continue; }
205
- const size = messages[i].content.length;
206
- // Under budget: keep. Otherwise elide — except for the result the model is reading right
207
- // now, which the `mustKeep` branch above has already kept.
208
- //
209
- // There used to be a `|| keep.size === 0` here, meaning "always keep at least the newest".
210
- // `mustKeep` is what actually protects the live result, and the override made a single large
211
- // result impossible to trim: it was the only candidate, so it was always "the newest", so
212
- // the budget never applied and the trim elided nothing.
213
- if (keepBytes + size <= budget) {
214
- keep.add(i);
215
- keepBytes += size;
216
- }
217
- }
218
-
219
- // THE FLOOR: never elide everything.
220
- //
221
- // The budget can be smaller than every candidate — one 200k result against a 60k budget is the
222
- // ordinary case, because a long turn leaves the history with only the newest result still
223
- // un-elided. Without this the trim would replace that result with a pointer, which is worse
224
- // than not trimming: the model loses the output it just asked for.
225
- if (!keep.size && candidates.length) keep.add(candidates[candidates.length - 1]);
226
- const elide = [];
227
- let elideBytes = 0;
228
- for (const i of candidates) {
229
- if (keep.has(i)) continue;
230
- elide.push(i);
231
- elideBytes += messages[i].content.length;
232
- }
233
- return { keep: [...keep].sort((a, b) => a - b), elide, totalBytes, keepBytes, elideBytes };
234
- }
235
-
236
- // Apply a trim to `messages` IN PLACE, replacing each elided result with a short
237
- // pointer to the text on disk.
238
- //
239
- // Two properties matter here and both are deliberate:
240
- //
241
- // * The message COUNT and every message's role stay identical. The provider's
242
- // prompt cache is keyed on the prefix, and a message list that changes SHAPE
243
- // invalidates it — replacing bodies keeps the shape.
244
- //
245
- // * The full text is written to disk first (spillDir), so an elided result is
246
- // RECOVERABLE: the model reads the pointer and pages through the file. That is
247
- // what makes "elided" different from "deleted" — the point the user raised
248
- // about trimming eating their work.
249
- //
250
- // `sessionId`/`messages` identify where the copies go. Returns
251
- // { elided, elidedBytes, kept, keptBytes }.
252
- export function applyTrim(messages, plan, sessionId) {
253
- const out = { elided: 0, elidedBytes: 0, kept: plan.keep.length, keptBytes: plan.keepBytes };
254
- if (!Array.isArray(messages) || !plan.elide.length) return out;
255
- for (const i of plan.elide) {
256
- const m = messages[i];
257
- const original = m.content;
258
- // Copy it out BEFORE overwriting: this is the whole difference between a trim
259
- // and a loss. If the write fails we still elide, but the pointer says so.
260
- const spilled = spillResult(sessionId, `trim-${m.toolCallId || i}`, original);
261
- const tool = m.name || 'tool';
262
- m.content = spilled
263
- ? `[Output elided to save context — ${fmtBytes(original.length)} from ${tool}.\n`
264
- + `Full text saved to: ${spilled.file}\n`
265
- + `Read that file (with start_line/end_line) if you need this output again.]`
266
- : `[Output elided to save context — ${fmtBytes(original.length)} from ${tool}; the full text could not be saved.]`;
267
- out.elided++;
268
- out.elidedBytes += original.length;
269
- }
270
- return out;
271
- }
272
-
273
- // Convenience: plan + apply in one go. Returns null when nothing needed trimming,
274
- // so a caller can skip its UI event entirely.
275
- export function trimToolResults(messages, opts = {}) {
276
- const plan = planTrim(messages, opts.keepRatio, opts.mustKeep);
277
- const mediaPlan = planMediaTrim(messages, opts.mediaKeep ?? 2);
278
- if (!plan.elide.length && !mediaPlan.elide.length) return null;
279
- const applied = plan.elide.length
280
- ? applyTrim(messages, plan, opts.sessionId)
281
- : { elided: 0, elidedBytes: 0, kept: plan.keep.length, keptBytes: plan.keepBytes };
282
- const mediaApplied = applyMediaTrim(messages, mediaPlan, opts.sessionId);
283
- return {
284
- ...applied,
285
- elided: applied.elided + mediaApplied.elided,
286
- elidedBytes: applied.elidedBytes + mediaApplied.elidedBytes,
287
- plan,
288
- };
289
- }
290
-
291
- // ---- media results ----------------------------------------------------------
292
- // A media tool result keeps its base64 payload IN the history object — and unlike
293
- // a string body, planTrim cannot elide it, so every screenshot was re-serialized
294
- // into every request body, every session save and every cache-prefix walk until a
295
- // full compaction dropped it. Keep only the newest `mediaKeep` media results;
296
- // older ones spill their text (if any) and lose the bytes, same contract as the
297
- // string path: saved to disk first, pointer left behind.
298
-
299
- function planMediaTrim(messages, keep) {
300
- const idx = [];
301
- if (Array.isArray(messages)) {
302
- for (let i = 0; i < messages.length; i++) {
303
- const m = messages[i];
304
- if (m && m.role === 'tool' && m.content && typeof m.content === 'object'
305
- && Array.isArray(m.content.media) && m.content.media.length) idx.push(i);
306
- }
307
- }
308
- const elide = idx.slice(0, Math.max(0, idx.length - Math.max(0, keep)));
309
- return { elide };
310
- }
311
-
312
- function applyMediaTrim(messages, mediaPlan, sessionId) {
313
- const out = { elided: 0, elidedBytes: 0 };
314
- for (const i of mediaPlan.elide) {
315
- const m = messages[i];
316
- let bytes = 0;
317
- for (const part of m.content.media) bytes += (part && part.data ? part.data.length : 0);
318
- const text = String(m.content.text || '');
319
- const spilled = spillResult(sessionId, `trim-${m.toolCallId || i}`, text || '[media only]');
320
- m.content = `[Media result elided to save context — ${fmtBytes(bytes)} of image data from ${m.name || 'tool'}`
321
- + (spilled ? `; the description was saved to: ${spilled.file}` : '; the description could not be saved')
322
- + '. Re-run the tool if you need the image again.]';
323
- out.elided++;
324
- out.elidedBytes += bytes;
325
- }
326
- return out;
327
- }
1
+ // Tool-result size control.
2
+ //
3
+ // Two separate problems, both of which used to be silent:
4
+ //
5
+ // 1. A SINGLE huge result. Per-tool caps exist (`MAX_OUTPUT_BYTES` in
6
+ // tools/utils.js) but `Read` deliberately has none, and nothing bounded the
7
+ // AGGREGATE of a step's results — a turn with four Reads could add half a
8
+ // megabyte to a history that is then resent on every later request. Real
9
+ // sessions in ~/.hncode/sessions reached 5 MB this way.
10
+ // 2. OLD results that no longer matter. A file read forty turns ago is dead
11
+ // weight, but the whole history is resent every request, so it is paid for
12
+ // again and again until something compacts.
13
+ //
14
+ // The cap is applied where the result is BUILT (see `shapeToolResult`), and the
15
+ // overflow is kept, not lost: it goes to a file under the session's own
16
+ // directory and the model gets a bounded preview plus the path, so it can Read
17
+ // the rest if it turns out to need it. This mirrors Claude Code's
18
+ // `<persisted-output>` handling (src/utils/toolResultStorage.ts).
19
+ //
20
+ // The ages pass (stale-pass) is the cheap half of compaction: it clears the
21
+ // BODY of old tool results while leaving the message — and therefore the
22
+ // assistant/tool pairing and the exact prefix length — untouched, so it does not
23
+ // disturb the message list shape the provider has already cached. Claude Code
24
+ // does the same thing in microCompact.ts ("[Old tool result content cleared]").
25
+
26
+ import fs from 'node:fs';
27
+ import path from 'node:path';
28
+
29
+ // Bytes of a single tool result that are kept inline. Above this the overflow is
30
+ // written to disk. 50 KB is Claude Code's DEFAULT_MAX_RESULT_SIZE_CHARS and is
31
+ // comfortably more than a whole source file's worth of lines.
32
+ export const MAX_RESULT_BYTES = 50 * 1024;
33
+
34
+ // Bytes of a spilled result that stay in the transcript as a preview.
35
+ export const PREVIEW_BYTES = 2 * 1024;
36
+
37
+ // Trigger ratio: trim once the request reaches this fraction of the model window.
38
+ // 50% by default (`trim_threshold` / HNCODE_TRIM_THRESHOLD). Well below the
39
+ // compaction trigger on purpose — this is the cheap pass that keeps the history
40
+ // from ever getting near compaction in the first place.
41
+ export const DEFAULT_TRIM_THRESHOLD = 0.5;
42
+
43
+ // Fraction of the tool-result TEXT that survives a trim. 30% by default
44
+ // (`trim_keep_ratio` / HNCODE_TRIM_KEEP_RATIO); the rest of the eligible tool text is
45
+ // elided.
46
+ //
47
+ // A DIFFERENT denominator from `trim_threshold` above, on purpose. The threshold asks
48
+ // whether the request is too big for the window (a share of the WINDOW); this asks how much
49
+ // of the removable output stays (a share of the TOOL TEXT). Measuring this against the
50
+ // request was tried and reverted — at a 1M window the budget then exceeded all the elidable
51
+ // text, so `/trim 0.6` could not trim anything at all.
52
+ //
53
+ // The conversation is protected by the candidate filter in `planTrim`, not by a ratio:
54
+ // only messages with `role === 'tool'` are ever elided.
55
+ export const DEFAULT_TRIM_KEEP_RATIO = 0.3;
56
+
57
+ // A tool result shorter than this is never worth eliding: the marker plus the
58
+ // pointer would cost more than the text it replaces.
59
+ export const MIN_TRIM_BYTES = 512;
60
+
61
+ export const CLEARED_MARKER = '[Old tool result content cleared]';
62
+ export const PERSISTED_TAG = 'persisted-output';
63
+
64
+ // Directory for spilled results, beside the session file so it is cleaned up
65
+ // with the session rather than accumulating in a temp dir.
66
+ export function spillDir(sessionId) {
67
+ const root = process.env.HNCODE_HOME || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.hncode');
68
+ return path.join(root, 'tool-results', String(sessionId || 'unscoped'));
69
+ }
70
+
71
+ // Write `text` to disk and return the preview + path, or null when the write
72
+ // fails (a read-only disk must not fail the tool call).
73
+ export function spillResult(sessionId, toolCallId, text) {
74
+ try {
75
+ const dir = spillDir(sessionId);
76
+ fs.mkdirSync(dir, { recursive: true });
77
+ // The tool-call id is already a unique, filesystem-safe token from the
78
+ // provider, so it needs no sanitizing beyond dropping path separators.
79
+ const safe = String(toolCallId || 'result').replace(/[^A-Za-z0-9_.-]/g, '_');
80
+ const file = path.join(dir, `${safe}.txt`);
81
+ fs.writeFileSync(file, text, 'utf8');
82
+ return { file, preview: previewOf(text, PREVIEW_BYTES), originalBytes: Buffer.byteLength(text, 'utf8') };
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ // A preview cut on a line boundary when one is close enough, so the model does
89
+ // not receive half a line of code as its last visible detail.
90
+ export function previewOf(text, maxBytes) {
91
+ const s = String(text == null ? '' : text);
92
+ if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;
93
+ let cut = Buffer.from(s, 'utf8').subarray(0, maxBytes).toString('utf8');
94
+ if (cut.endsWith('\uFFFD')) cut = cut.slice(0, -1);
95
+ const nl = cut.lastIndexOf('\n');
96
+ if (nl > maxBytes * 0.5) cut = cut.slice(0, nl);
97
+ return cut;
98
+ }
99
+
100
+ // The message the model sees in place of an oversized result. It says what
101
+ // happened, how big it was, where the rest is, and how to get it — an agent that
102
+ // cannot tell why its output is missing retries the same call forever.
103
+ export function spillNotice(spilled) {
104
+ return [
105
+ `Output too large (${fmtBytes(spilled.originalBytes)}). Full output saved to: ${spilled.file}`,
106
+ '',
107
+ `Preview (first ${fmtBytes(PREVIEW_BYTES)}):`,
108
+ spilled.preview,
109
+ '',
110
+ `Read the file above to see the rest — use start_line / end_line to page through it.`,
111
+ ].join('\n');
112
+ }
113
+
114
+ export function fmtBytes(n) {
115
+ const b = Number(n) || 0;
116
+ if (b < 1024) return `${b} B`;
117
+ if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
118
+ return `${(b / (1024 * 1024)).toFixed(1)} MB`;
119
+ }
120
+
121
+ // Shape ONE tool result for the model: pass small results through, spill big
122
+ // ones. Returns { content, spilled } where `content` is what goes into the
123
+ // message. `sessionId`/`toolCallId` identify the spill file.
124
+ export function shapeToolResult(content, { sessionId, toolCallId, maxBytes = MAX_RESULT_BYTES } = {}) {
125
+ if (typeof content !== 'string') return { content, spilled: false };
126
+ if (Buffer.byteLength(content, 'utf8') <= maxBytes) return { content, spilled: false };
127
+ const spilled = spillResult(sessionId, toolCallId, content);
128
+ // The write failed: a normal-sized preview is still better than megabytes, and
129
+ // the notice must not claim a path that does not exist.
130
+ if (!spilled) {
131
+ return {
132
+ content: `${previewOf(content, PREVIEW_BYTES)}\n\n[Output truncated: ${fmtBytes(Buffer.byteLength(content, 'utf8'))} total; the full output could not be saved.]`,
133
+ spilled: false,
134
+ };
135
+ }
136
+ return { content: spillNotice(spilled), spilled: true };
137
+ }
138
+
139
+ // Which tool results to elide, and by how much.
140
+ //
141
+ // RULE (the user's): keep a FRACTION of the TOOL-RESULT TEXT, the newest part.
142
+ // Walk the results from newest to oldest accumulating their size; once the total kept
143
+ // exceeds `keepRatio` of ALL tool-result text, everything older is elided.
144
+ //
145
+ // THE DENOMINATOR IS THE TOOL TEXT, NOT THE REQUEST, and the two knobs deliberately use
146
+ // different scales because they answer different questions:
147
+ //
148
+ // * `trimThreshold` asks "is the request too big for the window yet?" — a share of the
149
+ // WINDOW.
150
+ // * `keep` asks "of the output we are allowed to remove, how much stays?" — a share of
151
+ // the TOOL TEXT.
152
+ //
153
+ // Measuring `keep` against the request was tried and reverted: at a 1M window with 270k of
154
+ // tool text, `threshold` fires at 500k while `keep=0.6` asks to retain 300k — MORE than the
155
+ // 270k that could ever be elided. So `/trim 0.6` reported "nothing to trim", and it did so
156
+ // for every request above 450k. A knob whose behaviour depends on a total the user cannot
157
+ // see is a knob nobody can predict; a share of the tool text behaves the same in a short
158
+ // session and a long one.
159
+ //
160
+ // ONLY TOOL RESULTS ARE TOUCHED, whatever the ratio. The `role !== 'tool'` filter below is
161
+ // the real protection for the conversation: user messages, assistant prose and the system
162
+ // prompt are never candidates, so no ratio can reach them. (An earlier comment here claimed
163
+ // the denominator was what protected the conversation. It never was — the filter is.)
164
+ //
165
+ // Walking newest-first is what makes this behave the way a person expects: the
166
+ // results you were just working from are the ones that survive, and the material
167
+ // from twenty turns ago goes first.
168
+ //
169
+ // Returns { keep: [indices], elide: [indices], totalBytes, keepBytes, elideBytes }.
170
+ // `mustKeep` (an index) is never elided — the tool result belonging to the step
171
+ // currently in flight, if the caller knows it.
172
+ export function planTrim(messages, keepRatio, mustKeep) {
173
+ const empty = { keep: [], elide: [], totalBytes: 0, keepBytes: 0, elideBytes: 0 };
174
+ if (!Array.isArray(messages)) return empty;
175
+ const ratio = Number.isFinite(keepRatio) ? Math.min(Math.max(keepRatio, 0), 1) : DEFAULT_TRIM_KEEP_RATIO;
176
+
177
+ // Only string-bodied results can be elided; a media result carries content
178
+ // blocks and clearing it would delete the image itself.
179
+ const candidates = [];
180
+ let totalBytes = 0;
181
+ for (let i = 0; i < messages.length; i++) {
182
+ const m = messages[i];
183
+ if (!m || m.role !== 'tool') continue;
184
+ if (typeof m.content !== 'string') continue;
185
+ totalBytes += m.content.length;
186
+ if (m.content === CLEARED_MARKER) continue;
187
+ if (m.content.length < MIN_TRIM_BYTES) continue;
188
+ candidates.push(i);
189
+ }
190
+ if (!candidates.length) return { ...empty, totalBytes };
191
+
192
+ // A budget of 0 means "elide everything eligible"; a budget of 1 means "keep it
193
+ // all", in which case we still elide the already-marked ones so a repeated call
194
+ // is a no-op rather than a growing patch.
195
+ // The share of the ELIGIBLE text to keep, not of `totalBytes`. `totalBytes` counts the
196
+ // pointers left by earlier passes, so after a few passes it mostly describes text that can no
197
+ // longer be elided — and a budget drawn from it stops constraining the loop.
198
+ const eligibleBytes = candidates.reduce((n, i) => n + messages[i].content.length, 0);
199
+ const budget = eligibleBytes * ratio;
200
+ const keep = new Set();
201
+ let keepBytes = 0;
202
+ for (let k = candidates.length - 1; k >= 0; k--) {
203
+ const i = candidates[k];
204
+ if (i === mustKeep) { keep.add(i); keepBytes += messages[i].content.length; continue; }
205
+ const size = messages[i].content.length;
206
+ // Under budget: keep. Otherwise elide — except for the result the model is reading right
207
+ // now, which the `mustKeep` branch above has already kept.
208
+ //
209
+ // There used to be a `|| keep.size === 0` here, meaning "always keep at least the newest".
210
+ // `mustKeep` is what actually protects the live result, and the override made a single large
211
+ // result impossible to trim: it was the only candidate, so it was always "the newest", so
212
+ // the budget never applied and the trim elided nothing.
213
+ if (keepBytes + size <= budget) {
214
+ keep.add(i);
215
+ keepBytes += size;
216
+ }
217
+ }
218
+
219
+ // THE FLOOR: never elide everything.
220
+ //
221
+ // The budget can be smaller than every candidate — one 200k result against a 60k budget is the
222
+ // ordinary case, because a long turn leaves the history with only the newest result still
223
+ // un-elided. Without this the trim would replace that result with a pointer, which is worse
224
+ // than not trimming: the model loses the output it just asked for.
225
+ if (!keep.size && candidates.length) keep.add(candidates[candidates.length - 1]);
226
+ const elide = [];
227
+ let elideBytes = 0;
228
+ for (const i of candidates) {
229
+ if (keep.has(i)) continue;
230
+ elide.push(i);
231
+ elideBytes += messages[i].content.length;
232
+ }
233
+ return { keep: [...keep].sort((a, b) => a - b), elide, totalBytes, keepBytes, elideBytes };
234
+ }
235
+
236
+ // Apply a trim to `messages` IN PLACE, replacing each elided result with a short
237
+ // pointer to the text on disk.
238
+ //
239
+ // Two properties matter here and both are deliberate:
240
+ //
241
+ // * The message COUNT and every message's role stay identical. The provider's
242
+ // prompt cache is keyed on the prefix, and a message list that changes SHAPE
243
+ // invalidates it — replacing bodies keeps the shape.
244
+ //
245
+ // * The full text is written to disk first (spillDir), so an elided result is
246
+ // RECOVERABLE: the model reads the pointer and pages through the file. That is
247
+ // what makes "elided" different from "deleted" — the point the user raised
248
+ // about trimming eating their work.
249
+ //
250
+ // `sessionId`/`messages` identify where the copies go. Returns
251
+ // { elided, elidedBytes, kept, keptBytes }.
252
+ export function applyTrim(messages, plan, sessionId) {
253
+ const out = { elided: 0, elidedBytes: 0, kept: plan.keep.length, keptBytes: plan.keepBytes };
254
+ if (!Array.isArray(messages) || !plan.elide.length) return out;
255
+ for (const i of plan.elide) {
256
+ const m = messages[i];
257
+ const original = m.content;
258
+ // Copy it out BEFORE overwriting: this is the whole difference between a trim
259
+ // and a loss. If the write fails we still elide, but the pointer says so.
260
+ const spilled = spillResult(sessionId, `trim-${m.toolCallId || i}`, original);
261
+ const tool = m.name || 'tool';
262
+ m.content = spilled
263
+ ? `[Output elided to save context — ${fmtBytes(original.length)} from ${tool}.\n`
264
+ + `Full text saved to: ${spilled.file}\n`
265
+ + `Read that file (with start_line/end_line) if you need this output again.]`
266
+ : `[Output elided to save context — ${fmtBytes(original.length)} from ${tool}; the full text could not be saved.]`;
267
+ out.elided++;
268
+ out.elidedBytes += original.length;
269
+ }
270
+ return out;
271
+ }
272
+
273
+ // Convenience: plan + apply in one go. Returns null when nothing needed trimming,
274
+ // so a caller can skip its UI event entirely.
275
+ export function trimToolResults(messages, opts = {}) {
276
+ const plan = planTrim(messages, opts.keepRatio, opts.mustKeep);
277
+ const mediaPlan = planMediaTrim(messages, opts.mediaKeep ?? 2);
278
+ const argPlan = planArgTrim(messages, opts.argKeepTail ?? 20);
279
+ if (!plan.elide.length && !mediaPlan.elide.length && !argPlan.elide.length) return null;
280
+ const applied = plan.elide.length
281
+ ? applyTrim(messages, plan, opts.sessionId)
282
+ : { elided: 0, elidedBytes: 0, kept: plan.keep.length, keptBytes: plan.keepBytes };
283
+ const mediaApplied = applyMediaTrim(messages, mediaPlan, opts.sessionId);
284
+ const argApplied = applyArgTrim(messages, argPlan, opts.sessionId);
285
+ return {
286
+ ...applied,
287
+ elided: applied.elided + mediaApplied.elided + argApplied.elided,
288
+ elidedBytes: applied.elidedBytes + mediaApplied.elidedBytes + argApplied.elidedBytes,
289
+ plan,
290
+ };
291
+ }
292
+
293
+ // ---- media results ----------------------------------------------------------
294
+ // A media tool result keeps its base64 payload IN the history object — and unlike
295
+ // a string body, planTrim cannot elide it, so every screenshot was re-serialized
296
+ // into every request body, every session save and every cache-prefix walk until a
297
+ // full compaction dropped it. Keep only the newest `mediaKeep` media results;
298
+ // older ones spill their text (if any) and lose the bytes, same contract as the
299
+ // string path: saved to disk first, pointer left behind.
300
+
301
+ function planMediaTrim(messages, keep) {
302
+ const idx = [];
303
+ if (Array.isArray(messages)) {
304
+ for (let i = 0; i < messages.length; i++) {
305
+ const m = messages[i];
306
+ if (m && m.role === 'tool' && m.content && typeof m.content === 'object'
307
+ && Array.isArray(m.content.media) && m.content.media.length) idx.push(i);
308
+ }
309
+ }
310
+ const elide = idx.slice(0, Math.max(0, idx.length - Math.max(0, keep)));
311
+ return { elide };
312
+ }
313
+
314
+ function applyMediaTrim(messages, mediaPlan, sessionId) {
315
+ const out = { elided: 0, elidedBytes: 0 };
316
+ for (const i of mediaPlan.elide) {
317
+ const m = messages[i];
318
+ let bytes = 0;
319
+ for (const part of m.content.media) bytes += (part && part.data ? part.data.length : 0);
320
+ const text = String(m.content.text || '');
321
+ const spilled = spillResult(sessionId, `trim-${m.toolCallId || i}`, text || '[media only]');
322
+ m.content = `[Media result elided to save context — ${fmtBytes(bytes)} of image data from ${m.name || 'tool'}`
323
+ + (spilled ? `; the description was saved to: ${spilled.file}` : '; the description could not be saved')
324
+ + '. Re-run the tool if you need the image again.]';
325
+ out.elided++;
326
+ out.elidedBytes += bytes;
327
+ }
328
+ return out;
329
+ }
330
+
331
+
332
+ // ---- tool CALL arguments -----------------------------------------------------
333
+ //
334
+ // A TOOL CALL'S ARGUMENTS ARE ALSO HISTORY, AND THEY WERE NEVER TRIMMED.
335
+ //
336
+ // `planTrim` only ever looked at `role: 'tool'` messages, so the ARGUMENTS of a call — the full body a `Write` sent,
337
+ // the old and new text of an `Edit` — stayed in the history at full size forever and were re-sent on every request. On
338
+ // a real session that measured 1.27 MB of a 2.5 MB total, with one `Write` at 53 KB.
339
+ //
340
+ // The model has already acted on those arguments; the file on disk is the result. What it can still need is the SHAPE
341
+ // of the call and a way back to the full text — exactly the contract `applyTrim` gives for result bodies: spill to
342
+ // disk, leave a pointer.
343
+ //
344
+ // COMPATIBILITY, which is why this only rewrites VALUES:
345
+ //
346
+ // * field names, call ids and the number of calls are untouched, so a reader expecting `{id, name, args}` still
347
+ // sees exactly that;
348
+ // * `args` stays an OBJECT and every replaced value stays a STRING, so `JSON.stringify(tc.args)` is still valid
349
+ // arguments for the provider;
350
+ // * `argsJson` is left alone — dropping a field an older build wrote is how a resume breaks.
351
+ const ELIDE_ARG_BYTES = 4096; // an argument string longer than this is worth a pointer
352
+
353
+ function planArgTrim(messages, keepTail) {
354
+ const idx = [];
355
+ if (!Array.isArray(messages)) return { elide: idx };
356
+ for (let i = 0; i < messages.length; i++) {
357
+ const m = messages[i];
358
+ if (!m || m.role !== 'assistant' || !Array.isArray(m.toolCalls)) continue;
359
+ let big = false;
360
+ for (const tc of m.toolCalls) {
361
+ if (!tc || !tc.args || typeof tc.args !== 'object') continue;
362
+ for (const v of Object.values(tc.args)) {
363
+ if (typeof v === 'string' && Buffer.byteLength(v, 'utf8') > ELIDE_ARG_BYTES) { big = true; break; }
364
+ }
365
+ if (big) break;
366
+ }
367
+ if (big) idx.push(i);
368
+ }
369
+ // Only calls OLDER than the last `keepTail` messages: the current step's arguments are what the model is reasoning
370
+ // about, and the previous step's are plausibly still in view.
371
+ const cut = messages.length - Math.max(0, keepTail);
372
+ return { elide: idx.filter((i) => i < cut) };
373
+ }
374
+
375
+ function applyArgTrim(messages, argPlan, sessionId) {
376
+ const out = { elided: 0, elidedBytes: 0 };
377
+ for (const i of argPlan.elide) {
378
+ const m = messages[i];
379
+ let touched = false;
380
+ for (const tc of m.toolCalls) {
381
+ if (!tc || !tc.args || typeof tc.args !== 'object') continue;
382
+ for (const [k, v] of Object.entries(tc.args)) {
383
+ if (typeof v !== 'string' || Buffer.byteLength(v, 'utf8') <= ELIDE_ARG_BYTES) continue;
384
+ const bytes = Buffer.byteLength(v, 'utf8');
385
+ const spilled = spillResult(sessionId, `arg-${tc.id || i}-${k}`, v);
386
+ // THE VALUE STAYS A STRING and keeps naming itself, so a reader that shows the argument still shows which
387
+ // field it was and where the text went.
388
+ tc.args[k] = spilled
389
+ ? `[Argument elided to save context — ${fmtBytes(bytes)} of ${tc.name || 'tool'}.${k}.\n`
390
+ + `Full text saved to: ${spilled.file}\n`
391
+ + `Read that file if you need to see exactly what was sent.]`
392
+ : `[Argument elided to save context — ${fmtBytes(bytes)} of ${tc.name || 'tool'}.${k}; the full text could not be saved.]`;
393
+ out.elidedBytes += bytes;
394
+ touched = true;
395
+ }
396
+ }
397
+ if (touched) out.elided++;
398
+ }
399
+ return out;
400
+ }