@timmyjl12/pi-agy-bridge 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +15 -3
- package/README.md +7 -4
- package/compat/baselines/agy-1.5.18.json +284 -0
- package/compat/matrix.json +1 -1
- package/compat/probe.ts +1 -1
- package/package.json +1 -1
- package/src/account-manager.ts +46 -2
- package/src/accounts.ts +94 -4
- package/src/acp/connection.ts +17 -1
- package/src/config.ts +6 -0
- package/src/conversation-store.ts +168 -0
- package/src/errors.ts +2 -2
- package/src/index.ts +10 -2
- package/src/model-catalog.ts +48 -2
- package/src/provider.ts +10 -4
- package/src/runtime.ts +106 -9
- package/src/session-pool.ts +178 -7
- package/src/stream.ts +93 -13
- package/src/ui/menu.ts +69 -11
package/src/accounts.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// which account a process serves, and refuses to use an extra-account process that is not the expected account.
|
|
11
11
|
|
|
12
12
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
13
|
-
import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
|
|
13
|
+
import { chmod, mkdir, readFile, rename, rm, stat } from "node:fs/promises";
|
|
14
14
|
import path from "node:path";
|
|
15
15
|
import { writeFileAtomic } from "./atomic-write.ts";
|
|
16
16
|
|
|
@@ -22,9 +22,29 @@ export const DEFAULT_PROVIDER = "agy";
|
|
|
22
22
|
/** The value is only a marker: agy checks that the variable exists. */
|
|
23
23
|
export const FILE_STORAGE_ENV = { SSH_CONNECTION: "pi-agy-bridge 0 pi-agy-bridge 0" } as const;
|
|
24
24
|
|
|
25
|
+
/** Variables agy would read as API-key credentials. */
|
|
26
|
+
const API_KEY_ENV = new Set(["GEMINI_API_KEY", "GOOGLE_API_KEY"]);
|
|
27
|
+
|
|
28
|
+
/** A copy of `env` without any API-key variable, in any letter case (Windows environment names are case-insensitive,
|
|
29
|
+
* so `gemini_api_key` would reach agy as GEMINI_API_KEY). Applied to every agy spawn: a Google-login process must
|
|
30
|
+
* serve the account's own login, and an API-key process gets only the key stored for its account. */
|
|
31
|
+
export function withoutApiKeys(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
|
32
|
+
const copy: NodeJS.ProcessEnv = {};
|
|
33
|
+
for (const [name, value] of Object.entries(env)) if (!API_KEY_ENV.has(name.toUpperCase())) copy[name] = value;
|
|
34
|
+
return copy;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** How an account signs in. `google` (the default): the real agy CLI with the account's own signed-in Google login
|
|
38
|
+
* (keyring for the default account, its own token file for extras), exactly as before 0.4.0. `api-key`: agy's
|
|
39
|
+
* `gemini-api-key` ACP auth method. An account is in `api-key` mode exactly when a key is stored for it through the
|
|
40
|
+
* menu; the environment's GEMINI_API_KEY is never used. Derived from the key file, never persisted separately. */
|
|
41
|
+
export type AuthMode = "google" | "api-key";
|
|
42
|
+
|
|
25
43
|
export interface AccountRecord {
|
|
26
44
|
id: string;
|
|
27
45
|
alias?: string;
|
|
46
|
+
/** Derived at load from the account's stored key (absent = `google`); not written to accounts.json. */
|
|
47
|
+
auth?: AuthMode;
|
|
28
48
|
/** The Google account this profile must serve; recorded at sign-in (or set by PI_AGY_ACCOUNT_<ID>_EMAIL). */
|
|
29
49
|
email?: string;
|
|
30
50
|
enabled: boolean;
|
|
@@ -75,6 +95,11 @@ export function maskEmail(email: string | undefined): string {
|
|
|
75
95
|
export interface AccountPaths {
|
|
76
96
|
root: string;
|
|
77
97
|
geminiDir: string;
|
|
98
|
+
/** agy data dir for API-key mode. Separate from `geminiDir` because agy caches the chosen auth method in its dir
|
|
99
|
+
* (`antigravity-cli/cache/acp-auth-state.json`), so one dir must never serve both modes. */
|
|
100
|
+
apiKeyGeminiDir: string;
|
|
101
|
+
/** The stored Gemini API key (plain text, user-only permissions). Never logged. */
|
|
102
|
+
apiKeyFile: string;
|
|
78
103
|
logFile: string;
|
|
79
104
|
/** The previous process's agy log, kept so a failure (a stall, a timeout) can be read after the restart. */
|
|
80
105
|
prevLogFile: string;
|
|
@@ -88,6 +113,8 @@ export function accountPaths(home: string, id: string): AccountPaths {
|
|
|
88
113
|
return {
|
|
89
114
|
root,
|
|
90
115
|
geminiDir,
|
|
116
|
+
apiKeyGeminiDir: path.join(root, "gemini-apikey"),
|
|
117
|
+
apiKeyFile: path.join(root, "api-key"),
|
|
91
118
|
logFile: path.join(root, "acp.log"),
|
|
92
119
|
prevLogFile: path.join(root, "acp.prev.log"),
|
|
93
120
|
loginLog: path.join(root, "login.log"),
|
|
@@ -95,8 +122,19 @@ export function accountPaths(home: string, id: string): AccountPaths {
|
|
|
95
122
|
};
|
|
96
123
|
}
|
|
97
124
|
|
|
98
|
-
/**
|
|
99
|
-
*
|
|
125
|
+
/** ACP logs are private to one pi process. Several pi agents can use the same account concurrently without rotating
|
|
126
|
+
* or deleting the log another process still has open. `owner` is a test seam; production uses pi's process id. */
|
|
127
|
+
export function accountProcessPaths(home: string, id: string, owner = process.pid): AccountPaths {
|
|
128
|
+
const paths = accountPaths(home, id);
|
|
129
|
+
return {
|
|
130
|
+
...paths,
|
|
131
|
+
logFile: path.join(paths.root, `acp-${owner}.log`),
|
|
132
|
+
prevLogFile: path.join(paths.root, `acp-${owner}.prev.log`),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Before an extra-account process starts: move its last log to the matching previous-log path (replacing the older
|
|
137
|
+
* one) so the new process starts with an empty log for the identity guard, while the previous run stays readable. */
|
|
100
138
|
export async function rotateAccountLog(
|
|
101
139
|
paths: Pick<AccountPaths, "logFile" | "prevLogFile">,
|
|
102
140
|
io: { rename: typeof rename; rm: typeof rm } = { rename, rm },
|
|
@@ -117,6 +155,53 @@ export async function rotateAccountLog(
|
|
|
117
155
|
await io.rm(paths.logFile, { force: true, maxRetries: 5, retryDelay: 100 });
|
|
118
156
|
}
|
|
119
157
|
|
|
158
|
+
/** Where the default account keeps its API key and API-key agy dir: directly under the bridge home. */
|
|
159
|
+
export function defaultAccountPaths(home: string): Pick<AccountPaths, "root" | "apiKeyGeminiDir" | "apiKeyFile"> {
|
|
160
|
+
return { root: home, apiKeyGeminiDir: path.join(home, "gemini-apikey"), apiKeyFile: path.join(home, "api-key") };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function apiKeyPathsFor(home: string, id: string): Pick<AccountPaths, "root" | "apiKeyGeminiDir" | "apiKeyFile"> {
|
|
164
|
+
return id === DEFAULT_ACCOUNT ? defaultAccountPaths(home) : accountPaths(home, id);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** A Gemini API key: printable, no whitespace, a sane length. Rejects pasted prose or a whole env line. */
|
|
168
|
+
export function validateApiKey(value: string): string | undefined {
|
|
169
|
+
if (!value) return "the API key is empty";
|
|
170
|
+
if (/\s/.test(value)) return "the API key must not contain spaces or line breaks";
|
|
171
|
+
if (value.length < 20 || value.length > 200) return "that does not look like a Gemini API key (expected 20-200 characters)";
|
|
172
|
+
if (!/^[\x21-\x7e]+$/.test(value)) return "the API key contains characters an API key never has";
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The stored key, or undefined. A read problem counts as "no key" (the caller falls back to GEMINI_API_KEY). */
|
|
177
|
+
export async function readApiKey(file: string): Promise<string | undefined> {
|
|
178
|
+
try {
|
|
179
|
+
const value = (await readFile(file, "utf8")).trim();
|
|
180
|
+
return value && !validateApiKey(value) ? value : undefined;
|
|
181
|
+
} catch {
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Store (or with undefined, delete) an account's API key. Written atomically and readable by the user only. */
|
|
187
|
+
export async function writeApiKey(file: string, value: string | undefined): Promise<void> {
|
|
188
|
+
if (value === undefined) {
|
|
189
|
+
await rm(file, { force: true });
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const problem = validateApiKey(value);
|
|
193
|
+
if (problem) throw new Error(problem);
|
|
194
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
195
|
+
await writeFileAtomic(file, `${value}\n`);
|
|
196
|
+
// POSIX: owner read/write only. Windows ignores the mode; the file lives in the user's own profile.
|
|
197
|
+
await chmod(file, 0o600).catch(() => undefined);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Mask a key for display: the first four and last four characters only. */
|
|
201
|
+
export function maskApiKey(value: string): string {
|
|
202
|
+
return value.length <= 8 ? "…" : `${value.slice(0, 4)}…${value.slice(-4)}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
120
205
|
/** Is a saved login present for this extra account (existence only; the file is never read)? */
|
|
121
206
|
export async function hasSavedLogin(home: string, id: string): Promise<boolean> {
|
|
122
207
|
try {
|
|
@@ -159,6 +244,11 @@ export async function readRegistry(home: string): Promise<AccountRecord[]> {
|
|
|
159
244
|
}
|
|
160
245
|
}
|
|
161
246
|
|
|
247
|
+
/** An account's sign-in method: `api-key` exactly when a valid key is stored for it. */
|
|
248
|
+
export async function authModeFor(home: string, id: string): Promise<AuthMode> {
|
|
249
|
+
return (await readApiKey(apiKeyPathsFor(home, id).apiKeyFile)) ? "api-key" : "google";
|
|
250
|
+
}
|
|
251
|
+
|
|
162
252
|
export async function writeRegistry(home: string, accounts: readonly AccountRecord[]): Promise<void> {
|
|
163
253
|
await mkdir(home, { recursive: true });
|
|
164
254
|
const file: RegistryFile = {
|
|
@@ -326,7 +416,7 @@ export function startLogin(options: {
|
|
|
326
416
|
const args = [...(options.prefixArgs ?? []), "acp", "--login", "--gemini-dir", paths.geminiDir, "--log-file", paths.loginLog];
|
|
327
417
|
child = spawn(options.command, args, {
|
|
328
418
|
cwd: paths.root,
|
|
329
|
-
env: { ...(options.env ?? process.env), ...FILE_STORAGE_ENV },
|
|
419
|
+
env: { ...withoutApiKeys(options.env ?? process.env), ...FILE_STORAGE_ENV },
|
|
330
420
|
stdio: ["pipe", "pipe", "pipe"],
|
|
331
421
|
windowsHide: true,
|
|
332
422
|
});
|
package/src/acp/connection.ts
CHANGED
|
@@ -194,11 +194,27 @@ export class AcpProcess {
|
|
|
194
194
|
const result = await this.#rpc.request("initialize", {
|
|
195
195
|
protocolVersion: 1,
|
|
196
196
|
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
197
|
-
clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.
|
|
197
|
+
clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.4.1" },
|
|
198
198
|
});
|
|
199
199
|
return (result ?? {}) as AcpInitializeResult;
|
|
200
200
|
}
|
|
201
201
|
|
|
202
|
+
/** Select an advertised auth method (`gemini-api-key` reads GEMINI_API_KEY from agy's environment; verified on agy
|
|
203
|
+
* 1.5.17). agy caches the method in its gemini dir, so a dir must only ever serve one method. */
|
|
204
|
+
async authenticate(methodId: string): Promise<void> {
|
|
205
|
+
await this.#rpc.request("authenticate", { methodId });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Reopen a conversation agy already holds (its own store) without replaying it. Verified on agy 1.5.17: works in a
|
|
209
|
+
* new process, after session/close, and keeps the session's appended system prompt; an unknown id fails with
|
|
210
|
+
* "Failed to read session". The result has the same shape as session/new. */
|
|
211
|
+
async resumeSession(params: { sessionId: string; cwd: string }): Promise<AcpNewSessionResult> {
|
|
212
|
+
const result = (await this.#rpc.request("session/resume", { sessionId: params.sessionId, cwd: params.cwd, mcpServers: [] })) as
|
|
213
|
+
| AcpNewSessionResult
|
|
214
|
+
| undefined;
|
|
215
|
+
return { ...(result ?? {}), sessionId: params.sessionId };
|
|
216
|
+
}
|
|
217
|
+
|
|
202
218
|
/** Create a session. `systemPromptAppend` rides `_meta.antigravity.systemPrompt.append` (verified on agy 1.5.3 and 1.5.8). */
|
|
203
219
|
async newSession(params: { cwd: string; systemPromptAppend?: string }): Promise<AcpNewSessionResult> {
|
|
204
220
|
const body: Record<string, unknown> = { cwd: params.cwd, mcpServers: [] };
|
package/src/config.ts
CHANGED
|
@@ -39,6 +39,9 @@ export interface AgyConfig {
|
|
|
39
39
|
/** `auto` only: a fresh session with the appended system prompt that shows no model output (text or thinking) within
|
|
40
40
|
* this long is treated as refused and retried inline. agy 1.5.14 retries the refusal silently for ~140 s. 0 disables. */
|
|
41
41
|
refusalProbeMs: number;
|
|
42
|
+
/** Reattach continued pi sessions to agy's stored conversation with ACP `session/resume` instead of replaying
|
|
43
|
+
* history (PI_AGY_RESUME=0 turns it off). */
|
|
44
|
+
resume: boolean;
|
|
42
45
|
}
|
|
43
46
|
|
|
44
47
|
export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
|
|
@@ -55,6 +58,7 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
|
|
|
55
58
|
controlTimeoutMs: 60_000,
|
|
56
59
|
systemPrompt: "auto",
|
|
57
60
|
refusalProbeMs: 30_000,
|
|
61
|
+
resume: true,
|
|
58
62
|
});
|
|
59
63
|
|
|
60
64
|
/** Every environment variable loadConfig reads. pi resolves provider-scoped settings only through auth hooks, so the
|
|
@@ -73,6 +77,7 @@ export const CONFIG_ENV_NAMES = [
|
|
|
73
77
|
"PI_AGY_CONTROL_TIMEOUT_SEC",
|
|
74
78
|
"PI_AGY_SYSTEM_PROMPT",
|
|
75
79
|
"PI_AGY_REFUSAL_PROBE_SEC",
|
|
80
|
+
"PI_AGY_RESUME",
|
|
76
81
|
] as const;
|
|
77
82
|
|
|
78
83
|
function delivery(value: string | undefined): SystemPromptDelivery {
|
|
@@ -103,5 +108,6 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
|
|
103
108
|
controlTimeoutMs: positiveInt(env.PI_AGY_CONTROL_TIMEOUT_SEC, DEFAULT_CONFIG.controlTimeoutMs, 1000),
|
|
104
109
|
systemPrompt: delivery(env.PI_AGY_SYSTEM_PROMPT),
|
|
105
110
|
refusalProbeMs: positiveInt(env.PI_AGY_REFUSAL_PROBE_SEC, DEFAULT_CONFIG.refusalProbeMs, 1000),
|
|
111
|
+
resume: !/^(0|false|off|no)$/i.test(env.PI_AGY_RESUME?.trim() ?? ""),
|
|
106
112
|
};
|
|
107
113
|
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// agy's own conversation store, read-only, plus the bridge's record of which agy conversation holds which pi session.
|
|
2
|
+
//
|
|
3
|
+
// agy keeps every conversation in `<gemini-dir>/antigravity-cli/conversations/<sessionId>.db` (SQLite) and can reopen
|
|
4
|
+
// it in a new process with ACP `session/resume` without replaying it (verified on agy 1.5.17: a codeword told in one
|
|
5
|
+
// process was recalled in the next, input served from cache). The bridge records, per pi session, the agy session id,
|
|
6
|
+
// the hash chain it holds and agy's step count; a continued pi session can then reattach instead of replaying history.
|
|
7
|
+
//
|
|
8
|
+
// Resuming is only safe when agy's conversation is exactly what the bridge left behind. The check reads agy's database
|
|
9
|
+
// read-only and sends nothing: any client prompt (USER_INPUT step) after the recorded step count means another client
|
|
10
|
+
// or branch continued it, and a missing or shorter conversation means it is gone. Both fall back to a full replay.
|
|
11
|
+
// Idea and step type taken from patlux/pi-antigravity-thin-client (src/session/agy-resume.ts, MIT).
|
|
12
|
+
|
|
13
|
+
import { readFile } from "node:fs/promises";
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { writeFileAtomic } from "./atomic-write.ts";
|
|
17
|
+
|
|
18
|
+
/** agy's `steps.step_type` for a prompt sent by a client. Measured on 1.5.17: 14 USER_INPUT, 15 PLANNER_RESPONSE,
|
|
19
|
+
* 101 SYSTEM_MESSAGE (resume marker), 17 on failed attempts. */
|
|
20
|
+
export const USER_INPUT_STEP_TYPE = 14;
|
|
21
|
+
|
|
22
|
+
export type ConversationSinceRecord = "continued" | "prompted" | "lost";
|
|
23
|
+
|
|
24
|
+
export function conversationDbPath(geminiDir: string, sessionId: string): string {
|
|
25
|
+
return path.join(geminiDir, "antigravity-cli", "conversations", `${sessionId}.db`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** agy session ids are UUIDs; anything else is never used in a path. */
|
|
29
|
+
const SESSION_ID = /^[A-Za-z0-9-]{8,64}$/;
|
|
30
|
+
|
|
31
|
+
type Sqlite = typeof import("node:sqlite");
|
|
32
|
+
let sqliteModule: Promise<Sqlite | undefined> | undefined;
|
|
33
|
+
|
|
34
|
+
/** node:sqlite (Node >= 22.5). Undefined when unavailable: every check then answers "lost" and the bridge replays. */
|
|
35
|
+
function loadSqlite(): Promise<Sqlite | undefined> {
|
|
36
|
+
sqliteModule ??= import("node:sqlite").then(
|
|
37
|
+
(module) => module,
|
|
38
|
+
() => undefined,
|
|
39
|
+
);
|
|
40
|
+
return sqliteModule;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Read `{steps, userInputs since fromStep}` from agy's conversation db, or undefined when it cannot be read. */
|
|
44
|
+
export async function readConversationSteps(
|
|
45
|
+
geminiDir: string,
|
|
46
|
+
sessionId: string,
|
|
47
|
+
fromStep = 0,
|
|
48
|
+
): Promise<{ steps: number; promptsSince: number } | undefined> {
|
|
49
|
+
if (!SESSION_ID.test(sessionId)) return undefined;
|
|
50
|
+
const file = conversationDbPath(geminiDir, sessionId);
|
|
51
|
+
if (!existsSync(file)) return undefined;
|
|
52
|
+
const sqlite = await loadSqlite();
|
|
53
|
+
if (!sqlite) return undefined;
|
|
54
|
+
let db: import("node:sqlite").DatabaseSync | undefined;
|
|
55
|
+
try {
|
|
56
|
+
db = new sqlite.DatabaseSync(file, { readOnly: true });
|
|
57
|
+
db.exec("PRAGMA busy_timeout = 1500");
|
|
58
|
+
const total = db.prepare("SELECT COUNT(*) AS n FROM steps").get() as { n?: unknown } | undefined;
|
|
59
|
+
const since = db
|
|
60
|
+
.prepare("SELECT COUNT(*) AS n FROM steps WHERE idx >= ? AND step_type = ?")
|
|
61
|
+
.get(fromStep, USER_INPUT_STEP_TYPE) as { n?: unknown } | undefined;
|
|
62
|
+
const steps = Number(total?.n);
|
|
63
|
+
const promptsSince = Number(since?.n);
|
|
64
|
+
return Number.isFinite(steps) && Number.isFinite(promptsSince) ? { steps, promptsSince } : undefined;
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
} finally {
|
|
68
|
+
try {
|
|
69
|
+
db?.close();
|
|
70
|
+
} catch {
|
|
71
|
+
// already read; nothing to release
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** What happened to agy's conversation since the bridge recorded `steps`. Read-only; sends nothing to agy. */
|
|
77
|
+
export async function checkConversation(geminiDir: string, sessionId: string, steps: number): Promise<ConversationSinceRecord> {
|
|
78
|
+
const now = await readConversationSteps(geminiDir, sessionId, steps);
|
|
79
|
+
if (!now || now.steps < steps) return "lost";
|
|
80
|
+
return now.promptsSince > 0 ? "prompted" : "continued";
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ---- resume records ----------------------------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
export interface ResumeRecord {
|
|
86
|
+
acpSessionId: string;
|
|
87
|
+
/** Length of the hash chain agy holds (seed + one link per message). */
|
|
88
|
+
chainLength: number;
|
|
89
|
+
/** Last link of that chain. Each link hashes its predecessor, so equal last links at equal length prove the whole
|
|
90
|
+
* prefix (system prompt, tools, model, thinking level and every message) is identical. */
|
|
91
|
+
chainLast: string;
|
|
92
|
+
/** agy's step count when the record was written; the check looks for client prompts after it. */
|
|
93
|
+
steps: number;
|
|
94
|
+
savedAt: number;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface ResumeFile {
|
|
98
|
+
version: 1;
|
|
99
|
+
sessions: Record<string, ResumeRecord>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const MAX_RECORDS = 200;
|
|
103
|
+
|
|
104
|
+
function isRecord(value: unknown): value is ResumeRecord {
|
|
105
|
+
if (!value || typeof value !== "object") return false;
|
|
106
|
+
const r = value as Record<string, unknown>;
|
|
107
|
+
return (
|
|
108
|
+
typeof r.acpSessionId === "string" &&
|
|
109
|
+
SESSION_ID.test(r.acpSessionId) &&
|
|
110
|
+
typeof r.chainLength === "number" &&
|
|
111
|
+
typeof r.chainLast === "string" &&
|
|
112
|
+
typeof r.steps === "number" &&
|
|
113
|
+
typeof r.savedAt === "number"
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** pi session id -> record, persisted next to an account's agy dir. No long-lived cache: every read goes to disk and
|
|
118
|
+
* every change is a read-modify-write of one key, serialized within this process, so records written by another pi
|
|
119
|
+
* process (a subagent, a second window) survive. Two processes writing in the same instant can still lose one record,
|
|
120
|
+
* which only costs that session one replay. */
|
|
121
|
+
export class ResumeStore {
|
|
122
|
+
readonly file: string;
|
|
123
|
+
#writing: Promise<void> = Promise.resolve();
|
|
124
|
+
|
|
125
|
+
constructor(file: string) {
|
|
126
|
+
this.file = file;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async #read(): Promise<Map<string, ResumeRecord>> {
|
|
130
|
+
const map = new Map<string, ResumeRecord>();
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(await readFile(this.file, "utf8")) as Partial<ResumeFile>;
|
|
133
|
+
for (const [key, value] of Object.entries(parsed.sessions ?? {})) if (isRecord(value)) map.set(key, value);
|
|
134
|
+
} catch {
|
|
135
|
+
// missing or unreadable: empty
|
|
136
|
+
}
|
|
137
|
+
return map;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async get(piSessionId: string): Promise<ResumeRecord | undefined> {
|
|
141
|
+
await this.#writing.catch(() => undefined);
|
|
142
|
+
return (await this.#read()).get(piSessionId);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
set(piSessionId: string, record: ResumeRecord): Promise<void> {
|
|
146
|
+
return this.#update((map) => {
|
|
147
|
+
map.delete(piSessionId); // re-insert: most recent last
|
|
148
|
+
map.set(piSessionId, record);
|
|
149
|
+
while (map.size > MAX_RECORDS) map.delete(map.keys().next().value as string);
|
|
150
|
+
return true;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
delete(piSessionId: string): Promise<void> {
|
|
155
|
+
return this.#update((map) => map.delete(piSessionId));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
#update(change: (map: Map<string, ResumeRecord>) => boolean): Promise<void> {
|
|
159
|
+
const run = async (): Promise<void> => {
|
|
160
|
+
const map = await this.#read();
|
|
161
|
+
if (!change(map)) return;
|
|
162
|
+
const body: ResumeFile = { version: 1, sessions: Object.fromEntries(map) };
|
|
163
|
+
await writeFileAtomic(this.file, `${JSON.stringify(body)}\n`);
|
|
164
|
+
};
|
|
165
|
+
this.#writing = this.#writing.then(run, run);
|
|
166
|
+
return this.#writing;
|
|
167
|
+
}
|
|
168
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -111,8 +111,8 @@ export function looksLikeNotice(text: string): boolean {
|
|
|
111
111
|
|
|
112
112
|
/** agy reports some failures as an ordinary reply with no model call, for example
|
|
113
113
|
* "⚠ Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 141h13m52s."
|
|
114
|
-
* (observed on agy 1.5.3
|
|
115
|
-
*
|
|
114
|
+
* (observed on agy 1.5.3 with no usage field; agy 1.5.17 can emit thinking and nonzero usage before the same warning).
|
|
115
|
+
* Classify the text like any other failure so quota, login and context problems reach fallback
|
|
116
116
|
* chains with their words intact; a notice that matches nothing known must still not pass as an answer. */
|
|
117
117
|
export function noticeError(text: string): AgyError {
|
|
118
118
|
const notice = text.trim();
|
package/src/index.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
doctorText,
|
|
9
9
|
emailOf,
|
|
10
10
|
promptAdd,
|
|
11
|
+
promptApiKey,
|
|
11
12
|
promptRemove,
|
|
12
13
|
runAccountAction,
|
|
13
14
|
runLogin,
|
|
@@ -23,6 +24,7 @@ const COMMANDS: readonly AutocompleteItem[] = [
|
|
|
23
24
|
{ value: "accounts", label: "accounts", description: "List accounts, providers and recorded emails" },
|
|
24
25
|
{ value: "add", label: "add <id> [alias]", description: "Add an Antigravity account and sign it in" },
|
|
25
26
|
{ value: "login", label: "login <id>", description: "Sign an extra account in (or switch its Google account)" },
|
|
27
|
+
{ value: "apikey", label: "apikey <id>", description: "Set an account's Gemini API key (used instead of its Google login), or clear it" },
|
|
26
28
|
{ value: "alias", label: "alias <id> [alias]", description: "Set or clear an account's alias (provider agy-<alias>)" },
|
|
27
29
|
{ value: "email", label: "email <id> [email]", description: "Set or clear the expected Google account by hand" },
|
|
28
30
|
{ value: "enable", label: "enable <id>", description: "Register a disabled account's provider again" },
|
|
@@ -90,10 +92,10 @@ function completions(manager: AccountManager, prefix: string): AutocompleteItem[
|
|
|
90
92
|
}
|
|
91
93
|
const sub = parts[0];
|
|
92
94
|
if (parts.length > 2) return null; // the account is the only argument that completes
|
|
93
|
-
if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor"].includes(sub)) return null;
|
|
95
|
+
if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor", "apikey"].includes(sub)) return null;
|
|
94
96
|
const typed = parts[1] ?? "";
|
|
95
97
|
const ids = [
|
|
96
|
-
...(["check", "models", "reset", "doctor"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
|
|
98
|
+
...(["check", "models", "reset", "doctor", "apikey"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
|
|
97
99
|
...(sub === "reset" ? [{ id: "all", note: "every account" }] : []),
|
|
98
100
|
...manager.accounts.map((account) => ({
|
|
99
101
|
id: account.id,
|
|
@@ -161,6 +163,12 @@ export async function handle(manager: AccountManager, args: string, ctx: Extensi
|
|
|
161
163
|
case "login":
|
|
162
164
|
await runLogin(manager, extra(), ctx, say);
|
|
163
165
|
return;
|
|
166
|
+
case "apikey": {
|
|
167
|
+
const id = need();
|
|
168
|
+
if (!ctx.hasUI) throw new Error("setting an API key needs the interactive UI (the key is never taken from the command line)");
|
|
169
|
+
await promptApiKey(manager, id, ctx, say);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
164
172
|
case "alias": {
|
|
165
173
|
const id = extra();
|
|
166
174
|
const next = await manager.setAlias(id, rest[0]);
|
package/src/model-catalog.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
// discovery only, so an older agy is never offered a model it does not have.
|
|
8
8
|
|
|
9
9
|
import type { Model } from "@earendil-works/pi-ai";
|
|
10
|
+
import { getBuiltinModels, getBuiltinProviders, type BuiltinProvider } from "@earendil-works/pi-ai/providers/all";
|
|
10
11
|
import type { AcpConfigOption, AcpConfigOptionValue, AcpNewSessionResult } from "./acp/types.ts";
|
|
11
12
|
|
|
12
13
|
export const PROVIDER_ID = "agy";
|
|
@@ -105,6 +106,51 @@ function limitsFor(id: string, observed: number | undefined): Limits {
|
|
|
105
106
|
return observed && observed > 0 ? { ...base, contextWindow: observed } : base;
|
|
106
107
|
}
|
|
107
108
|
|
|
109
|
+
type Cost = AgyModel["cost"];
|
|
110
|
+
const ZERO_COST: Cost = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
111
|
+
/** Whose list price counts for an agy model id: the model's own vendor first, then the big clouds. */
|
|
112
|
+
const PRICE_PROVIDERS = ["google", "anthropic", "google-vertex", "openai", "opencode", "openrouter"];
|
|
113
|
+
let priceIndex: Map<string, Cost> | undefined;
|
|
114
|
+
|
|
115
|
+
function prices(): Map<string, Cost> {
|
|
116
|
+
if (priceIndex) return priceIndex;
|
|
117
|
+
const index = new Map<string, Cost>();
|
|
118
|
+
try {
|
|
119
|
+
const available = new Set<string>(getBuiltinProviders());
|
|
120
|
+
for (const provider of PRICE_PROVIDERS) {
|
|
121
|
+
if (!available.has(provider)) continue;
|
|
122
|
+
for (const model of getBuiltinModels(provider as BuiltinProvider)) {
|
|
123
|
+
const cost = model.cost;
|
|
124
|
+
if (!cost || !(cost.input > 0 || cost.output > 0)) continue;
|
|
125
|
+
const id = model.id.toLowerCase();
|
|
126
|
+
if (id.includes(":batch") || id.endsWith("-batch")) continue;
|
|
127
|
+
for (const key of [id, id.slice(id.lastIndexOf("/") + 1)]) if (!index.has(key)) index.set(key, cost);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
} catch {
|
|
131
|
+
// pi-ai's catalog layout changed: every model stays at zero rather than failing registration.
|
|
132
|
+
}
|
|
133
|
+
priceIndex = index;
|
|
134
|
+
return index;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Reference list price for an agy model, taken from pi's built-in catalog (the same model sold directly by its
|
|
138
|
+
* vendor). Tried in order: the id, the id without a baked-in level (`gpt-oss-120b-medium`), and the id with version
|
|
139
|
+
* dots and dashes swapped (`claude-opus-5-5` / `claude-opus-5.5`). Zero when pi does not know the model. Under a
|
|
140
|
+
* subscription pi labels this as list price covered by the plan; with an API key it is what Google bills. */
|
|
141
|
+
export function referenceCost(id: string): Cost {
|
|
142
|
+
const raw = id.toLowerCase();
|
|
143
|
+
const bases = [raw, raw.replace(FIXED_LEVEL, ""), raw.replace(/-thinking$/, "")];
|
|
144
|
+
const index = prices();
|
|
145
|
+
for (const base of bases) {
|
|
146
|
+
for (const key of [base, base.replace(/(\d)\.(\d)/g, "$1-$2"), base.replace(/(\d)-(\d)(?=$|-)/g, "$1.$2")]) {
|
|
147
|
+
const found = index.get(key);
|
|
148
|
+
if (found) return { ...found, ...(found.tiers ? { tiers: found.tiers.map((tier) => ({ ...tier })) } : {}) };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return { ...ZERO_COST };
|
|
152
|
+
}
|
|
153
|
+
|
|
108
154
|
type LevelMap = NonNullable<AgyModel["thinkingLevelMap"]>;
|
|
109
155
|
|
|
110
156
|
function levelMap(descriptor: AgyModelDescriptor): LevelMap {
|
|
@@ -146,8 +192,8 @@ export function toPiModel(descriptor: AgyModelDescriptor, observedWindow?: numbe
|
|
|
146
192
|
reasoning,
|
|
147
193
|
...(reasoning ? { thinkingLevelMap: levelMap(descriptor) } : {}),
|
|
148
194
|
input: limits.input,
|
|
149
|
-
//
|
|
150
|
-
cost:
|
|
195
|
+
// Reference list price (see referenceCost); the provider's auth marks subscription accounts as plan-covered.
|
|
196
|
+
cost: referenceCost(descriptor.id),
|
|
151
197
|
contextWindow: limits.contextWindow,
|
|
152
198
|
maxTokens: limits.maxTokens,
|
|
153
199
|
};
|
package/src/provider.ts
CHANGED
|
@@ -35,7 +35,13 @@ export function createAgyProvider(runtime: AgyRuntime) {
|
|
|
35
35
|
const ids: ProviderIds = account
|
|
36
36
|
? { provider: providerIdFor(account), api: apiIdFor(account), nameSuffix: ` · ${labelFor(account)}` }
|
|
37
37
|
: DEFAULT_IDS;
|
|
38
|
-
|
|
38
|
+
// Fixed when the provider is registered; a changed sign-in method re-registers the provider (AccountManager).
|
|
39
|
+
const apiKeyMode = runtime.authMode === "api-key";
|
|
40
|
+
const accountName = account
|
|
41
|
+
? `Antigravity · ${labelFor(account)}${apiKeyMode ? " (API key)" : account.email ? ` (${maskEmail(account.email)})` : ""}`
|
|
42
|
+
: apiKeyMode
|
|
43
|
+
? "Antigravity (agy acp, API key)"
|
|
44
|
+
: undefined;
|
|
39
45
|
// A provider registered again (alias rename, account edit) starts from what this account's process already reported,
|
|
40
46
|
// not from the static list: an account on a smaller plan must keep showing only its own models.
|
|
41
47
|
const known = account && runtime.pool.cachedDiscovery ? describeModels(runtime.pool.cachedDiscovery) : [];
|
|
@@ -64,7 +70,7 @@ export function createAgyProvider(runtime: AgyRuntime) {
|
|
|
64
70
|
runtime.trace(`provider.check: unavailable (${reason})`);
|
|
65
71
|
return undefined;
|
|
66
72
|
}
|
|
67
|
-
return { type: "oauth", source: SOURCE };
|
|
73
|
+
return runtime.authMode === "api-key" ? { type: "api_key", source: `${SOURCE}, Gemini API key` } : { type: "oauth", source: SOURCE };
|
|
68
74
|
}, async resolve({ ctx, signal }) {
|
|
69
75
|
signal.throwIfAborted();
|
|
70
76
|
runtime.trace("provider.resolve");
|
|
@@ -75,8 +81,8 @@ export function createAgyProvider(runtime: AgyRuntime) {
|
|
|
75
81
|
// Metadata marker so pi labels list price as subscription-covered. Login and logout belong to agy itself;
|
|
76
82
|
// pi-agy-bridge never reads, stores or forwards Antigravity credentials.
|
|
77
83
|
oauth: {
|
|
78
|
-
name: "Antigravity subscription (managed by agy)",
|
|
79
|
-
isSubscription:
|
|
84
|
+
name: apiKeyMode ? "Antigravity with a Gemini API key (billed per token)" : "Antigravity subscription (managed by agy)",
|
|
85
|
+
isSubscription: !apiKeyMode,
|
|
80
86
|
async login() {
|
|
81
87
|
throw new Error(
|
|
82
88
|
account
|