@timmyjl12/pi-agy-bridge 0.1.5 → 0.2.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/src/index.ts CHANGED
@@ -1,39 +1,73 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { buildDoctor, buildStatus } from "./doctor.ts";
3
- import { createAgyProvider } from "./provider.ts";
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
3
+ import { AccountManager } from "./account-manager.ts";
4
+ import { DEFAULT_ACCOUNT, maskEmail } from "./accounts.ts";
5
+ import { describeError } from "./errors.ts";
4
6
  import { AgyRuntime } from "./runtime.ts";
7
+ import {
8
+ doctorText,
9
+ emailOf,
10
+ promptAdd,
11
+ promptRemove,
12
+ runAccountAction,
13
+ runLogin,
14
+ runMenu,
15
+ stateOf,
16
+ statusText,
17
+ type Notify,
18
+ } from "./ui/menu.ts";
19
+
20
+ const COMMANDS: readonly AutocompleteItem[] = [
21
+ { value: "menu", label: "menu", description: "Open the accounts & settings overlay" },
22
+ { value: "status", label: "status", description: "One line per account: process, sessions, sign-in state" },
23
+ { value: "accounts", label: "accounts", description: "List accounts, providers and recorded emails" },
24
+ { value: "add", label: "add <id> [alias]", description: "Add an Antigravity account and sign it in" },
25
+ { value: "login", label: "login <id>", description: "Sign an extra account in (or switch its Google account)" },
26
+ { value: "alias", label: "alias <id> [alias]", description: "Set or clear an account's alias (provider agy-<alias>)" },
27
+ { value: "email", label: "email <id> [email]", description: "Set or clear the expected Google account by hand" },
28
+ { value: "enable", label: "enable <id>", description: "Register a disabled account's provider again" },
29
+ { value: "disable", label: "disable <id>", description: "Hide an account's models and stop its process" },
30
+ { value: "remove", label: "remove <id>", description: "Forget an account (asks before deleting its saved login)" },
31
+ { value: "check", label: "check [id]", description: "Start an account once and list its models (no quota)" },
32
+ { value: "models", label: "models [id]", description: "List the models an account offers" },
33
+ { value: "reset", label: "reset [id|all]", description: "Stop agy process(es) and forget pooled sessions" },
34
+ { value: "doctor", label: "doctor [id]", description: "Handshake, compatibility and model report" },
35
+ { value: "help", label: "help", description: "Show the command list" },
36
+ ];
37
+
38
+ const USAGE = `Usage: /agy-bridge [${COMMANDS.map((command) => command.label).join(" | ")}]`;
5
39
 
6
40
  export default function agyBridgeExtension(pi: ExtensionAPI): void {
7
- // Nothing is started here: the shared `agy acp` process is created on first use, so loading this extension
8
- // costs no processes and no I/O.
41
+ // Nothing is started here: each account's `agy acp` process is created on first use, so loading this extension
42
+ // costs no processes. The default provider is registered synchronously; extra accounts follow from accounts.json.
9
43
  const runtime = new AgyRuntime();
10
- pi.registerProvider(createAgyProvider(runtime));
44
+ const manager = new AccountManager({ host: pi, defaultRuntime: runtime });
45
+ manager.registerDefault();
46
+ void manager.load().catch((error: unknown) => runtime.trace(`accounts: load failed: ${describeError(error)}`));
47
+
48
+ let notify: Notify = (message) => runtime.trace(`notice: ${message}`);
11
49
 
12
50
  pi.registerCommand("agy-bridge", {
13
- description: "pi-agy-bridge: status | doctor | reset (Antigravity via agy acp)",
51
+ description: "pi-agy-bridge: accounts & settings menu, status, doctor, account management (Antigravity via agy acp)",
52
+ getArgumentCompletions: (prefix) => completions(manager, prefix),
14
53
  handler: async (args, ctx) => {
15
- const action = (args ?? "").trim().split(/\s+/)[0] || "status";
16
- switch (action) {
17
- case "status":
18
- ctx.ui.notify(buildStatus(runtime), "info");
19
- return;
20
- case "doctor": {
21
- const report = await buildDoctor(runtime, { force: true });
22
- ctx.ui.notify(report.lines.join("\n"), report.ok ? "info" : "error");
23
- return;
24
- }
25
- case "reset":
26
- await runtime.pool.reset();
27
- ctx.ui.notify("pi-agy-bridge: agy process and pooled sessions reset", "info");
28
- return;
29
- default:
30
- ctx.ui.notify("Usage: /agy-bridge [status|doctor|reset]", "warning");
54
+ const say: Notify = (message, level) => ctx.ui.notify(message, level);
55
+ try {
56
+ await handle(manager, (args ?? "").trim(), ctx, say);
57
+ } catch (error) {
58
+ say(`pi-agy-bridge: ${describeError(error)}`, "error");
31
59
  }
32
60
  },
33
61
  });
34
62
 
35
63
  pi.on("session_start", async (_event, ctx) => {
36
- runtime.onNotice = (message, level) => ctx.ui.notify(message, level);
64
+ notify = (message, level) => ctx.ui.notify(message, level);
65
+ const toUi = (message: string, level: "info" | "warning" | "error") => notify(message, level);
66
+ runtime.onNotice = toUi;
67
+ manager.onNotice = toUi;
68
+ await manager.load().catch((error: unknown) => runtime.trace(`accounts: load failed: ${describeError(error)}`));
69
+ manager.notice = toUi;
70
+ for (const warning of manager.warnings) notify(`pi-agy-bridge: ${warning}`, "warning");
37
71
  });
38
72
 
39
73
  // Every shutdown reason replaces this extension runtime. Recycle rather than permanently disposing the pool:
@@ -41,10 +75,150 @@ export default function agyBridgeExtension(pi: ExtensionAPI): void {
41
75
  // not hit a terminal shutdown latch. Hooks stay detached; a late process is bounded by the normal idle reaper.
42
76
  pi.on("session_shutdown", async () => {
43
77
  runtime.onNotice = undefined;
44
- await runtime.recycle();
78
+ manager.onNotice = undefined;
79
+ manager.notice = undefined;
80
+ await manager.recycle();
45
81
  });
46
82
  }
47
83
 
84
+ function completions(manager: AccountManager, prefix: string): AutocompleteItem[] | null {
85
+ const text = prefix.trimStart().toLowerCase();
86
+ const parts = text.split(/\s+/);
87
+ if (parts.length <= 1) {
88
+ const matches = COMMANDS.filter((command) => command.value.startsWith(parts[0] ?? ""));
89
+ return matches.length ? [...matches] : null;
90
+ }
91
+ const sub = parts[0];
92
+ 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;
94
+ const typed = parts[1] ?? "";
95
+ const ids = [
96
+ ...(["check", "models", "reset", "doctor"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
97
+ ...(sub === "reset" ? [{ id: "all", note: "every account" }] : []),
98
+ ...manager.accounts.map((account) => ({
99
+ id: account.id,
100
+ alias: account.alias,
101
+ note: `agy-${account.alias ?? account.id}${account.email ? ` · ${maskEmail(account.email)}` : ""}`,
102
+ })),
103
+ ].filter((entry) => entry.id.startsWith(typed) || ("alias" in entry && entry.alias?.startsWith(typed)));
104
+ return ids.length ? ids.map((entry) => ({ value: `${sub} ${entry.id}`, label: entry.id, description: entry.note })) : null;
105
+ }
106
+
107
+ /** One `/agy-bridge` invocation. Every branch calls the same function the menu uses. */
108
+ export async function handle(manager: AccountManager, args: string, ctx: ExtensionCommandContext, say: Notify): Promise<void> {
109
+ const [action = "", first, ...rest] = args.split(/\s+/).filter(Boolean);
110
+ await manager.load();
111
+ const need = (): string => {
112
+ const id = manager.resolve(first);
113
+ if (!id) throw new Error(first ? `no account "${first}" — /agy-bridge accounts lists them` : `which account? ${USAGE}`);
114
+ return id;
115
+ };
116
+ const extra = (): string => {
117
+ const id = need();
118
+ if (id === DEFAULT_ACCOUNT) throw new Error("the default account cannot be changed here; it uses agy's own login");
119
+ return id;
120
+ };
121
+ switch (action.toLowerCase()) {
122
+ case "":
123
+ if (ctx.mode === "tui") await runMenu({ manager, notify: say }, ctx);
124
+ else say(await statusText(manager), "info");
125
+ return;
126
+ case "menu":
127
+ case "settings":
128
+ await runMenu({ manager, notify: say }, ctx);
129
+ return;
130
+ case "status":
131
+ say(await statusText(manager), "info");
132
+ return;
133
+ case "accounts": {
134
+ const views = await manager.views();
135
+ say(
136
+ views
137
+ .map((view) => {
138
+ // Same state and email the menu shows; a failed identity check shows the expected account, not the wrong one.
139
+ const failed = view.identity !== undefined && !view.identity.ok;
140
+ const email = failed ? view.account.email : emailOf(view);
141
+ const state = stateOf(view).text;
142
+ return `${(view.isDefault ? "agy" : view.provider).padEnd(18)} ${view.account.id.padEnd(10)} ${email ? maskEmail(email) : view.isDefault ? "agy's own login" : "-"} ${state}${view.account.fromEnv ? " (PI_AGY_ACCOUNTS)" : ""}`;
143
+ })
144
+ .join("\n"),
145
+ "info",
146
+ );
147
+ return;
148
+ }
149
+ case "add": {
150
+ if (!first) {
151
+ await promptAdd(manager, ctx, say);
152
+ return;
153
+ }
154
+ const account = await manager.add(first, rest[0]?.toLowerCase());
155
+ say(`pi-agy-bridge: added account "${account.id}" as provider agy-${account.alias ?? account.id}`, "info");
156
+ if (ctx.hasUI && (await ctx.ui.confirm("Sign in now?", `Open the Google sign-in for "${account.id}" in your browser now?`))) {
157
+ await runLogin(manager, account.id, ctx, say);
158
+ } else say(`pi-agy-bridge: sign in with /agy-bridge login ${account.id}`, "info");
159
+ return;
160
+ }
161
+ case "login":
162
+ await runLogin(manager, extra(), ctx, say);
163
+ return;
164
+ case "alias": {
165
+ const id = extra();
166
+ const next = await manager.setAlias(id, rest[0]);
167
+ say(`pi-agy-bridge: ${id} is now provider agy-${next.alias ?? next.id}`, "info");
168
+ return;
169
+ }
170
+ case "email": {
171
+ const id = extra();
172
+ await manager.setEmail(id, rest[0]);
173
+ say(`pi-agy-bridge: expected account for ${id}: ${rest[0] ? maskEmail(rest[0]) : "cleared"}`, "info");
174
+ return;
175
+ }
176
+ case "enable":
177
+ case "disable": {
178
+ const id = extra();
179
+ await manager.setEnabled(id, action.toLowerCase() === "enable");
180
+ say(`pi-agy-bridge: ${id} ${action.toLowerCase()}d`, "info");
181
+ return;
182
+ }
183
+ case "remove": {
184
+ const id = extra();
185
+ if (ctx.hasUI) await promptRemove(manager, id, ctx, say);
186
+ else {
187
+ await manager.remove(id, false);
188
+ say(`pi-agy-bridge: removed account "${id}" (login kept on disk)`, "info");
189
+ }
190
+ return;
191
+ }
192
+ case "check":
193
+ await runAccountAction(manager, first ? need() : DEFAULT_ACCOUNT, "check", ctx, say);
194
+ return;
195
+ case "models": {
196
+ const id = first ? need() : DEFAULT_ACCOUNT;
197
+ const check = await manager.check(id); // discovery is cached for a minute, so this is cheap when recent
198
+ if (!check.ok) say(`pi-agy-bridge: ${check.message}`, "error");
199
+ else await runAccountAction(manager, id, "models", ctx, say);
200
+ return;
201
+ }
202
+ case "reset":
203
+ if (!first || first === "all") {
204
+ await manager.resetAll();
205
+ say(first ? "pi-agy-bridge: every agy process reset" : "pi-agy-bridge: agy processes and pooled sessions reset", "info");
206
+ } else await runAccountAction(manager, need(), "reset", ctx, say);
207
+ return;
208
+ case "doctor": {
209
+ const report = await doctorText(manager, first ? need() : DEFAULT_ACCOUNT);
210
+ say(report.text, report.ok ? "info" : "error");
211
+ return;
212
+ }
213
+ case "help":
214
+ say(`${USAGE}\n${COMMANDS.map((command) => ` ${command.label.padEnd(20)} ${command.description}`).join("\n")}`, "info");
215
+ return;
216
+ default:
217
+ say(USAGE, "warning");
218
+ }
219
+ }
220
+
221
+ export { AccountManager } from "./account-manager.ts";
48
222
  export { createAgyProvider } from "./provider.ts";
49
223
  export { AgyRuntime } from "./runtime.ts";
50
224
  export { makeStreamAgy } from "./stream.ts";
@@ -13,7 +13,8 @@ export const PROVIDER_ID = "agy";
13
13
  export const API_ID = "agy-acp";
14
14
  export const BASE_URL = "process://agy-acp";
15
15
 
16
- export type AgyModel = Model<typeof API_ID>;
16
+ /** API ids are per account (`agy-acp`, `agy-acp-<name>`), so the model type is open over the api string. */
17
+ export type AgyModel = Model<string>;
17
18
 
18
19
  export interface AgyModelDescriptor {
19
20
  /** Value of the ACP `model` config option; also the pi model id. */
@@ -122,14 +123,25 @@ function levelMap(descriptor: AgyModelDescriptor): LevelMap {
122
123
  return map as LevelMap;
123
124
  }
124
125
 
125
- export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: number): AgyModel {
126
+ /** Which pi provider/api a model belongs to: `agy`/`agy-acp` for the default account, `agy-<name>`/`agy-acp-<name>`
127
+ * for an extra account. */
128
+ export interface ProviderIds {
129
+ provider: string;
130
+ api: string;
131
+ /** Appended to model display names of an extra account, e.g. " · work". */
132
+ nameSuffix?: string;
133
+ }
134
+
135
+ export const DEFAULT_IDS: Readonly<ProviderIds> = Object.freeze({ provider: PROVIDER_ID, api: API_ID });
136
+
137
+ export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: number, ids: ProviderIds = DEFAULT_IDS): AgyModel {
126
138
  const reasoning = descriptor.levels.length > 0 || descriptor.fixedLevel !== undefined;
127
139
  const limits = limitsFor(descriptor.id, observedWindow);
128
140
  return {
129
141
  id: descriptor.id,
130
- name: descriptor.name,
131
- api: API_ID,
132
- provider: PROVIDER_ID,
142
+ name: `${descriptor.name}${ids.nameSuffix ?? ""}`,
143
+ api: ids.api,
144
+ provider: ids.provider,
133
145
  baseUrl: BASE_URL,
134
146
  reasoning,
135
147
  ...(reasoning ? { thinkingLevelMap: levelMap(descriptor) } : {}),
@@ -144,8 +156,9 @@ export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: numbe
144
156
  export function toPiModels(
145
157
  descriptors: readonly AgyModelDescriptor[],
146
158
  observedWindows: ReadonlyMap<string, number> = new Map(),
159
+ ids: ProviderIds = DEFAULT_IDS,
147
160
  ): AgyModel[] {
148
- return descriptors.map((descriptor) => toPiModel(descriptor, observedWindows.get(descriptor.id)));
161
+ return descriptors.map((descriptor) => toPiModel(descriptor, observedWindows.get(descriptor.id), ids));
149
162
  }
150
163
 
151
164
  export const STATIC_MODELS: AgyModel[] = toPiModels(FALLBACK_DESCRIPTORS);
package/src/provider.ts CHANGED
@@ -3,7 +3,17 @@
3
3
 
4
4
  import { createProvider, type AuthContext, type ProviderEnv } from "@earendil-works/pi-ai";
5
5
  import { CONFIG_ENV_NAMES } from "./config.ts";
6
- import { describeModels, FALLBACK_DESCRIPTORS, PROVIDER_ID, STATIC_MODELS, toPiModels, API_ID } from "./model-catalog.ts";
6
+ import { apiIdFor, labelFor, maskEmail, providerIdFor } from "./accounts.ts";
7
+ import {
8
+ describeModels,
9
+ DEFAULT_IDS,
10
+ FALLBACK_DESCRIPTORS,
11
+ PROVIDER_ID,
12
+ STATIC_MODELS,
13
+ toPiModels,
14
+ API_ID,
15
+ type ProviderIds,
16
+ } from "./model-catalog.ts";
7
17
  import type { AgyRuntime } from "./runtime.ts";
8
18
  import { makeStreamAgy } from "./stream.ts";
9
19
 
@@ -21,7 +31,15 @@ async function providerEnvironment(ctx: AuthContext): Promise<ProviderEnv | unde
21
31
  }
22
32
 
23
33
  export function createAgyProvider(runtime: AgyRuntime) {
24
- let discoveredIds: Set<string> | undefined;
34
+ const account = runtime.account;
35
+ const ids: ProviderIds = account
36
+ ? { provider: providerIdFor(account), api: apiIdFor(account), nameSuffix: ` · ${labelFor(account)}` }
37
+ : DEFAULT_IDS;
38
+ const accountName = account ? `Antigravity · ${labelFor(account)}${account.email ? ` (${maskEmail(account.email)})` : ""}` : undefined;
39
+ // A provider registered again (alias rename, account edit) starts from what this account's process already reported,
40
+ // not from the static list: an account on a smaller plan must keep showing only its own models.
41
+ const known = account && runtime.pool.cachedDiscovery ? describeModels(runtime.pool.cachedDiscovery) : [];
42
+ let discoveredIds: Set<string> | undefined = known.length > 0 ? new Set(known.map((descriptor) => descriptor.id)) : undefined;
25
43
  const streamAgy = makeStreamAgy(runtime);
26
44
  const externalOAuthMarker = () => ({
27
45
  type: "oauth" as const,
@@ -30,9 +48,9 @@ export function createAgyProvider(runtime: AgyRuntime) {
30
48
  expires: Date.now() + 365 * 24 * 60 * 60 * 1_000,
31
49
  });
32
50
  return createProvider({
33
- id: PROVIDER_ID,
34
- name: "Antigravity (agy acp)",
35
- baseUrl: "process://agy-acp",
51
+ id: ids.provider,
52
+ name: accountName ?? "Antigravity (agy acp)",
53
+ baseUrl: `process://${ids.api}`,
36
54
  auth: {
37
55
  apiKey: {
38
56
  name: "Antigravity login (agy)",
@@ -60,7 +78,11 @@ export function createAgyProvider(runtime: AgyRuntime) {
60
78
  name: "Antigravity subscription (managed by agy)",
61
79
  isSubscription: true,
62
80
  async login() {
63
- throw new Error("Antigravity manages its own login. Run `agy` in a terminal and sign in; this provider uses it automatically.");
81
+ throw new Error(
82
+ account
83
+ ? `Antigravity manages its own login. Run /agy-bridge login ${account.id} (or /agy-bridge menu) to sign this account in.`
84
+ : "Antigravity manages its own login. Run `agy` in a terminal and sign in; this provider uses it automatically.",
85
+ );
64
86
  },
65
87
  async refresh() {
66
88
  await runtime.pool.discover(true);
@@ -71,12 +93,12 @@ export function createAgyProvider(runtime: AgyRuntime) {
71
93
  },
72
94
  },
73
95
  },
74
- models: STATIC_MODELS,
96
+ models: account ? toPiModels(known.length > 0 ? known : FALLBACK_DESCRIPTORS, runtime.observedWindows, ids) : STATIC_MODELS,
75
97
  async fetchModels() {
76
98
  runtime.trace("provider.fetchModels");
77
99
  const discovery = await runtime.pool.discover();
78
100
  const descriptors = describeModels(discovery);
79
- const models = toPiModels(descriptors.length > 0 ? descriptors : FALLBACK_DESCRIPTORS, runtime.observedWindows);
101
+ const models = toPiModels(descriptors.length > 0 ? descriptors : FALLBACK_DESCRIPTORS, runtime.observedWindows, ids);
80
102
  discoveredIds = new Set(models.map((model) => model.id));
81
103
  return models;
82
104
  },
package/src/runtime.ts CHANGED
@@ -1,7 +1,19 @@
1
1
  // The per-extension runtime: configuration, the shared session pool, agy compatibility state and facts learned
2
2
  // while running (observed context windows). One instance per extension load; tests build their own.
3
3
 
4
+ import { rm } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import {
7
+ accountPaths,
8
+ DEFAULT_ACCOUNT,
9
+ FILE_STORAGE_ENV,
10
+ maskEmail,
11
+ waitForIdentity,
12
+ type AccountRecord,
13
+ type Identity,
14
+ } from "./accounts.ts";
4
15
  import { findAgyCommand } from "./acp/command.ts";
16
+ import type { AcpProcess } from "./acp/connection.ts";
5
17
  import type { AcpInitializeResult } from "./acp/types.ts";
6
18
  import { AgyCompatError, assertUsable, deriveFeatures, type AgyFeatures, type FeatureReport } from "./compat/features.ts";
7
19
  import { getMatrix } from "./compat/matrix.ts";
@@ -16,6 +28,19 @@ export interface RuntimeOptions {
16
28
  /** Test seams for the pool (fake argv, custom validator). */
17
29
  pool?: Partial<Pick<PoolOptions, "buildArgs" | "validate" | "env">>;
18
30
  log?: (message: string) => void;
31
+ /** The Antigravity account this runtime serves. Absent = the default (keyring) account, exactly as before. */
32
+ account?: AccountRecord;
33
+ /** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
34
+ * (default 10 s; agy writes it during that call, so normally no wait at all). */
35
+ identityTimeoutMs?: number;
36
+ }
37
+
38
+ /** What an extra-account process proved about itself at its last start. */
39
+ export interface AccountIdentityState {
40
+ at: number;
41
+ identity: Identity;
42
+ ok: boolean;
43
+ message?: string;
19
44
  }
20
45
 
21
46
  /** How long a recorded "logged out" or "too old" finding hides the models without re-checking. */
@@ -49,14 +74,58 @@ export class AgyRuntime {
49
74
  /** Disposals of pools replaced by applyEnv; dispose() waits for them so no old agy process outlives pi. */
50
75
  readonly #retiring = new Set<Promise<void>>();
51
76
  #writes = new Set<Promise<void>>();
77
+ #account: AccountRecord | undefined;
78
+ #identity: AccountIdentityState | undefined;
52
79
 
53
80
  constructor(options: RuntimeOptions = {}) {
54
81
  this.#options = options;
82
+ this.#account = options.account && options.account.id !== DEFAULT_ACCOUNT ? { ...options.account } : undefined;
55
83
  this.config = loadConfig(options.env ?? process.env);
56
- this.trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
84
+ const trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
85
+ this.trace = this.#account ? (message) => trace(`[${this.accountLabel}] ${message}`) : trace;
57
86
  this.#pool = this.#createPool();
58
87
  }
59
88
 
89
+ /** The extra account this runtime serves, or undefined for the default (keyring) account. */
90
+ get account(): AccountRecord | undefined {
91
+ return this.#account;
92
+ }
93
+
94
+ get accountLabel(): string {
95
+ return this.#account ? (this.#account.alias ?? this.#account.id) : "default";
96
+ }
97
+
98
+ /** What the last start of an extra-account process proved (email, storage); undefined before the first start. */
99
+ get identity(): AccountIdentityState | undefined {
100
+ return this.#identity;
101
+ }
102
+
103
+ /** Directory for this account's state hint (state.json): the shared home for the default account. */
104
+ get stateDir(): string {
105
+ return this.#account ? accountPaths(this.config.home, this.#account.id).root : this.config.home;
106
+ }
107
+
108
+ /** Change alias/email/enabled of the bound account. A changed email stops the process so the next use re-checks. */
109
+ updateAccount(next: AccountRecord): void {
110
+ if (!this.#account || next.id !== this.#account.id) return;
111
+ const emailChanged = next.email !== this.#account.email;
112
+ this.#account = { ...next };
113
+ if (emailChanged) {
114
+ this.#identity = undefined;
115
+ void this.#pool.reset().catch((error: unknown) => this.trace(`reset after account change failed: ${describeError(error)}`));
116
+ this.#pool.resetDiscovery();
117
+ }
118
+ }
119
+
120
+ /** Forget a recorded "unusable" hint (after a successful sign-in) so the provider is offered again at once. */
121
+ async clearUnusable(): Promise<void> {
122
+ this.#hintRecorded = false;
123
+ const state = await readState(this.stateDir);
124
+ if (!state.unusable) return;
125
+ const { unusable: _dropped, ...rest } = state;
126
+ await writeState(this.stateDir, rest);
127
+ }
128
+
60
129
  get pool(): SessionPool {
61
130
  return this.#pool;
62
131
  }
@@ -82,10 +151,23 @@ export class AgyRuntime {
82
151
  }
83
152
 
84
153
  #createPool(): SessionPool {
154
+ const account = this.#account;
155
+ const paths = account ? accountPaths(this.config.home, account.id) : undefined;
156
+ const baseEnv = this.#options.pool?.env;
85
157
  const pool = new SessionPool({
86
158
  config: this.config,
87
159
  buildArgs: this.#options.pool?.buildArgs,
88
- env: this.#options.pool?.env,
160
+ env: account ? { ...(baseEnv ?? process.env), ...FILE_STORAGE_ENV } : baseEnv,
161
+ ...(paths
162
+ ? {
163
+ stagingOverride: { geminiDir: paths.geminiDir, workDir: path.join(paths.root, "work") },
164
+ extraArgs: (staging) =>
165
+ // The real argv already names the gemini dir through the staging override; a test argv may not.
166
+ this.#options.pool?.buildArgs ? ["--gemini-dir", staging.geminiDir, "--log-file", paths.logFile] : ["--log-file", paths.logFile],
167
+ beforeStart: () => rm(paths.logFile, { force: true }),
168
+ verifyProcess: (proc, sessionFailure) => this.#checkIdentity(paths.logFile, proc, sessionFailure),
169
+ }
170
+ : {}),
89
171
  log: this.trace,
90
172
  onHealth: (event) => this.#onHealth(event),
91
173
  features: () => this.features,
@@ -110,6 +192,51 @@ export class AgyRuntime {
110
192
  return pool;
111
193
  }
112
194
 
195
+ /** Error text as pi sees it: default account unchanged; an extra account's message names the account so a fallback
196
+ * notice says which one failed. An account id is always prefixed by "account ", so it cannot form a bare
197
+ * three-digit number that the classifier would read as an HTTP status; agy's own text is left untouched. */
198
+ decorateError(message: string): string {
199
+ if (!this.#account) return message;
200
+ const id = this.#account.id;
201
+ return message.includes(`account ${id}`) ? message : `${message} (account ${id})`;
202
+ }
203
+
204
+ /** Identity guard for an extra account: agy must use the account's own token file and be signed in as the expected
205
+ * email. Anything else (keyring fallback, signed out, another account) stops the process before it serves a turn. */
206
+ async #checkIdentity(logFile: string, proc: AcpProcess, sessionFailure: unknown): Promise<void> {
207
+ const account = this.#account;
208
+ if (!account) return;
209
+ // Stop waiting as soon as the process is gone: it will never write the line.
210
+ const gone = new AbortController();
211
+ void proc.exited.then(() => gone.abort());
212
+ const identity = await waitForIdentity(logFile, this.#options.identityTimeoutMs ?? 10_000, gone.signal);
213
+ // session/new failed before agy resolved any login (we stopped the process, it crashed, the call timed out): that
214
+ // is not evidence about the account. Report the original failure instead of a guard verdict, so no 5-minute
215
+ // "unusable" hint is recorded for an ordinary reset.
216
+ const resolved = identity.fileStorage || identity.email !== undefined || identity.signedOut;
217
+ if (sessionFailure !== undefined && !resolved) throw sessionFailure;
218
+ const fail = (kind: "auth" | "compat", message: string): never => {
219
+ this.#identity = { at: Date.now(), identity, ok: false, message };
220
+ this.trace(`identity: FAILED ${message}`);
221
+ throw new AgyError(kind, message);
222
+ };
223
+ const login = `run /agy-bridge login ${account.id}`;
224
+ if (!identity.fileStorage) {
225
+ fail("compat", `pi-agy-bridge is unavailable: agy did not switch to per-account token storage for account ${account.id}, so it would use the default login (see UPGRADING.md)`);
226
+ }
227
+ if (!identity.email) {
228
+ fail("auth", `agy authentication required (not logged in) for account ${account.id}; ${login}`);
229
+ }
230
+ if (account.email && identity.email?.toLowerCase() !== account.email.toLowerCase()) {
231
+ fail(
232
+ "auth",
233
+ `agy authentication required (not logged in) for account ${account.id}: agy is signed in as ${maskEmail(identity.email)}, expected ${maskEmail(account.email)}; ${login}`,
234
+ );
235
+ }
236
+ this.#identity = { at: Date.now(), identity, ok: true };
237
+ this.trace(`identity: ok ${maskEmail(identity.email)} (file storage)`);
238
+ }
239
+
113
240
  /** Cheap, process-free answer to "should agy models be offered?": the executable exists and the last real use did
114
241
  * not find agy logged out or too old (within UNUSABLE_HINT_MS). pi waits for this during startup, so it must not
115
242
  * start agy; the handshake happens on first real use and records the outcome. */
@@ -118,7 +245,7 @@ export class AgyRuntime {
118
245
  if (!found) {
119
246
  return { available: false, reason: `agy was not found (command "${this.config.command}"); install the Antigravity CLI or set PI_AGY_COMMAND` };
120
247
  }
121
- const state = await readState(this.config.home);
248
+ const state = await readState(this.stateDir);
122
249
  const bad = state.unusable;
123
250
  if (bad && Date.now() - bad.at < UNUSABLE_HINT_MS) {
124
251
  this.#hintRecorded = true;
@@ -163,11 +290,11 @@ export class AgyRuntime {
163
290
  if (!event.ok) {
164
291
  this.#hintRecorded = true;
165
292
  const unusable = { at: Date.now(), kind: event.kind, message: event.message };
166
- update = readState(this.config.home).then((state: BridgeState) => writeState(this.config.home, { ...state, unusable }));
293
+ update = readState(this.stateDir).then((state: BridgeState) => writeState(this.stateDir, { ...state, unusable }));
167
294
  } else if (this.#hintRecorded) {
168
295
  this.#hintRecorded = false;
169
- update = readState(this.config.home).then((state: BridgeState) =>
170
- writeState(this.config.home, {
296
+ update = readState(this.stateDir).then((state: BridgeState) =>
297
+ writeState(this.stateDir, {
171
298
  lastOkAt: Date.now(),
172
299
  agyVersion: event.version ?? state.agyVersion,
173
300
  ...(state.appendRefused ? { appendRefused: state.appendRefused } : {}),