@timmyjl12/pi-agy-bridge 0.3.3 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ARCHITECTURE.md CHANGED
@@ -71,6 +71,14 @@ Internal replay acknowledgements and the single whitespace-recovery prompt are t
71
71
 
72
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
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.
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
+
74
82
  ## Process model
75
83
 
76
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.
@@ -83,6 +91,8 @@ An extra account's process differs from the default in three ways: `--gemini-dir
83
91
 
84
92
  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>)`.
85
93
 
94
+ 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.
95
+
86
96
  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`.
87
97
 
88
98
  ## Isolation and the native-tool fence
@@ -102,6 +112,8 @@ pi waits for the provider's availability `check` while it starts. The first desi
102
112
 
103
113
  ## Usage accounting
104
114
 
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.
116
+
105
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`. pi's `Usage` has the same shape, so the mapping is a copy; the prompt size pi-context sees is `input + cacheRead + cacheWrite`.
106
118
 
107
119
  ## Errors
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.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.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,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. 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.
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,8 @@ 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_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` |
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 |
104
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 |
105
108
  | `PI_AGY_ACCOUNTS` | none | extra accounts by id, comma-separated, in addition to `accounts.json` (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)) |
106
109
  | `PI_AGY_ACCOUNT_<ID>_EMAIL` | none | expected Google account of an extra account (normally recorded at sign-in) |
@@ -109,7 +112,7 @@ pi's own request `timeoutMs`, when set, is honoured as an idle deadline for the
109
112
 
110
113
  ### What is written to disk
111
114
 
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.
115
+ 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
116
 
114
117
  ## Working with your other extensions
115
118
 
@@ -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.3",
43
+ version: "0.4.2",
44
44
  } as const;
45
45
 
46
46
  /** One failed probe step. `step` names the command or exchange. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timmyjl12/pi-agy-bridge",
3
- "version": "0.3.3",
3
+ "version": "0.4.2",
4
4
  "description": "pi provider for Google Antigravity (agy) models over the official ACP server, modelled on pi-claude-code: pi keeps the loop, history and tool execution",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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,12 @@ 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 };
76
+ /** The account's agy Google login exists (default: agy's own; extra: its token file), whatever mode is active. */
77
+ hasGoogleLogin: boolean;
67
78
  }
68
79
 
69
80
  export interface ManagerOptions {
@@ -132,8 +143,20 @@ export class AccountManager {
132
143
  }
133
144
 
134
145
  async #reload(): Promise<void> {
146
+ // The sign-in method follows the stored key: a key set in the menu means API key, none means the account's own
147
+ // Google login through agy (the environment's GEMINI_API_KEY is never used).
148
+ const defaultAuth = await authModeFor(this.home, DEFAULT_ACCOUNT);
149
+ if (defaultAuth !== this.default.authMode) {
150
+ this.default.setDefaultAuth(defaultAuth);
151
+ // pi replaces a provider registered again under the same id: the name and subscription flag follow the method.
152
+ if (this.#registered.has(DEFAULT_ACCOUNT)) this.#host.registerProvider(createAgyProvider(this.default));
153
+ }
135
154
  const registry = await readRegistry(this.home);
136
155
  const { accounts, warnings } = mergeEnvAccounts(registry, this.#options.runtime?.env ?? process.env);
156
+ for (const account of accounts) {
157
+ if ((await authModeFor(this.home, account.id)) === "api-key") account.auth = "api-key";
158
+ else delete account.auth;
159
+ }
137
160
  this.#accounts = accounts;
138
161
  this.#warnings = warnings;
139
162
  for (const warning of warnings) this.default.trace(`accounts: ${warning}`);
@@ -197,13 +220,20 @@ export class AccountManager {
197
220
  const discovery = runtime?.pool.cachedDiscovery;
198
221
  const models = discovery ? describeModels(discovery).map((descriptor) => descriptor.id) : undefined;
199
222
  const identity = runtime?.identity;
223
+ const auth: AuthMode = isDefault ? this.default.authMode : (account.auth ?? "google");
224
+ const key = auth === "api-key" ? await runtime?.resolveApiKey() : undefined;
225
+ const hasGoogleLogin = isDefault || (await hasSavedLogin(this.home, account.id));
200
226
  return {
227
+ auth,
228
+ hasGoogleLogin,
229
+ ...(key ? { apiKey: { masked: maskApiKey(key) } } : {}),
201
230
  account,
202
231
  provider: providerIdFor(account),
203
232
  label: labelFor(account),
204
233
  isDefault,
205
234
  registered: this.#registered.has(account.id),
206
- savedLogin: isDefault ? true : await hasSavedLogin(this.home, account.id),
235
+ // Google: the default account uses agy's own login; an extra one needs its token file. API key: a key exists.
236
+ savedLogin: auth === "api-key" ? key !== undefined : hasGoogleLogin,
207
237
  running: status?.alive === true,
208
238
  ...(status?.pid !== undefined && status.alive ? { pid: status.pid } : {}),
209
239
  sessions: { idle: status?.idle ?? 0, busy: status?.busy ?? 0 },
@@ -284,6 +314,22 @@ export class AccountManager {
284
314
  if (deleteLogin) await removeAccountFolder(this.home, id);
285
315
  }
286
316
 
317
+ /** Store an account's Gemini API key (the account then signs in with it), or with an empty value remove it (the
318
+ * account goes back to its own Google login through agy, whose folder was never touched). Never logged. */
319
+ async setApiKey(id: string, value: string | undefined): Promise<void> {
320
+ await this.load();
321
+ if (id !== DEFAULT_ACCOUNT) this.#find(id);
322
+ const runtime = this.runtimeFor(id);
323
+ const before = runtime?.authMode;
324
+ await writeApiKey(apiKeyPathsFor(this.home, id).apiKeyFile, value?.trim() || undefined);
325
+ await this.load(); // re-derives the method; a changed method rebuilds the pool and re-registers the provider
326
+ const after = this.runtimeFor(id);
327
+ // A changed method retired the old process; let it exit before the next start reuses the account's log file.
328
+ if (after && before !== after.authMode) await after.settleRetired();
329
+ await after?.clearUnusable();
330
+ if (after && before === after.authMode) await after.apiKeyChanged(); // same method, new key: restart its process
331
+ }
332
+
287
333
  /** Set the expected email by hand (normally recorded by sign-in). Empty clears it. */
288
334
  async setEmail(id: string, email: string | undefined): Promise<void> {
289
335
  await this.load();
@@ -310,6 +356,7 @@ export class AccountManager {
310
356
  return { ok: false, message: "the default account uses agy's own login: run `agy` in a terminal and sign in there" };
311
357
  }
312
358
  const account = this.#find(id);
359
+ 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
360
  if (this.#logins.has(id)) return { ok: false, message: `a sign-in for "${id}" is already running` };
314
361
  const command = await resolveAgyCommand(this.default.config.command, this.#options.runtime?.env ?? process.env);
315
362
  // The process of this account must not run with the old login while the folder changes.
@@ -369,7 +416,8 @@ export class AccountManager {
369
416
  const discovery = await runtime.pool.discover(true);
370
417
  const count = describeModels(discovery).length;
371
418
  const email = runtime.identity?.identity.email;
372
- return { ok: true, message: `${labelFor(runtime.account ?? { id: DEFAULT_ACCOUNT })}: ok${email ? ` as ${maskEmail(email)}` : ""}, ${count} models` };
419
+ const how = runtime.authMode === "api-key" ? " with the Gemini API key" : email ? ` as ${maskEmail(email)}` : "";
420
+ return { ok: true, message: `${labelFor(runtime.account ?? { id: DEFAULT_ACCOUNT })}: ok${how}, ${count} models` };
373
421
  } catch (error) {
374
422
  return { ok: false, message: describeError(error) };
375
423
  }
package/src/accounts.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  // which account a process serves, and refuses to use an extra-account process that is not the expected account.
11
11
 
12
12
  import { spawn, type ChildProcess } from "node:child_process";
13
- import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
13
+ import { chmod, mkdir, readFile, rename, rm, stat } from "node:fs/promises";
14
14
  import path from "node:path";
15
15
  import { writeFileAtomic } from "./atomic-write.ts";
16
16
 
@@ -22,9 +22,29 @@ export const DEFAULT_PROVIDER = "agy";
22
22
  /** The value is only a marker: agy checks that the variable exists. */
23
23
  export const FILE_STORAGE_ENV = { SSH_CONNECTION: "pi-agy-bridge 0 pi-agy-bridge 0" } as const;
24
24
 
25
+ /** Variables agy would read as API-key credentials. */
26
+ const API_KEY_ENV = new Set(["GEMINI_API_KEY", "GOOGLE_API_KEY"]);
27
+
28
+ /** A copy of `env` without any API-key variable, in any letter case (Windows environment names are case-insensitive,
29
+ * so `gemini_api_key` would reach agy as GEMINI_API_KEY). Applied to every agy spawn: a Google-login process must
30
+ * serve the account's own login, and an API-key process gets only the key stored for its account. */
31
+ export function withoutApiKeys(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
32
+ const copy: NodeJS.ProcessEnv = {};
33
+ for (const [name, value] of Object.entries(env)) if (!API_KEY_ENV.has(name.toUpperCase())) copy[name] = value;
34
+ return copy;
35
+ }
36
+
37
+ /** How an account signs in. `google` (the default): the real agy CLI with the account's own signed-in Google login
38
+ * (keyring for the default account, its own token file for extras), exactly as before 0.4.0. `api-key`: agy's
39
+ * `gemini-api-key` ACP auth method. An account is in `api-key` mode exactly when a key is stored for it through the
40
+ * menu; the environment's GEMINI_API_KEY is never used. Derived from the key file, never persisted separately. */
41
+ export type AuthMode = "google" | "api-key";
42
+
25
43
  export interface AccountRecord {
26
44
  id: string;
27
45
  alias?: string;
46
+ /** Derived at load from the account's stored key (absent = `google`); not written to accounts.json. */
47
+ auth?: AuthMode;
28
48
  /** The Google account this profile must serve; recorded at sign-in (or set by PI_AGY_ACCOUNT_<ID>_EMAIL). */
29
49
  email?: string;
30
50
  enabled: boolean;
@@ -75,6 +95,11 @@ export function maskEmail(email: string | undefined): string {
75
95
  export interface AccountPaths {
76
96
  root: string;
77
97
  geminiDir: string;
98
+ /** agy data dir for API-key mode. Separate from `geminiDir` because agy caches the chosen auth method in its dir
99
+ * (`antigravity-cli/cache/acp-auth-state.json`), so one dir must never serve both modes. */
100
+ apiKeyGeminiDir: string;
101
+ /** The stored Gemini API key (plain text, user-only permissions). Never logged. */
102
+ apiKeyFile: string;
78
103
  logFile: string;
79
104
  /** The previous process's agy log, kept so a failure (a stall, a timeout) can be read after the restart. */
80
105
  prevLogFile: string;
@@ -88,6 +113,8 @@ export function accountPaths(home: string, id: string): AccountPaths {
88
113
  return {
89
114
  root,
90
115
  geminiDir,
116
+ apiKeyGeminiDir: path.join(root, "gemini-apikey"),
117
+ apiKeyFile: path.join(root, "api-key"),
91
118
  logFile: path.join(root, "acp.log"),
92
119
  prevLogFile: path.join(root, "acp.prev.log"),
93
120
  loginLog: path.join(root, "login.log"),
@@ -128,6 +155,53 @@ export async function rotateAccountLog(
128
155
  await io.rm(paths.logFile, { force: true, maxRetries: 5, retryDelay: 100 });
129
156
  }
130
157
 
158
+ /** Where the default account keeps its API key and API-key agy dir: directly under the bridge home. */
159
+ export function defaultAccountPaths(home: string): Pick<AccountPaths, "root" | "apiKeyGeminiDir" | "apiKeyFile"> {
160
+ return { root: home, apiKeyGeminiDir: path.join(home, "gemini-apikey"), apiKeyFile: path.join(home, "api-key") };
161
+ }
162
+
163
+ export function apiKeyPathsFor(home: string, id: string): Pick<AccountPaths, "root" | "apiKeyGeminiDir" | "apiKeyFile"> {
164
+ return id === DEFAULT_ACCOUNT ? defaultAccountPaths(home) : accountPaths(home, id);
165
+ }
166
+
167
+ /** A Gemini API key: printable, no whitespace, a sane length. Rejects pasted prose or a whole env line. */
168
+ export function validateApiKey(value: string): string | undefined {
169
+ if (!value) return "the API key is empty";
170
+ if (/\s/.test(value)) return "the API key must not contain spaces or line breaks";
171
+ if (value.length < 20 || value.length > 200) return "that does not look like a Gemini API key (expected 20-200 characters)";
172
+ if (!/^[\x21-\x7e]+$/.test(value)) return "the API key contains characters an API key never has";
173
+ return undefined;
174
+ }
175
+
176
+ /** The stored key, or undefined. A read problem counts as "no key" (the caller falls back to GEMINI_API_KEY). */
177
+ export async function readApiKey(file: string): Promise<string | undefined> {
178
+ try {
179
+ const value = (await readFile(file, "utf8")).trim();
180
+ return value && !validateApiKey(value) ? value : undefined;
181
+ } catch {
182
+ return undefined;
183
+ }
184
+ }
185
+
186
+ /** Store (or with undefined, delete) an account's API key. Written atomically and readable by the user only. */
187
+ export async function writeApiKey(file: string, value: string | undefined): Promise<void> {
188
+ if (value === undefined) {
189
+ await rm(file, { force: true });
190
+ return;
191
+ }
192
+ const problem = validateApiKey(value);
193
+ if (problem) throw new Error(problem);
194
+ await mkdir(path.dirname(file), { recursive: true });
195
+ await writeFileAtomic(file, `${value}\n`);
196
+ // POSIX: owner read/write only. Windows ignores the mode; the file lives in the user's own profile.
197
+ await chmod(file, 0o600).catch(() => undefined);
198
+ }
199
+
200
+ /** Mask a key for display: the first four and last four characters only. */
201
+ export function maskApiKey(value: string): string {
202
+ return value.length <= 8 ? "…" : `${value.slice(0, 4)}…${value.slice(-4)}`;
203
+ }
204
+
131
205
  /** Is a saved login present for this extra account (existence only; the file is never read)? */
132
206
  export async function hasSavedLogin(home: string, id: string): Promise<boolean> {
133
207
  try {
@@ -170,6 +244,11 @@ export async function readRegistry(home: string): Promise<AccountRecord[]> {
170
244
  }
171
245
  }
172
246
 
247
+ /** An account's sign-in method: `api-key` exactly when a valid key is stored for it. */
248
+ export async function authModeFor(home: string, id: string): Promise<AuthMode> {
249
+ return (await readApiKey(apiKeyPathsFor(home, id).apiKeyFile)) ? "api-key" : "google";
250
+ }
251
+
173
252
  export async function writeRegistry(home: string, accounts: readonly AccountRecord[]): Promise<void> {
174
253
  await mkdir(home, { recursive: true });
175
254
  const file: RegistryFile = {
@@ -337,7 +416,7 @@ export function startLogin(options: {
337
416
  const args = [...(options.prefixArgs ?? []), "acp", "--login", "--gemini-dir", paths.geminiDir, "--log-file", paths.loginLog];
338
417
  child = spawn(options.command, args, {
339
418
  cwd: paths.root,
340
- env: { ...(options.env ?? process.env), ...FILE_STORAGE_ENV },
419
+ env: { ...withoutApiKeys(options.env ?? process.env), ...FILE_STORAGE_ENV },
341
420
  stdio: ["pipe", "pipe", "pipe"],
342
421
  windowsHide: true,
343
422
  });