@timmyjl12/pi-agy-bridge 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ARCHITECTURE.md CHANGED
@@ -9,7 +9,8 @@ pi -> streamAgy(model, context, options)
9
9
  1 splitContext system prompt + current tools | history (up to the last assistant message) | latest input
10
10
  2 hashChain sha256 chain over [system, tools, model, thought] then each message
11
11
  3 pool.acquire reuse a pooled agy session only if it already holds exactly this prefix
12
- otherwise session/new (+ system prompt and tool protocol as _meta append) and set model / thought_level
12
+ otherwise session/new (+ system prompt and tool protocol as _meta append, or inline in step 4 when
13
+ PI_AGY_SYSTEM_PROMPT=inline or the append was refused earlier) and set model / thought_level
13
14
  4 buildPrompt [resource pi://conversation.md (history, only for a fresh session)] + text(latest input) + images
14
15
  5 session/prompt agy streams agent_thought_chunk / agent_message_chunk
15
16
  6 Translator thought -> thinking block; message -> ToolCallStreamParser -> text blocks | toolCall
@@ -101,7 +102,9 @@ Own messages avoid bare three-digit numbers because the classifier reads them as
101
102
 
102
103
  ## Upgrade path
103
104
 
104
- `compat/matrix.json` lists the tested agy versions, the minimum, known-bad versions and the ACP protocol. At handshake `deriveFeatures` negotiates optional features with fallbacks (system prompt inside the conversation resource, history inlined as text, no images). A protocol or minimum-version mismatch stops the provider with an actionable message; a newer untested version only warns once. `UPGRADING.md` is the runbook; the probe and the SDK canary cost no quota.
105
+ `compat/matrix.json` lists the tested agy versions, the minimum, known-bad versions and the ACP protocol. At handshake `deriveFeatures` negotiates optional features with fallbacks (system prompt inside the conversation resource, history inlined as text, no images). A protocol or minimum-version mismatch stops the provider with an actionable message; a newer untested version only warns once.
106
+
107
+ The backend can refuse a prompt that the protocol accepts. Since 2026-11-14 (agy 1.5.9) a session whose system prompt arrives through the append hook and contains pi's default opening line gets `RESOURCE_EXHAUSTED` on every try, for every model, while the same text inline is served. agy reports each retry as an `agent_message_chunk` ("⚠ API error (attempt N): ..."); the Translator keeps these out of the answer. With `PI_AGY_SYSTEM_PROMPT=auto` (default) a fresh appended session refused before any output is cancelled at the first notice and the turn is retried once with the system text inline; if that is served, later sessions of this runtime start inline. Everywhere else (continued sessions, inline sessions) agy's own retries run, so a short throttle in a subagent's tool loop is ridden out; only agy giving up becomes an error (`agy quota exceeded: Antigravity answered RESOURCE_EXHAUSTED ...`, worded so pi-ai does not retry on top while pi-fallback-chains rotates). `UPGRADING.md` is the runbook; the probe and the SDK canary cost no quota.
105
108
 
106
109
  ## Tests
107
110
 
package/README.md CHANGED
@@ -4,7 +4,7 @@ Use Google Antigravity models (Gemini, Claude, GPT-OSS) in [pi](https://github.c
4
4
 
5
5
  It follows the design of `pi-claude-code`: **pi keeps the conversation, the approvals and the tool execution; agy is only the model.** Every pi request becomes one ACP prompt turn. When the model wants a pi tool it writes a small tool-call block, pi runs the tool, and the next request carries the result. Nothing is parked between requests, so a slow tool (a long `pytest` run, a user dialog) can take as long as it needs and there is no turn time limit.
6
6
 
7
- > Status: 0.1.1. The compatibility probe and live bridge checks passed on `agy 1.5.8`. Live turns succeeded on `gemini-3.8-flash`, `gemini-4-hydrogen` (including `xhigh`), and `gemini-pro-orchestrator-g1-pro`. A real pi surface check with the configured extensions also passed. Claude and GPT-OSS have not been exercised in a live model turn.
7
+ > Status: 0.1.2. The compatibility probe passed on `agy 1.5.8` and `1.5.9` (identical surface). On 2026-11-14 (agy 1.5.9) the Antigravity backend began refusing pi's default system prompt sent through the append hook with `RESOURCE_EXHAUSTED`; live `gemini-4-hydrogen` turns and pi-subagents runs succeed through the `auto` inline fallback (see `PI_AGY_SYSTEM_PROMPT`). Earlier live bridge checks passed on `agy 1.5.8`. Live turns succeeded on `gemini-3.8-flash`, `gemini-4-hydrogen` (including `xhigh`), and `gemini-pro-orchestrator-g1-pro`. A real pi surface check with the configured extensions also passed. Claude and GPT-OSS have not been exercised in a live model turn.
8
8
 
9
9
  ## Requirements
10
10
 
@@ -57,6 +57,7 @@ Environment variables (all optional). Invalid values fall back to the default.
57
57
  | `PI_AGY_CANCEL_GRACE_MS` | `3000` | wait this long for a cancel before giving up on a turn |
58
58
  | `PI_AGY_MAX_REPLAY_KB` | `8192` | refuse to replay a conversation larger than this |
59
59
  | `PI_AGY_CONTROL_TIMEOUT_SEC` | `60` | timeout for handshake and session calls |
60
+ | `PI_AGY_SYSTEM_PROMPT` | `auto` | how pi's system prompt reaches agy: `append` (the `session/new` append hook), `inline` (top of the first prompt), or `auto` (append; if Antigravity refuses a fresh appended session with `RESOURCE_EXHAUSTED` before any output, retry that turn inline once and keep using inline). In `auto` the refusal is saved in `<home>/state.json` for 24 hours (or until agy's version changes), so other pi processes, including subagents, start inline without a refused attempt |
60
61
  | `PI_AGY_TRACE` | off | `1` appends diagnostics to `<home>/trace.log` |
61
62
 
62
63
  pi's own request `timeoutMs`, when set, is honoured as a total deadline for the turn.
@@ -93,6 +94,7 @@ Example chain, mirrored from an `antigravity/*` chain:
93
94
  | no `agy/*` models in `/model` | agy not found, or the last use found it logged out or too old (hidden for 5 minutes) | `agy` once to sign in, then `/agy-bridge doctor` (a successful run clears the hint) |
94
95
  | `agy authentication required (not logged in)` | login expired | run `agy` and sign in |
95
96
  | `agy quota exhausted: ... Resets in ...` | the plan's quota for that model is used up (agy delivers this as a normal reply with no tokens; the bridge turns it into an error so fallback chains rotate) | use another model; the reset time is in the message |
97
+ | `agy quota exceeded: Antigravity answered RESOURCE_EXHAUSTED ...` | the backend refused the request (429). agy would retry five times (~75 s); the bridge stops at the first notice. Since 2026-11-14 the backend refuses pi's default system prompt when it comes through the append hook (all models), while the same text inline is served; `auto` handles this | nothing in `auto` mode; otherwise use another model. The message says whether the prompt was appended or inline |
96
98
  | `agy stalled for 120s with no output` | the model produced nothing for the silence limit | retry; raise `PI_AGY_SILENCE_SEC` for very long silent thinking |
97
99
  | `agy exited with status N` | the agy process died | retry (a new process starts); `/agy-bridge doctor` shows agy's last stderr |
98
100
  | `pi-agy-bridge is unavailable: agy ... below the minimum` | agy too old | `agy update` |
@@ -0,0 +1,231 @@
1
+ {
2
+ "schema": 1,
3
+ "agyVersion": "1.5.9",
4
+ "collectedAt": "2026-11-14T15:46:02.141Z",
5
+ "helpFlags": [
6
+ "--add-dir",
7
+ "--agent",
8
+ "--continue",
9
+ "--conversation",
10
+ "--dangerously-skip-permissions",
11
+ "--disable-slash-commands",
12
+ "--effort",
13
+ "--input-format",
14
+ "--json-schema",
15
+ "--log-file",
16
+ "--mode",
17
+ "--model",
18
+ "--new-project",
19
+ "--output-format",
20
+ "--print",
21
+ "--print-timeout",
22
+ "--project",
23
+ "--prompt",
24
+ "--prompt-interactive",
25
+ "--remote-agent",
26
+ "--remote-control",
27
+ "--sandbox",
28
+ "--settings",
29
+ "-c",
30
+ "-i",
31
+ "-p"
32
+ ],
33
+ "acpHelpFlags": [
34
+ "--add-dir",
35
+ "--agent",
36
+ "--app-data-dir",
37
+ "--app_data_dir",
38
+ "--cli_dir_name",
39
+ "--cli_log_file",
40
+ "--cloud_code_endpoint",
41
+ "--dangerously-skip-permissions",
42
+ "--disable-telemetry",
43
+ "--disable_telemetry",
44
+ "--gemini-dir",
45
+ "--gemini_dir",
46
+ "--help",
47
+ "--ide-mcp-port",
48
+ "--ide_mcp_port",
49
+ "--include-default-customizations",
50
+ "--is_google3_workspace",
51
+ "--is_google_internal",
52
+ "--log-file",
53
+ "--login",
54
+ "--override_user_agent_name",
55
+ "--process-per-session",
56
+ "--sandbox",
57
+ "--stdio",
58
+ "--use_stubby_auth",
59
+ "--worker",
60
+ "-h"
61
+ ],
62
+ "models": [
63
+ {
64
+ "id": "claude-opus-5-5-high",
65
+ "label": "Claude Opus 5.5 (High)"
66
+ },
67
+ {
68
+ "id": "claude-opus-5-5-low",
69
+ "label": "Claude Opus 5.5 (Low)"
70
+ },
71
+ {
72
+ "id": "claude-opus-5-5-medium",
73
+ "label": "Claude Opus 5.5 (Medium)"
74
+ },
75
+ {
76
+ "id": "claude-sonnet-5-5-high",
77
+ "label": "Claude Sonnet 5.5 (High)"
78
+ },
79
+ {
80
+ "id": "claude-sonnet-5-5-low",
81
+ "label": "Claude Sonnet 5.5 (Low)"
82
+ },
83
+ {
84
+ "id": "claude-sonnet-5-5-medium",
85
+ "label": "Claude Sonnet 5.5 (Medium)"
86
+ },
87
+ {
88
+ "id": "gemini-3.8-flash-high",
89
+ "label": "Gemini 3.8 Flash (High)"
90
+ },
91
+ {
92
+ "id": "gemini-3.8-flash-low",
93
+ "label": "Gemini 3.8 Flash (Low)"
94
+ },
95
+ {
96
+ "id": "gemini-3.8-flash-medium",
97
+ "label": "Gemini 3.8 Flash (Medium)"
98
+ },
99
+ {
100
+ "id": "gemini-4-argon-high",
101
+ "label": "Gemini 4 Argon (High)"
102
+ },
103
+ {
104
+ "id": "gemini-4-argon-low",
105
+ "label": "Gemini 4 Argon (Low)"
106
+ },
107
+ {
108
+ "id": "gemini-4-argon-medium",
109
+ "label": "Gemini 4 Argon (Medium)"
110
+ },
111
+ {
112
+ "id": "gemini-4-hydrogen-high",
113
+ "label": "Gemini 4 Hydrogen (High)"
114
+ },
115
+ {
116
+ "id": "gemini-4-hydrogen-low",
117
+ "label": "Gemini 4 Hydrogen (Low)"
118
+ },
119
+ {
120
+ "id": "gemini-4-hydrogen-medium",
121
+ "label": "Gemini 4 Hydrogen (Medium)"
122
+ },
123
+ {
124
+ "id": "gemini-4-hydrogen-xhigh",
125
+ "label": "Gemini 4 Hydrogen (XHigh)"
126
+ },
127
+ {
128
+ "id": "gemini-pro-orchestrator-g1-pro",
129
+ "label": "Orchestrator (Argon)"
130
+ },
131
+ {
132
+ "id": "gpt-oss-120b-medium",
133
+ "label": "GPT-OSS 120B (Medium)"
134
+ }
135
+ ],
136
+ "initialize": {
137
+ "protocolVersion": 1,
138
+ "agentName": "Antigravity ACP Server",
139
+ "agentVersion": "1.5.9",
140
+ "capabilities": {
141
+ "_meta.antigravity.systemPrompt.append": true,
142
+ "auth.logout": true,
143
+ "loadSession": true,
144
+ "load_session": true,
145
+ "promptCapabilities.audio": false,
146
+ "promptCapabilities.embeddedContext": true,
147
+ "promptCapabilities.image": true,
148
+ "sessionCapabilities.additionalDirectories": true,
149
+ "sessionCapabilities.close": true,
150
+ "sessionCapabilities.list": true,
151
+ "sessionCapabilities.load": true,
152
+ "sessionCapabilities.resume": true,
153
+ "session_capabilities.additionalDirectories": true,
154
+ "session_capabilities.close": true,
155
+ "session_capabilities.list": true,
156
+ "session_capabilities.load": true,
157
+ "session_capabilities.resume": true
158
+ },
159
+ "authMethodIds": [
160
+ "agent-platform",
161
+ "gemini-api-key",
162
+ "oauth-business",
163
+ "oauth-personal"
164
+ ]
165
+ },
166
+ "session": {
167
+ "configOptions": [
168
+ {
169
+ "id": "mode",
170
+ "type": "select",
171
+ "values": [
172
+ "accept-edits",
173
+ "auto",
174
+ "default",
175
+ "plan"
176
+ ]
177
+ },
178
+ {
179
+ "id": "model",
180
+ "type": "select",
181
+ "values": [
182
+ "claude-opus-5-5",
183
+ "claude-sonnet-5-5",
184
+ "gemini-3.8-flash",
185
+ "gemini-4-argon",
186
+ "gemini-4-hydrogen",
187
+ "gemini-pro-orchestrator-g1-pro",
188
+ "gpt-oss-120b-medium"
189
+ ]
190
+ },
191
+ {
192
+ "id": "thought_level",
193
+ "type": "select",
194
+ "values": [
195
+ "high",
196
+ "low",
197
+ "medium"
198
+ ]
199
+ }
200
+ ],
201
+ "modeIds": [
202
+ "accept-edits",
203
+ "auto",
204
+ "default",
205
+ "plan"
206
+ ],
207
+ "modelIds": [
208
+ "claude-opus-5-5-high",
209
+ "claude-opus-5-5-low",
210
+ "claude-opus-5-5-medium",
211
+ "claude-sonnet-5-5-high",
212
+ "claude-sonnet-5-5-low",
213
+ "claude-sonnet-5-5-medium",
214
+ "gemini-3.8-flash-high",
215
+ "gemini-3.8-flash-low",
216
+ "gemini-3.8-flash-medium",
217
+ "gemini-4-argon-high",
218
+ "gemini-4-argon-low",
219
+ "gemini-4-argon-medium",
220
+ "gemini-4-hydrogen-high",
221
+ "gemini-4-hydrogen-low",
222
+ "gemini-4-hydrogen-medium",
223
+ "gemini-4-hydrogen-xhigh",
224
+ "gemini-pro-orchestrator-g1-pro",
225
+ "gpt-oss-120b-medium"
226
+ ],
227
+ "metaKeys": [
228
+ "antigravity"
229
+ ]
230
+ }
231
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "agy": {
4
- "tested": ["1.5.3", "1.5.8"],
4
+ "tested": ["1.5.3", "1.5.8", "1.5.9"],
5
5
  "minimum": "1.5.1",
6
6
  "knownBad": []
7
7
  },
package/compat/probe.ts CHANGED
@@ -40,7 +40,7 @@ export const PROBE_PROTOCOL_VERSION = 1;
40
40
  export const PROBE_CLIENT_INFO = {
41
41
  name: "pi-agy-bridge-compat-probe",
42
42
  title: "pi-agy-bridge zero-cost compat probe",
43
- version: "0.1.1",
43
+ version: "0.1.2",
44
44
  } as const;
45
45
 
46
46
  /** One failed probe step. `step` names the command or exchange. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timmyjl12/pi-agy-bridge",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "pi provider for Google Antigravity (agy) models over the official ACP server, modelled on pi-claude-code: pi keeps the loop, history and tool execution",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -194,7 +194,7 @@ export class AcpProcess {
194
194
  const result = await this.#rpc.request("initialize", {
195
195
  protocolVersion: 1,
196
196
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
197
- clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.1.1" },
197
+ clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.1.2" },
198
198
  });
199
199
  return (result ?? {}) as AcpInitializeResult;
200
200
  }
package/src/config.ts CHANGED
@@ -4,6 +4,11 @@
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
 
7
+ /** How pi's system prompt reaches agy. `append`: `_meta.antigravity.systemPrompt.append` on `session/new`. `inline`: at
8
+ * the top of the first prompt (the conversation resource). `auto`: append, but when the backend answers a fresh appended
9
+ * session with RESOURCE_EXHAUSTED before any output, retry that turn once inline and keep using inline if it worked. */
10
+ export type SystemPromptDelivery = "auto" | "append" | "inline";
11
+
7
12
  export interface AgyConfig {
8
13
  /** The agy executable (PATH lookup when bare). */
9
14
  command: string;
@@ -26,6 +31,7 @@ export interface AgyConfig {
26
31
  replayMaxBytes: number;
27
32
  /** Per-request timeout for ACP control calls (initialize, session/new, set_config_option). */
28
33
  controlTimeoutMs: number;
34
+ systemPrompt: SystemPromptDelivery;
29
35
  }
30
36
 
31
37
  export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
@@ -40,6 +46,7 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
40
46
  // Gemini windows reach ~4 MB of text. agy's own frame limit is unmeasured: verify with a large live turn.
41
47
  replayMaxBytes: 8 * 1024 * 1024,
42
48
  controlTimeoutMs: 60_000,
49
+ systemPrompt: "auto",
43
50
  });
44
51
 
45
52
  /** Every environment variable loadConfig reads. pi resolves provider-scoped settings only through auth hooks, so the
@@ -56,8 +63,14 @@ export const CONFIG_ENV_NAMES = [
56
63
  "PI_AGY_CANCEL_GRACE_MS",
57
64
  "PI_AGY_MAX_REPLAY_KB",
58
65
  "PI_AGY_CONTROL_TIMEOUT_SEC",
66
+ "PI_AGY_SYSTEM_PROMPT",
59
67
  ] as const;
60
68
 
69
+ function delivery(value: string | undefined): SystemPromptDelivery {
70
+ const v = value?.trim().toLowerCase();
71
+ return v === "append" || v === "inline" || v === "auto" ? v : DEFAULT_CONFIG.systemPrompt;
72
+ }
73
+
61
74
  function positiveInt(value: string | undefined, fallback: number, scale = 1): number {
62
75
  if (value === undefined || value.trim() === "") return fallback;
63
76
  const parsed = Number(value);
@@ -79,5 +92,6 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
79
92
  cancelGraceMs: positiveInt(env.PI_AGY_CANCEL_GRACE_MS, DEFAULT_CONFIG.cancelGraceMs),
80
93
  replayMaxBytes: Math.max(1024, positiveInt(env.PI_AGY_MAX_REPLAY_KB, DEFAULT_CONFIG.replayMaxBytes, 1024)),
81
94
  controlTimeoutMs: positiveInt(env.PI_AGY_CONTROL_TIMEOUT_SEC, DEFAULT_CONFIG.controlTimeoutMs, 1000),
95
+ systemPrompt: delivery(env.PI_AGY_SYSTEM_PROMPT),
82
96
  };
83
97
  }
package/src/errors.ts CHANGED
@@ -54,6 +54,35 @@ export function normalizeAgyError(error: unknown): AgyError {
54
54
  return new AgyError("other", `agy error: ${text}`, { cause: error });
55
55
  }
56
56
 
57
+ /** agy's own retry notice, sent as an ordinary `agent_message_chunk` while it backs off and retries a failed backend
58
+ * call (recorded on agy 1.5.8 and 1.5.9):
59
+ * "\n⚠ API error (attempt 1): RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n" */
60
+ const API_RETRY_NOTICE = /^\r?\n?\u26A0\uFE0F? API error \(attempt (\d+)\): ([^\n]*)\r?\n?$/u;
61
+
62
+ export interface ApiRetryNotice {
63
+ attempt: number;
64
+ /** The backend error after the colon, e.g. `RESOURCE_EXHAUSTED (code 429): ...`. */
65
+ detail: string;
66
+ /** RESOURCE_EXHAUSTED / 429: retrying inside agy only deepens the throttle, so the turn is stopped at once. */
67
+ exhausted: boolean;
68
+ }
69
+
70
+ /** Parse one message chunk as agy's retry notice; undefined for anything else (model text). */
71
+ export function parseApiRetryNotice(text: string): ApiRetryNotice | undefined {
72
+ const match = API_RETRY_NOTICE.exec(text);
73
+ if (!match) return undefined;
74
+ const detail = match[2].trim();
75
+ return { attempt: Number(match[1]), detail, exhausted: /resource_exhausted|\b429\b/i.test(detail) };
76
+ }
77
+
78
+ /** agy reported RESOURCE_EXHAUSTED and the turn was stopped instead of waiting through agy's own retries (~75 s, each
79
+ * one counting against the same limit). Worded on purpose for both classifiers:
80
+ * - "quota exceeded" is in pi-ai's non-retryable list, so pi does not pile its own retries on top;
81
+ * - "quota" / "resource_exhausted" are retryable provider caps for pi-fallback-chains, so it rotates to another model. */
82
+ export function exhaustedError(notice: ApiRetryNotice, context: string): AgyError {
83
+ return new AgyError("quota", `agy quota exceeded: Antigravity answered ${notice.detail} (${context})`);
84
+ }
85
+
57
86
  /** The silence guard fired: no ACP traffic for `ms`. */
58
87
  export function stalledError(ms: number): AgyError {
59
88
  const seconds = ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
package/src/runtime.ts CHANGED
@@ -20,11 +20,21 @@ export interface RuntimeOptions {
20
20
 
21
21
  /** How long a recorded "logged out" or "too old" finding hides the models without re-checking. */
22
22
  export const UNUSABLE_HINT_MS = 5 * 60_000;
23
+ /** How long a recorded append-hook refusal sends every pi process straight to inline before the hook is tried again. */
24
+ export const APPEND_REFUSED_TTL_MS = 24 * 60 * 60_000;
23
25
  const NOT_FOUND_RECHECK_MS = 30_000;
24
26
 
25
27
  export class AgyRuntime {
26
28
  config: AgyConfig;
27
29
  readonly observedWindows = new Map<string, number>();
30
+ /** Set when a fresh session with the appended system prompt was refused (RESOURCE_EXHAUSTED before any output) and
31
+ * the same turn then succeeded with the system text inline, here or (via state.json, within APPEND_REFUSED_TTL_MS)
32
+ * in another pi process: later sessions skip the append hook (systemPrompt=auto). */
33
+ appendRefused = false;
34
+ /** Has state.json been consulted for a recorded refusal yet (once per runtime, on the first request)? */
35
+ #refusalLoaded: Promise<void> | undefined;
36
+ /** agy version the loaded refusal was recorded on; a different running agy ignores it (an update may lift the filter). */
37
+ #refusalVersion: string | undefined;
28
38
  readonly trace: Trace;
29
39
  #pool: SessionPool;
30
40
  #options: RuntimeOptions;
@@ -157,7 +167,11 @@ export class AgyRuntime {
157
167
  } else if (this.#hintRecorded) {
158
168
  this.#hintRecorded = false;
159
169
  update = readState(this.config.home).then((state: BridgeState) =>
160
- writeState(this.config.home, { lastOkAt: Date.now(), agyVersion: event.version ?? state.agyVersion }),
170
+ writeState(this.config.home, {
171
+ lastOkAt: Date.now(),
172
+ agyVersion: event.version ?? state.agyVersion,
173
+ ...(state.appendRefused ? { appendRefused: state.appendRefused } : {}),
174
+ }),
161
175
  );
162
176
  }
163
177
  if (!update) return;
@@ -201,6 +215,47 @@ export class AgyRuntime {
201
215
  await Promise.allSettled([...this.#retiring]);
202
216
  }
203
217
 
218
+ /** Pick up a refusal recorded by another pi process (a subagent, an earlier run). Cheap and only once: one small
219
+ * file read on the first request. An expired record is ignored, so the append hook gets one fresh try.
220
+ * Not a guarantee: pi processes that start together all read before the first one writes, so a burst of subagents
221
+ * can still spend one refused attempt each, once. */
222
+ loadAppendRefusal(): Promise<void> {
223
+ if (this.config.systemPrompt !== "auto") return Promise.resolve();
224
+ this.#refusalLoaded ??= readState(this.config.home).then((state) => {
225
+ const at = state.appendRefused?.at;
226
+ if (typeof at === "number" && Date.now() - at < APPEND_REFUSED_TTL_MS) {
227
+ this.appendRefused = true;
228
+ this.#refusalVersion = state.appendRefused?.agyVersion;
229
+ this.trace(`system prompt: append hook refused ${Math.round((Date.now() - at) / 60_000)} min ago (state.json); starting inline`);
230
+ }
231
+ });
232
+ return this.#refusalLoaded;
233
+ }
234
+
235
+ /** The append hook was refused and the inline retry was served: remember it here and for other pi processes. */
236
+ recordAppendRefusal(): void {
237
+ this.appendRefused = true;
238
+ this.#refusalVersion = undefined; // seen by this agy itself
239
+ if (this.#disposed) return;
240
+ const agyVersion = this.#report?.agyVersion || undefined;
241
+ const update = readState(this.config.home).then((state: BridgeState) =>
242
+ writeState(this.config.home, { ...state, appendRefused: { at: Date.now(), ...(agyVersion ? { agyVersion } : {}) } }),
243
+ );
244
+ const tracked: Promise<void> = update
245
+ .catch((error: unknown) => this.trace(`state write failed: ${describeError(error)}`))
246
+ .finally(() => this.#writes.delete(tracked));
247
+ this.#writes.add(tracked);
248
+ }
249
+
250
+ /** Should a fresh session carry pi's system text in its first prompt rather than the append hook? */
251
+ get systemInline(): boolean {
252
+ if (this.config.systemPrompt === "inline") return true;
253
+ if (this.config.systemPrompt !== "auto" || !this.appendRefused) return false;
254
+ // Known only after the first handshake: until then a recorded refusal is trusted.
255
+ const running = this.#report?.agyVersion;
256
+ return !(running && this.#refusalVersion && running !== this.#refusalVersion);
257
+ }
258
+
204
259
  /** Remember a context window reported by agy (`usage_update.size`) for the next model refresh. */
205
260
  observeWindow(modelId: string, size: number): void {
206
261
  if (Number.isFinite(size) && size > 0) this.observedWindows.set(modelId, Math.floor(size));
@@ -31,6 +31,8 @@ export interface SessionRequest {
31
31
  thoughtLevel: string | undefined;
32
32
  /** Text for `_meta.antigravity.systemPrompt.append` (pi system prompt plus the tool protocol). */
33
33
  systemAppend: string;
34
+ /** Force the system text into the first prompt instead of the append hook (see AgyConfig.systemPrompt). */
35
+ systemInline?: boolean;
34
36
  }
35
37
 
36
38
  export type LeaseOutcome =
@@ -387,7 +389,7 @@ export class SessionPool {
387
389
  async #openFresh(proc: AcpProcess, request: SessionRequest): Promise<Entry> {
388
390
  const workDir = this.#staging?.workDir ?? this.#config.home;
389
391
  // Without agy's append hook the system text cannot ride session/new: the caller inlines it into the first prompt.
390
- const viaMeta = this.#options.features?.().systemPromptAppend !== false;
392
+ const viaMeta = this.#options.features?.().systemPromptAppend !== false && request.systemInline !== true;
391
393
  const created = await proc.newSession({ cwd: workDir, systemPromptAppend: viaMeta ? request.systemAppend : undefined });
392
394
  const acpSessionId = created.sessionId as string;
393
395
  try {
package/src/state.ts CHANGED
@@ -13,6 +13,10 @@ export type UnusableKind = "auth" | "compat";
13
13
 
14
14
  export interface BridgeState {
15
15
  unusable?: { at: number; kind: UnusableKind; message: string };
16
+ /** The backend refused a session whose system prompt came through the append hook (RESOURCE_EXHAUSTED before any
17
+ * output) and the same turn was served inline. Shared by every pi process (subagents too) so they start inline
18
+ * instead of each spending a refused attempt; expires so the append hook is tried again. */
19
+ appendRefused?: { at: number; agyVersion?: string };
16
20
  lastOkAt?: number;
17
21
  agyVersion?: string;
18
22
  }
package/src/stream.ts CHANGED
@@ -19,7 +19,18 @@ import {
19
19
  } from "@earendil-works/pi-ai";
20
20
  import { PERMISSION_DENIED_UPDATE } from "./acp/connection.ts";
21
21
  import type { AcpContentBlock, AcpPromptResult, AcpUpdate, AcpUsage } from "./acp/types.ts";
22
- import { AgyError, emptyError, exitedError, looksLikeNotice, noticeError, normalizeAgyError, stalledError } from "./errors.ts";
22
+ import {
23
+ AgyError,
24
+ emptyError,
25
+ exhaustedError,
26
+ exitedError,
27
+ looksLikeNotice,
28
+ noticeError,
29
+ normalizeAgyError,
30
+ parseApiRetryNotice,
31
+ stalledError,
32
+ type ApiRetryNotice,
33
+ } from "./errors.ts";
23
34
  import { thoughtLevelFor } from "./model-catalog.ts";
24
35
  import type { AgyRuntime } from "./runtime.ts";
25
36
  import type { Lease, LeaseOutcome, SessionPool, SessionRequest } from "./session-pool.ts";
@@ -61,10 +72,12 @@ type OpenKind = "text" | "thinking";
61
72
  class Translator {
62
73
  readonly #stream: AssistantMessageEventStream;
63
74
  readonly #output: AssistantMessage;
64
- readonly #parser = new ToolCallStreamParser();
75
+ #parser = new ToolCallStreamParser();
65
76
  #open: { kind: OpenKind; index: number } | undefined;
66
77
  toolCalled = false;
67
78
  producedOutput = false;
79
+ /** agy's latest "⚠ API error (attempt N)" notice. Never shown as model text. */
80
+ retryNotice: ApiRetryNotice | undefined;
68
81
 
69
82
  constructor(stream: AssistantMessageEventStream, output: AssistantMessage) {
70
83
  this.#stream = stream;
@@ -76,9 +89,27 @@ class Translator {
76
89
  this.#delta("thinking", text);
77
90
  }
78
91
 
92
+ /** Forget a refused attempt (only thinking can have been emitted, since no text was produced): empty the message so
93
+ * a retried turn starts clean. */
94
+ reset(): void {
95
+ this.#close();
96
+ this.#output.content = [];
97
+ this.#parser = new ToolCallStreamParser();
98
+ }
99
+
79
100
  /** Returns true when this chunk completed a tool-call block. */
80
101
  message(chunk: string): boolean {
81
102
  if (this.toolCalled) return false;
103
+ // agy only retries before the model has answered; once real text flowed, a matching line is the model's own.
104
+ const notice = this.producedOutput ? undefined : parseApiRetryNotice(chunk);
105
+ if (notice) {
106
+ this.retryNotice = notice;
107
+ return false;
108
+ }
109
+ // After its last retry agy sends one more line, "⚠ <the same error>", and ends the turn. Not model text either.
110
+ if (this.retryNotice && !this.producedOutput && /^\s*\u26A0/u.test(chunk) && chunk.includes(this.retryNotice.detail.slice(0, 40))) {
111
+ return false;
112
+ }
82
113
  this.#apply(this.#parser.push(chunk));
83
114
  return this.toolCalled;
84
115
  }
@@ -153,7 +184,7 @@ class Translator {
153
184
  }
154
185
  }
155
186
 
156
- type CancelReason = "tool" | "abort" | "stall" | "timeout";
187
+ type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted";
157
188
 
158
189
  interface TurnResult {
159
190
  result: AcpPromptResult | undefined;
@@ -232,18 +263,50 @@ async function run(
232
263
  const piSessionId = options?.cacheRetention === "none" ? undefined : options?.sessionId;
233
264
  const systemText = [split.systemPrompt.trim(), renderToolProtocol(split.tools)].filter(Boolean).join("\n\n");
234
265
 
235
- lease = await acquireOrAbort(runtime.pool, options?.signal, {
266
+ await runtime.loadAppendRefusal();
267
+ const request: SessionRequest = {
236
268
  piSessionId,
237
269
  chain,
238
270
  latestCount: split.latest.length,
239
271
  modelId: model.id,
240
272
  thoughtLevel: thought,
241
273
  systemAppend: systemText,
242
- });
274
+ systemInline: runtime.systemInline,
275
+ };
276
+ lease = await acquireOrAbort(runtime.pool, options?.signal, request);
243
277
  options?.signal?.throwIfAborted();
244
278
 
245
- const prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
246
- const turn = await runTurn(runtime, model, options, lease, prompt, translator);
279
+ let prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
280
+ const deadline = options?.timeoutMs && options.timeoutMs > 0 ? Date.now() + options.timeoutMs : undefined;
281
+ // Stop at the first RESOURCE_EXHAUSTED only when the inline retry below can follow. Anywhere else agy's own retries
282
+ // (~75 s) are the best chance of getting through a short throttle, e.g. in the middle of a subagent's tool loop.
283
+ const inlineFallback = runtime.config.systemPrompt === "auto" && !lease.reused && !lease.systemInline;
284
+ let turn = await runTurn(runtime, model, options, lease, prompt, translator, undefined, inlineFallback);
285
+
286
+ // The Antigravity backend refuses some system prompts sent through the append hook with RESOURCE_EXHAUSTED on
287
+ // every try, while the same text inside the first prompt is served (measured on agy 1.5.9, 2026-11-14: pi's
288
+ // default prompt, three models). In `auto` mode retry such a turn once with the system text inline and, if that
289
+ // works, keep sending it inline for this runtime.
290
+ if (turn.cancelReason === "exhausted" && inlineFallback && !translator.producedOutput) {
291
+ runtime.trace(`turn: model=${model.id} RESOURCE_EXHAUSTED with the appended system prompt; retrying inline`);
292
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "exhausted and ignored cancel");
293
+ await lease.finish({ reusable: false });
294
+ lease = undefined;
295
+ translator.retryNotice = undefined;
296
+ translator.reset();
297
+ const remaining = deadline === undefined ? undefined : deadline - Date.now();
298
+ if (remaining !== undefined && remaining <= 0) {
299
+ throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
300
+ }
301
+ lease = await acquireOrAbort(runtime.pool, options?.signal, { ...request, systemInline: true });
302
+ options?.signal?.throwIfAborted();
303
+ prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
304
+ turn = await runTurn(runtime, model, options, lease, prompt, translator, remaining);
305
+ if (turn.cancelReason !== "exhausted" && turn.result !== undefined && translator.producedOutput) {
306
+ runtime.recordAppendRefusal();
307
+ runtime.trace("turn: inline system prompt served; later sessions send it inline");
308
+ }
309
+ }
247
310
  translator.finish();
248
311
 
249
312
  if (turn.result) mapUsage(model, turn.result.usage, output.usage);
@@ -261,6 +324,17 @@ async function run(
261
324
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "timed out and ignored cancel");
262
325
  throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
263
326
  }
327
+ // Either we stopped at a RESOURCE_EXHAUSTED notice, or agy gave up retrying on its own. Its notices were kept out of
328
+ // the text, so report the last one instead of an empty answer.
329
+ const notice = translator.retryNotice;
330
+ if (notice && (turn.cancelReason === "exhausted" || (!translator.producedOutput && !translator.toolCalled))) {
331
+ output.content = [];
332
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "exhausted and ignored cancel");
333
+ const how = lease.reused ? "continued session" : lease.systemInline ? "system prompt inline" : "system prompt appended";
334
+ const when = turn.cancelReason === "exhausted" ? "stopped at" : "agy gave up after";
335
+ if (notice.exhausted) throw exhaustedError(notice, `${model.id}, ${how}; ${when} agy attempt ${notice.attempt}`);
336
+ throw normalizeAgyError(new Error(`Antigravity API error after ${notice.attempt} attempts: ${notice.detail}`));
337
+ }
264
338
 
265
339
  // A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning, with NO usage
266
340
  // object at all (measured on agy 1.5.3). Real model turns always report tokens, so: usage present and zero is
@@ -386,10 +460,14 @@ async function runTurn(
386
460
  lease: Lease,
387
461
  prompt: AcpContentBlock[],
388
462
  translator: Translator,
463
+ /** Time left of pi's request timeout when this is a retried turn. */
464
+ remainingMs?: number,
465
+ /** Cancel at agy's first RESOURCE_EXHAUSTED notice instead of letting it retry. */
466
+ failFastExhausted = false,
389
467
  ): Promise<TurnResult> {
390
468
  const { process: proc, acpSessionId } = lease;
391
469
  const silenceMs = runtime.config.silenceMs;
392
- const totalMs = options?.timeoutMs && options.timeoutMs > 0 ? options.timeoutMs : 0;
470
+ const totalMs = remainingMs ?? (options?.timeoutMs && options.timeoutMs > 0 ? options.timeoutMs : 0);
393
471
  let totalTimer: NodeJS.Timeout | undefined;
394
472
  const graceMs = runtime.config.cancelGraceMs;
395
473
  let cancelReason: CancelReason | undefined;
@@ -422,7 +500,10 @@ async function runTurn(
422
500
  arm();
423
501
  switch (update.sessionUpdate) {
424
502
  case "agent_message_chunk":
425
- if (!cancelReason && translator.message(updateText(update))) requestCancel("tool");
503
+ if (cancelReason) break;
504
+ if (translator.message(updateText(update))) requestCancel("tool");
505
+ // agy would back off and retry up to five times (~75 s), each try counting against the same limit.
506
+ else if (failFastExhausted && translator.retryNotice?.exhausted) requestCancel("exhausted");
426
507
  break;
427
508
  case "agent_thought_chunk":
428
509
  if (!cancelReason) translator.thought(updateText(update));