@timmyjl12/pi-agy-bridge 0.4.1 → 0.4.3

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
@@ -75,6 +75,10 @@ agy truncates oversized converted prompt content (a real failure retained roughl
75
75
 
76
76
  The pool keeps reusable sessions in memory only, so a pi restart, a new pi process (`pi -c`) or an idle-stopped agy used to replay the whole transcript. agy persists every conversation in `<gemini-dir>/antigravity-cli/conversations/<id>.db` and reopens it with ACP `session/resume` without replaying it (verified on agy 1.5.17: in a new process, after `session/close`, with the session's appended system prompt still in force). After every reusable turn the pool writes a record `pi session id → {agy session id, chain length, last chain link, agy step count}` to `<gemini-dir>.resume.json` (`conversation-store.ts` `ResumeStore`, at most 200, most recent kept). When no pooled session fits, `#tryResume` reattaches only if (1) the record's chain length and last link equal the request's held prefix (each link hashes its predecessor, so this proves system prompt, tools, model, thinking level and every message are identical), (2) that agy conversation is not open or being resumed in this process, and (3) a read-only `node:sqlite` read of agy's `steps` table shows no `USER_INPUT` step (type 14) after the recorded step count and no fewer steps (`checkConversation`: continued / prompted / lost; idea from patlux/pi-antigravity-thin-client). Then it calls `session/resume`, sets model and thinking level and sends only the new input. Anything else (another client or branch continued it, the db is gone, `node:sqlite` is missing, resume fails, `PI_AGY_RESUME=0`, or agy does not advertise `sessionCapabilities.resume`) drops the record and replays into a fresh session exactly as before. Live check (`.plan/api-key-resume-thin-client-ideas/evidence/live-resume-check.txt`): a second process recalled a codeword with a 59-character prompt.
77
77
 
78
+ ### Silent backend retries (0.4.2)
79
+
80
+ agy 1.5.18 no longer streams its "⚠ API error (attempt N)" notices: a failing backend call is retried for minutes with no ACP update at all, and each failed attempt is only an ERROR_MESSAGE step (`step_type` 17) in the conversation store, its payload holding `API error (attempt N): <error>` (recorded 2026-11-26 on acct2: seven 503 "high demand" attempts over 122 s, ended by the 120 s silence guard). While a turn has produced no model output, `runTurn` reads those steps once a second (`readBackendAttempts`, read-only, counting only steps after the turn's own start) and cancels after `PI_AGY_BACKEND_RETRIES` (3). The error is `backendFailedError`: a 429/RESOURCE_EXHAUSTED becomes `agy quota exceeded: …` (provider cap, rotate), anything else `agy backend unavailable: …` (retryable, siblings stay eligible; "No capacity available for model X" is reworded so pi-fallback-chains does not read it as a provider-wide cap). Any model output ends the watch; without a conversation store the silence guard stays in charge.
81
+
78
82
  ## Process model
79
83
 
80
84
  One shared `agy acp` per extension runtime, started on first real use, serving every caller (main session, subagents, side calls). Start is single-flight. A turn that went silent or hit pi's `timeoutMs` and then ignores `session/cancel` for the grace period gets its process killed (our PID only, identity-checked); an aborted or tool-call turn that ignores the cancel only has its session discarded. Other turns on a killed process fail with `agy exited with status N`, which fallback chains treat as transient. An unconditional synchronous kill runs on pi's `exit` event. Every `session_shutdown` (`quit`, `reload`, `new`, `resume` or `fork`) recycles the outgoing runtime: stop the process, forget sessions/discovery, detach global hooks and flush writes without permanently latching the pool. A background caller on the outgoing model runtime can therefore retry through a fresh process, which the normal idle reaper stops later. Explicit `AgyRuntime.dispose()` remains terminal for real cleanup and replaced pools.
@@ -110,7 +114,7 @@ pi waits for the provider's availability `check` while it starts. The first desi
110
114
 
111
115
  Models carry a reference list price from pi's built-in catalog (`referenceCost`: the id, then without a baked-in level or `-thinking`, then with version dots/dashes swapped; first match among google, anthropic, google-vertex, openai, opencode, openrouter; zero when unknown). On a Google-login account pi shows it as covered by the subscription; on an API-key account it approximates what Google bills.
112
116
 
113
- Measured on agy 1.5.3 (`evidence/cache-and-usage-semantics.md`, pinned by `tests/usage.test.ts`): `inputTokens` is the uncached input, `cachedReadTokens` is separate, `outputTokens` already contains `thoughtTokens`, and `totalTokens == input + output + cachedRead`. pi's `Usage` has the same shape, so the mapping is a copy; the prompt size pi-context sees is `input + cacheRead + cacheWrite`.
117
+ Measured on agy 1.5.3 (`evidence/cache-and-usage-semantics.md`, pinned by `tests/usage.test.ts`): `inputTokens` is the uncached input, `cachedReadTokens` is separate, `outputTokens` already contains `thoughtTokens`, and `totalTokens == input + output + cachedRead`. For a single turn the pi usage fields map directly. When a request includes internal replay or an answer retry, `input`, `output`, `cacheRead`, `cacheWrite`, and cost still cover all reported turns. Pi uses `totalTokens` to estimate context, so that field holds the final turn's context size (or a transcript estimate when the final prompt usage is unavailable), not the sum of repeated billable prefixes.
114
118
 
115
119
  ## Errors
116
120
 
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.4.1. Version bump for the npm release of 0.4.0 (no code change). 0.4.0: Continued conversations reattach to agy's own stored conversation (ACP `session/resume`) instead of re-sending history; a read-only check of agy's conversation store falls back to replay when another client or branch continued it. Any account can optionally sign in with a Gemini API key set in `/agy-bridge menu` (agy's `gemini-api-key` method); without one, every account keeps using the real agy CLI with its own Google login. agy's transient "⚠ API error (attempt N)" retry lines no longer leak into answers mid-stream, models carry reference prices from pi's catalog, and a new end-to-end test drives the real pi CLI against a scripted agy. agy 1.5.18 is tested (compat probe identical to 1.5.17); google-antigravity 0.1.24 is still the latest SDK. 0.3.3: Leading quota warnings now trigger fallback even after billable thinking, concurrent pi processes use isolated per-account ACP logs, internal replay ACKs can no longer abort the real request as tool calls, and reasoning-only or whitespace-only answers get one bounded same-session recovery retry without losing buffered text or truncated tool calls. 0.3.2: Large conversation replay is now sequential and bounded, model-window overflow triggers pi compaction before any model call, and switching providers recomputes context from the full pi transcript. agy 1.5.17 and google-antigravity SDK 0.1.24 are tested. 0.3.1: active agy turns no longer hit pi's idle request timeout merely because their total duration exceeds it: every ACP update refreshes that deadline, while the independent silence guard still cancels inactive turns. 0.3.0: agy 1.5.16 and the `google-antigravity` SDK 0.1.24 are now tested; agy 1.5.17 is also recorded and tested with an identical ACP contract. agy 1.5.16 retired `gemini-pro-orchestrator-g1-pro`; its orchestrators are now `gemini-pro-orchestrator` (Carbon), `gemini-pro-orchestrator-argon` and `gemini-pro-orchestrator-neon`, and Gemini 4 Carbon (low, medium, high) is new. The SDK change (a removed `InputConfig.use_interactions_api` field) does not touch the bridge, which uses the SDK only as a drift canary. Stalls and timeouts are now easier to diagnose: an extra account keeps its previous agy log as `acp.prev.log`, and with `PI_AGY_TRACE=1` a stalled or timed-out turn records what agy last sent and when. agy 1.5.16 also forwards subagent and workflow questions to the editor; the bridge's carrier agent has no agy tools, subagents or skills, so agy never asks them here. 0.2.1: Extra-account sign-in works on agy 1.5.14: agy now prints a link and waits for the authorization code, so the bridge opens the link and asks for the code in a dialog. 0.2.0: Multiple Antigravity accounts: each extra account runs as its own provider `agy-<alias or id>` with its own login, managed from `/agy-bridge menu` or the `/agy-bridge` account commands; verified live on agy 1.5.14 with two Google accounts answering side by side. agy 1.5.14 is now tested: it refuses pi's appended system prompt silently (no notice for ~2 min), which `auto` now detects with a 30 s refusal probe and answers inline (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)). 0.1.5: the default bridge home now honors Pi's configured agent directory (`PI_CODING_AGENT_DIR`). Every Pi session shutdown now recycles the outgoing runtime instead of permanently latching it shut, so a late pi-advisor retry can start a fresh ACP process; explicit terminal disposal remains terminal. The compatibility probe passed on `agy 1.5.8`, `1.5.9` and `1.5.12`; the drift from 1.5.9 to 1.5.12 is additive only (the `gemini-4-neon` family, `gemini-pro-orchestrator-neon`, and `xhigh` as a `thought_level`). The `google-antigravity` SDK was then current at `0.1.23`. 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, GPT-OSS and the `gemini-4-neon` family have not been exercised in a live model turn.
7
+ > Status: 0.4.3. Large conversation replay no longer inflates Pi's context estimate and triggers unnecessary compaction. Billing still includes every reported replay turn. 0.4.2: agy 1.5.18 retries a failing backend (503 "high demand", 429) silently for minutes; the bridge now reads agy's failed-attempt steps from its conversation store and stops a turn with no output after `PI_AGY_BACKEND_RETRIES` (3) attempts, reporting `agy backend unavailable: …` or `agy quota exceeded: …` so fallback chains move on in seconds instead of after the 120 s silence guard. The account menu has *Use agy login (remove API key)* (also `/agy-bridge use-agy-login <id>`) to go back from an API key to the account's own agy login folder. 0.4.1: Version bump for the npm release of 0.4.0 (no code change). 0.4.0: Continued conversations reattach to agy's own stored conversation (ACP `session/resume`) instead of re-sending history; a read-only check of agy's conversation store falls back to replay when another client or branch continued it. Any account can optionally sign in with a Gemini API key set in `/agy-bridge menu` (agy's `gemini-api-key` method); without one, every account keeps using the real agy CLI with its own Google login. agy's transient "⚠ API error (attempt N)" retry lines no longer leak into answers mid-stream, models carry reference prices from pi's catalog, and a new end-to-end test drives the real pi CLI against a scripted agy. agy 1.5.18 is tested (compat probe identical to 1.5.17); google-antigravity 0.1.24 is still the latest SDK. 0.3.3: Leading quota warnings now trigger fallback even after billable thinking, concurrent pi processes use isolated per-account ACP logs, internal replay ACKs can no longer abort the real request as tool calls, and reasoning-only or whitespace-only answers get one bounded same-session recovery retry without losing buffered text or truncated tool calls. 0.3.2: Large conversation replay is now sequential and bounded, model-window overflow triggers pi compaction before any model call, and switching providers recomputes context from the full pi transcript. agy 1.5.17 and google-antigravity SDK 0.1.24 are tested. 0.3.1: active agy turns no longer hit pi's idle request timeout merely because their total duration exceeds it: every ACP update refreshes that deadline, while the independent silence guard still cancels inactive turns. 0.3.0: agy 1.5.16 and the `google-antigravity` SDK 0.1.24 are now tested; agy 1.5.17 is also recorded and tested with an identical ACP contract. agy 1.5.16 retired `gemini-pro-orchestrator-g1-pro`; its orchestrators are now `gemini-pro-orchestrator` (Carbon), `gemini-pro-orchestrator-argon` and `gemini-pro-orchestrator-neon`, and Gemini 4 Carbon (low, medium, high) is new. The SDK change (a removed `InputConfig.use_interactions_api` field) does not touch the bridge, which uses the SDK only as a drift canary. Stalls and timeouts are now easier to diagnose: an extra account keeps its previous agy log as `acp.prev.log`, and with `PI_AGY_TRACE=1` a stalled or timed-out turn records what agy last sent and when. agy 1.5.16 also forwards subagent and workflow questions to the editor; the bridge's carrier agent has no agy tools, subagents or skills, so agy never asks them here. 0.2.1: Extra-account sign-in works on agy 1.5.14: agy now prints a link and waits for the authorization code, so the bridge opens the link and asks for the code in a dialog. 0.2.0: Multiple Antigravity accounts: each extra account runs as its own provider `agy-<alias or id>` with its own login, managed from `/agy-bridge menu` or the `/agy-bridge` account commands; verified live on agy 1.5.14 with two Google accounts answering side by side. agy 1.5.14 is now tested: it refuses pi's appended system prompt silently (no notice for ~2 min), which `auto` now detects with a 30 s refusal probe and answers inline (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)). 0.1.5: the default bridge home now honors Pi's configured agent directory (`PI_CODING_AGENT_DIR`). Every Pi session shutdown now recycles the outgoing runtime instead of permanently latching it shut, so a late pi-advisor retry can start a fresh ACP process; explicit terminal disposal remains terminal. The compatibility probe passed on `agy 1.5.8`, `1.5.9` and `1.5.12`; the drift from 1.5.9 to 1.5.12 is additive only (the `gemini-4-neon` family, `gemini-pro-orchestrator-neon`, and `xhigh` as a `thought_level`). The `google-antigravity` SDK was then current at `0.1.23`. 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, GPT-OSS and the `gemini-4-neon` family have not been exercised in a live model turn.
8
8
 
9
9
  ## Requirements
10
10
 
@@ -80,7 +80,7 @@ agy-acct2 acct2 timm…2385@gmail.com enabled
80
80
  - **Settings.** Accounts are stored in `<PI_AGY_HOME>/accounts.json` (id, alias, email, enabled: no credentials). `PI_AGY_ACCOUNTS=acct2,acct3` adds accounts from the environment; `PI_AGY_ACCOUNT_<ID>_EMAIL` pins the expected Google account.
81
81
  - **Cost.** One more `agy acp` process per account while in use; each stops after `PI_AGY_IDLE_MIN`.
82
82
  - **Terms.** Whether using several Google accounts is allowed for your plans is your decision.
83
- - **Optional Gemini API key.** `/agy-bridge menu` → an account → *Use a Gemini API key…* (or `/agy-bridge apikey <id>`). While a key is stored there, that account's agy process signs in with agy's own `gemini-api-key` method in a separate folder (`gemini-apikey/`), billed per token on the key's Google Cloud project and offering Gemini models only. Enter nothing to remove it: the account goes back to its Google login, whose folder was never touched. The key is stored in the account folder (`api-key`, user-only permissions) and never logged; `GEMINI_API_KEY` from your environment is **never** used and is removed from every Google-login agy process, so an exported key can never silently move an account off its subscription.
83
+ - **Optional Gemini API key.** `/agy-bridge menu` → an account → *Use a Gemini API key…* (or `/agy-bridge apikey <id>`). While a key is stored there, that account's agy process signs in with agy's own `gemini-api-key` method in a separate folder (`gemini-apikey/`), billed per token on the key's Google Cloud project and offering Gemini models only. To go back, choose *Use agy login (remove API key)* (or `/agy-bridge use-agy-login <id>`, or enter nothing as the key): the account returns to its own agy login in `accounts/<id>/gemini`, which was never touched, and is checked at once. The key is stored in the account folder (`api-key`, user-only permissions) and never logged; `GEMINI_API_KEY` from your environment is **never** used and is removed from every Google-login agy process, so an exported key can never silently move an account off its subscription.
84
84
 
85
85
  How it works: agy switches to per-folder token storage when it sees `SSH_CONNECTION` in its environment (measured on agy 1.5.12 and 1.5.14). The bridge sets that variable only on extra-account processes. It is not a documented agy option, so the free compat probe records it (`fileTokenStorageTrigger`) and reports breaking drift if a new agy stops honouring it; the wrong-account protection fails closed in that case.
86
86
 
@@ -102,6 +102,7 @@ Environment variables (all optional). Invalid values fall back to the default.
102
102
  | `PI_AGY_CONTROL_TIMEOUT_SEC` | `60` | timeout for handshake and session calls |
103
103
  | `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. agy 1.5.14 retries the refusal silently for about two minutes, so in `auto` a fresh appended session that shows no model output (text or thinking) within PI_AGY_REFUSAL_PROBE_SEC is treated as refused too |
104
104
  | `PI_AGY_REFUSAL_PROBE_SEC` | `30` | `auto` only: seconds a fresh session with the appended system prompt may stay silent before it is retried inline (measured first output on agy 1.5.14: 0.4-3.4 s); `0` disables the probe |
105
+ | `PI_AGY_BACKEND_RETRIES` | `3` | while a turn has produced nothing, stop it once agy's backend has failed this many retried attempts (read from agy's conversation store; agy 1.5.18 retries 503/429 silently). `0` leaves it to `PI_AGY_SILENCE_SEC` |
105
106
  | `PI_AGY_RESUME` | on | `0` turns off reattaching continued pi sessions to agy's stored conversation (`session/resume`); every continuation then replays history as before 0.4.0 |
106
107
  | `PI_AGY_TRACE` | off | `1` appends diagnostics to `<home>/trace.log`, including, for a stalled or timed-out turn, how many updates agy sent, the kind of the last one and how long ago it arrived |
107
108
  | `PI_AGY_ACCOUNTS` | none | extra accounts by id, comma-separated, in addition to `accounts.json` (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)) |
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.4.1",
43
+ version: "0.4.3",
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.4.1",
3
+ "version": "0.4.3",
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",
@@ -73,6 +73,8 @@ export interface AccountView {
73
73
  auth: AuthMode;
74
74
  /** API-key accounts: a masked preview of the stored key. */
75
75
  apiKey?: { masked: string };
76
+ /** The account's agy Google login exists (default: agy's own; extra: its token file), whatever mode is active. */
77
+ hasGoogleLogin: boolean;
76
78
  }
77
79
 
78
80
  export interface ManagerOptions {
@@ -220,8 +222,10 @@ export class AccountManager {
220
222
  const identity = runtime?.identity;
221
223
  const auth: AuthMode = isDefault ? this.default.authMode : (account.auth ?? "google");
222
224
  const key = auth === "api-key" ? await runtime?.resolveApiKey() : undefined;
225
+ const hasGoogleLogin = isDefault || (await hasSavedLogin(this.home, account.id));
223
226
  return {
224
227
  auth,
228
+ hasGoogleLogin,
225
229
  ...(key ? { apiKey: { masked: maskApiKey(key) } } : {}),
226
230
  account,
227
231
  provider: providerIdFor(account),
@@ -229,7 +233,7 @@ export class AccountManager {
229
233
  isDefault,
230
234
  registered: this.#registered.has(account.id),
231
235
  // Google: the default account uses agy's own login; an extra one needs its token file. API key: a key exists.
232
- savedLogin: auth === "api-key" ? key !== undefined : isDefault || (await hasSavedLogin(this.home, account.id)),
236
+ savedLogin: auth === "api-key" ? key !== undefined : hasGoogleLogin,
233
237
  running: status?.alive === true,
234
238
  ...(status?.pid !== undefined && status.alive ? { pid: status.pid } : {}),
235
239
  sessions: { idle: status?.idle ?? 0, busy: status?.busy ?? 0 },
@@ -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.4.1" },
197
+ clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.4.3" },
198
198
  });
199
199
  return (result ?? {}) as AcpInitializeResult;
200
200
  }
package/src/config.ts CHANGED
@@ -42,6 +42,9 @@ export interface AgyConfig {
42
42
  /** Reattach continued pi sessions to agy's stored conversation with ACP `session/resume` instead of replaying
43
43
  * history (PI_AGY_RESUME=0 turns it off). */
44
44
  resume: boolean;
45
+ /** Stop a turn that has produced no model output after agy's backend failed this many retried attempts in a row
46
+ * (agy 1.5.18 retries 503/429 silently for minutes). 0 disables and leaves it to the silence guard. */
47
+ backendRetries: number;
45
48
  }
46
49
 
47
50
  export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
@@ -59,6 +62,7 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
59
62
  systemPrompt: "auto",
60
63
  refusalProbeMs: 30_000,
61
64
  resume: true,
65
+ backendRetries: 3,
62
66
  });
63
67
 
64
68
  /** Every environment variable loadConfig reads. pi resolves provider-scoped settings only through auth hooks, so the
@@ -78,6 +82,7 @@ export const CONFIG_ENV_NAMES = [
78
82
  "PI_AGY_SYSTEM_PROMPT",
79
83
  "PI_AGY_REFUSAL_PROBE_SEC",
80
84
  "PI_AGY_RESUME",
85
+ "PI_AGY_BACKEND_RETRIES",
81
86
  ] as const;
82
87
 
83
88
  function delivery(value: string | undefined): SystemPromptDelivery {
@@ -109,5 +114,6 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
109
114
  systemPrompt: delivery(env.PI_AGY_SYSTEM_PROMPT),
110
115
  refusalProbeMs: positiveInt(env.PI_AGY_REFUSAL_PROBE_SEC, DEFAULT_CONFIG.refusalProbeMs, 1000),
111
116
  resume: !/^(0|false|off|no)$/i.test(env.PI_AGY_RESUME?.trim() ?? ""),
117
+ backendRetries: positiveInt(env.PI_AGY_BACKEND_RETRIES, DEFAULT_CONFIG.backendRetries),
112
118
  };
113
119
  }
@@ -19,8 +19,71 @@ import { writeFileAtomic } from "./atomic-write.ts";
19
19
  * 101 SYSTEM_MESSAGE (resume marker), 17 on failed attempts. */
20
20
  export const USER_INPUT_STEP_TYPE = 14;
21
21
 
22
+ /** agy's `steps.step_type` for a failed backend attempt it is about to retry (an ERROR_MESSAGE step). Measured on
23
+ * agy 1.5.17/1.5.18: the payload holds "API error (attempt N): Error 503, Message: …, Status: UNAVAILABLE". agy 1.5.18
24
+ * no longer streams these as message chunks, so this store is the only per-session place they appear. */
25
+ export const ERROR_STEP_TYPE = 17;
26
+
22
27
  export type ConversationSinceRecord = "continued" | "prompted" | "lost";
23
28
 
29
+ export interface BackendAttempt {
30
+ idx: number;
31
+ attempt: number;
32
+ /** The backend error after the colon, e.g. `Error 503, Message: This model is …, Status: UNAVAILABLE`. */
33
+ detail: string;
34
+ }
35
+
36
+ /** The text run ends at the next protobuf control byte (a field tag/length is a byte below 0x20 or a mangled one). */
37
+ const ATTEMPT_TEXT = /API error \(attempt (\d+)\):\s*([^\x00-\x1f\x7f\uFFFD]{1,600})/;
38
+
39
+ /** Pull agy's retry text out of a step payload (a protobuf blob: the text is a plain UTF-8 run inside it). */
40
+ export function parseAttemptPayload(payload: unknown): { attempt: number; detail: string } | undefined {
41
+ const text =
42
+ typeof payload === "string" ? payload : payload instanceof Uint8Array ? Buffer.from(payload).toString("utf8") : undefined;
43
+ if (!text) return undefined;
44
+ const match = ATTEMPT_TEXT.exec(text);
45
+ if (!match) return undefined;
46
+ // "..., Status: UNAVAILABLE, Details: []" may run straight into the next field's printable bytes; cut there.
47
+ const detail = (match[2] as string).replace(/(Details: \[[^\]]*\]).*$/s, "$1").trim();
48
+ return { attempt: Number(match[1]), detail };
49
+ }
50
+
51
+ /** Step count of a conversation (the index the next step will get), or undefined when it cannot be read. */
52
+ export async function stepCount(geminiDir: string, sessionId: string): Promise<number | undefined> {
53
+ return (await readConversationSteps(geminiDir, sessionId))?.steps;
54
+ }
55
+
56
+ /** agy's failed backend attempts in this conversation from step `fromStep` on, oldest first. Read-only. */
57
+ export async function readBackendAttempts(geminiDir: string, sessionId: string, fromStep: number): Promise<BackendAttempt[] | undefined> {
58
+ if (!SESSION_ID.test(sessionId)) return undefined;
59
+ const file = conversationDbPath(geminiDir, sessionId);
60
+ if (!existsSync(file)) return undefined;
61
+ const sqlite = await loadSqlite();
62
+ if (!sqlite) return undefined;
63
+ let db: import("node:sqlite").DatabaseSync | undefined;
64
+ try {
65
+ db = new sqlite.DatabaseSync(file, { readOnly: true });
66
+ db.exec("PRAGMA busy_timeout = 1500");
67
+ const rows = db
68
+ .prepare("SELECT idx, step_payload AS payload FROM steps WHERE idx >= ? AND step_type = ? ORDER BY idx")
69
+ .all(fromStep, ERROR_STEP_TYPE) as Array<{ idx: unknown; payload: unknown }>;
70
+ const out: BackendAttempt[] = [];
71
+ for (const row of rows) {
72
+ const parsed = parseAttemptPayload(row.payload);
73
+ if (parsed) out.push({ idx: Number(row.idx), ...parsed });
74
+ }
75
+ return out;
76
+ } catch {
77
+ return undefined;
78
+ } finally {
79
+ try {
80
+ db?.close();
81
+ } catch {
82
+ // already read
83
+ }
84
+ }
85
+ }
86
+
24
87
  export function conversationDbPath(geminiDir: string, sessionId: string): string {
25
88
  return path.join(geminiDir, "antigravity-cli", "conversations", `${sessionId}.db`);
26
89
  }
package/src/errors.ts CHANGED
@@ -83,6 +83,21 @@ export function exhaustedError(notice: ApiRetryNotice, context: string): AgyErro
83
83
  return new AgyError("quota", `agy quota exceeded: Antigravity answered ${notice.detail} (${context})`);
84
84
  }
85
85
 
86
+ /** agy's backend kept failing while the turn had produced nothing (agy 1.5.18 retries silently; the failures are read
87
+ * from its conversation store). Worded for the classifiers: a 429/RESOURCE_EXHAUSTED one is a quota (provider cap,
88
+ * rotate); anything else (503 "high demand", "No capacity available for model X") is "unavailable", which
89
+ * pi-fallback-chains retries on another model, without the words "quota" or "capacity" so siblings stay eligible. */
90
+ export function backendFailedError(attempts: number, detail: string, context: string): AgyError {
91
+ const text = detail.replace(/\s+/g, " ").replace(/,?\s*Details: \[\]\s*$/, "").trim().slice(0, 300);
92
+ if (/resource_exhausted|\b429\b|quota/i.test(text)) {
93
+ return new AgyError("quota", `agy quota exceeded: Antigravity refused ${attempts} attempts in a row: ${text} (${context})`);
94
+ }
95
+ // "No capacity available for model X" is that one model's problem, but the classifier reads a bare "capacity" as a
96
+ // provider-wide cap and would skip the account's other models. Say it without that word.
97
+ const safe = text.replace(/no capacity available for model (\S+)/gi, "model $1 has no free servers").replace(/\bcapacity\b/gi, "load");
98
+ return new AgyError("other", `agy backend unavailable: Antigravity failed ${attempts} attempts in a row: ${safe} (${context})`);
99
+ }
100
+
86
101
  /** The silence guard fired: no ACP traffic for `ms`. */
87
102
  export function stalledError(ms: number): AgyError {
88
103
  const seconds = ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ const COMMANDS: readonly AutocompleteItem[] = [
25
25
  { value: "add", label: "add <id> [alias]", description: "Add an Antigravity account and sign it in" },
26
26
  { value: "login", label: "login <id>", description: "Sign an extra account in (or switch its Google account)" },
27
27
  { value: "apikey", label: "apikey <id>", description: "Set an account's Gemini API key (used instead of its Google login), or clear it" },
28
+ { value: "use-agy-login", label: "use-agy-login <id>", description: "Remove an account's API key and go back to its agy Google login" },
28
29
  { value: "alias", label: "alias <id> [alias]", description: "Set or clear an account's alias (provider agy-<alias>)" },
29
30
  { value: "email", label: "email <id> [email]", description: "Set or clear the expected Google account by hand" },
30
31
  { value: "enable", label: "enable <id>", description: "Register a disabled account's provider again" },
@@ -92,10 +93,10 @@ function completions(manager: AccountManager, prefix: string): AutocompleteItem[
92
93
  }
93
94
  const sub = parts[0];
94
95
  if (parts.length > 2) return null; // the account is the only argument that completes
95
- if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor", "apikey"].includes(sub)) return null;
96
+ if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor", "apikey", "use-agy-login"].includes(sub)) return null;
96
97
  const typed = parts[1] ?? "";
97
98
  const ids = [
98
- ...(["check", "models", "reset", "doctor", "apikey"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
99
+ ...(["check", "models", "reset", "doctor", "apikey", "use-agy-login"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
99
100
  ...(sub === "reset" ? [{ id: "all", note: "every account" }] : []),
100
101
  ...manager.accounts.map((account) => ({
101
102
  id: account.id,
@@ -163,6 +164,9 @@ export async function handle(manager: AccountManager, args: string, ctx: Extensi
163
164
  case "login":
164
165
  await runLogin(manager, extra(), ctx, say);
165
166
  return;
167
+ case "use-agy-login":
168
+ await runAccountAction(manager, need(), "googlelogin", ctx, say);
169
+ return;
166
170
  case "apikey": {
167
171
  const id = need();
168
172
  if (!ctx.hasUI) throw new Error("setting an API key needs the interactive UI (the key is never taken from the command line)");
@@ -48,6 +48,8 @@ export interface Lease {
48
48
  readonly acpSessionId: string;
49
49
  /** True when the agy session already holds the conversation prefix: send only the latest input. */
50
50
  readonly reused: boolean;
51
+ /** agy's data dir for this session (its conversation store lives below it); undefined before staging. */
52
+ readonly geminiDir?: string;
51
53
  /** True for a fresh session whose agy has no system-prompt hook: the caller must put the system text (pi's prompt
52
54
  * and the tool protocol) into this session's first prompt. Always false for a reused session. */
53
55
  readonly systemInline: boolean;
@@ -683,6 +685,7 @@ export class SessionPool {
683
685
  process: entry.process,
684
686
  acpSessionId: entry.acpSessionId,
685
687
  reused,
688
+ geminiDir: this.#staging?.geminiDir,
686
689
  systemInline: !reused && entry.systemInline,
687
690
  finish: async (outcome) => {
688
691
  if (finished) return;
package/src/stream.ts CHANGED
@@ -20,8 +20,10 @@ import {
20
20
  import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
21
21
  import { PERMISSION_DENIED_UPDATE } from "./acp/connection.ts";
22
22
  import type { AcpContentBlock, AcpPromptResult, AcpUpdate, AcpUsage } from "./acp/types.ts";
23
+ import { readBackendAttempts, stepCount, type BackendAttempt } from "./conversation-store.ts";
23
24
  import {
24
25
  AgyError,
26
+ backendFailedError,
25
27
  emptyError,
26
28
  exhaustedError,
27
29
  exitedError,
@@ -41,9 +43,15 @@ import { hashChain, serializeHistory, serializeLatest, splitContext } from "./tr
41
43
  const HISTORY_URI = "pi://conversation.md";
42
44
  /** agy truncates converted prompt content at roughly 192 KiB. Keep a conservative margin for its wrappers. */
43
45
  const PROMPT_CHUNK_BYTES = 128 * 1024;
46
+ /** How often agy's conversation store is read for failed backend attempts while a turn has no output. */
47
+ const BACKEND_POLL_MS = 1_000;
44
48
  const CONTEXT_SAFETY_RATIO = 0.15;
45
49
  const MIN_OUTPUT_RESERVE = 32_768;
46
50
 
51
+ function estimateTranscriptTokens(messages: TranscriptContext["messages"]): number {
52
+ return messages.reduce((sum, message) => sum + estimateMessageTokens(message), 0);
53
+ }
54
+
47
55
  /** Give pi a context-overflow signal before agy can silently truncate or bill a request that cannot fit. Uses the
48
56
  * same token estimate and safety-margin shape as pi's own request option handling, scaled to each model's window. */
49
57
  function assertContextWindow(model: Model<any>, context: TranscriptContext, options: SimpleStreamOptions | undefined): void {
@@ -54,7 +62,7 @@ function assertContextWindow(model: Model<any>, context: TranscriptContext, opti
54
62
  // recompute every message instead of importing that provider-specific view of context size.
55
63
  const tokens =
56
64
  usageMessage?.role === "assistant" && (usageMessage.provider !== model.provider || usageMessage.api !== model.api)
57
- ? context.messages.reduce((sum, message) => sum + estimateMessageTokens(message), 0)
65
+ ? estimateTranscriptTokens(context.messages)
58
66
  : estimate.tokens;
59
67
  const safety = Math.max(4096, Math.ceil(tokens * CONTEXT_SAFETY_RATIO));
60
68
  const outputReserve = Math.min(options?.maxTokens ?? model.maxTokens, MIN_OUTPUT_RESERVE);
@@ -275,11 +283,13 @@ class Translator {
275
283
  /** `exhausted`: agy's RESOURCE_EXHAUSTED notice arrived (agy <= 1.5.12 sends one per retry). `refused`: a fresh session
276
284
  * with the appended system prompt produced nothing within the refusal probe window (agy 1.5.14 retries silently and
277
285
  * sends one notice only after ~140 s). Both mean "retry inline" in auto mode. */
278
- type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted" | "refused";
286
+ type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted" | "refused" | "backend";
279
287
 
280
288
  interface TurnResult {
281
289
  result: AcpPromptResult | undefined;
282
290
  cancelReason: CancelReason | undefined;
291
+ /** With cancelReason "backend": agy's failed attempts seen in its conversation store, and the last error. */
292
+ backend?: { attempts: number; detail: string };
283
293
  /** The prompt did not settle within the grace period after a cancel. */
284
294
  wedged: boolean;
285
295
  }
@@ -367,6 +377,10 @@ async function runReplayPart(
367
377
  translator.finish();
368
378
  replayStream.end();
369
379
  if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
380
+ if (turn.cancelReason === "backend") {
381
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "backend failed and ignored cancel");
382
+ throw backendFailedError(turn.backend?.attempts ?? 0, turn.backend?.detail ?? "unknown", `${model.id}, replay part ${index}/${total}`);
383
+ }
370
384
  if (turn.cancelReason === "stall") {
371
385
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay stalled and ignored cancel");
372
386
  throw stalledError(runtime.config.silenceMs);
@@ -561,13 +575,29 @@ async function run(
561
575
  }
562
576
  translator.finish();
563
577
 
564
- if (turn.result) mapUsage(model, mergeUsage([...replayUsages, turn.result.usage]), output.usage);
578
+ if (turn.result) {
579
+ const finalUsage = turn.result.usage;
580
+ mapUsage(model, mergeUsage([...replayUsages, finalUsage]), output.usage);
581
+ if (replayUsages.some((usage) => usage !== undefined) && output.usage.totalTokens > 0) {
582
+ // The breakdown and cost are billable totals. Pi reads totalTokens as a single context size,
583
+ // so don't count the same growing prefix once per replay or recovery request.
584
+ const finalPromptTokens = (finalUsage?.inputTokens ?? 0) + (finalUsage?.cachedReadTokens ?? 0) + (finalUsage?.cachedWriteTokens ?? 0);
585
+ output.usage.totalTokens = finalPromptTokens > 0
586
+ ? finalPromptTokens + (finalUsage?.outputTokens ?? 0)
587
+ : estimateTranscriptTokens(context.messages) + estimateMessageTokens(output);
588
+ }
589
+ }
565
590
  output.rawStopReason = turn.result?.stopReason;
566
591
  runtime.trace(
567
592
  `turn: model=${model.id} reused=${lease.reused} agy=${turn.result?.stopReason ?? "none"} in=${output.usage.input} cacheRead=${output.usage.cacheRead} out=${output.usage.output} replayParts=${replayUsages.length} promptChars=${promptChars}`,
568
593
  );
569
594
 
570
595
  if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
596
+ if (turn.cancelReason === "backend") {
597
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "backend failed and ignored cancel");
598
+ output.content = [];
599
+ throw backendFailedError(turn.backend?.attempts ?? 0, turn.backend?.detail ?? "unknown", `${model.id}, ${lease.reused ? "continued session" : "fresh session"}`);
600
+ }
571
601
  if (turn.cancelReason === "stall") {
572
602
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "stalled and ignored cancel");
573
603
  throw stalledError(runtime.config.silenceMs);
@@ -735,6 +765,8 @@ async function runTurn(
735
765
  let graceTimer: NodeJS.Timeout | undefined;
736
766
  let silenceTimer: NodeJS.Timeout | undefined;
737
767
  let probeTimer: NodeJS.Timeout | undefined;
768
+ let backendTimer: NodeJS.Timeout | undefined;
769
+ let backend: { attempts: number; detail: string } | undefined;
738
770
  let settled = false;
739
771
  // Diagnostics for stalls and timeouts (PI_AGY_TRACE=1): what agy last sent, and when.
740
772
  const startedAt = Date.now();
@@ -759,6 +791,7 @@ async function runTurn(
759
791
  if (silenceTimer) clearTimeout(silenceTimer);
760
792
  if (totalTimer) clearTimeout(totalTimer);
761
793
  if (probeTimer) clearTimeout(probeTimer);
794
+ if (backendTimer) clearInterval(backendTimer);
762
795
  proc.cancel(acpSessionId);
763
796
  graceTimer = setTimeout(expire, graceMs);
764
797
  graceTimer.unref();
@@ -825,6 +858,36 @@ async function runTurn(
825
858
  }, refusalProbeMs);
826
859
  probeTimer.unref();
827
860
  }
861
+ // agy 1.5.18 retries a failing backend (503 "high demand", 429) silently for minutes and only its conversation
862
+ // store records each failed attempt. While the model has said nothing, read those attempts and stop after
863
+ // `backendRetries` of them in a row, so fallback chains move on in seconds instead of after the silence guard.
864
+ // Any model output ends the watch: agy only retries before the model has produced anything.
865
+ const retries = runtime.config.backendRetries;
866
+ const geminiDir = lease.geminiDir;
867
+ if (retries > 0 && geminiDir) {
868
+ const fromStep = (await stepCount(geminiDir, acpSessionId)) ?? 0;
869
+ let reading = false;
870
+ backendTimer = setInterval(() => {
871
+ if (reading || settled || cancelReason) return;
872
+ if (translator.producedOutput || translator.toolCalled) {
873
+ if (backendTimer) clearInterval(backendTimer);
874
+ return;
875
+ }
876
+ reading = true;
877
+ void readBackendAttempts(geminiDir, acpSessionId, fromStep)
878
+ .then((attempts) => {
879
+ if (!attempts || attempts.length < retries || settled || cancelReason || translator.producedOutput) return;
880
+ const last = attempts[attempts.length - 1] as BackendAttempt;
881
+ backend = { attempts: attempts.length, detail: last.detail };
882
+ runtime.trace(`turn: backend model=${model.id} failed ${attempts.length} attempts with no output; last: ${last.detail.slice(0, 160)}`);
883
+ requestCancel("backend");
884
+ })
885
+ .finally(() => {
886
+ reading = false;
887
+ });
888
+ }, BACKEND_POLL_MS);
889
+ backendTimer.unref();
890
+ }
828
891
  const promptPromise = proc.prompt(acpSessionId, prompt).then(
829
892
  (result) => ({ kind: "result" as const, result }),
830
893
  (error: unknown) => ({ kind: "error" as const, error }),
@@ -833,7 +896,7 @@ async function runTurn(
833
896
  if (first === "grace") {
834
897
  // The prompt ignored the cancel. Do not wait for it forever; the caller discards or kills the session.
835
898
  void promptPromise;
836
- return { result: undefined, cancelReason, wedged: true };
899
+ return { result: undefined, cancelReason, wedged: true, ...(backend ? { backend } : {}) };
837
900
  }
838
901
  if (first.kind === "error") {
839
902
  if (!proc.alive) {
@@ -842,12 +905,13 @@ async function runTurn(
842
905
  }
843
906
  throw first.error;
844
907
  }
845
- return { result: first.result, cancelReason, wedged: false };
908
+ return { result: first.result, cancelReason, wedged: false, ...(backend ? { backend } : {}) };
846
909
  } finally {
847
910
  settled = true;
848
911
  if (silenceTimer) clearTimeout(silenceTimer);
849
912
  if (totalTimer) clearTimeout(totalTimer);
850
913
  if (probeTimer) clearTimeout(probeTimer);
914
+ if (backendTimer) clearInterval(backendTimer);
851
915
  if (graceTimer) clearTimeout(graceTimer);
852
916
  options?.signal?.removeEventListener("abort", onAbort);
853
917
  stop();
package/src/ui/menu.ts CHANGED
@@ -170,6 +170,17 @@ export function accountActionsView(view: AccountView, loginRunning: boolean): Pa
170
170
  apiKey ? (view.apiKey?.masked ?? "set") : "not set",
171
171
  apiKey ? "ok" : "muted",
172
172
  );
173
+ if (apiKey) {
174
+ add(
175
+ "googlelogin",
176
+ "Use agy login (remove API key)",
177
+ extra
178
+ ? `Delete the stored key and go back to this account's own agy Google login in accounts/${view.account.id}/gemini (kept untouched)`
179
+ : "Delete the stored key and go back to agy's own Google login",
180
+ extra ? (view.hasGoogleLogin ? "login saved" : "needs sign-in") : "agy login",
181
+ extra && !view.hasGoogleLogin ? "warn" : "ok",
182
+ );
183
+ }
173
184
  if (extra && !apiKey) {
174
185
  add(
175
186
  "login",
@@ -482,6 +493,22 @@ export async function runAccountAction(
482
493
  if (!view) throw new Error(`no account "${id}"`);
483
494
  const provider = view.isDefault ? "agy" : view.provider;
484
495
  switch (action) {
496
+ case "googlelogin": {
497
+ if (view.auth !== "api-key") {
498
+ notify(`pi-agy-bridge: ${provider} already uses its agy Google login`, "info");
499
+ break;
500
+ }
501
+ if (ctx.hasUI && !(await ctx.ui.confirm("Use agy login?", `Delete ${provider}'s stored API key and sign in with its agy Google login again?`))) break;
502
+ await manager.setApiKey(id, undefined);
503
+ const back = (await manager.views()).find((entry) => entry.account.id === id);
504
+ if (!view.isDefault && back && !back.savedLogin) {
505
+ notify(`pi-agy-bridge: API key removed; ${provider} has no saved agy login yet — run /agy-bridge login ${id}`, "warning");
506
+ } else {
507
+ const check = await manager.check(id);
508
+ notify(`pi-agy-bridge: API key removed; ${check.message}`, check.ok ? "info" : "warning");
509
+ }
510
+ break;
511
+ }
485
512
  case "apikey":
486
513
  await promptApiKey(manager, id, ctx, notify);
487
514
  break;