@estebanforge/pi-antigravity-bridge 1.15.2 → 1.16.1
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 +15 -0
- package/README.md +6 -4
- package/extensions/index.ts +45 -16
- package/package.json +1 -1
- package/src/bridge-catalog.ts +11 -2
- package/src/provider.ts +163 -20
- package/src/sysprompt-agent.ts +47 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.16.1] - 2026-11-28
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- stream-json provider sessions no longer fail every turn with `RESOURCE_EXHAUSTED (code 429)` at 0% quota use when pi runs with its default system prompt. Two lines of that prompt make the Antigravity backend reject any request of a session whose carrier agent holds them: the opening sentence ("running inside pi, a coding agent harness") and the docs-index line ("- When asked about: extensions (docs/..."). The carrier now rewords the first and omits the second; a custom system prompt passes through unchanged. The backend rule behind the two lines is unknown (the upstream match is not exact text), so this is a point fix: an upstream reword of pi's default prompt can bring the 429 back, and the `sysprompt-scrub` staging log event then shows whether the scrub still matched (needs `AGY_DEBUG=1`; the daily log is error-only by default).
|
|
10
|
+
|
|
11
|
+
## [1.16.0] - 2026-11-26
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
- `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`).
|
|
18
|
+
- 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.
|
|
19
|
+
|
|
5
20
|
## [1.15.2] - 2026-11-25
|
|
6
21
|
|
|
7
22
|
### Fixed
|
package/README.md
CHANGED
|
@@ -40,15 +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
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.
|
|
50
52
|
|
|
51
|
-
**Cost / fan-out.** Every registered pi tool except
|
|
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.
|
|
52
54
|
|
|
53
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.
|
|
54
56
|
|
|
@@ -119,9 +121,9 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
|
|
|
119
121
|
| --- | --- | --- |
|
|
120
122
|
| `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
|
|
121
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` |
|
|
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` |
|
|
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` |
|
|
123
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` |
|
|
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` |
|
|
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` |
|
|
125
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` |
|
|
126
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` |
|
|
127
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 |
|
package/extensions/index.ts
CHANGED
|
@@ -45,7 +45,7 @@ import {
|
|
|
45
45
|
createStreamSimple,
|
|
46
46
|
defaultEscalateAfterMs,
|
|
47
47
|
formatEscalatedAck,
|
|
48
|
-
|
|
48
|
+
answerPoll,
|
|
49
49
|
rotateSessionOnCompaction,
|
|
50
50
|
sessionKey,
|
|
51
51
|
type NativeDisplayEvent,
|
|
@@ -227,7 +227,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
227
227
|
let realmSession: RealmSession | null = null;
|
|
228
228
|
// Session-only visibility overrides; never change either application's MCP config.
|
|
229
229
|
const hiddenBridgeTools = new Set<string>();
|
|
230
|
-
const getBridgeTools = () => bridgedPiTools(pi.getAllTools(), pi.getActiveTools(), loadConfig().bridgeTools, hiddenBridgeTools);
|
|
230
|
+
const getBridgeTools = () => bridgedPiTools(pi.getAllTools(), pi.getActiveTools(), loadConfig().bridgeTools, hiddenBridgeTools, engine);
|
|
231
231
|
// Staged gate hooks do not stop agy's own request_permission path, so when
|
|
232
232
|
// true the ACP driver stops letting skipPermissions auto-allow it.
|
|
233
233
|
let gateActive = false;
|
|
@@ -537,21 +537,58 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
537
537
|
// SDK's exact usage metadata before it reaches the client.
|
|
538
538
|
if (engine === "acp") {
|
|
539
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
|
+
});
|
|
540
559
|
pi.on("message_update", (event, ctx) => {
|
|
541
560
|
if (!ctx.hasUI || event.message.role !== "assistant" || event.message.provider !== "antigravity" || loadConfig().acp.usageEstimate === "off") return;
|
|
542
|
-
const { input, output } = event.message.usage;
|
|
543
|
-
|
|
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`);
|
|
544
569
|
if (status !== lastUsageStatus) {
|
|
545
570
|
lastUsageStatus = status;
|
|
546
571
|
ctx.ui.setStatus("agy-usage", status);
|
|
547
572
|
}
|
|
548
573
|
});
|
|
549
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
|
+
}
|
|
550
586
|
lastUsageStatus = "";
|
|
551
587
|
if (ctx.hasUI) ctx.ui.setStatus("agy-usage", undefined);
|
|
552
588
|
};
|
|
553
589
|
pi.on("agent_end", (event, ctx) => {
|
|
554
590
|
clearUsageStatus(event, ctx);
|
|
591
|
+
usageByMessage.clear();
|
|
555
592
|
pendingNativeTools = 0;
|
|
556
593
|
closePollRun();
|
|
557
594
|
if (ctx.hasUI) ctx.ui.setStatus("agy-native", undefined);
|
|
@@ -1038,7 +1075,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
1038
1075
|
tools.push({
|
|
1039
1076
|
name: POLL_TOOL_NAME,
|
|
1040
1077
|
description:
|
|
1041
|
-
"Fetch the result of a long-running bridge tool call that answered STILL RUNNING with a callId.
|
|
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.",
|
|
1042
1079
|
inputSchema: {
|
|
1043
1080
|
type: "object",
|
|
1044
1081
|
properties: { callId: { type: "string", description: "callId from the STILL RUNNING answer" } },
|
|
@@ -1060,15 +1097,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
1060
1097
|
if (name === POLL_TOOL_NAME) {
|
|
1061
1098
|
const wanted = typeof args.callId === "string" ? args.callId : "";
|
|
1062
1099
|
mcpLog("poll-tool", { callId: wanted });
|
|
1063
|
-
|
|
1064
|
-
// A terminal answer means the model RECEIVED the result; mark it
|
|
1065
|
-
// so the redelivery path never double-delivers. poll() itself
|
|
1066
|
-
// stays pure (internal peeks must not mark). Accepted gap: the
|
|
1067
|
-
// mark fires when the poll ANSWERS, not when the HTTP response
|
|
1068
|
-
// lands; a drop inside that one-write window would mark a result
|
|
1069
|
-
// the model never saw.
|
|
1070
|
-
if (view && view.state !== "running") roundTrips.markDelivered(wanted);
|
|
1071
|
-
return Promise.resolve(formatPollAnswer(wanted, view));
|
|
1100
|
+
return answerPoll(roundTrips, wanted, signal, mcpLog);
|
|
1072
1101
|
}
|
|
1073
1102
|
if (name === TOOL_INFO_TOOL_NAME) {
|
|
1074
1103
|
const { proxied } = partitionBridgeTools(getBridgeTools());
|
|
@@ -1849,7 +1878,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
|
|
|
1849
1878
|
);
|
|
1850
1879
|
}
|
|
1851
1880
|
} else {
|
|
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");
|
|
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");
|
|
1853
1882
|
}
|
|
1854
1883
|
return;
|
|
1855
1884
|
}
|
|
@@ -2038,7 +2067,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
|
|
|
2038
2067
|
id: "bridge",
|
|
2039
2068
|
label: "Bridge tools",
|
|
2040
2069
|
description:
|
|
2041
|
-
"Which pi tools the MCP bridge exposes to agy. all: every non-builtin tool (
|
|
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).",
|
|
2042
2071
|
currentValue: config.bridgeTools,
|
|
2043
2072
|
values: ["all", "mcp", "codemode", "none"],
|
|
2044
2073
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@estebanforge/pi-antigravity-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.1",
|
|
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",
|
package/src/bridge-catalog.ts
CHANGED
|
@@ -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
|
-
:
|
|
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
|
@@ -48,7 +48,7 @@ import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-ga
|
|
|
48
48
|
import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
|
|
49
49
|
import path from "node:path";
|
|
50
50
|
import { TurnDiffContext, createExecGitOps, formatInlineDiff, parseEditToolInput } from "./diff-render.js";
|
|
51
|
-
import { stageSyspromptAgent } from "./sysprompt-agent.js";
|
|
51
|
+
import { carrierScrubInfo, stageSyspromptAgent } from "./sysprompt-agent.js";
|
|
52
52
|
import { buildImageNote, stagePromptImages } from "./prompt-images.js";
|
|
53
53
|
|
|
54
54
|
const DEFAULT_TIMEOUT_MIN = 10;
|
|
@@ -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
|
-
|
|
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 {
|
|
@@ -801,6 +817,9 @@ export interface PollView {
|
|
|
801
817
|
* markDelivered (the real poll path); poll() stays pure so internal
|
|
802
818
|
* peeks (escalatedNames) never mark. */
|
|
803
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;
|
|
804
823
|
/** The agy conversation this call belongs to. Stamped at turn end so an
|
|
805
824
|
* unpolled result can be re-delivered to the right conversation
|
|
806
825
|
* (first-turn parks never reach the provider's store.set). */
|
|
@@ -811,6 +830,7 @@ export interface PollView {
|
|
|
811
830
|
* evict first (a running call is never evicted while a newer one is). */
|
|
812
831
|
export class EscalationRegistry {
|
|
813
832
|
#calls = new Map<string, PollView>();
|
|
833
|
+
#waiters = new Map<string, Set<() => void>>();
|
|
814
834
|
#trim(): void {
|
|
815
835
|
// Soft cap: only settled entries evict. Evicting a RUNNING call would
|
|
816
836
|
// strand its result (settle becomes a no-op, poll reports unknown), so
|
|
@@ -836,6 +856,7 @@ export class EscalationRegistry {
|
|
|
836
856
|
e.isError = isError;
|
|
837
857
|
if (images.length > 0) e.images = images;
|
|
838
858
|
this.#trim();
|
|
859
|
+
this.#fireWaiters(callId);
|
|
839
860
|
}
|
|
840
861
|
settleFailed(callId: string, reason: string): void {
|
|
841
862
|
const e = this.#calls.get(callId);
|
|
@@ -843,6 +864,42 @@ export class EscalationRegistry {
|
|
|
843
864
|
e.state = "failed";
|
|
844
865
|
e.reason = reason;
|
|
845
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
|
+
});
|
|
846
903
|
}
|
|
847
904
|
poll(callId: string): PollView | undefined {
|
|
848
905
|
const e = this.#calls.get(callId);
|
|
@@ -859,6 +916,16 @@ export class EscalationRegistry {
|
|
|
859
916
|
return true;
|
|
860
917
|
}
|
|
861
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
|
+
|
|
862
929
|
/** Single-use claim of a done-but-undelivered result: returns the view
|
|
863
930
|
* and marks it delivered in one step, so a later pass can never deliver
|
|
864
931
|
* it twice. The entry stays pollable for a late model poll. Failed
|
|
@@ -914,8 +981,8 @@ export function formatEscalatedAck(e: BridgeEscalation): BridgeCallResultShape {
|
|
|
914
981
|
type: "text",
|
|
915
982
|
text: [
|
|
916
983
|
`STILL RUNNING: the pi tool "${e.name}" has not finished yet.`,
|
|
917
|
-
`Call ${POLL_TOOL_NAME} with callId "${e.callId}" to get the result.
|
|
918
|
-
"
|
|
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.",
|
|
919
986
|
].join("\n"),
|
|
920
987
|
},
|
|
921
988
|
],
|
|
@@ -923,6 +990,46 @@ export function formatEscalatedAck(e: BridgeEscalation): BridgeCallResultShape {
|
|
|
923
990
|
};
|
|
924
991
|
}
|
|
925
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
|
+
|
|
926
1033
|
export function formatPollAnswer(callId: string, view: PollView | undefined): BridgeCallResultShape {
|
|
927
1034
|
if (!view) {
|
|
928
1035
|
return {
|
|
@@ -936,8 +1043,16 @@ export function formatPollAnswer(callId: string, view: PollView | undefined): Br
|
|
|
936
1043
|
};
|
|
937
1044
|
}
|
|
938
1045
|
if (view.state === "running") {
|
|
1046
|
+
const handoff = (view.pollAnswers ?? 0) >= POLL_HANDOFF_AFTER;
|
|
939
1047
|
return {
|
|
940
|
-
content: [
|
|
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
|
+
],
|
|
941
1056
|
isError: false,
|
|
942
1057
|
};
|
|
943
1058
|
}
|
|
@@ -1059,12 +1174,23 @@ export class ToolRoundTrips {
|
|
|
1059
1174
|
return this.#escalations.markDelivered(callId);
|
|
1060
1175
|
}
|
|
1061
1176
|
|
|
1177
|
+
waitForSettle(callId: string, timeoutMs: number, signal?: AbortSignal): Promise<void> {
|
|
1178
|
+
return this.#escalations.waitForSettle(callId, timeoutMs, signal);
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1062
1181
|
/** Single-use claim of a settled-but-undelivered escalated result (the
|
|
1063
1182
|
* model ended its turn instead of polling). */
|
|
1064
1183
|
claimUndelivered(callId: string): (PollView & { callId: string }) | undefined {
|
|
1065
1184
|
return this.#escalations.claimUndelivered(callId);
|
|
1066
1185
|
}
|
|
1067
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
|
+
|
|
1068
1194
|
/** Registry-wide sweep for done-but-undelivered results: a toolResult is
|
|
1069
1195
|
* consumed by its own pass, so multi-pass strands are only findable
|
|
1070
1196
|
* here. */
|
|
@@ -1808,7 +1934,7 @@ async function runTurnDriver(
|
|
|
1808
1934
|
return {
|
|
1809
1935
|
callId: view.callId,
|
|
1810
1936
|
name: view.name,
|
|
1811
|
-
reason: "
|
|
1937
|
+
reason: "the call settled after your turn ended; the result is delivered here so the work is not lost",
|
|
1812
1938
|
text: view.text ?? "(no output)",
|
|
1813
1939
|
isError: view.isError ?? false,
|
|
1814
1940
|
images: view.images,
|
|
@@ -1864,6 +1990,20 @@ async function runTurnDriver(
|
|
|
1864
1990
|
codemodeNote = true;
|
|
1865
1991
|
}
|
|
1866
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;
|
|
1867
2007
|
// The sync orchestrator for THIS pass when the sync gate dispatched; the
|
|
1868
2008
|
// settle (and the park persist) sit outside the fresh-pass block, so the
|
|
1869
2009
|
// binding is function-level (the round-1 settle scope trap).
|
|
@@ -2061,7 +2201,7 @@ async function runTurnDriver(
|
|
|
2061
2201
|
// coordinator calls throw on invariants: both must fail the turn
|
|
2062
2202
|
// visibly, not surface as an unhandled rejection.
|
|
2063
2203
|
const input = turn.inputFor({
|
|
2064
|
-
prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) + stageImageNote(syncImages),
|
|
2204
|
+
prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect }) + stageImageNote(syncImages),
|
|
2065
2205
|
images: syncImages,
|
|
2066
2206
|
});
|
|
2067
2207
|
turn.bound(key);
|
|
@@ -2091,7 +2231,7 @@ async function runTurnDriver(
|
|
|
2091
2231
|
// history to a fresh conversation; the gate re-opens there.
|
|
2092
2232
|
const fresh = turn.loadFailed({
|
|
2093
2233
|
prompt:
|
|
2094
|
-
buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) +
|
|
2234
|
+
buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect }) +
|
|
2095
2235
|
stageImageNote(syncImages),
|
|
2096
2236
|
images: syncImages,
|
|
2097
2237
|
});
|
|
@@ -2200,14 +2340,17 @@ async function runTurnDriver(
|
|
|
2200
2340
|
let agent = config.agent;
|
|
2201
2341
|
if (deps.engine !== "acp") {
|
|
2202
2342
|
if (rawSysPrompt && !config.agent) {
|
|
2203
|
-
const
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
);
|
|
2343
|
+
const stagedBody = [
|
|
2344
|
+
SYSTEM_PROMPT_PREAMBLE,
|
|
2345
|
+
rawSysPrompt,
|
|
2346
|
+
toolNotes({ codemodeOnly: codemodeNote, acpToolsDirect }),
|
|
2347
|
+
].join("\n\n");
|
|
2348
|
+
const stagedName = stageSyspromptAgent(stagedBody);
|
|
2210
2349
|
if (stagedName) {
|
|
2350
|
+
// Issue #30 telemetry: separates "scrub ran, still 429" from
|
|
2351
|
+
// "pi reworded upstream and the scrub no longer matches".
|
|
2352
|
+
const scrub = carrierScrubInfo(stagedBody);
|
|
2353
|
+
deps.log?.("sysprompt-scrub", { opening: scrub.opening, docsLine: scrub.docsLine }, "info");
|
|
2211
2354
|
agent = stagedName;
|
|
2212
2355
|
sysPrompt = undefined;
|
|
2213
2356
|
stagedAgentName = stagedName;
|
|
@@ -2256,7 +2399,7 @@ async function runTurnDriver(
|
|
|
2256
2399
|
// Both features off: the variant would equal the plain prompt.
|
|
2257
2400
|
if (!fbSys && !freshDigest?.text) return undefined;
|
|
2258
2401
|
return {
|
|
2259
|
-
prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote }) + stageImageNote(runImages),
|
|
2402
|
+
prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect }) + stageImageNote(runImages),
|
|
2260
2403
|
contextBlock: freshDigest?.text
|
|
2261
2404
|
? {
|
|
2262
2405
|
uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
|
|
@@ -2269,7 +2412,7 @@ async function runTurnDriver(
|
|
|
2269
2412
|
const fullPrompt =
|
|
2270
2413
|
(late.length > 0
|
|
2271
2414
|
? buildLateResultPrompt(late, deliveredPrompt || undefined)
|
|
2272
|
-
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote })) +
|
|
2415
|
+
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect })) +
|
|
2273
2416
|
stageImageNote(runImages);
|
|
2274
2417
|
if (!syncTurn) {
|
|
2275
2418
|
try {
|
package/src/sysprompt-agent.ts
CHANGED
|
@@ -46,6 +46,52 @@ export function syspromptAgentsRoot(): string {
|
|
|
46
46
|
return process.env.AGY_AGENTS_ROOT ?? path.join(os.homedir(), ".gemini", "config", "agents");
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** Opening sentence of pi's default system prompt, and the wording the carrier
|
|
50
|
+
* ships instead. */
|
|
51
|
+
export const PI_OPENING = "running inside pi, a coding agent harness";
|
|
52
|
+
const PI_OPENING_REWORDED = "running inside the pi coding agent harness";
|
|
53
|
+
/** Start of the docs-index line of pi's default system prompt. */
|
|
54
|
+
export const PI_DOCS_INDEX_PREFIX = "- When asked about: extensions (docs/";
|
|
55
|
+
|
|
56
|
+
/** Scrubbed carrier text plus which scrubs applied (the `sysprompt-scrub`
|
|
57
|
+
* staging event's payload). */
|
|
58
|
+
export interface CarrierScrub {
|
|
59
|
+
text: string;
|
|
60
|
+
opening: boolean;
|
|
61
|
+
docsLine: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Two lines of pi's default system prompt make the Antigravity backend answer
|
|
65
|
+
* `RESOURCE_EXHAUSTED (code 429)` to every request of a carrier session, each
|
|
66
|
+
* on its own and at 0% quota use (probed 2026-11-27, agy 1.5.18, with
|
|
67
|
+
* gemini-4-hydrogen, gemini-4-neon and claude-sonnet-5-5): the opening
|
|
68
|
+
* sentence and the docs-index line. A carrier holding either one never
|
|
69
|
+
* completes a turn. Reword the first (same meaning) and drop the second (it
|
|
70
|
+
* only maps pi's own docs for questions about the harness). The match is
|
|
71
|
+
* exact on purpose: a custom system prompt passes through untouched.
|
|
72
|
+
* Point fix (issue #30): the backend rule behind the two lines is unknown
|
|
73
|
+
* (the upstream match is not exact text), so a future reword of pi's prompt
|
|
74
|
+
* can silently re-break staging; the provider's `sysprompt-scrub` staging
|
|
75
|
+
* event exists to tell "scrub ran, still 429" from "scrub no longer
|
|
76
|
+
* matches" (needs AGY_DEBUG=1: the daily log is error-only by default). */
|
|
77
|
+
export function carrierScrubInfo(body: string): CarrierScrub {
|
|
78
|
+
const lines = body.split("\n");
|
|
79
|
+
const kept = lines.filter((line) => !line.startsWith(PI_DOCS_INDEX_PREFIX));
|
|
80
|
+
const keptText = kept.join("\n");
|
|
81
|
+
return {
|
|
82
|
+
text: keptText.replaceAll(PI_OPENING, PI_OPENING_REWORDED),
|
|
83
|
+
// On the kept text: the phrase sitting only inside a dropped docs line
|
|
84
|
+
// must not report a reword that never happened.
|
|
85
|
+
opening: keptText.includes(PI_OPENING),
|
|
86
|
+
docsLine: kept.length !== lines.length,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** carrierScrubInfo's text, for callers that do not log the flags. */
|
|
91
|
+
export function carrierSafeBody(body: string): string {
|
|
92
|
+
return carrierScrubInfo(body).text;
|
|
93
|
+
}
|
|
94
|
+
|
|
49
95
|
/** agent.md for the carrier. The body is the pi system prompt composed by the
|
|
50
96
|
* provider (preamble + transcript system prompt + tool-priority note). */
|
|
51
97
|
export function syspromptAgentMd(name: string, body: string): string {
|
|
@@ -70,7 +116,7 @@ export function syspromptAgentMd(name: string, body: string): string {
|
|
|
70
116
|
" - search_web",
|
|
71
117
|
"---",
|
|
72
118
|
"",
|
|
73
|
-
body,
|
|
119
|
+
carrierSafeBody(body),
|
|
74
120
|
"",
|
|
75
121
|
].join("\n");
|
|
76
122
|
}
|