@bismawy/pi-arnative 0.16.1 → 0.18.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.
Files changed (61) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +113 -161
  18. package/{extensions → lib/features}/timestamps.ts +18 -94
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/themes/arnative-blossom.json +0 -0
  40. package/themes/arnative-crimson.json +0 -0
  41. package/themes/arnative-cyberpunk.json +0 -0
  42. package/themes/arnative-dracula.json +0 -0
  43. package/themes/arnative-earthy.json +0 -0
  44. package/themes/arnative-garden.json +0 -0
  45. package/themes/arnative-gruvbox.json +0 -0
  46. package/themes/arnative-lemonade.json +0 -0
  47. package/themes/arnative-magical.json +0 -0
  48. package/themes/arnative-matrix.json +0 -0
  49. package/themes/arnative-neutral.json +0 -0
  50. package/themes/arnative-nord.json +0 -0
  51. package/themes/arnative-zinc.json +0 -0
  52. package/themes/arnative.json +0 -0
  53. package/CHANGELOG.md +0 -683
  54. package/extensions/animations.ts +0 -242
  55. package/extensions/footer.ts +0 -2617
  56. package/extensions/tools.ts +0 -2231
  57. package/extensions/ui-render-tweaks.ts +0 -1005
  58. package/extensions/usage-export.ts +0 -283
  59. package/extensions/usage.ts +0 -1406
  60. package/lib/check.ts +0 -21
  61. package/themes/gen-themes.mjs +0 -715
@@ -17,24 +17,21 @@
17
17
  * so summarization stays under 1 MB when token compaction eventually runs.
18
18
  */
19
19
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20
- import { mkdtempSync, rmSync } from "node:fs";
21
- import { tmpdir } from "node:os";
22
- import { join } from "node:path";
23
- import { assert, isMain } from "../lib/check.ts";
24
- import { PAYLOAD_LIMIT_KEY, choiceSetting, loadChoice, loadSetting, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
25
- import { activeRenderCache, setRenderCache } from "./render-cache.ts";
20
+ import { PAYLOAD_LIMIT_KEY, choiceSetting, loadSetting, saveChoice } from "../preset-store.ts";
21
+ import { getRuntime } from "../runtime.ts";
22
+ import { activeRenderCache } from "./render-cache.ts";
26
23
 
27
24
  /** Stored exactly as the picker shows them; `Off` disables the trigger entirely. */
28
25
  export const AUTO_COMPACT_CHOICES = ["Off", "Smart", "100k", "150k", "200k", "300k", "400k"] as const;
29
26
  export type AutoCompactChoice = (typeof AUTO_COMPACT_CHOICES)[number];
30
- export const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
27
+ const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
31
28
  export const AUTO_COMPACT_KEY = "autoCompact";
32
29
 
33
30
  /** Proxy payload limit presets shown in `/arnative` → Payload limit. */
34
31
  export const PAYLOAD_LIMIT_PRESETS = ["Off", "1 MB", "4 MB", "8 MB", "16 MB", "32 MB"] as const;
35
32
  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;
33
+ const DEFAULT_PAYLOAD_LIMIT: PayloadLimitPreset = "1 MB";
34
+ const PAYLOAD_LIMIT_MB_RANGE = { min: 1, max: 1024 } as const;
38
35
  export const PAYLOAD_LIMIT_CONFIG_KEY = Symbol.for("pi-arnative.payloadLimit");
39
36
 
40
37
  export interface ByteCeilings {
@@ -134,14 +131,14 @@ const DEFAULT_OVERHEAD_BYTES = 64 * 1024;
134
131
  const MIN_MSG_BUDGET_BYTES = 64 * 1024;
135
132
  const TRIMMED_TOOL_STUB = "[earlier output omitted; full output in session]";
136
133
 
137
- interface ContentBlockLike {
134
+ export interface ContentBlockLike {
138
135
  type?: string;
139
136
  text?: string;
140
137
  thinking?: string;
141
138
  arguments?: Record<string, unknown>;
142
139
  }
143
140
 
144
- interface MessageLike {
141
+ export interface MessageLike {
145
142
  role?: string;
146
143
  content?: unknown;
147
144
  }
@@ -228,7 +225,7 @@ export function freshAutoCompactState(): AutoCompactState {
228
225
 
229
226
  /** How much usage must outgrow a previous attempt before it counts as real growth
230
227
  * (5% of the threshold, at least 5k tokens). */
231
- export function growthMargin(thresholdTokens: number): number {
228
+ function growthMargin(thresholdTokens: number): number {
232
229
  return Math.max(5000, Math.round(thresholdTokens * 0.05));
233
230
  }
234
231
 
@@ -342,7 +339,7 @@ export function shedMessagesForByteLimit<T extends MessageLike>(
342
339
  ): { messages: T[]; bytes: number; changed: boolean } {
343
340
  const trimLabel = trimLabelForMb(limitMb);
344
341
  const sizes = messages.map((m) => jsonByteLength(m));
345
- let totalBytes = jsonByteLength(messages);
342
+ let totalBytes = 2 + sizes.reduce((a, b) => a + b, 0) + Math.max(0, sizes.length - 1);
346
343
  if (totalBytes <= targetMsgBytes || messages.length === 0) {
347
344
  return { messages: messages as T[], bytes: totalBytes, changed: false };
348
345
  }
@@ -536,7 +533,7 @@ let trackedOverheadBytes = -1;
536
533
  export function wireBytesSnapshot(): { bytes: number; limit: number } | null {
537
534
  const ceilings = activeByteCeilings();
538
535
  if (!ceilings) return null;
539
- const state = (globalThis as Record<symbol, AutoCompactState | undefined>)[Symbol.for("pi-arnative.autocompactState")];
536
+ const state = getRuntime().autocompactState as AutoCompactState | null;
540
537
  if (!state || state.lastMessagesBytes <= 0) return null;
541
538
  const overhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
542
539
  return { bytes: state.lastMessagesBytes + overhead, limit: ceilings.shedTriggerBytes };
@@ -554,8 +551,8 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
554
551
  },
555
552
  });
556
553
  (state as { _overheadBytes?: number })._overheadBytes = 0;
557
- // Production and self-check both read this snapshot symbol (footer uses wireBytesSnapshot).
558
- (globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.autocompactState")] = state;
554
+ // Production and self-check both read this snapshot via RuntimeState (footer uses wireBytesSnapshot).
555
+ getRuntime().autocompactState = state;
559
556
 
560
557
  const resetByteTracking = (): void => {
561
558
  state.lastMessagesBytes = 0;
@@ -610,6 +607,12 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
610
607
  pi.on("before_provider_request", async (event) => {
611
608
  if (state.inFlight || state.compacting) return;
612
609
  if (!state.awaitingContextPayload || state.lastMessagesBytes <= 0) return;
610
+ // Overhead (system prompt + tool schemas) is stable within a session/model;
611
+ // avoid re-stringifying multi-MB payloads on every turn once measured.
612
+ if (state.overheadBytes > 0 && !state.saw413) {
613
+ state.awaitingContextPayload = false;
614
+ return;
615
+ }
613
616
  const payload = (event as { payload?: unknown } | undefined)?.payload;
614
617
  const bytes = jsonByteLength(payload);
615
618
  if (bytes <= 0) return;
@@ -684,314 +687,14 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
684
687
  });
685
688
  }
686
689
 
687
- // Self-check: `node extensions/autocompact.ts`
688
- if (isMain(import.meta.url)) {
689
- // The real agent dir must not decide pass/fail, and the test must not touch it.
690
- const fixture = mkdtempSync(join(tmpdir(), "arnative-autocompact-"));
691
- process.env.PI_CODING_AGENT_DIR = fixture;
692
- delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
693
- delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
694
- resetPresetCache();
695
-
696
- // Payload limit parsing, persistence, and Off mode.
697
- assert(parsePayloadLimit("off") === "Off", "parses off case-insensitively");
698
- assert(parsePayloadLimit("11") === "11 MB" && parsePayloadLimit("11mb") === "11 MB", "normalizes MB unit");
699
- assert(parsePayloadLimit(16) === "16 MB", "accepts numeric MB");
700
- assert(parsePayloadLimit("0") === undefined && parsePayloadLimit("2000") === undefined && parsePayloadLimit("abc") === undefined, "rejects out-of-range or invalid payload limits");
701
- assert(savedPayloadLimit() === "1 MB", "stored payload limit defaults to 1 MB");
702
- setPayloadLimit("11 MB");
703
- assert(activePayloadLimit() === "11 MB" && savedPayloadLimit() === "11 MB", "custom payload limit applies live and persists");
704
- assert(activeByteCeilings()!.shedTriggerBytes === Math.round(900 * 1024 * 11), "custom MB scales shed trigger");
705
- setPayloadLimit("Off");
706
- assert(activeByteCeilings() === null, "Off disables byte ceilings");
707
- delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
708
- saveChoice(PAYLOAD_LIMIT_KEY, "1 MB");
709
- resetPresetCache();
710
- const liveCeilings = activeByteCeilings()!;
711
-
712
- // Choice parsing and persistence.
713
- assert(activeAutoCompact() === "Off", "the default is off");
714
- assert(activeAutoCompactThreshold(1_048_576) === null, "off reads as no threshold");
715
- setAutoCompact("200k");
716
- assert(activeAutoCompactThreshold(131072) === 200000, "a manual budget ignores the window");
717
- assert(loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES) === "200k", "the choice survives a restart (read from disk)");
718
-
719
- // Smart's tier table: scales to 90% with Render cache On, and falls back to ~200k tiers when Off.
720
- setRenderCache("On");
721
- assert(smartPercent(131072) === null, "128k defers to pi core (the 100% tier)");
722
- assert(smartPercent(196607) === null, "just under the 192k tier edge still defers");
723
- assert(smartPercent(196608) === 90, "the 192k tier edge takes 90% when render cache is On");
724
- assert(smartPercent(262144) === 90, "256k takes 90% when render cache is On");
725
- assert(smartPercent(524288) === 90, "512k takes 90% when render cache is On");
726
- assert(smartPercent(1048576) === 90, "1M takes 90% when render cache is On");
727
- assert(smartPercent(1048576, false) === 20, "1M falls back to 20% when render cache is Off");
728
- assert(smartPercent(524288, false) === 40, "512k falls back to 40% when render cache is Off");
729
- assert(smartPercent(262144, false) === 80, "256k falls back to 80% when render cache is Off");
730
- setAutoCompact("Smart");
731
- assert(activeAutoCompactThreshold(1048576) === 943718, "Smart + Render cache On triggers at 90% of 1M");
732
- assert(activeAutoCompactThreshold(262144) === 235930, "Smart + Render cache On triggers at 90% of 256k");
733
- assert(activeAutoCompactThreshold(131072) === null, "Smart on 128k defers to pi core");
734
- setRenderCache("Off");
735
- assert(activeAutoCompactThreshold(1048576) === 209715, "Smart + Render cache Off falls back to ~200k on 1M");
736
- assert(activeAutoCompactThreshold(262144) === 209715, "Smart + Render cache Off falls back to ~205k on 256k");
737
- setRenderCache("On");
738
- setAutoCompact("Off");
739
- assert(activeAutoCompactThreshold(1048576) === null, "switching back to off disables the trigger");
740
-
741
- // Remote / 413 detection helpers.
742
- assert(isByteLimitedModel({ id: "remote/agy-cli/gemini-4-hydrogen" }), "remote/* is byte-limited");
743
- assert(isByteLimitedModel({ id: "remote-magpie/auto/glm-5.3" }), "remote-magpie/* is byte-limited");
744
- assert(!isByteLimitedModel({ id: "auto/zaicoding_glm-5.3" }), "non-remote model is not byte-limited by default");
745
- assert(isPayloadTooLargeError('413 {"error":{"type":"request_too_large"}}'), "detects HTTP 413 request_too_large");
746
- assert(!isPayloadTooLargeError("429 rate limit"), "ignores non-413 errors");
747
-
748
- // Decision table (tokens only — byte protection stays decoupled from ctx.compact).
749
- const s = freshAutoCompactState();
750
- assert(autoCompactDecision(s, null, 200000) === "wait", "no usage estimate: wait");
751
- assert(autoCompactDecision(s, 199999, 200000) === "wait", "below the threshold: wait");
752
- assert(autoCompactDecision(s, 200000, 200000) === "compact", "at the threshold with fresh state: compact");
753
- s.inFlight = true;
754
- assert(autoCompactDecision(s, 250000, 200000) === "wait", "a compaction is still running: wait");
755
- s.inFlight = false;
756
- s.blockedUntilTokens = 260000;
757
- assert(autoCompactDecision(s, 250000, 200000) === "wait", "below the failure backoff: wait");
758
- s.blockedUntilTokens = 0;
759
- s.attemptSettled = true;
760
- s.lastAttemptTokens = 240000;
761
- assert(autoCompactDecision(s, 245000, 200000) === "wait", "a settled attempt that freed too little waits for the growth margin");
762
- assert(autoCompactDecision(s, 250500, 200000) === "compact", "usage outgrew the settled attempt: compact again");
763
-
764
- // Rearm after a dip: shallow keeps the attempt memory, deep forgets it.
765
- const r = freshAutoCompactState();
766
- r.lastAttemptTokens = 200000;
767
- r.attemptSettled = true;
768
- r.blockedUntilTokens = 200001;
769
- rearmAfterDip(r, 195000, 200000);
770
- assert(r.lastAttemptTokens === 200000, "a shallow dip keeps the attempt memory");
771
- rearmAfterDip(r, 189000, 200000);
772
- assert(r.lastAttemptTokens === null && r.attemptSettled === false && r.blockedUntilTokens === 0, "a real drop forgets the attempt and re-arms");
773
-
774
- // Mid-run byte shedding keeps recent tail + latest image + latest thinking + tool pairing intact.
775
- const bigText = "x".repeat(80_000);
776
- const sampleMsgs: MessageLike[] = [
777
- { role: "user", content: [{ type: "text", text: "goal" }, { type: "image", data: "A".repeat(40_000) }] },
778
- {
779
- role: "assistant",
780
- content: [
781
- { type: "thinking", thinking: "T".repeat(30_000), thinkingSignature: "sig123" } as ContentBlockLike,
782
- { type: "toolCall", arguments: { path: "a.ts" } },
783
- ],
784
- },
785
- { role: "toolResult", content: [{ type: "text", text: bigText }] },
786
- { role: "assistant", content: [{ type: "toolCall", arguments: { path: "b.ts" } }] },
787
- { role: "toolResult", content: [{ type: "text", text: bigText }] },
788
- { role: "user", content: [{ type: "text", text: "latest" }, { type: "image", data: "B".repeat(20_000) }] },
789
- {
790
- role: "assistant",
791
- content: [
792
- { type: "thinking", thinking: "keep latest thinking", thinkingSignature: "sigLatest" } as ContentBlockLike,
793
- { type: "text", text: "working" },
794
- ],
795
- },
796
- ];
797
- const shed = shedMessagesForByteLimit(sampleMsgs, 90_000);
798
- assert(shed.changed && shed.bytes <= 90_000, "shedding brings oversized messages under budget");
799
- assert((shed.messages[0].content as ContentBlockLike[])[1].type === "text", "earlier image is omitted");
800
- assert(
801
- !(shed.messages[1].content as ContentBlockLike[]).some((b) => b.type === "thinking"),
802
- "earlier thinking and signature are dropped before latest user turn",
803
- );
804
- assert((shed.messages[5].content as ContentBlockLike[])[1].type === "image", "latest image is kept");
805
- assert(
806
- (shed.messages[6].content as ContentBlockLike[]).some((b) => b.type === "thinking"),
807
- "latest turn thinking is kept",
808
- );
809
- assert((shed.messages[2].content as ContentBlockLike[])[0].text === TRIMMED_TOOL_STUB, "old tool result trimmed");
810
- assert((sampleMsgs[2].content as ContentBlockLike[])[0].text === bigText, "shedding never mutates original messages");
811
-
812
- // Compaction input trimming shrinks huge toolCall args without mutating originals.
813
- const hugeWriteArgs = "y".repeat(20_000);
814
- const compactInput: MessageLike[] = [
815
- { role: "assistant", content: [{ type: "toolCall", arguments: { path: "big.ts", content: hugeWriteArgs } }] },
816
- ];
817
- assert(trimCompactionInput(compactInput, 5_000), "trimCompactionInput shrinks oversized toolCall arguments");
818
- assert((compactInput[0].content as ContentBlockLike[])[0].arguments!.content !== hugeWriteArgs, "cloned argument was truncated");
819
-
820
- // Emergency tail trim: a single massive toolResult in the newest turn still sheds below target.
821
- const tailOnlyHuge: MessageLike[] = [
822
- { role: "user", content: [{ type: "text", text: "run tool" }] },
823
- { role: "toolResult", content: [{ type: "text", text: "y".repeat(liveCeilings.shedTriggerBytes + 20_000) }] },
824
- ];
825
- const tailShed = shedMessagesForByteLimit(tailOnlyHuge, 100_000);
826
- assert(tailShed.changed && tailShed.bytes <= 100_000, "emergency tail trim bounds even a single giant newest message");
827
-
828
- // Registered handlers against a fake pi: Smart + Render cache On uses 90% on 1M (~943k tokens),
829
- // while Render cache Off falls back to ~200k tokens.
830
- setRenderCache("Off");
831
- setAutoCompact("Smart");
832
- const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
833
- registerAutoCompact({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
834
- const compactCalls: number[] = [];
835
- const ctxOf = (tokens: number | null, contextWindow = 1_048_576, model?: { id: string }) => ({
836
- model,
837
- getContextUsage: () => ({ tokens, contextWindow, percent: tokens === null ? null : (tokens / contextWindow) * 100 }),
838
- compact: () => compactCalls.push(tokens ?? -1),
839
- });
840
-
841
- await handlers.session_start!({}, undefined);
842
- await handlers.agent_before_settle!({}, ctxOf(210000));
843
- assert(compactCalls.length === 1 && compactCalls[0] === 210000, "usage at/above the threshold triggers pi's compaction");
844
- await handlers.agent_before_settle!({}, ctxOf(215000));
845
- assert(compactCalls.length === 1, "the anti-flap guard blocks an immediate re-trigger");
846
- await handlers.session_compact!({}, undefined);
847
- await handlers.agent_before_settle!({}, ctxOf(215000));
848
- assert(compactCalls.length === 1, "a settled attempt that still sits above the threshold waits for growth");
849
- await handlers.agent_before_settle!({}, ctxOf(222000));
850
- assert(compactCalls.length === 2 && compactCalls[1] === 222000, "usage outgrowing the attempt compacts again");
851
- await handlers.session_compact!({}, undefined); // the compaction that made usage drop
852
- await handlers.agent_before_settle!({}, ctxOf(60000));
853
- assert(compactCalls.length === 2, "below the threshold nothing fires");
854
- await handlers.agent_before_settle!({}, ctxOf(210500));
855
- assert(compactCalls.length === 3 && compactCalls[2] === 210500, "the next crossing starts a fresh cycle");
856
-
857
- // Oscillation at the threshold: one compaction per growth margin, not every turn.
858
- await handlers.session_compact!({}, undefined);
859
- await handlers.agent_before_settle!({}, ctxOf(208000)); // shallow dip under the threshold
860
- await handlers.agent_before_settle!({}, ctxOf(211000));
861
- assert(compactCalls.length === 3, "an oscillation at the threshold does not re-summarize every turn");
862
- await handlers.agent_before_settle!({}, ctxOf(222000));
863
- assert(compactCalls.length === 4 && compactCalls[3] === 222000, "real growth past the attempt compacts again");
864
-
865
- // A failed compaction backs off; session_start clears the backoff for a fresh session.
866
- await handlers.session_compact_failed!({}, undefined);
867
- await handlers.agent_before_settle!({}, ctxOf(225000));
868
- assert(compactCalls.length === 4, "after a failure the backoff holds below attempt + margin");
869
- await handlers.agent_before_settle!({}, ctxOf(234000));
870
- assert(compactCalls.length === 5, "and gives way once usage outgrows the failed attempt");
871
- await handlers.session_compact_failed!({}, undefined);
872
- await handlers.session_start!({}, undefined);
873
- await handlers.agent_before_settle!({}, ctxOf(210500));
874
- assert(compactCalls.length === 6, "a fresh session clears the backoff");
875
-
876
- // Smart + Render cache On: scales 1M window to 90% (~943k), and remote 1 MB payloads shed silently
877
- // without forcing premature session compaction at low token counts (e.g. 49k–110k).
878
- setRenderCache("On");
879
- await handlers.session_start!({}, undefined);
880
- const remoteCtx = ctxOf(49836, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" });
881
- const hugeRunMsgs: MessageLike[] = [
882
- { role: "user", content: [{ type: "text", text: "start" }] },
883
- { role: "assistant", content: [{ type: "toolCall", arguments: { path: "x" } }] },
884
- { role: "toolResult", content: [{ type: "text", text: "z".repeat(liveCeilings.shedTriggerBytes + 10_000) }] },
885
- { role: "user", content: [{ type: "text", text: "continue" }] },
886
- { role: "assistant", content: [{ type: "text", text: "ok" }] },
887
- ];
888
- const ctxResult = (await handlers.context!({ messages: hugeRunMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
889
- assert(
890
- Array.isArray(ctxResult?.messages) &&
891
- jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= liveCeilings.shedTargetBytes,
892
- "context hook sheds payload with hysteresis down to the target ceiling",
893
- );
894
- await handlers.before_provider_request!({ payload: { blob: "p".repeat(liveCeilings.shedTriggerBytes + 20_000) } }, remoteCtx);
895
- await handlers.agent_before_settle!({}, remoteCtx);
896
- assert(compactCalls.length === 6, "remote byte shedding does not force premature compaction at 49k tokens");
897
-
898
- // Only crossing 90% of 1M context triggers Smart compaction when Render cache is On.
899
- await handlers.agent_before_settle!({}, ctxOf(900000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
900
- assert(compactCalls.length === 6, "900k tokens is still under 90% of 1M");
901
- await handlers.agent_before_settle!({}, ctxOf(945000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
902
- assert(compactCalls.length === 7 && compactCalls[6] === 945000, "945k tokens hits 90% Smart threshold and compacts");
903
- await handlers.session_compact!({}, undefined);
904
-
905
- // Compaction input trimming shrinks split-turn prefixes cleanly without triggering follow-ups.
906
- const splitTurnPrefix: MessageLike[] = [
907
- { role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(liveCeilings.compactInputBytes) } }] },
908
- ];
909
- await handlers.session_before_compact!({ preparation: { turnPrefixMessages: splitTurnPrefix } }, remoteCtx);
910
- assert(jsonByteLength(splitTurnPrefix) < liveCeilings.compactInputBytes, "session_before_compact trims split-turn prefix messages too");
911
-
912
- // Remote byte silent shedding stays active even when Auto-compact is Off, and never triggers ctx.compact().
913
- setAutoCompact("Off");
914
- await handlers.session_start!({}, undefined);
915
- const manyMsgs: MessageLike[] = [];
916
- for (let i = 0; i < 900; i++) {
917
- manyMsgs.push(
918
- { role: "user", content: [{ type: "text", text: `turn ${i}: ` + "u".repeat(350) }] },
919
- { role: "assistant", content: [{ type: "toolCall", arguments: { cmd: `echo ${i}` } }] },
920
- { role: "toolResult", content: [{ type: "text", text: "r".repeat(600) }] },
921
- { role: "assistant", content: [{ type: "text", text: "a".repeat(350) }] },
922
- );
923
- }
924
- assert(jsonByteLength(manyMsgs) > 1_048_576, "fixture spans thousands of messages and over a megabyte");
925
- const shedMany = (await handlers.context!({ messages: manyMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
926
- // A fixture sized for the 1 MB default says nothing once the wall scales: at 16 MB
927
- // the same array is far under the trigger and the hook rightly stays quiet.
928
- // Size it against the ceiling in force, or skip when scaling makes that impractical.
929
- const overTrigger = jsonByteLength(manyMsgs) > liveCeilings.shedTriggerBytes;
930
- if (overTrigger) {
931
- assert(
932
- Array.isArray(shedMany?.messages) &&
933
- jsonByteLength(shedMany.messages) <= liveCeilings.shedTargetBytes &&
934
- shedMany.messages[0]?.role === "user",
935
- "many-message session sheds below the ceiling even with Auto-compact Off",
936
- );
937
- } else {
938
- assert(shedMany === undefined, "a fixture under the scaled trigger is left untouched");
939
- }
940
- const compactMany = manyMsgs.slice();
941
- await handlers.session_before_compact!({ preparation: { messagesToSummarize: compactMany } }, remoteCtx);
942
- assert(
943
- jsonByteLength(compactMany) <= liveCeilings.compactInputBytes && compactMany[0]?.role !== "toolResult",
944
- "many-message compaction input trims below 720 KB without orphaned toolResult",
945
- );
946
- await handlers.agent_before_settle!({}, ctxOf(950000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
947
- assert(compactCalls.length === 7, "Auto-compact Off never calls ctx.compact() even at 950k tokens on remote/*");
948
-
949
- // Non-remote model that hits HTTP 413 tightens silent shedding without forcing compaction.
950
- const nonRemoteCtx = ctxOf(50000, 1_048_576, { id: "custom/model" });
951
- await handlers.turn_end!({ message: { stopReason: "error", errorMessage: "413 request_too_large" } }, nonRemoteCtx);
952
- const after413 = (await handlers.context!({ messages: hugeRunMsgs }, nonRemoteCtx)) as { messages?: MessageLike[] } | undefined;
953
- assert(
954
- Array.isArray(after413?.messages) &&
955
- jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= liveCeilings.shedTargetAfter413Bytes,
956
- "saw413 activates tighter silent shedding on any model",
957
- );
958
- // Payload limit Off skips shedding and clears wireBytesSnapshot even for remote models.
959
- setPayloadLimit("Off");
960
- const offResult = await handlers.context!({ messages: hugeRunMsgs }, remoteCtx);
961
- assert(offResult === undefined && wireBytesSnapshot() === null, "Off disables silent shedding and wireBytesSnapshot");
962
- delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
963
- setAutoCompact("Smart");
964
-
965
- // i1 guard: models with no byte wall never measure payload bytes at all.
966
- await handlers.session_start!({}, undefined);
967
- const plainCtx = ctxOf(210000, 1_048_576, { id: "auto/zaicoding_glm-5.3" });
968
- const plainMsgs: MessageLike[] = [{ role: "user", content: [{ type: "text", text: "plain" }] }];
969
- const plainResult = (await handlers.context!({ messages: plainMsgs }, plainCtx)) as { messages?: MessageLike[] } | undefined;
970
- assert(plainResult === undefined, "non-remote context hook skips byte measurement entirely");
971
- const overheadBefore = trackedOverheadBytes;
972
- const plainReq = await handlers.before_provider_request!({ payload: { blob: "p".repeat(4 * 1024 * 1024) } }, plainCtx);
973
- assert(plainReq === undefined && trackedOverheadBytes === overheadBefore, "non-remote before_provider_request skips the 4 MB stringify");
974
-
975
- // The 128k case from the field: Smart defers the whole window to pi's own
976
- // compaction — no percent, however close to full, ever fires ours.
977
- await handlers.session_start!({}, undefined);
978
- await handlers.agent_before_settle!({}, ctxOf(130000, 131072));
979
- assert(compactCalls.length === 7, "a 128k window under Smart never triggers: pi core stays in charge");
980
-
981
- // Older hosts: missing ctx APIs must degrade to a no-op, not throw.
982
- await handlers.agent_before_settle!({}, { getContextUsage: () => undefined });
983
- assert(compactCalls.length === 7, "no usage estimate: no trigger");
984
- // Reset inFlight first, so the missing compact() — not a pending compaction — is what stops it.
985
- await handlers.session_start!({}, undefined);
986
- await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens: 950000, contextWindow: 1_048_576, percent: 90.6 }) });
987
- assert(compactCalls.length === 7, "no ctx.compact on the host: no trigger");
988
-
989
- // Restore: the next module load starts from the real agent dir and the stored default.
990
- rmSync(fixture, { recursive: true, force: true });
991
- delete process.env.PI_CODING_AGENT_DIR;
992
- delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
993
- delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
994
- delete (globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.renderCache")];
995
- resetPresetCache();
996
- console.log("autocompact.ts self-check OK");
997
- }
690
+ export const __test = {
691
+ DEFAULT_OVERHEAD_BYTES,
692
+ TRIMMED_TOOL_STUB,
693
+ AUTO_COMPACT_CONFIG_KEY,
694
+ get trackedOverheadBytes() {
695
+ return trackedOverheadBytes;
696
+ },
697
+ set trackedOverheadBytes(v) {
698
+ trackedOverheadBytes = v;
699
+ },
700
+ };