@timmyjl12/pi-agy-bridge 0.3.3 → 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 +8 -0
- package/README.md +4 -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 +46 -2
- package/src/accounts.ts +81 -2
- package/src/acp/connection.ts +17 -1
- package/src/config.ts +6 -0
- package/src/conversation-store.ts +168 -0
- package/src/index.ts +10 -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 +178 -7
- package/src/stream.ts +36 -3
- package/src/ui/menu.ts +69 -11
package/src/session-pool.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// into a fresh session, which is always correct.
|
|
9
9
|
|
|
10
10
|
import { mkdir } from "node:fs/promises";
|
|
11
|
+
import path from "node:path";
|
|
11
12
|
import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";
|
|
12
13
|
import { resolveAgyCommand } from "./acp/command.ts";
|
|
13
14
|
import { AcpProcess } from "./acp/connection.ts";
|
|
@@ -15,6 +16,7 @@ import { ensureStaging, type Staging } from "./acp/staging.ts";
|
|
|
15
16
|
import type { AcpConfigOption, AcpInitializeResult, AcpNewSessionResult } from "./acp/types.ts";
|
|
16
17
|
import type { AgyFeatures } from "./compat/features.ts";
|
|
17
18
|
import type { AgyConfig } from "./config.ts";
|
|
19
|
+
import { checkConversation, readConversationSteps, ResumeStore } from "./conversation-store.ts";
|
|
18
20
|
import { AgyError, describeError, normalizeAgyError } from "./errors.ts";
|
|
19
21
|
import { registerHistoryRewriteHook } from "./pi-context-hook.ts";
|
|
20
22
|
import { isLinearContinuation } from "./transcript.ts";
|
|
@@ -85,10 +87,17 @@ export interface PoolOptions {
|
|
|
85
87
|
* failure. */
|
|
86
88
|
verifyProcess?: (proc: AcpProcess, sessionFailure: unknown) => Promise<void>;
|
|
87
89
|
env?: NodeJS.ProcessEnv;
|
|
90
|
+
/** Resolved right before each spawn (wins over `env`): an API-key account adds its key here, so a key changed in the
|
|
91
|
+
* menu is used by the next process without rebuilding the pool. A throw fails the start with that error. */
|
|
92
|
+
resolveEnv?: () => Promise<NodeJS.ProcessEnv | undefined>;
|
|
93
|
+
/** ACP auth method to select right after `initialize` (API-key accounts: `gemini-api-key`). */
|
|
94
|
+
authMethod?: string;
|
|
95
|
+
/** Reattach continued pi sessions to agy's own stored conversation with `session/resume` (default true). */
|
|
96
|
+
resume?: boolean;
|
|
88
97
|
log?: (message: string) => void;
|
|
89
98
|
onHealth?: (event: HealthEvent) => void;
|
|
90
99
|
/** Negotiated optional features, read when a session opens (after the handshake). Absent = assume supported. */
|
|
91
|
-
features?: () => Pick<AgyFeatures, "systemPromptAppend" | "sessionClose"
|
|
100
|
+
features?: () => Pick<AgyFeatures, "systemPromptAppend" | "sessionClose"> & Partial<Pick<AgyFeatures, "sessionResume">>;
|
|
92
101
|
}
|
|
93
102
|
|
|
94
103
|
interface Entry {
|
|
@@ -107,6 +116,8 @@ interface Entry {
|
|
|
107
116
|
systemInline: boolean;
|
|
108
117
|
lastUsed: number;
|
|
109
118
|
timer: NodeJS.Timeout | undefined;
|
|
119
|
+
/** Bumped on every lease: a resume record started for an earlier turn is dropped once the session moved on. */
|
|
120
|
+
generation?: number;
|
|
110
121
|
}
|
|
111
122
|
|
|
112
123
|
function firstDifference(a: readonly string[], b: readonly string[]): number {
|
|
@@ -145,6 +156,11 @@ export class SessionPool {
|
|
|
145
156
|
/** Processes whose identity check passed (see PoolOptions.verifyProcess). */
|
|
146
157
|
readonly #verified = new WeakSet<AcpProcess>();
|
|
147
158
|
readonly #verifying = new WeakMap<AcpProcess, Promise<void>>();
|
|
159
|
+
#resumeStore: ResumeStore | undefined;
|
|
160
|
+
/** agy conversations being reattached right now: a concurrent request for the same one replays instead. */
|
|
161
|
+
readonly #resuming = new Set<string>();
|
|
162
|
+
/** Record writes in flight (awaited by dispose/reset so a test or shutdown never races a half-written file). */
|
|
163
|
+
readonly #recording = new Set<Promise<void>>();
|
|
148
164
|
|
|
149
165
|
constructor(options: PoolOptions) {
|
|
150
166
|
this.#options = options;
|
|
@@ -219,11 +235,18 @@ export class SessionPool {
|
|
|
219
235
|
this.#options.log?.(`beforeStart failed: ${describeError(error)}`);
|
|
220
236
|
throw new AgyError("spawn", `agy spawn failed: could not prepare the account log (${code}); retry`, { cause: error });
|
|
221
237
|
}
|
|
238
|
+
let env = this.#options.env;
|
|
239
|
+
try {
|
|
240
|
+
env = (await this.#options.resolveEnv?.()) ?? env;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
this.#reportFailure(error);
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
222
245
|
const proc = AcpProcess.start({
|
|
223
246
|
command,
|
|
224
247
|
args,
|
|
225
248
|
cwd: staging.workDir,
|
|
226
|
-
env
|
|
249
|
+
env,
|
|
227
250
|
controlTimeoutMs: this.#config.controlTimeoutMs,
|
|
228
251
|
onStderr: this.#options.log ? (chunk) => this.#options.log?.(`agy stderr: ${chunk.trimEnd()}`) : undefined,
|
|
229
252
|
});
|
|
@@ -242,6 +265,22 @@ export class SessionPool {
|
|
|
242
265
|
this.#reportFailure(error);
|
|
243
266
|
throw error;
|
|
244
267
|
}
|
|
268
|
+
const method = this.#options.authMethod;
|
|
269
|
+
if (method) {
|
|
270
|
+
const offered = (init.authMethods ?? []).map((entry) => entry.id);
|
|
271
|
+
try {
|
|
272
|
+
if (!offered.includes(method)) {
|
|
273
|
+
throw new AgyError("compat", `pi-agy-bridge is unavailable: agy does not offer the ${method} sign-in method (offers ${offered.join(", ") || "none"})`);
|
|
274
|
+
}
|
|
275
|
+
await proc.authenticate(method).catch((error: unknown) => {
|
|
276
|
+
throw new AgyError("auth", `agy authentication required (not logged in): the ${method} sign-in was refused: ${describeError(error)}`, { cause: error });
|
|
277
|
+
});
|
|
278
|
+
} catch (error) {
|
|
279
|
+
await proc.dispose();
|
|
280
|
+
this.#reportFailure(error);
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
245
284
|
if (!this.#open) {
|
|
246
285
|
await proc.dispose();
|
|
247
286
|
throw new AgyError("exited", "agy is unavailable: pi-agy-bridge is shut down");
|
|
@@ -261,13 +300,19 @@ export class SessionPool {
|
|
|
261
300
|
* fails the check is stopped; a failed `session/new` on an unverified process is still checked, because agy reports
|
|
262
301
|
* a missing login exactly that way and the guard words it for the user. */
|
|
263
302
|
async #newSession(proc: AcpProcess, params: { cwd: string; systemPromptAppend?: string }): Promise<AcpNewSessionResult> {
|
|
303
|
+
return this.#verifiedOpen(proc, () => proc.newSession(params));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Open a session (`session/new` or `session/resume`) on a process whose identity is checked once, before the first
|
|
307
|
+
* session it serves. A resumed session must pass the same guard: after a restart it may be the process's first. */
|
|
308
|
+
async #verifiedOpen(proc: AcpProcess, open: () => Promise<AcpNewSessionResult>): Promise<AcpNewSessionResult> {
|
|
264
309
|
const verify = this.#options.verifyProcess;
|
|
265
|
-
if (!verify || this.#verified.has(proc)) return
|
|
310
|
+
if (!verify || this.#verified.has(proc)) return open();
|
|
266
311
|
// Single-flight: concurrent first callers wait for one verification instead of each racing their own.
|
|
267
312
|
const pending = this.#verifying.get(proc);
|
|
268
313
|
if (pending) {
|
|
269
314
|
await pending;
|
|
270
|
-
return
|
|
315
|
+
return open();
|
|
271
316
|
}
|
|
272
317
|
let release: () => void = () => undefined;
|
|
273
318
|
let fail: (error: unknown) => void = () => undefined;
|
|
@@ -281,7 +326,7 @@ export class SessionPool {
|
|
|
281
326
|
let created: AcpNewSessionResult | undefined;
|
|
282
327
|
let failure: unknown;
|
|
283
328
|
try {
|
|
284
|
-
created = await
|
|
329
|
+
created = await open();
|
|
285
330
|
} catch (error) {
|
|
286
331
|
failure = error;
|
|
287
332
|
}
|
|
@@ -436,11 +481,135 @@ export class SessionPool {
|
|
|
436
481
|
reusable.timer = undefined;
|
|
437
482
|
return this.#lease(reusable, true);
|
|
438
483
|
}
|
|
484
|
+
const resumed = await this.#tryResume(proc, request);
|
|
485
|
+
if (resumed) {
|
|
486
|
+
resumed.leasedAtSeq = seq;
|
|
487
|
+
return this.#lease(resumed, true);
|
|
488
|
+
}
|
|
439
489
|
const entry = await this.#openFresh(proc, request);
|
|
440
490
|
entry.leasedAtSeq = seq;
|
|
441
491
|
return this.#lease(entry, false);
|
|
442
492
|
}
|
|
443
493
|
|
|
494
|
+
// ---- resume across processes -------------------------------------------------------------------------------
|
|
495
|
+
|
|
496
|
+
#resumeEnabled(): boolean {
|
|
497
|
+
return this.#options.resume !== false && this.#config.resume !== false && this.#options.features?.().sessionResume === true;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** The record file lives beside agy's dir (`<gemini-dir>.resume.json`): one per account and auth mode. */
|
|
501
|
+
#store(): ResumeStore | undefined {
|
|
502
|
+
const geminiDir = this.#staging?.geminiDir;
|
|
503
|
+
if (!geminiDir) return undefined;
|
|
504
|
+
this.#resumeStore ??= new ResumeStore(path.join(path.dirname(geminiDir), `${path.basename(geminiDir)}.resume.json`));
|
|
505
|
+
return this.#resumeStore;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Reattach a continued pi session to the agy conversation that already holds its prefix (a previous process, a pi
|
|
509
|
+
* restart). Only when the record matches the request's chain exactly and agy's own store shows no client prompt
|
|
510
|
+
* since; everything else returns undefined and the caller replays into a fresh session, as before. */
|
|
511
|
+
async #tryResume(proc: AcpProcess, request: SessionRequest): Promise<Entry | undefined> {
|
|
512
|
+
const log = this.#options.log;
|
|
513
|
+
if (!request.piSessionId || request.latestCount <= 0 || !this.#resumeEnabled()) return undefined;
|
|
514
|
+
const store = this.#store();
|
|
515
|
+
const geminiDir = this.#staging?.geminiDir;
|
|
516
|
+
if (!store || !geminiDir) return undefined;
|
|
517
|
+
const record = await store.get(request.piSessionId).catch(() => undefined);
|
|
518
|
+
if (!record) return undefined;
|
|
519
|
+
const held = request.chain.length - request.latestCount;
|
|
520
|
+
if (record.chainLength !== held || request.chain[held - 1] !== record.chainLast) {
|
|
521
|
+
log?.(`resume: skipped (recorded conversation holds ${record.chainLength - 1} messages, request continues from ${held - 1}${record.chainLength === held ? "; context differs" : ""})`);
|
|
522
|
+
return undefined;
|
|
523
|
+
}
|
|
524
|
+
if (this.#resuming.has(record.acpSessionId) || [...this.#entries].some((entry) => entry.acpSessionId === record.acpSessionId)) {
|
|
525
|
+
log?.("resume: skipped (that agy conversation is open in this process)");
|
|
526
|
+
return undefined;
|
|
527
|
+
}
|
|
528
|
+
this.#resuming.add(record.acpSessionId);
|
|
529
|
+
try {
|
|
530
|
+
return await this.#resume(proc, request, record, held, store, geminiDir);
|
|
531
|
+
} finally {
|
|
532
|
+
this.#resuming.delete(record.acpSessionId);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async #resume(
|
|
537
|
+
proc: AcpProcess,
|
|
538
|
+
request: SessionRequest,
|
|
539
|
+
record: NonNullable<Awaited<ReturnType<ResumeStore["get"]>>>,
|
|
540
|
+
held: number,
|
|
541
|
+
store: ResumeStore,
|
|
542
|
+
geminiDir: string,
|
|
543
|
+
): Promise<Entry | undefined> {
|
|
544
|
+
const log = this.#options.log;
|
|
545
|
+
const piSessionId = request.piSessionId as string;
|
|
546
|
+
const since = await checkConversation(geminiDir, record.acpSessionId, record.steps);
|
|
547
|
+
if (since !== "continued") {
|
|
548
|
+
log?.(`resume: skipped (agy conversation ${since === "prompted" ? "was prompted by another client or branch" : "is gone or unreadable"})`);
|
|
549
|
+
await store.delete(piSessionId).catch(() => undefined);
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
try {
|
|
553
|
+
await this.#verifiedOpen(proc, () => proc.resumeSession({ sessionId: record.acpSessionId, cwd: this.#staging?.workDir ?? this.#config.home }));
|
|
554
|
+
await proc.setConfigOption(record.acpSessionId, "model", request.modelId);
|
|
555
|
+
if (request.thoughtLevel) await proc.setConfigOption(record.acpSessionId, "thought_level", request.thoughtLevel);
|
|
556
|
+
} catch (error) {
|
|
557
|
+
log?.(`resume: failed, replaying instead (${describeError(error)})`);
|
|
558
|
+
await store.delete(piSessionId).catch(() => undefined);
|
|
559
|
+
if (this.#canClose()) void this.#track(proc.closeSession(record.acpSessionId));
|
|
560
|
+
if (!proc.alive) throw error;
|
|
561
|
+
return undefined;
|
|
562
|
+
}
|
|
563
|
+
log?.(`resume: reattached agy conversation ${record.acpSessionId.slice(0, 8)} (${held - 1} messages, no replay)`);
|
|
564
|
+
const entry: Entry = {
|
|
565
|
+
process: proc,
|
|
566
|
+
acpSessionId: record.acpSessionId,
|
|
567
|
+
piSessionId,
|
|
568
|
+
chain: request.chain.slice(0, held),
|
|
569
|
+
busy: true,
|
|
570
|
+
stale: false,
|
|
571
|
+
waitingForTool: false,
|
|
572
|
+
leasedAtSeq: 0,
|
|
573
|
+
systemInline: false,
|
|
574
|
+
lastUsed: Date.now(),
|
|
575
|
+
timer: undefined,
|
|
576
|
+
};
|
|
577
|
+
this.#entries.add(entry);
|
|
578
|
+
return entry;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** Remember which agy conversation holds this pi session's chain, with agy's current step count. */
|
|
582
|
+
#record(entry: Entry): void {
|
|
583
|
+
const piSessionId = entry.piSessionId;
|
|
584
|
+
const geminiDir = this.#staging?.geminiDir;
|
|
585
|
+
const store = this.#resumeEnabled() ? this.#store() : undefined;
|
|
586
|
+
if (!piSessionId || !geminiDir || !store || entry.chain.length === 0) return;
|
|
587
|
+
const chain = entry.chain;
|
|
588
|
+
const generation = entry.generation ?? 0;
|
|
589
|
+
// Only valid while the session is idle at this chain: once it is leased again agy's step count belongs to a later
|
|
590
|
+
// turn (a record pairing this chain with those steps would hide that turn's prompt from the resume check).
|
|
591
|
+
const current = (): boolean => !entry.busy && (entry.generation ?? 0) === generation && entry.chain === chain;
|
|
592
|
+
const task = (async () => {
|
|
593
|
+
const now = await readConversationSteps(geminiDir, entry.acpSessionId);
|
|
594
|
+
if (!now) return; // agy has not written it (or the store is unreadable): nothing safe to record
|
|
595
|
+
if (!current()) return;
|
|
596
|
+
await store.set(piSessionId, {
|
|
597
|
+
acpSessionId: entry.acpSessionId,
|
|
598
|
+
chainLength: chain.length,
|
|
599
|
+
chainLast: chain[chain.length - 1] as string,
|
|
600
|
+
steps: now.steps,
|
|
601
|
+
savedAt: Date.now(),
|
|
602
|
+
});
|
|
603
|
+
})().catch((error: unknown) => this.#options.log?.(`resume: record not written (${describeError(error)})`));
|
|
604
|
+
const tracked = task.finally(() => this.#recording.delete(tracked));
|
|
605
|
+
this.#recording.add(tracked);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Wait for resume records that are being written. */
|
|
609
|
+
async flushRecords(): Promise<void> {
|
|
610
|
+
await Promise.allSettled([...this.#recording]);
|
|
611
|
+
}
|
|
612
|
+
|
|
444
613
|
/** Was this pi session (or everything) invalidated after `seq`? */
|
|
445
614
|
#invalidatedSince(piSessionId: string | undefined, seq: number): boolean {
|
|
446
615
|
if (this.#invalidatedAll > seq) return true;
|
|
@@ -508,6 +677,7 @@ export class SessionPool {
|
|
|
508
677
|
}
|
|
509
678
|
|
|
510
679
|
#lease(entry: Entry, reused: boolean): Lease {
|
|
680
|
+
entry.generation = (entry.generation ?? 0) + 1;
|
|
511
681
|
let finished = false;
|
|
512
682
|
return {
|
|
513
683
|
process: entry.process,
|
|
@@ -534,6 +704,7 @@ export class SessionPool {
|
|
|
534
704
|
entry.chain = outcome.chain;
|
|
535
705
|
entry.waitingForTool = outcome.awaitingTool === true;
|
|
536
706
|
entry.lastUsed = Date.now();
|
|
707
|
+
this.#record(entry);
|
|
537
708
|
this.#armTtl(entry);
|
|
538
709
|
this.#trim();
|
|
539
710
|
} else {
|
|
@@ -607,7 +778,7 @@ export class SessionPool {
|
|
|
607
778
|
this.#entries.delete(entry);
|
|
608
779
|
}
|
|
609
780
|
await this.#stopProcess("dispose");
|
|
610
|
-
await Promise.allSettled([...this.#closing]);
|
|
781
|
+
await Promise.allSettled([...this.#closing, ...this.#recording]);
|
|
611
782
|
}
|
|
612
783
|
|
|
613
784
|
/** Kill one specific agy process that stopped answering (a turn ignored its cancel). Other turns on it fail with
|
|
@@ -623,7 +794,7 @@ export class SessionPool {
|
|
|
623
794
|
this.resetDiscovery();
|
|
624
795
|
await this.#stopProcess("reset");
|
|
625
796
|
if (this.#starting) await this.#starting.catch(() => undefined);
|
|
626
|
-
await Promise.allSettled([...this.#closing]);
|
|
797
|
+
await Promise.allSettled([...this.#closing, ...this.#recording]);
|
|
627
798
|
}
|
|
628
799
|
|
|
629
800
|
/** Apply changed settings that need no restart (limits, timeouts). New timers use them; running ones finish as armed. */
|
package/src/stream.ts
CHANGED
|
@@ -123,6 +123,12 @@ class Translator {
|
|
|
123
123
|
#parser = new ToolCallStreamParser();
|
|
124
124
|
readonly #parseTools: boolean;
|
|
125
125
|
#open: { kind: OpenKind; index: number } | undefined;
|
|
126
|
+
/** Inside a ``` code fence of the visible text (model text there is never filtered). */
|
|
127
|
+
#inFence = false;
|
|
128
|
+
/** The visible text so far ends at a line start (a notice chunk starts on its own line). */
|
|
129
|
+
#atLineStart = true;
|
|
130
|
+
/** The unfinished last line of the visible text (a fence marker can be split across chunks). */
|
|
131
|
+
#partialLine = "";
|
|
126
132
|
toolCalled = false;
|
|
127
133
|
producedOutput = false;
|
|
128
134
|
/** agy's latest "⚠ API error (attempt N)" notice. Never shown as model text. */
|
|
@@ -146,17 +152,44 @@ class Translator {
|
|
|
146
152
|
this.#output.content = [];
|
|
147
153
|
this.#parser = new ToolCallStreamParser();
|
|
148
154
|
this.retryNotice = undefined;
|
|
155
|
+
this.#inFence = false;
|
|
156
|
+
this.#atLineStart = true;
|
|
157
|
+
this.#partialLine = "";
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Keep fence/line state of the text the model has shown, so a notice-shaped chunk can be judged in context. */
|
|
161
|
+
#track(chunk: string): void {
|
|
162
|
+
const lines = (this.#partialLine + chunk).split("\n");
|
|
163
|
+
this.#partialLine = lines.pop() ?? "";
|
|
164
|
+
for (const line of lines) if (/^\s*```/.test(line)) this.#inFence = !this.#inFence;
|
|
165
|
+
this.#atLineStart = this.#partialLine.trim() === "";
|
|
149
166
|
}
|
|
150
167
|
|
|
151
168
|
/** Returns true when this chunk completed a tool-call block. */
|
|
152
169
|
message(chunk: string): boolean {
|
|
153
170
|
if (this.toolCalled) return false;
|
|
154
|
-
//
|
|
155
|
-
const notice =
|
|
156
|
-
if (notice) {
|
|
171
|
+
// Before the model has answered, every retry notice is agy's (a 429 one is acted on by the caller).
|
|
172
|
+
const notice = parseApiRetryNotice(chunk);
|
|
173
|
+
if (notice && !this.producedOutput) {
|
|
157
174
|
this.retryNotice = notice;
|
|
158
175
|
return false;
|
|
159
176
|
}
|
|
177
|
+
// agy also retries transient backend errors mid-answer ("stream reading error: unexpected EOF", 503): such a
|
|
178
|
+
// notice arrives as its own chunk on its own line and is not model text. A model quoting one does so inside a
|
|
179
|
+
// code fence or mid-line, and a quoted 429 notice is kept as text (the `quote` contract). Idea from
|
|
180
|
+
// patlux/pi-antigravity-thin-client (QuotaSoftErrorFilter, MIT).
|
|
181
|
+
if (notice && !notice.exhausted) {
|
|
182
|
+
// agy's notice brings its own leading line break, so it starts a line even right after a sentence that was cut
|
|
183
|
+
// off; that break also completes a pending ``` marker, which then opens or closes a fence before the notice.
|
|
184
|
+
const ownLine = /^\r?\n/.test(chunk);
|
|
185
|
+
const fenceClosedHere = ownLine && /^\s*```/.test(this.#partialLine);
|
|
186
|
+
const inFence = fenceClosedHere ? !this.#inFence : this.#inFence;
|
|
187
|
+
if (!inFence && (this.#atLineStart || ownLine)) {
|
|
188
|
+
// Keep the line structure: the text before the notice ends its line, as agy's own break would have done.
|
|
189
|
+
return this.#partialLine ? this.message("\n") : false;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
this.#track(chunk);
|
|
160
193
|
// After its last retry agy sends one more line, "⚠ <the same error>", and ends the turn. Not model text either.
|
|
161
194
|
if (this.retryNotice && !this.producedOutput && /^\s*\u26A0/u.test(chunk) && chunk.includes(this.retryNotice.detail.slice(0, 40))) {
|
|
162
195
|
return false;
|
package/src/ui/menu.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
7
|
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
-
import { DEFAULT_ACCOUNT, labelFor, maskEmail, validateAccountName, type RequestLoginCode } from "../accounts.ts";
|
|
8
|
+
import { DEFAULT_ACCOUNT, labelFor, maskEmail, validateAccountName, validateApiKey, type RequestLoginCode } from "../accounts.ts";
|
|
9
9
|
import type { AccountManager, AccountView } from "../account-manager.ts";
|
|
10
10
|
import { buildDoctor, buildStatus } from "../doctor.ts";
|
|
11
11
|
import { CONFIG_ENV_NAMES } from "../config.ts";
|
|
@@ -20,6 +20,7 @@ const GROUPS = ["Accounts", "Add account", "Processes", "Diagnostics", "Settings
|
|
|
20
20
|
|
|
21
21
|
export function stateOf(view: AccountView): { text: string; tone: PanelItem["tone"] } {
|
|
22
22
|
if (!view.account.enabled) return { text: "disabled", tone: "muted" };
|
|
23
|
+
if (view.auth === "api-key" && !view.apiKey) return { text: "no API key", tone: "warn" };
|
|
23
24
|
if (view.identity && !view.identity.ok) return { text: "sign-in problem", tone: "error" };
|
|
24
25
|
if (!view.isDefault && !view.savedLogin) return { text: "not signed in", tone: "warn" };
|
|
25
26
|
if (view.running) return { text: `running · ${view.models?.length ?? "?"} models`, tone: "ok" };
|
|
@@ -34,11 +35,17 @@ export function emailOf(view: AccountView): string | undefined {
|
|
|
34
35
|
export function accountDetail(view: AccountView): string[] {
|
|
35
36
|
const lines: string[] = [];
|
|
36
37
|
const email = emailOf(view);
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
`
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
if (view.auth === "api-key") {
|
|
39
|
+
lines.push(
|
|
40
|
+
`provider ${view.provider} · Gemini API key ${view.apiKey?.masked ?? "missing"} (set in this menu) · billed per token · Gemini models only`,
|
|
41
|
+
);
|
|
42
|
+
} else {
|
|
43
|
+
lines.push(
|
|
44
|
+
`provider ${view.provider} · ${view.isDefault ? "Windows/OS keyring login (agy's own)" : "own token file"}` +
|
|
45
|
+
` · account ${email ? maskEmail(email) : view.isDefault ? "(agy's signed-in user)" : "not recorded"}` +
|
|
46
|
+
(view.tier ? ` · ${view.tier}` : ""),
|
|
47
|
+
);
|
|
48
|
+
}
|
|
42
49
|
lines.push(
|
|
43
50
|
`process ${view.running ? `running (pid ${view.pid ?? "?"})` : "stopped"} · sessions ${view.sessions.idle} reusable / ${view.sessions.busy} busy` +
|
|
44
51
|
(view.agyVersion ? ` · agy ${view.agyVersion}` : ""),
|
|
@@ -71,7 +78,7 @@ export async function mainView(manager: AccountManager, activeGroup?: string): P
|
|
|
71
78
|
label: `${view.isDefault ? "agy" : view.provider} ${view.isDefault ? "(default)" : view.account.alias ? `(${view.account.id})` : ""}`.trim(),
|
|
72
79
|
value: state.text,
|
|
73
80
|
tone: state.tone,
|
|
74
|
-
description: `${email ? maskEmail(email) : view.isDefault ? "agy's own login" : "no account recorded"} · Enter for actions: sign in, alias, enable/disable, check, reset, remove`,
|
|
81
|
+
description: `${view.auth === "api-key" ? `Gemini API key${view.apiKey ? ` ${view.apiKey.masked}` : " (missing)"}` : email ? maskEmail(email) : view.isDefault ? "agy's own login" : "no account recorded"} · Enter for actions: sign in, API key, alias, enable/disable, check, reset, remove`,
|
|
75
82
|
search: `${view.account.id} ${view.account.alias ?? ""} ${email ?? ""} ${view.provider}`,
|
|
76
83
|
});
|
|
77
84
|
}
|
|
@@ -124,7 +131,10 @@ export async function mainView(manager: AccountManager, activeGroup?: string): P
|
|
|
124
131
|
help("commands", "Commands", "/agy-bridge accounts | add <id> [alias] | login <id> | alias <id> <alias> | enable|disable <id> | remove <id> | check [id] | reset [id] | status | doctor [id] | menu");
|
|
125
132
|
help("fallback", "Using accounts in fallback chains", 'e.g. "agy/claude-opus-5-5": ["agy-acct2/claude-opus-4-6-thinking", …] — a quota error parks one provider/model only');
|
|
126
133
|
help("safety", "Wrong-account protection", "An extra account is used only when agy reports its own token file and the recorded email; otherwise it stops with a sign-in error");
|
|
127
|
-
help("
|
|
134
|
+
help("how", "How it signs in", "Each account runs the real agy CLI (`agy acp`) with that account's own signed-in Google login and folder, the way pi-claude-code runs the Claude Code CLI. pi-agy-bridge never reads or forwards the login.");
|
|
135
|
+
help("apikey", "Optional Gemini API key", "Per account: Enter an account → API key. While a key is set there, that account uses agy's gemini-api-key sign-in (billed per token, Gemini models only); clear it to go back to the Google login. GEMINI_API_KEY from the environment is never used.");
|
|
136
|
+
help("terms", "Terms of service", "Using several accounts and fallback chains across them is your decision for your plan; see Google's Antigravity terms and FAQ");
|
|
137
|
+
help("resume", "Conversation resume", "A continued pi session reattaches to agy's stored conversation (ACP session/resume) instead of re-sending history; PI_AGY_RESUME=0 turns it off");
|
|
128
138
|
|
|
129
139
|
const enabled = views.filter((view) => view.account.enabled).length;
|
|
130
140
|
return {
|
|
@@ -150,7 +160,17 @@ export function accountActionsView(view: AccountView, loginRunning: boolean): Pa
|
|
|
150
160
|
items.push({ group: "Actions", id, label, description, value, tone });
|
|
151
161
|
};
|
|
152
162
|
const extra = !view.isDefault;
|
|
153
|
-
|
|
163
|
+
const apiKey = view.auth === "api-key";
|
|
164
|
+
add(
|
|
165
|
+
"apikey",
|
|
166
|
+
apiKey ? "API key (in use)…" : "Use a Gemini API key…",
|
|
167
|
+
apiKey
|
|
168
|
+
? "Replace the key, or enter nothing to remove it and go back to this account's Google login through agy"
|
|
169
|
+
: "Optional: paste a Gemini API key to sign this account in with it instead of its Google login (billed per token, Gemini models only)",
|
|
170
|
+
apiKey ? (view.apiKey?.masked ?? "set") : "not set",
|
|
171
|
+
apiKey ? "ok" : "muted",
|
|
172
|
+
);
|
|
173
|
+
if (extra && !apiKey) {
|
|
154
174
|
add(
|
|
155
175
|
"login",
|
|
156
176
|
view.savedLogin ? "Sign in again (switch Google account)" : "Sign in with Google",
|
|
@@ -158,8 +178,10 @@ export function accountActionsView(view: AccountView, loginRunning: boolean): Pa
|
|
|
158
178
|
loginRunning ? "running…" : view.savedLogin ? "signed in" : "required",
|
|
159
179
|
view.savedLogin ? "ok" : "warn",
|
|
160
180
|
);
|
|
161
|
-
add("alias", "Set alias", `Rename the provider to agy-<alias>; the folder stays accounts/${view.account.id}`, view.account.alias ?? "none");
|
|
162
181
|
add("email", "Set expected email", "Normally recorded at sign-in; set by hand only to pin an account", view.account.email ? maskEmail(view.account.email) : "none");
|
|
182
|
+
}
|
|
183
|
+
if (extra) {
|
|
184
|
+
add("alias", "Set alias", `Rename the provider to agy-<alias>; the folder stays accounts/${view.account.id}`, view.account.alias ?? "none");
|
|
163
185
|
add("toggle", view.account.enabled ? "Disable" : "Enable", view.account.enabled ? "Hide its models and stop its process; the login is kept" : "Register its provider again", view.account.enabled ? "enabled" : "disabled", view.account.enabled ? "ok" : "muted");
|
|
164
186
|
}
|
|
165
187
|
if (view.account.enabled) {
|
|
@@ -169,7 +191,13 @@ export function accountActionsView(view: AccountView, loginRunning: boolean): Pa
|
|
|
169
191
|
if (view.models) add("models", "Show models", "List the model ids this account offers (for fallback chains)", `${view.models.length}`);
|
|
170
192
|
}
|
|
171
193
|
if (extra && !view.account.fromEnv) add("remove", "Remove account…", "Forget it; optionally delete its saved login and agy data", "CAUTION", "caution");
|
|
172
|
-
if (view.isDefault)
|
|
194
|
+
if (view.isDefault) {
|
|
195
|
+
add(
|
|
196
|
+
"default-help",
|
|
197
|
+
"About the default account",
|
|
198
|
+
apiKey ? "Signs in with the Gemini API key set here; cannot be removed or renamed" : "Uses agy's own login (run `agy` in a terminal to change it); cannot be removed or renamed",
|
|
199
|
+
);
|
|
200
|
+
}
|
|
173
201
|
add("back", "Back", "Return to the account list");
|
|
174
202
|
return {
|
|
175
203
|
title: `pi-agy-bridge · ${view.isDefault ? "agy (default)" : view.provider}`,
|
|
@@ -261,6 +289,33 @@ export async function promptAdd(manager: AccountManager, ctx: Ctx, notify: Notif
|
|
|
261
289
|
return id;
|
|
262
290
|
}
|
|
263
291
|
|
|
292
|
+
/** Ask for a Gemini API key and store it. Returns true when a key was stored, false when the stored key was removed,
|
|
293
|
+
* undefined when cancelled. The key is never echoed back, only a masked preview. */
|
|
294
|
+
export async function promptApiKey(manager: AccountManager, id: string, ctx: Ctx, notify: Notify): Promise<boolean | undefined> {
|
|
295
|
+
const raw = await ctx.ui.input(
|
|
296
|
+
`Gemini API key for ${id === DEFAULT_ACCOUNT ? "the default account" : id} (from aistudio.google.com/apikey; empty = remove it and use the Google login)`,
|
|
297
|
+
"AIza…",
|
|
298
|
+
);
|
|
299
|
+
if (raw === undefined) return undefined;
|
|
300
|
+
const value = raw.trim();
|
|
301
|
+
if (value) {
|
|
302
|
+
const problem = validateApiKey(value);
|
|
303
|
+
if (problem) {
|
|
304
|
+
notify(`pi-agy-bridge: ${problem}`, "error");
|
|
305
|
+
return undefined;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
await manager.setApiKey(id, value || undefined);
|
|
309
|
+
const name = id === DEFAULT_ACCOUNT ? "agy" : id;
|
|
310
|
+
notify(
|
|
311
|
+
value
|
|
312
|
+
? `pi-agy-bridge: ${name} now signs in with the API key ${value.slice(0, 4)}…${value.slice(-4)} (Gemini models only, billed per token); its Google login is kept`
|
|
313
|
+
: `pi-agy-bridge: API key removed; ${name} signs in with its Google login through agy again`,
|
|
314
|
+
"info",
|
|
315
|
+
);
|
|
316
|
+
return value ? true : false;
|
|
317
|
+
}
|
|
318
|
+
|
|
264
319
|
export async function promptRemove(manager: AccountManager, id: string, ctx: Ctx, notify: Notify): Promise<boolean> {
|
|
265
320
|
if (!(await ctx.ui.confirm(`Remove account "${id}"?`, `Its provider agy-${labelFor(manager.accounts.find((a) => a.id === id) ?? { id })} disappears from pi.`))) return false;
|
|
266
321
|
const deleteLogin = await ctx.ui.confirm(
|
|
@@ -427,6 +482,9 @@ export async function runAccountAction(
|
|
|
427
482
|
if (!view) throw new Error(`no account "${id}"`);
|
|
428
483
|
const provider = view.isDefault ? "agy" : view.provider;
|
|
429
484
|
switch (action) {
|
|
485
|
+
case "apikey":
|
|
486
|
+
await promptApiKey(manager, id, ctx, notify);
|
|
487
|
+
break;
|
|
430
488
|
case "login":
|
|
431
489
|
await runLogin(manager, id, ctx, notify);
|
|
432
490
|
break;
|