@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/ARCHITECTURE.md +11 -1
- package/README.md +53 -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 +399 -0
- package/src/accounts.ts +394 -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 +478 -0
- package/src/ui/panel.ts +376 -0
package/src/accounts.ts
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
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
|
+
/** agy >= 1.5.14 with file token storage does not catch the OAuth redirect itself: it prints the sign-in link and
|
|
263
|
+
* waits on stdin for the authorization code (or the full URL of the page the browser lands on). */
|
|
264
|
+
const CODE_PROMPT = /paste the authorization code/i;
|
|
265
|
+
|
|
266
|
+
/** Asked once agy waits for the authorization code. Resolve with the code / landing URL, or undefined to cancel. */
|
|
267
|
+
export type RequestLoginCode = (url: string | undefined, signal: AbortSignal) => Promise<string | undefined>;
|
|
268
|
+
|
|
269
|
+
export interface LoginResult {
|
|
270
|
+
ok: boolean;
|
|
271
|
+
email?: string;
|
|
272
|
+
message: string;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export interface LoginHandle {
|
|
276
|
+
result: Promise<LoginResult>;
|
|
277
|
+
cancel(): void;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Run `agy acp --login` for one extra account. agy opens the system browser itself; the bridge only waits, reads the
|
|
281
|
+
* log for the resulting email and never touches the token. */
|
|
282
|
+
export function startLogin(options: {
|
|
283
|
+
command: string;
|
|
284
|
+
home: string;
|
|
285
|
+
id: string;
|
|
286
|
+
env?: NodeJS.ProcessEnv;
|
|
287
|
+
timeoutMs?: number;
|
|
288
|
+
onProgress?: (progress: LoginProgress) => void;
|
|
289
|
+
/** Supplies the authorization code when agy asks for it. Without it agy's stdin is closed (sign-in fails). */
|
|
290
|
+
requestCode?: RequestLoginCode;
|
|
291
|
+
/** Test seam: arguments placed before agy's own (e.g. a fake script run by node). */
|
|
292
|
+
prefixArgs?: readonly string[];
|
|
293
|
+
}): LoginHandle {
|
|
294
|
+
const paths = accountPaths(options.home, options.id);
|
|
295
|
+
let child: ChildProcess | undefined;
|
|
296
|
+
let cancelled = false;
|
|
297
|
+
const result = (async (): Promise<LoginResult> => {
|
|
298
|
+
await mkdir(paths.geminiDir, { recursive: true });
|
|
299
|
+
await rm(paths.loginLog, { force: true });
|
|
300
|
+
if (cancelled) return { ok: false, message: "sign-in cancelled" };
|
|
301
|
+
const args = [...(options.prefixArgs ?? []), "acp", "--login", "--gemini-dir", paths.geminiDir, "--log-file", paths.loginLog];
|
|
302
|
+
child = spawn(options.command, args, {
|
|
303
|
+
cwd: paths.root,
|
|
304
|
+
env: { ...(options.env ?? process.env), ...FILE_STORAGE_ENV },
|
|
305
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
306
|
+
windowsHide: true,
|
|
307
|
+
});
|
|
308
|
+
const stdin = child.stdin;
|
|
309
|
+
stdin?.on("error", () => undefined); // agy may exit before the code is written (EPIPE)
|
|
310
|
+
if (!options.requestCode) stdin?.end();
|
|
311
|
+
const asking = new AbortController();
|
|
312
|
+
let loginUrl: string | undefined;
|
|
313
|
+
let prompted = false;
|
|
314
|
+
let transcript = "";
|
|
315
|
+
const askForCode = async (): Promise<void> => {
|
|
316
|
+
if (!options.requestCode || !stdin) return;
|
|
317
|
+
let code: string | undefined;
|
|
318
|
+
try {
|
|
319
|
+
code = await options.requestCode(loginUrl, asking.signal);
|
|
320
|
+
} catch {
|
|
321
|
+
code = undefined;
|
|
322
|
+
}
|
|
323
|
+
if (asking.signal.aborted) return;
|
|
324
|
+
const value = code?.trim();
|
|
325
|
+
if (!value) {
|
|
326
|
+
cancelled = true;
|
|
327
|
+
child?.kill();
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
stdin.end(`${value}\n`);
|
|
331
|
+
};
|
|
332
|
+
const onText = (chunk: Buffer | string): void => {
|
|
333
|
+
const text = String(chunk).replace(/\x1b\[[0-9;]*m/g, "");
|
|
334
|
+
for (const line of text.split(/\r?\n/)) {
|
|
335
|
+
const clean = line.trim();
|
|
336
|
+
if (!clean) continue;
|
|
337
|
+
const url = /https:\/\/\S+/.exec(clean)?.[0];
|
|
338
|
+
if (url && !loginUrl) loginUrl = url;
|
|
339
|
+
options.onProgress?.(url ? { url, line: clean } : { line: clean });
|
|
340
|
+
}
|
|
341
|
+
// The prompt has no trailing newline and may arrive split across chunks.
|
|
342
|
+
transcript = (transcript + text).slice(-4096);
|
|
343
|
+
if (!prompted && CODE_PROMPT.test(transcript)) {
|
|
344
|
+
prompted = true;
|
|
345
|
+
void askForCode();
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
child.stdout?.on("data", onText);
|
|
349
|
+
child.stderr?.on("data", onText);
|
|
350
|
+
const timeoutMs = options.timeoutMs ?? 5 * 60_000;
|
|
351
|
+
const running = child;
|
|
352
|
+
let timedOut = false;
|
|
353
|
+
const exit = await new Promise<{ code: number | null; error?: Error }>((resolve) => {
|
|
354
|
+
// On timeout the process is killed and the promise still resolves on its "exit", so the caller may delete
|
|
355
|
+
// the folder as soon as the result is in.
|
|
356
|
+
const timer = setTimeout(() => {
|
|
357
|
+
timedOut = true;
|
|
358
|
+
running.kill();
|
|
359
|
+
}, timeoutMs);
|
|
360
|
+
timer.unref();
|
|
361
|
+
running.once("error", (error) => {
|
|
362
|
+
clearTimeout(timer);
|
|
363
|
+
resolve({ code: null, error });
|
|
364
|
+
});
|
|
365
|
+
running.once("exit", (code) => {
|
|
366
|
+
clearTimeout(timer);
|
|
367
|
+
resolve({ code });
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
asking.abort(); // dismiss a still-open code dialog when agy has already exited
|
|
371
|
+
const identity = await readIdentity(paths.loginLog);
|
|
372
|
+
if (cancelled) return { ok: false, message: "sign-in cancelled" };
|
|
373
|
+
if (exit.error) return { ok: false, message: `could not start agy: ${exit.error.message}` };
|
|
374
|
+
if (timedOut) {
|
|
375
|
+
const limit = timeoutMs >= 60_000 ? `${Math.round(timeoutMs / 60_000)} min` : `${Math.round(timeoutMs / 1000)} s`;
|
|
376
|
+
return { ok: false, message: `sign-in did not finish within ${limit}` };
|
|
377
|
+
}
|
|
378
|
+
if (!identity.fileStorage) {
|
|
379
|
+
return { ok: false, message: "agy did not switch to per-account token storage; the account was not isolated (see UPGRADING.md)" };
|
|
380
|
+
}
|
|
381
|
+
if (!identity.email) {
|
|
382
|
+
const reason = /(?:Error|couldn't log in):?\s*(.+)$/im.exec(transcript)?.[1]?.trim();
|
|
383
|
+
return { ok: false, message: `sign-in did not complete (agy exit code ${exit.code ?? "?"}${reason ? `: ${reason}` : ""})` };
|
|
384
|
+
}
|
|
385
|
+
return { ok: true, email: identity.email, message: `signed in as ${maskEmail(identity.email)}` };
|
|
386
|
+
})();
|
|
387
|
+
return {
|
|
388
|
+
result,
|
|
389
|
+
cancel() {
|
|
390
|
+
cancelled = true;
|
|
391
|
+
child?.kill();
|
|
392
|
+
},
|
|
393
|
+
};
|
|
394
|
+
}
|
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;
|