@timmyjl12/pi-agy-bridge 0.3.2 → 0.4.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/ARCHITECTURE.md CHANGED
@@ -67,7 +67,13 @@ A pooled session is reused only when all of these hold:
67
67
 
68
68
  Invalidation comes from three places: pi-context's rewrite registry (`Symbol.for("claude-bridge:markRebuildHooks")`), pi-ai `cleanupSessionResources` (`/fresh`, session end), and the prefix check itself as the backstop. Boundary compaction and rollover notify the registry; pi-context shake currently does not, but its edits change the hash chain and therefore force the same safe fresh-session replay even without a notification. Busy/opening leases use invalidation sequence markers, and repeat invalidation refreshes recency before the bounded map evicts its oldest entry. Replaying is always correct; reuse saves a `session/new` (about a second), the resent history and, above roughly 16k prompt tokens, most of the prompt cost: agy's cache works only inside a continuing session (three fresh sessions with an identical 22.9k prefix cached nothing). A session that ended at a tool call is kept for `PI_AGY_TOOL_TTL_MIN` (30 min) because pi may run a long tool; any retained session also keeps the process alive.
69
69
 
70
- agy truncates oversized converted prompt content (a real failure retained roughly 192 KiB). `buildPrompt` therefore splits replayed history, inline instructions and latest input into ordered blocks of at most 128 KiB of UTF-8. Embedded history uses `pi://conversation.md`, then `?part=2`, `?part=3`, and so on; the plain-text fallback splits its combined text the same way. Chunking never splits a Unicode codepoint. When total replay exceeds that budget, the blocks become sequential bounded prompt turns within one agy session: the model acknowledges each historical part, receives the actual request only after every part arrives, and the bridge aggregates usage from all parts instead of hiding replay cost. The completed session is then reused under the normal exact-prefix rule. Before acquisition, a separate model-window guard uses pi-ai's `estimateContextTokens` plus 15% safety and the output reserve (up to 32,768 tokens); if that cannot fit `model.contextWindow`, the bridge returns `context_length_exceeded` before any model call so pi compacts instead of replaying beyond the backend limit. The last assistant's usage is used only when it belongs to the same provider/api; on a handoff (for example agy → neuralwatt), every pi message is re-estimated because the old provider's usage can describe a compacted session mirror rather than pi's full history. The 8 MiB `PI_AGY_MAX_REPLAY_KB` total guard remains independent of these per-block and token-window limits. A real agy check with a late-history synthetic fact returned the fact with zero truncation markers and 42,164 cacheRead tokens.
70
+ Internal replay acknowledgements and the single whitespace-recovery prompt are transport details, not pi transcript messages. They stay inside the same agy session; the next exact continuation sends only pi's new suffix, while a fresh replay uses pi's transcript as the source of truth. Parser-buffered text and truncated tool calls are flushed before empty-answer recovery is considered, so recovery cannot discard emitted work. These rules preserve the context delivered to the model; they do not guarantee correct model reasoning over that context.
71
+
72
+ agy truncates oversized converted prompt content (a real failure retained roughly 192 KiB). `buildPrompt` therefore splits replayed history, inline instructions and latest input into ordered blocks of at most 128 KiB of UTF-8. Embedded history uses `pi://conversation.md`, then `?part=2`, `?part=3`, and so on; the plain-text fallback splits its combined text the same way. Chunking never splits a Unicode codepoint. When total replay exceeds that budget, the blocks become sequential bounded prompt turns within one agy session: the model acknowledges each historical part, receives the actual request only after every part arrives, and the bridge aggregates usage from all parts instead of hiding replay cost. Replay ACK turns do not interpret pi's tool protocol: a protocol-looking block is unexecuted text and cannot cancel context delivery, while the actual user request keeps normal tool parsing. The completed session is then reused under the normal exact-prefix rule. Before acquisition, a separate model-window guard uses pi-ai's `estimateContextTokens` plus 15% safety and the output reserve (up to 32,768 tokens); if that cannot fit `model.contextWindow`, the bridge returns `context_length_exceeded` before any model call so pi compacts instead of replaying beyond the backend limit. The last assistant's usage is used only when it belongs to the same provider/api; on a handoff (for example agy → neuralwatt), every pi message is re-estimated because the old provider's usage can describe a compacted session mirror rather than pi's full history. The 8 MiB `PI_AGY_MAX_REPLAY_KB` total guard remains independent of these per-block and token-window limits. A real agy check with a late-history synthetic fact returned the fact with zero truncation markers and 42,164 cacheRead tokens.
73
+
74
+ ### Resume across processes (0.4.0)
75
+
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.
71
77
 
72
78
  ## Process model
73
79
 
@@ -77,10 +83,12 @@ One shared `agy acp` per extension runtime, started on first real use, serving e
77
83
 
78
84
  `AccountManager` (`account-manager.ts`) owns one `AgyRuntime` per Antigravity account. The default runtime is the one described above (provider `agy`, api `agy-acp`, agy's keyring login) and is registered synchronously at load, exactly as before. Each enabled entry of `<home>/accounts.json` (plus `PI_AGY_ACCOUNTS`) gets its own runtime, pool and `agy acp` process, and its own pi provider `agy-<alias ?? id>` with its own api id `agy-acp-<alias ?? id>` (pi-ai's compat stream registry is keyed by api id, so ids must not be shared). Providers are (un)registered live through `pi.registerProvider` / `pi.unregisterProvider` when an account is added, renamed, enabled, disabled or removed.
79
85
 
80
- An extra account's process differs from the default in three ways: `--gemini-dir <home>/accounts/<id>/gemini` (and its own work dir), `--log-file <home>/accounts/<id>/acp.log` (moved to `acp.prev.log` when the next process starts, so a failed run can still be read), and `SSH_CONNECTION` in its environment. agy keeps one login per OS user in the keyring; when it sees an SSH session it uses a token file inside the gemini dir instead (measured on 1.5.12 and 1.5.14, `.plan/agy-multi-account/evidence`). `agy acp --login` with the same three settings signs that folder in (`accounts.ts` `startLogin`).
86
+ An extra account's process differs from the default in three ways: `--gemini-dir <home>/accounts/<id>/gemini` (and its own work dir), `--log-file <home>/accounts/<id>/acp-<pid>.log` (moved to `acp-<pid>.prev.log` when that pi process restarts agy, so a failed run can still be read and concurrent pi processes never rotate each other's logs), and `SSH_CONNECTION` in its environment. agy keeps one login per OS user in the keyring; when it sees an SSH session it uses a token file inside the gemini dir instead (measured on 1.5.12 and 1.5.14, `.plan/agy-multi-account/evidence`). `agy acp --login` with the same three settings signs that folder in (`accounts.ts` `startLogin`).
81
87
 
82
88
  The identity guard (`PoolOptions.verifyProcess`, `AgyRuntime` `#checkIdentity`) runs once per process right after its first `session/new`, because agy resolves the login lazily during that call. It reads agy's own log: the process is used only if agy reports file-based token storage and `authenticated successfully as <expected email>`. Otherwise the session is closed, the process stopped, and the request fails with `agy authentication required (not logged in) … account <id>` (non-retryable for pi-fallback-chains) or, when the storage trigger is missing, `pi-agy-bridge is unavailable: …` - so an extra provider never silently spends the default account's quota. Each account has its own `state.json` hint and trace tag; error messages of an extra account end with `(account <id>)`.
83
89
 
90
+ Sign-in method: every account runs the real agy CLI with its own Google login (above), the way pi-claude-code runs the Claude Code CLI. An account switches to agy's `gemini-api-key` ACP auth method exactly while a key is stored for it through the menu (`<root>/api-key`; `authModeFor` derives the mode from that file, nothing else is persisted). Such a process runs in its own `gemini-apikey/` dir (agy caches the chosen method per dir in `antigravity-cli/cache/acp-auth-state.json`, so one dir must never serve both), gets the key as its `GEMINI_API_KEY` only, calls `authenticate` right after `initialize`, and skips the SSH marker and the email guard (a key has no Google identity). `GEMINI_API_KEY` / `GOOGLE_API_KEY` from pi's environment are removed from every spawn (`withoutApiKeys`), so a key exported for other tools never changes which login agy uses. The provider is re-registered on a mode change: `isSubscription` and the display name follow the mode.
91
+
84
92
  Management: `/agy-bridge` subcommands (`index.ts` `handle`) and the overlay (`ui/menu.ts` on `ui/panel.ts`, modelled on pi-advisor's settings overlay) call the same `AccountManager` and `runAccountAction` functions; outside the TUI the menu falls back to `ui.select` / `ui.input` / `ui.confirm`.
85
93
 
86
94
  ## Isolation and the native-tool fence
@@ -100,6 +108,8 @@ pi waits for the provider's availability `check` while it starts. The first desi
100
108
 
101
109
  ## Usage accounting
102
110
 
111
+ 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
+
103
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`.
104
114
 
105
115
  ## Errors
@@ -111,11 +121,13 @@ Measured on agy 1.5.3 (`evidence/cache-and-usage-semantics.md`, pinned by `tests
111
121
  | no output for the silence limit | `agy stalled for Ns with no output` | retryable |
112
122
  | pi's idle `timeoutMs` elapsed without an ACP update | `agy request timed out after Ns` | retryable |
113
123
  | empty answer | `agy returned success but produced no model output:` | retryable |
114
- | quota (agy sends it as a normal `end_turn` reply with no usage; detected and failed) | `agy quota exhausted:` + agy's text (keeps `Resets in ...`) | retryable, provider cap |
124
+ | quota (agy sends it as a normal `end_turn` reply, with absent/zero usage or after billable thinking; detected and failed) | `agy quota exhausted:` + agy's text (keeps `Resets in ...`) | retryable, provider cap |
115
125
  | not logged in | `agy authentication required (not logged in)` | non-retryable |
116
126
  | context too large | `context_length_exceeded:` | non-retryable |
117
127
  | agy too old / wrong protocol | `pi-agy-bridge is unavailable:` | retryable |
118
128
 
129
+ A successful `end_turn` that spent output tokens or emitted reasoning but produced no visible answer gets one same-session retry for a normal answer or protocol tool call; usage from both attempts is aggregated. A second whitespace-only answer, or a truly empty zero-output reply, keeps the error above.
130
+
119
131
  Own messages avoid bare three-digit numbers because the classifier reads them as HTTP statuses.
120
132
 
121
133
  ## Upgrade path
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.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.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,6 +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
84
 
84
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.
85
86
 
@@ -101,6 +102,7 @@ Environment variables (all optional). Invalid values fall back to the default.
101
102
  | `PI_AGY_CONTROL_TIMEOUT_SEC` | `60` | timeout for handshake and session calls |
102
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 |
103
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_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 |
104
106
  | `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 |
105
107
  | `PI_AGY_ACCOUNTS` | none | extra accounts by id, comma-separated, in addition to `accounts.json` (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)) |
106
108
  | `PI_AGY_ACCOUNT_<ID>_EMAIL` | none | expected Google account of an extra account (normally recorded at sign-in) |
@@ -109,7 +111,7 @@ pi's own request `timeoutMs`, when set, is honoured as an idle deadline for the
109
111
 
110
112
  ### What is written to disk
111
113
 
112
- Only under `PI_AGY_HOME`: the staged carrier agent (`stage/`), agy's private config root (`gemini/`), an empty working directory (`work/`), a small health hint (`state.json`), the account list (`accounts.json`), one folder per extra account (`accounts/<id>/`, holding that account's agy data, agy's log and the login agy saved there) and the optional trace. Nothing is written to your project, to `~/.gemini` or to any global agy setting. Logins are only *used*: the bridge never reads, copies or forwards a token; it reads only agy's own log line that names the signed-in account.
114
+ Only under `PI_AGY_HOME`: the staged carrier agent (`stage/`), agy's private config root (`gemini/`), an empty working directory (`work/`), a small health hint (`state.json`), the account list (`accounts.json`), resume records (`gemini.resume.json` and one per account folder: pi session id → agy conversation id, chain hash and step count; no content), an optional API key per account (`api-key`) with its own agy folder (`gemini-apikey/`), one folder per extra account (`accounts/<id>/`, holding that account's agy data, agy's log and the login agy saved there) and the optional trace. Nothing is written to your project, to `~/.gemini` or to any global agy setting. Logins are only *used*: the bridge never reads, copies or forwards a token; it reads only agy's own log line that names the signed-in account.
113
115
 
114
116
  ## Working with your other extensions
115
117
 
@@ -140,11 +142,12 @@ Example chain, mirrored from an `antigravity/*` chain:
140
142
  | `agy authentication required (not logged in)` | login expired | run `agy` and sign in |
141
143
  | `agy authentication required (not logged in) for account <id>` | that extra account has no saved login, or agy is signed in as a different Google account than the one recorded | `/agy-bridge login <id>` (the new email becomes the expected one) |
142
144
  | `pi-agy-bridge is unavailable: agy did not switch to per-account token storage for account <id>` | an agy update stopped honouring the trigger extra accounts use; they fail closed rather than use your default login | see `UPGRADING.md` §1 (the compat probe reports this as breaking) |
143
- | `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 |
145
+ | `agy quota exhausted: ... Resets in ...` | the plan's quota for that model is used up (agy delivers this as a normal reply, sometimes after billable thinking; the bridge turns a leading warning into an error whether usage is absent, zero or nonzero so fallback chains rotate immediately) | use another model/account; the reset time is in the message |
144
146
  | `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 |
145
- | `agy stalled for 120s with no output` | the model produced nothing for the silence limit (with agy 1.5.14 and `PI_AGY_SYSTEM_PROMPT=append`: the backend's silent refusal of the appended prompt; use `auto`) | retry; raise `PI_AGY_SILENCE_SEC` for very long silent thinking. To see why, set `PI_AGY_TRACE=1` (the trace names agy's last update); for an extra account agy's own log of the failed run is `<home>/accounts/<id>/acp.prev.log` after the next start |
147
+ | `agy stalled for 120s with no output` | the model produced nothing for the silence limit (with agy 1.5.14 and `PI_AGY_SYSTEM_PROMPT=append`: the backend's silent refusal of the appended prompt; use `auto`) | retry; raise `PI_AGY_SILENCE_SEC` for very long silent thinking. To see why, set `PI_AGY_TRACE=1` (the trace names agy's last update); for an extra account agy's own log of the failed run is `<home>/accounts/<id>/acp-<pid>.prev.log` after that pi process's next start (per-process logs avoid concurrent-start rotation locks) |
146
148
  | `agy request timed out after 300s` | agy sent no ACP update within pi's request timeout (`timeoutMs`; 300 s here), which defaults to pi's `httpIdleTimeoutMs`. Active turns refresh this deadline; with the default 120 s silence guard, that guard normally fires first | retry; pi's `/settings` HTTP timeout controls this idle limit (or set `retry.provider.timeoutMs`). The same `PI_AGY_TRACE=1` line shows what agy last sent |
147
149
  | the model says `pi://conversation.md` was truncated before it could see the request | agy truncates oversized converted prompt content; this build delivers history, instructions and latest input as sequential bounded turns within one agy session instead | reload the extension and retry the current session (a fresh session alone would replay the same content). If pi's token estimate plus safety/output reserve exceeds the model window, the bridge returns `context_length_exceeded` before any model call so pi compacts automatically; total replay above `PI_AGY_MAX_REPLAY_KB` still needs a higher safe cap |
150
+ | `agy returned success but produced no model output: stop reason end_turn` | agy ended without visible answer text or a tool call | retry; when agy emitted reasoning or spent output tokens, this build automatically asks once in the same session for the missing visible answer before reporting this error |
148
151
  | `agy exited with status N` | the agy process died | retry (a new process starts); `/agy-bridge doctor` shows agy's last stderr |
149
152
  | `agy is unavailable: pi-agy-bridge is shut down` during or just after reload/session replacement | 0.1.2 or older permanently latched the outgoing pool while a background caller (often pi-advisor) was retrying | upgrade to 0.1.3 or newer. An old advisor error can remain visible until a later review succeeds; that sticky status is normal |
150
153
  | `pi-agy-bridge is unavailable: agy ... below the minimum` | agy too old | `agy update` |
@@ -0,0 +1,284 @@
1
+ {
2
+ "schema": 1,
3
+ "agyVersion": "1.5.18",
4
+ "collectedAt": "2026-11-26T15:16:33.005Z",
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
+ "--resume",
28
+ "--sandbox",
29
+ "--settings",
30
+ "-c",
31
+ "-i",
32
+ "-p",
33
+ "-r"
34
+ ],
35
+ "acpHelpFlags": [
36
+ "--add-dir",
37
+ "--agent",
38
+ "--app-data-dir",
39
+ "--app_data_dir",
40
+ "--cli_dir_name",
41
+ "--cli_log_file",
42
+ "--cloud_code_endpoint",
43
+ "--dangerously-skip-permissions",
44
+ "--disable-telemetry",
45
+ "--disable_telemetry",
46
+ "--gemini-dir",
47
+ "--gemini_dir",
48
+ "--help",
49
+ "--ide-mcp-port",
50
+ "--ide_mcp_port",
51
+ "--include-default-customizations",
52
+ "--is_google3_workspace",
53
+ "--is_google_internal",
54
+ "--log-file",
55
+ "--login",
56
+ "--override_user_agent_name",
57
+ "--process-per-session",
58
+ "--sandbox",
59
+ "--stdio",
60
+ "--use_stubby_auth",
61
+ "--worker",
62
+ "-h"
63
+ ],
64
+ "models": [
65
+ {
66
+ "id": "claude-opus-5-5-high",
67
+ "label": "Claude Opus 5.5 (High)"
68
+ },
69
+ {
70
+ "id": "claude-opus-5-5-low",
71
+ "label": "Claude Opus 5.5 (Low)"
72
+ },
73
+ {
74
+ "id": "claude-opus-5-5-medium",
75
+ "label": "Claude Opus 5.5 (Medium)"
76
+ },
77
+ {
78
+ "id": "claude-sonnet-5-5-high",
79
+ "label": "Claude Sonnet 5.5 (High)"
80
+ },
81
+ {
82
+ "id": "claude-sonnet-5-5-low",
83
+ "label": "Claude Sonnet 5.5 (Low)"
84
+ },
85
+ {
86
+ "id": "claude-sonnet-5-5-medium",
87
+ "label": "Claude Sonnet 5.5 (Medium)"
88
+ },
89
+ {
90
+ "id": "gemini-3.8-flash-high",
91
+ "label": "Gemini 3.8 Flash (High)"
92
+ },
93
+ {
94
+ "id": "gemini-3.8-flash-low",
95
+ "label": "Gemini 3.8 Flash (Low)"
96
+ },
97
+ {
98
+ "id": "gemini-3.8-flash-medium",
99
+ "label": "Gemini 3.8 Flash (Medium)"
100
+ },
101
+ {
102
+ "id": "gemini-4-argon-high",
103
+ "label": "Gemini 4 Argon (High)"
104
+ },
105
+ {
106
+ "id": "gemini-4-argon-low",
107
+ "label": "Gemini 4 Argon (Low)"
108
+ },
109
+ {
110
+ "id": "gemini-4-argon-medium",
111
+ "label": "Gemini 4 Argon (Medium)"
112
+ },
113
+ {
114
+ "id": "gemini-4-carbon-high",
115
+ "label": "Gemini 4 Carbon (High)"
116
+ },
117
+ {
118
+ "id": "gemini-4-carbon-low",
119
+ "label": "Gemini 4 Carbon (Low)"
120
+ },
121
+ {
122
+ "id": "gemini-4-carbon-medium",
123
+ "label": "Gemini 4 Carbon (Medium)"
124
+ },
125
+ {
126
+ "id": "gemini-4-hydrogen-high",
127
+ "label": "Gemini 4 Hydrogen (High)"
128
+ },
129
+ {
130
+ "id": "gemini-4-hydrogen-low",
131
+ "label": "Gemini 4 Hydrogen (Low)"
132
+ },
133
+ {
134
+ "id": "gemini-4-hydrogen-medium",
135
+ "label": "Gemini 4 Hydrogen (Medium)"
136
+ },
137
+ {
138
+ "id": "gemini-4-hydrogen-xhigh",
139
+ "label": "Gemini 4 Hydrogen (XHigh)"
140
+ },
141
+ {
142
+ "id": "gemini-4-neon-high",
143
+ "label": "Gemini 4 Neon (High)"
144
+ },
145
+ {
146
+ "id": "gemini-4-neon-low",
147
+ "label": "Gemini 4 Neon (Low)"
148
+ },
149
+ {
150
+ "id": "gemini-4-neon-medium",
151
+ "label": "Gemini 4 Neon (Medium)"
152
+ },
153
+ {
154
+ "id": "gemini-4-neon-xhigh",
155
+ "label": "Gemini 4 Neon (XHigh)"
156
+ },
157
+ {
158
+ "id": "gemini-pro-orchestrator",
159
+ "label": "Orchestrator (Carbon)"
160
+ },
161
+ {
162
+ "id": "gemini-pro-orchestrator-argon",
163
+ "label": "Orchestrator (Argon)"
164
+ },
165
+ {
166
+ "id": "gemini-pro-orchestrator-neon",
167
+ "label": "Orchestrator (Neon)"
168
+ },
169
+ {
170
+ "id": "gpt-oss-120b-medium",
171
+ "label": "GPT-OSS 120B (Medium)"
172
+ }
173
+ ],
174
+ "initialize": {
175
+ "protocolVersion": 1,
176
+ "agentName": "Antigravity ACP Server",
177
+ "agentVersion": "1.5.18",
178
+ "capabilities": {
179
+ "_meta.antigravity.systemPrompt.append": true,
180
+ "auth.logout": true,
181
+ "loadSession": true,
182
+ "load_session": true,
183
+ "promptCapabilities.audio": false,
184
+ "promptCapabilities.embeddedContext": true,
185
+ "promptCapabilities.image": true,
186
+ "sessionCapabilities.additionalDirectories": true,
187
+ "sessionCapabilities.close": true,
188
+ "sessionCapabilities.list": true,
189
+ "sessionCapabilities.load": true,
190
+ "sessionCapabilities.resume": true,
191
+ "session_capabilities.additionalDirectories": true,
192
+ "session_capabilities.close": true,
193
+ "session_capabilities.list": true,
194
+ "session_capabilities.load": true,
195
+ "session_capabilities.resume": true
196
+ },
197
+ "authMethodIds": [
198
+ "agent-platform",
199
+ "gemini-api-key",
200
+ "oauth-business",
201
+ "oauth-personal"
202
+ ]
203
+ },
204
+ "session": {
205
+ "configOptions": [
206
+ {
207
+ "id": "mode",
208
+ "type": "select",
209
+ "values": [
210
+ "accept-edits",
211
+ "auto",
212
+ "default",
213
+ "plan"
214
+ ]
215
+ },
216
+ {
217
+ "id": "model",
218
+ "type": "select",
219
+ "values": [
220
+ "claude-opus-5-5",
221
+ "claude-sonnet-5-5",
222
+ "gemini-3.8-flash",
223
+ "gemini-4-argon",
224
+ "gemini-4-carbon",
225
+ "gemini-4-hydrogen",
226
+ "gemini-4-neon",
227
+ "gemini-pro-orchestrator",
228
+ "gemini-pro-orchestrator-argon",
229
+ "gemini-pro-orchestrator-neon",
230
+ "gpt-oss-120b-medium"
231
+ ]
232
+ },
233
+ {
234
+ "id": "thought_level",
235
+ "type": "select",
236
+ "values": [
237
+ "high",
238
+ "low",
239
+ "medium",
240
+ "xhigh"
241
+ ]
242
+ }
243
+ ],
244
+ "modeIds": [
245
+ "accept-edits",
246
+ "auto",
247
+ "default",
248
+ "plan"
249
+ ],
250
+ "modelIds": [
251
+ "claude-opus-5-5-high",
252
+ "claude-opus-5-5-low",
253
+ "claude-opus-5-5-medium",
254
+ "claude-sonnet-5-5-high",
255
+ "claude-sonnet-5-5-low",
256
+ "claude-sonnet-5-5-medium",
257
+ "gemini-3.8-flash-high",
258
+ "gemini-3.8-flash-low",
259
+ "gemini-3.8-flash-medium",
260
+ "gemini-4-argon-high",
261
+ "gemini-4-argon-low",
262
+ "gemini-4-argon-medium",
263
+ "gemini-4-carbon-high",
264
+ "gemini-4-carbon-low",
265
+ "gemini-4-carbon-medium",
266
+ "gemini-4-hydrogen-high",
267
+ "gemini-4-hydrogen-low",
268
+ "gemini-4-hydrogen-medium",
269
+ "gemini-4-hydrogen-xhigh",
270
+ "gemini-4-neon-high",
271
+ "gemini-4-neon-low",
272
+ "gemini-4-neon-medium",
273
+ "gemini-4-neon-xhigh",
274
+ "gemini-pro-orchestrator",
275
+ "gemini-pro-orchestrator-argon",
276
+ "gemini-pro-orchestrator-neon",
277
+ "gpt-oss-120b-medium"
278
+ ],
279
+ "metaKeys": [
280
+ "antigravity"
281
+ ]
282
+ },
283
+ "fileTokenStorageTrigger": "SSH_CONNECTION"
284
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "agy": {
4
- "tested": ["1.5.3", "1.5.8", "1.5.9", "1.5.12", "1.5.14", "1.5.16", "1.5.17"],
4
+ "tested": ["1.5.3", "1.5.8", "1.5.9", "1.5.12", "1.5.14", "1.5.16", "1.5.17", "1.5.18"],
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.3.2",
43
+ version: "0.4.1",
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.3.2",
3
+ "version": "0.4.1",
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",
@@ -7,8 +7,12 @@
7
7
  import { resolveAgyCommand } from "./acp/command.ts";
8
8
  import {
9
9
  accountPaths,
10
+ apiKeyPathsFor,
11
+ authModeFor,
10
12
  DEFAULT_ACCOUNT,
11
13
  hasSavedLogin,
14
+ maskApiKey,
15
+ writeApiKey,
12
16
  labelFor,
13
17
  maskEmail,
14
18
  mergeEnvAccounts,
@@ -19,6 +23,7 @@ import {
19
23
  startLogin,
20
24
  writeRegistry,
21
25
  type AccountRecord,
26
+ type AuthMode,
22
27
  type LoginHandle,
23
28
  type LoginProgress,
24
29
  type LoginResult,
@@ -64,6 +69,10 @@ export interface AccountView {
64
69
  /** Result of the identity guard at the last start (extra accounts). */
65
70
  identity?: { ok: boolean; email?: string; message?: string; at: number };
66
71
  agyVersion?: string;
72
+ /** How the account signs in. */
73
+ auth: AuthMode;
74
+ /** API-key accounts: a masked preview of the stored key. */
75
+ apiKey?: { masked: string };
67
76
  }
68
77
 
69
78
  export interface ManagerOptions {
@@ -132,8 +141,20 @@ export class AccountManager {
132
141
  }
133
142
 
134
143
  async #reload(): Promise<void> {
144
+ // The sign-in method follows the stored key: a key set in the menu means API key, none means the account's own
145
+ // Google login through agy (the environment's GEMINI_API_KEY is never used).
146
+ const defaultAuth = await authModeFor(this.home, DEFAULT_ACCOUNT);
147
+ if (defaultAuth !== this.default.authMode) {
148
+ this.default.setDefaultAuth(defaultAuth);
149
+ // pi replaces a provider registered again under the same id: the name and subscription flag follow the method.
150
+ if (this.#registered.has(DEFAULT_ACCOUNT)) this.#host.registerProvider(createAgyProvider(this.default));
151
+ }
135
152
  const registry = await readRegistry(this.home);
136
153
  const { accounts, warnings } = mergeEnvAccounts(registry, this.#options.runtime?.env ?? process.env);
154
+ for (const account of accounts) {
155
+ if ((await authModeFor(this.home, account.id)) === "api-key") account.auth = "api-key";
156
+ else delete account.auth;
157
+ }
137
158
  this.#accounts = accounts;
138
159
  this.#warnings = warnings;
139
160
  for (const warning of warnings) this.default.trace(`accounts: ${warning}`);
@@ -197,13 +218,18 @@ export class AccountManager {
197
218
  const discovery = runtime?.pool.cachedDiscovery;
198
219
  const models = discovery ? describeModels(discovery).map((descriptor) => descriptor.id) : undefined;
199
220
  const identity = runtime?.identity;
221
+ const auth: AuthMode = isDefault ? this.default.authMode : (account.auth ?? "google");
222
+ const key = auth === "api-key" ? await runtime?.resolveApiKey() : undefined;
200
223
  return {
224
+ auth,
225
+ ...(key ? { apiKey: { masked: maskApiKey(key) } } : {}),
201
226
  account,
202
227
  provider: providerIdFor(account),
203
228
  label: labelFor(account),
204
229
  isDefault,
205
230
  registered: this.#registered.has(account.id),
206
- savedLogin: isDefault ? true : await hasSavedLogin(this.home, account.id),
231
+ // 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)),
207
233
  running: status?.alive === true,
208
234
  ...(status?.pid !== undefined && status.alive ? { pid: status.pid } : {}),
209
235
  sessions: { idle: status?.idle ?? 0, busy: status?.busy ?? 0 },
@@ -284,6 +310,22 @@ export class AccountManager {
284
310
  if (deleteLogin) await removeAccountFolder(this.home, id);
285
311
  }
286
312
 
313
+ /** Store an account's Gemini API key (the account then signs in with it), or with an empty value remove it (the
314
+ * account goes back to its own Google login through agy, whose folder was never touched). Never logged. */
315
+ async setApiKey(id: string, value: string | undefined): Promise<void> {
316
+ await this.load();
317
+ if (id !== DEFAULT_ACCOUNT) this.#find(id);
318
+ const runtime = this.runtimeFor(id);
319
+ const before = runtime?.authMode;
320
+ await writeApiKey(apiKeyPathsFor(this.home, id).apiKeyFile, value?.trim() || undefined);
321
+ await this.load(); // re-derives the method; a changed method rebuilds the pool and re-registers the provider
322
+ const after = this.runtimeFor(id);
323
+ // A changed method retired the old process; let it exit before the next start reuses the account's log file.
324
+ if (after && before !== after.authMode) await after.settleRetired();
325
+ await after?.clearUnusable();
326
+ if (after && before === after.authMode) await after.apiKeyChanged(); // same method, new key: restart its process
327
+ }
328
+
287
329
  /** Set the expected email by hand (normally recorded by sign-in). Empty clears it. */
288
330
  async setEmail(id: string, email: string | undefined): Promise<void> {
289
331
  await this.load();
@@ -310,6 +352,7 @@ export class AccountManager {
310
352
  return { ok: false, message: "the default account uses agy's own login: run `agy` in a terminal and sign in there" };
311
353
  }
312
354
  const account = this.#find(id);
355
+ if (account.auth === "api-key") return { ok: false, message: `account "${id}" signs in with an API key; switch its sign-in method to Google first` };
313
356
  if (this.#logins.has(id)) return { ok: false, message: `a sign-in for "${id}" is already running` };
314
357
  const command = await resolveAgyCommand(this.default.config.command, this.#options.runtime?.env ?? process.env);
315
358
  // The process of this account must not run with the old login while the folder changes.
@@ -369,7 +412,8 @@ export class AccountManager {
369
412
  const discovery = await runtime.pool.discover(true);
370
413
  const count = describeModels(discovery).length;
371
414
  const email = runtime.identity?.identity.email;
372
- return { ok: true, message: `${labelFor(runtime.account ?? { id: DEFAULT_ACCOUNT })}: ok${email ? ` as ${maskEmail(email)}` : ""}, ${count} models` };
415
+ const how = runtime.authMode === "api-key" ? " with the Gemini API key" : email ? ` as ${maskEmail(email)}` : "";
416
+ return { ok: true, message: `${labelFor(runtime.account ?? { id: DEFAULT_ACCOUNT })}: ok${how}, ${count} models` };
373
417
  } catch (error) {
374
418
  return { ok: false, message: describeError(error) };
375
419
  }