@timmyjl12/pi-agy-bridge 0.1.5 → 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/ARCHITECTURE.md +11 -1
- package/README.md +51 -7
- package/UPGRADING.md +12 -0
- package/compat/baselines/agy-1.5.14.json +260 -0
- package/compat/matrix.json +1 -1
- package/compat/probe.ts +71 -2
- package/package.json +4 -2
- package/src/account-manager.ts +397 -0
- package/src/accounts.ts +349 -0
- package/src/acp/connection.ts +1 -1
- package/src/config.ts +6 -0
- package/src/doctor.ts +13 -3
- package/src/index.ts +199 -25
- package/src/model-catalog.ts +19 -6
- package/src/provider.ts +30 -8
- package/src/runtime.ts +133 -6
- package/src/session-pool.ts +88 -6
- package/src/stream.ts +41 -8
- package/src/ui/menu.ts +440 -0
- package/src/ui/panel.ts +376 -0
package/src/accounts.ts
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
// Antigravity accounts: a persisted registry (<home>/accounts.json) plus the paths, identity guard and login runner
|
|
2
|
+
// for each extra account.
|
|
3
|
+
//
|
|
4
|
+
// agy keeps ONE login per OS user in the keyring (Windows: Credential Manager entry `gemini:antigravity`). It switches
|
|
5
|
+
// to a per-folder token file (`<gemini-dir>/antigravity-cli/antigravity-oauth-token`) when it believes it runs in an
|
|
6
|
+
// SSH session, so an extra account is an agy process with its own `--gemini-dir` and the `SSH_CONNECTION` marker.
|
|
7
|
+
// Measured on agy 1.5.12 (.plan/agy-multi-account/evidence). The default account keeps the keyring, exactly as before.
|
|
8
|
+
//
|
|
9
|
+
// The bridge never reads a token. It reads only agy's own log line ("authenticated successfully as <email>") to tell
|
|
10
|
+
// which account a process serves, and refuses to use an extra-account process that is not the expected account.
|
|
11
|
+
|
|
12
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
13
|
+
import { mkdir, readFile, rm, stat } from "node:fs/promises";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { writeFileAtomic } from "./atomic-write.ts";
|
|
16
|
+
|
|
17
|
+
/** Folder name / registry key. Kept short and filesystem-safe. */
|
|
18
|
+
export const ACCOUNT_ID = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
|
|
19
|
+
export const DEFAULT_ACCOUNT = "default";
|
|
20
|
+
/** Provider id of the default (keyring) account; extra accounts are `agy-<alias ?? id>`. */
|
|
21
|
+
export const DEFAULT_PROVIDER = "agy";
|
|
22
|
+
/** The value is only a marker: agy checks that the variable exists. */
|
|
23
|
+
export const FILE_STORAGE_ENV = { SSH_CONNECTION: "pi-agy-bridge 0 pi-agy-bridge 0" } as const;
|
|
24
|
+
|
|
25
|
+
export interface AccountRecord {
|
|
26
|
+
id: string;
|
|
27
|
+
alias?: string;
|
|
28
|
+
/** The Google account this profile must serve; recorded at sign-in (or set by PI_AGY_ACCOUNT_<ID>_EMAIL). */
|
|
29
|
+
email?: string;
|
|
30
|
+
enabled: boolean;
|
|
31
|
+
createdAt: number;
|
|
32
|
+
/** Defined by PI_AGY_ACCOUNTS rather than the registry file (cannot be removed from the menu). */
|
|
33
|
+
fromEnv?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface RegistryFile {
|
|
37
|
+
version: 1;
|
|
38
|
+
accounts: AccountRecord[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const FILE = "accounts.json";
|
|
42
|
+
|
|
43
|
+
export function validateAccountName(value: string, kind: "id" | "alias"): string | undefined {
|
|
44
|
+
if (!ACCOUNT_ID.test(value)) return `${kind} must be 1-32 characters of a-z, 0-9 and '-', starting and ending with a letter or digit`;
|
|
45
|
+
// A purely numeric name ("429") would surface in error text as a bare number the fallback classifier reads as a status.
|
|
46
|
+
if (!/[a-z]/.test(value)) return `${kind} must contain at least one letter`;
|
|
47
|
+
if (value === DEFAULT_ACCOUNT || value === "agy") return `"${value}" is reserved`;
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `agy` for the default account, `agy-<alias ?? id>` otherwise. */
|
|
52
|
+
export function providerIdFor(account: Pick<AccountRecord, "id" | "alias">): string {
|
|
53
|
+
return account.id === DEFAULT_ACCOUNT ? DEFAULT_PROVIDER : `agy-${account.alias ?? account.id}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** pi-ai's compat stream registry is keyed by api id, so every account gets its own. */
|
|
57
|
+
export function apiIdFor(account: Pick<AccountRecord, "id" | "alias">): string {
|
|
58
|
+
return account.id === DEFAULT_ACCOUNT ? "agy-acp" : `agy-acp-${account.alias ?? account.id}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function labelFor(account: Pick<AccountRecord, "id" | "alias">): string {
|
|
62
|
+
return account.id === DEFAULT_ACCOUNT ? "default" : (account.alias ?? account.id);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** `timm…2385@gmail.com`: enough to tell accounts apart in a status line, not a full address. */
|
|
66
|
+
export function maskEmail(email: string | undefined): string {
|
|
67
|
+
if (!email) return "unknown";
|
|
68
|
+
const at = email.indexOf("@");
|
|
69
|
+
if (at <= 0) return "…";
|
|
70
|
+
const local = email.slice(0, at);
|
|
71
|
+
const shown = local.length <= 4 ? local.slice(0, 1) : `${local.slice(0, 4)}…${local.length > 8 ? local.slice(-4) : ""}`;
|
|
72
|
+
return `${shown}@${email.slice(at + 1)}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface AccountPaths {
|
|
76
|
+
root: string;
|
|
77
|
+
geminiDir: string;
|
|
78
|
+
logFile: string;
|
|
79
|
+
loginLog: string;
|
|
80
|
+
tokenFile: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function accountPaths(home: string, id: string): AccountPaths {
|
|
84
|
+
const root = path.join(home, "accounts", id);
|
|
85
|
+
const geminiDir = path.join(root, "gemini");
|
|
86
|
+
return {
|
|
87
|
+
root,
|
|
88
|
+
geminiDir,
|
|
89
|
+
logFile: path.join(root, "acp.log"),
|
|
90
|
+
loginLog: path.join(root, "login.log"),
|
|
91
|
+
tokenFile: path.join(geminiDir, "antigravity-cli", "antigravity-oauth-token"),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Is a saved login present for this extra account (existence only; the file is never read)? */
|
|
96
|
+
export async function hasSavedLogin(home: string, id: string): Promise<boolean> {
|
|
97
|
+
try {
|
|
98
|
+
return (await stat(accountPaths(home, id).tokenFile)).isFile();
|
|
99
|
+
} catch {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---- registry ----------------------------------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
export async function readRegistry(home: string): Promise<AccountRecord[]> {
|
|
107
|
+
let text: string;
|
|
108
|
+
try {
|
|
109
|
+
text = await readFile(path.join(home, FILE), "utf8");
|
|
110
|
+
} catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
const parsed = JSON.parse(text) as Partial<RegistryFile>;
|
|
115
|
+
if (!Array.isArray(parsed.accounts)) return [];
|
|
116
|
+
const seen = new Set<string>();
|
|
117
|
+
const out: AccountRecord[] = [];
|
|
118
|
+
for (const raw of parsed.accounts) {
|
|
119
|
+
if (!raw || typeof raw !== "object" || typeof raw.id !== "string" || validateAccountName(raw.id, "id")) continue;
|
|
120
|
+
if (seen.has(raw.id)) continue;
|
|
121
|
+
seen.add(raw.id);
|
|
122
|
+
const alias = typeof raw.alias === "string" && !validateAccountName(raw.alias, "alias") ? raw.alias : undefined;
|
|
123
|
+
out.push({
|
|
124
|
+
id: raw.id,
|
|
125
|
+
...(alias ? { alias } : {}),
|
|
126
|
+
...(typeof raw.email === "string" && raw.email.includes("@") ? { email: raw.email } : {}),
|
|
127
|
+
enabled: raw.enabled !== false,
|
|
128
|
+
createdAt: typeof raw.createdAt === "number" ? raw.createdAt : 0,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
} catch {
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function writeRegistry(home: string, accounts: readonly AccountRecord[]): Promise<void> {
|
|
138
|
+
await mkdir(home, { recursive: true });
|
|
139
|
+
const file: RegistryFile = {
|
|
140
|
+
version: 1,
|
|
141
|
+
accounts: accounts
|
|
142
|
+
.filter((account) => !account.fromEnv && account.id !== DEFAULT_ACCOUNT)
|
|
143
|
+
.map(({ id, alias, email, enabled, createdAt }) => ({ id, ...(alias ? { alias } : {}), ...(email ? { email } : {}), enabled, createdAt })),
|
|
144
|
+
};
|
|
145
|
+
await writeFileAtomic(path.join(home, FILE), `${JSON.stringify(file, null, 2)}\n`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Registry accounts plus PI_AGY_ACCOUNTS (comma list) and PI_AGY_ACCOUNT_<ID>_EMAIL overrides. Invalid env ids are
|
|
149
|
+
* reported, not thrown. */
|
|
150
|
+
export function mergeEnvAccounts(
|
|
151
|
+
registry: readonly AccountRecord[],
|
|
152
|
+
env: Record<string, string | undefined>,
|
|
153
|
+
): { accounts: AccountRecord[]; warnings: string[] } {
|
|
154
|
+
const warnings: string[] = [];
|
|
155
|
+
const accounts = registry.map((account) => ({ ...account }));
|
|
156
|
+
const listed = new Set<string>();
|
|
157
|
+
for (const raw of (env.PI_AGY_ACCOUNTS ?? "").split(",")) {
|
|
158
|
+
const id = raw.trim().toLowerCase();
|
|
159
|
+
if (!id) continue;
|
|
160
|
+
if (listed.has(id)) {
|
|
161
|
+
warnings.push(`PI_AGY_ACCOUNTS: "${id}" is listed twice; the duplicate is ignored`);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
listed.add(id);
|
|
165
|
+
const problem = validateAccountName(id, "id");
|
|
166
|
+
if (problem) {
|
|
167
|
+
warnings.push(`PI_AGY_ACCOUNTS: "${id}" ignored (${problem})`);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (!accounts.some((account) => account.id === id)) accounts.push({ id, enabled: true, createdAt: 0, fromEnv: true });
|
|
171
|
+
}
|
|
172
|
+
for (const account of accounts) {
|
|
173
|
+
const email = env[`PI_AGY_ACCOUNT_${account.id.toUpperCase().replace(/-/g, "_")}_EMAIL`]?.trim();
|
|
174
|
+
if (email?.includes("@")) account.email = email;
|
|
175
|
+
}
|
|
176
|
+
const providers = new Map<string, string>();
|
|
177
|
+
for (const account of accounts) {
|
|
178
|
+
const provider = providerIdFor(account);
|
|
179
|
+
const clash = providers.get(provider);
|
|
180
|
+
if (clash) {
|
|
181
|
+
warnings.push(`account "${account.id}" ignored: provider ${provider} is already used by "${clash}"`);
|
|
182
|
+
account.enabled = false;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
providers.set(provider, account.id);
|
|
186
|
+
}
|
|
187
|
+
return { accounts, warnings };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Why a new id/alias cannot be used, or undefined when it can. */
|
|
191
|
+
export function nameConflict(accounts: readonly AccountRecord[], value: string, kind: "id" | "alias", self?: string): string | undefined {
|
|
192
|
+
const problem = validateAccountName(value, kind);
|
|
193
|
+
if (problem) return problem;
|
|
194
|
+
for (const account of accounts) {
|
|
195
|
+
if (account.id === self) continue;
|
|
196
|
+
if (account.id === value || account.alias === value) return `"${value}" is already used by account "${account.id}"`;
|
|
197
|
+
}
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function removeAccountFolder(home: string, id: string): Promise<void> {
|
|
202
|
+
if (validateAccountName(id, "id")) throw new Error(`refusing to delete folder for invalid account id "${id}"`);
|
|
203
|
+
const target = accountPaths(home, id).root;
|
|
204
|
+
// Defence in depth: only ever a direct child of <home>/accounts.
|
|
205
|
+
if (path.dirname(target) !== path.join(home, "accounts")) throw new Error(`refusing to delete ${target}`);
|
|
206
|
+
// Windows can hold a just-killed agy's files for a moment (EBUSY/EPERM).
|
|
207
|
+
await rm(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ---- identity ----------------------------------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
export interface Identity {
|
|
213
|
+
/** agy said it uses the per-folder token file (the SSH trigger worked). */
|
|
214
|
+
fileStorage: boolean;
|
|
215
|
+
email?: string;
|
|
216
|
+
/** agy found no saved login for this folder. */
|
|
217
|
+
signedOut: boolean;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const AUTHENTICATED = /authenticated successfully as (\S+@\S+)/g;
|
|
221
|
+
|
|
222
|
+
/** Parse agy's own log text. The LAST authenticated email wins (a log file may hold several runs). */
|
|
223
|
+
export function parseIdentity(logText: string): Identity {
|
|
224
|
+
const emails = [...logText.matchAll(AUTHENTICATED)].map((match) => match[1].replace(/[.,;]+$/, ""));
|
|
225
|
+
return {
|
|
226
|
+
fileStorage: /Using file-based token storage/.test(logText),
|
|
227
|
+
email: emails.at(-1),
|
|
228
|
+
signedOut: /Silent sign-in failed|You are not logged into Antigravity|Authentication required/.test(logText) && emails.length === 0,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function readIdentity(logFile: string): Promise<Identity> {
|
|
233
|
+
try {
|
|
234
|
+
return parseIdentity(await readFile(logFile, "utf8"));
|
|
235
|
+
} catch {
|
|
236
|
+
return { fileStorage: false, signedOut: false };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Poll agy's log until it states which account it serves (or gives up). agy resolves its login lazily: on 1.5.14 the
|
|
241
|
+
* token-store and "authenticated as" lines are written while the first `session/new` runs, so after that call the
|
|
242
|
+
* answer is normally already there. */
|
|
243
|
+
export async function waitForIdentity(logFile: string, timeoutMs: number, signal?: AbortSignal): Promise<Identity> {
|
|
244
|
+
const deadline = Date.now() + timeoutMs;
|
|
245
|
+
let last: Identity = { fileStorage: false, signedOut: false };
|
|
246
|
+
while (Date.now() < deadline && !signal?.aborted) {
|
|
247
|
+
last = await readIdentity(logFile);
|
|
248
|
+
if (last.email || last.signedOut) return last;
|
|
249
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
250
|
+
}
|
|
251
|
+
return last;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ---- login -------------------------------------------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
export interface LoginProgress {
|
|
257
|
+
/** A URL agy printed for a manual sign-in (shown when the browser could not open). */
|
|
258
|
+
url?: string;
|
|
259
|
+
line?: string;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface LoginResult {
|
|
263
|
+
ok: boolean;
|
|
264
|
+
email?: string;
|
|
265
|
+
message: string;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export interface LoginHandle {
|
|
269
|
+
result: Promise<LoginResult>;
|
|
270
|
+
cancel(): void;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Run `agy acp --login` for one extra account. agy opens the system browser itself; the bridge only waits, reads the
|
|
274
|
+
* log for the resulting email and never touches the token. */
|
|
275
|
+
export function startLogin(options: {
|
|
276
|
+
command: string;
|
|
277
|
+
home: string;
|
|
278
|
+
id: string;
|
|
279
|
+
env?: NodeJS.ProcessEnv;
|
|
280
|
+
timeoutMs?: number;
|
|
281
|
+
onProgress?: (progress: LoginProgress) => void;
|
|
282
|
+
/** Test seam: arguments placed before agy's own (e.g. a fake script run by node). */
|
|
283
|
+
prefixArgs?: readonly string[];
|
|
284
|
+
}): LoginHandle {
|
|
285
|
+
const paths = accountPaths(options.home, options.id);
|
|
286
|
+
let child: ChildProcess | undefined;
|
|
287
|
+
let cancelled = false;
|
|
288
|
+
const result = (async (): Promise<LoginResult> => {
|
|
289
|
+
await mkdir(paths.geminiDir, { recursive: true });
|
|
290
|
+
await rm(paths.loginLog, { force: true });
|
|
291
|
+
if (cancelled) return { ok: false, message: "sign-in cancelled" };
|
|
292
|
+
const args = [...(options.prefixArgs ?? []), "acp", "--login", "--gemini-dir", paths.geminiDir, "--log-file", paths.loginLog];
|
|
293
|
+
child = spawn(options.command, args, {
|
|
294
|
+
cwd: paths.root,
|
|
295
|
+
env: { ...(options.env ?? process.env), ...FILE_STORAGE_ENV },
|
|
296
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
297
|
+
windowsHide: true,
|
|
298
|
+
});
|
|
299
|
+
const onText = (chunk: Buffer | string): void => {
|
|
300
|
+
for (const line of String(chunk).split(/\r?\n/)) {
|
|
301
|
+
const clean = line.replace(/\x1b\[[0-9;]*m/g, "").trim();
|
|
302
|
+
if (!clean) continue;
|
|
303
|
+
const url = /https:\/\/\S+/.exec(clean)?.[0];
|
|
304
|
+
options.onProgress?.(url ? { url, line: clean } : { line: clean });
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
child.stdout?.on("data", onText);
|
|
308
|
+
child.stderr?.on("data", onText);
|
|
309
|
+
const timeoutMs = options.timeoutMs ?? 5 * 60_000;
|
|
310
|
+
const running = child;
|
|
311
|
+
let timedOut = false;
|
|
312
|
+
const exit = await new Promise<{ code: number | null; error?: Error }>((resolve) => {
|
|
313
|
+
// On timeout the process is killed and the promise still resolves on its "exit", so the caller may delete
|
|
314
|
+
// the folder as soon as the result is in.
|
|
315
|
+
const timer = setTimeout(() => {
|
|
316
|
+
timedOut = true;
|
|
317
|
+
running.kill();
|
|
318
|
+
}, timeoutMs);
|
|
319
|
+
timer.unref();
|
|
320
|
+
running.once("error", (error) => {
|
|
321
|
+
clearTimeout(timer);
|
|
322
|
+
resolve({ code: null, error });
|
|
323
|
+
});
|
|
324
|
+
running.once("exit", (code) => {
|
|
325
|
+
clearTimeout(timer);
|
|
326
|
+
resolve({ code });
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
const identity = await readIdentity(paths.loginLog);
|
|
330
|
+
if (cancelled) return { ok: false, message: "sign-in cancelled" };
|
|
331
|
+
if (exit.error) return { ok: false, message: `could not start agy: ${exit.error.message}` };
|
|
332
|
+
if (timedOut) {
|
|
333
|
+
const limit = timeoutMs >= 60_000 ? `${Math.round(timeoutMs / 60_000)} min` : `${Math.round(timeoutMs / 1000)} s`;
|
|
334
|
+
return { ok: false, message: `sign-in did not finish within ${limit}` };
|
|
335
|
+
}
|
|
336
|
+
if (!identity.fileStorage) {
|
|
337
|
+
return { ok: false, message: "agy did not switch to per-account token storage; the account was not isolated (see UPGRADING.md)" };
|
|
338
|
+
}
|
|
339
|
+
if (!identity.email) return { ok: false, message: `sign-in did not complete (agy exit code ${exit.code ?? "?"})` };
|
|
340
|
+
return { ok: true, email: identity.email, message: `signed in as ${maskEmail(identity.email)}` };
|
|
341
|
+
})();
|
|
342
|
+
return {
|
|
343
|
+
result,
|
|
344
|
+
cancel() {
|
|
345
|
+
cancelled = true;
|
|
346
|
+
child?.kill();
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
}
|
package/src/acp/connection.ts
CHANGED
|
@@ -194,7 +194,7 @@ 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.
|
|
197
|
+
clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.2.0" },
|
|
198
198
|
});
|
|
199
199
|
return (result ?? {}) as AcpInitializeResult;
|
|
200
200
|
}
|
package/src/config.ts
CHANGED
|
@@ -36,6 +36,9 @@ export interface AgyConfig {
|
|
|
36
36
|
/** Per-request timeout for ACP control calls (initialize, session/new, set_config_option). */
|
|
37
37
|
controlTimeoutMs: number;
|
|
38
38
|
systemPrompt: SystemPromptDelivery;
|
|
39
|
+
/** `auto` only: a fresh session with the appended system prompt that shows no model output (text or thinking) within
|
|
40
|
+
* this long is treated as refused and retried inline. agy 1.5.14 retries the refusal silently for ~140 s. 0 disables. */
|
|
41
|
+
refusalProbeMs: number;
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
|
|
@@ -51,6 +54,7 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
|
|
|
51
54
|
replayMaxBytes: 8 * 1024 * 1024,
|
|
52
55
|
controlTimeoutMs: 60_000,
|
|
53
56
|
systemPrompt: "auto",
|
|
57
|
+
refusalProbeMs: 30_000,
|
|
54
58
|
});
|
|
55
59
|
|
|
56
60
|
/** Every environment variable loadConfig reads. pi resolves provider-scoped settings only through auth hooks, so the
|
|
@@ -68,6 +72,7 @@ export const CONFIG_ENV_NAMES = [
|
|
|
68
72
|
"PI_AGY_MAX_REPLAY_KB",
|
|
69
73
|
"PI_AGY_CONTROL_TIMEOUT_SEC",
|
|
70
74
|
"PI_AGY_SYSTEM_PROMPT",
|
|
75
|
+
"PI_AGY_REFUSAL_PROBE_SEC",
|
|
71
76
|
] as const;
|
|
72
77
|
|
|
73
78
|
function delivery(value: string | undefined): SystemPromptDelivery {
|
|
@@ -97,5 +102,6 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
|
|
97
102
|
replayMaxBytes: Math.max(1024, positiveInt(env.PI_AGY_MAX_REPLAY_KB, DEFAULT_CONFIG.replayMaxBytes, 1024)),
|
|
98
103
|
controlTimeoutMs: positiveInt(env.PI_AGY_CONTROL_TIMEOUT_SEC, DEFAULT_CONFIG.controlTimeoutMs, 1000),
|
|
99
104
|
systemPrompt: delivery(env.PI_AGY_SYSTEM_PROMPT),
|
|
105
|
+
refusalProbeMs: positiveInt(env.PI_AGY_REFUSAL_PROBE_SEC, DEFAULT_CONFIG.refusalProbeMs, 1000),
|
|
100
106
|
};
|
|
101
107
|
}
|
package/src/doctor.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { historyRewriteHookCount } from "./pi-context-hook.ts";
|
|
|
6
6
|
import { describeModels, FALLBACK_DESCRIPTORS, toPiModels } from "./model-catalog.ts";
|
|
7
7
|
import { describeError } from "./errors.ts";
|
|
8
8
|
import type { AgyRuntime } from "./runtime.ts";
|
|
9
|
+
import { maskEmail, providerIdFor } from "./accounts.ts";
|
|
9
10
|
|
|
10
11
|
export interface DoctorReport {
|
|
11
12
|
ok: boolean;
|
|
@@ -13,9 +14,18 @@ export interface DoctorReport {
|
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
export async function buildDoctor(runtime: AgyRuntime, options: { force?: boolean } = {}): Promise<DoctorReport> {
|
|
16
|
-
const
|
|
17
|
+
const account = runtime.account;
|
|
18
|
+
const provider = account ? providerIdFor(account) : "agy";
|
|
19
|
+
const lines: string[] = [account ? `pi-agy-bridge doctor · ${provider}` : "pi-agy-bridge doctor"];
|
|
17
20
|
let ok = true;
|
|
18
|
-
lines.push(`command: ${runtime.config.command} state dir: ${runtime.
|
|
21
|
+
lines.push(`command: ${runtime.config.command} state dir: ${runtime.stateDir}`);
|
|
22
|
+
if (account) {
|
|
23
|
+
const identity = runtime.identity;
|
|
24
|
+
lines.push(
|
|
25
|
+
`account: ${account.id}${account.alias ? ` (alias ${account.alias})` : ""} expected: ${maskEmail(account.email)}` +
|
|
26
|
+
` last start: ${identity ? `${identity.ok ? "ok" : "FAILED"} as ${maskEmail(identity.identity.email)}${identity.identity.fileStorage ? " (own token file)" : ""}` : "not started yet"}`,
|
|
27
|
+
);
|
|
28
|
+
}
|
|
19
29
|
try {
|
|
20
30
|
const discovery = await runtime.pool.discover(options.force === true);
|
|
21
31
|
if (runtime.report) lines.push(...formatFeatureReport(runtime.report));
|
|
@@ -29,7 +39,7 @@ export async function buildDoctor(runtime: AgyRuntime, options: { force?: boolea
|
|
|
29
39
|
.filter(([, value]) => value !== null)
|
|
30
40
|
.map(([key]) => key)
|
|
31
41
|
.join("/");
|
|
32
|
-
lines.push(`
|
|
42
|
+
lines.push(` ${provider}/${model.id} ctx ${Math.round(model.contextWindow / 1000)}K max ${Math.round(model.maxTokens / 1000)}K thinking ${levels || "-"}`);
|
|
33
43
|
}
|
|
34
44
|
} catch (error) {
|
|
35
45
|
ok = false;
|
package/src/index.ts
CHANGED
|
@@ -1,39 +1,73 @@
|
|
|
1
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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:
|
|
8
|
-
// costs no processes
|
|
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
|
|
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
|
|
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
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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";
|