@timmyjl12/pi-agy-bridge 0.1.4 → 0.2.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timmyjl12/pi-agy-bridge",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
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",
@@ -35,11 +35,13 @@
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@earendil-works/pi-ai": "*",
38
- "@earendil-works/pi-coding-agent": "*"
38
+ "@earendil-works/pi-coding-agent": "*",
39
+ "@earendil-works/pi-tui": "*"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@earendil-works/pi-ai": "^1.5.2",
42
43
  "@earendil-works/pi-coding-agent": "^1.5.2",
44
+ "@earendil-works/pi-tui": "^1.5.2",
43
45
  "@types/node": "^22.19.0",
44
46
  "typescript": "^5.9.3"
45
47
  },
@@ -0,0 +1,397 @@
1
+ // Owns one AgyRuntime per Antigravity account and keeps pi's provider list in step with the account registry.
2
+ //
3
+ // The default account (provider `agy`) always exists and behaves exactly as before this feature. Each enabled extra
4
+ // account gets its own runtime, `agy acp` process and pi provider `agy-<alias ?? id>`. Adding, renaming, enabling,
5
+ // disabling or removing an account registers/unregisters its provider immediately (pi applies these without /reload).
6
+
7
+ import { resolveAgyCommand } from "./acp/command.ts";
8
+ import {
9
+ accountPaths,
10
+ DEFAULT_ACCOUNT,
11
+ hasSavedLogin,
12
+ labelFor,
13
+ maskEmail,
14
+ mergeEnvAccounts,
15
+ nameConflict,
16
+ providerIdFor,
17
+ readRegistry,
18
+ removeAccountFolder,
19
+ startLogin,
20
+ writeRegistry,
21
+ type AccountRecord,
22
+ type LoginHandle,
23
+ type LoginProgress,
24
+ type LoginResult,
25
+ } from "./accounts.ts";
26
+ import { describeError } from "./errors.ts";
27
+ import { describeModels } from "./model-catalog.ts";
28
+ import { createAgyProvider } from "./provider.ts";
29
+ import { AgyRuntime, type RuntimeOptions } from "./runtime.ts";
30
+
31
+ type Provider = ReturnType<typeof createAgyProvider>;
32
+
33
+ /** `session/new` reports the subscription as `_meta.antigravity.tier.name` ("Google AI Pro"); absent on older agy. */
34
+ function tierName(meta: Record<string, unknown> | undefined): string | undefined {
35
+ const antigravity = meta?.antigravity;
36
+ if (!antigravity || typeof antigravity !== "object") return undefined;
37
+ const tier = (antigravity as Record<string, unknown>).tier;
38
+ if (!tier || typeof tier !== "object") return undefined;
39
+ const name = (tier as Record<string, unknown>).name;
40
+ return typeof name === "string" ? name : undefined;
41
+ }
42
+
43
+ /** The slice of pi's ExtensionAPI the manager needs (tests pass a recorder). */
44
+ export interface ProviderHost {
45
+ registerProvider(provider: Provider): void;
46
+ unregisterProvider(name: string): void;
47
+ }
48
+
49
+ export interface AccountView {
50
+ account: AccountRecord;
51
+ provider: string;
52
+ label: string;
53
+ isDefault: boolean;
54
+ registered: boolean;
55
+ /** A saved login exists in the account folder (extra accounts) — the token itself is never read. */
56
+ savedLogin: boolean;
57
+ running: boolean;
58
+ pid?: number;
59
+ sessions: { idle: number; busy: number };
60
+ /** Models from the last discovery of this account's own process, if any. */
61
+ models?: string[];
62
+ tier?: string;
63
+ /** Result of the identity guard at the last start (extra accounts). */
64
+ identity?: { ok: boolean; email?: string; message?: string; at: number };
65
+ agyVersion?: string;
66
+ }
67
+
68
+ export interface ManagerOptions {
69
+ host: ProviderHost;
70
+ /** Base runtime options (env, test seams); each account gets a copy with its `account`. */
71
+ runtime?: Omit<RuntimeOptions, "account">;
72
+ /** Pass a pre-built default runtime (keeps the existing extension entry and tests intact). */
73
+ defaultRuntime?: AgyRuntime;
74
+ /** Test seam: arguments placed before `acp --login` (a fake agy script run by node). */
75
+ loginPrefixArgs?: readonly string[];
76
+ }
77
+
78
+ export class AccountManager {
79
+ readonly default: AgyRuntime;
80
+ readonly #host: ProviderHost;
81
+ readonly #options: ManagerOptions;
82
+ /** Extra-account runtimes by account id. */
83
+ readonly #runtimes = new Map<string, AgyRuntime>();
84
+ /** Provider id currently registered for each account id. */
85
+ readonly #registered = new Map<string, string>();
86
+ #accounts: AccountRecord[] = [];
87
+ #warnings: string[] = [];
88
+ #loaded: Promise<void> | undefined;
89
+ /** A load was requested while one was running: run one more pass after it, so a write that raced an in-flight
90
+ * read is always picked up. */
91
+ #reloadAgain = false;
92
+ #logins = new Map<string, LoginHandle>();
93
+ onNotice: ((message: string, level: "info" | "warning" | "error") => void) | undefined;
94
+
95
+ constructor(options: ManagerOptions) {
96
+ this.#options = options;
97
+ this.#host = options.host;
98
+ this.default = options.defaultRuntime ?? new AgyRuntime(options.runtime);
99
+ }
100
+
101
+ get home(): string {
102
+ return this.default.config.home;
103
+ }
104
+
105
+ get warnings(): readonly string[] {
106
+ return this.#warnings;
107
+ }
108
+
109
+ /** Register the default provider synchronously (pi queues it during load); extra accounts follow from disk. */
110
+ registerDefault(): void {
111
+ this.#host.registerProvider(createAgyProvider(this.default));
112
+ this.#registered.set(DEFAULT_ACCOUNT, "agy");
113
+ }
114
+
115
+ /** Read the registry and register every enabled extra account. Idempotent; safe to call again after edits. */
116
+ load(): Promise<void> {
117
+ if (this.#loaded) {
118
+ this.#reloadAgain = true;
119
+ return this.#loaded;
120
+ }
121
+ const run = async (): Promise<void> => {
122
+ do {
123
+ this.#reloadAgain = false;
124
+ await this.#reload();
125
+ } while (this.#reloadAgain);
126
+ };
127
+ this.#loaded = run().finally(() => {
128
+ this.#loaded = undefined;
129
+ });
130
+ return this.#loaded;
131
+ }
132
+
133
+ async #reload(): Promise<void> {
134
+ const registry = await readRegistry(this.home);
135
+ const { accounts, warnings } = mergeEnvAccounts(registry, this.#options.runtime?.env ?? process.env);
136
+ this.#accounts = accounts;
137
+ this.#warnings = warnings;
138
+ for (const warning of warnings) this.default.trace(`accounts: ${warning}`);
139
+ const wanted = new Set(accounts.filter((account) => account.enabled).map((account) => account.id));
140
+ for (const id of [...this.#runtimes.keys()]) if (!wanted.has(id)) await this.#drop(id);
141
+ for (const account of accounts) if (account.enabled) this.#ensure(account);
142
+ }
143
+
144
+ #ensure(account: AccountRecord): void {
145
+ let runtime = this.#runtimes.get(account.id);
146
+ const provider = providerIdFor(account);
147
+ if (!runtime) {
148
+ runtime = new AgyRuntime({ ...this.#options.runtime, account });
149
+ runtime.onNotice = (message, level) => this.onNotice?.(message, level);
150
+ this.#runtimes.set(account.id, runtime);
151
+ } else {
152
+ runtime.updateAccount(account);
153
+ }
154
+ // pi replaces a provider registered again under the same id (display name, email). A renamed provider (alias
155
+ // change) is unregistered under its old id first so its models disappear from /model.
156
+ const current = this.#registered.get(account.id);
157
+ if (current && current !== provider) this.#host.unregisterProvider(current);
158
+ this.#host.registerProvider(createAgyProvider(runtime));
159
+ this.#registered.set(account.id, provider);
160
+ }
161
+
162
+ async #drop(id: string): Promise<void> {
163
+ const provider = this.#registered.get(id);
164
+ if (provider) this.#host.unregisterProvider(provider);
165
+ this.#registered.delete(id);
166
+ const runtime = this.#runtimes.get(id);
167
+ this.#runtimes.delete(id);
168
+ if (runtime) await runtime.dispose();
169
+ }
170
+
171
+ runtimeFor(id: string): AgyRuntime | undefined {
172
+ return id === DEFAULT_ACCOUNT ? this.default : this.#runtimes.get(id);
173
+ }
174
+
175
+ /** Resolve a user-typed name (id, alias or provider id) to an account id. */
176
+ resolve(name: string | undefined): string | undefined {
177
+ const value = (name ?? "").trim().toLowerCase();
178
+ if (!value || value === DEFAULT_ACCOUNT || value === "agy") return value ? DEFAULT_ACCOUNT : undefined;
179
+ const stripped = value.startsWith("agy-") ? value.slice(4) : value;
180
+ return this.#accounts.find((account) => account.id === stripped || account.alias === stripped || account.id === value)?.id;
181
+ }
182
+
183
+ get accounts(): readonly AccountRecord[] {
184
+ return this.#accounts;
185
+ }
186
+
187
+ /** Every account, default first, with what is known without starting a process. */
188
+ async views(): Promise<AccountView[]> {
189
+ const defaultAccount: AccountRecord = { id: DEFAULT_ACCOUNT, enabled: true, createdAt: 0 };
190
+ const all = [defaultAccount, ...this.#accounts];
191
+ return Promise.all(
192
+ all.map(async (account): Promise<AccountView> => {
193
+ const isDefault = account.id === DEFAULT_ACCOUNT;
194
+ const runtime = this.runtimeFor(account.id);
195
+ const status = runtime?.pool.status();
196
+ const discovery = runtime?.pool.cachedDiscovery;
197
+ const models = discovery ? describeModels(discovery).map((descriptor) => descriptor.id) : undefined;
198
+ const identity = runtime?.identity;
199
+ return {
200
+ account,
201
+ provider: providerIdFor(account),
202
+ label: labelFor(account),
203
+ isDefault,
204
+ registered: this.#registered.has(account.id),
205
+ savedLogin: isDefault ? true : await hasSavedLogin(this.home, account.id),
206
+ running: status?.alive === true,
207
+ ...(status?.pid !== undefined && status.alive ? { pid: status.pid } : {}),
208
+ sessions: { idle: status?.idle ?? 0, busy: status?.busy ?? 0 },
209
+ ...(models ? { models } : {}),
210
+ ...(tierName(discovery?.meta) ? { tier: tierName(discovery?.meta) } : {}),
211
+ ...(identity
212
+ ? { identity: { ok: identity.ok, email: identity.identity.email, message: identity.message, at: identity.at } }
213
+ : {}),
214
+ ...(runtime?.report?.agyVersion ? { agyVersion: runtime.report.agyVersion } : {}),
215
+ };
216
+ }),
217
+ );
218
+ }
219
+
220
+ // ---- mutations (shared by commands and the menu) -------------------------------------------------------------
221
+
222
+ async #save(next: AccountRecord[]): Promise<void> {
223
+ await writeRegistry(this.home, next);
224
+ await this.load();
225
+ }
226
+
227
+ #find(id: string): AccountRecord {
228
+ const account = this.#accounts.find((entry) => entry.id === id);
229
+ if (!account) throw new Error(`no account "${id}"`);
230
+ return account;
231
+ }
232
+
233
+ /** Create a new (not yet signed in) account. Returns its id. */
234
+ async add(id: string, alias?: string): Promise<AccountRecord> {
235
+ await this.load();
236
+ const clean = id.trim().toLowerCase();
237
+ const problem = nameConflict(this.#accounts, clean, "id");
238
+ if (problem) throw new Error(problem);
239
+ if (alias) {
240
+ const aliasProblem = nameConflict(this.#accounts, alias, "alias");
241
+ if (aliasProblem) throw new Error(aliasProblem);
242
+ if (alias === clean) alias = undefined;
243
+ }
244
+ const account: AccountRecord = { id: clean, ...(alias ? { alias } : {}), enabled: true, createdAt: Date.now() };
245
+ await this.#save([...this.#accounts, account]);
246
+ return account;
247
+ }
248
+
249
+ /** Set (or clear with an empty value) an account's alias; the provider is renamed to `agy-<alias>`. */
250
+ async setAlias(id: string, alias: string | undefined): Promise<AccountRecord> {
251
+ await this.load();
252
+ const account = this.#find(id);
253
+ const value = alias?.trim().toLowerCase() || undefined;
254
+ if (value && value !== account.id) {
255
+ const problem = nameConflict(this.#accounts, value, "alias", account.id);
256
+ if (problem) throw new Error(problem);
257
+ }
258
+ const next = { ...account };
259
+ if (value && value !== account.id) next.alias = value;
260
+ else delete next.alias;
261
+ await this.#save(this.#accounts.map((entry) => (entry.id === id ? next : entry)));
262
+ return next;
263
+ }
264
+
265
+ async setEnabled(id: string, enabled: boolean): Promise<void> {
266
+ await this.load();
267
+ const account = this.#find(id);
268
+ if (account.fromEnv && !enabled) throw new Error(`account "${id}" comes from PI_AGY_ACCOUNTS; remove it there to disable it`);
269
+ await this.#save(this.#accounts.map((entry) => (entry.id === id ? { ...entry, enabled } : entry)));
270
+ }
271
+
272
+ /** Forget the account; with `deleteLogin` also delete its folder (saved login, agy data). */
273
+ async remove(id: string, deleteLogin: boolean): Promise<void> {
274
+ await this.load();
275
+ const account = this.#find(id);
276
+ if (account.fromEnv) throw new Error(`account "${id}" comes from PI_AGY_ACCOUNTS; remove it there`);
277
+ const login = this.#logins.get(id);
278
+ if (login) {
279
+ login.cancel();
280
+ await login.result.catch(() => undefined); // the agy login process must be gone before its folder is deleted
281
+ }
282
+ await this.#save(this.#accounts.filter((entry) => entry.id !== id));
283
+ if (deleteLogin) await removeAccountFolder(this.home, id);
284
+ }
285
+
286
+ /** Set the expected email by hand (normally recorded by sign-in). Empty clears it. */
287
+ async setEmail(id: string, email: string | undefined): Promise<void> {
288
+ await this.load();
289
+ const account = this.#find(id);
290
+ const value = email?.trim() || undefined;
291
+ if (value && !/^[^@\s]+@[^@\s]+$/.test(value)) throw new Error(`"${value}" is not an email address`);
292
+ const next = { ...account };
293
+ if (value) next.email = value;
294
+ else delete next.email;
295
+ await this.#save(this.#accounts.map((entry) => (entry.id === id ? next : entry)));
296
+ // A corrected expectation must not stay hidden behind the hint the old mismatch recorded.
297
+ if (value !== account.email) await this.#runtimes.get(id)?.clearUnusable();
298
+ }
299
+
300
+ loginRunning(id: string): boolean {
301
+ return this.#logins.has(id);
302
+ }
303
+
304
+ /** Sign an extra account in through `agy acp --login` (browser). On success the email is recorded as the
305
+ * account's expected identity and its provider is refreshed. */
306
+ async login(id: string, onProgress?: (progress: LoginProgress) => void): Promise<LoginResult> {
307
+ await this.load();
308
+ if (id === DEFAULT_ACCOUNT) {
309
+ return { ok: false, message: "the default account uses agy's own login: run `agy` in a terminal and sign in there" };
310
+ }
311
+ const account = this.#find(id);
312
+ if (this.#logins.has(id)) return { ok: false, message: `a sign-in for "${id}" is already running` };
313
+ const command = await resolveAgyCommand(this.default.config.command, this.#options.runtime?.env ?? process.env);
314
+ // The process of this account must not run with the old login while the folder changes.
315
+ await this.#runtimes.get(id)?.pool.reset();
316
+ const handle = startLogin({
317
+ command,
318
+ home: this.home,
319
+ id,
320
+ env: this.#options.runtime?.pool?.env ?? process.env,
321
+ onProgress,
322
+ ...(this.#options.loginPrefixArgs ? { prefixArgs: this.#options.loginPrefixArgs } : {}),
323
+ });
324
+ this.#logins.set(id, handle);
325
+ try {
326
+ const result = await handle.result;
327
+ if (!result.ok || !result.email) return result;
328
+ const previous = account.email;
329
+ await this.#save(this.#accounts.map((entry) => (entry.id === id ? { ...entry, email: result.email } : entry)));
330
+ const runtime = this.#runtimes.get(id);
331
+ await runtime?.clearUnusable();
332
+ runtime?.pool.resetDiscovery();
333
+ const changed = previous && previous.toLowerCase() !== result.email.toLowerCase();
334
+ return {
335
+ ...result,
336
+ message: changed ? `${result.message} (was ${maskEmail(previous)}; expected account updated)` : result.message,
337
+ };
338
+ } finally {
339
+ this.#logins.delete(id);
340
+ }
341
+ }
342
+
343
+ cancelLogin(id: string): void {
344
+ this.#logins.get(id)?.cancel();
345
+ }
346
+
347
+ /** Stop an account's process and forget its pooled sessions (next use starts fresh). */
348
+ async reset(id: string): Promise<void> {
349
+ const runtime = this.runtimeFor(id);
350
+ if (!runtime) throw new Error(`account "${id}" is not active`);
351
+ await runtime.pool.reset();
352
+ runtime.pool.resetDiscovery();
353
+ }
354
+
355
+ async resetAll(): Promise<void> {
356
+ await Promise.allSettled([this.default, ...this.#runtimes.values()].map(async (runtime) => {
357
+ await runtime.pool.reset();
358
+ runtime.pool.resetDiscovery();
359
+ }));
360
+ }
361
+
362
+ /** Start the account's process and list its models (one handshake, no prompt, no quota). */
363
+ async check(id: string): Promise<{ ok: boolean; message: string }> {
364
+ const runtime = this.runtimeFor(id);
365
+ if (!runtime) return { ok: false, message: `account "${id}" is not active (disabled?)` };
366
+ try {
367
+ const discovery = await runtime.pool.discover(true);
368
+ const count = describeModels(discovery).length;
369
+ const email = runtime.identity?.identity.email;
370
+ return { ok: true, message: `${labelFor(runtime.account ?? { id: DEFAULT_ACCOUNT })}: ok${email ? ` as ${maskEmail(email)}` : ""}, ${count} models` };
371
+ } catch (error) {
372
+ return { ok: false, message: describeError(error) };
373
+ }
374
+ }
375
+
376
+ folderOf(id: string): string {
377
+ return id === DEFAULT_ACCOUNT ? this.home : accountPaths(this.home, id).root;
378
+ }
379
+
380
+ allRuntimes(): AgyRuntime[] {
381
+ return [this.default, ...this.#runtimes.values()];
382
+ }
383
+
384
+ set notice(fn: ((message: string, level: "info" | "warning") => void) | undefined) {
385
+ for (const runtime of this.allRuntimes()) runtime.onNotice = fn;
386
+ }
387
+
388
+ async recycle(): Promise<void> {
389
+ for (const handle of this.#logins.values()) handle.cancel();
390
+ await Promise.allSettled(this.allRuntimes().map((runtime) => runtime.recycle()));
391
+ }
392
+
393
+ async dispose(): Promise<void> {
394
+ for (const handle of this.#logins.values()) handle.cancel();
395
+ await Promise.allSettled(this.allRuntimes().map((runtime) => runtime.dispose()));
396
+ }
397
+ }