@bismawy/pi-arnative 0.12.0 → 0.13.0
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/CHANGELOG.md +28 -6
- package/README.md +13 -4
- package/extensions/arnative.ts +102 -19
- package/extensions/autocompact.ts +659 -63
- package/extensions/footer.ts +43 -39
- package/extensions/model-heal.ts +14 -17
- package/extensions/render-cache.ts +638 -0
- package/extensions/tools.ts +52 -2
- package/lib/list-picker.ts +11 -3
- package/lib/patch.ts +26 -1
- package/lib/preset-store.ts +3 -1
- package/lib/status-widget.ts +5 -16
- package/package.json +3 -3
|
@@ -1,23 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Auto-compact —
|
|
2
|
+
* Auto-compact — scale Smart capacity with Render cache and keep remote payloads < 1 MB.
|
|
3
3
|
*
|
|
4
|
-
* Why: pi renders the whole transcript on every frame, so
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* Why: When Render cache is Off, pi re-renders the whole transcript on every frame, so
|
|
5
|
+
* Smart caps ≥192k windows around ~200k tokens to keep the TUI responsive. When Render
|
|
6
|
+
* cache is On, settled history renders in O(1), so Smart scales ≥192k windows to 90%
|
|
7
|
+
* of `contextWindow` (while ≤128k windows still defer to pi's `reserveTokens`).
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* -
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* through `ctx.compact()` — the same machinery and summary as /compact, never mid-run.
|
|
19
|
-
* Pi's own `compaction.reserveTokens` threshold, including per-model overrides, is
|
|
20
|
-
* unaffected; whichever fires first wins.
|
|
9
|
+
* Remote-routed models (`remote/*`, `remote-magpie/*`) sit behind a 1 MB HTTP body limit.
|
|
10
|
+
* Rather than forcing premature session compaction at low token counts, byte protection
|
|
11
|
+
* stays decoupled from `ctx.compact()`:
|
|
12
|
+
* - `before_provider_request` measures serialized request bytes to track prompt/tool overhead.
|
|
13
|
+
* - `context` stays silent (preserving prompt caching) until payload approaches ~900 KB,
|
|
14
|
+
* then trims in-memory down to ~760 KB (old images → old thinking → old tool outputs →
|
|
15
|
+
* old args → head turns) without touching the transcript, UI, or `render-cache`.
|
|
16
|
+
* - `session_before_compact` caps oversized `toolCall` arguments / text in compaction input
|
|
17
|
+
* so summarization stays under 1 MB when token compaction eventually runs.
|
|
21
18
|
*/
|
|
22
19
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
23
20
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
@@ -25,6 +22,7 @@ import { tmpdir } from "node:os";
|
|
|
25
22
|
import { join } from "node:path";
|
|
26
23
|
import { assert, isMain } from "../lib/check.ts";
|
|
27
24
|
import { loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
|
|
25
|
+
import { activeRenderCache, setRenderCache } from "./render-cache.ts";
|
|
28
26
|
|
|
29
27
|
/** Stored exactly as the picker shows them; `Off` disables the trigger entirely. */
|
|
30
28
|
export const AUTO_COMPACT_CHOICES = ["Off", "Smart", "100k", "150k", "200k", "300k", "400k"] as const;
|
|
@@ -32,18 +30,59 @@ export type AutoCompactChoice = (typeof AUTO_COMPACT_CHOICES)[number];
|
|
|
32
30
|
export const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
|
|
33
31
|
export const AUTO_COMPACT_KEY = "autoCompact";
|
|
34
32
|
|
|
35
|
-
/**
|
|
36
|
-
*
|
|
37
|
-
|
|
33
|
+
/** Byte ceilings for byte-capped proxies (e.g. `remote/*` endpoints).
|
|
34
|
+
* The ratios target a 1 MB HTTP body wall. Raise `PI_ARNATIVE_BYTE_WALL_MB` when the
|
|
35
|
+
* proxy accepts more, or the shed fires at a fraction of the real wall and caps the
|
|
36
|
+
* context long before the token window is used. Read once at module load: a shell
|
|
37
|
+
* override must be set before pi starts. */
|
|
38
|
+
function byteWallBytes(): number {
|
|
39
|
+
const mb = Number(process.env.PI_ARNATIVE_BYTE_WALL_MB);
|
|
40
|
+
return Number.isFinite(mb) && mb > 0 ? Math.round(mb * 1024 * 1024) : 1024 * 1024;
|
|
41
|
+
}
|
|
42
|
+
const WALL_SCALE = byteWallBytes() / (1024 * 1024);
|
|
43
|
+
/** Trim markers name the real ceiling, so a raised wall does not report 1MB. */
|
|
44
|
+
const TRIM_LABEL = WALL_SCALE === 1 ? "trimmed for 1MB limit" : `trimmed for ${Math.round(WALL_SCALE)}MB limit`;
|
|
45
|
+
|
|
46
|
+
export const SHED_TRIGGER_BYTES = Math.round(900 * 1024 * WALL_SCALE);
|
|
47
|
+
export const SHED_TARGET_BYTES = Math.round(760 * 1024 * WALL_SCALE);
|
|
48
|
+
export const COMPACT_INPUT_BYTES = Math.round(720 * 1024 * WALL_SCALE);
|
|
49
|
+
const SHED_TRIGGER_AFTER_413_BYTES = Math.round(820 * 1024 * WALL_SCALE);
|
|
50
|
+
const SHED_TARGET_AFTER_413_BYTES = Math.round(680 * 1024 * WALL_SCALE);
|
|
51
|
+
const DEFAULT_OVERHEAD_BYTES = 64 * 1024;
|
|
52
|
+
const MIN_MSG_BUDGET_BYTES = 64 * 1024;
|
|
53
|
+
const TRIMMED_TOOL_STUB = "[earlier output omitted; full output in session]";
|
|
54
|
+
|
|
55
|
+
interface ContentBlockLike {
|
|
56
|
+
type?: string;
|
|
57
|
+
text?: string;
|
|
58
|
+
thinking?: string;
|
|
59
|
+
arguments?: Record<string, unknown>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface MessageLike {
|
|
63
|
+
role?: string;
|
|
64
|
+
content?: unknown;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Smart's tier table when Render cache is Off (keeps uncached transcripts near ~200k).
|
|
68
|
+
* When Render cache is On, settled history renders in O(1), so ≥192k windows scale
|
|
69
|
+
* up to 90% of contextWindow while ≤128k windows still defer to pi core. */
|
|
70
|
+
const SMART_TIERS_UNCACHED: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
|
|
38
71
|
{ minWindow: 786432, percent: 20 }, // ≥768k: a 1M window triggers at ~200k tokens
|
|
39
72
|
{ minWindow: 393216, percent: 40 }, // 384k–768k: a 512k window triggers at ~205k
|
|
40
73
|
{ minWindow: 196608, percent: 80 }, // 192k–384k: a 256k window triggers at ~205k
|
|
41
74
|
{ minWindow: 0, percent: null }, // below 192k (128k models): pi core stays in charge
|
|
42
75
|
];
|
|
43
76
|
|
|
77
|
+
const SMART_TIERS_CACHED: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
|
|
78
|
+
{ minWindow: 196608, percent: 90 }, // ≥192k: let render-cached sessions reach 90% of capacity
|
|
79
|
+
{ minWindow: 0, percent: null }, // below 192k (128k models): pi core stays in charge
|
|
80
|
+
];
|
|
81
|
+
|
|
44
82
|
/** The Smart percent for a context window, or null when the window defers to pi core. */
|
|
45
|
-
export function smartPercent(contextWindow: number): number | null {
|
|
46
|
-
const
|
|
83
|
+
export function smartPercent(contextWindow: number, renderCacheOn = activeRenderCache() === "On"): number | null {
|
|
84
|
+
const tiers = renderCacheOn ? SMART_TIERS_CACHED : SMART_TIERS_UNCACHED;
|
|
85
|
+
const tier = tiers.find((t) => contextWindow >= t.minWindow);
|
|
47
86
|
return tier?.percent ?? null;
|
|
48
87
|
}
|
|
49
88
|
|
|
@@ -86,10 +125,30 @@ export interface AutoCompactState {
|
|
|
86
125
|
attemptSettled: boolean;
|
|
87
126
|
/** Do not trigger while usage stays below this (failure backoff, anti-flap). */
|
|
88
127
|
blockedUntilTokens: number;
|
|
128
|
+
/** Last observed `context` event messages size in bytes. */
|
|
129
|
+
lastMessagesBytes: number;
|
|
130
|
+
/** Estimated non-message request overhead (system prompt + tool schemas). */
|
|
131
|
+
overheadBytes: number;
|
|
132
|
+
/** Set if this session saw an HTTP 413 / request_too_large error on the active model. */
|
|
133
|
+
saw413: boolean;
|
|
134
|
+
/** True while a compaction request is in progress (prevents polluting byte metrics). */
|
|
135
|
+
compacting: boolean;
|
|
136
|
+
/** True between `context` and the matching `before_provider_request` for that turn. */
|
|
137
|
+
awaitingContextPayload: boolean;
|
|
89
138
|
}
|
|
90
139
|
|
|
91
140
|
export function freshAutoCompactState(): AutoCompactState {
|
|
92
|
-
return {
|
|
141
|
+
return {
|
|
142
|
+
inFlight: false,
|
|
143
|
+
lastAttemptTokens: null,
|
|
144
|
+
attemptSettled: false,
|
|
145
|
+
blockedUntilTokens: 0,
|
|
146
|
+
lastMessagesBytes: 0,
|
|
147
|
+
overheadBytes: 0,
|
|
148
|
+
saw413: false,
|
|
149
|
+
compacting: false,
|
|
150
|
+
awaitingContextPayload: false,
|
|
151
|
+
};
|
|
93
152
|
}
|
|
94
153
|
|
|
95
154
|
/** How much usage must outgrow a previous attempt before it counts as real growth
|
|
@@ -98,57 +157,422 @@ export function growthMargin(thresholdTokens: number): number {
|
|
|
98
157
|
return Math.max(5000, Math.round(thresholdTokens * 0.05));
|
|
99
158
|
}
|
|
100
159
|
|
|
160
|
+
/** Remote-routed models enforced behind a 1 MB HTTP body proxy. */
|
|
161
|
+
export function isByteLimitedModel(model: { id?: string; provider?: string } | undefined): boolean {
|
|
162
|
+
const id = model?.id;
|
|
163
|
+
const provider = model?.provider;
|
|
164
|
+
return (
|
|
165
|
+
(typeof id === "string" && (id.startsWith("remote/") || id.startsWith("remote-magpie/"))) ||
|
|
166
|
+
(typeof provider === "string" && (provider === "remote" || provider.startsWith("remote-")))
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** True when a provider error string indicates an HTTP 413 request-body size limit. */
|
|
171
|
+
export function isPayloadTooLargeError(errorMessage: string | undefined): boolean {
|
|
172
|
+
return typeof errorMessage === "string" && /\b413\b|request_too_large|entity too large/i.test(errorMessage);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** UTF-8 JSON byte length, returning 0 on non-serializable values. */
|
|
176
|
+
export function jsonByteLength(value: unknown): number {
|
|
177
|
+
try {
|
|
178
|
+
const raw = JSON.stringify(value);
|
|
179
|
+
return raw === undefined ? 0 : Buffer.byteLength(raw, "utf8");
|
|
180
|
+
} catch {
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Keep the helper API, but measure each request: Pi clones messages before `context`. */
|
|
186
|
+
export function cachedArrayBytes(messages: MessageLike[]): number {
|
|
187
|
+
return jsonByteLength(messages);
|
|
188
|
+
}
|
|
189
|
+
|
|
101
190
|
/** Pure decision for the settle handler: fire pi's compaction now, or wait. */
|
|
102
191
|
export function autoCompactDecision(
|
|
103
192
|
state: AutoCompactState,
|
|
104
193
|
tokens: number | null,
|
|
105
|
-
thresholdTokens: number,
|
|
194
|
+
thresholdTokens: number | null,
|
|
106
195
|
): "compact" | "wait" {
|
|
107
|
-
if (
|
|
108
|
-
if (state.
|
|
109
|
-
if (
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
196
|
+
if (state.inFlight || thresholdTokens === null || tokens === null) return "wait";
|
|
197
|
+
if (tokens < thresholdTokens || tokens < state.blockedUntilTokens) return "wait";
|
|
198
|
+
if (
|
|
199
|
+
state.attemptSettled &&
|
|
200
|
+
state.lastAttemptTokens !== null &&
|
|
201
|
+
tokens < state.lastAttemptTokens + growthMargin(thresholdTokens)
|
|
202
|
+
) {
|
|
113
203
|
return "wait";
|
|
114
204
|
}
|
|
115
205
|
return "compact";
|
|
116
206
|
}
|
|
117
207
|
|
|
118
|
-
/**
|
|
119
|
-
*
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
208
|
+
/** Clear attempt memory once usage really dropped under the threshold (prevents
|
|
209
|
+
* oscillation at the edge while re-arming cleanly after an effective compaction). */
|
|
210
|
+
export function rearmAfterDip(state: AutoCompactState, tokens: number | null, thresholdTokens: number | null): void {
|
|
211
|
+
if (thresholdTokens === null || tokens === null || tokens >= thresholdTokens) return;
|
|
212
|
+
if (state.lastAttemptTokens !== null && tokens >= state.lastAttemptTokens - growthMargin(thresholdTokens)) return;
|
|
213
|
+
state.lastAttemptTokens = null;
|
|
214
|
+
state.attemptSettled = false;
|
|
215
|
+
state.blockedUntilTokens = 0;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function truncateStringHead(text: string, maxChars: number, label: string): string {
|
|
219
|
+
if (text.length <= maxChars) return text;
|
|
220
|
+
return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} chars ${label}]`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function mapContentBlocks(
|
|
224
|
+
msg: MessageLike,
|
|
225
|
+
transform: (block: ContentBlockLike) => ContentBlockLike | null,
|
|
226
|
+
): MessageLike | null {
|
|
227
|
+
if (!Array.isArray(msg.content)) return null;
|
|
228
|
+
let changed = false;
|
|
229
|
+
const nextContent: ContentBlockLike[] = [];
|
|
230
|
+
for (const raw of msg.content) {
|
|
231
|
+
const block = raw as ContentBlockLike;
|
|
232
|
+
const updated = transform(block);
|
|
233
|
+
if (updated) {
|
|
234
|
+
changed = true;
|
|
235
|
+
nextContent.push(updated);
|
|
236
|
+
} else {
|
|
237
|
+
nextContent.push(block);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return changed ? { ...msg, content: nextContent } : null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function shrinkToolCallArgs(block: ContentBlockLike, maxArgChars: number, label: string): ContentBlockLike | null {
|
|
244
|
+
if (block.type !== "toolCall" || !block.arguments || typeof block.arguments !== "object") return null;
|
|
245
|
+
let changed = false;
|
|
246
|
+
const nextArgs: Record<string, unknown> = {};
|
|
247
|
+
for (const [k, v] of Object.entries(block.arguments)) {
|
|
248
|
+
if (typeof v === "string" && v.length > maxArgChars) {
|
|
249
|
+
changed = true;
|
|
250
|
+
nextArgs[k] = truncateStringHead(v, maxArgChars, label);
|
|
251
|
+
} else {
|
|
252
|
+
nextArgs[k] = v;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return changed ? { ...block, arguments: nextArgs } : null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Trim only older images / bulky tool payloads in-memory when a mid-run request is about
|
|
260
|
+
* to exceed the hard byte ceiling, keeping message order and toolCall/toolResult pairing
|
|
261
|
+
* intact so the active run finishes without hitting HTTP 413.
|
|
262
|
+
*/
|
|
263
|
+
export function shedMessagesForByteLimit<T extends MessageLike>(
|
|
264
|
+
messages: readonly T[],
|
|
265
|
+
targetMsgBytes: number,
|
|
266
|
+
): { messages: T[]; bytes: number; changed: boolean } {
|
|
267
|
+
const sizes = messages.map((m) => jsonByteLength(m));
|
|
268
|
+
let totalBytes = jsonByteLength(messages);
|
|
269
|
+
if (totalBytes <= targetMsgBytes || messages.length === 0) {
|
|
270
|
+
return { messages: messages as T[], bytes: totalBytes, changed: false };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const out = messages.slice();
|
|
274
|
+
let changed = false;
|
|
275
|
+
|
|
276
|
+
const replaceMessage = (idx: number, next: MessageLike | null): void => {
|
|
277
|
+
if (!next) return;
|
|
278
|
+
const nextSize = jsonByteLength(next);
|
|
279
|
+
if (nextSize >= sizes[idx]) return;
|
|
280
|
+
totalBytes -= sizes[idx] - nextSize;
|
|
281
|
+
sizes[idx] = nextSize;
|
|
282
|
+
out[idx] = next as T;
|
|
283
|
+
changed = true;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// Pass 1: drop images from all messages before the newest image-bearing message.
|
|
287
|
+
let latestImageIdx = -1;
|
|
288
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
289
|
+
const content = out[i]?.content;
|
|
290
|
+
if (Array.isArray(content) && content.some((b) => (b as ContentBlockLike)?.type === "image")) {
|
|
291
|
+
latestImageIdx = i;
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
for (let i = 0; i < latestImageIdx && totalBytes > targetMsgBytes; i++) {
|
|
296
|
+
replaceMessage(
|
|
297
|
+
i,
|
|
298
|
+
mapContentBlocks(out[i], (b) =>
|
|
299
|
+
b.type === "image" ? { type: "text", text: "[earlier image omitted]" } : null,
|
|
300
|
+
),
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Pass 1b: drop thinking blocks (and signatures) from assistant turns before the latest user message.
|
|
305
|
+
let lastUserIdx = -1;
|
|
306
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
307
|
+
if (out[i]?.role === "user") {
|
|
308
|
+
lastUserIdx = i;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
for (let i = 0; i < lastUserIdx && totalBytes > targetMsgBytes; i++) {
|
|
313
|
+
if (out[i]?.role !== "assistant" || !Array.isArray(out[i]?.content)) continue;
|
|
314
|
+
const content = out[i].content as ContentBlockLike[];
|
|
315
|
+
if (!content.some((b) => b.type === "thinking")) continue;
|
|
316
|
+
const filtered = content.filter((b) => b.type !== "thinking");
|
|
317
|
+
replaceMessage(i, {
|
|
318
|
+
...out[i],
|
|
319
|
+
content: filtered.length > 0 ? filtered : [{ type: "text", text: "[thinking omitted]" }],
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Preserve the newest turn(s) untouched so the active prompt/tool results stay exact.
|
|
324
|
+
const tailStart = Math.max(0, out.length - (out.length > 8 ? 4 : 2));
|
|
325
|
+
|
|
326
|
+
// Pass 2: trim bulky toolResult text blocks from oldest to newest before tailStart.
|
|
327
|
+
for (let i = 0; i < tailStart && totalBytes > targetMsgBytes; i++) {
|
|
328
|
+
if (out[i]?.role !== "toolResult") continue;
|
|
329
|
+
replaceMessage(
|
|
330
|
+
i,
|
|
331
|
+
mapContentBlocks(out[i], (b) =>
|
|
332
|
+
b.type === "text" && typeof b.text === "string" && b.text.length > 300
|
|
333
|
+
? { ...b, text: TRIMMED_TOOL_STUB }
|
|
334
|
+
: null,
|
|
335
|
+
),
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Pass 3: trim long assistant/user text & toolCall args before tailStart.
|
|
340
|
+
for (let i = 0; i < tailStart && totalBytes > targetMsgBytes; i++) {
|
|
341
|
+
replaceMessage(
|
|
342
|
+
i,
|
|
343
|
+
mapContentBlocks(out[i], (b) => {
|
|
344
|
+
if (b.type === "text" && typeof b.text === "string" && b.text.length > 600) {
|
|
345
|
+
return { ...b, text: truncateStringHead(b.text, 600, TRIM_LABEL) };
|
|
346
|
+
}
|
|
347
|
+
if (b.type === "thinking" && typeof b.thinking === "string" && b.thinking.length > 300) {
|
|
348
|
+
return { ...b, thinking: truncateStringHead(b.thinking, 300, "trimmed") };
|
|
349
|
+
}
|
|
350
|
+
return shrinkToolCallArgs(b, 400, "trimmed");
|
|
351
|
+
}),
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Pass 4: emergency tail trim when even the newest turn alone exceeds the byte ceiling.
|
|
356
|
+
for (let i = tailStart; i < out.length && totalBytes > targetMsgBytes; i++) {
|
|
357
|
+
replaceMessage(
|
|
358
|
+
i,
|
|
359
|
+
mapContentBlocks(out[i], (b) => {
|
|
360
|
+
if (b.type === "thinking" && typeof b.thinking === "string" && b.thinking.length > 300) {
|
|
361
|
+
return { ...b, thinking: truncateStringHead(b.thinking, 300, "trimmed") };
|
|
362
|
+
}
|
|
363
|
+
if (b.type === "text" && typeof b.text === "string" && b.text.length > 8000) {
|
|
364
|
+
return { ...b, text: truncateStringHead(b.text, 8000, TRIM_LABEL) };
|
|
365
|
+
}
|
|
366
|
+
return shrinkToolCallArgs(b, 4000, TRIM_LABEL);
|
|
367
|
+
}),
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Pass 5: when thousands of short messages still exceed the byte ceiling, drop oldest
|
|
372
|
+
// turns from the head while keeping toolCall/toolResult pairing and user-first order intact.
|
|
373
|
+
if (totalBytes > targetMsgBytes && out.length > 2) {
|
|
374
|
+
const minKeep = Math.min(out.length, 4);
|
|
375
|
+
let dropEnd = 0;
|
|
376
|
+
while (totalBytes > targetMsgBytes && out.length - dropEnd > minKeep) {
|
|
377
|
+
totalBytes -= sizes[dropEnd] + 1;
|
|
378
|
+
dropEnd += 1;
|
|
379
|
+
while (dropEnd < out.length - minKeep && out[dropEnd]?.role === "toolResult") {
|
|
380
|
+
totalBytes -= sizes[dropEnd] + 1;
|
|
381
|
+
dropEnd += 1;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (dropEnd > 0) {
|
|
385
|
+
const kept = out.slice(dropEnd);
|
|
386
|
+
if (kept[0]?.role !== "user") {
|
|
387
|
+
kept.unshift({ role: "user", content: [{ type: "text", text: "[earlier turns omitted for 1MB request limit]" }] } as T);
|
|
388
|
+
}
|
|
389
|
+
return { messages: kept, bytes: jsonByteLength(kept), changed: true };
|
|
390
|
+
}
|
|
127
391
|
}
|
|
392
|
+
|
|
393
|
+
return { messages: out, bytes: totalBytes, changed };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Shrink oversized `toolCall` arguments and long text blocks inside `messagesToSummarize`
|
|
398
|
+
* (cloned, never mutating live transcript entries) so compaction itself stays under 1 MB.
|
|
399
|
+
*/
|
|
400
|
+
export function trimCompactionInput(messagesToSummarize: MessageLike[] | undefined, maxBytes: number): boolean {
|
|
401
|
+
if (!Array.isArray(messagesToSummarize) || messagesToSummarize.length === 0) return false;
|
|
402
|
+
let totalBytes = jsonByteLength(messagesToSummarize);
|
|
403
|
+
if (totalBytes <= maxBytes) return false;
|
|
404
|
+
|
|
405
|
+
let changed = false;
|
|
406
|
+
const shrinkPass = (maxText: number, maxArg: number): void => {
|
|
407
|
+
for (let i = 0; i < messagesToSummarize.length && totalBytes > maxBytes; i++) {
|
|
408
|
+
const msg = messagesToSummarize[i];
|
|
409
|
+
const oldSize = jsonByteLength(msg);
|
|
410
|
+
const next = mapContentBlocks(msg, (b) => {
|
|
411
|
+
const shrunk = shrinkToolCallArgs(b, maxArg, "trimmed for compaction");
|
|
412
|
+
if (shrunk) return shrunk;
|
|
413
|
+
if (b.type === "text" && typeof b.text === "string" && b.text.length > maxText) {
|
|
414
|
+
return { ...b, text: truncateStringHead(b.text, maxText, "trimmed for compaction") };
|
|
415
|
+
}
|
|
416
|
+
return null;
|
|
417
|
+
});
|
|
418
|
+
if (!next) continue;
|
|
419
|
+
const nextSize = jsonByteLength(next);
|
|
420
|
+
if (nextSize < oldSize) {
|
|
421
|
+
messagesToSummarize[i] = next;
|
|
422
|
+
totalBytes -= oldSize - nextSize;
|
|
423
|
+
changed = true;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
shrinkPass(3000, 1200);
|
|
429
|
+
if (totalBytes > maxBytes) {
|
|
430
|
+
shrinkPass(800, 300);
|
|
431
|
+
}
|
|
432
|
+
if (totalBytes > maxBytes && messagesToSummarize.length > 2) {
|
|
433
|
+
const sizes = messagesToSummarize.map((m) => jsonByteLength(m));
|
|
434
|
+
let dropEnd = 0;
|
|
435
|
+
const minKeep = 2;
|
|
436
|
+
while (totalBytes > maxBytes && messagesToSummarize.length - dropEnd > minKeep) {
|
|
437
|
+
totalBytes -= sizes[dropEnd] + 1;
|
|
438
|
+
dropEnd += 1;
|
|
439
|
+
while (dropEnd < messagesToSummarize.length - minKeep && messagesToSummarize[dropEnd]?.role === "toolResult") {
|
|
440
|
+
totalBytes -= sizes[dropEnd] + 1;
|
|
441
|
+
dropEnd += 1;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (dropEnd > 0) {
|
|
445
|
+
messagesToSummarize.splice(0, dropEnd);
|
|
446
|
+
changed = true;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
return changed;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Registered handlers against a fake pi: Smart + Render cache On uses 90% on 1M (~943k tokens),
|
|
453
|
+
// while Render cache Off falls back to ~200k tokens. The registrar's byte tracking is exposed
|
|
454
|
+
// through a getter so the self-check can assert the i1 guard never touches it for plain models.
|
|
455
|
+
let trackedOverheadBytes = -1;
|
|
456
|
+
|
|
457
|
+
/** Last observed wire size (messages + overhead) for byte-limited models, or null.
|
|
458
|
+
* Consumed by the footer to show payload pressure against the 1 MB proxy wall. */
|
|
459
|
+
export function wireBytesSnapshot(): { bytes: number; limit: number } | null {
|
|
460
|
+
const state = (globalThis as Record<symbol, AutoCompactState | undefined>)[Symbol.for("pi-arnative.autocompactState")];
|
|
461
|
+
if (!state || state.lastMessagesBytes <= 0) return null;
|
|
462
|
+
const overhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
|
|
463
|
+
return { bytes: state.lastMessagesBytes + overhead, limit: SHED_TRIGGER_BYTES };
|
|
128
464
|
}
|
|
129
465
|
|
|
130
466
|
export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
131
467
|
const state = freshAutoCompactState();
|
|
468
|
+
Object.defineProperty(state, "overheadBytes", {
|
|
469
|
+
get(): number {
|
|
470
|
+
return this._overheadBytes;
|
|
471
|
+
},
|
|
472
|
+
set(v: number) {
|
|
473
|
+
this._overheadBytes = v;
|
|
474
|
+
trackedOverheadBytes = v;
|
|
475
|
+
},
|
|
476
|
+
});
|
|
477
|
+
(state as { _overheadBytes?: number })._overheadBytes = 0;
|
|
478
|
+
// Production and self-check both read this snapshot symbol (footer uses wireBytesSnapshot).
|
|
479
|
+
(globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.autocompactState")] = state;
|
|
480
|
+
|
|
481
|
+
const resetByteTracking = (): void => {
|
|
482
|
+
state.lastMessagesBytes = 0;
|
|
483
|
+
state.overheadBytes = 0;
|
|
484
|
+
state.saw413 = false;
|
|
485
|
+
state.compacting = false;
|
|
486
|
+
state.awaitingContextPayload = false;
|
|
487
|
+
};
|
|
132
488
|
|
|
133
489
|
pi.on("session_start", async () => {
|
|
134
490
|
// Fresh session (or /reload): backoff and attempt state belonged to the previous branch.
|
|
135
491
|
Object.assign(state, freshAutoCompactState());
|
|
136
492
|
});
|
|
137
493
|
|
|
494
|
+
pi.on("model_select", async () => {
|
|
495
|
+
resetByteTracking();
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
pi.on("turn_end", async (event) => {
|
|
499
|
+
const msg = (event as { message?: { stopReason?: string; errorMessage?: string } } | undefined)?.message;
|
|
500
|
+
if (msg?.stopReason === "error" && isPayloadTooLargeError(msg.errorMessage)) {
|
|
501
|
+
state.saw413 = true;
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
pi.on("context", async (event, ctx) => {
|
|
506
|
+
// Skip the full-transcript JSON.stringify entirely for models with no byte wall:
|
|
507
|
+
// measurement is the only cost here, and non-remote sessions pay it every turn.
|
|
508
|
+
if (!state.saw413 && !isByteLimitedModel(ctx?.model)) return;
|
|
509
|
+
const messages = (event as { messages?: MessageLike[] } | undefined)?.messages;
|
|
510
|
+
if (!Array.isArray(messages)) return;
|
|
511
|
+
// JSON serialization includes UTF-8 characters, escapes, and array separators.
|
|
512
|
+
const msgBytes = cachedArrayBytes(messages);
|
|
513
|
+
state.lastMessagesBytes = msgBytes;
|
|
514
|
+
state.awaitingContextPayload = true;
|
|
515
|
+
|
|
516
|
+
const triggerBytes = state.saw413 ? SHED_TRIGGER_AFTER_413_BYTES : SHED_TRIGGER_BYTES;
|
|
517
|
+
const targetBytes = state.saw413 ? SHED_TARGET_AFTER_413_BYTES : SHED_TARGET_BYTES;
|
|
518
|
+
const effectiveOverhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
|
|
519
|
+
if (msgBytes + effectiveOverhead < triggerBytes) return;
|
|
520
|
+
|
|
521
|
+
const targetMsgBytes = Math.max(MIN_MSG_BUDGET_BYTES, targetBytes - effectiveOverhead);
|
|
522
|
+
const shed = shedMessagesForByteLimit(messages, targetMsgBytes);
|
|
523
|
+
if (!shed.changed) return;
|
|
524
|
+
|
|
525
|
+
state.lastMessagesBytes = shed.bytes;
|
|
526
|
+
return { messages: shed.messages } as never;
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
pi.on("before_provider_request", async (event) => {
|
|
530
|
+
if (state.inFlight || state.compacting) return;
|
|
531
|
+
if (!state.awaitingContextPayload || state.lastMessagesBytes <= 0) return;
|
|
532
|
+
const payload = (event as { payload?: unknown } | undefined)?.payload;
|
|
533
|
+
const bytes = jsonByteLength(payload);
|
|
534
|
+
if (bytes <= 0) return;
|
|
535
|
+
|
|
536
|
+
if (bytes >= state.lastMessagesBytes) {
|
|
537
|
+
state.overheadBytes = bytes - state.lastMessagesBytes;
|
|
538
|
+
}
|
|
539
|
+
state.awaitingContextPayload = false;
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
pi.on("session_before_compact", async (event, ctx) => {
|
|
543
|
+
state.compacting = true;
|
|
544
|
+
if (!state.saw413 && !isByteLimitedModel(ctx?.model)) return;
|
|
545
|
+
const prep = (
|
|
546
|
+
event as {
|
|
547
|
+
preparation?: {
|
|
548
|
+
messagesToSummarize?: MessageLike[];
|
|
549
|
+
turnPrefixMessages?: MessageLike[];
|
|
550
|
+
previousSummary?: string;
|
|
551
|
+
};
|
|
552
|
+
} | undefined
|
|
553
|
+
)?.preparation;
|
|
554
|
+
if (!prep) return;
|
|
555
|
+
const prevBytes = prep.previousSummary ? jsonByteLength(prep.previousSummary) : 0;
|
|
556
|
+
const summaryBudget = Math.max(128 * 1024, COMPACT_INPUT_BYTES - prevBytes);
|
|
557
|
+
trimCompactionInput(prep.messagesToSummarize, summaryBudget);
|
|
558
|
+
trimCompactionInput(prep.turnPrefixMessages, Math.round(COMPACT_INPUT_BYTES / 2));
|
|
559
|
+
});
|
|
560
|
+
|
|
138
561
|
pi.on("agent_before_settle", async (_event, ctx) => {
|
|
139
562
|
const usage = typeof ctx.getContextUsage === "function" ? ctx.getContextUsage() : undefined;
|
|
140
|
-
const window = usage?.contextWindow;
|
|
141
|
-
|
|
142
|
-
const threshold = activeAutoCompactThreshold(window);
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
563
|
+
const window = typeof usage?.contextWindow === "number" && usage.contextWindow > 0 ? usage.contextWindow : 0;
|
|
564
|
+
|
|
565
|
+
const threshold = window > 0 ? activeAutoCompactThreshold(window) : null;
|
|
566
|
+
const tokens = usage?.tokens ?? null;
|
|
567
|
+
if (threshold === null || tokens === null) return;
|
|
568
|
+
|
|
569
|
+
rearmAfterDip(state, tokens, threshold);
|
|
570
|
+
|
|
571
|
+
if (autoCompactDecision(state, tokens, threshold) !== "compact") {
|
|
148
572
|
return;
|
|
149
573
|
}
|
|
150
|
-
if (autoCompactDecision(state, tokens, threshold) !== "compact") return;
|
|
151
574
|
if (typeof ctx.compact !== "function") return; // older host without the API
|
|
575
|
+
|
|
152
576
|
state.inFlight = true;
|
|
153
577
|
state.attemptSettled = false;
|
|
154
578
|
state.lastAttemptTokens = tokens;
|
|
@@ -159,16 +583,21 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
|
159
583
|
pi.on("session_compact", async () => {
|
|
160
584
|
// Also fires for pi's own compactions; harmless — the flags only matter after a trigger.
|
|
161
585
|
state.inFlight = false;
|
|
586
|
+
state.compacting = false;
|
|
162
587
|
state.attemptSettled = true;
|
|
588
|
+
state.lastMessagesBytes = 0;
|
|
163
589
|
});
|
|
164
590
|
|
|
165
591
|
pi.on("session_compact_failed", async () => {
|
|
592
|
+
state.compacting = false;
|
|
166
593
|
if (!state.inFlight) return;
|
|
167
594
|
// A failed (or user-aborted) compaction must not retry-loop at the same usage:
|
|
168
595
|
// wait until usage outgrows the attempt by the growth margin.
|
|
169
596
|
state.inFlight = false;
|
|
170
597
|
state.attemptSettled = true;
|
|
171
|
-
|
|
598
|
+
if (state.lastAttemptTokens !== null) {
|
|
599
|
+
state.blockedUntilTokens = state.lastAttemptTokens + growthMargin(state.lastAttemptTokens);
|
|
600
|
+
}
|
|
172
601
|
});
|
|
173
602
|
}
|
|
174
603
|
|
|
@@ -186,21 +615,36 @@ if (isMain(import.meta.url)) {
|
|
|
186
615
|
assert(activeAutoCompactThreshold(131072) === 200000, "a manual budget ignores the window");
|
|
187
616
|
assert(loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES) === "200k", "the choice survives a restart (read from disk)");
|
|
188
617
|
|
|
189
|
-
// Smart's tier table:
|
|
618
|
+
// Smart's tier table: scales to 90% with Render cache On, and falls back to ~200k tiers when Off.
|
|
619
|
+
setRenderCache("On");
|
|
190
620
|
assert(smartPercent(131072) === null, "128k defers to pi core (the 100% tier)");
|
|
191
621
|
assert(smartPercent(196607) === null, "just under the 192k tier edge still defers");
|
|
192
|
-
assert(smartPercent(196608) ===
|
|
193
|
-
assert(smartPercent(262144) ===
|
|
194
|
-
assert(smartPercent(524288) ===
|
|
195
|
-
assert(smartPercent(1048576) ===
|
|
622
|
+
assert(smartPercent(196608) === 90, "the 192k tier edge takes 90% when render cache is On");
|
|
623
|
+
assert(smartPercent(262144) === 90, "256k takes 90% when render cache is On");
|
|
624
|
+
assert(smartPercent(524288) === 90, "512k takes 90% when render cache is On");
|
|
625
|
+
assert(smartPercent(1048576) === 90, "1M takes 90% when render cache is On");
|
|
626
|
+
assert(smartPercent(1048576, false) === 20, "1M falls back to 20% when render cache is Off");
|
|
627
|
+
assert(smartPercent(524288, false) === 40, "512k falls back to 40% when render cache is Off");
|
|
628
|
+
assert(smartPercent(262144, false) === 80, "256k falls back to 80% when render cache is Off");
|
|
196
629
|
setAutoCompact("Smart");
|
|
197
|
-
assert(activeAutoCompactThreshold(1048576) ===
|
|
198
|
-
assert(activeAutoCompactThreshold(262144) ===
|
|
630
|
+
assert(activeAutoCompactThreshold(1048576) === 943718, "Smart + Render cache On triggers at 90% of 1M");
|
|
631
|
+
assert(activeAutoCompactThreshold(262144) === 235930, "Smart + Render cache On triggers at 90% of 256k");
|
|
199
632
|
assert(activeAutoCompactThreshold(131072) === null, "Smart on 128k defers to pi core");
|
|
633
|
+
setRenderCache("Off");
|
|
634
|
+
assert(activeAutoCompactThreshold(1048576) === 209715, "Smart + Render cache Off falls back to ~200k on 1M");
|
|
635
|
+
assert(activeAutoCompactThreshold(262144) === 209715, "Smart + Render cache Off falls back to ~205k on 256k");
|
|
636
|
+
setRenderCache("On");
|
|
200
637
|
setAutoCompact("Off");
|
|
201
638
|
assert(activeAutoCompactThreshold(1048576) === null, "switching back to off disables the trigger");
|
|
202
639
|
|
|
203
|
-
//
|
|
640
|
+
// Remote / 413 detection helpers.
|
|
641
|
+
assert(isByteLimitedModel({ id: "remote/agy-cli/gemini-4-hydrogen" }), "remote/* is byte-limited");
|
|
642
|
+
assert(isByteLimitedModel({ id: "remote-magpie/auto/glm-5.3" }), "remote-magpie/* is byte-limited");
|
|
643
|
+
assert(!isByteLimitedModel({ id: "auto/zaicoding_glm-5.3" }), "non-remote model is not byte-limited by default");
|
|
644
|
+
assert(isPayloadTooLargeError('413 {"error":{"type":"request_too_large"}}'), "detects HTTP 413 request_too_large");
|
|
645
|
+
assert(!isPayloadTooLargeError("429 rate limit"), "ignores non-413 errors");
|
|
646
|
+
|
|
647
|
+
// Decision table (tokens only — byte protection stays decoupled from ctx.compact).
|
|
204
648
|
const s = freshAutoCompactState();
|
|
205
649
|
assert(autoCompactDecision(s, null, 200000) === "wait", "no usage estimate: wait");
|
|
206
650
|
assert(autoCompactDecision(s, 199999, 200000) === "wait", "below the threshold: wait");
|
|
@@ -226,12 +670,69 @@ if (isMain(import.meta.url)) {
|
|
|
226
670
|
rearmAfterDip(r, 189000, 200000);
|
|
227
671
|
assert(r.lastAttemptTokens === null && r.attemptSettled === false && r.blockedUntilTokens === 0, "a real drop forgets the attempt and re-arms");
|
|
228
672
|
|
|
229
|
-
//
|
|
673
|
+
// Mid-run byte shedding keeps recent tail + latest image + latest thinking + tool pairing intact.
|
|
674
|
+
const bigText = "x".repeat(80_000);
|
|
675
|
+
const sampleMsgs: MessageLike[] = [
|
|
676
|
+
{ role: "user", content: [{ type: "text", text: "goal" }, { type: "image", data: "A".repeat(40_000) }] },
|
|
677
|
+
{
|
|
678
|
+
role: "assistant",
|
|
679
|
+
content: [
|
|
680
|
+
{ type: "thinking", thinking: "T".repeat(30_000), thinkingSignature: "sig123" } as ContentBlockLike,
|
|
681
|
+
{ type: "toolCall", arguments: { path: "a.ts" } },
|
|
682
|
+
],
|
|
683
|
+
},
|
|
684
|
+
{ role: "toolResult", content: [{ type: "text", text: bigText }] },
|
|
685
|
+
{ role: "assistant", content: [{ type: "toolCall", arguments: { path: "b.ts" } }] },
|
|
686
|
+
{ role: "toolResult", content: [{ type: "text", text: bigText }] },
|
|
687
|
+
{ role: "user", content: [{ type: "text", text: "latest" }, { type: "image", data: "B".repeat(20_000) }] },
|
|
688
|
+
{
|
|
689
|
+
role: "assistant",
|
|
690
|
+
content: [
|
|
691
|
+
{ type: "thinking", thinking: "keep latest thinking", thinkingSignature: "sigLatest" } as ContentBlockLike,
|
|
692
|
+
{ type: "text", text: "working" },
|
|
693
|
+
],
|
|
694
|
+
},
|
|
695
|
+
];
|
|
696
|
+
const shed = shedMessagesForByteLimit(sampleMsgs, 90_000);
|
|
697
|
+
assert(shed.changed && shed.bytes <= 90_000, "shedding brings oversized messages under budget");
|
|
698
|
+
assert((shed.messages[0].content as ContentBlockLike[])[1].type === "text", "earlier image is omitted");
|
|
699
|
+
assert(
|
|
700
|
+
!(shed.messages[1].content as ContentBlockLike[]).some((b) => b.type === "thinking"),
|
|
701
|
+
"earlier thinking and signature are dropped before latest user turn",
|
|
702
|
+
);
|
|
703
|
+
assert((shed.messages[5].content as ContentBlockLike[])[1].type === "image", "latest image is kept");
|
|
704
|
+
assert(
|
|
705
|
+
(shed.messages[6].content as ContentBlockLike[]).some((b) => b.type === "thinking"),
|
|
706
|
+
"latest turn thinking is kept",
|
|
707
|
+
);
|
|
708
|
+
assert((shed.messages[2].content as ContentBlockLike[])[0].text === TRIMMED_TOOL_STUB, "old tool result trimmed");
|
|
709
|
+
assert((sampleMsgs[2].content as ContentBlockLike[])[0].text === bigText, "shedding never mutates original messages");
|
|
710
|
+
|
|
711
|
+
// Compaction input trimming shrinks huge toolCall args without mutating originals.
|
|
712
|
+
const hugeWriteArgs = "y".repeat(20_000);
|
|
713
|
+
const compactInput: MessageLike[] = [
|
|
714
|
+
{ role: "assistant", content: [{ type: "toolCall", arguments: { path: "big.ts", content: hugeWriteArgs } }] },
|
|
715
|
+
];
|
|
716
|
+
assert(trimCompactionInput(compactInput, 5_000), "trimCompactionInput shrinks oversized toolCall arguments");
|
|
717
|
+
assert((compactInput[0].content as ContentBlockLike[])[0].arguments!.content !== hugeWriteArgs, "cloned argument was truncated");
|
|
718
|
+
|
|
719
|
+
// Emergency tail trim: a single massive toolResult in the newest turn still sheds below target.
|
|
720
|
+
const tailOnlyHuge: MessageLike[] = [
|
|
721
|
+
{ role: "user", content: [{ type: "text", text: "run tool" }] },
|
|
722
|
+
{ role: "toolResult", content: [{ type: "text", text: "y".repeat(SHED_TRIGGER_BYTES + 20_000) }] },
|
|
723
|
+
];
|
|
724
|
+
const tailShed = shedMessagesForByteLimit(tailOnlyHuge, 100_000);
|
|
725
|
+
assert(tailShed.changed && tailShed.bytes <= 100_000, "emergency tail trim bounds even a single giant newest message");
|
|
726
|
+
|
|
727
|
+
// Registered handlers against a fake pi: Smart + Render cache On uses 90% on 1M (~943k tokens),
|
|
728
|
+
// while Render cache Off falls back to ~200k tokens.
|
|
729
|
+
setRenderCache("Off");
|
|
230
730
|
setAutoCompact("Smart");
|
|
231
731
|
const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
|
|
232
732
|
registerAutoCompact({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
|
|
233
733
|
const compactCalls: number[] = [];
|
|
234
|
-
const ctxOf = (tokens: number | null, contextWindow = 1_048_576) => ({
|
|
734
|
+
const ctxOf = (tokens: number | null, contextWindow = 1_048_576, model?: { id: string }) => ({
|
|
735
|
+
model,
|
|
235
736
|
getContextUsage: () => ({ tokens, contextWindow, percent: tokens === null ? null : (tokens / contextWindow) * 100 }),
|
|
236
737
|
compact: () => compactCalls.push(tokens ?? -1),
|
|
237
738
|
});
|
|
@@ -271,24 +772,119 @@ if (isMain(import.meta.url)) {
|
|
|
271
772
|
await handlers.agent_before_settle!({}, ctxOf(210500));
|
|
272
773
|
assert(compactCalls.length === 6, "a fresh session clears the backoff");
|
|
273
774
|
|
|
775
|
+
// Smart + Render cache On: scales 1M window to 90% (~943k), and remote 1 MB payloads shed silently
|
|
776
|
+
// without forcing premature session compaction at low token counts (e.g. 49k–110k).
|
|
777
|
+
setRenderCache("On");
|
|
778
|
+
await handlers.session_start!({}, undefined);
|
|
779
|
+
const remoteCtx = ctxOf(49836, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" });
|
|
780
|
+
const hugeRunMsgs: MessageLike[] = [
|
|
781
|
+
{ role: "user", content: [{ type: "text", text: "start" }] },
|
|
782
|
+
{ role: "assistant", content: [{ type: "toolCall", arguments: { path: "x" } }] },
|
|
783
|
+
{ role: "toolResult", content: [{ type: "text", text: "z".repeat(SHED_TRIGGER_BYTES + 10_000) }] },
|
|
784
|
+
{ role: "user", content: [{ type: "text", text: "continue" }] },
|
|
785
|
+
{ role: "assistant", content: [{ type: "text", text: "ok" }] },
|
|
786
|
+
];
|
|
787
|
+
const ctxResult = (await handlers.context!({ messages: hugeRunMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
|
|
788
|
+
assert(
|
|
789
|
+
Array.isArray(ctxResult?.messages) &&
|
|
790
|
+
jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= SHED_TARGET_BYTES,
|
|
791
|
+
"context hook sheds payload with hysteresis down to the target ceiling",
|
|
792
|
+
);
|
|
793
|
+
await handlers.before_provider_request!({ payload: { blob: "p".repeat(SHED_TRIGGER_BYTES + 20_000) } }, remoteCtx);
|
|
794
|
+
await handlers.agent_before_settle!({}, remoteCtx);
|
|
795
|
+
assert(compactCalls.length === 6, "remote byte shedding does not force premature compaction at 49k tokens");
|
|
796
|
+
|
|
797
|
+
// Only crossing 90% of 1M context triggers Smart compaction when Render cache is On.
|
|
798
|
+
await handlers.agent_before_settle!({}, ctxOf(900000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
|
|
799
|
+
assert(compactCalls.length === 6, "900k tokens is still under 90% of 1M");
|
|
800
|
+
await handlers.agent_before_settle!({}, ctxOf(945000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
|
|
801
|
+
assert(compactCalls.length === 7 && compactCalls[6] === 945000, "945k tokens hits 90% Smart threshold and compacts");
|
|
802
|
+
await handlers.session_compact!({}, undefined);
|
|
803
|
+
|
|
804
|
+
// Compaction input trimming shrinks split-turn prefixes cleanly without triggering follow-ups.
|
|
805
|
+
const splitTurnPrefix: MessageLike[] = [
|
|
806
|
+
{ role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(COMPACT_INPUT_BYTES) } }] },
|
|
807
|
+
];
|
|
808
|
+
await handlers.session_before_compact!({ preparation: { turnPrefixMessages: splitTurnPrefix } }, remoteCtx);
|
|
809
|
+
assert(jsonByteLength(splitTurnPrefix) < COMPACT_INPUT_BYTES, "session_before_compact trims split-turn prefix messages too");
|
|
810
|
+
|
|
811
|
+
// Remote byte silent shedding stays active even when Auto-compact is Off, and never triggers ctx.compact().
|
|
812
|
+
setAutoCompact("Off");
|
|
813
|
+
await handlers.session_start!({}, undefined);
|
|
814
|
+
const manyMsgs: MessageLike[] = [];
|
|
815
|
+
for (let i = 0; i < 900; i++) {
|
|
816
|
+
manyMsgs.push(
|
|
817
|
+
{ role: "user", content: [{ type: "text", text: `turn ${i}: ` + "u".repeat(350) }] },
|
|
818
|
+
{ role: "assistant", content: [{ type: "toolCall", arguments: { cmd: `echo ${i}` } }] },
|
|
819
|
+
{ role: "toolResult", content: [{ type: "text", text: "r".repeat(600) }] },
|
|
820
|
+
{ role: "assistant", content: [{ type: "text", text: "a".repeat(350) }] },
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
assert(jsonByteLength(manyMsgs) > 1_048_576, "fixture spans thousands of messages and over a megabyte");
|
|
824
|
+
const shedMany = (await handlers.context!({ messages: manyMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
|
|
825
|
+
// A fixture sized for the 1 MB default says nothing once the wall scales: at 16 MB
|
|
826
|
+
// the same array is far under the trigger and the hook rightly stays quiet.
|
|
827
|
+
// Size it against the ceiling in force, or skip when scaling makes that impractical.
|
|
828
|
+
const overTrigger = jsonByteLength(manyMsgs) > SHED_TRIGGER_BYTES;
|
|
829
|
+
if (overTrigger) {
|
|
830
|
+
assert(
|
|
831
|
+
Array.isArray(shedMany?.messages) &&
|
|
832
|
+
jsonByteLength(shedMany.messages) <= SHED_TARGET_BYTES &&
|
|
833
|
+
shedMany.messages[0]?.role === "user",
|
|
834
|
+
"many-message session sheds below the ceiling even with Auto-compact Off",
|
|
835
|
+
);
|
|
836
|
+
} else {
|
|
837
|
+
assert(shedMany === undefined, "a fixture under the scaled trigger is left untouched");
|
|
838
|
+
}
|
|
839
|
+
const compactMany = manyMsgs.slice();
|
|
840
|
+
await handlers.session_before_compact!({ preparation: { messagesToSummarize: compactMany } }, remoteCtx);
|
|
841
|
+
assert(
|
|
842
|
+
jsonByteLength(compactMany) <= COMPACT_INPUT_BYTES && compactMany[0]?.role !== "toolResult",
|
|
843
|
+
"many-message compaction input trims below 720 KB without orphaned toolResult",
|
|
844
|
+
);
|
|
845
|
+
await handlers.agent_before_settle!({}, ctxOf(950000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
|
|
846
|
+
assert(compactCalls.length === 7, "Auto-compact Off never calls ctx.compact() even at 950k tokens on remote/*");
|
|
847
|
+
|
|
848
|
+
// Non-remote model that hits HTTP 413 tightens silent shedding without forcing compaction.
|
|
849
|
+
const nonRemoteCtx = ctxOf(50000, 1_048_576, { id: "custom/model" });
|
|
850
|
+
await handlers.turn_end!({ message: { stopReason: "error", errorMessage: "413 request_too_large" } }, nonRemoteCtx);
|
|
851
|
+
const after413 = (await handlers.context!({ messages: hugeRunMsgs }, nonRemoteCtx)) as { messages?: MessageLike[] } | undefined;
|
|
852
|
+
assert(
|
|
853
|
+
Array.isArray(after413?.messages) &&
|
|
854
|
+
jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= SHED_TARGET_AFTER_413_BYTES,
|
|
855
|
+
"saw413 activates tighter silent shedding on any model",
|
|
856
|
+
);
|
|
857
|
+
setAutoCompact("Smart");
|
|
858
|
+
|
|
859
|
+
// i1 guard: models with no byte wall never measure payload bytes at all.
|
|
860
|
+
await handlers.session_start!({}, undefined);
|
|
861
|
+
const plainCtx = ctxOf(210000, 1_048_576, { id: "auto/zaicoding_glm-5.3" });
|
|
862
|
+
const plainMsgs: MessageLike[] = [{ role: "user", content: [{ type: "text", text: "plain" }] }];
|
|
863
|
+
const plainResult = (await handlers.context!({ messages: plainMsgs }, plainCtx)) as { messages?: MessageLike[] } | undefined;
|
|
864
|
+
assert(plainResult === undefined, "non-remote context hook skips byte measurement entirely");
|
|
865
|
+
const overheadBefore = trackedOverheadBytes;
|
|
866
|
+
const plainReq = await handlers.before_provider_request!({ payload: { blob: "p".repeat(4 * 1024 * 1024) } }, plainCtx);
|
|
867
|
+
assert(plainReq === undefined && trackedOverheadBytes === overheadBefore, "non-remote before_provider_request skips the 4 MB stringify");
|
|
868
|
+
|
|
274
869
|
// The 128k case from the field: Smart defers the whole window to pi's own
|
|
275
870
|
// compaction — no percent, however close to full, ever fires ours.
|
|
276
871
|
await handlers.session_start!({}, undefined);
|
|
277
872
|
await handlers.agent_before_settle!({}, ctxOf(130000, 131072));
|
|
278
|
-
assert(compactCalls.length ===
|
|
873
|
+
assert(compactCalls.length === 7, "a 128k window under Smart never triggers: pi core stays in charge");
|
|
279
874
|
|
|
280
875
|
// Older hosts: missing ctx APIs must degrade to a no-op, not throw.
|
|
281
876
|
await handlers.agent_before_settle!({}, { getContextUsage: () => undefined });
|
|
282
|
-
assert(compactCalls.length ===
|
|
877
|
+
assert(compactCalls.length === 7, "no usage estimate: no trigger");
|
|
283
878
|
// Reset inFlight first, so the missing compact() — not a pending compaction — is what stops it.
|
|
284
879
|
await handlers.session_start!({}, undefined);
|
|
285
|
-
await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens:
|
|
286
|
-
assert(compactCalls.length ===
|
|
880
|
+
await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens: 950000, contextWindow: 1_048_576, percent: 90.6 }) });
|
|
881
|
+
assert(compactCalls.length === 7, "no ctx.compact on the host: no trigger");
|
|
287
882
|
|
|
288
883
|
// Restore: the next module load starts from the real agent dir and the stored default.
|
|
289
884
|
rmSync(fixture, { recursive: true, force: true });
|
|
290
885
|
delete process.env.PI_CODING_AGENT_DIR;
|
|
291
886
|
delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
|
|
887
|
+
delete (globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.renderCache")];
|
|
292
888
|
resetPresetCache();
|
|
293
889
|
console.log("autocompact.ts self-check OK");
|
|
294
890
|
}
|