@timmyjl12/pi-agy-bridge 0.3.3 → 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.
@@ -194,11 +194,27 @@ export class AcpProcess {
194
194
  const result = await this.#rpc.request("initialize", {
195
195
  protocolVersion: 1,
196
196
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
197
- clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.3.3" },
197
+ clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.4.1" },
198
198
  });
199
199
  return (result ?? {}) as AcpInitializeResult;
200
200
  }
201
201
 
202
+ /** Select an advertised auth method (`gemini-api-key` reads GEMINI_API_KEY from agy's environment; verified on agy
203
+ * 1.5.17). agy caches the method in its gemini dir, so a dir must only ever serve one method. */
204
+ async authenticate(methodId: string): Promise<void> {
205
+ await this.#rpc.request("authenticate", { methodId });
206
+ }
207
+
208
+ /** Reopen a conversation agy already holds (its own store) without replaying it. Verified on agy 1.5.17: works in a
209
+ * new process, after session/close, and keeps the session's appended system prompt; an unknown id fails with
210
+ * "Failed to read session". The result has the same shape as session/new. */
211
+ async resumeSession(params: { sessionId: string; cwd: string }): Promise<AcpNewSessionResult> {
212
+ const result = (await this.#rpc.request("session/resume", { sessionId: params.sessionId, cwd: params.cwd, mcpServers: [] })) as
213
+ | AcpNewSessionResult
214
+ | undefined;
215
+ return { ...(result ?? {}), sessionId: params.sessionId };
216
+ }
217
+
202
218
  /** Create a session. `systemPromptAppend` rides `_meta.antigravity.systemPrompt.append` (verified on agy 1.5.3 and 1.5.8). */
203
219
  async newSession(params: { cwd: string; systemPromptAppend?: string }): Promise<AcpNewSessionResult> {
204
220
  const body: Record<string, unknown> = { cwd: params.cwd, mcpServers: [] };
package/src/config.ts CHANGED
@@ -39,6 +39,9 @@ export interface AgyConfig {
39
39
  /** `auto` only: a fresh session with the appended system prompt that shows no model output (text or thinking) within
40
40
  * this long is treated as refused and retried inline. agy 1.5.14 retries the refusal silently for ~140 s. 0 disables. */
41
41
  refusalProbeMs: number;
42
+ /** Reattach continued pi sessions to agy's stored conversation with ACP `session/resume` instead of replaying
43
+ * history (PI_AGY_RESUME=0 turns it off). */
44
+ resume: boolean;
42
45
  }
43
46
 
44
47
  export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
@@ -55,6 +58,7 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
55
58
  controlTimeoutMs: 60_000,
56
59
  systemPrompt: "auto",
57
60
  refusalProbeMs: 30_000,
61
+ resume: true,
58
62
  });
59
63
 
60
64
  /** Every environment variable loadConfig reads. pi resolves provider-scoped settings only through auth hooks, so the
@@ -73,6 +77,7 @@ export const CONFIG_ENV_NAMES = [
73
77
  "PI_AGY_CONTROL_TIMEOUT_SEC",
74
78
  "PI_AGY_SYSTEM_PROMPT",
75
79
  "PI_AGY_REFUSAL_PROBE_SEC",
80
+ "PI_AGY_RESUME",
76
81
  ] as const;
77
82
 
78
83
  function delivery(value: string | undefined): SystemPromptDelivery {
@@ -103,5 +108,6 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
103
108
  controlTimeoutMs: positiveInt(env.PI_AGY_CONTROL_TIMEOUT_SEC, DEFAULT_CONFIG.controlTimeoutMs, 1000),
104
109
  systemPrompt: delivery(env.PI_AGY_SYSTEM_PROMPT),
105
110
  refusalProbeMs: positiveInt(env.PI_AGY_REFUSAL_PROBE_SEC, DEFAULT_CONFIG.refusalProbeMs, 1000),
111
+ resume: !/^(0|false|off|no)$/i.test(env.PI_AGY_RESUME?.trim() ?? ""),
106
112
  };
107
113
  }
@@ -0,0 +1,168 @@
1
+ // agy's own conversation store, read-only, plus the bridge's record of which agy conversation holds which pi session.
2
+ //
3
+ // agy keeps every conversation in `<gemini-dir>/antigravity-cli/conversations/<sessionId>.db` (SQLite) and can reopen
4
+ // it in a new process with ACP `session/resume` without replaying it (verified on agy 1.5.17: a codeword told in one
5
+ // process was recalled in the next, input served from cache). The bridge records, per pi session, the agy session id,
6
+ // the hash chain it holds and agy's step count; a continued pi session can then reattach instead of replaying history.
7
+ //
8
+ // Resuming is only safe when agy's conversation is exactly what the bridge left behind. The check reads agy's database
9
+ // read-only and sends nothing: any client prompt (USER_INPUT step) after the recorded step count means another client
10
+ // or branch continued it, and a missing or shorter conversation means it is gone. Both fall back to a full replay.
11
+ // Idea and step type taken from patlux/pi-antigravity-thin-client (src/session/agy-resume.ts, MIT).
12
+
13
+ import { readFile } from "node:fs/promises";
14
+ import { existsSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { writeFileAtomic } from "./atomic-write.ts";
17
+
18
+ /** agy's `steps.step_type` for a prompt sent by a client. Measured on 1.5.17: 14 USER_INPUT, 15 PLANNER_RESPONSE,
19
+ * 101 SYSTEM_MESSAGE (resume marker), 17 on failed attempts. */
20
+ export const USER_INPUT_STEP_TYPE = 14;
21
+
22
+ export type ConversationSinceRecord = "continued" | "prompted" | "lost";
23
+
24
+ export function conversationDbPath(geminiDir: string, sessionId: string): string {
25
+ return path.join(geminiDir, "antigravity-cli", "conversations", `${sessionId}.db`);
26
+ }
27
+
28
+ /** agy session ids are UUIDs; anything else is never used in a path. */
29
+ const SESSION_ID = /^[A-Za-z0-9-]{8,64}$/;
30
+
31
+ type Sqlite = typeof import("node:sqlite");
32
+ let sqliteModule: Promise<Sqlite | undefined> | undefined;
33
+
34
+ /** node:sqlite (Node >= 22.5). Undefined when unavailable: every check then answers "lost" and the bridge replays. */
35
+ function loadSqlite(): Promise<Sqlite | undefined> {
36
+ sqliteModule ??= import("node:sqlite").then(
37
+ (module) => module,
38
+ () => undefined,
39
+ );
40
+ return sqliteModule;
41
+ }
42
+
43
+ /** Read `{steps, userInputs since fromStep}` from agy's conversation db, or undefined when it cannot be read. */
44
+ export async function readConversationSteps(
45
+ geminiDir: string,
46
+ sessionId: string,
47
+ fromStep = 0,
48
+ ): Promise<{ steps: number; promptsSince: number } | undefined> {
49
+ if (!SESSION_ID.test(sessionId)) return undefined;
50
+ const file = conversationDbPath(geminiDir, sessionId);
51
+ if (!existsSync(file)) return undefined;
52
+ const sqlite = await loadSqlite();
53
+ if (!sqlite) return undefined;
54
+ let db: import("node:sqlite").DatabaseSync | undefined;
55
+ try {
56
+ db = new sqlite.DatabaseSync(file, { readOnly: true });
57
+ db.exec("PRAGMA busy_timeout = 1500");
58
+ const total = db.prepare("SELECT COUNT(*) AS n FROM steps").get() as { n?: unknown } | undefined;
59
+ const since = db
60
+ .prepare("SELECT COUNT(*) AS n FROM steps WHERE idx >= ? AND step_type = ?")
61
+ .get(fromStep, USER_INPUT_STEP_TYPE) as { n?: unknown } | undefined;
62
+ const steps = Number(total?.n);
63
+ const promptsSince = Number(since?.n);
64
+ return Number.isFinite(steps) && Number.isFinite(promptsSince) ? { steps, promptsSince } : undefined;
65
+ } catch {
66
+ return undefined;
67
+ } finally {
68
+ try {
69
+ db?.close();
70
+ } catch {
71
+ // already read; nothing to release
72
+ }
73
+ }
74
+ }
75
+
76
+ /** What happened to agy's conversation since the bridge recorded `steps`. Read-only; sends nothing to agy. */
77
+ export async function checkConversation(geminiDir: string, sessionId: string, steps: number): Promise<ConversationSinceRecord> {
78
+ const now = await readConversationSteps(geminiDir, sessionId, steps);
79
+ if (!now || now.steps < steps) return "lost";
80
+ return now.promptsSince > 0 ? "prompted" : "continued";
81
+ }
82
+
83
+ // ---- resume records ----------------------------------------------------------------------------------------------
84
+
85
+ export interface ResumeRecord {
86
+ acpSessionId: string;
87
+ /** Length of the hash chain agy holds (seed + one link per message). */
88
+ chainLength: number;
89
+ /** Last link of that chain. Each link hashes its predecessor, so equal last links at equal length prove the whole
90
+ * prefix (system prompt, tools, model, thinking level and every message) is identical. */
91
+ chainLast: string;
92
+ /** agy's step count when the record was written; the check looks for client prompts after it. */
93
+ steps: number;
94
+ savedAt: number;
95
+ }
96
+
97
+ interface ResumeFile {
98
+ version: 1;
99
+ sessions: Record<string, ResumeRecord>;
100
+ }
101
+
102
+ const MAX_RECORDS = 200;
103
+
104
+ function isRecord(value: unknown): value is ResumeRecord {
105
+ if (!value || typeof value !== "object") return false;
106
+ const r = value as Record<string, unknown>;
107
+ return (
108
+ typeof r.acpSessionId === "string" &&
109
+ SESSION_ID.test(r.acpSessionId) &&
110
+ typeof r.chainLength === "number" &&
111
+ typeof r.chainLast === "string" &&
112
+ typeof r.steps === "number" &&
113
+ typeof r.savedAt === "number"
114
+ );
115
+ }
116
+
117
+ /** pi session id -> record, persisted next to an account's agy dir. No long-lived cache: every read goes to disk and
118
+ * every change is a read-modify-write of one key, serialized within this process, so records written by another pi
119
+ * process (a subagent, a second window) survive. Two processes writing in the same instant can still lose one record,
120
+ * which only costs that session one replay. */
121
+ export class ResumeStore {
122
+ readonly file: string;
123
+ #writing: Promise<void> = Promise.resolve();
124
+
125
+ constructor(file: string) {
126
+ this.file = file;
127
+ }
128
+
129
+ async #read(): Promise<Map<string, ResumeRecord>> {
130
+ const map = new Map<string, ResumeRecord>();
131
+ try {
132
+ const parsed = JSON.parse(await readFile(this.file, "utf8")) as Partial<ResumeFile>;
133
+ for (const [key, value] of Object.entries(parsed.sessions ?? {})) if (isRecord(value)) map.set(key, value);
134
+ } catch {
135
+ // missing or unreadable: empty
136
+ }
137
+ return map;
138
+ }
139
+
140
+ async get(piSessionId: string): Promise<ResumeRecord | undefined> {
141
+ await this.#writing.catch(() => undefined);
142
+ return (await this.#read()).get(piSessionId);
143
+ }
144
+
145
+ set(piSessionId: string, record: ResumeRecord): Promise<void> {
146
+ return this.#update((map) => {
147
+ map.delete(piSessionId); // re-insert: most recent last
148
+ map.set(piSessionId, record);
149
+ while (map.size > MAX_RECORDS) map.delete(map.keys().next().value as string);
150
+ return true;
151
+ });
152
+ }
153
+
154
+ delete(piSessionId: string): Promise<void> {
155
+ return this.#update((map) => map.delete(piSessionId));
156
+ }
157
+
158
+ #update(change: (map: Map<string, ResumeRecord>) => boolean): Promise<void> {
159
+ const run = async (): Promise<void> => {
160
+ const map = await this.#read();
161
+ if (!change(map)) return;
162
+ const body: ResumeFile = { version: 1, sessions: Object.fromEntries(map) };
163
+ await writeFileAtomic(this.file, `${JSON.stringify(body)}\n`);
164
+ };
165
+ this.#writing = this.#writing.then(run, run);
166
+ return this.#writing;
167
+ }
168
+ }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  doctorText,
9
9
  emailOf,
10
10
  promptAdd,
11
+ promptApiKey,
11
12
  promptRemove,
12
13
  runAccountAction,
13
14
  runLogin,
@@ -23,6 +24,7 @@ const COMMANDS: readonly AutocompleteItem[] = [
23
24
  { value: "accounts", label: "accounts", description: "List accounts, providers and recorded emails" },
24
25
  { value: "add", label: "add <id> [alias]", description: "Add an Antigravity account and sign it in" },
25
26
  { value: "login", label: "login <id>", description: "Sign an extra account in (or switch its Google account)" },
27
+ { value: "apikey", label: "apikey <id>", description: "Set an account's Gemini API key (used instead of its Google login), or clear it" },
26
28
  { value: "alias", label: "alias <id> [alias]", description: "Set or clear an account's alias (provider agy-<alias>)" },
27
29
  { value: "email", label: "email <id> [email]", description: "Set or clear the expected Google account by hand" },
28
30
  { value: "enable", label: "enable <id>", description: "Register a disabled account's provider again" },
@@ -90,10 +92,10 @@ function completions(manager: AccountManager, prefix: string): AutocompleteItem[
90
92
  }
91
93
  const sub = parts[0];
92
94
  if (parts.length > 2) return null; // the account is the only argument that completes
93
- if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor"].includes(sub)) return null;
95
+ if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor", "apikey"].includes(sub)) return null;
94
96
  const typed = parts[1] ?? "";
95
97
  const ids = [
96
- ...(["check", "models", "reset", "doctor"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
98
+ ...(["check", "models", "reset", "doctor", "apikey"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
97
99
  ...(sub === "reset" ? [{ id: "all", note: "every account" }] : []),
98
100
  ...manager.accounts.map((account) => ({
99
101
  id: account.id,
@@ -161,6 +163,12 @@ export async function handle(manager: AccountManager, args: string, ctx: Extensi
161
163
  case "login":
162
164
  await runLogin(manager, extra(), ctx, say);
163
165
  return;
166
+ case "apikey": {
167
+ const id = need();
168
+ if (!ctx.hasUI) throw new Error("setting an API key needs the interactive UI (the key is never taken from the command line)");
169
+ await promptApiKey(manager, id, ctx, say);
170
+ return;
171
+ }
164
172
  case "alias": {
165
173
  const id = extra();
166
174
  const next = await manager.setAlias(id, rest[0]);
@@ -7,6 +7,7 @@
7
7
  // discovery only, so an older agy is never offered a model it does not have.
8
8
 
9
9
  import type { Model } from "@earendil-works/pi-ai";
10
+ import { getBuiltinModels, getBuiltinProviders, type BuiltinProvider } from "@earendil-works/pi-ai/providers/all";
10
11
  import type { AcpConfigOption, AcpConfigOptionValue, AcpNewSessionResult } from "./acp/types.ts";
11
12
 
12
13
  export const PROVIDER_ID = "agy";
@@ -105,6 +106,51 @@ function limitsFor(id: string, observed: number | undefined): Limits {
105
106
  return observed && observed > 0 ? { ...base, contextWindow: observed } : base;
106
107
  }
107
108
 
109
+ type Cost = AgyModel["cost"];
110
+ const ZERO_COST: Cost = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
111
+ /** Whose list price counts for an agy model id: the model's own vendor first, then the big clouds. */
112
+ const PRICE_PROVIDERS = ["google", "anthropic", "google-vertex", "openai", "opencode", "openrouter"];
113
+ let priceIndex: Map<string, Cost> | undefined;
114
+
115
+ function prices(): Map<string, Cost> {
116
+ if (priceIndex) return priceIndex;
117
+ const index = new Map<string, Cost>();
118
+ try {
119
+ const available = new Set<string>(getBuiltinProviders());
120
+ for (const provider of PRICE_PROVIDERS) {
121
+ if (!available.has(provider)) continue;
122
+ for (const model of getBuiltinModels(provider as BuiltinProvider)) {
123
+ const cost = model.cost;
124
+ if (!cost || !(cost.input > 0 || cost.output > 0)) continue;
125
+ const id = model.id.toLowerCase();
126
+ if (id.includes(":batch") || id.endsWith("-batch")) continue;
127
+ for (const key of [id, id.slice(id.lastIndexOf("/") + 1)]) if (!index.has(key)) index.set(key, cost);
128
+ }
129
+ }
130
+ } catch {
131
+ // pi-ai's catalog layout changed: every model stays at zero rather than failing registration.
132
+ }
133
+ priceIndex = index;
134
+ return index;
135
+ }
136
+
137
+ /** Reference list price for an agy model, taken from pi's built-in catalog (the same model sold directly by its
138
+ * vendor). Tried in order: the id, the id without a baked-in level (`gpt-oss-120b-medium`), and the id with version
139
+ * dots and dashes swapped (`claude-opus-5-5` / `claude-opus-5.5`). Zero when pi does not know the model. Under a
140
+ * subscription pi labels this as list price covered by the plan; with an API key it is what Google bills. */
141
+ export function referenceCost(id: string): Cost {
142
+ const raw = id.toLowerCase();
143
+ const bases = [raw, raw.replace(FIXED_LEVEL, ""), raw.replace(/-thinking$/, "")];
144
+ const index = prices();
145
+ for (const base of bases) {
146
+ for (const key of [base, base.replace(/(\d)\.(\d)/g, "$1-$2"), base.replace(/(\d)-(\d)(?=$|-)/g, "$1.$2")]) {
147
+ const found = index.get(key);
148
+ if (found) return { ...found, ...(found.tiers ? { tiers: found.tiers.map((tier) => ({ ...tier })) } : {}) };
149
+ }
150
+ }
151
+ return { ...ZERO_COST };
152
+ }
153
+
108
154
  type LevelMap = NonNullable<AgyModel["thinkingLevelMap"]>;
109
155
 
110
156
  function levelMap(descriptor: AgyModelDescriptor): LevelMap {
@@ -146,8 +192,8 @@ export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: numbe
146
192
  reasoning,
147
193
  ...(reasoning ? { thinkingLevelMap: levelMap(descriptor) } : {}),
148
194
  input: limits.input,
149
- // Subscription-billed through the user's Antigravity plan: pi shows list price as zero.
150
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
195
+ // Reference list price (see referenceCost); the provider's auth marks subscription accounts as plan-covered.
196
+ cost: referenceCost(descriptor.id),
151
197
  contextWindow: limits.contextWindow,
152
198
  maxTokens: limits.maxTokens,
153
199
  };
package/src/provider.ts CHANGED
@@ -35,7 +35,13 @@ export function createAgyProvider(runtime: AgyRuntime) {
35
35
  const ids: ProviderIds = account
36
36
  ? { provider: providerIdFor(account), api: apiIdFor(account), nameSuffix: ` · ${labelFor(account)}` }
37
37
  : DEFAULT_IDS;
38
- const accountName = account ? `Antigravity · ${labelFor(account)}${account.email ? ` (${maskEmail(account.email)})` : ""}` : undefined;
38
+ // Fixed when the provider is registered; a changed sign-in method re-registers the provider (AccountManager).
39
+ const apiKeyMode = runtime.authMode === "api-key";
40
+ const accountName = account
41
+ ? `Antigravity · ${labelFor(account)}${apiKeyMode ? " (API key)" : account.email ? ` (${maskEmail(account.email)})` : ""}`
42
+ : apiKeyMode
43
+ ? "Antigravity (agy acp, API key)"
44
+ : undefined;
39
45
  // A provider registered again (alias rename, account edit) starts from what this account's process already reported,
40
46
  // not from the static list: an account on a smaller plan must keep showing only its own models.
41
47
  const known = account && runtime.pool.cachedDiscovery ? describeModels(runtime.pool.cachedDiscovery) : [];
@@ -64,7 +70,7 @@ export function createAgyProvider(runtime: AgyRuntime) {
64
70
  runtime.trace(`provider.check: unavailable (${reason})`);
65
71
  return undefined;
66
72
  }
67
- return { type: "oauth", source: SOURCE };
73
+ return runtime.authMode === "api-key" ? { type: "api_key", source: `${SOURCE}, Gemini API key` } : { type: "oauth", source: SOURCE };
68
74
  }, async resolve({ ctx, signal }) {
69
75
  signal.throwIfAborted();
70
76
  runtime.trace("provider.resolve");
@@ -75,8 +81,8 @@ export function createAgyProvider(runtime: AgyRuntime) {
75
81
  // Metadata marker so pi labels list price as subscription-covered. Login and logout belong to agy itself;
76
82
  // pi-agy-bridge never reads, stores or forwards Antigravity credentials.
77
83
  oauth: {
78
- name: "Antigravity subscription (managed by agy)",
79
- isSubscription: true,
84
+ name: apiKeyMode ? "Antigravity with a Gemini API key (billed per token)" : "Antigravity subscription (managed by agy)",
85
+ isSubscription: !apiKeyMode,
80
86
  async login() {
81
87
  throw new Error(
82
88
  account
package/src/runtime.ts CHANGED
@@ -5,12 +5,16 @@ import path from "node:path";
5
5
  import {
6
6
  accountPaths,
7
7
  accountProcessPaths,
8
+ apiKeyPathsFor,
8
9
  DEFAULT_ACCOUNT,
9
10
  FILE_STORAGE_ENV,
10
11
  maskEmail,
12
+ readApiKey,
13
+ withoutApiKeys,
11
14
  rotateAccountLog,
12
15
  waitForIdentity,
13
16
  type AccountRecord,
17
+ type AuthMode,
14
18
  type Identity,
15
19
  } from "./accounts.ts";
16
20
  import { findAgyCommand } from "./acp/command.ts";
@@ -31,6 +35,8 @@ export interface RuntimeOptions {
31
35
  log?: (message: string) => void;
32
36
  /** The Antigravity account this runtime serves. Absent = the default (keyring) account, exactly as before. */
33
37
  account?: AccountRecord;
38
+ /** Sign-in method of the default account (extra accounts carry theirs in `account.auth`). Absent = google. */
39
+ defaultAuth?: AuthMode;
34
40
  /** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
35
41
  * (default 10 s; agy writes it during that call, so normally no wait at all). */
36
42
  identityTimeoutMs?: number;
@@ -79,10 +85,12 @@ export class AgyRuntime {
79
85
  #writes = new Set<Promise<void>>();
80
86
  #account: AccountRecord | undefined;
81
87
  #identity: AccountIdentityState | undefined;
88
+ #defaultAuth: AuthMode;
82
89
 
83
90
  constructor(options: RuntimeOptions = {}) {
84
91
  this.#options = options;
85
92
  this.#account = options.account && options.account.id !== DEFAULT_ACCOUNT ? { ...options.account } : undefined;
93
+ this.#defaultAuth = options.defaultAuth ?? "google";
86
94
  this.config = loadConfig(options.env ?? process.env);
87
95
  const trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
88
96
  this.trace = this.#account ? (message) => trace(`[${this.accountLabel}] ${message}`) : trace;
@@ -108,18 +116,66 @@ export class AgyRuntime {
108
116
  return this.#account ? accountPaths(this.config.home, this.#account.id).root : this.config.home;
109
117
  }
110
118
 
111
- /** Change alias/email/enabled of the bound account. A changed email stops the process so the next use re-checks. */
119
+ /** How this account signs in. */
120
+ get authMode(): AuthMode {
121
+ return this.#account ? (this.#account.auth ?? "google") : this.#defaultAuth;
122
+ }
123
+
124
+ /** Change alias/email/enabled/auth of the bound account. A changed email or sign-in method stops the process (and,
125
+ * for the method, rebuilds the pool on its own agy dir) so the next use starts with the new identity. */
112
126
  updateAccount(next: AccountRecord): void {
113
127
  if (!this.#account || next.id !== this.#account.id) return;
114
128
  const emailChanged = next.email !== this.#account.email;
129
+ const authChanged = (next.auth ?? "google") !== (this.#account.auth ?? "google");
115
130
  this.#account = { ...next };
116
- if (emailChanged) {
131
+ if (authChanged) {
132
+ this.#identity = undefined;
133
+ this.#rebuildPool("sign-in method changed");
134
+ } else if (emailChanged) {
117
135
  this.#identity = undefined;
118
136
  void this.#pool.reset().catch((error: unknown) => this.trace(`reset after account change failed: ${describeError(error)}`));
119
137
  this.#pool.resetDiscovery();
120
138
  }
121
139
  }
122
140
 
141
+ /** Switch the default account's sign-in method (extra accounts go through updateAccount). */
142
+ setDefaultAuth(mode: AuthMode): void {
143
+ if (this.#account || mode === this.#defaultAuth) return;
144
+ this.#defaultAuth = mode;
145
+ this.#rebuildPool("sign-in method changed");
146
+ }
147
+
148
+ /** The stored API key was replaced (same mode): the next process must start with the new key. */
149
+ async apiKeyChanged(): Promise<void> {
150
+ if (this.authMode !== "api-key") return;
151
+ await this.clearUnusable();
152
+ await this.#pool.reset();
153
+ this.#pool.resetDiscovery();
154
+ }
155
+
156
+ /** Where this account's API key and API-key agy dir live. */
157
+ get apiKeyPaths(): { root: string; apiKeyGeminiDir: string; apiKeyFile: string } {
158
+ return apiKeyPathsFor(this.config.home, this.#account?.id ?? DEFAULT_ACCOUNT);
159
+ }
160
+
161
+ /** The key an API-key process uses: only the one stored through the menu. The environment is never consulted, so a
162
+ * GEMINI_API_KEY exported for other tools cannot silently move an account off its subscription login. */
163
+ async resolveApiKey(): Promise<string | undefined> {
164
+ return readApiKey(this.apiKeyPaths.apiKeyFile);
165
+ }
166
+
167
+ #rebuildPool(reason: string): void {
168
+ const old = this.#pool;
169
+ this.#pool = this.#createPool();
170
+ this.trace(`pool rebuilt (${reason}); auth=${this.authMode}`);
171
+ const retired: Promise<void> = old.dispose().then(
172
+ () => undefined,
173
+ (error: unknown) => this.#options.log?.(`retired agy pool failed to stop: ${describeError(error)}`),
174
+ );
175
+ this.#retiring.add(retired);
176
+ void retired.finally(() => this.#retiring.delete(retired));
177
+ }
178
+
123
179
  /** Forget a recorded "unusable" hint (after a successful sign-in) so the provider is offered again at once. */
124
180
  async clearUnusable(): Promise<void> {
125
181
  this.#hintRecorded = false;
@@ -157,18 +213,53 @@ export class AgyRuntime {
157
213
  const account = this.#account;
158
214
  const paths = account ? accountProcessPaths(this.config.home, account.id, this.#options.accountLogOwner) : undefined;
159
215
  const baseEnv = this.#options.pool?.env;
216
+ const apiKey = this.authMode === "api-key";
217
+ const keyPaths = this.apiKeyPaths;
218
+ // API-key mode: agy's own `gemini-api-key` method in a dir of its own (agy caches the method per dir), the key in
219
+ // the child's GEMINI_API_KEY only, no SSH marker and no email guard (an API key has no Google identity).
220
+ const googleAccount = account && !apiKey ? paths : undefined;
221
+ const workDir = paths ? path.join(paths.root, "work") : undefined;
222
+ // Google mode never sees an API key from the environment: agy must serve the account's own signed-in login.
223
+ const googleEnv = withoutApiKeys(baseEnv ?? process.env);
160
224
  const pool = new SessionPool({
161
225
  config: this.config,
162
226
  buildArgs: this.#options.pool?.buildArgs,
163
- env: account ? { ...(baseEnv ?? process.env), ...FILE_STORAGE_ENV } : baseEnv,
164
- ...(paths
227
+ env: apiKey ? googleEnv : googleAccount ? { ...googleEnv, ...FILE_STORAGE_ENV } : googleEnv,
228
+ ...(apiKey
229
+ ? {
230
+ authMethod: "gemini-api-key",
231
+ stagingOverride: { geminiDir: keyPaths.apiKeyGeminiDir, ...(workDir ? { workDir } : {}) },
232
+ resolveEnv: async () => {
233
+ const key = await this.resolveApiKey();
234
+ if (!key) {
235
+ throw new AgyError(
236
+ "auth",
237
+ `agy authentication required (not logged in): the stored Gemini API key for ${this.#account ? `account ${this.#account.id}` : "the default account"} is gone; set it again in /agy-bridge menu or remove it to use the Google login`,
238
+ );
239
+ }
240
+ return { ...googleEnv, GEMINI_API_KEY: key };
241
+ },
242
+ ...(paths || this.#options.pool?.buildArgs
243
+ ? {
244
+ extraArgs: (staging: { geminiDir: string }) => [
245
+ ...(this.#options.pool?.buildArgs ? ["--gemini-dir", staging.geminiDir] : []),
246
+ ...(paths ? ["--log-file", paths.logFile] : []),
247
+ ],
248
+ ...(paths ? { beforeStart: () => rotateAccountLog(paths) } : {}),
249
+ }
250
+ : {}),
251
+ }
252
+ : {}),
253
+ ...(googleAccount
165
254
  ? {
166
- stagingOverride: { geminiDir: paths.geminiDir, workDir: path.join(paths.root, "work") },
255
+ stagingOverride: { geminiDir: googleAccount.geminiDir, workDir: path.join(googleAccount.root, "work") },
167
256
  extraArgs: (staging) =>
168
257
  // The real argv already names the gemini dir through the staging override; a test argv may not.
169
- this.#options.pool?.buildArgs ? ["--gemini-dir", staging.geminiDir, "--log-file", paths.logFile] : ["--log-file", paths.logFile],
170
- beforeStart: () => rotateAccountLog(paths),
171
- verifyProcess: (proc, sessionFailure) => this.#checkIdentity(paths.logFile, proc, sessionFailure),
258
+ this.#options.pool?.buildArgs
259
+ ? ["--gemini-dir", staging.geminiDir, "--log-file", googleAccount.logFile]
260
+ : ["--log-file", googleAccount.logFile],
261
+ beforeStart: () => rotateAccountLog(googleAccount),
262
+ verifyProcess: (proc, sessionFailure) => this.#checkIdentity(googleAccount.logFile, proc, sessionFailure),
172
263
  }
173
264
  : {}),
174
265
  log: this.trace,
@@ -248,6 +339,9 @@ export class AgyRuntime {
248
339
  if (!found) {
249
340
  return { available: false, reason: `agy was not found (command "${this.config.command}"); install the Antigravity CLI or set PI_AGY_COMMAND` };
250
341
  }
342
+ if (this.authMode === "api-key" && !(await this.resolveApiKey())) {
343
+ return { available: false, reason: "the stored Gemini API key is gone: set it again in /agy-bridge menu" };
344
+ }
251
345
  const state = await readState(this.stateDir);
252
346
  const bad = state.unusable;
253
347
  if (bad && Date.now() - bad.at < UNUSABLE_HINT_MS) {