@estebanforge/pi-antigravity-bridge 1.15.0 → 1.15.2

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,27 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.15.2] - 2026-11-25
6
+
7
+ ### Fixed
8
+
9
+ - With the approval gate on, the shadow `bash` (which replaces pi's `bash` for every model, not only Antigravity) now runs commands with the session's `shellCommandPrefix` and `shellPath` settings, like pi's own bash. Before, the twin was built without them, so a configured prefix or shell wrapper silently stopped applying to every bash call once the gate was enabled. Hosts without `pi.getSettings` keep the previous behavior.
10
+ - `bridgeTools: "none"` no longer disables an active approval gate. Startup returned before staging the gate, so agy's native tools ran ungated while the provider stayed usable. The listener now starts for the gate alone and exposes no pi tools.
11
+ - A required approval gate that cannot be staged (for example, the MCP listener failed to start) now refuses provider turns with a visible error instead of letting agy's native tools run without pi-side approval.
12
+ - The shadow `bash` twin resolves a `file://` `shellPath` the way pi does.
13
+ - The gate mode is resolved once per session start: the staging block and the fail-closed refusal state now act on the same verdict, so a config or gate-extension change mid-startup can no longer leave a required gate unstaged while the refusal state says pending (every turn refused until restart).
14
+ - A throw while reading shell settings (host skew, malformed `file://` path) no longer aborts gate staging between hook staging and shadow registration; the twin degrades to default shell options, because losing the whole gate to shell fidelity would refuse every turn.
15
+ - With `bridgeTools: "none"`, the bridge no longer writes its per-pid entry into the global agy config (`~/.gemini/config/mcp_config.json`), including the staged-home recovery path: with no pi tools exposed, a global entry would only announce the listener to agy processes the user opted out of. The gate needs no registration; its hook rides the session's own add-dir.
16
+ ### Changed
17
+
18
+ - With the approval gate active, `AskAntigravity` consults can no longer mutate the machine: the consult spawn now carries the staged gate dir, so its mutating tool calls park into a streaming antigravity turn's approval surface when one happens to be streaming and are denied fail-closed otherwise, because a park cannot reach a pi-side approval outside an antigravity turn. Read-only consult work is unaffected. When a wanted gate was never staged, the tool refuses up-front. Previously a consult's native tools ran with no pi-side approval even with the gate forced on.
19
+
20
+ ## [1.15.1] - 2026-11-25
21
+
22
+ ### Fixed
23
+
24
+ - A user message typed while a bridge tool round-trip was parked no longer vanishes (Baluard session 2026-11-25 11:54): pi's steering poll delivered it into the transcript, but the continuation pass re-attached to the parked turn without sending any new user event, so the model answered the pre-park work, the queue stayed empty, and the turn ended with the message sitting unanswered. The provider now late-delivers steered messages to the same conversation once the parked turn settles OK, combined with any stranded escalated results in a single prompt (image blocks ride along; the plain no-steer continuation still starts no run). Delivery floor is a per-session dispatch cursor, not the first-pending-toolResult anchor, so a steer from an EARLIER park of a park chain (the normal shape under the approval gate) is still found; a failed or unbindable late start holds both the watermark and the boundary fingerprint at the first undelivered message so the digest re-offers the steer instead of resetting to full history (delivery invariant: claim only what reached agy); the sync handoff contract invalidates on that failure so its checkpoint cannot claim it either; a steer leads the fresh dispatch when the parked turn is already gone (dead handle) instead of an error stop; and an oversized steer is visibly truncated on stream-json instead of silently dropped (issue #2).
25
+
5
26
  ## [1.15.0] - 2026-11-24
6
27
 
7
28
  ### Added
package/README.md CHANGED
@@ -46,6 +46,8 @@ The bridge starts a localhost MCP server inside pi's process. The exposed catalo
46
46
 
47
47
  **Recursion safety.** Only the provider's agy receives the extra `--add-dir`. `AskAntigravity` is also filtered from the exposed tool list. Its delegated `agy -p` spawns with just the workspace, and for the whole delegated run the bridge hides its global per-pid entries: disabled before the spawn, released only on process close or error - agy watches the config and hot-reloads MCP servers on file changes, so a mid-run re-enable would poke the live delegation back into pi. A cross-process marker (`suppression.json` in the bridge's extensions-data dir) coordinates concurrent delegations: entries come back only when no live delegation remains, a session starting mid-delegation registers its own entry disabled, and the session-start heal re-enables only once the last delegator is gone (dead entries pruned by pid liveness with a 24h age bound). The inner agy therefore sees no bridge and cannot re-enter pi. Foreign servers in the global config are never touched.
48
48
 
49
+ **Approval gate and consults.** When a gate is wanted (`approvals.gateMode`), the consult spawn also carries the staged gate dir (print-mode agy loads add-dir hooks, live-verified on agy 1.5.17): its mutating tool calls park into a streaming antigravity turn's approval surface when one is streaming, and are denied fail-closed otherwise, so a gated consult is effectively read-only; an unstaged wanted gate refuses the tool up-front.
50
+
49
51
  **Cost / fan-out.** Every registered pi tool except builtins and the bridge's own internal tools is exposed (respecting the `bridgeTools` mode and any `/agy tools` hides), including other delegation tools like `AskClaude`/`AskCodex`. agy can therefore chain into other models via the bridge, which is a new cost/time fan-out vector that did not exist before this feature.
50
52
 
51
53
  **Security.** The MCP server binds to `127.0.0.1` only and requires a per-session shared-secret header (`x-bridge-token`) that agy sends from the bridge config; browsers cannot set custom headers on a simple cross-origin POST, so this blocks web CSRF against the loopback server. Request bodies are size-capped. This is intended for single-user developer machines: any local process running as the same user can read the token from the per-pid config and call the exposed tools, so do not run it on a shared host where you do not trust other same-user processes.
@@ -117,7 +119,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
117
119
  | --- | --- | --- |
118
120
  | `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
119
121
  | `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), `codemode` (pi's `codemode` tool + the info/call pair only; requires pi's codemode tool to be active, e.g. `--tools codemode`) | `all` |
122
+ | `bridgeTools` | `none` (no pi tools; an active approval gate still starts the listener gate-only, and no global registration is written), `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
123
  | `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
124
  | `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
125
  | `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` |
@@ -55,6 +55,7 @@ import { PollRunFolder, type PollRunData } from "../src/poll-fold.js";
55
55
  import {
56
56
  createShadowTool,
57
57
  stripMarkerFields,
58
+ bashSettingsOptions,
58
59
  type AnyToolDefinition,
59
60
  type GatePolicy,
60
61
  } from "../src/approval-gate.js";
@@ -230,6 +231,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
230
231
  // Staged gate hooks do not stop agy's own request_permission path, so when
231
232
  // true the ACP driver stops letting skipPermissions auto-allow it.
232
233
  let gateActive = false;
234
+ // Set while a required approval gate is not staged; provider turns are
235
+ // refused until the shadows are registered (fail closed).
236
+ let gateUnavailable: string | undefined;
233
237
  let managedAcpCleanupRan = false;
234
238
  let legacyConfigCleanupRan = false;
235
239
  let digestMigrationRan = false;
@@ -307,8 +311,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
307
311
  fileLog.log("stream-home-stage-failed", { error: String(err) }, "warn");
308
312
  // The per-pid --add-dir config is not the stream-json delivery
309
313
  // path; restore the global registration so the bridge stays
310
- // reachable when the staged home is unusable.
311
- if (mcpHandle) {
314
+ // reachable when the staged home is unusable. "none" still skips:
315
+ // no pi tools exposed means nothing to reach.
316
+ if (mcpHandle && loadConfig().bridgeTools !== "none") {
312
317
  registerBridgeServer({ pid: process.pid, port: mcpHandle.port, token: mcpHandle.realmToken, tokenHeader: TOKEN_HEADER });
313
318
  }
314
319
  return undefined;
@@ -686,6 +691,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
686
691
  onNativeEvent,
687
692
  onNativeBackground: (info) => armConversationWatcher(info.conversationId, info.turnStartMs),
688
693
  roster,
694
+ gateUnavailable: () => gateUnavailable,
689
695
  pendingCompactionHandoff,
690
696
  hasActiveTool: (name) => pi.getActiveTools().includes(name),
691
697
  engine,
@@ -985,10 +991,18 @@ export default async function (pi: ExtensionAPI): Promise<void> {
985
991
  sweepStaleBridgeDirs();
986
992
  sweepStagedAgyHomes();
987
993
  // Start the bridge unless the user turned it off. No patch gate, no
988
- // consent flow: calls route through pi's normal toolUse loop.
994
+ // consent flow: calls route through pi's normal toolUse loop. The
995
+ // approval gate rides the same listener, so an active gate keeps it
996
+ // running even with bridgeTools "none" (no pi tools are listed):
997
+ // hiding pi tools from agy must never un-gate agy's native tools.
989
998
  const bridgeMode: BridgeTools = loadConfig().bridgeTools;
990
- if (bridgeMode === "none") return; // user opted out
999
+ // One resolution per session_start: the staging block below must gate
1000
+ // on the SAME verdict, or a mid-start flip leaves the gate unstaged
1001
+ // while gateUnavailable says pending (every turn refused until restart).
1002
+ const gateMode = resolveGateMode(loadConfig().approvals.gateMode, detectPermissionGateExtensions());
991
1003
  if (mcpHandle) return; // already running (reload re-fires session_start)
1004
+ gateUnavailable = gateMode === "off" ? undefined : "approval gate not staged yet";
1005
+ if (bridgeMode === "none" && gateMode === "off") return; // user opted out
992
1006
  // pi loads project skill locations only after the project is trusted;
993
1007
  // mirror that gate. Global skill dirs are always scanned.
994
1008
  const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? { projectDir: process.cwd() } : {});
@@ -1118,7 +1132,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1118
1132
  // stream-json skips the global file entirely when the isolated home
1119
1133
  // is active (issue #14): this session's bridge rides the staged
1120
1134
  // config instead, so no other agy on the machine can see or call it.
1121
- if (engine === "stream-json" && !streamHome.isolated) {
1135
+ // bridgeTools "none" skips it too: with no pi tools exposed, a global
1136
+ // entry would only announce the listener to agy processes the user
1137
+ // opted out of; the gate needs no registration (its hook rides the
1138
+ // session's own add-dir).
1139
+ if (engine === "stream-json" && !streamHome.isolated && bridgeMode !== "none") {
1122
1140
  if (r.first) {
1123
1141
  registerBridgeServer({
1124
1142
  pid: process.pid,
@@ -1150,7 +1168,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1150
1168
  // enabled (auto = on only when a third-party gate extension exists).
1151
1169
  {
1152
1170
  const cfg = loadConfig();
1153
- const mode = resolveGateMode(cfg.approvals.gateMode, detectPermissionGateExtensions());
1171
+ const mode = gateMode;
1154
1172
  gateActive = mode !== "off";
1155
1173
  if (mode !== "off" && engine === "acp") {
1156
1174
  // Staged-home hook delivery is probe-verified on agy 1.5.12
@@ -1210,11 +1228,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1210
1228
  // pi.getAllTools() is unusable here: it returns ToolInfo, which
1211
1229
  // strips execute. Marker calls never execute; non-marker calls
1212
1230
  // delegate to the twins, so behavior matches the standard
1213
- // builtins (session-level bash-operations overrides are not
1214
- // inherited; documented in README).
1231
+ // builtins. The shadow replaces bash for EVERY model, so the
1232
+ // twin gets the same shellCommandPrefix/shellPath settings pi
1233
+ // gives its own bash (session-level bash-operations overrides
1234
+ // are still not inherited; documented in README).
1215
1235
  const gateCwd = process.cwd();
1216
1236
  const bases: Record<string, AnyToolDefinition> = {
1217
- bash: createBashToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1237
+ bash: createBashToolDefinition(gateCwd, bashSettingsOptions(pi)) as unknown as AnyToolDefinition,
1218
1238
  write: createWriteToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1219
1239
  edit: createEditToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1220
1240
  };
@@ -1254,9 +1274,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1254
1274
  // approval toolUse must never dispatch to the REAL builtin and
1255
1275
  // execute locally.
1256
1276
  roundTrips.approvalPark = handle.approvals;
1277
+ gateUnavailable = undefined;
1257
1278
  }
1258
1279
  }
1259
1280
  } else {
1281
+ if (gateUnavailable) gateUnavailable = `MCP listener failed: ${r.reason}`;
1260
1282
  console.error(`[antigravity-bridge] MCP tool bridge disabled: ${r.reason}`);
1261
1283
  }
1262
1284
  });
@@ -1827,7 +1849,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1827
1849
  );
1828
1850
  }
1829
1851
  } else {
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");
1852
+ 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: no pi tools (an active approval gate still runs the listener gate-only).`, "info");
1831
1853
  }
1832
1854
  return;
1833
1855
  }
@@ -2016,7 +2038,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2016
2038
  id: "bridge",
2017
2039
  label: "Bridge tools",
2018
2040
  description:
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.",
2041
+ "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: no pi tools (an active approval gate still runs the listener gate-only).",
2020
2042
  currentValue: config.bridgeTools,
2021
2043
  values: ["all", "mcp", "codemode", "none"],
2022
2044
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.15.0",
3
+ "version": "1.15.2",
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",
@@ -22,6 +22,9 @@
22
22
  //
23
23
  // Run: npm test
24
24
 
25
+ import os from "node:os";
26
+ import path from "node:path";
27
+ import { fileURLToPath } from "node:url";
25
28
  import type {
26
29
  AgentToolResult,
27
30
  AgentToolUpdateCallback,
@@ -231,3 +234,35 @@ export function createShadowTool(base: AnyToolDefinition, policy: GatePolicy, op
231
234
  };
232
235
  return { ...base, parameters: withGateMarkerSchema(base.parameters), execute } as AnyToolDefinition;
233
236
  }
237
+
238
+ /** The shell options pi passes its own bash tool (shellCommandPrefix,
239
+ * shellPath), read from the session's effective settings. The bash shadow
240
+ * replaces pi's bash for every model, so its twin must run commands the same
241
+ * way. pi expands a leading "~" and file:// URLs in shellPath; mirror that. Hosts without
242
+ * pi.getSettings keep the previous option-less twin, and any throw degrades
243
+ * to the same: the twin is built after the gate hooks are staged, so a
244
+ * throw here would leave a required gate unstaged and refuse every turn
245
+ * over what is only shell fidelity. */
246
+ export function bashSettingsOptions(pi: {
247
+ getSettings?: () => { shellCommandPrefix?: string; shellPath?: string };
248
+ }): { commandPrefix?: string; shellPath?: string } {
249
+ if (typeof pi.getSettings !== "function") return {};
250
+ try {
251
+ const { shellCommandPrefix, shellPath } = pi.getSettings();
252
+ const home = os.homedir();
253
+ const expanded =
254
+ shellPath === "~"
255
+ ? home
256
+ : shellPath?.startsWith("~/")
257
+ ? path.join(home, shellPath.slice(2))
258
+ : shellPath?.startsWith("file://")
259
+ ? fileURLToPath(shellPath)
260
+ : shellPath;
261
+ return {
262
+ ...(shellCommandPrefix ? { commandPrefix: shellCommandPrefix } : {}),
263
+ ...(expanded ? { shellPath: expanded } : {}),
264
+ };
265
+ } catch {
266
+ return {};
267
+ }
268
+ }
@@ -1,9 +1,10 @@
1
1
  // Staging for the approval-gate hooks.json (docs/TODO.md 2.5).
2
2
  //
3
3
  // The agy CLI discovers `.agents/hooks.json` in its --add-dir directories
4
- // (live-probed 2026-09-22: stream-json and interactive sessions load and
5
- // execute PreToolUse hooks from any add-dir; print mode reads only the
6
- // global config) and fires them before a gated tool runs (V2: deny
4
+ // (live-probed 2026-09-22 for stream-json and interactive sessions, and
5
+ // 2026-11-25 on agy 1.5.17 for print mode `-p`, which also loads and
6
+ // executes add-dir hooks - an earlier note here claimed print mode read
7
+ // only the global config) and fires them before a gated tool runs (V2: deny
7
8
  // honored, reason reaches the model; V3: hook TIMEOUT = soft-pass, agy
8
9
  // proceeds ungated). Therefore:
9
10
  // - the staged handler timeout must exceed the whole park budget with
package/src/ask-tool.ts CHANGED
@@ -42,6 +42,9 @@ import {
42
42
  type Mode,
43
43
  } from "@estebanforge/pi-ask-shared";
44
44
  import { extensionsDataDir, loadConfig, type AgyMode, type ThinkingTier } from "./config.js";
45
+ import { detectPermissionGateExtensions, resolveGateMode } from "./approval-detect.js";
46
+ import { gateHooksStaged } from "./approval-hook.js";
47
+ import { bridgeMcpConfigDir } from "./mcp-server.js";
45
48
  import { redactText } from "./redact.js";
46
49
  import { acquireBridgeSuppression } from "./mcp-registration.js";
47
50
  import { AGY_EFFORT_ORDER, spawnAgyModelsRaw, toAgyEffort } from "./models.js";
@@ -825,6 +828,20 @@ export async function registerAskAntigravityTool(
825
828
  details: emptyDetails(),
826
829
  };
827
830
  }
831
+ // Provider-parity gate wiring: the delegated spawn must ride the staged gate (driver.ts adds it to every turn) or AskAntigravity is an ungated spawn path around it; gateHooksStaged implies a live listener (a failed listener never stages).
832
+ const gateWanted =
833
+ resolveGateMode(config.approvals.gateMode, detectPermissionGateExtensions()) !== "off";
834
+ if (gateWanted && !gateHooksStaged()) {
835
+ return {
836
+ content: [
837
+ {
838
+ type: "text",
839
+ text: "Error: the approval gate is required but not staged for this session, so a delegated agy run would bypass it. Restart pi and check /agy doctor; if the problem persists, set approvals.gateMode to off.",
840
+ },
841
+ ],
842
+ details: emptyDetails(),
843
+ };
844
+ }
828
845
  const requestedModel = (params.model as string | undefined) ?? config.defaultModel;
829
846
  if (typeof params.model === "string" && params.model.trim().startsWith("-")) {
830
847
  return {
@@ -964,7 +981,10 @@ export async function registerAskAntigravityTool(
964
981
  skipPermissions: config.skipPermissions !== false,
965
982
  conversationId: isContinuation ? (rawConvId as string) : null,
966
983
  timeoutMinutes: timeoutMin,
967
- addDirs: contextFile ? [askContextDir()] : [],
984
+ addDirs: [
985
+ ...(contextFile ? [askContextDir()] : []),
986
+ ...(gateWanted ? [bridgeMcpConfigDir()] : []),
987
+ ],
968
988
  extraArgs: extraArgs(),
969
989
  prompt: effectivePrompt,
970
990
  });
package/src/provider.ts CHANGED
@@ -88,6 +88,15 @@ export function _resetObservationalMemoryWarnedForTesting(): void {
88
88
  * each other's files. */
89
89
  const stagedAgentByConversation = new Map<string, string>();
90
90
 
91
+ /** Per-session mid-park steering cursor: the context length the current turn
92
+ * was dispatched with, and the transcript index past the last steer actually
93
+ * delivered to agy. The moving first-pending-toolResult anchor alone misses
94
+ * a steer that landed during an EARLIER park of a park chain: the anchor
95
+ * moves to the newer park's toolResult, which sits after the steer, and the
96
+ * settle claims it undelivered. Absent (pi restart mid-turn) the provider
97
+ * falls back to the anchor rule. */
98
+ const steerCursors = new Map<string, { dispatchedAt: number; deliveredThrough: number }>();
99
+
91
100
  /** Zero-usage helper. agy doesn't expose token counts; pi's cost math gets
92
101
  * zeros (we're not billing through this provider). */
93
102
  function zeroUsage(): Usage {
@@ -375,9 +384,9 @@ const ACP_DIGEST_MAX_CHARS = 24_000;
375
384
  /** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
376
385
  * the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
377
386
  * and the dropped turn leaves the conversation permanently unresponsive. */
378
- const STREAM_JSON_PROMPT_CAP = 25_000;
387
+ export const STREAM_JSON_PROMPT_CAP = 25_000;
379
388
  /** Headroom under the cap for the staged-image note and prompt framing. */
380
- const STREAM_JSON_PROMPT_MARGIN = 4_096;
389
+ export const STREAM_JSON_PROMPT_MARGIN = 4_096;
381
390
 
382
391
  /** Per-engine digest cap. ACP ships the digest as an embeddedContext
383
392
  resource block: no prompt cap applies, so the probe-raised cap stands.
@@ -679,6 +688,11 @@ export interface StreamSimpleDeps {
679
688
  onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
680
689
  /** Subagent roster (both engines); folded from every activity. */
681
690
  roster?: SubagentRoster;
691
+ /** Why the approval gate this session requires is not staged, or
692
+ * undefined when it is staged or not required. A set reason refuses
693
+ * provider turns: an unstaged gate would let agy's native tools run
694
+ * without the pi-side approval the config asked for. */
695
+ gateUnavailable?: () => string | undefined;
682
696
  /** Session keys rotated on `session_compact` awaiting a one-shot
683
697
  * compaction handoff into a fresh agy conversation. */
684
698
  pendingCompactionHandoff?: Set<string>;
@@ -1364,6 +1378,57 @@ export interface LateToolResult {
1364
1378
  images?: Array<{ data: string; mimeType: string }>;
1365
1379
  }
1366
1380
 
1381
+ export interface SteeredUserMessage {
1382
+ /** Transcript index of the message; the watermark hold on a failed
1383
+ * delivery claims up to this index. */
1384
+ index: number;
1385
+ text: string;
1386
+ images: Array<{ data: string; mimeType: string }>;
1387
+ }
1388
+
1389
+ /** User messages pi delivered into the context after the steering floor: pi's
1390
+ * steering poll runs right after tool results, so a message typed while agy
1391
+ * was parked joins the transcript but the continuation pass re-attaches to
1392
+ * the parked turn and sends no new user event (Baluard 2026-11-25: the
1393
+ * message sat in the transcript, agy never saw it, and pi's drained queue
1394
+ * never re-triggered - the turn just ended). The floor is the session's
1395
+ * steering cursor (dispatch length + delivered-through); without one (pi
1396
+ * restart mid-turn) it falls back to the first still-pending toolResult's
1397
+ * index, whose everything-before belongs to the parked turn's dispatched
1398
+ * prompt. Backlog shapes (compaction/branch/bash runs) never count as
1399
+ * steering. Pure; exported for tests. */
1400
+ export function collectSteeredUserMessages(messages: Message[], pendingIds: readonly string[], floor?: number): SteeredUserMessage[] {
1401
+ if (pendingIds.length === 0) return [];
1402
+ let start: number;
1403
+ if (floor !== undefined) {
1404
+ start = floor;
1405
+ } else {
1406
+ const pending = new Set(pendingIds);
1407
+ let anchor = -1;
1408
+ for (let i = 0; i < messages.length; i++) {
1409
+ const m = messages[i];
1410
+ if (m.role !== "toolResult") continue;
1411
+ const id = (m as { toolCallId?: string }).toolCallId;
1412
+ if (id && pending.has(id)) {
1413
+ anchor = i;
1414
+ break;
1415
+ }
1416
+ }
1417
+ if (anchor < 0) return [];
1418
+ start = anchor + 1;
1419
+ }
1420
+ const out: SteeredUserMessage[] = [];
1421
+ for (let i = start; i < messages.length; i++) {
1422
+ const m = messages[i];
1423
+ if (m.role !== "user") continue;
1424
+ if (isBacklogUserShape(blocksToText(m.content))) continue;
1425
+ const parts = lastMessageParts(m);
1426
+ if (!parts.text && parts.images.length === 0) continue;
1427
+ out.push({ index: i, text: parts.text ?? "", images: parts.images });
1428
+ }
1429
+ return out;
1430
+ }
1431
+
1367
1432
  /** Frame late tool results so agy treats them as the results its bridge calls
1368
1433
  * never received: a park whose round-trip died while the pi tool ran, or an
1369
1434
  * escalated result the model never polled. The reason carries the framing. */
@@ -1668,6 +1733,22 @@ async function runTurnDriver(
1668
1733
  // agy receives the result via the bridge's MCP HTTP response.
1669
1734
  const results = collectToolResults(context.messages, deps.roundTrips.pendingIds);
1670
1735
  const isContinuation = results.length > 0;
1736
+ // Scanned before the resolve loop: the pending set must still contain the
1737
+ // parks being resolved. The steering floor is the session's dispatch
1738
+ // cursor when one exists (dispatch length + delivered-through), else the
1739
+ // first-pending-toolResult anchor fallback.
1740
+ const steerCursor = steerCursors.get(key);
1741
+ const steered = ephemeral
1742
+ ? []
1743
+ : collectSteeredUserMessages(
1744
+ context.messages,
1745
+ deps.roundTrips.pendingIds,
1746
+ steerCursor ? Math.max(steerCursor.dispatchedAt, steerCursor.deliveredThrough) : undefined,
1747
+ );
1748
+ // Set when a steer leads the dead-turn fallback into a fresh dispatch: the
1749
+ // steer shipped as that dispatch's own prompt, so the post-outcome sweep
1750
+ // must stay off (and its stranded-claim re-sweep with it).
1751
+ let steerLedFresh = false;
1671
1752
  // Escalated calls answer through bridge_poll_result, not through an agy
1672
1753
  // turn waiting on the park, so note them before resolving.
1673
1754
  const escalatedNames = results
@@ -1798,7 +1879,13 @@ async function runTurnDriver(
1798
1879
  // Dead turn: claim NOW (single-use). A live turn claims after outcome
1799
1880
  // instead — claiming here would eat the post-outcome recovery.
1800
1881
  if (!ephemeral) late.push(...collectStranded());
1801
- if (isContinuation && late.length === 0) {
1882
+ // A steer with a bound conversation leads the fresh dispatch instead of
1883
+ // stopping quietly: the trailing user run becomes the prompt, so the
1884
+ // message is answered rather than dropped or left to the digest window.
1885
+ // The sweep below must not re-deliver what that dispatch just shipped.
1886
+ const steerCanLead = steered.length > 0 && Boolean(existing?.conversationId);
1887
+ if (isContinuation && late.length === 0 && steerCanLead) steerLedFresh = true;
1888
+ if (isContinuation && late.length === 0 && !steerCanLead) {
1802
1889
  if (escalatedNames.length === 0) {
1803
1890
  deps.log?.("turn-error", { reason: "tool-result-no-active-turn" }, "warn");
1804
1891
  finalize(stream, blocks, "error", "tool result arrived but no antigravity turn is running");
@@ -1924,6 +2011,14 @@ async function runTurnDriver(
1924
2011
  // contract, and the settle bypasses the digest store writes. Legacy
1925
2012
  // paths (late/strand redelivery, retry-dropped resume, post-compaction
1926
2013
  // resume) and the churn latch stay on the digest flow.
2014
+ // A fresh dispatch of the trailing user run opens a new steering window:
2015
+ // everything up to here is the prompt the turn carries, so mid-park
2016
+ // steers must land strictly after this index. Synthetic prompts (late
2017
+ // strands, resume, compaction seeding) do NOT open one - their context
2018
+ // may still hold undelivered steers.
2019
+ if (!resume && !compactionResume && late.length === 0) {
2020
+ steerCursors.set(key, { dispatchedAt: messageCount, deliveredThrough: 0 });
2021
+ }
1927
2022
  const handoffRuntime = deps.handoffRuntime;
1928
2023
  const syncTurnRequested = config.handoff === "sync" && engine === "acp";
1929
2024
  if (
@@ -2353,38 +2448,89 @@ async function runTurnDriver(
2353
2448
  // fix: sweep and deliver as a late run in the same conversation. Single
2354
2449
  // shot: claims are single-use, so a re-delivered strand cannot reappear
2355
2450
  // here; a late run that parks hands recovery to the next pi pass.
2451
+ // A late-start failure must invalidate the sync contract below: its
2452
+ // checkpoint would claim the steer agy never received.
2453
+ let lateStartFailed = false;
2356
2454
  if (!ephemeral && isContinuation && outcome.status === "OK" && !outcome.aborted) {
2357
- const more = collectStranded();
2358
- if (more.length > 0) {
2455
+ const more = steerLedFresh ? [] : collectStranded();
2456
+ // Steered messages join the same late run: pi delivered them into the
2457
+ // context while the turn was parked and the reentry pass sent nothing
2458
+ // to agy, so this sweep is the only delivery window left.
2459
+ if (!steerLedFresh && (more.length > 0 || steered.length > 0)) {
2359
2460
  const conv = redeliveryConversation ?? outcome.conversationId ?? existing?.conversationId ?? null;
2360
- deps.log?.("escalated-redelivery-turn", { tools: more.map((s) => s.name), conversation: conv }, "info");
2361
- const moreImages = more.flatMap((s) => s.images ?? []);
2362
- try {
2363
- const lateHandle = await deps.driver.run({
2364
- cwd,
2365
- model: agyModel,
2366
- effort,
2367
- mode: config.mode,
2368
- skipPermissions: config.skipPermissions,
2369
- timeoutMin: config.turnTimeoutMin,
2370
- inactivityMin: config.inactivityTimeoutMin,
2371
- conversationId: conv,
2372
- prompt: buildLateResultPrompt(more) + stageImageNote(moreImages),
2373
- images: moreImages.length > 0 ? moreImages : undefined,
2374
- agent: config.agent ?? (conv ? stagedAgentByConversation.get(conv) : undefined),
2375
- signal: options?.signal,
2376
- });
2377
- if ((await drainTurn(lateHandle)) === "parked") return;
2378
- outcome = await lateHandle.outcome;
2379
- } catch (err) {
2380
- // Release the claims so the next pass can retry the delivery.
2381
- for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
2461
+ const steerText = steered.map((s) => s.text).filter(Boolean).join("\n\n");
2462
+ const latePrompt = more.length > 0 ? buildLateResultPrompt(more, steerText || undefined) : steerText;
2463
+ // stream-json silently drops any prompt past the cap (issue #2) and
2464
+ // the dropped turn leaves the conversation unresponsive: slice the
2465
+ // steer visibly instead of killing it.
2466
+ const lateBudget = STREAM_JSON_PROMPT_CAP - STREAM_JSON_PROMPT_MARGIN;
2467
+ let deliveredLatePrompt = latePrompt;
2468
+ if ((deps.engine ?? config.engine) !== "acp" && Buffer.byteLength(latePrompt, "utf8") > lateBudget) {
2469
+ deliveredLatePrompt = `[truncated]\n${Buffer.from(latePrompt, "utf8").subarray(0, Math.max(0, lateBudget - 32)).toString("utf8")}`;
2382
2470
  deps.log?.(
2383
- "turn-error",
2384
- { reason: "redelivery-start-failed", error: err instanceof Error ? err.message : String(err) },
2385
- "error",
2471
+ "turn-warning",
2472
+ { reason: "steer-prompt-truncated", bytes: Buffer.byteLength(latePrompt, "utf8"), budget: lateBudget },
2473
+ "warn",
2386
2474
  );
2387
2475
  }
2476
+ const moreImages = [...more.flatMap((s) => s.images ?? []), ...steered.flatMap((s) => s.images)];
2477
+ deps.log?.(
2478
+ "steered-redelivery-turn",
2479
+ { tools: more.map((s) => s.name), steered: steered.length, conversation: conv },
2480
+ "info",
2481
+ );
2482
+ if (!conv) {
2483
+ // Unbindable: a brand-new conversation would answer the steer with
2484
+ // zero context. Release the claims and hold the watermark - the
2485
+ // digest re-offers the steer once a conversation is bound.
2486
+ for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
2487
+ lateStartFailed = true;
2488
+ if (steered.length > 0) {
2489
+ nextCount = steered[0].index;
2490
+ nextBoundary = boundaryFingerprint(context.messages[steered[0].index - 1]);
2491
+ }
2492
+ deps.log?.("turn-warning", { reason: "steer-redelivery-unbound", steered: steered.length }, "warn");
2493
+ } else {
2494
+ try {
2495
+ const lateHandle = await deps.driver.run({
2496
+ cwd,
2497
+ model: agyModel,
2498
+ effort,
2499
+ mode: config.mode,
2500
+ skipPermissions: config.skipPermissions,
2501
+ timeoutMin: config.turnTimeoutMin,
2502
+ inactivityMin: config.inactivityTimeoutMin,
2503
+ conversationId: conv,
2504
+ prompt: deliveredLatePrompt + stageImageNote(moreImages),
2505
+ images: moreImages.length > 0 ? moreImages : undefined,
2506
+ agent: config.agent ?? (conv ? stagedAgentByConversation.get(conv) : undefined),
2507
+ signal: options?.signal,
2508
+ });
2509
+ // Accepted by agy from here on: a parked late run hands
2510
+ // recovery to the next pass, which must not re-collect it.
2511
+ const cursor = steerCursors.get(key);
2512
+ if (cursor && steered.length > 0) cursor.deliveredThrough = steered[steered.length - 1].index + 1;
2513
+ if ((await drainTurn(lateHandle)) === "parked") return;
2514
+ outcome = await lateHandle.outcome;
2515
+ } catch (err) {
2516
+ // Release the claims so the next pass can retry the delivery.
2517
+ for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
2518
+ // A steer has no registry to re-arm, only the digest window: hold
2519
+ // the watermark AND the boundary fingerprint at the first
2520
+ // undelivered message, or the next turn reads the mismatched
2521
+ // boundary as a mutated transcript and resets to full history.
2522
+ lateStartFailed = true;
2523
+ if (steered.length > 0) {
2524
+ nextCount = steered[0].index;
2525
+ nextBoundary = boundaryFingerprint(context.messages[steered[0].index - 1]);
2526
+ }
2527
+ deps.log?.(
2528
+ "turn-error",
2529
+ { reason: "redelivery-start-failed", error: err instanceof Error ? err.message : String(err) },
2530
+ "error",
2531
+ );
2532
+ }
2533
+ }
2388
2534
  }
2389
2535
  }
2390
2536
  // Sync settle: the orchestrator owns the record write (zeroed contract),
@@ -2411,7 +2557,10 @@ async function runTurnDriver(
2411
2557
  })();
2412
2558
  const result = settleSync.finish(
2413
2559
  {
2414
- ok: outcome.status === "OK",
2560
+ // A late-start failure leaves the steer undelivered: a terminal
2561
+ // checkpoint would claim it. Invalidate so the next turn re-plans
2562
+ // and the rebuild re-ships the steer as the newest user entry.
2563
+ ok: outcome.status === "OK" && !lateStartFailed,
2415
2564
  conversationId: outcome.conversationId ?? null,
2416
2565
  aborted: outcome.aborted,
2417
2566
  promptAttempted: outcome.promptAttempted,
@@ -2591,6 +2740,19 @@ export function createStreamSimple(
2591
2740
  );
2592
2741
  return stream;
2593
2742
  }
2743
+ const gateMissing = deps.gateUnavailable?.();
2744
+ if (gateMissing) {
2745
+ const partial = newAssistant(model);
2746
+ const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
2747
+ deps.log?.("turn-error", { reason: "approval-gate-unavailable" }, "warn");
2748
+ finalize(
2749
+ stream,
2750
+ blocks,
2751
+ "error",
2752
+ `The approval gate is required but not active (${gateMissing}), so agy's native tools would run without pi-side approval. Restart pi; /agy doctor shows the bridge state.`,
2753
+ );
2754
+ return stream;
2755
+ }
2594
2756
  if (selected && roundTrips) {
2595
2757
  void runTurnDriver(stream, model, context, options, entries, store, {
2596
2758
  driver: selected,
package/src/runtime.ts CHANGED
@@ -236,7 +236,7 @@ class Realm implements BridgeRealm {
236
236
  onApproval(ticket, payload);
237
237
  return;
238
238
  }
239
- this.#server?.approvals.resolve(ticket, { allow: false, reason: `approval gate: ${this.#unattributed()}` });
239
+ this.#server?.approvals.resolve(ticket, { allow: false, reason: this.#unroutableApproval() });
240
240
  },
241
241
  };
242
242
 
@@ -253,6 +253,15 @@ class Realm implements BridgeRealm {
253
253
  return open.length > 1 ? SEVERAL_TURNS : NO_TURN;
254
254
  }
255
255
 
256
+ // The deny reaches delegated `agy -p` runs too once they carry the staged
257
+ // gate dir, so this text is written for that reader, not the provider.
258
+ #unroutableApproval(): string {
259
+ const open = [...this.#members].filter((m) => m.bridge && m.port.hasActiveTurn());
260
+ return open.length > 1
261
+ ? `approval gate: ${SEVERAL_TURNS}`
262
+ : "approval gate: no antigravity turn is streaming, so this delegated run's mutating tool call cannot reach a pi-side approval and is denied; run the mutating step inside an antigravity turn, or set approvals.gateMode off";
263
+ }
264
+
256
265
  #log(event: string, data?: unknown): void {
257
266
  const sink = [...this.#members].find((m) => m.log)?.log;
258
267
  if (!sink) return;