@timmyjl12/pi-agy-bridge 0.1.5 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +11 -1
- package/README.md +53 -7
- package/UPGRADING.md +12 -0
- package/compat/baselines/agy-1.5.14.json +260 -0
- package/compat/matrix.json +1 -1
- package/compat/probe.ts +71 -2
- package/package.json +4 -2
- package/src/account-manager.ts +399 -0
- package/src/accounts.ts +394 -0
- package/src/acp/connection.ts +1 -1
- package/src/config.ts +6 -0
- package/src/doctor.ts +13 -3
- package/src/index.ts +199 -25
- package/src/model-catalog.ts +19 -6
- package/src/provider.ts +30 -8
- package/src/runtime.ts +133 -6
- package/src/session-pool.ts +88 -6
- package/src/stream.ts +41 -8
- package/src/ui/menu.ts +478 -0
- package/src/ui/panel.ts +376 -0
package/src/session-pool.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
// of the hash chain), the previous turn ended cleanly, and nobody invalidated it. Everything else replays history
|
|
8
8
|
// into a fresh session, which is always correct.
|
|
9
9
|
|
|
10
|
+
import { mkdir } from "node:fs/promises";
|
|
10
11
|
import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";
|
|
11
12
|
import { resolveAgyCommand } from "./acp/command.ts";
|
|
12
13
|
import { AcpProcess } from "./acp/connection.ts";
|
|
@@ -69,6 +70,20 @@ export interface PoolOptions {
|
|
|
69
70
|
buildArgs?: (staging: Staging) => string[];
|
|
70
71
|
/** Reject an unusable agy (version/protocol) right after `initialize`. */
|
|
71
72
|
validate?: (init: AcpInitializeResult) => void;
|
|
73
|
+
/** Replace parts of the staging layout (an extra account's own `--gemini-dir` and work dir). The stage/carrier agent
|
|
74
|
+
* stays shared. */
|
|
75
|
+
stagingOverride?: Partial<Pick<Staging, "geminiDir" | "workDir">>;
|
|
76
|
+
/** Arguments appended after the base argv (also after `buildArgs`), e.g. an account's `--log-file`. */
|
|
77
|
+
extraArgs?: (staging: Staging) => string[];
|
|
78
|
+
/** Runs before each process start (e.g. clear the account's previous log). */
|
|
79
|
+
beforeStart?: () => Promise<void>;
|
|
80
|
+
/** Identity guard. agy resolves its login lazily (measured on 1.5.14: the token-store and "authenticated as" lines
|
|
81
|
+
* appear while the first `session/new` runs), so this is called once per process right after its first
|
|
82
|
+
* `session/new` and before any model switch or prompt. A throw closes that session and stops the process.
|
|
83
|
+
* `sessionFailure` is the error of that `session/new`, if it failed: the guard rethrows it unchanged when agy never
|
|
84
|
+
* got as far as resolving its login (process stopped, timeout), so an ordinary reset is not reported as a guard
|
|
85
|
+
* failure. */
|
|
86
|
+
verifyProcess?: (proc: AcpProcess, sessionFailure: unknown) => Promise<void>;
|
|
72
87
|
env?: NodeJS.ProcessEnv;
|
|
73
88
|
log?: (message: string) => void;
|
|
74
89
|
onHealth?: (event: HealthEvent) => void;
|
|
@@ -127,6 +142,9 @@ export class SessionPool {
|
|
|
127
142
|
#invalidationSeq = 0;
|
|
128
143
|
#invalidatedAll = 0;
|
|
129
144
|
readonly #invalidatedAt = new Map<string, number>();
|
|
145
|
+
/** Processes whose identity check passed (see PoolOptions.verifyProcess). */
|
|
146
|
+
readonly #verified = new WeakSet<AcpProcess>();
|
|
147
|
+
readonly #verifying = new WeakMap<AcpProcess, Promise<void>>();
|
|
130
148
|
|
|
131
149
|
constructor(options: PoolOptions) {
|
|
132
150
|
this.#options = options;
|
|
@@ -147,6 +165,11 @@ export class SessionPool {
|
|
|
147
165
|
};
|
|
148
166
|
}
|
|
149
167
|
|
|
168
|
+
/** The last successful discovery, without starting anything (menus and status lines). */
|
|
169
|
+
get cachedDiscovery(): Discovery | undefined {
|
|
170
|
+
return this.#discovery?.value;
|
|
171
|
+
}
|
|
172
|
+
|
|
150
173
|
get processAlive(): boolean {
|
|
151
174
|
return this.#process?.alive === true;
|
|
152
175
|
}
|
|
@@ -178,11 +201,15 @@ export class SessionPool {
|
|
|
178
201
|
|
|
179
202
|
async #startProcess(): Promise<AcpProcess> {
|
|
180
203
|
const generation = this.#generation;
|
|
181
|
-
const staging = (this.#staging ??= await
|
|
204
|
+
const staging = (this.#staging ??= await this.#stage());
|
|
182
205
|
const command = await resolveAgyCommand(this.#config.command);
|
|
183
|
-
const args =
|
|
184
|
-
|
|
185
|
-
|
|
206
|
+
const args = [
|
|
207
|
+
...(this.#options.buildArgs
|
|
208
|
+
? this.#options.buildArgs(staging)
|
|
209
|
+
: ["acp", "--add-dir", staging.addDir, "--agent", staging.agentName, "--gemini-dir", staging.geminiDir]),
|
|
210
|
+
...(this.#options.extraArgs?.(staging) ?? []),
|
|
211
|
+
];
|
|
212
|
+
await this.#options.beforeStart?.();
|
|
186
213
|
const proc = AcpProcess.start({
|
|
187
214
|
command,
|
|
188
215
|
args,
|
|
@@ -221,6 +248,61 @@ export class SessionPool {
|
|
|
221
248
|
return proc;
|
|
222
249
|
}
|
|
223
250
|
|
|
251
|
+
/** `session/new`, plus the one-time identity check of a process (see PoolOptions.verifyProcess). A process that
|
|
252
|
+
* fails the check is stopped; a failed `session/new` on an unverified process is still checked, because agy reports
|
|
253
|
+
* a missing login exactly that way and the guard words it for the user. */
|
|
254
|
+
async #newSession(proc: AcpProcess, params: { cwd: string; systemPromptAppend?: string }): Promise<AcpNewSessionResult> {
|
|
255
|
+
const verify = this.#options.verifyProcess;
|
|
256
|
+
if (!verify || this.#verified.has(proc)) return proc.newSession(params);
|
|
257
|
+
// Single-flight: concurrent first callers wait for one verification instead of each racing their own.
|
|
258
|
+
const pending = this.#verifying.get(proc);
|
|
259
|
+
if (pending) {
|
|
260
|
+
await pending;
|
|
261
|
+
return proc.newSession(params);
|
|
262
|
+
}
|
|
263
|
+
let release: () => void = () => undefined;
|
|
264
|
+
let fail: (error: unknown) => void = () => undefined;
|
|
265
|
+
const gate = new Promise<void>((resolve, reject) => {
|
|
266
|
+
release = resolve;
|
|
267
|
+
fail = reject;
|
|
268
|
+
});
|
|
269
|
+
gate.catch(() => undefined); // waiters observe the rejection; an unobserved one must not crash pi
|
|
270
|
+
this.#verifying.set(proc, gate);
|
|
271
|
+
try {
|
|
272
|
+
let created: AcpNewSessionResult | undefined;
|
|
273
|
+
let failure: unknown;
|
|
274
|
+
try {
|
|
275
|
+
created = await proc.newSession(params);
|
|
276
|
+
} catch (error) {
|
|
277
|
+
failure = error;
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
await verify(proc, failure);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (created?.sessionId && this.#canClose()) void this.#track(proc.closeSession(created.sessionId));
|
|
283
|
+
if (error !== failure) await this.killProcess(proc, "identity check failed");
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
if (failure !== undefined || !created) throw failure;
|
|
287
|
+
this.#verified.add(proc);
|
|
288
|
+
release();
|
|
289
|
+
return created;
|
|
290
|
+
} catch (error) {
|
|
291
|
+
fail(error);
|
|
292
|
+
throw error;
|
|
293
|
+
} finally {
|
|
294
|
+
this.#verifying.delete(proc);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async #stage(): Promise<Staging> {
|
|
299
|
+
const base = await ensureStaging(this.#config.home);
|
|
300
|
+
const override = this.#options.stagingOverride;
|
|
301
|
+
if (!override) return base;
|
|
302
|
+
for (const dir of [override.geminiDir, override.workDir]) if (dir) await mkdir(dir, { recursive: true });
|
|
303
|
+
return { ...base, ...override };
|
|
304
|
+
}
|
|
305
|
+
|
|
224
306
|
#onProcessExit(proc: AcpProcess): void {
|
|
225
307
|
for (const entry of [...this.#entries]) {
|
|
226
308
|
if (entry.process !== proc) continue;
|
|
@@ -280,7 +362,7 @@ export class SessionPool {
|
|
|
280
362
|
this.#inflight += 1;
|
|
281
363
|
try {
|
|
282
364
|
const proc = await this.#ensureProcess();
|
|
283
|
-
const created = await
|
|
365
|
+
const created = await this.#newSession(proc, { cwd: this.#staging?.workDir ?? this.#config.home });
|
|
284
366
|
if (created.sessionId && this.#canClose()) void this.#track(proc.closeSession(created.sessionId));
|
|
285
367
|
const value: Discovery = {
|
|
286
368
|
init: this.#init ?? {},
|
|
@@ -390,7 +472,7 @@ export class SessionPool {
|
|
|
390
472
|
const workDir = this.#staging?.workDir ?? this.#config.home;
|
|
391
473
|
// Without agy's append hook the system text cannot ride session/new: the caller inlines it into the first prompt.
|
|
392
474
|
const viaMeta = this.#options.features?.().systemPromptAppend !== false && request.systemInline !== true;
|
|
393
|
-
const created = await
|
|
475
|
+
const created = await this.#newSession(proc, { cwd: workDir, systemPromptAppend: viaMeta ? request.systemAppend : undefined });
|
|
394
476
|
const acpSessionId = created.sessionId as string;
|
|
395
477
|
try {
|
|
396
478
|
await proc.setConfigOption(acpSessionId, "model", request.modelId);
|
package/src/stream.ts
CHANGED
|
@@ -184,7 +184,10 @@ class Translator {
|
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
-
|
|
187
|
+
/** `exhausted`: agy's RESOURCE_EXHAUSTED notice arrived (agy <= 1.5.12 sends one per retry). `refused`: a fresh session
|
|
188
|
+
* with the appended system prompt produced nothing within the refusal probe window (agy 1.5.14 retries silently and
|
|
189
|
+
* sends one notice only after ~140 s). Both mean "retry inline" in auto mode. */
|
|
190
|
+
type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted" | "refused";
|
|
188
191
|
|
|
189
192
|
interface TurnResult {
|
|
190
193
|
result: AcpPromptResult | undefined;
|
|
@@ -231,7 +234,7 @@ export function makeStreamAgy(runtime: AgyRuntime) {
|
|
|
231
234
|
// error handling: an unhandled rejection here could take down the whole pi process.
|
|
232
235
|
void run(runtime, model, sourceContext, options, stream, output).catch((error: unknown) => {
|
|
233
236
|
output.stopReason = "error";
|
|
234
|
-
output.errorMessage = normalizeAgyError(error).message;
|
|
237
|
+
output.errorMessage = runtime.decorateError(normalizeAgyError(error).message);
|
|
235
238
|
stream.push({ type: "error", reason: "error", error: output });
|
|
236
239
|
stream.end();
|
|
237
240
|
});
|
|
@@ -281,15 +284,24 @@ async function run(
|
|
|
281
284
|
// Stop at the first RESOURCE_EXHAUSTED only when the inline retry below can follow. Anywhere else agy's own retries
|
|
282
285
|
// (~75 s) are the best chance of getting through a short throttle, e.g. in the middle of a subagent's tool loop.
|
|
283
286
|
const inlineFallback = runtime.config.systemPrompt === "auto" && !lease.reused && !lease.systemInline;
|
|
284
|
-
|
|
287
|
+
// agy 1.5.14 retries the refused prompt silently for ~140 s and only then sends one notice, so the notice alone no
|
|
288
|
+
// longer arrives in time. A fresh appended session that produced no model output (text or thinking) within the probe
|
|
289
|
+
// window is treated as refused too. Measured first output on 1.5.14: 0.4-3.4 s across Claude, Gemini 4 xhigh and the
|
|
290
|
+
// orchestrator; a false positive only costs one inline session, which is always served.
|
|
291
|
+
let turn = await runTurn(runtime, model, options, lease, prompt, translator, undefined, inlineFallback, runtime.config.refusalProbeMs);
|
|
285
292
|
|
|
286
293
|
// The Antigravity backend refuses some system prompts sent through the append hook with RESOURCE_EXHAUSTED on
|
|
287
294
|
// every try, while the same text inside the first prompt is served (measured on agy 1.5.9, 2026-11-14: pi's
|
|
288
295
|
// default prompt, three models). In `auto` mode retry such a turn once with the system text inline and, if that
|
|
289
296
|
// works, keep sending it inline for this runtime.
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
297
|
+
const refused = turn.cancelReason === "exhausted" || turn.cancelReason === "refused";
|
|
298
|
+
if (refused && inlineFallback && !translator.producedOutput) {
|
|
299
|
+
runtime.trace(
|
|
300
|
+
turn.cancelReason === "refused"
|
|
301
|
+
? `turn: model=${model.id} no output within ${runtime.config.refusalProbeMs}ms with the appended system prompt; retrying inline`
|
|
302
|
+
: `turn: model=${model.id} RESOURCE_EXHAUSTED with the appended system prompt; retrying inline`,
|
|
303
|
+
);
|
|
304
|
+
if (turn.wedged) await runtime.pool.killProcess(lease.process, "refused and ignored cancel");
|
|
293
305
|
await lease.finish({ reusable: false });
|
|
294
306
|
lease = undefined;
|
|
295
307
|
translator.retryNotice = undefined;
|
|
@@ -374,7 +386,7 @@ async function run(
|
|
|
374
386
|
stream.end();
|
|
375
387
|
} catch (error) {
|
|
376
388
|
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
377
|
-
output.errorMessage = options?.signal?.aborted ? "aborted" : normalizeAgyError(error).message;
|
|
389
|
+
output.errorMessage = options?.signal?.aborted ? "aborted" : runtime.decorateError(normalizeAgyError(error).message);
|
|
378
390
|
if (!options?.signal?.aborted) runtime.noteFailure(error);
|
|
379
391
|
await lease?.finish({ reusable: false });
|
|
380
392
|
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
@@ -464,6 +476,8 @@ async function runTurn(
|
|
|
464
476
|
remainingMs?: number,
|
|
465
477
|
/** Cancel at agy's first RESOURCE_EXHAUSTED notice instead of letting it retry. */
|
|
466
478
|
failFastExhausted = false,
|
|
479
|
+
/** With failFastExhausted: also cancel when no model output (text or thinking) arrived within this many ms. */
|
|
480
|
+
refusalProbeMs = 0,
|
|
467
481
|
): Promise<TurnResult> {
|
|
468
482
|
const { process: proc, acpSessionId } = lease;
|
|
469
483
|
const silenceMs = runtime.config.silenceMs;
|
|
@@ -473,6 +487,7 @@ async function runTurn(
|
|
|
473
487
|
let cancelReason: CancelReason | undefined;
|
|
474
488
|
let graceTimer: NodeJS.Timeout | undefined;
|
|
475
489
|
let silenceTimer: NodeJS.Timeout | undefined;
|
|
490
|
+
let probeTimer: NodeJS.Timeout | undefined;
|
|
476
491
|
let settled = false;
|
|
477
492
|
let expire: () => void = () => undefined;
|
|
478
493
|
const graceExpired = new Promise<"grace">((resolve) => {
|
|
@@ -484,6 +499,7 @@ async function runTurn(
|
|
|
484
499
|
cancelReason = reason;
|
|
485
500
|
if (silenceTimer) clearTimeout(silenceTimer);
|
|
486
501
|
if (totalTimer) clearTimeout(totalTimer);
|
|
502
|
+
if (probeTimer) clearTimeout(probeTimer);
|
|
487
503
|
proc.cancel(acpSessionId);
|
|
488
504
|
graceTimer = setTimeout(expire, graceMs);
|
|
489
505
|
graceTimer.unref();
|
|
@@ -495,18 +511,28 @@ async function runTurn(
|
|
|
495
511
|
silenceTimer.unref();
|
|
496
512
|
};
|
|
497
513
|
const onAbort = (): void => requestCancel("abort");
|
|
514
|
+
/** Any model chunk (text or thinking) proves the backend accepted the prompt: the refusal probe ends. */
|
|
515
|
+
const modelSpoke = (): void => {
|
|
516
|
+
if (probeTimer) clearTimeout(probeTimer);
|
|
517
|
+
probeTimer = undefined;
|
|
518
|
+
};
|
|
498
519
|
|
|
499
520
|
const stop = proc.listen(acpSessionId, (update) => {
|
|
500
521
|
arm();
|
|
501
522
|
switch (update.sessionUpdate) {
|
|
502
523
|
case "agent_message_chunk":
|
|
503
524
|
if (cancelReason) break;
|
|
525
|
+
// agy's own "⚠ ..." notices are not the model speaking; anything else is.
|
|
526
|
+
if (!/^\s*\u26A0/u.test(updateText(update))) modelSpoke();
|
|
504
527
|
if (translator.message(updateText(update))) requestCancel("tool");
|
|
505
528
|
// agy would back off and retry up to five times (~75 s), each try counting against the same limit.
|
|
506
529
|
else if (failFastExhausted && translator.retryNotice?.exhausted) requestCancel("exhausted");
|
|
507
530
|
break;
|
|
508
531
|
case "agent_thought_chunk":
|
|
509
|
-
if (!cancelReason)
|
|
532
|
+
if (!cancelReason) {
|
|
533
|
+
modelSpoke();
|
|
534
|
+
translator.thought(updateText(update));
|
|
535
|
+
}
|
|
510
536
|
break;
|
|
511
537
|
case "usage_update":
|
|
512
538
|
if (typeof update.size === "number") runtime.observeWindow(model.id, update.size);
|
|
@@ -528,6 +554,12 @@ async function runTurn(
|
|
|
528
554
|
totalTimer = setTimeout(() => requestCancel("timeout"), totalMs);
|
|
529
555
|
totalTimer.unref();
|
|
530
556
|
}
|
|
557
|
+
if (failFastExhausted && refusalProbeMs > 0) {
|
|
558
|
+
probeTimer = setTimeout(() => {
|
|
559
|
+
if (!translator.producedOutput) requestCancel("refused");
|
|
560
|
+
}, refusalProbeMs);
|
|
561
|
+
probeTimer.unref();
|
|
562
|
+
}
|
|
531
563
|
const promptPromise = proc.prompt(acpSessionId, prompt).then(
|
|
532
564
|
(result) => ({ kind: "result" as const, result }),
|
|
533
565
|
(error: unknown) => ({ kind: "error" as const, error }),
|
|
@@ -550,6 +582,7 @@ async function runTurn(
|
|
|
550
582
|
settled = true;
|
|
551
583
|
if (silenceTimer) clearTimeout(silenceTimer);
|
|
552
584
|
if (totalTimer) clearTimeout(totalTimer);
|
|
585
|
+
if (probeTimer) clearTimeout(probeTimer);
|
|
553
586
|
if (graceTimer) clearTimeout(graceTimer);
|
|
554
587
|
options?.signal?.removeEventListener("abort", onAbort);
|
|
555
588
|
stop();
|