@estebanforge/pi-antigravity-bridge 1.15.1 → 1.16.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,30 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.16.0] - 2026-11-26
6
+
7
+ ### Changed
8
+
9
+ - ACP-first catalog: on ACP (the default engine), `bridgeTools: "all"` now declares pi's default builtins (read, ls, grep, find, edit, write, bash) directly in the bridge catalog (each active builtin individually; the prompt note additionally requires bash), and the system prompt gains an ACP note - shipped only when bash is active in pi - steering anything longer than a minute onto the bridge bash. On ACP, agy's native tool calls execute agy-side (provider Gate C), so without direct declarations pi's tools were unreachable pi-side and a silent native command longer than five minutes was killed by the stall guard with no result (observed live 2026-11-26: a 10-minute sleep ran as a native execute and died at 5m32s). Admission is limited to the seven default builtins; an active codemode builtin stays codemode-mode-only on both engines. The stream-json CATALOG is unchanged (it keeps the builtin-free fallback contract); engine-wide behavior does touch it: the reworded tool-priority note, the 110s poll window, and the turn-end handoff apply on both engines, so the staged stream-json agent file re-stages once. On stream-json native commands also run agy-side and long silent ones still die at pi's idle cap (issue #21). The poll/escalation/handoff machinery covers MCP-routed calls on both engines. `bridgedPiTools` takes a required engine parameter. Security note: bridged tools execute pi-side and are not gated by `approvals.mode` or `skipPermissions` (pre-existing for extension tools; now also true for bash/edit/write on ACP) - with `skipPermissions: false` and no pi permission extension, native agy tools prompt or deny while bridged builtins do not.
10
+ - After three still-running `bridge_poll_result` answers, the next answer arms a turn-end handoff: the model is told to stop polling and end its turn, and the settled result is delivered through the existing strand sweep as the next message (issue #29 follow-up: a 30-minute human-gated park now costs a handful of inference calls instead of one per minute). The ack and system-priority note license that exit only when a poll answer arms it; ending the turn on the model's own initiative still strands the result, and the late-delivery reason text is now neutral for both paths (`POLL_HANDOFF_AFTER`, `tests/poll-wait.test.ts`). Live-verified on ACP 2026-11-26 with a real agy (call-tool-escalated → four polls → poll-handoff → turn end → escalated-redelivery → the model continued and reported the late-delivered result verbatim); the machinery is provider-level and engine-agnostic, but the handoff itself has not been exercised live on stream-json (the stream-json smoke was blocked by upstream quota); an aborted poll never counts toward the cap, and serving the handoff logs a `poll-handoff` event so live sessions can prove it.
11
+ - `bridge_poll_result` now long-waits up to 110s for the call to settle instead of answering `STILL RUNNING` immediately (issue #29: the model burned an LLM turn per poll on multi-minute commands). Settle wakes the held request instantly, so a 40s command costs one poll instead of dozens, and a still-running call answers about once every two minutes. The poll tool description and the ack text now tell the model to poll again immediately, since each poll blocks up to 110s. `failAll` does not settle escalated entries, so an abandoned poll wakes via its request abort or the window (`tests/poll-wait.test.ts`).
12
+ - ACP sessions show session-cumulative cache telemetry in the usage status line (`· cache 91% · 14 calls`, from `PromptResponse.usage` after overflow clamping; the count is pi assistant messages, not raw model calls) and log one `turn-usage` event per turn with the turn's call count and cache ratio (visible in the daily log only with `AGY_DEBUG`, and only when the usage status line is enabled). Probed 2026-11-26 (agy 1.5.17): a per-server `timeout` field in `mcp_config.json` parses but is not honored, so the ~180s tools/call wall stays hard upstream and escalation remains necessary.
13
+
14
+ ## [1.15.2] - 2026-11-25
15
+
16
+ ### Fixed
17
+
18
+ - 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.
19
+ - `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.
20
+ - 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.
21
+ - The shadow `bash` twin resolves a `file://` `shellPath` the way pi does.
22
+ - 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).
23
+ - 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.
24
+ - 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.
25
+ ### Changed
26
+
27
+ - 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.
28
+
5
29
  ## [1.15.1] - 2026-11-25
6
30
 
7
31
  ### Fixed
package/README.md CHANGED
@@ -40,13 +40,17 @@ The bridge starts a localhost MCP server inside pi's process. The exposed catalo
40
40
 
41
41
  **Upstream pi APIs only.** Bridge calls park in the provider's round-trip store; the provider ends the pi assistant message with a `toolUse` stop reason for the real pi tool, pi executes it in its own loop (native cards, permissions, hooks), and the toolResult completes the parked MCP response on the next stream call.
42
42
 
43
- **Long calls don't die.** agy's MCP client abandons a `tools/call` request at a flat ~180s, which used to kill any pi tool that ran longer (a long peer review, a build, a commit preview waiting for you). A call still running after ~20 seconds now settles its HTTP request with a `STILL RUNNING` answer carrying a `callId` while pi keeps executing; agy fetches the result through the bridge-local `bridge_poll_result` tool and polls until it lands. Delegation-shaped tools (pi subagent/delegation tools, e.g. `subagent_run`, `agent_spawn`) hold the synchronous window 120s instead (issue #6: orchestrators expect a plain result across the 30-120s subagent range, and 120s stays under the 180s wall); `escalateLongTools` in config.json adds custom names. Escalated calls get their own 30-minute budget, so human-gated tools can take as long as the human takes. Fast calls stay fully synchronous and never see any of this. If a park does fail (abort, timeout, recycle), the late result is re-routed to agy as a follow-up prompt in the same conversation instead of being lost. If pi retries a failed turn and drops the attempt from the projected context (pi core `_omitRecoveryAttempt`), leaving a toolResult or assistant tail with no live turn, the provider re-opens the bound conversation with a synthetic resume prompt instead of the unretryable "No user message" hard error (issue #8); a first-ever turn that parks binds its conversation at park time, so a retry-dropped tail has a conversation to resume into unless the park produced no conversation id or the later failure proved the conversation dead. Consecutive polls render as ONE ♊︎-marked counted line (`♊︎ bridge_poll_result Poll git_commit (x30)`) instead of one entry per poll, with a live muted status counter while a run is open.
43
+ **Long calls don't die.** agy's MCP client abandons a `tools/call` request at a flat ~180s, which used to kill any pi tool that ran longer (a long peer review, a build, a commit preview waiting for you). A call still running after ~20 seconds now settles its HTTP request with a `STILL RUNNING` answer carrying a `callId` while pi keeps executing; agy fetches the result through the bridge-local `bridge_poll_result` tool, which now waits up to 110s for the settle before reporting `STILL RUNNING` again (issue #29: an immediate answer made agy burn an LLM turn per poll; settle wakes the held request instantly, so a 40s command costs one poll instead of dozens) and polls until it lands. After three still-running answers the poll answer arms a handoff: the model is told to end its turn, and the settled result is delivered as the next message through the strand sweep, so a 30-minute human-gated park costs a handful of calls instead of one per minute. Delegation-shaped tools (pi subagent/delegation tools, e.g. `subagent_run`, `agent_spawn`) hold the synchronous window 120s instead (issue #6: orchestrators expect a plain result across the 30-120s subagent range, and 120s stays under the 180s wall); `escalateLongTools` in config.json adds custom names. Escalated calls get their own 30-minute budget, so human-gated tools can take as long as the human takes. Fast calls stay fully synchronous and never see any of this. If a park does fail (abort, timeout, recycle), the late result is re-routed to agy as a follow-up prompt in the same conversation instead of being lost. If pi retries a failed turn and drops the attempt from the projected context (pi core `_omitRecoveryAttempt`), leaving a toolResult or assistant tail with no live turn, the provider re-opens the bound conversation with a synthetic resume prompt instead of the unretryable "No user message" hard error (issue #8); a first-ever turn that parks binds its conversation at park time, so a retry-dropped tail has a conversation to resume into unless the park produced no conversation id or the later failure proved the conversation dead. Consecutive polls render as ONE ♊︎-marked counted line (`♊︎ bridge_poll_result Poll git_commit (x30)`) instead of one entry per poll, with a live muted status counter while a run is open.
44
44
 
45
45
  **Session isolation.** Both engines keep their agy in a private MCP home with every global `pi-bridge` and `pi-bridge-<pid>` entry filtered out (issue #14): ACP via per-session `mcpServers`, stream-json via the top-level `--gemini_dir` flag, which a quota-free capability probe verifies per agy version. If the running CLI refuses the flag or the home cannot be staged, stream-json falls back to the legacy global per-pid registration plus the delegation suppression machinery, with a one-time warning. The home shares CLI credentials, settings, and conversation state without inheriting another pi session's bridge.
46
46
 
47
+ **Engine split.** ACP is the primary engine; stream-json is the maintained fallback. The engines agree on one structural fact: on BOTH, agy's native tool calls execute agy-side (on ACP after a permission frame; on stream-json pi only re-executes read-only calls for card rendering and displays mutating ones through the wrapper). The escalation, poll long-wait, and turn-end handoff machinery covers MCP-routed bridge calls on both engines; a silent native command outlasting the idle guard dies on both (ACP: the bridge's 5-minute stall guard; stream-json: pi's idle cap, issue #21). The engines differ in the catalog: `bridgeTools: "all"` declares pi's default builtins (read, ls, grep, find, edit, write, bash) directly on ACP, making pi's tool surface reachable and long commands protectable; the stream-json CATALOG stays builtin-free (the fallback contract), though the engine-wide prompt note, 110s poll window, and turn-end handoff apply on both engines (the staged stream-json agent file re-stages once). The system prompt ships an ACP note (only when bash is actually active) steering anything longer than a minute onto the bridge bash. One asymmetry to know: bridged tools execute pi-side and are not gated by `approvals.mode` or `skipPermissions` (true for extension tools since the first bridge, and for bash/edit/write on ACP since this change); tighten pi-side with a permission extension or the approval gate if you need those gated too.
48
+
47
49
  **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
50
 
49
- **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.
51
+ **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.
52
+
53
+ **Cost / fan-out.** Every registered pi tool except the bridge's own internal tools is exposed (respecting the `bridgeTools` mode and any `/agy tools` hides; builtins ride along on ACP under `all`, where they are declared directly), 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
54
 
51
55
  **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.
52
56
 
@@ -117,9 +121,9 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
117
121
  | --- | --- | --- |
118
122
  | `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
119
123
  | `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` |
124
+ | `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; on ACP also pi's builtins - read, ls, grep, find, edit, write, bash - declared directly, since ACP's native tool calls execute agy-side and would otherwise bypass pi entirely), `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
125
  | `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
- | `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` |
126
+ | `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; on ACP with `bridgeTools: "all"` and bash active, an extra ACP note steers long commands onto the bridge bash (a silent native command past the stall guard is killed). 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
127
  | `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` |
124
128
  | `skipPermissions` | `true`: pass `--dangerously-skip-permissions` so agy tool calls never hang on an unanswerable prompt in non-interactive runs; DANGEROUS: agy executes commands without per-action review (see [Permissions](#permissions)). `false`: prompt instead - hangs any `run_command` in `-p` mode | `true` |
125
129
  | `turnTimeoutMin` | Overall cap on ONE agy turn, minutes, both engines. Parked time (pi-tool round-trips, escalated calls, human-gated approvals) does not count against it on either engine: the cap pauses with remaining-budget semantics and resumes on unpark. When it fires, the bridge kills the agy process mid-task ("ACP turn exceeded the 10m deadline" / "agy exceeded the 10m turn timeout") - it is a bridge cap, not a Google server limit. Default is TTY-aware: `0` (no cap) on an interactive pi - you are the backstop with Esc; `20` headless, where nobody can abort and one runaway turn blocks the serialized turn queue. Opt into a gate with 1-1440 (free type via `config.json` or `/agy timeout <1-1440|off>`, or the `/agy` picker's preset list); `0` disables explicitly; anything else falls back to the TTY-aware default. The 5m inactivity stall guard always still bounds a hung server | `0` TTY / `20` headless |
@@ -45,7 +45,7 @@ import {
45
45
  createStreamSimple,
46
46
  defaultEscalateAfterMs,
47
47
  formatEscalatedAck,
48
- formatPollAnswer,
48
+ answerPoll,
49
49
  rotateSessionOnCompaction,
50
50
  sessionKey,
51
51
  type NativeDisplayEvent,
@@ -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";
@@ -226,10 +227,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
226
227
  let realmSession: RealmSession | null = null;
227
228
  // Session-only visibility overrides; never change either application's MCP config.
228
229
  const hiddenBridgeTools = new Set<string>();
229
- const getBridgeTools = () => bridgedPiTools(pi.getAllTools(), pi.getActiveTools(), loadConfig().bridgeTools, hiddenBridgeTools);
230
+ const getBridgeTools = () => bridgedPiTools(pi.getAllTools(), pi.getActiveTools(), loadConfig().bridgeTools, hiddenBridgeTools, engine);
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;
@@ -532,21 +537,58 @@ export default async function (pi: ExtensionAPI): Promise<void> {
532
537
  // SDK's exact usage metadata before it reaches the client.
533
538
  if (engine === "acp") {
534
539
  let lastUsageStatus = "";
540
+ // Per-session usage accumulator. Replace-per-message, never sum-per-event:
541
+ // message_update refires with growing totals while an assistant message
542
+ // streams, so adding on every event would double-count.
543
+ const usageByMessage = new Map<number, { input: number; output: number; cacheRead: number }>();
544
+ let usageTurnStart = { calls: 0, input: 0, output: 0, cacheRead: 0 };
545
+ const usageSums = () => {
546
+ let input = 0;
547
+ let output = 0;
548
+ let cacheRead = 0;
549
+ for (const u of usageByMessage.values()) {
550
+ input += u.input;
551
+ output += u.output;
552
+ cacheRead += u.cacheRead;
553
+ }
554
+ return { input, output, cacheRead, calls: usageByMessage.size };
555
+ };
556
+ pi.on("agent_start", () => {
557
+ usageTurnStart = usageSums();
558
+ });
535
559
  pi.on("message_update", (event, ctx) => {
536
560
  if (!ctx.hasUI || event.message.role !== "assistant" || event.message.provider !== "antigravity" || loadConfig().acp.usageEstimate === "off") return;
537
- const { input, output } = event.message.usage;
538
- const status = ctx.ui.theme.fg("dim", `ACP ≈ ${input} in / ${output} out`);
561
+ const { input, output, cacheRead } = event.message.usage;
562
+ // AssistantMessage carries no id; the request-start timestamp is the
563
+ // per-inference key and is stable across streaming updates.
564
+ usageByMessage.set(event.message.timestamp, { input, output, cacheRead });
565
+ const sums = usageSums();
566
+ const cacheBase = sums.input + sums.cacheRead;
567
+ const cachePct = cacheBase > 0 ? Math.round((sums.cacheRead / cacheBase) * 100) : 0;
568
+ const status = ctx.ui.theme.fg("dim", `ACP ≈ ${input} in / ${output} out · cache ${cachePct}% · ${sums.calls} calls`);
539
569
  if (status !== lastUsageStatus) {
540
570
  lastUsageStatus = status;
541
571
  ctx.ui.setStatus("agy-usage", status);
542
572
  }
543
573
  });
544
574
  const clearUsageStatus = (_event: unknown, ctx: { hasUI: boolean; ui: ExtensionUIContext }) => {
575
+ const sums = usageSums();
576
+ const turn = {
577
+ calls: sums.calls - usageTurnStart.calls,
578
+ input: sums.input - usageTurnStart.input,
579
+ output: sums.output - usageTurnStart.output,
580
+ cacheRead: sums.cacheRead - usageTurnStart.cacheRead,
581
+ };
582
+ if (turn.calls > 0) {
583
+ const base = turn.input + turn.cacheRead;
584
+ fileLog.log("turn-usage", { ...turn, cachePct: base > 0 ? Math.round((turn.cacheRead / base) * 100) : 0 });
585
+ }
545
586
  lastUsageStatus = "";
546
587
  if (ctx.hasUI) ctx.ui.setStatus("agy-usage", undefined);
547
588
  };
548
589
  pi.on("agent_end", (event, ctx) => {
549
590
  clearUsageStatus(event, ctx);
591
+ usageByMessage.clear();
550
592
  pendingNativeTools = 0;
551
593
  closePollRun();
552
594
  if (ctx.hasUI) ctx.ui.setStatus("agy-native", undefined);
@@ -686,6 +728,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
686
728
  onNativeEvent,
687
729
  onNativeBackground: (info) => armConversationWatcher(info.conversationId, info.turnStartMs),
688
730
  roster,
731
+ gateUnavailable: () => gateUnavailable,
689
732
  pendingCompactionHandoff,
690
733
  hasActiveTool: (name) => pi.getActiveTools().includes(name),
691
734
  engine,
@@ -985,10 +1028,18 @@ export default async function (pi: ExtensionAPI): Promise<void> {
985
1028
  sweepStaleBridgeDirs();
986
1029
  sweepStagedAgyHomes();
987
1030
  // Start the bridge unless the user turned it off. No patch gate, no
988
- // consent flow: calls route through pi's normal toolUse loop.
1031
+ // consent flow: calls route through pi's normal toolUse loop. The
1032
+ // approval gate rides the same listener, so an active gate keeps it
1033
+ // running even with bridgeTools "none" (no pi tools are listed):
1034
+ // hiding pi tools from agy must never un-gate agy's native tools.
989
1035
  const bridgeMode: BridgeTools = loadConfig().bridgeTools;
990
- if (bridgeMode === "none") return; // user opted out
1036
+ // One resolution per session_start: the staging block below must gate
1037
+ // on the SAME verdict, or a mid-start flip leaves the gate unstaged
1038
+ // while gateUnavailable says pending (every turn refused until restart).
1039
+ const gateMode = resolveGateMode(loadConfig().approvals.gateMode, detectPermissionGateExtensions());
991
1040
  if (mcpHandle) return; // already running (reload re-fires session_start)
1041
+ gateUnavailable = gateMode === "off" ? undefined : "approval gate not staged yet";
1042
+ if (bridgeMode === "none" && gateMode === "off") return; // user opted out
992
1043
  // pi loads project skill locations only after the project is trusted;
993
1044
  // mirror that gate. Global skill dirs are always scanned.
994
1045
  const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? { projectDir: process.cwd() } : {});
@@ -1024,7 +1075,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1024
1075
  tools.push({
1025
1076
  name: POLL_TOOL_NAME,
1026
1077
  description:
1027
- "Fetch the result of a long-running bridge tool call that answered STILL RUNNING with a callId. Poll again if it still reports running; the result or an error arrives here.",
1078
+ "Fetch the result of a long-running bridge tool call that answered STILL RUNNING with a callId. The poll blocks up to 110 seconds for the result; call it again immediately if it still reports running.",
1028
1079
  inputSchema: {
1029
1080
  type: "object",
1030
1081
  properties: { callId: { type: "string", description: "callId from the STILL RUNNING answer" } },
@@ -1046,15 +1097,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1046
1097
  if (name === POLL_TOOL_NAME) {
1047
1098
  const wanted = typeof args.callId === "string" ? args.callId : "";
1048
1099
  mcpLog("poll-tool", { callId: wanted });
1049
- const view = roundTrips.poll(wanted);
1050
- // A terminal answer means the model RECEIVED the result; mark it
1051
- // so the redelivery path never double-delivers. poll() itself
1052
- // stays pure (internal peeks must not mark). Accepted gap: the
1053
- // mark fires when the poll ANSWERS, not when the HTTP response
1054
- // lands; a drop inside that one-write window would mark a result
1055
- // the model never saw.
1056
- if (view && view.state !== "running") roundTrips.markDelivered(wanted);
1057
- return Promise.resolve(formatPollAnswer(wanted, view));
1100
+ return answerPoll(roundTrips, wanted, signal, mcpLog);
1058
1101
  }
1059
1102
  if (name === TOOL_INFO_TOOL_NAME) {
1060
1103
  const { proxied } = partitionBridgeTools(getBridgeTools());
@@ -1118,7 +1161,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1118
1161
  // stream-json skips the global file entirely when the isolated home
1119
1162
  // is active (issue #14): this session's bridge rides the staged
1120
1163
  // config instead, so no other agy on the machine can see or call it.
1121
- if (engine === "stream-json" && !streamHome.isolated) {
1164
+ // bridgeTools "none" skips it too: with no pi tools exposed, a global
1165
+ // entry would only announce the listener to agy processes the user
1166
+ // opted out of; the gate needs no registration (its hook rides the
1167
+ // session's own add-dir).
1168
+ if (engine === "stream-json" && !streamHome.isolated && bridgeMode !== "none") {
1122
1169
  if (r.first) {
1123
1170
  registerBridgeServer({
1124
1171
  pid: process.pid,
@@ -1150,7 +1197,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1150
1197
  // enabled (auto = on only when a third-party gate extension exists).
1151
1198
  {
1152
1199
  const cfg = loadConfig();
1153
- const mode = resolveGateMode(cfg.approvals.gateMode, detectPermissionGateExtensions());
1200
+ const mode = gateMode;
1154
1201
  gateActive = mode !== "off";
1155
1202
  if (mode !== "off" && engine === "acp") {
1156
1203
  // Staged-home hook delivery is probe-verified on agy 1.5.12
@@ -1210,11 +1257,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1210
1257
  // pi.getAllTools() is unusable here: it returns ToolInfo, which
1211
1258
  // strips execute. Marker calls never execute; non-marker calls
1212
1259
  // delegate to the twins, so behavior matches the standard
1213
- // builtins (session-level bash-operations overrides are not
1214
- // inherited; documented in README).
1260
+ // builtins. The shadow replaces bash for EVERY model, so the
1261
+ // twin gets the same shellCommandPrefix/shellPath settings pi
1262
+ // gives its own bash (session-level bash-operations overrides
1263
+ // are still not inherited; documented in README).
1215
1264
  const gateCwd = process.cwd();
1216
1265
  const bases: Record<string, AnyToolDefinition> = {
1217
- bash: createBashToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1266
+ bash: createBashToolDefinition(gateCwd, bashSettingsOptions(pi)) as unknown as AnyToolDefinition,
1218
1267
  write: createWriteToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1219
1268
  edit: createEditToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1220
1269
  };
@@ -1254,9 +1303,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1254
1303
  // approval toolUse must never dispatch to the REAL builtin and
1255
1304
  // execute locally.
1256
1305
  roundTrips.approvalPark = handle.approvals;
1306
+ gateUnavailable = undefined;
1257
1307
  }
1258
1308
  }
1259
1309
  } else {
1310
+ if (gateUnavailable) gateUnavailable = `MCP listener failed: ${r.reason}`;
1260
1311
  console.error(`[antigravity-bridge] MCP tool bridge disabled: ${r.reason}`);
1261
1312
  }
1262
1313
  });
@@ -1827,7 +1878,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1827
1878
  );
1828
1879
  }
1829
1880
  } 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");
1881
+ ui?.notify(`bridge: ${loadConfig().bridgeTools}\nusage: /agy bridge all|mcp|codemode|none\n all: active non-builtin pi tools (ACP: pi's builtins too, declared directly). 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
1882
  }
1832
1883
  return;
1833
1884
  }
@@ -2016,7 +2067,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2016
2067
  id: "bridge",
2017
2068
  label: "Bridge tools",
2018
2069
  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.",
2070
+ "Which pi tools the MCP bridge exposes to agy. all (default): every non-builtin tool; on ACP also pi's builtins (read, ls, grep, find, edit, write, bash), declared directly so long commands ride the poll machinery. 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
2071
  currentValue: config.bridgeTools,
2021
2072
  values: ["all", "mcp", "codemode", "none"],
2022
2073
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.15.1",
3
+ "version": "1.16.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",
@@ -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
  });
@@ -1,4 +1,4 @@
1
- import type { BridgeTools } from "./config.js";
1
+ import type { BridgeTools, Engine } from "./config.js";
2
2
  import { POLL_TOOL_NAME } from "./provider.js";
3
3
  import { ACTIVATE_SKILL_TOOL_NAME } from "./skills.js";
4
4
 
@@ -45,6 +45,7 @@ export function serializeToolSchema(parameters?: object): object {
45
45
  * A stale tools/call must not bypass a disabled Pi tool. */
46
46
  export function bridgedPiTools(
47
47
  all: BridgeToolInfo[], active: readonly string[], mode: BridgeTools, hidden: ReadonlySet<string>,
48
+ engine: Engine,
48
49
  ): BridgeToolInfo[] {
49
50
  if (mode === "none") return [];
50
51
  const enabled = new Set(active);
@@ -60,7 +61,15 @@ export function bridgedPiTools(
60
61
  ? tool.name === "codemode" || tool.sourceInfo?.source !== "builtin"
61
62
  : mode === "mcp"
62
63
  ? /pi-mcp-adapter/.test(tool.sourceInfo?.source ?? "")
63
- : tool.sourceInfo?.source !== "builtin"),
64
+ // ACP must declare pi's default builtins directly: its native tool
65
+ // calls execute agy-side (provider Gate C), so pi's tools would be
66
+ // unreachable pi-side and long commands would bypass the poll
67
+ // machinery entirely. Limited to the seven defaults: a builtin like
68
+ // codemode stays codemode-mode-only on both engines. stream-json
69
+ // keeps them out: its native commands also run agy-side (pi only
70
+ // re-executes read-only calls for card rendering), so the catalog
71
+ // there stays exactly as it shipped.
72
+ : tool.sourceInfo?.source !== "builtin" || (engine === "acp" && PI_DEFAULT_TOOLS.has(tool.name))),
64
73
  );
65
74
  }
66
75
 
package/src/provider.ts CHANGED
@@ -252,7 +252,7 @@ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
252
252
  * the user's machine must go through the bridge. Rides the systemPrompt
253
253
  * gate: the note ships only when the system prompt ships. */
254
254
  export const TOOL_PRIORITY_NOTE =
255
- "[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, write, bash). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. Your turn ends when your reply ends, and pi never waits for agy's own wake-ups: never let a native run_command go to the background (keep WaitMsBeforeAsync at 0 for foreground runs and native commands under two minutes, since longer foreground waits hit pi's idle cap and kill the turn; wrap long commands in timeout and run anything longer through the Pi Bridge bash tool, which keeps it inside your turn, and poll bridge_poll_result if it answers STILL RUNNING) and never use the native schedule tool or timers. A task left running when you reply outlives your turn: its wake-up cannot call Pi Bridge tools, and a delegated subagent session is already gone when it fires.]";
255
+ "[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, write, bash). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. If a poll answer tells you to stop polling and end your turn, obey it: the result is delivered as your next message. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. Your turn ends when your reply ends, and pi never waits for agy's own wake-ups: never let a native run_command go to the background (keep WaitMsBeforeAsync at 0 for foreground runs and native commands under two minutes, since longer foreground waits hit pi's idle cap and kill the turn; wrap long commands in timeout and run anything longer through the Pi Bridge bash tool, which keeps it inside your turn, and poll bridge_poll_result if it answers STILL RUNNING) and never use the native schedule tool or timers. A task left running when you reply outlives your turn: its wake-up cannot call Pi Bridge tools, and a delegated subagent session is already gone when it fires.]";
256
256
 
257
257
  /** Assemble the full agy prompt: system prompt block, pi-side digest, user
258
258
  * prompt. Empty parts are dropped. Pure; exported for unit testing.
@@ -264,16 +264,23 @@ export const TOOL_PRIORITY_NOTE =
264
264
  export const CODEMODE_NOTE =
265
265
  "This conversation runs in codemode configuration: the direct Pi file tools (read, ls, grep, find, edit, write, bash) are not in your tool list; call them from inside codemode scripts as tools.read, tools.ls, tools.grep, tools.find, tools.edit, tools.write, tools.bash. Long or multi-step file work belongs in one script, not many tool calls.";
266
266
 
267
+ /** Appended after the tool-priority note when the engine's catalog actually
268
+ * declares pi's builtins directly (bridgeTools "all" on ACP). On ACP the
269
+ * native tools run agy-side and a silent native command past the bridge's
270
+ * 5-minute stall guard is killed, so the note must move long commands onto
271
+ * the bridge bash surface where polls keep the call alive. */
272
+ export const ACP_TOOL_NOTE =
273
+ "[ACP note: the Pi Bridge tools (read, ls, grep, find, edit, write, bash) are in your tool list; call them directly. For anything that may run longer than a minute use the Pi Bridge bash tool, never native run_command or execute: a silent native command running longer than five minutes is killed and its result is lost. Bridge bash calls are safe over long waits: the bridge answers STILL RUNNING with a callId and polling delivers the result even after many minutes. Keep native commands for short tasks only.]";
274
+
267
275
  export function buildFullPrompt(
268
276
  systemPrompt: string | undefined,
269
277
  digest: string,
270
278
  prompt: string,
271
- options?: { codemodeOnly?: boolean },
279
+ options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean },
272
280
  ): string {
273
281
  const parts: string[] = [];
274
282
  if (systemPrompt) {
275
- const note = options?.codemodeOnly ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE;
276
- parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${note}\n\n${SYSTEM_PROMPT_END}`);
283
+ parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${toolNotes(options)}\n\n${SYSTEM_PROMPT_END}`);
277
284
  }
278
285
  if (digest) {
279
286
  parts.push(`${DIGEST_PREAMBLE}\n\n${digest}`);
@@ -284,6 +291,15 @@ export function buildFullPrompt(
284
291
  return parts.join("\n\n---\n\n");
285
292
  }
286
293
 
294
+ /** Shared note composition for the system prompt block and the stream-json
295
+ * staged agent file (which concatenates the notes without buildFullPrompt). */
296
+ function toolNotes(options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean }): string {
297
+ const parts = [TOOL_PRIORITY_NOTE];
298
+ if (options?.acpToolsDirect) parts.push(ACP_TOOL_NOTE);
299
+ if (options?.codemodeOnly) parts.push(CODEMODE_NOTE);
300
+ return parts.join("\n\n");
301
+ }
302
+
287
303
  /** Flatten any message content shape (string or content-block array) to text.
288
304
  * Drops images, thinking, and tool-call blocks. */
289
305
  function blocksToText(content: unknown): string {
@@ -688,6 +704,11 @@ export interface StreamSimpleDeps {
688
704
  onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
689
705
  /** Subagent roster (both engines); folded from every activity. */
690
706
  roster?: SubagentRoster;
707
+ /** Why the approval gate this session requires is not staged, or
708
+ * undefined when it is staged or not required. A set reason refuses
709
+ * provider turns: an unstaged gate would let agy's native tools run
710
+ * without the pi-side approval the config asked for. */
711
+ gateUnavailable?: () => string | undefined;
691
712
  /** Session keys rotated on `session_compact` awaiting a one-shot
692
713
  * compaction handoff into a fresh agy conversation. */
693
714
  pendingCompactionHandoff?: Set<string>;
@@ -796,6 +817,9 @@ export interface PollView {
796
817
  * markDelivered (the real poll path); poll() stays pure so internal
797
818
  * peeks (escalatedNames) never mark. */
798
819
  delivered?: boolean;
820
+ /** Still-running poll answers served to the model (the poll path only).
821
+ * The handoff in formatPollAnswer arms at POLL_HANDOFF_AFTER. */
822
+ pollAnswers?: number;
799
823
  /** The agy conversation this call belongs to. Stamped at turn end so an
800
824
  * unpolled result can be re-delivered to the right conversation
801
825
  * (first-turn parks never reach the provider's store.set). */
@@ -806,6 +830,7 @@ export interface PollView {
806
830
  * evict first (a running call is never evicted while a newer one is). */
807
831
  export class EscalationRegistry {
808
832
  #calls = new Map<string, PollView>();
833
+ #waiters = new Map<string, Set<() => void>>();
809
834
  #trim(): void {
810
835
  // Soft cap: only settled entries evict. Evicting a RUNNING call would
811
836
  // strand its result (settle becomes a no-op, poll reports unknown), so
@@ -831,6 +856,7 @@ export class EscalationRegistry {
831
856
  e.isError = isError;
832
857
  if (images.length > 0) e.images = images;
833
858
  this.#trim();
859
+ this.#fireWaiters(callId);
834
860
  }
835
861
  settleFailed(callId: string, reason: string): void {
836
862
  const e = this.#calls.get(callId);
@@ -838,6 +864,42 @@ export class EscalationRegistry {
838
864
  e.state = "failed";
839
865
  e.reason = reason;
840
866
  this.#trim();
867
+ this.#fireWaiters(callId);
868
+ }
869
+
870
+ #fireWaiters(callId: string): void {
871
+ const waiters = this.#waiters.get(callId);
872
+ if (!waiters) return;
873
+ this.#waiters.delete(callId);
874
+ for (const wake of waiters) wake();
875
+ }
876
+
877
+ /** Resolve when the call settles, the window elapses, or signal aborts.
878
+ * Turn end and shutdown do not settle escalated entries (failAll spares
879
+ * them), so the abort listener and the window are the wake-up paths for
880
+ * abandoned polls. The caller re-reads through poll(), which stays the
881
+ * single pure read path. */
882
+ waitForSettle(callId: string, timeoutMs: number, signal?: AbortSignal): Promise<void> {
883
+ const entry = this.#calls.get(callId);
884
+ if (!entry || entry.state !== "running" || signal?.aborted) return Promise.resolve();
885
+ return new Promise<void>((resolve) => {
886
+ let done = false;
887
+ const waiters = this.#waiters.get(callId) ?? new Set<() => void>();
888
+ this.#waiters.set(callId, waiters);
889
+ const finish = () => {
890
+ if (done) return;
891
+ done = true;
892
+ clearTimeout(timer);
893
+ waiters.delete(finish);
894
+ if (waiters.size === 0 && this.#waiters.get(callId) === waiters) this.#waiters.delete(callId);
895
+ if (signal) signal.removeEventListener("abort", finish);
896
+ resolve();
897
+ };
898
+ waiters.add(finish);
899
+ const timer = setTimeout(finish, timeoutMs);
900
+ timer.unref?.();
901
+ if (signal) signal.addEventListener("abort", finish, { once: true });
902
+ });
841
903
  }
842
904
  poll(callId: string): PollView | undefined {
843
905
  const e = this.#calls.get(callId);
@@ -854,6 +916,16 @@ export class EscalationRegistry {
854
916
  return true;
855
917
  }
856
918
 
919
+ /** Count a STILL RUNNING answer served to the model (the poll path only).
920
+ * formatPollAnswer turns the count into a turn-end handoff at
921
+ * POLL_HANDOFF_AFTER; the settled result then reaches the model through
922
+ * the strand sweep instead of further polls. */
923
+ noteStillRunningPoll(callId: string): void {
924
+ const e = this.#calls.get(callId);
925
+ if (!e || e.state !== "running") return;
926
+ e.pollAnswers = (e.pollAnswers ?? 0) + 1;
927
+ }
928
+
857
929
  /** Single-use claim of a done-but-undelivered result: returns the view
858
930
  * and marks it delivered in one step, so a later pass can never deliver
859
931
  * it twice. The entry stays pollable for a late model poll. Failed
@@ -909,8 +981,8 @@ export function formatEscalatedAck(e: BridgeEscalation): BridgeCallResultShape {
909
981
  type: "text",
910
982
  text: [
911
983
  `STILL RUNNING: the pi tool "${e.name}" has not finished yet.`,
912
- `Call ${POLL_TOOL_NAME} with callId "${e.callId}" to get the result. Poll again if it still reports running; you may do other work between polls.`,
913
- "Do NOT end your turn while this call is unresolved: keep polling until it reports done or failed. Ending the turn strands the result.",
984
+ `Call ${POLL_TOOL_NAME} with callId "${e.callId}" to get the result. Call it again immediately after each answer: each poll now blocks up to 110 seconds and returns the moment the call settles. Do other work between polls only when that work is genuinely useful.`,
985
+ "Keep polling until the call reports done or failed. If a poll answer tells you to stop polling and end your turn, obey it: the bridge delivers the result as your next message in this conversation. Ending the turn on your own initiative, without that instruction, strands the result.",
914
986
  ].join("\n"),
915
987
  },
916
988
  ],
@@ -918,6 +990,46 @@ export function formatEscalatedAck(e: BridgeEscalation): BridgeCallResultShape {
918
990
  };
919
991
  }
920
992
 
993
+ /** Long-waiting bridge_poll_result (issue #29): a running call holds the
994
+ * request up to POLL_WAIT_MS for an instant settle, because every early
995
+ * STILL RUNNING costs agy a full LLM turn (quota + context). Settle wakes
996
+ * the waiter immediately, so the window only bounds still-running holds;
997
+ * 110s stays under agy's ~180s request deadline with the 120s delegation
998
+ * hold as production precedent, and a poll killed by that deadline is
999
+ * harmless (abort skips the delivered mark). Turn end and shutdown do not
1000
+ * settle escalated entries (failAll spares them), so the abort and the
1001
+ * window are the wake-up paths for abandoned polls. An abort skips
1002
+ * markDelivered: marking a result the client never received would strand
1003
+ * it away from the redelivery paths. Accepted gap (unchanged): the mark
1004
+ * fires when the poll ANSWERS, not when the HTTP response lands. */
1005
+ export const POLL_WAIT_MS = 110_000;
1006
+
1007
+ /** Still-running poll answers served before the poll answer switches to the
1008
+ * turn-end handoff. Every poll answer costs agy a full inference, so a
1009
+ * 30-minute human-gated park costs roughly this constant plus the ack
1010
+ * instead of one call per minute; the settled result then reaches the
1011
+ * model through the dead-turn strand sweep (claimAllUndelivered is
1012
+ * registry-wide, so sibling parks ride the same handoff). */
1013
+ export const POLL_HANDOFF_AFTER = 3;
1014
+
1015
+ export async function answerPoll(
1016
+ roundTrips: Pick<ToolRoundTrips, "poll" | "markDelivered" | "waitForSettle" | "noteStillRunningPoll">,
1017
+ callId: string,
1018
+ signal: AbortSignal,
1019
+ log?: (event: string, data?: unknown) => void,
1020
+ ): Promise<BridgeCallResultShape> {
1021
+ if (roundTrips.poll(callId)?.state === "running") {
1022
+ await roundTrips.waitForSettle(callId, POLL_WAIT_MS, signal);
1023
+ }
1024
+ const view = roundTrips.poll(callId);
1025
+ if (view && view.state === "running" && !signal.aborted) {
1026
+ if ((view.pollAnswers ?? 0) >= POLL_HANDOFF_AFTER) log?.("poll-handoff", { callId, name: view.name });
1027
+ roundTrips.noteStillRunningPoll(callId);
1028
+ }
1029
+ if (view && view.state !== "running" && !signal.aborted) roundTrips.markDelivered(callId);
1030
+ return formatPollAnswer(callId, view);
1031
+ }
1032
+
921
1033
  export function formatPollAnswer(callId: string, view: PollView | undefined): BridgeCallResultShape {
922
1034
  if (!view) {
923
1035
  return {
@@ -931,8 +1043,16 @@ export function formatPollAnswer(callId: string, view: PollView | undefined): Br
931
1043
  };
932
1044
  }
933
1045
  if (view.state === "running") {
1046
+ const handoff = (view.pollAnswers ?? 0) >= POLL_HANDOFF_AFTER;
934
1047
  return {
935
- content: [{ type: "text", text: `STILL RUNNING: "${view.name}" (callId ${callId}) has not finished. Poll again later.` }],
1048
+ content: [
1049
+ {
1050
+ type: "text",
1051
+ text: handoff
1052
+ ? `STILL RUNNING: "${view.name}" (callId ${callId}) is taking long. Stop polling: end your turn now, and the bridge will deliver the result as your next message in this conversation. Do not call ${POLL_TOOL_NAME} again for this callId.`
1053
+ : `STILL RUNNING: "${view.name}" (callId ${callId}) has not finished. Call ${POLL_TOOL_NAME} again now: it blocks up to 110 seconds and returns the moment the call settles.`,
1054
+ },
1055
+ ],
936
1056
  isError: false,
937
1057
  };
938
1058
  }
@@ -1054,12 +1174,23 @@ export class ToolRoundTrips {
1054
1174
  return this.#escalations.markDelivered(callId);
1055
1175
  }
1056
1176
 
1177
+ waitForSettle(callId: string, timeoutMs: number, signal?: AbortSignal): Promise<void> {
1178
+ return this.#escalations.waitForSettle(callId, timeoutMs, signal);
1179
+ }
1180
+
1057
1181
  /** Single-use claim of a settled-but-undelivered escalated result (the
1058
1182
  * model ended its turn instead of polling). */
1059
1183
  claimUndelivered(callId: string): (PollView & { callId: string }) | undefined {
1060
1184
  return this.#escalations.claimUndelivered(callId);
1061
1185
  }
1062
1186
 
1187
+ /** Count a STILL RUNNING answer served to the model (the poll path only);
1188
+ * formatPollAnswer turns the count into a turn-end handoff at
1189
+ * POLL_HANDOFF_AFTER. */
1190
+ noteStillRunningPoll(callId: string): void {
1191
+ return this.#escalations.noteStillRunningPoll(callId);
1192
+ }
1193
+
1063
1194
  /** Registry-wide sweep for done-but-undelivered results: a toolResult is
1064
1195
  * consumed by its own pass, so multi-pass strands are only findable
1065
1196
  * here. */
@@ -1803,7 +1934,7 @@ async function runTurnDriver(
1803
1934
  return {
1804
1935
  callId: view.callId,
1805
1936
  name: view.name,
1806
- reason: "you never received this result: you ended your turn without calling bridge_poll_result",
1937
+ reason: "the call settled after your turn ended; the result is delivered here so the work is not lost",
1807
1938
  text: view.text ?? "(no output)",
1808
1939
  isError: view.isError ?? false,
1809
1940
  images: view.images,
@@ -1859,6 +1990,20 @@ async function runTurnDriver(
1859
1990
  codemodeNote = true;
1860
1991
  }
1861
1992
  }
1993
+ // The ACP note ships only when the engine's catalog actually declares
1994
+ // pi's builtins: bridgeTools "all" on ACP AND bash in pi's active set
1995
+ // (pi can start with a narrowed toolset; a hidden bash is a deliberate
1996
+ // session-local override and keeps the note). Without the probe the note
1997
+ // would point at tools agy cannot call and forbid its only working ones.
1998
+ // Same staleness window as codemodeNote: a /agy bridge flip re-reads on
1999
+ // the next conversation, the held one keeps its note until then.
2000
+ let acpBashActive = true;
2001
+ try {
2002
+ acpBashActive = deps.hasActiveTool?.("bash") ?? true;
2003
+ } catch {
2004
+ acpBashActive = true;
2005
+ }
2006
+ const acpToolsDirect = deps.engine === "acp" && config.bridgeTools === "all" && acpBashActive;
1862
2007
  // The sync orchestrator for THIS pass when the sync gate dispatched; the
1863
2008
  // settle (and the park persist) sit outside the fresh-pass block, so the
1864
2009
  // binding is function-level (the round-1 settle scope trap).
@@ -2056,7 +2201,7 @@ async function runTurnDriver(
2056
2201
  // coordinator calls throw on invariants: both must fail the turn
2057
2202
  // visibly, not surface as an unhandled rejection.
2058
2203
  const input = turn.inputFor({
2059
- prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) + stageImageNote(syncImages),
2204
+ prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect }) + stageImageNote(syncImages),
2060
2205
  images: syncImages,
2061
2206
  });
2062
2207
  turn.bound(key);
@@ -2086,7 +2231,7 @@ async function runTurnDriver(
2086
2231
  // history to a fresh conversation; the gate re-opens there.
2087
2232
  const fresh = turn.loadFailed({
2088
2233
  prompt:
2089
- buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) +
2234
+ buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect }) +
2090
2235
  stageImageNote(syncImages),
2091
2236
  images: syncImages,
2092
2237
  });
@@ -2199,7 +2344,7 @@ async function runTurnDriver(
2199
2344
  [
2200
2345
  SYSTEM_PROMPT_PREAMBLE,
2201
2346
  rawSysPrompt,
2202
- codemodeNote ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE,
2347
+ toolNotes({ codemodeOnly: codemodeNote, acpToolsDirect }),
2203
2348
  ].join("\n\n"),
2204
2349
  );
2205
2350
  if (stagedName) {
@@ -2251,7 +2396,7 @@ async function runTurnDriver(
2251
2396
  // Both features off: the variant would equal the plain prompt.
2252
2397
  if (!fbSys && !freshDigest?.text) return undefined;
2253
2398
  return {
2254
- prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote }) + stageImageNote(runImages),
2399
+ prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect }) + stageImageNote(runImages),
2255
2400
  contextBlock: freshDigest?.text
2256
2401
  ? {
2257
2402
  uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
@@ -2264,7 +2409,7 @@ async function runTurnDriver(
2264
2409
  const fullPrompt =
2265
2410
  (late.length > 0
2266
2411
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
2267
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote })) +
2412
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect })) +
2268
2413
  stageImageNote(runImages);
2269
2414
  if (!syncTurn) {
2270
2415
  try {
@@ -2735,6 +2880,19 @@ export function createStreamSimple(
2735
2880
  );
2736
2881
  return stream;
2737
2882
  }
2883
+ const gateMissing = deps.gateUnavailable?.();
2884
+ if (gateMissing) {
2885
+ const partial = newAssistant(model);
2886
+ const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
2887
+ deps.log?.("turn-error", { reason: "approval-gate-unavailable" }, "warn");
2888
+ finalize(
2889
+ stream,
2890
+ blocks,
2891
+ "error",
2892
+ `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.`,
2893
+ );
2894
+ return stream;
2895
+ }
2738
2896
  if (selected && roundTrips) {
2739
2897
  void runTurnDriver(stream, model, context, options, entries, store, {
2740
2898
  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;