@estebanforge/pi-antigravity-bridge 1.12.0 → 1.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 CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.13.0] - 2026-11-19
6
+
7
+ ### Fixed
8
+
9
+ - **Multi-step agy turns no longer trip a phantom pi-side compaction (issue #20).** pi-ai's `isContextOverflow` judges overflow by `usage.input + usage.cacheRead` alone (Case 2, `stopReason "stop"`), while the ACP driver keeps those two as cumulative billing sums over every inference of the prompt (issue #12's finding: only `total_tokens` was corrected). A long tool-loop turn therefore satisfied the overflow check on a healthy conversation and pi silently compacted. The provider now clamps the emitted usage (`clampOverflowUsage`): when the corrected occupancy (`totalTokens`) fits the context window but the billing sums do not, `input`/`cacheRead` are proportionally rescaled into the single-turn budget with the cache-hit ratio preserved; genuine overflows, normal turns, and the driver's raw billing fields are untouched. pi's usage ledger slightly understates input/cacheRead on clamped turns (on stream-json with no `total_tokens` the clamp shrinks cacheRead in the ledger so the window arithmetic stays consistent); cost stays exact at zero (subscription quota).
10
+ - **pi's ephemeral helper calls no longer touch the session store (issue #20).** Compaction/summarization calls arrive with `cacheRetention: "none"` and a synthetic `uuidv7` sessionId, and replay-style callers can arrive with `disableContinuation` plus the LIVE session id - both previously ran the full binding path: reading the live record, overwriting its watermark, binding the synthetic id, claiming dead/stranded tool results, and arming the background watcher. Both shapes now classify as ephemeral: a fresh agy conversation, zero store reads/writes/deletes, no late-result or stranded claiming, no background arming. Each ephemeral call starts its own never-reclaimed agy conversation; the cache warmer never starts for agy models today (no `promptCache`), so the `disableContinuation` half is defensive for future replay callers.
11
+ - **`session_compact` now rotates the agy conversation binding (issue #20).** A pi compaction previously left the stale binding, so the next turn resumed an old conversation that had never seen the summary. `rotateSessionOnCompaction` deletes the binding on `session_compact` (also cleared on `session_shutdown` and `/agy clear`) and arms a one-shot `pendingCompactionHandoff` latch that survives failed retries (even with the digest disabled) and is consumed by the next successful bind. A turn whose transcript ends in a toolResult or assistant message with no user prompt then seeds a fresh conversation with the compaction summary (`buildContextDigest` with `bound: false, includeLast: true` plus `COMPACTION_RESUME_PROMPT`) instead of failing with the unretryable "No user message to send to agy." error; non-compaction unbound tails keep the old hard error. Known limits, deliberate: the latch is memory-only (after a restart with the digest off, a user-prompt-tailed session starts fresh without the summary - the tail rescue still applies); rotation is unconditional on the active model, so a compaction fired on another provider also rotates the agy binding and the conversation rebuilds from the digest on return; and a `session_compact` landing while a bridge call is parked keeps the rotation - passes that would bind a PRE-ROTATION conversation (parked continuations and strand redeliveries into the old conversation id) decline to rebind and leave the handoff for the next pass.
12
+
13
+ ## [1.12.1] - 2026-11-19
14
+
15
+ ### Fixed
16
+
17
+ - **The agy installer no longer reports a working install as a failure (issue #19).** The Linux/macOS pipeline ran `curl | bash` under `set -o pipefail`: when Google's `install.sh` found agy already present it exited without draining the pipe, curl died with write error 23, and the bridge surfaced the raw notice plus curl noise as "installation failed" followed by a contradictory "agy is not installed" line. The download now lands in a temp file first (a consumer early-exit can no longer fake a download failure; real curl errors stay loud), the version-floor branch points at `agy update` instead of offering an installer that cannot upgrade an existing install, and the post-install verification failure now names the actual remedy (set `AGY_BIN` or fix PATH for pi) instead of advising a terminal that already works. Installer output in the failure toast is tail-truncated; the full text stays in the daily log.
18
+
5
19
  ## [1.12.0] - 2026-11-19
6
20
 
7
21
  ### Fixed
package/README.md CHANGED
@@ -87,7 +87,7 @@ Install with pi's package manager:
87
87
  pi install npm:@estebanforge/pi-antigravity-bridge
88
88
  ```
89
89
 
90
- Requires the **`agy` CLI** installed and authenticated. On an interactive start without it, the extension offers once per process to run Google's official installer after your confirmation, without blocking bridge startup. Linux and macOS use `set -o pipefail; curl -fsSL https://antigravity.google/cli/install.sh | bash`; Windows PowerShell uses `irm https://antigravity.google/cli/install.ps1 | iex`. Installation is verified before the success message. Then run `agy` once to complete Google OAuth and restart pi. The extension resolves `agy` on `$PATH`, or via `AGY_BIN`; a bad explicit override gets correction instructions instead of an install. Headless sessions print the instructions without installing.
90
+ Requires the **`agy` CLI** installed and authenticated. On an interactive start without it, the extension offers once per process to run Google's official installer after your confirmation, without blocking bridge startup. Linux and macOS download the install script to a temp file and run it under bash; Windows PowerShell uses `irm https://antigravity.google/cli/install.ps1 | iex`. Installation is verified before the success message. Then run `agy` once to complete Google OAuth and restart pi. The extension resolves `agy` on `$PATH`, or via `AGY_BIN`; a bad explicit override gets correction instructions instead of an install, and a too-old `agy` points at `agy update` (the installer cannot upgrade an existing install). Headless sessions print the instructions without installing.
91
91
 
92
92
  ## Usage
93
93
 
@@ -46,6 +46,7 @@ import {
46
46
  defaultEscalateAfterMs,
47
47
  formatEscalatedAck,
48
48
  formatPollAnswer,
49
+ rotateSessionOnCompaction,
49
50
  sessionKey,
50
51
  type NativeDisplayEvent,
51
52
  } from "../src/provider.js";
@@ -69,7 +70,7 @@ import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
69
70
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
70
71
  import { configPath, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
71
72
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
72
- import { agyVersionVerdict, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
73
+ import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
73
74
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
74
75
  import { formatSubagentRoster, SubagentRoster } from "../src/subagent-roster.js";
75
76
  import { spawn } from "node:child_process";
@@ -227,6 +228,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
227
228
  let agySetupOffer: (() => Promise<void>) | null = null;
228
229
  let agyMissingWarned = false;
229
230
  let agyVersionWarned = false;
231
+ let agyVersionMessage = "";
230
232
  // Two turn engines behind one contract: `agy acp` (default for new
231
233
  // installs) and the stream-json `agy` CLI
232
234
  // (fallback). Neither spawns anything until its first turn.
@@ -602,10 +604,30 @@ export default async function (pi: ExtensionAPI): Promise<void> {
602
604
  fileLog.log("background-watch-sweep-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
603
605
  }
604
606
  });
607
+ // Session keys whose bound agy conversation was rotated on session_compact
608
+ // so the next turn starts a fresh backend conversation and ships the
609
+ // compaction summary once (even when config.digest is disabled).
610
+ const pendingCompactionHandoff = new Set<string>();
605
611
  pi.on("session_shutdown", () => {
606
612
  backgroundWatchDisposed = true;
607
613
  for (const handle of backgroundWatchers.values()) handle.stop();
608
614
  backgroundWatchers.clear();
615
+ pendingCompactionHandoff.clear();
616
+ });
617
+ pi.on("session_compact", (_event, ctx) => {
618
+ try {
619
+ // Shape-cast as in model_select below: tolerate pi builds whose dts
620
+ // omits getSessionId.
621
+ const sm = ctx.sessionManager as { getSessionId?: () => string };
622
+ const sid = sm.getSessionId?.();
623
+ const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
624
+ const rotated = rotateSessionOnCompaction(store, key, pendingCompactionHandoff);
625
+ if (rotated) {
626
+ fileLog.log("session-compact-rotate", { key, previousConversation: rotated }, "info");
627
+ }
628
+ } catch (err) {
629
+ fileLog.log("session-compact-rotate-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
630
+ }
609
631
  });
610
632
  // Model-switch handoff toast: entering an unbound antigravity model
611
633
  // mid-session opens a fresh agy conversation on the next turn; the
@@ -617,8 +639,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
617
639
  digestEnabled: loadConfig().digest,
618
640
  source: event.source,
619
641
  bound: (() => {
620
- // getSessionId is missing from the published ReadonlySessionManager
621
- // type (dts minification), so shape-cast instead of trusting it.
642
+ // Shape-cast as in the session_compact handler above: tolerate pi
643
+ // builds whose dts omits getSessionId.
622
644
  const sm = ctx.sessionManager as { getSessionId?: () => string };
623
645
  const sid = sm.getSessionId?.();
624
646
  const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
@@ -644,6 +666,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
644
666
  onNativeEvent,
645
667
  onNativeBackground: (info) => armConversationWatcher(info.conversationId, info.turnStartMs),
646
668
  roster,
669
+ pendingCompactionHandoff,
647
670
  engine,
648
671
  log: fileLog.log.bind(fileLog),
649
672
  });
@@ -680,6 +703,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
680
703
  hiddenBridgeTools,
681
704
  fileLog,
682
705
  roster,
706
+ pendingCompactionHandoff,
683
707
  checkAgySetup,
684
708
  });
685
709
 
@@ -743,7 +767,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
743
767
  return;
744
768
  }
745
769
  if (agyVersionWarned) {
746
- if (explicit && ctx.mode === "tui") offerSetup(ctx.ui, true);
770
+ // The installer no-ops on an existing install, so re-offering it
771
+ // on an explicit re-check would toast a false "installed" (issue #19).
772
+ if (explicit && ctx.mode === "tui") ctx.ui.notify(agyVersionMessage, "warning");
747
773
  return;
748
774
  }
749
775
  const rawCheck = await checkAgyCliVersion(binary);
@@ -751,11 +777,10 @@ export default async function (pi: ExtensionAPI): Promise<void> {
751
777
  const check = agyVersionVerdict(rawCheck.raw, floor);
752
778
  if (check.status !== "unsupported") return;
753
779
  agyVersionWarned = true;
754
- const msg = `agy ${check.version} is too old for ${selectedEngine}; install ${floor} or newer.`;
780
+ agyVersionMessage = agyUpdateMessage(check.version ?? rawCheck.raw, floor);
755
781
  if (ctx.mode === "tui") {
756
- ctx.ui.notify(msg, "warning");
757
- offerSetup(ctx.ui, explicit);
758
- } else console.error(`[antigravity-bridge] ${msg}`);
782
+ ctx.ui.notify(agyVersionMessage, "warning");
783
+ } else console.error(`[antigravity-bridge] ${agyVersionMessage}`);
759
784
  } catch (err) {
760
785
  fileLog.log("agy-version-check", { error: String(err) }, "warn");
761
786
  }
@@ -1214,6 +1239,7 @@ interface AgyCommandCtx {
1214
1239
  fileLog: DailyLogger;
1215
1240
  /** Live subagent roster (folded in the provider); /agy subagents. */
1216
1241
  roster: SubagentRoster;
1242
+ pendingCompactionHandoff: Set<string>;
1217
1243
  checkAgySetup: (ctx: { ui: ExtensionUIContext; mode: string }, engine: Engine, explicit?: boolean) => Promise<void>;
1218
1244
  }
1219
1245
 
@@ -1288,6 +1314,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1288
1314
  // Direct subcommands work everywhere (headless + TUI).
1289
1315
  if (sub === "clear") {
1290
1316
  ctx.store.clear();
1317
+ ctx.pendingCompactionHandoff.clear();
1291
1318
  ui?.notify("Cleared all antigravity session bindings.", "info");
1292
1319
  return;
1293
1320
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -13,9 +13,12 @@ export function agyInstallCommand(platform: NodeJS.Platform = process.platform):
13
13
  args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "irm https://antigravity.google/cli/install.ps1 | iex"],
14
14
  };
15
15
  }
16
+ // curl|bash under pipefail turned install.sh's early "already installed"
17
+ // exit into curl write error 23, reported as a failed install (issue #19).
18
+ // Download to a file first so a consumer early-exit cannot fake one.
16
19
  return {
17
20
  command: "bash",
18
- args: ["-c", "set -o pipefail; curl -fsSL https://antigravity.google/cli/install.sh | bash"],
21
+ args: ["-c", "t=$(mktemp) && trap 'rm -f \"$t\"' EXIT && curl -fsSL https://antigravity.google/cli/install.sh -o \"$t\" && bash \"$t\""],
19
22
  };
20
23
  }
21
24
 
@@ -77,7 +80,12 @@ export async function installAgyCli(opts: {
77
80
  const result = await (opts.run ?? defaultRunner)(agyInstallCommand(opts.platform), opts.timeoutMs ?? 10 * 60_000);
78
81
  if (result.code !== 0) return { ok: false, error: result.output || `installer exited with code ${result.code ?? "unknown"}` };
79
82
  const verify = opts.verify ?? (() => isAgyInstalled(process.env.AGY_BIN || "agy"));
80
- if (!(await verify())) return { ok: false, error: "installer finished, but agy is not available in this pi process; open a new terminal, run `agy --version`, then restart pi" };
83
+ if (!(await verify())) {
84
+ // The installer output often names where agy already lives (the
85
+ // already-installed notice); the tail turns the guidance actionable.
86
+ const tail = result.output.split("\n").slice(-3).join("\n");
87
+ return { ok: false, error: `installer finished, but agy is not available in this pi process; set AGY_BIN to the binary path or add its directory to PATH, then restart pi${tail ? `\n${tail}` : ""}` };
88
+ }
81
89
  return { ok: true, output: result.output };
82
90
  } catch (err) {
83
91
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
package/src/agy-setup.ts CHANGED
@@ -6,12 +6,17 @@ export interface AgySetupUi {
6
6
  setStatus: (id: string, text?: string) => void;
7
7
  }
8
8
 
9
+ const toastError = (error: string): string => {
10
+ const tail = error.split("\n").slice(-5).join("\n");
11
+ return tail.length > 600 ? tail.slice(-600) : tail;
12
+ };
13
+
9
14
  export function createAgySetupOffer(opts: {
10
15
  ui: AgySetupUi;
11
16
  binaryOverride?: string;
12
17
  install?: typeof installAgyCli;
13
18
  missingMessage: () => string;
14
- log: (event: string, data: unknown, level: "warn" | "info") => void;
19
+ log: (event: string, data: unknown, level: "warn" | "info" | "error") => void;
15
20
  }): () => Promise<void> {
16
21
  let offered = false;
17
22
  let inFlight: Promise<void> | null = null;
@@ -50,13 +55,17 @@ export function createAgySetupOffer(opts: {
50
55
  opts.ui.setStatus("agy-install", "Installing Antigravity CLI…");
51
56
  const result = await install();
52
57
  if (!result.ok) {
53
- opts.log("agy-install", { error: result.error }, "warn");
54
- notify(`Antigravity CLI installation failed: ${result.error}\n${opts.missingMessage()}`, "warning");
58
+ // Error tier: the default log keeps only errors, so the full
59
+ // installer output survives on disk while the toast shows the tail.
60
+ opts.log("agy-install", { error: result.error }, "error");
61
+ // The error text carries its own remedy; appending the
62
+ // missing-CLI copy contradicted "already installed" (issue #19).
63
+ notify(`Antigravity CLI installation failed: ${toastError(result.error)}`, "warning");
55
64
  return;
56
65
  }
57
66
  notify(`Antigravity CLI installed. ${agyAuthenticationMessage()}`, "info");
58
67
  } catch (err) {
59
- opts.log("agy-install", { error: String(err) }, "warn");
68
+ opts.log("agy-install", { error: String(err) }, "error");
60
69
  notify(`Antigravity CLI setup failed: ${String(err)}\n${opts.missingMessage()}`, "warning");
61
70
  } finally {
62
71
  try {
@@ -19,6 +19,12 @@ import path from "node:path";
19
19
  * and the event mapping rely on; older agy predates verified fields. */
20
20
  export const MIN_AGY_VERSION = "1.1.22";
21
21
  export const MIN_AGY_ACP_VERSION = "1.5.3";
22
+
23
+ /** A too-old agy cannot be fixed by the official installer (it no-ops on an
24
+ * existing install); the CLI updates itself, so the remedy is `agy update`. */
25
+ export function agyUpdateMessage(version: string, floor: string): string {
26
+ return `agy ${version} is too old for this engine; run \`agy update\` in a terminal to upgrade to ${floor} or newer (the official installer cannot upgrade an existing install).`;
27
+ }
22
28
  /** Highest agy release where the top-level --gemini_dir flag was
23
29
  * live-verified to isolate MCP discovery (issue #14 work, 2026-11-13).
24
30
  * The flag is undocumented upstream and may change shape in future
package/src/provider.ts CHANGED
@@ -36,7 +36,7 @@ import type { Api } from "@earendil-works/pi-ai";
36
36
  import type { DriverActivity, TurnDriver, TurnHandle } from "./driver-types.js";
37
37
  import { looksBackgroundNativeCall } from "./background-watch.js";
38
38
  import { SubagentRoster } from "./subagent-roster.js";
39
- import { toPiUsage } from "./stream-events.js";
39
+ import { clampOverflowUsage, toPiUsage } from "./stream-events.js";
40
40
  import { mapAgyToolToNative } from "./native-tools.js";
41
41
  import { toAgyEffort, type AgyModelEntry } from "./models.js";
42
42
  import { SessionStore } from "./sessions.js";
@@ -151,6 +151,12 @@ const COMPACTION_MARKER = "compacted into the following summary";
151
151
  export const RESUME_PROMPT =
152
152
  "[The previous attempt of this turn failed and was discarded. Check your conversation history for the last step you completed, then continue the task from there. Do not repeat completed actions.]";
153
153
 
154
+ /** Synthetic prompt for resuming into a fresh agy conversation right after pi
155
+ * compacts mid-tool-loop (transcript ends in a toolResult or assistant
156
+ * message after the bound conversation was rotated on session_compact). */
157
+ export const COMPACTION_RESUME_PROMPT =
158
+ "[The conversation was compacted into a summary and moved to a fresh Antigravity session. Continue the task from the compaction summary and any recent context above without repeating completed actions.]";
159
+
154
160
  export const DIGEST_PREAMBLE =
155
161
  "[The following is context from the broader pi session that this Antigravity turn was not directly spawned for: compaction summaries and turns handled by other providers or pi's own tools. Your own prior turns are already in your conversation history. Use this for continuity only.]";
156
162
 
@@ -244,6 +250,11 @@ export interface DigestOptions {
244
250
  * the front, so every compaction lands at the same index; content
245
251
  * identity ships a NEW summary exactly once. */
246
252
  seenSummaryId?: string;
253
+ /** Include the trailing message in the delta window instead of reserving
254
+ * it as the current user prompt. Used when resuming into a fresh
255
+ * post-compaction conversation whose transcript ends in a toolResult or
256
+ * assistant message. Default false. */
257
+ includeLast?: boolean;
247
258
  }
248
259
 
249
260
  /** Soft cap on the digest body when no tighter budget applies. */
@@ -356,7 +367,7 @@ export function buildContextDigest(
356
367
  } else if (watermark > messages.length) {
357
368
  start = 0;
358
369
  }
359
- const end = Math.max(0, messages.length - 1);
370
+ const end = opts.includeLast ? messages.length : Math.max(0, messages.length - 1);
360
371
  for (let i = start; i < end; i++) {
361
372
  const m = messages[i];
362
373
  if (m.role === "assistant") {
@@ -445,6 +456,25 @@ export function sessionKey(
445
456
  return base + (engine === "acp" ? "@acp" : "");
446
457
  }
447
458
 
459
+ /** Rotate the bound agy conversation after pi compacts the session.
460
+ * Deleting the binding forces the next turn onto a fresh agy conversation so
461
+ * server-side context is freed alongside pi's transcript; recording the key
462
+ * in `pendingCompactionHandoff` guarantees a one-shot compaction handoff even
463
+ * when `config.digest` is disabled. Returns the rotated conversation id, or
464
+ * null when the session had no binding. */
465
+ export function rotateSessionOnCompaction(
466
+ store: SessionStore,
467
+ key: string,
468
+ pendingCompactionHandoff?: Set<string>,
469
+ ): string | null {
470
+ const existing = store.get(key);
471
+ if (!existing) return null;
472
+ store.delete(key);
473
+ stagedAgentByConversation.delete(existing.conversationId);
474
+ pendingCompactionHandoff?.add(key);
475
+ return existing.conversationId;
476
+ }
477
+
448
478
  /** Track which content block is currently open so we close-on-switch.
449
479
  * At most one of textIdx / thinkingIdx is non-null at a time. */
450
480
  export interface BlockState {
@@ -497,6 +527,9 @@ export interface StreamSimpleDeps {
497
527
  onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
498
528
  /** Subagent roster (both engines); folded from every activity. */
499
529
  roster?: SubagentRoster;
530
+ /** Session keys rotated on `session_compact` awaiting a one-shot
531
+ * compaction handoff into a fresh agy conversation. */
532
+ pendingCompactionHandoff?: Set<string>;
500
533
  /** Daily file log sink (src/daily-log.ts). Records pre-dispatch turn
501
534
  * errors that never create a driver turn (and so never reach onTurnEnd). */
502
535
  log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
@@ -1197,6 +1230,9 @@ export interface DriverDeps {
1197
1230
  onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
1198
1231
  /** Subagent roster fold target (both engines; best-effort telemetry). */
1199
1232
  roster?: SubagentRoster;
1233
+ /** Session keys rotated on `session_compact` awaiting a one-shot
1234
+ * compaction handoff into a fresh agy conversation. */
1235
+ pendingCompactionHandoff?: Set<string>;
1200
1236
  /** Active engine (config), for engine-scoped session keys. */
1201
1237
  engine: "stream-json" | "acp";
1202
1238
  /** Daily file log sink for pre-dispatch errors (see StreamSimpleDeps). */
@@ -1431,7 +1467,16 @@ async function runTurnDriver(
1431
1467
 
1432
1468
  const cwd = (options as { cwd?: string } | undefined)?.cwd ?? process.cwd();
1433
1469
  const key = sessionKey(options, cwd, deps.engine);
1434
- const existing = store.get(key);
1470
+ // Ephemeral helper calls (pi compaction / branch summarization set
1471
+ // cacheRetention: "none"; cache warming / replay callers set
1472
+ // disableContinuation: true) must run in a fresh, isolated agy
1473
+ // conversation: never reuse or mutate the live session's SessionStore
1474
+ // binding, never claim dead/stranded tool results, and never arm
1475
+ // background watchers for throwaway turns.
1476
+ const ephemeral = options?.cacheRetention === "none" || options?.disableContinuation === true;
1477
+ const existing = ephemeral ? null : store.get(key);
1478
+ const compactionHandoff =
1479
+ !ephemeral && !existing?.conversationId && Boolean(deps.pendingCompactionHandoff?.has(key));
1435
1480
  const messageCount = context.messages.length;
1436
1481
  const config = loadConfig();
1437
1482
  // Settle bookkeeping shared by both store.set paths: the boundary
@@ -1472,7 +1517,7 @@ async function runTurnDriver(
1472
1517
  // nor start a new prompt. Leave the tombstone for the next fresh pass
1473
1518
  // instead of consuming it blind.
1474
1519
  const late: LateToolResult[] = [];
1475
- if (!isContinuation) {
1520
+ if (!ephemeral && !isContinuation) {
1476
1521
  for (const r of collectToolResults(context.messages, deps.roundTrips.deadIds)) {
1477
1522
  const dead = deps.roundTrips.consumeDead(r.toolCallId);
1478
1523
  if (dead)
@@ -1487,7 +1532,7 @@ async function runTurnDriver(
1487
1532
  if (late.length > 0) {
1488
1533
  deps.log?.("late-result", { tools: late.map((l) => l.name), freshConversation: !existing?.conversationId }, "info");
1489
1534
  }
1490
- } else if (deps.roundTrips.deadIds.length > 0) {
1535
+ } else if (!ephemeral && deps.roundTrips.deadIds.length > 0) {
1491
1536
  deps.log?.("late-result-deferred", { count: deps.roundTrips.deadIds.length }, "info");
1492
1537
  }
1493
1538
 
@@ -1512,6 +1557,14 @@ async function runTurnDriver(
1512
1557
  images: view.images,
1513
1558
  };
1514
1559
  });
1560
+ // A rotation that lands mid-turn must win over any bind of a PRE-ROTATION
1561
+ // conversation: continuations and strand redeliveries both target the old
1562
+ // conversation id, so binding their outcomes would restore the
1563
+ // rotated-away binding and swallow the handoff. Evaluated at bind time:
1564
+ // the latch may arm after turn start.
1565
+ const rotationGuardArmed = (): boolean =>
1566
+ (isContinuation || redeliveryConversation !== undefined) &&
1567
+ deps.pendingCompactionHandoff?.has(key) === true;
1515
1568
  /** Stream-json has no image channel in the turn input: stage the blocks
1516
1569
  * to temp files and let the note point the model at the bridge read
1517
1570
  * tool, whose result images the CLI delivers (probe 2026-09-07). ACP
@@ -1544,7 +1597,7 @@ async function runTurnDriver(
1544
1597
  } else {
1545
1598
  // Dead turn: claim NOW (single-use). A live turn claims after outcome
1546
1599
  // instead — claiming here would eat the post-outcome recovery.
1547
- late.push(...collectStranded());
1600
+ if (!ephemeral) late.push(...collectStranded());
1548
1601
  if (isContinuation && late.length === 0) {
1549
1602
  if (escalatedNames.length === 0) {
1550
1603
  deps.log?.("turn-error", { reason: "tool-result-no-active-turn" }, "warn");
@@ -1582,14 +1635,29 @@ async function runTurnDriver(
1582
1635
  // transcript (lastRole undefined) and a user tail both keep their
1583
1636
  // existing behavior.
1584
1637
  const lastRole = context.messages[context.messages.length - 1]?.role;
1638
+ const hasCompactionSummary = findLastCompactionIdx(context.messages) >= 0;
1585
1639
  const resume =
1586
1640
  !userPrompt &&
1587
1641
  images.length === 0 &&
1588
1642
  late.length === 0 &&
1589
1643
  Boolean(existing?.conversationId) &&
1590
1644
  (lastRole === "toolResult" || lastRole === "assistant");
1591
- const prompt = resume ? RESUME_PROMPT : userPrompt;
1645
+ // Post-compaction mid-tool-loop resume: session_compact rotated the old
1646
+ // agy conversation (so existing is null), and pi's compacted transcript
1647
+ // ends in a toolResult or assistant message. Seed a fresh agy
1648
+ // conversation with the compaction summary + trailing messages instead
1649
+ // of failing with the unretryable "No user message" error.
1650
+ const compactionResume =
1651
+ !ephemeral &&
1652
+ !userPrompt &&
1653
+ images.length === 0 &&
1654
+ late.length === 0 &&
1655
+ !existing?.conversationId &&
1656
+ (compactionHandoff || hasCompactionSummary) &&
1657
+ (lastRole === "toolResult" || lastRole === "assistant");
1658
+ const prompt = resume ? RESUME_PROMPT : compactionResume ? COMPACTION_RESUME_PROMPT : userPrompt;
1592
1659
  if (resume) deps.log?.("resume-turn", { conversation: existing?.conversationId }, "error");
1660
+ if (compactionResume) deps.log?.("compaction-resume-turn", { key, handoff: compactionHandoff }, "info");
1593
1661
  // An image-only message (no text) is valid on the ACP engine; only fail
1594
1662
  // when there is nothing at all to send (no text, no images, no late
1595
1663
  // tool results to deliver).
@@ -1615,15 +1683,20 @@ async function runTurnDriver(
1615
1683
  // Late and resume turns re-open the conversation with a synthetic
1616
1684
  // prompt; the digest would re-send context agy already holds (against a
1617
1685
  // stale watermark: a failed pass never advances it), so skip it.
1686
+ // Post-compaction handoff / compactionResume always ships the digest
1687
+ // once even if config.digest is false, because the old agy conversation
1688
+ // was rotated and the fresh conversation has no prior history.
1618
1689
  const engine = deps.engine ?? config.engine;
1619
1690
  const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
1620
1691
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1692
+ const wantDigest = config.digest || compactionHandoff || compactionResume;
1621
1693
  const digest =
1622
- config.digest && maxChars !== null && late.length === 0 && !resume
1694
+ wantDigest && maxChars !== null && late.length === 0 && !resume
1623
1695
  ? buildContextDigest(context.messages, watermark, {
1624
1696
  bound: Boolean(existing?.conversationId),
1625
1697
  seenSummaryId: existing?.digestSummaryId,
1626
1698
  maxChars,
1699
+ includeLast: compactionResume,
1627
1700
  })
1628
1701
  : "";
1629
1702
  // Byte-level fail closed (issue #2): the char budget over-reserves for
@@ -1770,7 +1843,7 @@ async function runTurnDriver(
1770
1843
  // recreated a conversation, so the snapshot id is the real one, and
1771
1844
  // the staged agent must move with the binding or a stream-json resume
1772
1845
  // re-runs without its carrier-agent profile.
1773
- if (!existing) {
1846
+ if (!ephemeral && !existing && !rotationGuardArmed()) {
1774
1847
  const parkedConv = deps.driver.snapshot().conversationId;
1775
1848
  if (parkedConv) {
1776
1849
  store.set(key, {
@@ -1780,6 +1853,7 @@ async function runTurnDriver(
1780
1853
  digestBoundary: settleBoundary,
1781
1854
  digestSummaryId: settleSummaryId,
1782
1855
  });
1856
+ deps.pendingCompactionHandoff?.delete(key);
1783
1857
  if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
1784
1858
  }
1785
1859
  }
@@ -1807,7 +1881,7 @@ async function runTurnDriver(
1807
1881
  outcome.modelOutputSeen === false &&
1808
1882
  Boolean(existing?.conversationId);
1809
1883
  if (silentDrop || poisonedResume) {
1810
- if (existing?.conversationId || outcome.conversationId) {
1884
+ if (!ephemeral && (existing?.conversationId || outcome.conversationId)) {
1811
1885
  store.delete(key);
1812
1886
  if (outcome.conversationId) stagedAgentByConversation.delete(outcome.conversationId);
1813
1887
  }
@@ -1852,7 +1926,7 @@ async function runTurnDriver(
1852
1926
  // fix: sweep and deliver as a late run in the same conversation. Single
1853
1927
  // shot: claims are single-use, so a re-delivered strand cannot reappear
1854
1928
  // here; a late run that parks hands recovery to the next pi pass.
1855
- if (isContinuation && outcome.status === "OK" && !outcome.aborted) {
1929
+ if (!ephemeral && isContinuation && outcome.status === "OK" && !outcome.aborted) {
1856
1930
  const more = collectStranded();
1857
1931
  if (more.length > 0) {
1858
1932
  const conv = redeliveryConversation ?? outcome.conversationId ?? existing?.conversationId ?? null;
@@ -1886,7 +1960,7 @@ async function runTurnDriver(
1886
1960
  }
1887
1961
  }
1888
1962
  }
1889
- if (outcome.conversationId) {
1963
+ if (!ephemeral && outcome.conversationId) {
1890
1964
  // A different id than the stored one means the driver recreated the
1891
1965
  // conversation under us (ACP session-load fallback, stream-json CLI
1892
1966
  // dropping a stale --conversation). The recreated conversation has seen
@@ -1899,14 +1973,19 @@ async function runTurnDriver(
1899
1973
  store.delete(key);
1900
1974
  stagedAgentByConversation.delete(existing.conversationId);
1901
1975
  } else if (outcome.status === "OK" && !outcome.aborted) {
1902
- store.set(key, {
1903
- conversationId: outcome.conversationId,
1904
- lastStepIdx: -1,
1905
- lastMessageCount: messageCount,
1906
- digestBoundary: settleBoundary,
1907
- digestSummaryId: settleSummaryId,
1908
- });
1909
- if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
1976
+ if (rotationGuardArmed()) {
1977
+ deps.log?.("rotation-binding-deferred", { conversation: outcome.conversationId, key }, "info");
1978
+ } else {
1979
+ store.set(key, {
1980
+ conversationId: outcome.conversationId,
1981
+ lastStepIdx: -1,
1982
+ lastMessageCount: messageCount,
1983
+ digestBoundary: settleBoundary,
1984
+ digestSummaryId: settleSummaryId,
1985
+ });
1986
+ deps.pendingCompactionHandoff?.delete(key);
1987
+ if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
1988
+ }
1910
1989
  }
1911
1990
  // A failed or aborted turn on the SAME conversation keeps the pre-turn
1912
1991
  // record: whether the prompt actually landed in agy's DB is not
@@ -1928,10 +2007,15 @@ async function runTurnDriver(
1928
2007
  if (blocks.textIdx === null && blocks.thinkingIdx === null) {
1929
2008
  ensureTextOpen(stream, blocks);
1930
2009
  }
1931
- if (nativeBackgroundSeen && outcome.conversationId) {
2010
+ if (!ephemeral && nativeBackgroundSeen && outcome.conversationId) {
1932
2011
  deps.onNativeBackground?.({ conversationId: outcome.conversationId, turnStartMs });
1933
2012
  deps.log?.("native-background-arm", { conversation: outcome.conversationId, turnStartMs }, "info");
1934
2013
  }
2014
+ // Multi-inference billing sums in usage.input + usage.cacheRead can exceed
2015
+ // model.contextWindow even when live occupancy (totalTokens) is well under
2016
+ // the window. Clamp before emitting stop so pi-ai's isContextOverflow()
2017
+ // Case 2 does not trigger a phantom overflow compaction on a healthy turn.
2018
+ clampOverflowUsage(blocks.partial.usage, model.contextWindow);
1935
2019
  finalize(stream, blocks, "stop");
1936
2020
  }
1937
2021
 
@@ -2020,6 +2104,7 @@ export function createStreamSimple(
2020
2104
  onNativeEvent: deps.onNativeEvent,
2021
2105
  onNativeBackground: deps.onNativeBackground,
2022
2106
  roster: deps.roster,
2107
+ pendingCompactionHandoff: deps.pendingCompactionHandoff,
2023
2108
  // Record the engine of the driver that will ACTUALLY run: if the
2024
2109
  // ACP driver is absent, the config switch falls back to stream,
2025
2110
  // and keying the session as @acp would store a stream
@@ -120,3 +120,42 @@ export function toPiUsage(
120
120
  piUsage.cacheRead = u.cache_read_tokens ?? piUsage.cacheRead;
121
121
  piUsage.totalTokens = u.total_tokens ?? piUsage.input + piUsage.output;
122
122
  }
123
+
124
+ /**
125
+ * Prevent pi-ai's silent-overflow detector (`isContextOverflow` Case 2) from
126
+ * false-triggering on multi-inference billing sums.
127
+ *
128
+ * In multi-step turns (several tool inferences inside one prompt), agy sums
129
+ * `input_tokens` and `cache_read_tokens` across every inference. `AcpDriver`
130
+ * keeps those billing fields while replacing `total_tokens` with single-turn
131
+ * context occupancy (issue #12). However, pi-ai's `isContextOverflow` ignores
132
+ * `totalTokens` and checks `usage.input + usage.cacheRead > contextWindow` on
133
+ * `stopReason === "stop"`, which triggers emergency overflow compaction at a
134
+ * fraction of the real context window.
135
+ *
136
+ * When live occupancy (`totalTokens`) fits inside `contextWindow` but
137
+ * `input + cacheRead` exceeds it, scale `input` and `cacheRead` proportionally
138
+ * to fit within the single-turn input budget (preserving the cache-hit ratio).
139
+ * Normal turns (`input + cacheRead <= contextWindow`) and genuine silent
140
+ * overflows (`totalTokens > contextWindow`) are left untouched.
141
+ */
142
+ export function clampOverflowUsage(
143
+ usage: { input: number; output: number; cacheRead: number; totalTokens: number },
144
+ contextWindow: number | undefined,
145
+ ): void {
146
+ if (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0) return;
147
+ if (!Number.isFinite(usage.totalTokens) || usage.totalTokens <= 0) return;
148
+ if (usage.totalTokens > contextWindow) return;
149
+ if (!Number.isFinite(usage.input) || !Number.isFinite(usage.cacheRead)) return;
150
+ if (usage.input < 0 || usage.cacheRead < 0) return;
151
+ const rawInput = usage.input + usage.cacheRead;
152
+ if (rawInput <= contextWindow) return;
153
+
154
+ const target =
155
+ Number.isFinite(usage.output) && usage.output >= 0 && usage.output < usage.totalTokens
156
+ ? usage.totalTokens - usage.output
157
+ : usage.totalTokens;
158
+ const scaledInput = Math.min(target, Math.max(0, Math.round((usage.input / rawInput) * target)));
159
+ usage.input = scaledInput;
160
+ usage.cacheRead = target - scaledInput;
161
+ }