@bismawy/pi-arnative 0.12.0 → 0.14.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.
@@ -1,30 +1,28 @@
1
1
  /**
2
- * Auto-compact — keep long sessions light without the manual /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 the drag a user feels tracks
5
- * the ABSOLUTE size of the session, not how full the window is. A 1M-window model gets
6
- * heavy around 200k tokens (a fifth of its window), while a 128k model can run to
7
- * nearly 100% and let pi's own threshold compaction handle it safely.
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
- * Two shapes of control, both off until picked in `/arnative` → Auto-compact:
10
- * - **Smart** maps the context window through a tier table (≥768k→20%, ≥384k→40%,
11
- * ≥192k→80%, smaller→defer to pi core). Every tier lands the trigger near the same
12
- * ~200k-token transcript ceiling, and small windows never fire at all — pi's own
13
- * `compaction.reserveTokens` compaction stays their safety net.
14
- * - **A manual token budget** (100k–400k) fires at the same absolute size whatever the
15
- * window, for users who want one number.
16
- *
17
- * The trigger is `agent_before_settle` (idle, nothing queued) and fires pi's compaction
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";
24
21
  import { tmpdir } from "node:os";
25
22
  import { join } from "node:path";
26
23
  import { assert, isMain } from "../lib/check.ts";
27
- import { loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
24
+ import { PAYLOAD_LIMIT_KEY, loadChoice, loadSetting, 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,141 @@ 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
- /** Smart's tier table, first match wins. `null` defers the window to pi's own
36
- * compaction — the "100%" tier, where the current behavior is already safe. */
37
- const SMART_TIERS: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
33
+ /** Proxy payload limit presets shown in `/arnative` → Payload limit. */
34
+ export const PAYLOAD_LIMIT_PRESETS = ["Off", "1 MB", "4 MB", "8 MB", "16 MB", "32 MB"] as const;
35
+ export type PayloadLimitPreset = (typeof PAYLOAD_LIMIT_PRESETS)[number];
36
+ export const DEFAULT_PAYLOAD_LIMIT: PayloadLimitPreset = "1 MB";
37
+ export const PAYLOAD_LIMIT_MB_RANGE = { min: 1, max: 1024 } as const;
38
+ export const PAYLOAD_LIMIT_CONFIG_KEY = Symbol.for("pi-arnative.payloadLimit");
39
+
40
+ export interface ByteCeilings {
41
+ mb: number;
42
+ shedTriggerBytes: number;
43
+ shedTargetBytes: number;
44
+ compactInputBytes: number;
45
+ shedTriggerAfter413Bytes: number;
46
+ shedTargetAfter413Bytes: number;
47
+ }
48
+
49
+ function formatMb(mb: number): string {
50
+ return Number.isInteger(mb) ? String(mb) : String(Number(mb.toFixed(2)));
51
+ }
52
+
53
+ /** Parse `"Off"`, a number, or `"16 MB"` / `"16m"` into normalized storage form (`"Off"` or `"<N> MB"`). */
54
+ export function parsePayloadLimit(raw: unknown): string | undefined {
55
+ if (typeof raw === "number") {
56
+ if (!Number.isFinite(raw) || raw < PAYLOAD_LIMIT_MB_RANGE.min || raw > PAYLOAD_LIMIT_MB_RANGE.max) return undefined;
57
+ return `${formatMb(raw)} MB`;
58
+ }
59
+ if (typeof raw !== "string") return undefined;
60
+ const trimmed = raw.trim();
61
+ if (/^off$/i.test(trimmed)) return "Off";
62
+ const m = /^(\d+(?:\.\d+)?)\s*(?:mb|m)?$/i.exec(trimmed);
63
+ if (!m) return undefined;
64
+ const mb = Number(m[1]);
65
+ if (!Number.isFinite(mb) || mb < PAYLOAD_LIMIT_MB_RANGE.min || mb > PAYLOAD_LIMIT_MB_RANGE.max) return undefined;
66
+ return `${formatMb(mb)} MB`;
67
+ }
68
+
69
+ /** Numeric MB limit for a parsed payload limit string, or `null` when `"Off"`. */
70
+ export function payloadLimitMb(choice: string): number | null {
71
+ if (choice === "Off") return null;
72
+ const n = Number.parseFloat(choice);
73
+ return Number.isFinite(n) && n > 0 ? n : 1;
74
+ }
75
+
76
+ /** Shell override via `PI_ARNATIVE_BYTE_WALL_MB`, when set to a valid positive number. */
77
+ export function envByteWallOverride(): string | undefined {
78
+ const raw = process.env.PI_ARNATIVE_BYTE_WALL_MB;
79
+ if (typeof raw !== "string" || raw.trim() === "") return undefined;
80
+ const mb = Number(raw);
81
+ return Number.isFinite(mb) && mb > 0 ? `${formatMb(mb)} MB` : undefined;
82
+ }
83
+
84
+ /** Stored `config.json` choice (`"Off"` or `"<N> MB"`), ignoring process env overrides. */
85
+ export function savedPayloadLimit(): string {
86
+ return parsePayloadLimit(loadSetting(PAYLOAD_LIMIT_KEY)) ?? DEFAULT_PAYLOAD_LIMIT;
87
+ }
88
+
89
+ /** Active payload limit: in-session choice, else `PI_ARNATIVE_BYTE_WALL_MB`, else `config.json` (default `1 MB`). */
90
+ export function activePayloadLimit(): string {
91
+ const slot = (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
92
+ const fromSlot = parsePayloadLimit(slot);
93
+ if (fromSlot) return fromSlot;
94
+ return envByteWallOverride() ?? savedPayloadLimit();
95
+ }
96
+
97
+ /** Apply a payload limit live for this session and persist it to `config.json`. */
98
+ export function setPayloadLimit(choice: string): string {
99
+ const parsed = parsePayloadLimit(choice);
100
+ if (!parsed) throw new Error(`Invalid payload limit: ${choice}`);
101
+ (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY] = parsed;
102
+ saveChoice(PAYLOAD_LIMIT_KEY, parsed);
103
+ return parsed;
104
+ }
105
+
106
+ /** Byte ceilings for an HTTP body wall in MB (ratios target 900/760/720 KB per 1 MB). */
107
+ export function ceilingsForMb(mb: number): ByteCeilings {
108
+ return {
109
+ mb,
110
+ shedTriggerBytes: Math.round(900 * 1024 * mb),
111
+ shedTargetBytes: Math.round(760 * 1024 * mb),
112
+ compactInputBytes: Math.round(720 * 1024 * mb),
113
+ shedTriggerAfter413Bytes: Math.round(820 * 1024 * mb),
114
+ shedTargetAfter413Bytes: Math.round(680 * 1024 * mb),
115
+ };
116
+ }
117
+
118
+ /** Active byte ceilings for this session, or `null` when payload limiting is `Off`. */
119
+ export function activeByteCeilings(): ByteCeilings | null {
120
+ const mb = payloadLimitMb(activePayloadLimit());
121
+ return mb === null ? null : ceilingsForMb(mb);
122
+ }
123
+
124
+ function trimLabelForMb(limitMb: number): string {
125
+ return `trimmed for ${formatMb(limitMb)}MB limit`;
126
+ }
127
+
128
+ // Module-load ceilings retained for backward-compatible test/caller imports.
129
+ const INITIAL_CEILINGS = ceilingsForMb(payloadLimitMb(envByteWallOverride() ?? savedPayloadLimit()) ?? 1);
130
+ export const SHED_TRIGGER_BYTES = INITIAL_CEILINGS.shedTriggerBytes;
131
+ export const SHED_TARGET_BYTES = INITIAL_CEILINGS.shedTargetBytes;
132
+ export const COMPACT_INPUT_BYTES = INITIAL_CEILINGS.compactInputBytes;
133
+ const DEFAULT_OVERHEAD_BYTES = 64 * 1024;
134
+ const MIN_MSG_BUDGET_BYTES = 64 * 1024;
135
+ const TRIMMED_TOOL_STUB = "[earlier output omitted; full output in session]";
136
+
137
+ interface ContentBlockLike {
138
+ type?: string;
139
+ text?: string;
140
+ thinking?: string;
141
+ arguments?: Record<string, unknown>;
142
+ }
143
+
144
+ interface MessageLike {
145
+ role?: string;
146
+ content?: unknown;
147
+ }
148
+
149
+ /** Smart's tier table when Render cache is Off (keeps uncached transcripts near ~200k).
150
+ * When Render cache is On, settled history renders in O(1), so ≥192k windows scale
151
+ * up to 90% of contextWindow while ≤128k windows still defer to pi core. */
152
+ const SMART_TIERS_UNCACHED: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
38
153
  { minWindow: 786432, percent: 20 }, // ≥768k: a 1M window triggers at ~200k tokens
39
154
  { minWindow: 393216, percent: 40 }, // 384k–768k: a 512k window triggers at ~205k
40
155
  { minWindow: 196608, percent: 80 }, // 192k–384k: a 256k window triggers at ~205k
41
156
  { minWindow: 0, percent: null }, // below 192k (128k models): pi core stays in charge
42
157
  ];
43
158
 
159
+ const SMART_TIERS_CACHED: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
160
+ { minWindow: 196608, percent: 90 }, // ≥192k: let render-cached sessions reach 90% of capacity
161
+ { minWindow: 0, percent: null }, // below 192k (128k models): pi core stays in charge
162
+ ];
163
+
44
164
  /** 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 tier = SMART_TIERS.find((t) => contextWindow >= t.minWindow);
165
+ export function smartPercent(contextWindow: number, renderCacheOn = activeRenderCache() === "On"): number | null {
166
+ const tiers = renderCacheOn ? SMART_TIERS_CACHED : SMART_TIERS_UNCACHED;
167
+ const tier = tiers.find((t) => contextWindow >= t.minWindow);
47
168
  return tier?.percent ?? null;
48
169
  }
49
170
 
@@ -86,10 +207,30 @@ export interface AutoCompactState {
86
207
  attemptSettled: boolean;
87
208
  /** Do not trigger while usage stays below this (failure backoff, anti-flap). */
88
209
  blockedUntilTokens: number;
210
+ /** Last observed `context` event messages size in bytes. */
211
+ lastMessagesBytes: number;
212
+ /** Estimated non-message request overhead (system prompt + tool schemas). */
213
+ overheadBytes: number;
214
+ /** Set if this session saw an HTTP 413 / request_too_large error on the active model. */
215
+ saw413: boolean;
216
+ /** True while a compaction request is in progress (prevents polluting byte metrics). */
217
+ compacting: boolean;
218
+ /** True between `context` and the matching `before_provider_request` for that turn. */
219
+ awaitingContextPayload: boolean;
89
220
  }
90
221
 
91
222
  export function freshAutoCompactState(): AutoCompactState {
92
- return { inFlight: false, lastAttemptTokens: null, attemptSettled: false, blockedUntilTokens: 0 };
223
+ return {
224
+ inFlight: false,
225
+ lastAttemptTokens: null,
226
+ attemptSettled: false,
227
+ blockedUntilTokens: 0,
228
+ lastMessagesBytes: 0,
229
+ overheadBytes: 0,
230
+ saw413: false,
231
+ compacting: false,
232
+ awaitingContextPayload: false,
233
+ };
93
234
  }
94
235
 
95
236
  /** How much usage must outgrow a previous attempt before it counts as real growth
@@ -98,57 +239,430 @@ export function growthMargin(thresholdTokens: number): number {
98
239
  return Math.max(5000, Math.round(thresholdTokens * 0.05));
99
240
  }
100
241
 
242
+ /** Remote-routed models enforced behind a 1 MB HTTP body proxy. */
243
+ export function isByteLimitedModel(model: { id?: string; provider?: string } | undefined): boolean {
244
+ const id = model?.id;
245
+ const provider = model?.provider;
246
+ return (
247
+ (typeof id === "string" && (id.startsWith("remote/") || id.startsWith("remote-magpie/"))) ||
248
+ (typeof provider === "string" && (provider === "remote" || provider.startsWith("remote-")))
249
+ );
250
+ }
251
+
252
+ /** True when a provider error string indicates an HTTP 413 request-body size limit. */
253
+ export function isPayloadTooLargeError(errorMessage: string | undefined): boolean {
254
+ return typeof errorMessage === "string" && /\b413\b|request_too_large|entity too large/i.test(errorMessage);
255
+ }
256
+
257
+ /** UTF-8 JSON byte length, returning 0 on non-serializable values. */
258
+ export function jsonByteLength(value: unknown): number {
259
+ try {
260
+ const raw = JSON.stringify(value);
261
+ return raw === undefined ? 0 : Buffer.byteLength(raw, "utf8");
262
+ } catch {
263
+ return 0;
264
+ }
265
+ }
266
+
267
+ /** Keep the helper API, but measure each request: Pi clones messages before `context`. */
268
+ export function cachedArrayBytes(messages: MessageLike[]): number {
269
+ return jsonByteLength(messages);
270
+ }
271
+
101
272
  /** Pure decision for the settle handler: fire pi's compaction now, or wait. */
102
273
  export function autoCompactDecision(
103
274
  state: AutoCompactState,
104
275
  tokens: number | null,
105
- thresholdTokens: number,
276
+ thresholdTokens: number | null,
106
277
  ): "compact" | "wait" {
107
- if (tokens === null || tokens < thresholdTokens) return "wait";
108
- if (state.inFlight) return "wait";
109
- if (tokens < state.blockedUntilTokens) return "wait";
110
- // A finished compaction that still left usage at or above the threshold freed too
111
- // little: wait for real growth instead of re-summarizing every settle.
112
- if (state.attemptSettled && state.lastAttemptTokens !== null && tokens < state.lastAttemptTokens + growthMargin(thresholdTokens)) {
278
+ if (state.inFlight || thresholdTokens === null || tokens === null) return "wait";
279
+ if (tokens < thresholdTokens || tokens < state.blockedUntilTokens) return "wait";
280
+ if (
281
+ state.attemptSettled &&
282
+ state.lastAttemptTokens !== null &&
283
+ tokens < state.lastAttemptTokens + growthMargin(thresholdTokens)
284
+ ) {
113
285
  return "wait";
114
286
  }
115
287
  return "compact";
116
288
  }
117
289
 
118
- /** Usage dropped back under the threshold (the handler's below-threshold branch).
119
- * A shallow dip — still within the growth margin of the last attempt — keeps the
120
- * attempt memory, so usage oscillating right at the threshold cannot re-summarize
121
- * every turn. A real drop forgets the attempt and re-arms the trigger fully. */
122
- export function rearmAfterDip(state: AutoCompactState, tokens: number, thresholdTokens: number): void {
123
- if (state.lastAttemptTokens === null || tokens < state.lastAttemptTokens - growthMargin(thresholdTokens)) {
124
- state.lastAttemptTokens = null;
125
- state.attemptSettled = false;
126
- state.blockedUntilTokens = 0;
290
+ /** Clear attempt memory once usage really dropped under the threshold (prevents
291
+ * oscillation at the edge while re-arming cleanly after an effective compaction). */
292
+ export function rearmAfterDip(state: AutoCompactState, tokens: number | null, thresholdTokens: number | null): void {
293
+ if (thresholdTokens === null || tokens === null || tokens >= thresholdTokens) return;
294
+ if (state.lastAttemptTokens !== null && tokens >= state.lastAttemptTokens - growthMargin(thresholdTokens)) return;
295
+ state.lastAttemptTokens = null;
296
+ state.attemptSettled = false;
297
+ state.blockedUntilTokens = 0;
298
+ }
299
+
300
+ function truncateStringHead(text: string, maxChars: number, label: string): string {
301
+ if (text.length <= maxChars) return text;
302
+ return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} chars ${label}]`;
303
+ }
304
+
305
+ function mapContentBlocks(
306
+ msg: MessageLike,
307
+ transform: (block: ContentBlockLike) => ContentBlockLike | null,
308
+ ): MessageLike | null {
309
+ if (!Array.isArray(msg.content)) return null;
310
+ let changed = false;
311
+ const nextContent: ContentBlockLike[] = [];
312
+ for (const raw of msg.content) {
313
+ const block = raw as ContentBlockLike;
314
+ const updated = transform(block);
315
+ if (updated) {
316
+ changed = true;
317
+ nextContent.push(updated);
318
+ } else {
319
+ nextContent.push(block);
320
+ }
321
+ }
322
+ return changed ? { ...msg, content: nextContent } : null;
323
+ }
324
+
325
+ function shrinkToolCallArgs(block: ContentBlockLike, maxArgChars: number, label: string): ContentBlockLike | null {
326
+ if (block.type !== "toolCall" || !block.arguments || typeof block.arguments !== "object") return null;
327
+ let changed = false;
328
+ const nextArgs: Record<string, unknown> = {};
329
+ for (const [k, v] of Object.entries(block.arguments)) {
330
+ if (typeof v === "string" && v.length > maxArgChars) {
331
+ changed = true;
332
+ nextArgs[k] = truncateStringHead(v, maxArgChars, label);
333
+ } else {
334
+ nextArgs[k] = v;
335
+ }
127
336
  }
337
+ return changed ? { ...block, arguments: nextArgs } : null;
338
+ }
339
+
340
+ /**
341
+ * Trim only older images / bulky tool payloads in-memory when a mid-run request is about
342
+ * to exceed the hard byte ceiling, keeping message order and toolCall/toolResult pairing
343
+ * intact so the active run finishes without hitting HTTP 413.
344
+ */
345
+ export function shedMessagesForByteLimit<T extends MessageLike>(
346
+ messages: readonly T[],
347
+ targetMsgBytes: number,
348
+ limitMb = payloadLimitMb(activePayloadLimit()) ?? 1,
349
+ ): { messages: T[]; bytes: number; changed: boolean } {
350
+ const trimLabel = trimLabelForMb(limitMb);
351
+ const sizes = messages.map((m) => jsonByteLength(m));
352
+ let totalBytes = jsonByteLength(messages);
353
+ if (totalBytes <= targetMsgBytes || messages.length === 0) {
354
+ return { messages: messages as T[], bytes: totalBytes, changed: false };
355
+ }
356
+
357
+ const out = messages.slice();
358
+ let changed = false;
359
+
360
+ const replaceMessage = (idx: number, next: MessageLike | null): void => {
361
+ if (!next) return;
362
+ const nextSize = jsonByteLength(next);
363
+ if (nextSize >= sizes[idx]) return;
364
+ totalBytes -= sizes[idx] - nextSize;
365
+ sizes[idx] = nextSize;
366
+ out[idx] = next as T;
367
+ changed = true;
368
+ };
369
+
370
+ // Pass 1: drop images from all messages before the newest image-bearing message.
371
+ let latestImageIdx = -1;
372
+ for (let i = out.length - 1; i >= 0; i--) {
373
+ const content = out[i]?.content;
374
+ if (Array.isArray(content) && content.some((b) => (b as ContentBlockLike)?.type === "image")) {
375
+ latestImageIdx = i;
376
+ break;
377
+ }
378
+ }
379
+ for (let i = 0; i < latestImageIdx && totalBytes > targetMsgBytes; i++) {
380
+ replaceMessage(
381
+ i,
382
+ mapContentBlocks(out[i], (b) =>
383
+ b.type === "image" ? { type: "text", text: "[earlier image omitted]" } : null,
384
+ ),
385
+ );
386
+ }
387
+
388
+ // Pass 1b: drop thinking blocks (and signatures) from assistant turns before the latest user message.
389
+ let lastUserIdx = -1;
390
+ for (let i = out.length - 1; i >= 0; i--) {
391
+ if (out[i]?.role === "user") {
392
+ lastUserIdx = i;
393
+ break;
394
+ }
395
+ }
396
+ for (let i = 0; i < lastUserIdx && totalBytes > targetMsgBytes; i++) {
397
+ if (out[i]?.role !== "assistant" || !Array.isArray(out[i]?.content)) continue;
398
+ const content = out[i].content as ContentBlockLike[];
399
+ if (!content.some((b) => b.type === "thinking")) continue;
400
+ const filtered = content.filter((b) => b.type !== "thinking");
401
+ replaceMessage(i, {
402
+ ...out[i],
403
+ content: filtered.length > 0 ? filtered : [{ type: "text", text: "[thinking omitted]" }],
404
+ });
405
+ }
406
+
407
+ // Preserve the newest turn(s) untouched so the active prompt/tool results stay exact.
408
+ const tailStart = Math.max(0, out.length - (out.length > 8 ? 4 : 2));
409
+
410
+ // Pass 2: trim bulky toolResult text blocks from oldest to newest before tailStart.
411
+ for (let i = 0; i < tailStart && totalBytes > targetMsgBytes; i++) {
412
+ if (out[i]?.role !== "toolResult") continue;
413
+ replaceMessage(
414
+ i,
415
+ mapContentBlocks(out[i], (b) =>
416
+ b.type === "text" && typeof b.text === "string" && b.text.length > 300
417
+ ? { ...b, text: TRIMMED_TOOL_STUB }
418
+ : null,
419
+ ),
420
+ );
421
+ }
422
+
423
+ // Pass 3: trim long assistant/user text & toolCall args before tailStart.
424
+ for (let i = 0; i < tailStart && totalBytes > targetMsgBytes; i++) {
425
+ replaceMessage(
426
+ i,
427
+ mapContentBlocks(out[i], (b) => {
428
+ if (b.type === "text" && typeof b.text === "string" && b.text.length > 600) {
429
+ return { ...b, text: truncateStringHead(b.text, 600, trimLabel) };
430
+ }
431
+ if (b.type === "thinking" && typeof b.thinking === "string" && b.thinking.length > 300) {
432
+ return { ...b, thinking: truncateStringHead(b.thinking, 300, "trimmed") };
433
+ }
434
+ return shrinkToolCallArgs(b, 400, "trimmed");
435
+ }),
436
+ );
437
+ }
438
+
439
+ // Pass 4: emergency tail trim when even the newest turn alone exceeds the byte ceiling.
440
+ for (let i = tailStart; i < out.length && totalBytes > targetMsgBytes; i++) {
441
+ replaceMessage(
442
+ i,
443
+ mapContentBlocks(out[i], (b) => {
444
+ if (b.type === "thinking" && typeof b.thinking === "string" && b.thinking.length > 300) {
445
+ return { ...b, thinking: truncateStringHead(b.thinking, 300, "trimmed") };
446
+ }
447
+ if (b.type === "text" && typeof b.text === "string" && b.text.length > 8000) {
448
+ return { ...b, text: truncateStringHead(b.text, 8000, trimLabel) };
449
+ }
450
+ return shrinkToolCallArgs(b, 4000, trimLabel);
451
+ }),
452
+ );
453
+ }
454
+
455
+ // Pass 5: when thousands of short messages still exceed the byte ceiling, drop oldest
456
+ // turns from the head while keeping toolCall/toolResult pairing and user-first order intact.
457
+ if (totalBytes > targetMsgBytes && out.length > 2) {
458
+ const minKeep = Math.min(out.length, 4);
459
+ let dropEnd = 0;
460
+ while (totalBytes > targetMsgBytes && out.length - dropEnd > minKeep) {
461
+ totalBytes -= sizes[dropEnd] + 1;
462
+ dropEnd += 1;
463
+ while (dropEnd < out.length - minKeep && out[dropEnd]?.role === "toolResult") {
464
+ totalBytes -= sizes[dropEnd] + 1;
465
+ dropEnd += 1;
466
+ }
467
+ }
468
+ if (dropEnd > 0) {
469
+ const kept = out.slice(dropEnd);
470
+ if (kept[0]?.role !== "user") {
471
+ kept.unshift({ role: "user", content: [{ type: "text", text: `[earlier turns omitted for ${formatMb(limitMb)}MB request limit]` }] } as T);
472
+ }
473
+ return { messages: kept, bytes: jsonByteLength(kept), changed: true };
474
+ }
475
+ }
476
+
477
+ return { messages: out, bytes: totalBytes, changed };
478
+ }
479
+
480
+ /**
481
+ * Shrink oversized `toolCall` arguments and long text blocks inside `messagesToSummarize`
482
+ * (cloned, never mutating live transcript entries) so compaction itself stays under 1 MB.
483
+ */
484
+ export function trimCompactionInput(messagesToSummarize: MessageLike[] | undefined, maxBytes: number): boolean {
485
+ if (!Array.isArray(messagesToSummarize) || messagesToSummarize.length === 0) return false;
486
+ let totalBytes = jsonByteLength(messagesToSummarize);
487
+ if (totalBytes <= maxBytes) return false;
488
+
489
+ let changed = false;
490
+ const shrinkPass = (maxText: number, maxArg: number): void => {
491
+ for (let i = 0; i < messagesToSummarize.length && totalBytes > maxBytes; i++) {
492
+ const msg = messagesToSummarize[i];
493
+ const oldSize = jsonByteLength(msg);
494
+ const next = mapContentBlocks(msg, (b) => {
495
+ const shrunk = shrinkToolCallArgs(b, maxArg, "trimmed for compaction");
496
+ if (shrunk) return shrunk;
497
+ if (b.type === "text" && typeof b.text === "string" && b.text.length > maxText) {
498
+ return { ...b, text: truncateStringHead(b.text, maxText, "trimmed for compaction") };
499
+ }
500
+ return null;
501
+ });
502
+ if (!next) continue;
503
+ const nextSize = jsonByteLength(next);
504
+ if (nextSize < oldSize) {
505
+ messagesToSummarize[i] = next;
506
+ totalBytes -= oldSize - nextSize;
507
+ changed = true;
508
+ }
509
+ }
510
+ };
511
+
512
+ shrinkPass(3000, 1200);
513
+ if (totalBytes > maxBytes) {
514
+ shrinkPass(800, 300);
515
+ }
516
+ if (totalBytes > maxBytes && messagesToSummarize.length > 2) {
517
+ const sizes = messagesToSummarize.map((m) => jsonByteLength(m));
518
+ let dropEnd = 0;
519
+ const minKeep = 2;
520
+ while (totalBytes > maxBytes && messagesToSummarize.length - dropEnd > minKeep) {
521
+ totalBytes -= sizes[dropEnd] + 1;
522
+ dropEnd += 1;
523
+ while (dropEnd < messagesToSummarize.length - minKeep && messagesToSummarize[dropEnd]?.role === "toolResult") {
524
+ totalBytes -= sizes[dropEnd] + 1;
525
+ dropEnd += 1;
526
+ }
527
+ }
528
+ if (dropEnd > 0) {
529
+ messagesToSummarize.splice(0, dropEnd);
530
+ changed = true;
531
+ }
532
+ }
533
+ return changed;
534
+ }
535
+
536
+ // Registered handlers against a fake pi: Smart + Render cache On uses 90% on 1M (~943k tokens),
537
+ // while Render cache Off falls back to ~200k tokens. The registrar's byte tracking is exposed
538
+ // through a getter so the self-check can assert the i1 guard never touches it for plain models.
539
+ let trackedOverheadBytes = -1;
540
+
541
+ /** Last observed wire size (messages + overhead) for byte-limited models, or null.
542
+ * Consumed by the footer to show payload pressure against the 1 MB proxy wall. */
543
+ export function wireBytesSnapshot(): { bytes: number; limit: number } | null {
544
+ const ceilings = activeByteCeilings();
545
+ if (!ceilings) return null;
546
+ const state = (globalThis as Record<symbol, AutoCompactState | undefined>)[Symbol.for("pi-arnative.autocompactState")];
547
+ if (!state || state.lastMessagesBytes <= 0) return null;
548
+ const overhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
549
+ return { bytes: state.lastMessagesBytes + overhead, limit: ceilings.shedTriggerBytes };
128
550
  }
129
551
 
130
552
  export default function registerAutoCompact(pi: ExtensionAPI): void {
131
553
  const state = freshAutoCompactState();
554
+ Object.defineProperty(state, "overheadBytes", {
555
+ get(): number {
556
+ return this._overheadBytes;
557
+ },
558
+ set(v: number) {
559
+ this._overheadBytes = v;
560
+ trackedOverheadBytes = v;
561
+ },
562
+ });
563
+ (state as { _overheadBytes?: number })._overheadBytes = 0;
564
+ // Production and self-check both read this snapshot symbol (footer uses wireBytesSnapshot).
565
+ (globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.autocompactState")] = state;
566
+
567
+ const resetByteTracking = (): void => {
568
+ state.lastMessagesBytes = 0;
569
+ state.overheadBytes = 0;
570
+ state.saw413 = false;
571
+ state.compacting = false;
572
+ state.awaitingContextPayload = false;
573
+ };
132
574
 
133
575
  pi.on("session_start", async () => {
134
576
  // Fresh session (or /reload): backoff and attempt state belonged to the previous branch.
135
577
  Object.assign(state, freshAutoCompactState());
136
578
  });
137
579
 
580
+ pi.on("model_select", async () => {
581
+ resetByteTracking();
582
+ });
583
+
584
+ pi.on("turn_end", async (event) => {
585
+ const msg = (event as { message?: { stopReason?: string; errorMessage?: string } } | undefined)?.message;
586
+ if (msg?.stopReason === "error" && isPayloadTooLargeError(msg.errorMessage)) {
587
+ state.saw413 = true;
588
+ }
589
+ });
590
+
591
+ pi.on("context", async (event, ctx) => {
592
+ const ceilings = activeByteCeilings();
593
+ if (!ceilings) return;
594
+ // Skip the full-transcript JSON.stringify entirely for models with no byte wall:
595
+ // measurement is the only cost here, and non-remote sessions pay it every turn.
596
+ if (!state.saw413 && !isByteLimitedModel(ctx?.model)) return;
597
+ const messages = (event as { messages?: MessageLike[] } | undefined)?.messages;
598
+ if (!Array.isArray(messages)) return;
599
+ // JSON serialization includes UTF-8 characters, escapes, and array separators.
600
+ const msgBytes = cachedArrayBytes(messages);
601
+ state.lastMessagesBytes = msgBytes;
602
+ state.awaitingContextPayload = true;
603
+
604
+ const triggerBytes = state.saw413 ? ceilings.shedTriggerAfter413Bytes : ceilings.shedTriggerBytes;
605
+ const targetBytes = state.saw413 ? ceilings.shedTargetAfter413Bytes : ceilings.shedTargetBytes;
606
+ const effectiveOverhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
607
+ if (msgBytes + effectiveOverhead < triggerBytes) return;
608
+
609
+ const targetMsgBytes = Math.max(MIN_MSG_BUDGET_BYTES, targetBytes - effectiveOverhead);
610
+ const shed = shedMessagesForByteLimit(messages, targetMsgBytes, ceilings.mb);
611
+ if (!shed.changed) return;
612
+
613
+ state.lastMessagesBytes = shed.bytes;
614
+ return { messages: shed.messages } as never;
615
+ });
616
+
617
+ pi.on("before_provider_request", async (event) => {
618
+ if (state.inFlight || state.compacting) return;
619
+ if (!state.awaitingContextPayload || state.lastMessagesBytes <= 0) return;
620
+ const payload = (event as { payload?: unknown } | undefined)?.payload;
621
+ const bytes = jsonByteLength(payload);
622
+ if (bytes <= 0) return;
623
+
624
+ if (bytes >= state.lastMessagesBytes) {
625
+ state.overheadBytes = bytes - state.lastMessagesBytes;
626
+ }
627
+ state.awaitingContextPayload = false;
628
+ });
629
+
630
+ pi.on("session_before_compact", async (event, ctx) => {
631
+ state.compacting = true;
632
+ const ceilings = activeByteCeilings();
633
+ if (!ceilings) return;
634
+ if (!state.saw413 && !isByteLimitedModel(ctx?.model)) return;
635
+ const prep = (
636
+ event as {
637
+ preparation?: {
638
+ messagesToSummarize?: MessageLike[];
639
+ turnPrefixMessages?: MessageLike[];
640
+ previousSummary?: string;
641
+ };
642
+ } | undefined
643
+ )?.preparation;
644
+ if (!prep) return;
645
+ const prevBytes = prep.previousSummary ? jsonByteLength(prep.previousSummary) : 0;
646
+ const summaryBudget = Math.max(128 * 1024, ceilings.compactInputBytes - prevBytes);
647
+ trimCompactionInput(prep.messagesToSummarize, summaryBudget);
648
+ trimCompactionInput(prep.turnPrefixMessages, Math.round(ceilings.compactInputBytes / 2));
649
+ });
650
+
138
651
  pi.on("agent_before_settle", async (_event, ctx) => {
139
652
  const usage = typeof ctx.getContextUsage === "function" ? ctx.getContextUsage() : undefined;
140
- const window = usage?.contextWindow;
141
- if (typeof window !== "number" || window <= 0) return;
142
- const threshold = activeAutoCompactThreshold(window);
143
- if (threshold === null) return;
144
- const tokens = usage.tokens ?? null;
145
- if (tokens === null) return;
146
- if (tokens < threshold) {
147
- rearmAfterDip(state, tokens, threshold);
653
+ const window = typeof usage?.contextWindow === "number" && usage.contextWindow > 0 ? usage.contextWindow : 0;
654
+
655
+ const threshold = window > 0 ? activeAutoCompactThreshold(window) : null;
656
+ const tokens = usage?.tokens ?? null;
657
+ if (threshold === null || tokens === null) return;
658
+
659
+ rearmAfterDip(state, tokens, threshold);
660
+
661
+ if (autoCompactDecision(state, tokens, threshold) !== "compact") {
148
662
  return;
149
663
  }
150
- if (autoCompactDecision(state, tokens, threshold) !== "compact") return;
151
664
  if (typeof ctx.compact !== "function") return; // older host without the API
665
+
152
666
  state.inFlight = true;
153
667
  state.attemptSettled = false;
154
668
  state.lastAttemptTokens = tokens;
@@ -159,16 +673,21 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
159
673
  pi.on("session_compact", async () => {
160
674
  // Also fires for pi's own compactions; harmless — the flags only matter after a trigger.
161
675
  state.inFlight = false;
676
+ state.compacting = false;
162
677
  state.attemptSettled = true;
678
+ state.lastMessagesBytes = 0;
163
679
  });
164
680
 
165
681
  pi.on("session_compact_failed", async () => {
682
+ state.compacting = false;
166
683
  if (!state.inFlight) return;
167
684
  // A failed (or user-aborted) compaction must not retry-loop at the same usage:
168
685
  // wait until usage outgrows the attempt by the growth margin.
169
686
  state.inFlight = false;
170
687
  state.attemptSettled = true;
171
- state.blockedUntilTokens = (state.lastAttemptTokens ?? 0) + growthMargin(state.lastAttemptTokens ?? 200000);
688
+ if (state.lastAttemptTokens !== null) {
689
+ state.blockedUntilTokens = state.lastAttemptTokens + growthMargin(state.lastAttemptTokens);
690
+ }
172
691
  });
173
692
  }
174
693
 
@@ -178,6 +697,22 @@ if (isMain(import.meta.url)) {
178
697
  const fixture = mkdtempSync(join(tmpdir(), "arnative-autocompact-"));
179
698
  process.env.PI_CODING_AGENT_DIR = fixture;
180
699
  delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
700
+ delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
701
+
702
+ // Payload limit parsing, persistence, and Off mode.
703
+ assert(parsePayloadLimit("off") === "Off", "parses off case-insensitively");
704
+ assert(parsePayloadLimit("11") === "11 MB" && parsePayloadLimit("11mb") === "11 MB", "normalizes MB unit");
705
+ assert(parsePayloadLimit(16) === "16 MB", "accepts numeric MB");
706
+ assert(parsePayloadLimit("0") === undefined && parsePayloadLimit("2000") === undefined && parsePayloadLimit("abc") === undefined, "rejects out-of-range or invalid payload limits");
707
+ assert(savedPayloadLimit() === "1 MB", "stored payload limit defaults to 1 MB");
708
+ setPayloadLimit("11 MB");
709
+ assert(activePayloadLimit() === "11 MB" && savedPayloadLimit() === "11 MB", "custom payload limit applies live and persists");
710
+ assert(activeByteCeilings()!.shedTriggerBytes === Math.round(900 * 1024 * 11), "custom MB scales shed trigger");
711
+ setPayloadLimit("Off");
712
+ assert(activeByteCeilings() === null, "Off disables byte ceilings");
713
+ delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
714
+ saveChoice(PAYLOAD_LIMIT_KEY, "1 MB");
715
+ resetPresetCache();
181
716
 
182
717
  // Choice parsing and persistence.
183
718
  assert(activeAutoCompact() === "Off", "the default is off");
@@ -186,21 +721,36 @@ if (isMain(import.meta.url)) {
186
721
  assert(activeAutoCompactThreshold(131072) === 200000, "a manual budget ignores the window");
187
722
  assert(loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES) === "200k", "the choice survives a restart (read from disk)");
188
723
 
189
- // Smart's tier table: the field examples land where they were asked to.
724
+ // Smart's tier table: scales to 90% with Render cache On, and falls back to ~200k tiers when Off.
725
+ setRenderCache("On");
190
726
  assert(smartPercent(131072) === null, "128k defers to pi core (the 100% tier)");
191
727
  assert(smartPercent(196607) === null, "just under the 192k tier edge still defers");
192
- assert(smartPercent(196608) === 80, "the 192k tier edge takes 80%");
193
- assert(smartPercent(262144) === 80, "256k takes 80%");
194
- assert(smartPercent(524288) === 40, "512k takes 40%");
195
- assert(smartPercent(1048576) === 20, "1M takes 20%");
728
+ assert(smartPercent(196608) === 90, "the 192k tier edge takes 90% when render cache is On");
729
+ assert(smartPercent(262144) === 90, "256k takes 90% when render cache is On");
730
+ assert(smartPercent(524288) === 90, "512k takes 90% when render cache is On");
731
+ assert(smartPercent(1048576) === 90, "1M takes 90% when render cache is On");
732
+ assert(smartPercent(1048576, false) === 20, "1M falls back to 20% when render cache is Off");
733
+ assert(smartPercent(524288, false) === 40, "512k falls back to 40% when render cache is Off");
734
+ assert(smartPercent(262144, false) === 80, "256k falls back to 80% when render cache is Off");
196
735
  setAutoCompact("Smart");
197
- assert(activeAutoCompactThreshold(1048576) === 209715, "Smart on 1M triggers at ~200k tokens");
198
- assert(activeAutoCompactThreshold(262144) === 209715, "Smart on 256k triggers at ~205k tokens");
736
+ assert(activeAutoCompactThreshold(1048576) === 943718, "Smart + Render cache On triggers at 90% of 1M");
737
+ assert(activeAutoCompactThreshold(262144) === 235930, "Smart + Render cache On triggers at 90% of 256k");
199
738
  assert(activeAutoCompactThreshold(131072) === null, "Smart on 128k defers to pi core");
739
+ setRenderCache("Off");
740
+ assert(activeAutoCompactThreshold(1048576) === 209715, "Smart + Render cache Off falls back to ~200k on 1M");
741
+ assert(activeAutoCompactThreshold(262144) === 209715, "Smart + Render cache Off falls back to ~205k on 256k");
742
+ setRenderCache("On");
200
743
  setAutoCompact("Off");
201
744
  assert(activeAutoCompactThreshold(1048576) === null, "switching back to off disables the trigger");
202
745
 
203
- // Decision table.
746
+ // Remote / 413 detection helpers.
747
+ assert(isByteLimitedModel({ id: "remote/agy-cli/gemini-4-hydrogen" }), "remote/* is byte-limited");
748
+ assert(isByteLimitedModel({ id: "remote-magpie/auto/glm-5.3" }), "remote-magpie/* is byte-limited");
749
+ assert(!isByteLimitedModel({ id: "auto/zaicoding_glm-5.3" }), "non-remote model is not byte-limited by default");
750
+ assert(isPayloadTooLargeError('413 {"error":{"type":"request_too_large"}}'), "detects HTTP 413 request_too_large");
751
+ assert(!isPayloadTooLargeError("429 rate limit"), "ignores non-413 errors");
752
+
753
+ // Decision table (tokens only — byte protection stays decoupled from ctx.compact).
204
754
  const s = freshAutoCompactState();
205
755
  assert(autoCompactDecision(s, null, 200000) === "wait", "no usage estimate: wait");
206
756
  assert(autoCompactDecision(s, 199999, 200000) === "wait", "below the threshold: wait");
@@ -226,12 +776,69 @@ if (isMain(import.meta.url)) {
226
776
  rearmAfterDip(r, 189000, 200000);
227
777
  assert(r.lastAttemptTokens === null && r.attemptSettled === false && r.blockedUntilTokens === 0, "a real drop forgets the attempt and re-arms");
228
778
 
229
- // Registered handlers against a fake pi, driven like a Smart session on a 1M model.
779
+ // Mid-run byte shedding keeps recent tail + latest image + latest thinking + tool pairing intact.
780
+ const bigText = "x".repeat(80_000);
781
+ const sampleMsgs: MessageLike[] = [
782
+ { role: "user", content: [{ type: "text", text: "goal" }, { type: "image", data: "A".repeat(40_000) }] },
783
+ {
784
+ role: "assistant",
785
+ content: [
786
+ { type: "thinking", thinking: "T".repeat(30_000), thinkingSignature: "sig123" } as ContentBlockLike,
787
+ { type: "toolCall", arguments: { path: "a.ts" } },
788
+ ],
789
+ },
790
+ { role: "toolResult", content: [{ type: "text", text: bigText }] },
791
+ { role: "assistant", content: [{ type: "toolCall", arguments: { path: "b.ts" } }] },
792
+ { role: "toolResult", content: [{ type: "text", text: bigText }] },
793
+ { role: "user", content: [{ type: "text", text: "latest" }, { type: "image", data: "B".repeat(20_000) }] },
794
+ {
795
+ role: "assistant",
796
+ content: [
797
+ { type: "thinking", thinking: "keep latest thinking", thinkingSignature: "sigLatest" } as ContentBlockLike,
798
+ { type: "text", text: "working" },
799
+ ],
800
+ },
801
+ ];
802
+ const shed = shedMessagesForByteLimit(sampleMsgs, 90_000);
803
+ assert(shed.changed && shed.bytes <= 90_000, "shedding brings oversized messages under budget");
804
+ assert((shed.messages[0].content as ContentBlockLike[])[1].type === "text", "earlier image is omitted");
805
+ assert(
806
+ !(shed.messages[1].content as ContentBlockLike[]).some((b) => b.type === "thinking"),
807
+ "earlier thinking and signature are dropped before latest user turn",
808
+ );
809
+ assert((shed.messages[5].content as ContentBlockLike[])[1].type === "image", "latest image is kept");
810
+ assert(
811
+ (shed.messages[6].content as ContentBlockLike[]).some((b) => b.type === "thinking"),
812
+ "latest turn thinking is kept",
813
+ );
814
+ assert((shed.messages[2].content as ContentBlockLike[])[0].text === TRIMMED_TOOL_STUB, "old tool result trimmed");
815
+ assert((sampleMsgs[2].content as ContentBlockLike[])[0].text === bigText, "shedding never mutates original messages");
816
+
817
+ // Compaction input trimming shrinks huge toolCall args without mutating originals.
818
+ const hugeWriteArgs = "y".repeat(20_000);
819
+ const compactInput: MessageLike[] = [
820
+ { role: "assistant", content: [{ type: "toolCall", arguments: { path: "big.ts", content: hugeWriteArgs } }] },
821
+ ];
822
+ assert(trimCompactionInput(compactInput, 5_000), "trimCompactionInput shrinks oversized toolCall arguments");
823
+ assert((compactInput[0].content as ContentBlockLike[])[0].arguments!.content !== hugeWriteArgs, "cloned argument was truncated");
824
+
825
+ // Emergency tail trim: a single massive toolResult in the newest turn still sheds below target.
826
+ const tailOnlyHuge: MessageLike[] = [
827
+ { role: "user", content: [{ type: "text", text: "run tool" }] },
828
+ { role: "toolResult", content: [{ type: "text", text: "y".repeat(SHED_TRIGGER_BYTES + 20_000) }] },
829
+ ];
830
+ const tailShed = shedMessagesForByteLimit(tailOnlyHuge, 100_000);
831
+ assert(tailShed.changed && tailShed.bytes <= 100_000, "emergency tail trim bounds even a single giant newest message");
832
+
833
+ // Registered handlers against a fake pi: Smart + Render cache On uses 90% on 1M (~943k tokens),
834
+ // while Render cache Off falls back to ~200k tokens.
835
+ setRenderCache("Off");
230
836
  setAutoCompact("Smart");
231
837
  const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
232
838
  registerAutoCompact({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
233
839
  const compactCalls: number[] = [];
234
- const ctxOf = (tokens: number | null, contextWindow = 1_048_576) => ({
840
+ const ctxOf = (tokens: number | null, contextWindow = 1_048_576, model?: { id: string }) => ({
841
+ model,
235
842
  getContextUsage: () => ({ tokens, contextWindow, percent: tokens === null ? null : (tokens / contextWindow) * 100 }),
236
843
  compact: () => compactCalls.push(tokens ?? -1),
237
844
  });
@@ -271,24 +878,125 @@ if (isMain(import.meta.url)) {
271
878
  await handlers.agent_before_settle!({}, ctxOf(210500));
272
879
  assert(compactCalls.length === 6, "a fresh session clears the backoff");
273
880
 
881
+ // Smart + Render cache On: scales 1M window to 90% (~943k), and remote 1 MB payloads shed silently
882
+ // without forcing premature session compaction at low token counts (e.g. 49k–110k).
883
+ setRenderCache("On");
884
+ await handlers.session_start!({}, undefined);
885
+ const remoteCtx = ctxOf(49836, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" });
886
+ const hugeRunMsgs: MessageLike[] = [
887
+ { role: "user", content: [{ type: "text", text: "start" }] },
888
+ { role: "assistant", content: [{ type: "toolCall", arguments: { path: "x" } }] },
889
+ { role: "toolResult", content: [{ type: "text", text: "z".repeat(SHED_TRIGGER_BYTES + 10_000) }] },
890
+ { role: "user", content: [{ type: "text", text: "continue" }] },
891
+ { role: "assistant", content: [{ type: "text", text: "ok" }] },
892
+ ];
893
+ const ctxResult = (await handlers.context!({ messages: hugeRunMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
894
+ assert(
895
+ Array.isArray(ctxResult?.messages) &&
896
+ jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= SHED_TARGET_BYTES,
897
+ "context hook sheds payload with hysteresis down to the target ceiling",
898
+ );
899
+ await handlers.before_provider_request!({ payload: { blob: "p".repeat(SHED_TRIGGER_BYTES + 20_000) } }, remoteCtx);
900
+ await handlers.agent_before_settle!({}, remoteCtx);
901
+ assert(compactCalls.length === 6, "remote byte shedding does not force premature compaction at 49k tokens");
902
+
903
+ // Only crossing 90% of 1M context triggers Smart compaction when Render cache is On.
904
+ await handlers.agent_before_settle!({}, ctxOf(900000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
905
+ assert(compactCalls.length === 6, "900k tokens is still under 90% of 1M");
906
+ await handlers.agent_before_settle!({}, ctxOf(945000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
907
+ assert(compactCalls.length === 7 && compactCalls[6] === 945000, "945k tokens hits 90% Smart threshold and compacts");
908
+ await handlers.session_compact!({}, undefined);
909
+
910
+ // Compaction input trimming shrinks split-turn prefixes cleanly without triggering follow-ups.
911
+ const splitTurnPrefix: MessageLike[] = [
912
+ { role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(COMPACT_INPUT_BYTES) } }] },
913
+ ];
914
+ await handlers.session_before_compact!({ preparation: { turnPrefixMessages: splitTurnPrefix } }, remoteCtx);
915
+ assert(jsonByteLength(splitTurnPrefix) < COMPACT_INPUT_BYTES, "session_before_compact trims split-turn prefix messages too");
916
+
917
+ // Remote byte silent shedding stays active even when Auto-compact is Off, and never triggers ctx.compact().
918
+ setAutoCompact("Off");
919
+ await handlers.session_start!({}, undefined);
920
+ const manyMsgs: MessageLike[] = [];
921
+ for (let i = 0; i < 900; i++) {
922
+ manyMsgs.push(
923
+ { role: "user", content: [{ type: "text", text: `turn ${i}: ` + "u".repeat(350) }] },
924
+ { role: "assistant", content: [{ type: "toolCall", arguments: { cmd: `echo ${i}` } }] },
925
+ { role: "toolResult", content: [{ type: "text", text: "r".repeat(600) }] },
926
+ { role: "assistant", content: [{ type: "text", text: "a".repeat(350) }] },
927
+ );
928
+ }
929
+ assert(jsonByteLength(manyMsgs) > 1_048_576, "fixture spans thousands of messages and over a megabyte");
930
+ const shedMany = (await handlers.context!({ messages: manyMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
931
+ // A fixture sized for the 1 MB default says nothing once the wall scales: at 16 MB
932
+ // the same array is far under the trigger and the hook rightly stays quiet.
933
+ // Size it against the ceiling in force, or skip when scaling makes that impractical.
934
+ const overTrigger = jsonByteLength(manyMsgs) > SHED_TRIGGER_BYTES;
935
+ if (overTrigger) {
936
+ assert(
937
+ Array.isArray(shedMany?.messages) &&
938
+ jsonByteLength(shedMany.messages) <= SHED_TARGET_BYTES &&
939
+ shedMany.messages[0]?.role === "user",
940
+ "many-message session sheds below the ceiling even with Auto-compact Off",
941
+ );
942
+ } else {
943
+ assert(shedMany === undefined, "a fixture under the scaled trigger is left untouched");
944
+ }
945
+ const compactMany = manyMsgs.slice();
946
+ await handlers.session_before_compact!({ preparation: { messagesToSummarize: compactMany } }, remoteCtx);
947
+ assert(
948
+ jsonByteLength(compactMany) <= COMPACT_INPUT_BYTES && compactMany[0]?.role !== "toolResult",
949
+ "many-message compaction input trims below 720 KB without orphaned toolResult",
950
+ );
951
+ await handlers.agent_before_settle!({}, ctxOf(950000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
952
+ assert(compactCalls.length === 7, "Auto-compact Off never calls ctx.compact() even at 950k tokens on remote/*");
953
+
954
+ // Non-remote model that hits HTTP 413 tightens silent shedding without forcing compaction.
955
+ const nonRemoteCtx = ctxOf(50000, 1_048_576, { id: "custom/model" });
956
+ await handlers.turn_end!({ message: { stopReason: "error", errorMessage: "413 request_too_large" } }, nonRemoteCtx);
957
+ const after413 = (await handlers.context!({ messages: hugeRunMsgs }, nonRemoteCtx)) as { messages?: MessageLike[] } | undefined;
958
+ assert(
959
+ Array.isArray(after413?.messages) &&
960
+ jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= INITIAL_CEILINGS.shedTargetAfter413Bytes,
961
+ "saw413 activates tighter silent shedding on any model",
962
+ );
963
+ // Payload limit Off skips shedding and clears wireBytesSnapshot even for remote models.
964
+ setPayloadLimit("Off");
965
+ const offResult = await handlers.context!({ messages: hugeRunMsgs }, remoteCtx);
966
+ assert(offResult === undefined && wireBytesSnapshot() === null, "Off disables silent shedding and wireBytesSnapshot");
967
+ delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
968
+ setAutoCompact("Smart");
969
+
970
+ // i1 guard: models with no byte wall never measure payload bytes at all.
971
+ await handlers.session_start!({}, undefined);
972
+ const plainCtx = ctxOf(210000, 1_048_576, { id: "auto/zaicoding_glm-5.3" });
973
+ const plainMsgs: MessageLike[] = [{ role: "user", content: [{ type: "text", text: "plain" }] }];
974
+ const plainResult = (await handlers.context!({ messages: plainMsgs }, plainCtx)) as { messages?: MessageLike[] } | undefined;
975
+ assert(plainResult === undefined, "non-remote context hook skips byte measurement entirely");
976
+ const overheadBefore = trackedOverheadBytes;
977
+ const plainReq = await handlers.before_provider_request!({ payload: { blob: "p".repeat(4 * 1024 * 1024) } }, plainCtx);
978
+ assert(plainReq === undefined && trackedOverheadBytes === overheadBefore, "non-remote before_provider_request skips the 4 MB stringify");
979
+
274
980
  // The 128k case from the field: Smart defers the whole window to pi's own
275
981
  // compaction — no percent, however close to full, ever fires ours.
276
982
  await handlers.session_start!({}, undefined);
277
983
  await handlers.agent_before_settle!({}, ctxOf(130000, 131072));
278
- assert(compactCalls.length === 6, "a 128k window under Smart never triggers: pi core stays in charge");
984
+ assert(compactCalls.length === 7, "a 128k window under Smart never triggers: pi core stays in charge");
279
985
 
280
986
  // Older hosts: missing ctx APIs must degrade to a no-op, not throw.
281
987
  await handlers.agent_before_settle!({}, { getContextUsage: () => undefined });
282
- assert(compactCalls.length === 6, "no usage estimate: no trigger");
988
+ assert(compactCalls.length === 7, "no usage estimate: no trigger");
283
989
  // Reset inFlight first, so the missing compact() — not a pending compaction — is what stops it.
284
990
  await handlers.session_start!({}, undefined);
285
- await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens: 400000, contextWindow: 1_048_576, percent: 40 }) });
286
- assert(compactCalls.length === 6, "no ctx.compact on the host: no trigger");
991
+ await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens: 950000, contextWindow: 1_048_576, percent: 90.6 }) });
992
+ assert(compactCalls.length === 7, "no ctx.compact on the host: no trigger");
287
993
 
288
994
  // Restore: the next module load starts from the real agent dir and the stored default.
289
995
  rmSync(fixture, { recursive: true, force: true });
290
996
  delete process.env.PI_CODING_AGENT_DIR;
291
997
  delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
998
+ delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
999
+ delete (globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.renderCache")];
292
1000
  resetPresetCache();
293
1001
  console.log("autocompact.ts self-check OK");
294
1002
  }