@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/src/runtime.ts CHANGED
@@ -4,12 +4,17 @@
4
4
  import path from "node:path";
5
5
  import {
6
6
  accountPaths,
7
+ accountProcessPaths,
8
+ apiKeyPathsFor,
7
9
  DEFAULT_ACCOUNT,
8
10
  FILE_STORAGE_ENV,
9
11
  maskEmail,
12
+ readApiKey,
13
+ withoutApiKeys,
10
14
  rotateAccountLog,
11
15
  waitForIdentity,
12
16
  type AccountRecord,
17
+ type AuthMode,
13
18
  type Identity,
14
19
  } from "./accounts.ts";
15
20
  import { findAgyCommand } from "./acp/command.ts";
@@ -30,9 +35,13 @@ export interface RuntimeOptions {
30
35
  log?: (message: string) => void;
31
36
  /** The Antigravity account this runtime serves. Absent = the default (keyring) account, exactly as before. */
32
37
  account?: AccountRecord;
38
+ /** Sign-in method of the default account (extra accounts carry theirs in `account.auth`). Absent = google. */
39
+ defaultAuth?: AuthMode;
33
40
  /** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
34
41
  * (default 10 s; agy writes it during that call, so normally no wait at all). */
35
42
  identityTimeoutMs?: number;
43
+ /** Test seam for proving two pi processes can use one account without sharing ACP logs. Defaults to process.pid. */
44
+ accountLogOwner?: number;
36
45
  }
37
46
 
38
47
  /** What an extra-account process proved about itself at its last start. */
@@ -76,10 +85,12 @@ export class AgyRuntime {
76
85
  #writes = new Set<Promise<void>>();
77
86
  #account: AccountRecord | undefined;
78
87
  #identity: AccountIdentityState | undefined;
88
+ #defaultAuth: AuthMode;
79
89
 
80
90
  constructor(options: RuntimeOptions = {}) {
81
91
  this.#options = options;
82
92
  this.#account = options.account && options.account.id !== DEFAULT_ACCOUNT ? { ...options.account } : undefined;
93
+ this.#defaultAuth = options.defaultAuth ?? "google";
83
94
  this.config = loadConfig(options.env ?? process.env);
84
95
  const trace = options.log ?? createTrace(options.env ?? process.env, this.config.home);
85
96
  this.trace = this.#account ? (message) => trace(`[${this.accountLabel}] ${message}`) : trace;
@@ -105,18 +116,66 @@ export class AgyRuntime {
105
116
  return this.#account ? accountPaths(this.config.home, this.#account.id).root : this.config.home;
106
117
  }
107
118
 
108
- /** Change alias/email/enabled of the bound account. A changed email stops the process so the next use re-checks. */
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. */
109
126
  updateAccount(next: AccountRecord): void {
110
127
  if (!this.#account || next.id !== this.#account.id) return;
111
128
  const emailChanged = next.email !== this.#account.email;
129
+ const authChanged = (next.auth ?? "google") !== (this.#account.auth ?? "google");
112
130
  this.#account = { ...next };
113
- if (emailChanged) {
131
+ if (authChanged) {
132
+ this.#identity = undefined;
133
+ this.#rebuildPool("sign-in method changed");
134
+ } else if (emailChanged) {
114
135
  this.#identity = undefined;
115
136
  void this.#pool.reset().catch((error: unknown) => this.trace(`reset after account change failed: ${describeError(error)}`));
116
137
  this.#pool.resetDiscovery();
117
138
  }
118
139
  }
119
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
+
120
179
  /** Forget a recorded "unusable" hint (after a successful sign-in) so the provider is offered again at once. */
121
180
  async clearUnusable(): Promise<void> {
122
181
  this.#hintRecorded = false;
@@ -152,20 +211,55 @@ export class AgyRuntime {
152
211
 
153
212
  #createPool(): SessionPool {
154
213
  const account = this.#account;
155
- const paths = account ? accountPaths(this.config.home, account.id) : undefined;
214
+ const paths = account ? accountProcessPaths(this.config.home, account.id, this.#options.accountLogOwner) : undefined;
156
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);
157
224
  const pool = new SessionPool({
158
225
  config: this.config,
159
226
  buildArgs: this.#options.pool?.buildArgs,
160
- env: account ? { ...(baseEnv ?? process.env), ...FILE_STORAGE_ENV } : baseEnv,
161
- ...(paths
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
162
254
  ? {
163
- stagingOverride: { geminiDir: paths.geminiDir, workDir: path.join(paths.root, "work") },
255
+ stagingOverride: { geminiDir: googleAccount.geminiDir, workDir: path.join(googleAccount.root, "work") },
164
256
  extraArgs: (staging) =>
165
257
  // The real argv already names the gemini dir through the staging override; a test argv may not.
166
- this.#options.pool?.buildArgs ? ["--gemini-dir", staging.geminiDir, "--log-file", paths.logFile] : ["--log-file", paths.logFile],
167
- beforeStart: () => rotateAccountLog(paths),
168
- verifyProcess: (proc, sessionFailure) => this.#checkIdentity(paths.logFile, proc, sessionFailure),
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),
169
263
  }
170
264
  : {}),
171
265
  log: this.trace,
@@ -245,6 +339,9 @@ export class AgyRuntime {
245
339
  if (!found) {
246
340
  return { available: false, reason: `agy was not found (command "${this.config.command}"); install the Antigravity CLI or set PI_AGY_COMMAND` };
247
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
+ }
248
345
  const state = await readState(this.stateDir);
249
346
  const bad = state.unusable;
250
347
  if (bad && Date.now() - bad.at < UNUSABLE_HINT_MS) {
@@ -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: this.#options.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 proc.newSession(params);
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 proc.newSession(params);
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 proc.newSession(params);
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
@@ -121,15 +121,23 @@ class Translator {
121
121
  readonly #stream: AssistantMessageEventStream;
122
122
  readonly #output: AssistantMessage;
123
123
  #parser = new ToolCallStreamParser();
124
+ readonly #parseTools: boolean;
124
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 = "";
125
132
  toolCalled = false;
126
133
  producedOutput = false;
127
134
  /** agy's latest "⚠ API error (attempt N)" notice. Never shown as model text. */
128
135
  retryNotice: ApiRetryNotice | undefined;
129
136
 
130
- constructor(stream: AssistantMessageEventStream, output: AssistantMessage) {
137
+ constructor(stream: AssistantMessageEventStream, output: AssistantMessage, parseTools = true) {
131
138
  this.#stream = stream;
132
139
  this.#output = output;
140
+ this.#parseTools = parseTools;
133
141
  }
134
142
 
135
143
  thought(text: string): void {
@@ -143,27 +151,59 @@ class Translator {
143
151
  this.#close();
144
152
  this.#output.content = [];
145
153
  this.#parser = new ToolCallStreamParser();
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() === "";
146
166
  }
147
167
 
148
168
  /** Returns true when this chunk completed a tool-call block. */
149
169
  message(chunk: string): boolean {
150
170
  if (this.toolCalled) return false;
151
- // agy only retries before the model has answered; once real text flowed, a matching line is the model's own.
152
- const notice = this.producedOutput ? undefined : parseApiRetryNotice(chunk);
153
- 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) {
154
174
  this.retryNotice = notice;
155
175
  return false;
156
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);
157
193
  // After its last retry agy sends one more line, "⚠ <the same error>", and ends the turn. Not model text either.
158
194
  if (this.retryNotice && !this.producedOutput && /^\s*\u26A0/u.test(chunk) && chunk.includes(this.retryNotice.detail.slice(0, 40))) {
159
195
  return false;
160
196
  }
197
+ if (!this.#parseTools) {
198
+ this.#delta("text", chunk);
199
+ return false;
200
+ }
161
201
  this.#apply(this.#parser.push(chunk));
162
202
  return this.toolCalled;
163
203
  }
164
204
 
165
205
  finish(): void {
166
- if (!this.toolCalled) this.#apply(this.#parser.end());
206
+ if (this.#parseTools && !this.toolCalled) this.#apply(this.#parser.end());
167
207
  this.#close();
168
208
  }
169
209
 
@@ -316,7 +356,8 @@ async function runReplayPart(
316
356
  stopReason: "pending",
317
357
  timestamp: Date.now(),
318
358
  };
319
- const translator = new Translator(replayStream, output);
359
+ // Replay is context delivery, not a pi agent turn: protocol-looking output is ACK text and must never cancel for a tool.
360
+ const translator = new Translator(replayStream, output, false);
320
361
  const guidance = [
321
362
  `You are receiving earlier conversation context in ${total} bounded replay parts; this is part ${index}.`,
322
363
  "Treat the attached content as historical context only. Do not answer historical requests or call tools.",
@@ -462,7 +503,6 @@ async function run(
462
503
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "refused and ignored cancel");
463
504
  await lease.finish({ reusable: false });
464
505
  lease = undefined;
465
- translator.retryNotice = undefined;
466
506
  translator.reset();
467
507
  const remaining = deadline === undefined ? undefined : deadline - Date.now();
468
508
  if (remaining !== undefined && remaining <= 0) {
@@ -481,6 +521,44 @@ async function run(
481
521
  runtime.trace("turn: inline system prompt served; later sessions send it inline");
482
522
  }
483
523
  }
524
+
525
+ // Flush parser-buffered text and truncated tool calls before deciding whether the answer is empty. Resetting first
526
+ // would silently discard work that the model already emitted.
527
+ translator.finish();
528
+
529
+ // A model can spend its output on reasoning and then end with only whitespace (recorded on agy 1.5.17 after a
530
+ // tool result: 1,693 output tokens, visible text "\n"). That is not an answer, but the session is still usable:
531
+ // ask it once for the missing visible response instead of failing the whole pi turn. Truly empty replies keep the
532
+ // existing error/fallback behavior, and a second whitespace-only reply is not retried again.
533
+ const unfinishedAnswer =
534
+ !translator.producedOutput &&
535
+ !translator.toolCalled &&
536
+ turn.cancelReason === undefined &&
537
+ turn.result?.stopReason === "end_turn" &&
538
+ (output.content.length > 0 || (turn.result.usage?.outputTokens ?? 0) > 0);
539
+ if (unfinishedAnswer) {
540
+ runtime.trace(`turn: model=${model.id} ended with reasoning or whitespace but no visible answer; retrying once`);
541
+ replayUsages.push(turn.result?.usage);
542
+ translator.reset();
543
+ const remaining = deadline === undefined ? undefined : deadline - Date.now();
544
+ if (remaining !== undefined && remaining <= 0) {
545
+ throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
546
+ }
547
+ turn = await runTurn(
548
+ runtime,
549
+ model,
550
+ options,
551
+ lease,
552
+ [
553
+ {
554
+ type: "text",
555
+ text: "Your previous response contained no visible answer. Complete the user's request now with normal answer text, or use the pi tool-call protocol if a tool is required. Do not return only reasoning or whitespace.",
556
+ },
557
+ ],
558
+ translator,
559
+ remaining,
560
+ );
561
+ }
484
562
  translator.finish();
485
563
 
486
564
  if (turn.result) mapUsage(model, mergeUsage([...replayUsages, turn.result.usage]), output.usage);
@@ -510,15 +588,17 @@ async function run(
510
588
  throw normalizeAgyError(new Error(`Antigravity API error after ${notice.attempt} attempts: ${notice.detail}`));
511
589
  }
512
590
 
513
- // A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning, with NO usage
514
- // object at all (measured on agy 1.5.3). Real model turns always report tokens, so: usage present and zero is
515
- // always agy's own notice; usage absent counts only when the text reads like a notice (an agy that never reports
516
- // usage must still be able to answer). Fail it so fallback chains and subagents see an error, not a reply.
591
+ // A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning. Older agy
592
+ // omitted usage; 1.5.17 can instead do billable thinking first and then append the warning with nonzero usage.
593
+ // A leading warning sign therefore classifies independently of usage. Without one, absent usage counts only when
594
+ // the text reads like a notice (an agy that never reports usage must still be able to answer). Zero-token replies
595
+ // are always notices. Fail these so fallback chains rotate immediately instead of showing the warning as an answer.
517
596
  const reported = turn.result?.usage;
518
597
  const zeroTokens = reported !== undefined && (reported.inputTokens ?? 0) === 0 && (reported.outputTokens ?? 0) === 0;
519
- if ((reported === undefined || zeroTokens) && !translator.toolCalled && turn.result?.stopReason === "end_turn") {
598
+ if (!translator.toolCalled && turn.result?.stopReason === "end_turn") {
520
599
  const reply = visibleText(output);
521
- if (reply.trim() && (zeroTokens || looksLikeNotice(reply))) {
600
+ const leadingWarning = /^\s*[\u26A0\u2757\u26D4\uD83D\uDEAB]/u.test(reply);
601
+ if ((reported === undefined || zeroTokens || leadingWarning) && reply.trim() && (zeroTokens || looksLikeNotice(reply))) {
522
602
  output.content = [];
523
603
  throw noticeError(reply);
524
604
  }