@timmyjl12/pi-agy-bridge 0.3.3 → 0.4.2
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 +12 -0
- package/README.md +5 -2
- 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 +50 -2
- package/src/accounts.ts +81 -2
- package/src/acp/connection.ts +17 -1
- package/src/config.ts +12 -0
- package/src/conversation-store.ts +231 -0
- package/src/errors.ts +15 -0
- package/src/index.ts +14 -2
- package/src/model-catalog.ts +48 -2
- package/src/provider.ts +10 -4
- package/src/runtime.ts +102 -8
- package/src/session-pool.ts +181 -7
- package/src/stream.ts +88 -6
- package/src/ui/menu.ts +96 -11
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.2" },
|
|
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,12 @@ 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;
|
|
45
|
+
/** Stop a turn that has produced no model output after agy's backend failed this many retried attempts in a row
|
|
46
|
+
* (agy 1.5.18 retries 503/429 silently for minutes). 0 disables and leaves it to the silence guard. */
|
|
47
|
+
backendRetries: number;
|
|
42
48
|
}
|
|
43
49
|
|
|
44
50
|
export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
|
|
@@ -55,6 +61,8 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
|
|
|
55
61
|
controlTimeoutMs: 60_000,
|
|
56
62
|
systemPrompt: "auto",
|
|
57
63
|
refusalProbeMs: 30_000,
|
|
64
|
+
resume: true,
|
|
65
|
+
backendRetries: 3,
|
|
58
66
|
});
|
|
59
67
|
|
|
60
68
|
/** Every environment variable loadConfig reads. pi resolves provider-scoped settings only through auth hooks, so the
|
|
@@ -73,6 +81,8 @@ export const CONFIG_ENV_NAMES = [
|
|
|
73
81
|
"PI_AGY_CONTROL_TIMEOUT_SEC",
|
|
74
82
|
"PI_AGY_SYSTEM_PROMPT",
|
|
75
83
|
"PI_AGY_REFUSAL_PROBE_SEC",
|
|
84
|
+
"PI_AGY_RESUME",
|
|
85
|
+
"PI_AGY_BACKEND_RETRIES",
|
|
76
86
|
] as const;
|
|
77
87
|
|
|
78
88
|
function delivery(value: string | undefined): SystemPromptDelivery {
|
|
@@ -103,5 +113,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
|
|
103
113
|
controlTimeoutMs: positiveInt(env.PI_AGY_CONTROL_TIMEOUT_SEC, DEFAULT_CONFIG.controlTimeoutMs, 1000),
|
|
104
114
|
systemPrompt: delivery(env.PI_AGY_SYSTEM_PROMPT),
|
|
105
115
|
refusalProbeMs: positiveInt(env.PI_AGY_REFUSAL_PROBE_SEC, DEFAULT_CONFIG.refusalProbeMs, 1000),
|
|
116
|
+
resume: !/^(0|false|off|no)$/i.test(env.PI_AGY_RESUME?.trim() ?? ""),
|
|
117
|
+
backendRetries: positiveInt(env.PI_AGY_BACKEND_RETRIES, DEFAULT_CONFIG.backendRetries),
|
|
106
118
|
};
|
|
107
119
|
}
|
|
@@ -0,0 +1,231 @@
|
|
|
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
|
+
/** agy's `steps.step_type` for a failed backend attempt it is about to retry (an ERROR_MESSAGE step). Measured on
|
|
23
|
+
* agy 1.5.17/1.5.18: the payload holds "API error (attempt N): Error 503, Message: …, Status: UNAVAILABLE". agy 1.5.18
|
|
24
|
+
* no longer streams these as message chunks, so this store is the only per-session place they appear. */
|
|
25
|
+
export const ERROR_STEP_TYPE = 17;
|
|
26
|
+
|
|
27
|
+
export type ConversationSinceRecord = "continued" | "prompted" | "lost";
|
|
28
|
+
|
|
29
|
+
export interface BackendAttempt {
|
|
30
|
+
idx: number;
|
|
31
|
+
attempt: number;
|
|
32
|
+
/** The backend error after the colon, e.g. `Error 503, Message: This model is …, Status: UNAVAILABLE`. */
|
|
33
|
+
detail: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The text run ends at the next protobuf control byte (a field tag/length is a byte below 0x20 or a mangled one). */
|
|
37
|
+
const ATTEMPT_TEXT = /API error \(attempt (\d+)\):\s*([^\x00-\x1f\x7f\uFFFD]{1,600})/;
|
|
38
|
+
|
|
39
|
+
/** Pull agy's retry text out of a step payload (a protobuf blob: the text is a plain UTF-8 run inside it). */
|
|
40
|
+
export function parseAttemptPayload(payload: unknown): { attempt: number; detail: string } | undefined {
|
|
41
|
+
const text =
|
|
42
|
+
typeof payload === "string" ? payload : payload instanceof Uint8Array ? Buffer.from(payload).toString("utf8") : undefined;
|
|
43
|
+
if (!text) return undefined;
|
|
44
|
+
const match = ATTEMPT_TEXT.exec(text);
|
|
45
|
+
if (!match) return undefined;
|
|
46
|
+
// "..., Status: UNAVAILABLE, Details: []" may run straight into the next field's printable bytes; cut there.
|
|
47
|
+
const detail = (match[2] as string).replace(/(Details: \[[^\]]*\]).*$/s, "$1").trim();
|
|
48
|
+
return { attempt: Number(match[1]), detail };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Step count of a conversation (the index the next step will get), or undefined when it cannot be read. */
|
|
52
|
+
export async function stepCount(geminiDir: string, sessionId: string): Promise<number | undefined> {
|
|
53
|
+
return (await readConversationSteps(geminiDir, sessionId))?.steps;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** agy's failed backend attempts in this conversation from step `fromStep` on, oldest first. Read-only. */
|
|
57
|
+
export async function readBackendAttempts(geminiDir: string, sessionId: string, fromStep: number): Promise<BackendAttempt[] | undefined> {
|
|
58
|
+
if (!SESSION_ID.test(sessionId)) return undefined;
|
|
59
|
+
const file = conversationDbPath(geminiDir, sessionId);
|
|
60
|
+
if (!existsSync(file)) return undefined;
|
|
61
|
+
const sqlite = await loadSqlite();
|
|
62
|
+
if (!sqlite) return undefined;
|
|
63
|
+
let db: import("node:sqlite").DatabaseSync | undefined;
|
|
64
|
+
try {
|
|
65
|
+
db = new sqlite.DatabaseSync(file, { readOnly: true });
|
|
66
|
+
db.exec("PRAGMA busy_timeout = 1500");
|
|
67
|
+
const rows = db
|
|
68
|
+
.prepare("SELECT idx, step_payload AS payload FROM steps WHERE idx >= ? AND step_type = ? ORDER BY idx")
|
|
69
|
+
.all(fromStep, ERROR_STEP_TYPE) as Array<{ idx: unknown; payload: unknown }>;
|
|
70
|
+
const out: BackendAttempt[] = [];
|
|
71
|
+
for (const row of rows) {
|
|
72
|
+
const parsed = parseAttemptPayload(row.payload);
|
|
73
|
+
if (parsed) out.push({ idx: Number(row.idx), ...parsed });
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
} catch {
|
|
77
|
+
return undefined;
|
|
78
|
+
} finally {
|
|
79
|
+
try {
|
|
80
|
+
db?.close();
|
|
81
|
+
} catch {
|
|
82
|
+
// already read
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function conversationDbPath(geminiDir: string, sessionId: string): string {
|
|
88
|
+
return path.join(geminiDir, "antigravity-cli", "conversations", `${sessionId}.db`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** agy session ids are UUIDs; anything else is never used in a path. */
|
|
92
|
+
const SESSION_ID = /^[A-Za-z0-9-]{8,64}$/;
|
|
93
|
+
|
|
94
|
+
type Sqlite = typeof import("node:sqlite");
|
|
95
|
+
let sqliteModule: Promise<Sqlite | undefined> | undefined;
|
|
96
|
+
|
|
97
|
+
/** node:sqlite (Node >= 22.5). Undefined when unavailable: every check then answers "lost" and the bridge replays. */
|
|
98
|
+
function loadSqlite(): Promise<Sqlite | undefined> {
|
|
99
|
+
sqliteModule ??= import("node:sqlite").then(
|
|
100
|
+
(module) => module,
|
|
101
|
+
() => undefined,
|
|
102
|
+
);
|
|
103
|
+
return sqliteModule;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Read `{steps, userInputs since fromStep}` from agy's conversation db, or undefined when it cannot be read. */
|
|
107
|
+
export async function readConversationSteps(
|
|
108
|
+
geminiDir: string,
|
|
109
|
+
sessionId: string,
|
|
110
|
+
fromStep = 0,
|
|
111
|
+
): Promise<{ steps: number; promptsSince: number } | undefined> {
|
|
112
|
+
if (!SESSION_ID.test(sessionId)) return undefined;
|
|
113
|
+
const file = conversationDbPath(geminiDir, sessionId);
|
|
114
|
+
if (!existsSync(file)) return undefined;
|
|
115
|
+
const sqlite = await loadSqlite();
|
|
116
|
+
if (!sqlite) return undefined;
|
|
117
|
+
let db: import("node:sqlite").DatabaseSync | undefined;
|
|
118
|
+
try {
|
|
119
|
+
db = new sqlite.DatabaseSync(file, { readOnly: true });
|
|
120
|
+
db.exec("PRAGMA busy_timeout = 1500");
|
|
121
|
+
const total = db.prepare("SELECT COUNT(*) AS n FROM steps").get() as { n?: unknown } | undefined;
|
|
122
|
+
const since = db
|
|
123
|
+
.prepare("SELECT COUNT(*) AS n FROM steps WHERE idx >= ? AND step_type = ?")
|
|
124
|
+
.get(fromStep, USER_INPUT_STEP_TYPE) as { n?: unknown } | undefined;
|
|
125
|
+
const steps = Number(total?.n);
|
|
126
|
+
const promptsSince = Number(since?.n);
|
|
127
|
+
return Number.isFinite(steps) && Number.isFinite(promptsSince) ? { steps, promptsSince } : undefined;
|
|
128
|
+
} catch {
|
|
129
|
+
return undefined;
|
|
130
|
+
} finally {
|
|
131
|
+
try {
|
|
132
|
+
db?.close();
|
|
133
|
+
} catch {
|
|
134
|
+
// already read; nothing to release
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** What happened to agy's conversation since the bridge recorded `steps`. Read-only; sends nothing to agy. */
|
|
140
|
+
export async function checkConversation(geminiDir: string, sessionId: string, steps: number): Promise<ConversationSinceRecord> {
|
|
141
|
+
const now = await readConversationSteps(geminiDir, sessionId, steps);
|
|
142
|
+
if (!now || now.steps < steps) return "lost";
|
|
143
|
+
return now.promptsSince > 0 ? "prompted" : "continued";
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---- resume records ----------------------------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
export interface ResumeRecord {
|
|
149
|
+
acpSessionId: string;
|
|
150
|
+
/** Length of the hash chain agy holds (seed + one link per message). */
|
|
151
|
+
chainLength: number;
|
|
152
|
+
/** Last link of that chain. Each link hashes its predecessor, so equal last links at equal length prove the whole
|
|
153
|
+
* prefix (system prompt, tools, model, thinking level and every message) is identical. */
|
|
154
|
+
chainLast: string;
|
|
155
|
+
/** agy's step count when the record was written; the check looks for client prompts after it. */
|
|
156
|
+
steps: number;
|
|
157
|
+
savedAt: number;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
interface ResumeFile {
|
|
161
|
+
version: 1;
|
|
162
|
+
sessions: Record<string, ResumeRecord>;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const MAX_RECORDS = 200;
|
|
166
|
+
|
|
167
|
+
function isRecord(value: unknown): value is ResumeRecord {
|
|
168
|
+
if (!value || typeof value !== "object") return false;
|
|
169
|
+
const r = value as Record<string, unknown>;
|
|
170
|
+
return (
|
|
171
|
+
typeof r.acpSessionId === "string" &&
|
|
172
|
+
SESSION_ID.test(r.acpSessionId) &&
|
|
173
|
+
typeof r.chainLength === "number" &&
|
|
174
|
+
typeof r.chainLast === "string" &&
|
|
175
|
+
typeof r.steps === "number" &&
|
|
176
|
+
typeof r.savedAt === "number"
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** pi session id -> record, persisted next to an account's agy dir. No long-lived cache: every read goes to disk and
|
|
181
|
+
* every change is a read-modify-write of one key, serialized within this process, so records written by another pi
|
|
182
|
+
* process (a subagent, a second window) survive. Two processes writing in the same instant can still lose one record,
|
|
183
|
+
* which only costs that session one replay. */
|
|
184
|
+
export class ResumeStore {
|
|
185
|
+
readonly file: string;
|
|
186
|
+
#writing: Promise<void> = Promise.resolve();
|
|
187
|
+
|
|
188
|
+
constructor(file: string) {
|
|
189
|
+
this.file = file;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async #read(): Promise<Map<string, ResumeRecord>> {
|
|
193
|
+
const map = new Map<string, ResumeRecord>();
|
|
194
|
+
try {
|
|
195
|
+
const parsed = JSON.parse(await readFile(this.file, "utf8")) as Partial<ResumeFile>;
|
|
196
|
+
for (const [key, value] of Object.entries(parsed.sessions ?? {})) if (isRecord(value)) map.set(key, value);
|
|
197
|
+
} catch {
|
|
198
|
+
// missing or unreadable: empty
|
|
199
|
+
}
|
|
200
|
+
return map;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async get(piSessionId: string): Promise<ResumeRecord | undefined> {
|
|
204
|
+
await this.#writing.catch(() => undefined);
|
|
205
|
+
return (await this.#read()).get(piSessionId);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
set(piSessionId: string, record: ResumeRecord): Promise<void> {
|
|
209
|
+
return this.#update((map) => {
|
|
210
|
+
map.delete(piSessionId); // re-insert: most recent last
|
|
211
|
+
map.set(piSessionId, record);
|
|
212
|
+
while (map.size > MAX_RECORDS) map.delete(map.keys().next().value as string);
|
|
213
|
+
return true;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
delete(piSessionId: string): Promise<void> {
|
|
218
|
+
return this.#update((map) => map.delete(piSessionId));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
#update(change: (map: Map<string, ResumeRecord>) => boolean): Promise<void> {
|
|
222
|
+
const run = async (): Promise<void> => {
|
|
223
|
+
const map = await this.#read();
|
|
224
|
+
if (!change(map)) return;
|
|
225
|
+
const body: ResumeFile = { version: 1, sessions: Object.fromEntries(map) };
|
|
226
|
+
await writeFileAtomic(this.file, `${JSON.stringify(body)}\n`);
|
|
227
|
+
};
|
|
228
|
+
this.#writing = this.#writing.then(run, run);
|
|
229
|
+
return this.#writing;
|
|
230
|
+
}
|
|
231
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -83,6 +83,21 @@ export function exhaustedError(notice: ApiRetryNotice, context: string): AgyErro
|
|
|
83
83
|
return new AgyError("quota", `agy quota exceeded: Antigravity answered ${notice.detail} (${context})`);
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/** agy's backend kept failing while the turn had produced nothing (agy 1.5.18 retries silently; the failures are read
|
|
87
|
+
* from its conversation store). Worded for the classifiers: a 429/RESOURCE_EXHAUSTED one is a quota (provider cap,
|
|
88
|
+
* rotate); anything else (503 "high demand", "No capacity available for model X") is "unavailable", which
|
|
89
|
+
* pi-fallback-chains retries on another model, without the words "quota" or "capacity" so siblings stay eligible. */
|
|
90
|
+
export function backendFailedError(attempts: number, detail: string, context: string): AgyError {
|
|
91
|
+
const text = detail.replace(/\s+/g, " ").replace(/,?\s*Details: \[\]\s*$/, "").trim().slice(0, 300);
|
|
92
|
+
if (/resource_exhausted|\b429\b|quota/i.test(text)) {
|
|
93
|
+
return new AgyError("quota", `agy quota exceeded: Antigravity refused ${attempts} attempts in a row: ${text} (${context})`);
|
|
94
|
+
}
|
|
95
|
+
// "No capacity available for model X" is that one model's problem, but the classifier reads a bare "capacity" as a
|
|
96
|
+
// provider-wide cap and would skip the account's other models. Say it without that word.
|
|
97
|
+
const safe = text.replace(/no capacity available for model (\S+)/gi, "model $1 has no free servers").replace(/\bcapacity\b/gi, "load");
|
|
98
|
+
return new AgyError("other", `agy backend unavailable: Antigravity failed ${attempts} attempts in a row: ${safe} (${context})`);
|
|
99
|
+
}
|
|
100
|
+
|
|
86
101
|
/** The silence guard fired: no ACP traffic for `ms`. */
|
|
87
102
|
export function stalledError(ms: number): AgyError {
|
|
88
103
|
const seconds = ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
|
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,8 @@ 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" },
|
|
28
|
+
{ value: "use-agy-login", label: "use-agy-login <id>", description: "Remove an account's API key and go back to its agy Google login" },
|
|
26
29
|
{ value: "alias", label: "alias <id> [alias]", description: "Set or clear an account's alias (provider agy-<alias>)" },
|
|
27
30
|
{ value: "email", label: "email <id> [email]", description: "Set or clear the expected Google account by hand" },
|
|
28
31
|
{ value: "enable", label: "enable <id>", description: "Register a disabled account's provider again" },
|
|
@@ -90,10 +93,10 @@ function completions(manager: AccountManager, prefix: string): AutocompleteItem[
|
|
|
90
93
|
}
|
|
91
94
|
const sub = parts[0];
|
|
92
95
|
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;
|
|
96
|
+
if (!["login", "alias", "email", "enable", "disable", "remove", "check", "models", "reset", "doctor", "apikey", "use-agy-login"].includes(sub)) return null;
|
|
94
97
|
const typed = parts[1] ?? "";
|
|
95
98
|
const ids = [
|
|
96
|
-
...(["check", "models", "reset", "doctor"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
|
|
99
|
+
...(["check", "models", "reset", "doctor", "apikey", "use-agy-login"].includes(sub) ? [{ id: DEFAULT_ACCOUNT, note: "agy (default)" }] : []),
|
|
97
100
|
...(sub === "reset" ? [{ id: "all", note: "every account" }] : []),
|
|
98
101
|
...manager.accounts.map((account) => ({
|
|
99
102
|
id: account.id,
|
|
@@ -161,6 +164,15 @@ export async function handle(manager: AccountManager, args: string, ctx: Extensi
|
|
|
161
164
|
case "login":
|
|
162
165
|
await runLogin(manager, extra(), ctx, say);
|
|
163
166
|
return;
|
|
167
|
+
case "use-agy-login":
|
|
168
|
+
await runAccountAction(manager, need(), "googlelogin", ctx, say);
|
|
169
|
+
return;
|
|
170
|
+
case "apikey": {
|
|
171
|
+
const id = need();
|
|
172
|
+
if (!ctx.hasUI) throw new Error("setting an API key needs the interactive UI (the key is never taken from the command line)");
|
|
173
|
+
await promptApiKey(manager, id, ctx, say);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
164
176
|
case "alias": {
|
|
165
177
|
const id = extra();
|
|
166
178
|
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
|
package/src/runtime.ts
CHANGED
|
@@ -5,12 +5,16 @@ import path from "node:path";
|
|
|
5
5
|
import {
|
|
6
6
|
accountPaths,
|
|
7
7
|
accountProcessPaths,
|
|
8
|
+
apiKeyPathsFor,
|
|
8
9
|
DEFAULT_ACCOUNT,
|
|
9
10
|
FILE_STORAGE_ENV,
|
|
10
11
|
maskEmail,
|
|
12
|
+
readApiKey,
|
|
13
|
+
withoutApiKeys,
|
|
11
14
|
rotateAccountLog,
|
|
12
15
|
waitForIdentity,
|
|
13
16
|
type AccountRecord,
|
|
17
|
+
type AuthMode,
|
|
14
18
|
type Identity,
|
|
15
19
|
} from "./accounts.ts";
|
|
16
20
|
import { findAgyCommand } from "./acp/command.ts";
|
|
@@ -31,6 +35,8 @@ export interface RuntimeOptions {
|
|
|
31
35
|
log?: (message: string) => void;
|
|
32
36
|
/** The Antigravity account this runtime serves. Absent = the default (keyring) account, exactly as before. */
|
|
33
37
|
account?: AccountRecord;
|
|
38
|
+
/** Sign-in method of the default account (extra accounts carry theirs in `account.auth`). Absent = google. */
|
|
39
|
+
defaultAuth?: AuthMode;
|
|
34
40
|
/** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
|
|
35
41
|
* (default 10 s; agy writes it during that call, so normally no wait at all). */
|
|
36
42
|
identityTimeoutMs?: number;
|
|
@@ -79,10 +85,12 @@ export class AgyRuntime {
|
|
|
79
85
|
#writes = new Set<Promise<void>>();
|
|
80
86
|
#account: AccountRecord | undefined;
|
|
81
87
|
#identity: AccountIdentityState | undefined;
|
|
88
|
+
#defaultAuth: AuthMode;
|
|
82
89
|
|
|
83
90
|
constructor(options: RuntimeOptions = {}) {
|
|
84
91
|
this.#options = options;
|
|
85
92
|
this.#account = options.account && options.account.id !== DEFAULT_ACCOUNT ? { ...options.account } : undefined;
|
|
93
|
+
this.#defaultAuth = options.defaultAuth ?? "google";
|
|
86
94
|
this.config = loadConfig(options.env ?? process.env);
|
|
87
95
|
const trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
|
|
88
96
|
this.trace = this.#account ? (message) => trace(`[${this.accountLabel}] ${message}`) : trace;
|
|
@@ -108,18 +116,66 @@ export class AgyRuntime {
|
|
|
108
116
|
return this.#account ? accountPaths(this.config.home, this.#account.id).root : this.config.home;
|
|
109
117
|
}
|
|
110
118
|
|
|
111
|
-
/**
|
|
119
|
+
/** How this account signs in. */
|
|
120
|
+
get authMode(): AuthMode {
|
|
121
|
+
return this.#account ? (this.#account.auth ?? "google") : this.#defaultAuth;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Change alias/email/enabled/auth of the bound account. A changed email or sign-in method stops the process (and,
|
|
125
|
+
* for the method, rebuilds the pool on its own agy dir) so the next use starts with the new identity. */
|
|
112
126
|
updateAccount(next: AccountRecord): void {
|
|
113
127
|
if (!this.#account || next.id !== this.#account.id) return;
|
|
114
128
|
const emailChanged = next.email !== this.#account.email;
|
|
129
|
+
const authChanged = (next.auth ?? "google") !== (this.#account.auth ?? "google");
|
|
115
130
|
this.#account = { ...next };
|
|
116
|
-
if (
|
|
131
|
+
if (authChanged) {
|
|
132
|
+
this.#identity = undefined;
|
|
133
|
+
this.#rebuildPool("sign-in method changed");
|
|
134
|
+
} else if (emailChanged) {
|
|
117
135
|
this.#identity = undefined;
|
|
118
136
|
void this.#pool.reset().catch((error: unknown) => this.trace(`reset after account change failed: ${describeError(error)}`));
|
|
119
137
|
this.#pool.resetDiscovery();
|
|
120
138
|
}
|
|
121
139
|
}
|
|
122
140
|
|
|
141
|
+
/** Switch the default account's sign-in method (extra accounts go through updateAccount). */
|
|
142
|
+
setDefaultAuth(mode: AuthMode): void {
|
|
143
|
+
if (this.#account || mode === this.#defaultAuth) return;
|
|
144
|
+
this.#defaultAuth = mode;
|
|
145
|
+
this.#rebuildPool("sign-in method changed");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The stored API key was replaced (same mode): the next process must start with the new key. */
|
|
149
|
+
async apiKeyChanged(): Promise<void> {
|
|
150
|
+
if (this.authMode !== "api-key") return;
|
|
151
|
+
await this.clearUnusable();
|
|
152
|
+
await this.#pool.reset();
|
|
153
|
+
this.#pool.resetDiscovery();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Where this account's API key and API-key agy dir live. */
|
|
157
|
+
get apiKeyPaths(): { root: string; apiKeyGeminiDir: string; apiKeyFile: string } {
|
|
158
|
+
return apiKeyPathsFor(this.config.home, this.#account?.id ?? DEFAULT_ACCOUNT);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The key an API-key process uses: only the one stored through the menu. The environment is never consulted, so a
|
|
162
|
+
* GEMINI_API_KEY exported for other tools cannot silently move an account off its subscription login. */
|
|
163
|
+
async resolveApiKey(): Promise<string | undefined> {
|
|
164
|
+
return readApiKey(this.apiKeyPaths.apiKeyFile);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#rebuildPool(reason: string): void {
|
|
168
|
+
const old = this.#pool;
|
|
169
|
+
this.#pool = this.#createPool();
|
|
170
|
+
this.trace(`pool rebuilt (${reason}); auth=${this.authMode}`);
|
|
171
|
+
const retired: Promise<void> = old.dispose().then(
|
|
172
|
+
() => undefined,
|
|
173
|
+
(error: unknown) => this.#options.log?.(`retired agy pool failed to stop: ${describeError(error)}`),
|
|
174
|
+
);
|
|
175
|
+
this.#retiring.add(retired);
|
|
176
|
+
void retired.finally(() => this.#retiring.delete(retired));
|
|
177
|
+
}
|
|
178
|
+
|
|
123
179
|
/** Forget a recorded "unusable" hint (after a successful sign-in) so the provider is offered again at once. */
|
|
124
180
|
async clearUnusable(): Promise<void> {
|
|
125
181
|
this.#hintRecorded = false;
|
|
@@ -157,18 +213,53 @@ export class AgyRuntime {
|
|
|
157
213
|
const account = this.#account;
|
|
158
214
|
const paths = account ? accountProcessPaths(this.config.home, account.id, this.#options.accountLogOwner) : undefined;
|
|
159
215
|
const baseEnv = this.#options.pool?.env;
|
|
216
|
+
const apiKey = this.authMode === "api-key";
|
|
217
|
+
const keyPaths = this.apiKeyPaths;
|
|
218
|
+
// API-key mode: agy's own `gemini-api-key` method in a dir of its own (agy caches the method per dir), the key in
|
|
219
|
+
// the child's GEMINI_API_KEY only, no SSH marker and no email guard (an API key has no Google identity).
|
|
220
|
+
const googleAccount = account && !apiKey ? paths : undefined;
|
|
221
|
+
const workDir = paths ? path.join(paths.root, "work") : undefined;
|
|
222
|
+
// Google mode never sees an API key from the environment: agy must serve the account's own signed-in login.
|
|
223
|
+
const googleEnv = withoutApiKeys(baseEnv ?? process.env);
|
|
160
224
|
const pool = new SessionPool({
|
|
161
225
|
config: this.config,
|
|
162
226
|
buildArgs: this.#options.pool?.buildArgs,
|
|
163
|
-
env:
|
|
164
|
-
...(
|
|
227
|
+
env: apiKey ? googleEnv : googleAccount ? { ...googleEnv, ...FILE_STORAGE_ENV } : googleEnv,
|
|
228
|
+
...(apiKey
|
|
229
|
+
? {
|
|
230
|
+
authMethod: "gemini-api-key",
|
|
231
|
+
stagingOverride: { geminiDir: keyPaths.apiKeyGeminiDir, ...(workDir ? { workDir } : {}) },
|
|
232
|
+
resolveEnv: async () => {
|
|
233
|
+
const key = await this.resolveApiKey();
|
|
234
|
+
if (!key) {
|
|
235
|
+
throw new AgyError(
|
|
236
|
+
"auth",
|
|
237
|
+
`agy authentication required (not logged in): the stored Gemini API key for ${this.#account ? `account ${this.#account.id}` : "the default account"} is gone; set it again in /agy-bridge menu or remove it to use the Google login`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
return { ...googleEnv, GEMINI_API_KEY: key };
|
|
241
|
+
},
|
|
242
|
+
...(paths || this.#options.pool?.buildArgs
|
|
243
|
+
? {
|
|
244
|
+
extraArgs: (staging: { geminiDir: string }) => [
|
|
245
|
+
...(this.#options.pool?.buildArgs ? ["--gemini-dir", staging.geminiDir] : []),
|
|
246
|
+
...(paths ? ["--log-file", paths.logFile] : []),
|
|
247
|
+
],
|
|
248
|
+
...(paths ? { beforeStart: () => rotateAccountLog(paths) } : {}),
|
|
249
|
+
}
|
|
250
|
+
: {}),
|
|
251
|
+
}
|
|
252
|
+
: {}),
|
|
253
|
+
...(googleAccount
|
|
165
254
|
? {
|
|
166
|
-
stagingOverride: { geminiDir:
|
|
255
|
+
stagingOverride: { geminiDir: googleAccount.geminiDir, workDir: path.join(googleAccount.root, "work") },
|
|
167
256
|
extraArgs: (staging) =>
|
|
168
257
|
// The real argv already names the gemini dir through the staging override; a test argv may not.
|
|
169
|
-
this.#options.pool?.buildArgs
|
|
170
|
-
|
|
171
|
-
|
|
258
|
+
this.#options.pool?.buildArgs
|
|
259
|
+
? ["--gemini-dir", staging.geminiDir, "--log-file", googleAccount.logFile]
|
|
260
|
+
: ["--log-file", googleAccount.logFile],
|
|
261
|
+
beforeStart: () => rotateAccountLog(googleAccount),
|
|
262
|
+
verifyProcess: (proc, sessionFailure) => this.#checkIdentity(googleAccount.logFile, proc, sessionFailure),
|
|
172
263
|
}
|
|
173
264
|
: {}),
|
|
174
265
|
log: this.trace,
|
|
@@ -248,6 +339,9 @@ export class AgyRuntime {
|
|
|
248
339
|
if (!found) {
|
|
249
340
|
return { available: false, reason: `agy was not found (command "${this.config.command}"); install the Antigravity CLI or set PI_AGY_COMMAND` };
|
|
250
341
|
}
|
|
342
|
+
if (this.authMode === "api-key" && !(await this.resolveApiKey())) {
|
|
343
|
+
return { available: false, reason: "the stored Gemini API key is gone: set it again in /agy-bridge menu" };
|
|
344
|
+
}
|
|
251
345
|
const state = await readState(this.stateDir);
|
|
252
346
|
const bad = state.unusable;
|
|
253
347
|
if (bad && Date.now() - bad.at < UNUSABLE_HINT_MS) {
|