@estebanforge/pi-antigravity-bridge 1.13.3 → 1.15.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,33 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.15.0] - 2026-11-24
6
+
7
+ ### Added
8
+
9
+ - Opt-in canonical-history handoff (`config.handoff: "sync"`, env `AGY_HANDOFF=sync`; ACP-only, digest stays the default): a rolling sha256 prefix chain over the projected transcript drives a per-turn plan, so warm sessions ship only the owed delta as an `urn:pi-bridge:history:v1` block and a session/load failure re-plans as a lossless rebuild (the settle re-arms; no blind turn, no double rebuild). The settle persists the zeroed contract plus the confirmed checkpoint, the churn gate falls back to digest after 3 consecutive `changed-prefix` rebuilds (the latch rides the record so digest turns keep it), and the framed delta hard-fails past the 3 MiB outbound frame budget (the engine silently truncates resources near 3.82 MiB, so bigger frames would checkpoint content it never read). Mode flips are safe both directions. Design: `docs/designs/history-sync-mode.md` (including implementation deviations); live proof: `scripts/smoke-handoff.mjs` scenario 4 and `scripts/probe-acp-frame.mjs` on agy 1.5.16.
10
+ - Codemode-only bridge mode (`/agy bridge codemode`, env `AGY_BRIDGE_TOOLS=codemode`): the engine's catalog shrinks to pi's `codemode` tool (the one direct tool) plus `bridge_tool_info`/`bridge_call_tool` and `bridge_poll_result`, so multi-step work runs as scripts pi-side and nested tool calls never re-enter the engine's context (spike: `scripts/probe-codemode.mjs`, one wire call carried two nested sandbox calls; session/load on a fresh engine process kept the registration; ~2.5k input tokens over a plain baseline turn; live round trip through a real pi session: `scripts/smoke-codemode.mjs` - the engine called the advertised codemode tool and its script executed pi-side read/write on a planted secret, proven end to end). Prerequisite: pi's codemode tool must be ACTIVE (`--tools codemode`, the `defaultTools` setting, or `/tools`) - without it the mode degrades to `all` behavior; the flip warns and `/agy doctor` reports it. The provider system prompt gains a codemode note redirecting the file-tool instruction into scripts, shipped only when the catalog actually has the tool (`buildFullPrompt` `codemodeOnly` gated on live tool visibility).
11
+
12
+ ### Changed
13
+
14
+ - The provider tool-priority note's bridge-tool enumeration names the real pi tools (`write`, `bash`) instead of the nonexistent `execute`: fresh conversations get the corrected text, and each stream-json staged agent re-stages under a new content hash (harmless one-time cache bust per conversation).
15
+ - Native xhigh thinking tier: the catalog splits `gemini-4-{hydrogen,neon}-xhigh` slugs into base + tier, pi's `xhigh` thinking level passes through to the engine when the base lists it (clamps to the nearest tier below otherwise; pi's own clamp now resolves `max` to xhigh on bases that ship it, so provider turns get the top tier - the direct `max`→`high` clamp remains only in `toAgyEffort` for direct callers), the model toggle shows the xhigh stop only for bases that ship it, and `/agy thinking` plus the AskAntigravity `thinking` param and the config default (`defaultThinking` / `AGY_DEFAULT_THINKING`) accept `xhigh` end to end (probe: `scripts/probe-xhigh.mjs`, agy 1.5.16 accepted the qualified xhigh slug). Requires `@estebanforge/pi-ask-shared` `^0.1.7` (floor bump: the resolver vocabulary widens first; publish shared before this package).
16
+
17
+ ## [1.14.0] - 2026-11-24
18
+
19
+ ### Fixed
20
+
21
+ - One oversized tool result no longer erases earlier turns from the context digest (#25): tool-result bodies are capped per part (head + tail with an elision marker) before the delta budget is spent, so a single >8KB read/bash result can no longer starve the mid-session handoff.
22
+ - Assistant tool calls now render into the digest (`[tool call: name(args)]`, args capped and redacted) instead of vanishing with their text blocks; a turn carrying only tool calls ships too, where it used to be skipped entirely (#25).
23
+ - A config.json saved before the digest-default flip no longer silently keeps the digest off (#25): `migrateStaleDigestDefault` at session start flips the stale `digest: false` to the shipped ON default once, writes a `digestMigrated` marker so later deliberate `/agy digest off` survives, and respects `AGY_DIGEST`. One-time ambiguity window: an `/agy digest off` chosen between the flip commit and this release migrates to ON once (the toast explains how to keep it off).
24
+ - A bound turn whose digest build fails the stream-json byte cap no longer permanently loses that delta (#25 follow-up): the settle write holds the watermark when nothing shipped, so the window re-offers on the next turn (the re-offer re-includes the prior turn's user prompt, which already reached the conversation as that turn's prompt - a small duplicate, never a loss); partial renders (budget cut old turns) still advance and now log the skipped span (`digest` event, AGY_DEBUG-visible) for cap-deciding data.
25
+ - An ACP `session/load` failure that silently falls back to a fresh agy conversation no longer ships a blind turn (#25): bound turns carry an as-if-fresh fallback variant (system prompt gate open, full `bound: false` digest) that the driver swaps in at the load-failure point; the variant honors the same `/agy digest off` and `/agy system-prompt off` choices as the normal turn, and with both off no variant is built at all. stream-json cannot detect its stale-id drop, so the fallback is ACP-only.
26
+
27
+ ### Changed
28
+
29
+ - ACP digest cap raised 8k to 24k chars after a live probe (scripts/probe-acp-context.mjs): a 120k-char embeddedContext block shipped and the model recalled needle strings at both block extremities exactly (end needle on the digest turn; start needle again on a bound follow-up with no block re-sent, proving the block persists server-side), so 24k is transport-safe and shrinks the newest-first partial-render hole. stream-json keeps its 8k inline clamp under the ~25KB prompt cap.
30
+ - AskAntigravity model param description now names the configured default (gemini-4-hydrogen) and the Gemini 4 lines. Removed the legacy flash/pro examples: callers read them as the house default, hard-coded `model: "flash"`, and skipped the hydrogen default entirely (flash resolves to the deprecated 3.x era).
31
+
5
32
  ## [1.13.3] - 2026-11-23
6
33
 
7
34
  ### Fixed
package/README.md CHANGED
@@ -117,7 +117,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
117
117
  | --- | --- | --- |
118
118
  | `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
119
119
  | `webTools` | `false` (no web tools), `true` (register `agy_web_search` + `agy_read_url` as Pi tools, usable by ANY provider's model). Each call spawns a one-shot search-only `agy` agent (plan mode, bridge MCP inheritance off), gates the answer on an observed native `search_web`/`read_url_content` step, and spends Antigravity quota. Off by default: Antigravity sessions already have native web tools on both engines; these serve other providers | `false` |
120
- | `bridgeTools` | `none` (bridge off), `all` (every non-builtin tool, incl. other `Ask*` delegations), `mcp` (pi-mcp-adapter tools + skills bridge only) | `all` |
120
+ | `bridgeTools` | `none` (bridge off), `all` (every non-builtin tool, incl. other `Ask*` delegations), `mcp` (pi-mcp-adapter tools + skills bridge only), `codemode` (pi's `codemode` tool + the info/call pair only; requires pi's codemode tool to be active, e.g. `--tools codemode`) | `all` |
121
121
  | `digest` | Self-gating delta of pi-side context (compaction summaries, other-provider turns, handoffs after a mid-session switch) shipped to agy only when the delta is non-empty, each piece once. Pure antigravity sessions get byte-stable prompts and an intact prompt cache. `false` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `true` |
122
122
  | `systemPrompt` | `on` (send pi's system prompt - operating instructions plus the global agent-dir `AGENTS.md` and ancestor `AGENTS.md`/`CLAUDE.md` - to the first prompt of each new agy conversation, plus a tool-priority note: Pi Bridge tools win over agy's native interactive ones, which never reach the user. Delivery: stream-json stages it as an agy agent file via `--agent`, off the prompt line - the CLI silently drops single prompts past a ~25KB cap and the dropped turn kills the conversation; the carrier declares the productive toolset explicitly (omitting `tools:` reads as a read-only set upstream, issue #13) plus `subagent: false` + `agents: []` so the native subagent tools stay masked (ACP carries no agent file, so its natives remain and the tool-priority note steers the model to pi delegation). ACP prepends it to the first prompt) or `false` (agy-native behavior) | `true` |
123
123
  | `readOnly` | `true`: fail-closed kill switch - every provider turn and the `AskAntigravity` tool are refused with a visible error (the CLI has no review-only enforcement, see [Permissions](#permissions) and [readOnly](#readonly)). In the file, any value that is not a recognized boolean spelling (or an explicit blank) also fails closed to `true` | `false` |
@@ -149,7 +149,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
149
149
  /agy thinking low|medium|high fallback thinking tier for the AskAntigravity tool; callers may override per call
150
150
  /agy digest on|off ship pi-side context to agy when the delta is non-empty (default on; see table above)
151
151
  /agy system-prompt on|off send pi's system prompt + AGENTS.md + the Pi Bridge tool-priority note to new agy conversations (default on)
152
- /agy bridge all|mcp|none which pi tools the MCP bridge exposes to agy (default all; none = bridge off; a running server picks up the new catalog immediately, a stopped one on the next start)
152
+ /agy bridge all|mcp|codemode|none which pi tools the MCP bridge exposes to agy (default all; codemode = scripts only; none = bridge off; a running server picks up the new catalog immediately, a stopped one on the next start)
153
153
  /agy tools [hide|show <name>|reset] session-only bridge-catalog hides (multi-word names OK; reset restores the full set; bare lists exposed + hidden; never touches saved config)
154
154
  /agy web on|off register the agy_web_search + agy_read_url pi tools for ANY provider's model (default off; applies on the next pi start or /reload; every call spawns agy and spends Antigravity quota)
155
155
  /agy engine acp|stream-json switch the turn engine (restart to apply; default acp, stream-json is the fallback; both use the agy CLI). No arguments opens the engine picker modal (TUI)
@@ -68,7 +68,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
68
68
  import { createAgySetupOffer } from "../src/agy-setup.js";
69
69
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
70
70
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
71
- import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
71
+ import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, migrateStaleDigestDefault, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
72
72
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
73
73
  import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
74
74
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
@@ -117,6 +117,7 @@ import {
117
117
  formatBridgeToolInfo,
118
118
  parseBridgeCallRequest,
119
119
  partitionBridgeTools,
120
+ codemodeCatalog,
120
121
  serializeToolSchema,
121
122
  } from "../src/bridge-catalog.js";
122
123
  import { Type } from "typebox";
@@ -231,6 +232,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
231
232
  let gateActive = false;
232
233
  let managedAcpCleanupRan = false;
233
234
  let legacyConfigCleanupRan = false;
235
+ let digestMigrationRan = false;
234
236
  let legacyConfigCleanupFailed = false;
235
237
  let legacyEnvAcpWarningShown = false;
236
238
  let legacyFileAcpWarningShown = false;
@@ -685,6 +687,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
685
687
  onNativeBackground: (info) => armConversationWatcher(info.conversationId, info.turnStartMs),
686
688
  roster,
687
689
  pendingCompactionHandoff,
690
+ hasActiveTool: (name) => pi.getActiveTools().includes(name),
688
691
  engine,
689
692
  log: fileLog.log.bind(fileLog),
690
693
  });
@@ -868,6 +871,25 @@ export default async function (pi: ExtensionAPI): Promise<void> {
868
871
  fileLog.log("legacy-acp-config-cleanup", { error: String(err) }, "error");
869
872
  }
870
873
  }
874
+ // One-time digest-default migration (issue #25): a config saved before
875
+ // the default flip carries digest:false as a bare default, silently
876
+ // keeping mid-session context handoffs off. Best-effort like the
877
+ // cleanup above: a failure must never block session_start.
878
+ if (!digestMigrationRan) {
879
+ digestMigrationRan = true;
880
+ try {
881
+ const migrated = migrateStaleDigestDefault().migrated;
882
+ fileLog.log("digest-default-migration", { migrated }, migrated ? "info" : "debug");
883
+ if (migrated && ctx.hasUI) {
884
+ ctx.ui.notify(
885
+ "digest was still off from an older default; enabled it (keeps context visible on model switches). Keep it off with /agy digest off.",
886
+ "info",
887
+ );
888
+ }
889
+ } catch (err) {
890
+ fileLog.log("digest-default-migration", { error: String(err) }, "warn");
891
+ }
892
+ }
871
893
  if (!legacyEnvAcpWarningShown && process.env.AGY_ACP_BIN?.trim()) {
872
894
  legacyEnvAcpWarningShown = true;
873
895
  const msg = "AGY_ACP_BIN is set but no longer used; turns run \"agy acp\" from the CLI. Remove it from your shell config, then start a new terminal.";
@@ -974,14 +996,20 @@ export default async function (pi: ExtensionAPI): Promise<void> {
974
996
  // /mcp and pi.setActiveTools() update the same live catalog. ACP gets
975
997
  // this endpoint through session/new or session/load; no global config write.
976
998
  const mode = loadConfig().bridgeTools;
977
- const { direct, proxied } = partitionBridgeTools(getBridgeTools());
978
- const tools = direct.map((t) => ({
979
- name: t.name,
980
- description: t.description ?? t.name,
981
- inputSchema: serializeToolSchema(t.parameters),
982
- }));
983
- if (mode !== "none" && proxied.length > 0) {
984
- tools.push(bridgeToolInfoDef(proxied), bridgeCallToolDef());
999
+ const authorized = getBridgeTools();
1000
+ const codemode = mode === "codemode" ? codemodeCatalog(authorized) : null;
1001
+ const { direct, proxied } = partitionBridgeTools(authorized);
1002
+ const directDefs = codemode
1003
+ ? codemode.direct
1004
+ : direct.map((t) => ({
1005
+ name: t.name,
1006
+ description: t.description ?? t.name,
1007
+ inputSchema: serializeToolSchema(t.parameters),
1008
+ }));
1009
+ const tools = directDefs;
1010
+ const proxiedForInfo = codemode ? codemode.proxied : proxied;
1011
+ if (mode !== "none" && proxiedForInfo.length > 0) {
1012
+ tools.push(bridgeToolInfoDef(proxiedForInfo), bridgeCallToolDef());
985
1013
  }
986
1014
  if (skills.length > 0 && mode !== "none") {
987
1015
  tools.push({
@@ -1339,7 +1367,7 @@ function statusText(ctx: AgyCommandCtx): string {
1339
1367
  ` sessions: ${ctx.store.size} bound`,
1340
1368
  ` config: ${configPath()}`,
1341
1369
  "",
1342
- "Subcommands: /agy auth, /agy auth-manual, /agy engine stream-json|acp, /agy mode plan|accept-edits, /agy readonly on|off, /agy permissions on|off, /agy ask on|off, /agy model <alias>, /agy thinking low|medium|high, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|none, /agy tools [hide|show <name>|reset], /agy web on|off, /agy digest on|off, /agy system-prompt on|off, /agy timeout <1-1440|off>, /agy patch-cleanup, /agy clear, /agy doctor",
1370
+ "Subcommands: /agy auth, /agy auth-manual, /agy engine stream-json|acp, /agy mode plan|accept-edits, /agy readonly on|off, /agy permissions on|off, /agy ask on|off, /agy model <alias>, /agy thinking low|medium|high|xhigh, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|codemode|none, /agy tools [hide|show <name>|reset], /agy web on|off, /agy digest on|off, /agy system-prompt on|off, /agy timeout <1-1440|off>, /agy patch-cleanup, /agy clear, /agy doctor",
1343
1371
  ].join("\n");
1344
1372
  }
1345
1373
 
@@ -1347,7 +1375,7 @@ function statusText(ctx: AgyCommandCtx): string {
1347
1375
  function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1348
1376
  pi.registerCommand("agy", {
1349
1377
  description:
1350
- "Antigravity provider: doctor (health + settings), settings picker, clear sessions. Usage: /agy [doctor|auth|auth-manual|engine stream-json|acp|mode plan|accept-edits|readonly on|off|permissions on|off|ask on|off|model <alias>|thinking low|medium|high|agent <name|off>|subagents|quota|artifacts [open <n|name>]|tasks [tail <id>]|bridge all|mcp|none|tools [hide|show <name>|reset]|web on|off|digest on|off|system-prompt on|off|timeout <1-1440|off>|patch-cleanup|clear]",
1378
+ "Antigravity provider: doctor (health + settings), settings picker, clear sessions. Usage: /agy [doctor|auth|auth-manual|engine stream-json|acp|mode plan|accept-edits|readonly on|off|permissions on|off|ask on|off|model <alias>|thinking low|medium|high|xhigh|agent <name|off>|subagents|quota|artifacts [open <n|name>]|tasks [tail <id>]|bridge all|mcp|codemode|none|tools [hide|show <name>|reset]|web on|off|digest on|off|system-prompt on|off|timeout <1-1440|off>|patch-cleanup|clear]",
1351
1379
  handler: async (args, cmdCtx: ExtensionCommandContext) => {
1352
1380
  const ui = cmdCtx.ui;
1353
1381
  if (ui) ctx.setActiveUi(ui);
@@ -1467,6 +1495,9 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1467
1495
  "Antigravity doctor (no tokens spent)",
1468
1496
  ` engine: ${engine}`,
1469
1497
  ` bridge: ${config.bridgeTools}${port ? ` (port ${port})` : " (not running)"}`,
1498
+ ...(config.bridgeTools === "codemode" && !pi.getActiveTools().includes("codemode")
1499
+ ? [" bridge: codemode tool INACTIVE in pi; the engine sees an all-mode catalog without the codemode note. Activate with --tools codemode or the defaultTools setting."]
1500
+ : []),
1470
1501
  ` driver: ${snap.state}${snap.pid ? ` pid=${snap.pid}` : ""}${snap.conversationId ? ` session=${snap.conversationId.slice(0, 8)}` : ""}`,
1471
1502
  ` driver stats: spawns=${snap.stats.spawns} turns=${snap.stats.turns} reused=${snap.stats.reused} recycles=${snap.stats.recycles}${snap.stats.lastRecycleReason ? ` (last: ${snap.stats.lastRecycleReason})` : ""}`,
1472
1503
  ` sessions: ${ctx.store.size} bound`,
@@ -1781,7 +1812,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1781
1812
  return;
1782
1813
  }
1783
1814
  if (sub === "bridge") {
1784
- if (val === "all" || val === "mcp" || val === "none") {
1815
+ if (val === "all" || val === "mcp" || val === "none" || val === "codemode") {
1785
1816
  const next = saveConfig({ bridgeTools: val });
1786
1817
  ui?.notify(
1787
1818
  ctx.getMcpPort() === null
@@ -1789,8 +1820,14 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1789
1820
  : `bridge ${next.bridgeTools}. The active catalog and call guard update now; ACP may keep cached tool schemas until a session reloads or an agy process restarts (/reload applies it).`,
1790
1821
  "info",
1791
1822
  );
1823
+ if (val === "codemode" && !pi.getActiveTools().includes("codemode")) {
1824
+ ui?.notify(
1825
+ "pi's codemode tool is inactive, so the engine sees an all-mode catalog and no codemode note. Activate it first: --tools codemode, the defaultTools setting, or /tools.",
1826
+ "warning",
1827
+ );
1828
+ }
1792
1829
  } else {
1793
- ui?.notify(`bridge: ${loadConfig().bridgeTools}\nusage: /agy bridge all|mcp|none\n all: active non-builtin pi tools. mcp: active pi-mcp-adapter tools + skills. none: bridge off.`, "info");
1830
+ ui?.notify(`bridge: ${loadConfig().bridgeTools}\nusage: /agy bridge all|mcp|codemode|none\n all: active non-builtin pi tools. mcp: active pi-mcp-adapter tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active; without it this behaves like all). none: bridge off.`, "info");
1794
1831
  }
1795
1832
  return;
1796
1833
  }
@@ -1879,11 +1916,11 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1879
1916
  }
1880
1917
 
1881
1918
  if (sub === "thinking") {
1882
- if (val === "low" || val === "medium" || val === "high") {
1919
+ if (val === "low" || val === "medium" || val === "high" || val === "xhigh") {
1883
1920
  const next = saveConfig({ defaultThinking: val as ThinkingTier });
1884
1921
  ui?.notify(`AskAntigravity default thinking set to ${next.defaultThinking}`, "info");
1885
1922
  } else {
1886
- ui?.notify(`AskAntigravity thinking: ${loadConfig().defaultThinking} (fallback; callers may override per call)\nusage: /agy thinking low|medium|high`, "info");
1923
+ ui?.notify(`AskAntigravity thinking: ${loadConfig().defaultThinking} (fallback; callers may override per call)\nusage: /agy thinking low|medium|high|xhigh|xhigh`, "info");
1887
1924
  }
1888
1925
  return;
1889
1926
  }
@@ -1973,15 +2010,15 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
1973
2010
  description:
1974
2011
  "AskAntigravity one-shot delegation tool: thinking tier used when the call names none. Callers may override per call; this is only the fallback. Pro has no Medium; it falls back to nearest.",
1975
2012
  currentValue: config.defaultThinking,
1976
- values: ["low", "medium", "high"],
2013
+ values: ["low", "medium", "high", "xhigh"],
1977
2014
  },
1978
2015
  {
1979
2016
  id: "bridge",
1980
2017
  label: "Bridge tools",
1981
2018
  description:
1982
- "Which pi tools the MCP bridge exposes to agy. all: every non-builtin tool (default). mcp: pi-mcp-adapter tools + skills. none: bridge off.",
2019
+ "Which pi tools the MCP bridge exposes to agy. all: every non-builtin tool (default). mcp: pi-mcp-adapter tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active, e.g. --tools codemode). none: bridge off.",
1983
2020
  currentValue: config.bridgeTools,
1984
- values: ["all", "mcp", "none"],
2021
+ values: ["all", "mcp", "codemode", "none"],
1985
2022
  },
1986
2023
  {
1987
2024
  id: "turn-cap",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.13.3",
3
+ "version": "1.15.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",
@@ -54,7 +54,7 @@
54
54
  }
55
55
  },
56
56
  "dependencies": {
57
- "@estebanforge/pi-ask-shared": "^0.1.6",
57
+ "@estebanforge/pi-ask-shared": "^0.1.7",
58
58
  "@estebanforge/pi-tui-dialogs": "^0.1.3",
59
59
  "@modelcontextprotocol/sdk": "^1.31.0"
60
60
  }
package/src/acp/driver.ts CHANGED
@@ -293,7 +293,10 @@ export class AcpDriver implements TurnDriver {
293
293
  }
294
294
 
295
295
  async #executeTurn(turn: ActiveTurn): Promise<void> {
296
- const request = turn.request;
296
+ // Reassigned when a load failure applies the request's fresh-mode
297
+ // fallback (issue #25): everything after session setup must read the
298
+ // swapped variant.
299
+ let request = turn.request;
297
300
  const conn = await this.#ensureConnection(request);
298
301
  let reused = false;
299
302
 
@@ -332,6 +335,16 @@ export class AcpDriver implements TurnDriver {
332
335
  sessionId: request.conversationId,
333
336
  message: err instanceof Error ? err.message : String(err),
334
337
  });
338
+ // Sync hook BEFORE the fresh creation: the provider invalidates
339
+ // and re-prepares without an orphaned session (a hook failure
340
+ // after newSession would strand the created conversation).
341
+ let rebuild: { prompt: string; contextBlock?: { uri: string; text: string }; images?: Array<{ data: string; mimeType: string }> } | undefined;
342
+ try {
343
+ rebuild = request.onSessionLoadFailed?.({ sessionId: request.conversationId, error: err }) || undefined;
344
+ } catch (hookErr) {
345
+ this.#failTurn(turn, `ACP session-load hook failed: ${describe(hookErr)}`);
346
+ return;
347
+ }
335
348
  try {
336
349
  const created = await conn.newSession(request.cwd);
337
350
  turn.sessionId = created.sessionId;
@@ -340,6 +353,26 @@ export class AcpDriver implements TurnDriver {
340
353
  this.#failTurn(turn, `ACP session failed: ${describe(err2)}`);
341
354
  return;
342
355
  }
356
+ if (rebuild) {
357
+ // The recreated conversation holds nothing: swap in the sync
358
+ // rebuild input — a fresh conversation needs the full history
359
+ // block and the complete image set.
360
+ this.#log("session-load-fallback-applied", { sessionId: request.conversationId, source: "sync-rebuild" });
361
+ request = {
362
+ ...request,
363
+ prompt: rebuild.prompt,
364
+ contextBlock: rebuild.contextBlock,
365
+ ...(rebuild.images ? { images: rebuild.images } : {}),
366
+ };
367
+ turn.request = request;
368
+ } else if (request.fallback) {
369
+ // Digest mode: swap in the as-if-fresh variant the provider
370
+ // prebuilt (system prompt + full bound:false digest) instead
371
+ // of shipping the bound-mode prompt blind.
372
+ this.#log("session-load-fallback-applied", { sessionId: request.conversationId, source: "digest-fallback" });
373
+ request = { ...request, prompt: request.fallback.prompt, contextBlock: request.fallback.contextBlock };
374
+ turn.request = request;
375
+ }
343
376
  } else {
344
377
  this.#failTurn(turn, `ACP session failed: ${describe(err)}`);
345
378
  return;
@@ -347,6 +380,18 @@ export class AcpDriver implements TurnDriver {
347
380
  }
348
381
  if (turn.closed) return;
349
382
 
383
+ // Binding hook before config apply: the provider persists the binding
384
+ // before model config/prompt, so a later failure cannot leave state
385
+ // that claims a session the transport never confirmed. fresh compares
386
+ // ids, not request.conversationId: a load-failure fresh session must
387
+ // report fresh despite the stale request id.
388
+ try {
389
+ await request.onSessionBound?.({ sessionId: turn.sessionId, reused, fresh: turn.sessionId !== request.conversationId });
390
+ } catch (err) {
391
+ this.#failTurn(turn, `ACP session-bound hook failed: ${describe(err)}`);
392
+ return;
393
+ }
394
+
350
395
  // Config: model + mode. Model failure fails the turn (wrong-model turns
351
396
  // are a parity break); mode failure is best-effort (auto policy makes
352
397
  // the modes converge anyway).
@@ -368,6 +413,14 @@ export class AcpDriver implements TurnDriver {
368
413
  // Prompt. Updates stream through the connection's onUpdate callback.
369
414
  try {
370
415
  // Nothing to cancel before the prompt RPC exists; see promptStarted.
416
+ // attempted stamps only after the write-ahead hook passed: a hook
417
+ // failure means the prompt never went out (unconfirmed, not unknown).
418
+ try {
419
+ await request.onBeforePrompt?.({ sessionId: turn.sessionId });
420
+ } catch (err) {
421
+ this.#failTurn(turn, `ACP before-prompt hook failed: ${describe(err)}`);
422
+ return;
423
+ }
371
424
  turn.promptStarted = true;
372
425
  const result = await this.#sessionStep(
373
426
  conn,
@@ -844,6 +897,11 @@ export class AcpDriver implements TurnDriver {
844
897
 
845
898
  #settle(turn: ActiveTurn, outcome: TurnOutcome): void {
846
899
  if (turn.closed) return;
900
+ // Provenance for the sync settle contract, populated once here so the
901
+ // failTurn, connection-exit and abort paths all carry it (??= keeps any
902
+ // explicitly set value).
903
+ outcome.promptAttempted ??= turn.promptStarted;
904
+ outcome.promptTerminal ??= turn.sawResult;
847
905
  const flushed = turn.response.flush();
848
906
  if (flushed) {
849
907
  turn.textDeltas += 1;
@@ -0,0 +1,221 @@
1
+ // Per-turn orchestrator for history-sync handoff turns (handoff = "sync").
2
+ //
3
+ // Wraps the pure plan/coordinator modules around one provider turn: prepare
4
+ // the plan from the pi transcript plus the session record, assemble the
5
+ // driver input (framed history resource block + deduped images), and settle
6
+ // the turn with the documented outcome ordering. Store writes stay with the
7
+ // provider (rotation guards live there); record() only builds the zeroed
8
+ // persist contract shape.
9
+ // Run: npm test
10
+
11
+ import { projectHistory, type HistoryProjection } from "../history-projection.js";
12
+ import { SessionSyncCoordinator, type HistorySyncPlan, type SessionSyncState, type SyncOptions } from "../history-sync.js";
13
+ import type { AgySession } from "../sessions.js";
14
+ import type { Message } from "@earendil-works/pi-ai";
15
+
16
+ /** Thrown by inputFor when the framed turn would exceed the outbound budget;
17
+ * the provider uses it to report a budget refusal without string matching. */
18
+ export class OutboundFrameBudgetError extends Error {}
19
+
20
+ export interface AcpHistorySyncOptions extends SyncOptions {}
21
+
22
+ export interface SyncTurnOutcome {
23
+ ok: boolean;
24
+ conversationId?: string | null;
25
+ /** The driver invoked the transport prompt call (weaker than delivery). */
26
+ promptAttempted?: boolean;
27
+ /** The transport reported a terminal result for the prompt. */
28
+ promptTerminal?: boolean;
29
+ aborted?: boolean;
30
+ }
31
+
32
+ export interface SyncInput {
33
+ prompt: string;
34
+ images?: Array<{ data: string; mimeType: string }>;
35
+ contextBlock?: { uri: string; text: string };
36
+ }
37
+
38
+ export type SyncFinishResult = { settled: "terminal" } | { settled: "invalidated"; reason: string };
39
+
40
+ const HISTORY_URI = "urn:pi-bridge:history:v1";
41
+ const FRAME_MARGIN_BYTES = 2048;
42
+ // The engine ACCEPTS outbound frames past ~3.8MiB but silently truncates
43
+ // the resource there (probe-acp-frame 2026-11-24: "truncated at 4002908
44
+ // bytes" on a 4MiB block), so the lossless budget sits safely below the
45
+ // truncation point - well under frame-guard's 32MiB inbound cap.
46
+ const OUTBOUND_FRAME_BUDGET_BYTES = 3 * 1024 * 1024;
47
+
48
+ export class AcpHistorySync {
49
+ #coordinator: SessionSyncCoordinator;
50
+ #messages: Message[];
51
+ #conversationId: string | null;
52
+ #options: AcpHistorySyncOptions;
53
+ #plan: HistorySyncPlan;
54
+
55
+ constructor(messages: readonly Message[], existing?: AgySession | null, options: AcpHistorySyncOptions = {}) {
56
+ this.#messages = [...messages];
57
+ this.#options = options;
58
+ this.#coordinator = new SessionSyncCoordinator(existing?.sync);
59
+ this.#plan = this.#coordinator.prepare(this.#projection(), options);
60
+ // A rebuild deliberately starts a fresh conversation: the tracked id
61
+ // must be null so the outcome id is adopted instead of classified as a
62
+ // binding change, and a mid-turn crash cannot resurrect the stale id.
63
+ this.#conversationId = this.#plan.kind === "rebuild" ? null : (existing?.conversationId ?? null);
64
+ }
65
+
66
+ #projection(): HistoryProjection {
67
+ return projectHistory(this.#messages);
68
+ }
69
+
70
+ get plan(): HistorySyncPlan {
71
+ return this.#plan;
72
+ }
73
+
74
+ /** A rebuild always starts a fresh conversation, even over an old binding. */
75
+ get freshConversation(): boolean {
76
+ return this.#plan.kind === "rebuild";
77
+ }
78
+
79
+ /** Null while an unbound rebuild is pending; warm sessions keep theirs. */
80
+ get boundConversationId(): string | null {
81
+ return this.#plan.kind === "rebuild" ? null : this.#conversationId;
82
+ }
83
+
84
+ get snapshot(): SessionSyncState {
85
+ return this.#coordinator.snapshot;
86
+ }
87
+
88
+ /** Re-plan from idle (multi-turn reuse); the constructor already planned. */
89
+ prepare(): HistorySyncPlan {
90
+ this.#plan = this.#coordinator.prepare(this.#projection(), this.#options);
91
+ return this.#plan;
92
+ }
93
+
94
+ bound(turnId: string): void {
95
+ this.#coordinator.bound(turnId);
96
+ }
97
+
98
+ /** Write-ahead adoption from the driver's onSessionBound hook: the fresh
99
+ * conversation id is known before the prompt, so a mid-turn crash still
100
+ * persists the right binding. No-op once tracked. */
101
+ adoptBinding(sessionId: string): void {
102
+ if (!this.#conversationId) this.#conversationId = sessionId;
103
+ }
104
+
105
+ /** Session/load failed: invalidate, re-plan as a rebuild over the same
106
+ * transcript, unbind, and return the complete fresh-conversation input
107
+ * (system-prompt-bearing prompt plus full history block and images).
108
+ * The recreated conversation is adopted by the next finish, not treated
109
+ * as a binding change. */
110
+ loadFailed(request: { prompt: string; images?: Array<{ data: string; mimeType: string }> }): SyncInput {
111
+ this.#coordinator.invalidate("session-load-failed");
112
+ this.#conversationId = null;
113
+ this.#plan = this.#coordinator.prepare(this.#projection(), { ...this.#options, continuation: false });
114
+ return this.inputFor(request);
115
+ }
116
+
117
+ dispatching(): void {
118
+ this.#coordinator.dispatching();
119
+ }
120
+
121
+ park(messages: readonly Message[], assistant: Message): void {
122
+ this.#coordinator.park(projectHistory(messages), assistant);
123
+ }
124
+
125
+ terminal(messages: readonly Message[], assistant: Message, conversationId?: string | null): void {
126
+ this.#coordinator.terminal(projectHistory(messages), assistant);
127
+ if (conversationId) this.#conversationId = conversationId;
128
+ }
129
+
130
+ invalidate(reason: string): void {
131
+ this.#coordinator.invalidate(reason);
132
+ }
133
+
134
+ /** Churn-gate latch: the session goes back to the digest flow after this
135
+ * turn's record persists. */
136
+ markDigestFallback(): void {
137
+ this.#coordinator.markDigestFallback();
138
+ }
139
+
140
+ /** Assemble the driver turn input: prompt, request + deduped history
141
+ * images, and the framed history resource block when history is owed.
142
+ * Hard-fails over the frame budget — history is never truncated. */
143
+ inputFor(request: { prompt: string; images?: Array<{ data: string; mimeType: string }> }): SyncInput {
144
+ const images = [...(request.images ?? [])];
145
+ const seen = new Set(images.map((image) => image.mimeType + ":" + image.data));
146
+ for (const image of this.#plan.historyImages) {
147
+ const key = image.mimeType + ":" + image.data;
148
+ if (seen.has(key)) continue;
149
+ seen.add(key);
150
+ images.push({ data: image.data, mimeType: image.mimeType });
151
+ }
152
+ const input: SyncInput = { prompt: request.prompt, ...(images.length ? { images } : {}) };
153
+ if (this.#plan.history.length > 0 && this.#plan.embeddedContext) {
154
+ input.contextBlock = { uri: HISTORY_URI, text: this.#plan.embeddedContext };
155
+ }
156
+ const bytes = Buffer.byteLength(JSON.stringify(input)) + FRAME_MARGIN_BYTES;
157
+ if (bytes > OUTBOUND_FRAME_BUDGET_BYTES) {
158
+ throw new OutboundFrameBudgetError(
159
+ `history-sync input exceeds the outbound frame budget (${bytes} bytes); compact the session to shrink history, or shorten the prompt, then retry`,
160
+ );
161
+ }
162
+ return input;
163
+ }
164
+
165
+ /** Settle the turn per the documented ordering: binding mismatch first,
166
+ * then adopt, then abort-before-terminal, then OK/terminal, then the
167
+ * delivery-unknown and unconfirmed-turn invalidations. */
168
+ finish(
169
+ outcome: SyncTurnOutcome,
170
+ assistant: Message,
171
+ messages: readonly Message[],
172
+ priorConversationId?: string | null,
173
+ ): SyncFinishResult {
174
+ const id = outcome.conversationId ?? null;
175
+ // A rebuild EXPECTS a new conversation: only compare against a prior
176
+ // binding when the plan continued a warm session.
177
+ const known = this.freshConversation ? null : (priorConversationId ?? this.#conversationId);
178
+ if (id && known && id !== known) {
179
+ this.#coordinator.invalidate("unexpected-session-change");
180
+ return { settled: "invalidated", reason: "unexpected-session-change" };
181
+ }
182
+ if (id && this.#conversationId !== id) this.#conversationId = id;
183
+ if (outcome.aborted) {
184
+ this.#coordinator.invalidate("interrupted");
185
+ return { settled: "invalidated", reason: "interrupted" };
186
+ }
187
+ if (outcome.ok && outcome.promptTerminal && this.#coordinator.settleable) {
188
+ this.#coordinator.terminal(this.#projectionOf(messages), assistant);
189
+ return { settled: "terminal" };
190
+ }
191
+ if (outcome.ok && outcome.promptTerminal) {
192
+ // Driver-confirmed delivery, but the turn was never bound (provider
193
+ // contract violation or an unwired hook): the checkpoint cannot
194
+ // absorb, so force the named rebuild instead of crashing terminal().
195
+ this.#coordinator.invalidate("unsettled-terminal");
196
+ return { settled: "invalidated", reason: "unsettled-terminal" };
197
+ }
198
+ // A terminal-but-failed outcome (refusal, engine error with a result
199
+ // frame) IS confirmed delivery - only an attempted prompt that never
200
+ // went terminal stays delivery-unknown; everything else never left.
201
+ const reason = outcome.promptAttempted && !outcome.promptTerminal ? "delivery-unknown" : "unconfirmed-turn";
202
+ this.#coordinator.invalidate(reason);
203
+ return { settled: "invalidated", reason };
204
+ }
205
+
206
+ #projectionOf(messages: readonly Message[]): HistoryProjection {
207
+ return projectHistory(messages);
208
+ }
209
+
210
+ /** Zeroed persist-contract record: digest watermark fields zeroed so a
211
+ * later digest flip re-offers the backlog once, safely. Null
212
+ * conversationId means the caller skips persisting. */
213
+ record(): Omit<AgySession, 'conversationId'> & { conversationId: string | null } {
214
+ return {
215
+ conversationId: this.#conversationId,
216
+ lastStepIdx: -1,
217
+ lastMessageCount: 0,
218
+ sync: this.#coordinator.snapshot,
219
+ };
220
+ }
221
+ }
package/src/ask-tool.ts CHANGED
@@ -64,7 +64,7 @@ COMPACT OUTPUT (param: digest): when true, the prompt is prefixed to request com
64
64
  THINKING LEVEL (params: thinking, effort - SYNONYMS for one knob):
65
65
  - pi calls it thinking, agy calls it effort. Same thing. Pass ONE of the two.
66
66
  - Values (pi vocabulary): minimal|low|medium|high|xhigh|max. Clamped to agy's low|medium|high; unknown values fall back to low. "peer review on high thinking" -> thinking: "high".
67
- - An explicit level beats a tier embedded in model ("flash high") and the configured default. Omit both for the configured default.`;
67
+ - An explicit level beats a tier embedded in model ("gemini-4-carbon-high") and the configured default. Omit both for the configured default.`;
68
68
 
69
69
  // Delegations legitimately run long (research, review, analysis); a short
70
70
  // default kills the run mid-task and the caller re-pays the whole prompt.
@@ -669,13 +669,13 @@ export async function registerAskAntigravityTool(
669
669
  model: Type.Optional(
670
670
  Type.String({
671
671
  description:
672
- "Model alias or exact id. Friendly: 'flash', 'pro', 'gemini'. Add a tier: 'flash high'. Pin a version: '3.5 flash'. Exact: 'gemini-3.6-flash-medium'. Omit for the configured default.",
672
+ "Model alias or exact id. Omit for the configured default (gemini-4-hydrogen, fast all-rounder). Gemini 4 lines: 'gemini-4-hydrogen' (default), 'gemini-4-neon' (more capable), 'gemini-4-carbon' (most capable). Tier via suffix: 'gemini-4-carbon-high'. Legacy 'flash'/'pro' resolve to the deprecated 3.x era.",
673
673
  }),
674
674
  ),
675
675
  thinking: Type.Optional(
676
676
  Type.String({
677
677
  description:
678
- "Thinking level (= agy effort tier). pi vocabulary: minimal|low|medium|high|xhigh|max, clamped to agy's low|medium|high (unknown values fall back to low). Overrides a tier embedded in `model`. Omit for the configured default.",
678
+ "Thinking level (= agy effort tier). pi vocabulary: minimal|low|medium|high|xhigh|max; passes through when the target model lists the tier (the Gemini 4 line ships xhigh) and clamps to the nearest tier below otherwise. Overrides a tier embedded in `model`. Omit for the configured default.",
679
679
  }),
680
680
  ),
681
681
  effort: Type.Optional(
@@ -53,9 +53,14 @@ export function bridgedPiTools(
53
53
  // Never bridge the bridge's own tools. agy has native web tools, so
54
54
  // our quota-burning one-shot wrappers must not tempt it through MCP.
55
55
  !BRIDGE_INTERNAL_TOOLS.has(tool.name) &&
56
- (mode === "mcp"
57
- ? /pi-mcp-adapter/.test(tool.sourceInfo?.source ?? "")
58
- : tool.sourceInfo?.source !== "builtin"),
56
+ (mode === "codemode"
57
+ // Codemode mode: pi's builtin codemode tool is the one builtin that
58
+ // bridges (scripts reach the rest pi-side); the info/call pair covers
59
+ // tools the engine should not call directly.
60
+ ? tool.name === "codemode" || tool.sourceInfo?.source !== "builtin"
61
+ : mode === "mcp"
62
+ ? /pi-mcp-adapter/.test(tool.sourceInfo?.source ?? "")
63
+ : tool.sourceInfo?.source !== "builtin"),
59
64
  );
60
65
  }
61
66
 
@@ -70,6 +75,21 @@ export function partitionBridgeTools<T extends BridgeToolInfo>(tools: readonly T
70
75
  return { direct, proxied };
71
76
  }
72
77
 
78
+ /** Codemode-only catalog projection: pi's codemode tool is the one direct
79
+ * tool (its own description teaches the script grammar and pi executes the
80
+ * scripts with pi's tools injected), every other authorized tool rides the
81
+ * info/call pair so the engine never sees a wide direct catalog. */
82
+ export function codemodeCatalog<T extends BridgeToolInfo>(
83
+ authorized: readonly T[],
84
+ ): { direct: Array<{ name: string; description: string; inputSchema: object }>; proxied: T[] } {
85
+ const cm = authorized.find((t) => t.name === "codemode");
86
+ const proxied = authorized.filter((t) => t.name !== "codemode");
87
+ const direct = cm
88
+ ? [{ name: cm.name, description: cm.description ?? cm.name, inputSchema: serializeToolSchema(cm.parameters) }]
89
+ : [];
90
+ return { direct, proxied };
91
+ }
92
+
73
93
  /** Build the bridge_tool_info MCP tool definition listing proxied extension tool names. */
74
94
  export function bridgeToolInfoDef(proxied: readonly BridgeToolInfo[]): {
75
95
  name: string;