@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.
@@ -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";
@@ -46,6 +48,8 @@ export interface Lease {
46
48
  readonly acpSessionId: string;
47
49
  /** True when the agy session already holds the conversation prefix: send only the latest input. */
48
50
  readonly reused: boolean;
51
+ /** agy's data dir for this session (its conversation store lives below it); undefined before staging. */
52
+ readonly geminiDir?: string;
49
53
  /** True for a fresh session whose agy has no system-prompt hook: the caller must put the system text (pi's prompt
50
54
  * and the tool protocol) into this session's first prompt. Always false for a reused session. */
51
55
  readonly systemInline: boolean;
@@ -85,10 +89,17 @@ export interface PoolOptions {
85
89
  * failure. */
86
90
  verifyProcess?: (proc: AcpProcess, sessionFailure: unknown) => Promise<void>;
87
91
  env?: NodeJS.ProcessEnv;
92
+ /** Resolved right before each spawn (wins over `env`): an API-key account adds its key here, so a key changed in the
93
+ * menu is used by the next process without rebuilding the pool. A throw fails the start with that error. */
94
+ resolveEnv?: () => Promise<NodeJS.ProcessEnv | undefined>;
95
+ /** ACP auth method to select right after `initialize` (API-key accounts: `gemini-api-key`). */
96
+ authMethod?: string;
97
+ /** Reattach continued pi sessions to agy's own stored conversation with `session/resume` (default true). */
98
+ resume?: boolean;
88
99
  log?: (message: string) => void;
89
100
  onHealth?: (event: HealthEvent) => void;
90
101
  /** Negotiated optional features, read when a session opens (after the handshake). Absent = assume supported. */
91
- features?: () => Pick<AgyFeatures, "systemPromptAppend" | "sessionClose">;
102
+ features?: () => Pick<AgyFeatures, "systemPromptAppend" | "sessionClose"> & Partial<Pick<AgyFeatures, "sessionResume">>;
92
103
  }
93
104
 
94
105
  interface Entry {
@@ -107,6 +118,8 @@ interface Entry {
107
118
  systemInline: boolean;
108
119
  lastUsed: number;
109
120
  timer: NodeJS.Timeout | undefined;
121
+ /** Bumped on every lease: a resume record started for an earlier turn is dropped once the session moved on. */
122
+ generation?: number;
110
123
  }
111
124
 
112
125
  function firstDifference(a: readonly string[], b: readonly string[]): number {
@@ -145,6 +158,11 @@ export class SessionPool {
145
158
  /** Processes whose identity check passed (see PoolOptions.verifyProcess). */
146
159
  readonly #verified = new WeakSet<AcpProcess>();
147
160
  readonly #verifying = new WeakMap<AcpProcess, Promise<void>>();
161
+ #resumeStore: ResumeStore | undefined;
162
+ /** agy conversations being reattached right now: a concurrent request for the same one replays instead. */
163
+ readonly #resuming = new Set<string>();
164
+ /** Record writes in flight (awaited by dispose/reset so a test or shutdown never races a half-written file). */
165
+ readonly #recording = new Set<Promise<void>>();
148
166
 
149
167
  constructor(options: PoolOptions) {
150
168
  this.#options = options;
@@ -219,11 +237,18 @@ export class SessionPool {
219
237
  this.#options.log?.(`beforeStart failed: ${describeError(error)}`);
220
238
  throw new AgyError("spawn", `agy spawn failed: could not prepare the account log (${code}); retry`, { cause: error });
221
239
  }
240
+ let env = this.#options.env;
241
+ try {
242
+ env = (await this.#options.resolveEnv?.()) ?? env;
243
+ } catch (error) {
244
+ this.#reportFailure(error);
245
+ throw error;
246
+ }
222
247
  const proc = AcpProcess.start({
223
248
  command,
224
249
  args,
225
250
  cwd: staging.workDir,
226
- env: this.#options.env,
251
+ env,
227
252
  controlTimeoutMs: this.#config.controlTimeoutMs,
228
253
  onStderr: this.#options.log ? (chunk) => this.#options.log?.(`agy stderr: ${chunk.trimEnd()}`) : undefined,
229
254
  });
@@ -242,6 +267,22 @@ export class SessionPool {
242
267
  this.#reportFailure(error);
243
268
  throw error;
244
269
  }
270
+ const method = this.#options.authMethod;
271
+ if (method) {
272
+ const offered = (init.authMethods ?? []).map((entry) => entry.id);
273
+ try {
274
+ if (!offered.includes(method)) {
275
+ throw new AgyError("compat", `pi-agy-bridge is unavailable: agy does not offer the ${method} sign-in method (offers ${offered.join(", ") || "none"})`);
276
+ }
277
+ await proc.authenticate(method).catch((error: unknown) => {
278
+ throw new AgyError("auth", `agy authentication required (not logged in): the ${method} sign-in was refused: ${describeError(error)}`, { cause: error });
279
+ });
280
+ } catch (error) {
281
+ await proc.dispose();
282
+ this.#reportFailure(error);
283
+ throw error;
284
+ }
285
+ }
245
286
  if (!this.#open) {
246
287
  await proc.dispose();
247
288
  throw new AgyError("exited", "agy is unavailable: pi-agy-bridge is shut down");
@@ -261,13 +302,19 @@ export class SessionPool {
261
302
  * fails the check is stopped; a failed `session/new` on an unverified process is still checked, because agy reports
262
303
  * a missing login exactly that way and the guard words it for the user. */
263
304
  async #newSession(proc: AcpProcess, params: { cwd: string; systemPromptAppend?: string }): Promise<AcpNewSessionResult> {
305
+ return this.#verifiedOpen(proc, () => proc.newSession(params));
306
+ }
307
+
308
+ /** Open a session (`session/new` or `session/resume`) on a process whose identity is checked once, before the first
309
+ * session it serves. A resumed session must pass the same guard: after a restart it may be the process's first. */
310
+ async #verifiedOpen(proc: AcpProcess, open: () => Promise<AcpNewSessionResult>): Promise<AcpNewSessionResult> {
264
311
  const verify = this.#options.verifyProcess;
265
- if (!verify || this.#verified.has(proc)) return proc.newSession(params);
312
+ if (!verify || this.#verified.has(proc)) return open();
266
313
  // Single-flight: concurrent first callers wait for one verification instead of each racing their own.
267
314
  const pending = this.#verifying.get(proc);
268
315
  if (pending) {
269
316
  await pending;
270
- return proc.newSession(params);
317
+ return open();
271
318
  }
272
319
  let release: () => void = () => undefined;
273
320
  let fail: (error: unknown) => void = () => undefined;
@@ -281,7 +328,7 @@ export class SessionPool {
281
328
  let created: AcpNewSessionResult | undefined;
282
329
  let failure: unknown;
283
330
  try {
284
- created = await proc.newSession(params);
331
+ created = await open();
285
332
  } catch (error) {
286
333
  failure = error;
287
334
  }
@@ -436,11 +483,135 @@ export class SessionPool {
436
483
  reusable.timer = undefined;
437
484
  return this.#lease(reusable, true);
438
485
  }
486
+ const resumed = await this.#tryResume(proc, request);
487
+ if (resumed) {
488
+ resumed.leasedAtSeq = seq;
489
+ return this.#lease(resumed, true);
490
+ }
439
491
  const entry = await this.#openFresh(proc, request);
440
492
  entry.leasedAtSeq = seq;
441
493
  return this.#lease(entry, false);
442
494
  }
443
495
 
496
+ // ---- resume across processes -------------------------------------------------------------------------------
497
+
498
+ #resumeEnabled(): boolean {
499
+ return this.#options.resume !== false && this.#config.resume !== false && this.#options.features?.().sessionResume === true;
500
+ }
501
+
502
+ /** The record file lives beside agy's dir (`<gemini-dir>.resume.json`): one per account and auth mode. */
503
+ #store(): ResumeStore | undefined {
504
+ const geminiDir = this.#staging?.geminiDir;
505
+ if (!geminiDir) return undefined;
506
+ this.#resumeStore ??= new ResumeStore(path.join(path.dirname(geminiDir), `${path.basename(geminiDir)}.resume.json`));
507
+ return this.#resumeStore;
508
+ }
509
+
510
+ /** Reattach a continued pi session to the agy conversation that already holds its prefix (a previous process, a pi
511
+ * restart). Only when the record matches the request's chain exactly and agy's own store shows no client prompt
512
+ * since; everything else returns undefined and the caller replays into a fresh session, as before. */
513
+ async #tryResume(proc: AcpProcess, request: SessionRequest): Promise<Entry | undefined> {
514
+ const log = this.#options.log;
515
+ if (!request.piSessionId || request.latestCount <= 0 || !this.#resumeEnabled()) return undefined;
516
+ const store = this.#store();
517
+ const geminiDir = this.#staging?.geminiDir;
518
+ if (!store || !geminiDir) return undefined;
519
+ const record = await store.get(request.piSessionId).catch(() => undefined);
520
+ if (!record) return undefined;
521
+ const held = request.chain.length - request.latestCount;
522
+ if (record.chainLength !== held || request.chain[held - 1] !== record.chainLast) {
523
+ log?.(`resume: skipped (recorded conversation holds ${record.chainLength - 1} messages, request continues from ${held - 1}${record.chainLength === held ? "; context differs" : ""})`);
524
+ return undefined;
525
+ }
526
+ if (this.#resuming.has(record.acpSessionId) || [...this.#entries].some((entry) => entry.acpSessionId === record.acpSessionId)) {
527
+ log?.("resume: skipped (that agy conversation is open in this process)");
528
+ return undefined;
529
+ }
530
+ this.#resuming.add(record.acpSessionId);
531
+ try {
532
+ return await this.#resume(proc, request, record, held, store, geminiDir);
533
+ } finally {
534
+ this.#resuming.delete(record.acpSessionId);
535
+ }
536
+ }
537
+
538
+ async #resume(
539
+ proc: AcpProcess,
540
+ request: SessionRequest,
541
+ record: NonNullable<Awaited<ReturnType<ResumeStore["get"]>>>,
542
+ held: number,
543
+ store: ResumeStore,
544
+ geminiDir: string,
545
+ ): Promise<Entry | undefined> {
546
+ const log = this.#options.log;
547
+ const piSessionId = request.piSessionId as string;
548
+ const since = await checkConversation(geminiDir, record.acpSessionId, record.steps);
549
+ if (since !== "continued") {
550
+ log?.(`resume: skipped (agy conversation ${since === "prompted" ? "was prompted by another client or branch" : "is gone or unreadable"})`);
551
+ await store.delete(piSessionId).catch(() => undefined);
552
+ return undefined;
553
+ }
554
+ try {
555
+ await this.#verifiedOpen(proc, () => proc.resumeSession({ sessionId: record.acpSessionId, cwd: this.#staging?.workDir ?? this.#config.home }));
556
+ await proc.setConfigOption(record.acpSessionId, "model", request.modelId);
557
+ if (request.thoughtLevel) await proc.setConfigOption(record.acpSessionId, "thought_level", request.thoughtLevel);
558
+ } catch (error) {
559
+ log?.(`resume: failed, replaying instead (${describeError(error)})`);
560
+ await store.delete(piSessionId).catch(() => undefined);
561
+ if (this.#canClose()) void this.#track(proc.closeSession(record.acpSessionId));
562
+ if (!proc.alive) throw error;
563
+ return undefined;
564
+ }
565
+ log?.(`resume: reattached agy conversation ${record.acpSessionId.slice(0, 8)} (${held - 1} messages, no replay)`);
566
+ const entry: Entry = {
567
+ process: proc,
568
+ acpSessionId: record.acpSessionId,
569
+ piSessionId,
570
+ chain: request.chain.slice(0, held),
571
+ busy: true,
572
+ stale: false,
573
+ waitingForTool: false,
574
+ leasedAtSeq: 0,
575
+ systemInline: false,
576
+ lastUsed: Date.now(),
577
+ timer: undefined,
578
+ };
579
+ this.#entries.add(entry);
580
+ return entry;
581
+ }
582
+
583
+ /** Remember which agy conversation holds this pi session's chain, with agy's current step count. */
584
+ #record(entry: Entry): void {
585
+ const piSessionId = entry.piSessionId;
586
+ const geminiDir = this.#staging?.geminiDir;
587
+ const store = this.#resumeEnabled() ? this.#store() : undefined;
588
+ if (!piSessionId || !geminiDir || !store || entry.chain.length === 0) return;
589
+ const chain = entry.chain;
590
+ const generation = entry.generation ?? 0;
591
+ // Only valid while the session is idle at this chain: once it is leased again agy's step count belongs to a later
592
+ // turn (a record pairing this chain with those steps would hide that turn's prompt from the resume check).
593
+ const current = (): boolean => !entry.busy && (entry.generation ?? 0) === generation && entry.chain === chain;
594
+ const task = (async () => {
595
+ const now = await readConversationSteps(geminiDir, entry.acpSessionId);
596
+ if (!now) return; // agy has not written it (or the store is unreadable): nothing safe to record
597
+ if (!current()) return;
598
+ await store.set(piSessionId, {
599
+ acpSessionId: entry.acpSessionId,
600
+ chainLength: chain.length,
601
+ chainLast: chain[chain.length - 1] as string,
602
+ steps: now.steps,
603
+ savedAt: Date.now(),
604
+ });
605
+ })().catch((error: unknown) => this.#options.log?.(`resume: record not written (${describeError(error)})`));
606
+ const tracked = task.finally(() => this.#recording.delete(tracked));
607
+ this.#recording.add(tracked);
608
+ }
609
+
610
+ /** Wait for resume records that are being written. */
611
+ async flushRecords(): Promise<void> {
612
+ await Promise.allSettled([...this.#recording]);
613
+ }
614
+
444
615
  /** Was this pi session (or everything) invalidated after `seq`? */
445
616
  #invalidatedSince(piSessionId: string | undefined, seq: number): boolean {
446
617
  if (this.#invalidatedAll > seq) return true;
@@ -508,11 +679,13 @@ export class SessionPool {
508
679
  }
509
680
 
510
681
  #lease(entry: Entry, reused: boolean): Lease {
682
+ entry.generation = (entry.generation ?? 0) + 1;
511
683
  let finished = false;
512
684
  return {
513
685
  process: entry.process,
514
686
  acpSessionId: entry.acpSessionId,
515
687
  reused,
688
+ geminiDir: this.#staging?.geminiDir,
516
689
  systemInline: !reused && entry.systemInline,
517
690
  finish: async (outcome) => {
518
691
  if (finished) return;
@@ -534,6 +707,7 @@ export class SessionPool {
534
707
  entry.chain = outcome.chain;
535
708
  entry.waitingForTool = outcome.awaitingTool === true;
536
709
  entry.lastUsed = Date.now();
710
+ this.#record(entry);
537
711
  this.#armTtl(entry);
538
712
  this.#trim();
539
713
  } else {
@@ -607,7 +781,7 @@ export class SessionPool {
607
781
  this.#entries.delete(entry);
608
782
  }
609
783
  await this.#stopProcess("dispose");
610
- await Promise.allSettled([...this.#closing]);
784
+ await Promise.allSettled([...this.#closing, ...this.#recording]);
611
785
  }
612
786
 
613
787
  /** Kill one specific agy process that stopped answering (a turn ignored its cancel). Other turns on it fail with
@@ -623,7 +797,7 @@ export class SessionPool {
623
797
  this.resetDiscovery();
624
798
  await this.#stopProcess("reset");
625
799
  if (this.#starting) await this.#starting.catch(() => undefined);
626
- await Promise.allSettled([...this.#closing]);
800
+ await Promise.allSettled([...this.#closing, ...this.#recording]);
627
801
  }
628
802
 
629
803
  /** Apply changed settings that need no restart (limits, timeouts). New timers use them; running ones finish as armed. */
package/src/stream.ts CHANGED
@@ -20,8 +20,10 @@ import {
20
20
  import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
21
21
  import { PERMISSION_DENIED_UPDATE } from "./acp/connection.ts";
22
22
  import type { AcpContentBlock, AcpPromptResult, AcpUpdate, AcpUsage } from "./acp/types.ts";
23
+ import { readBackendAttempts, stepCount, type BackendAttempt } from "./conversation-store.ts";
23
24
  import {
24
25
  AgyError,
26
+ backendFailedError,
25
27
  emptyError,
26
28
  exhaustedError,
27
29
  exitedError,
@@ -41,6 +43,8 @@ import { hashChain, serializeHistory, serializeLatest, splitContext } from "./tr
41
43
  const HISTORY_URI = "pi://conversation.md";
42
44
  /** agy truncates converted prompt content at roughly 192 KiB. Keep a conservative margin for its wrappers. */
43
45
  const PROMPT_CHUNK_BYTES = 128 * 1024;
46
+ /** How often agy's conversation store is read for failed backend attempts while a turn has no output. */
47
+ const BACKEND_POLL_MS = 1_000;
44
48
  const CONTEXT_SAFETY_RATIO = 0.15;
45
49
  const MIN_OUTPUT_RESERVE = 32_768;
46
50
 
@@ -123,6 +127,12 @@ class Translator {
123
127
  #parser = new ToolCallStreamParser();
124
128
  readonly #parseTools: boolean;
125
129
  #open: { kind: OpenKind; index: number } | undefined;
130
+ /** Inside a ``` code fence of the visible text (model text there is never filtered). */
131
+ #inFence = false;
132
+ /** The visible text so far ends at a line start (a notice chunk starts on its own line). */
133
+ #atLineStart = true;
134
+ /** The unfinished last line of the visible text (a fence marker can be split across chunks). */
135
+ #partialLine = "";
126
136
  toolCalled = false;
127
137
  producedOutput = false;
128
138
  /** agy's latest "⚠ API error (attempt N)" notice. Never shown as model text. */
@@ -146,17 +156,44 @@ class Translator {
146
156
  this.#output.content = [];
147
157
  this.#parser = new ToolCallStreamParser();
148
158
  this.retryNotice = undefined;
159
+ this.#inFence = false;
160
+ this.#atLineStart = true;
161
+ this.#partialLine = "";
162
+ }
163
+
164
+ /** Keep fence/line state of the text the model has shown, so a notice-shaped chunk can be judged in context. */
165
+ #track(chunk: string): void {
166
+ const lines = (this.#partialLine + chunk).split("\n");
167
+ this.#partialLine = lines.pop() ?? "";
168
+ for (const line of lines) if (/^\s*```/.test(line)) this.#inFence = !this.#inFence;
169
+ this.#atLineStart = this.#partialLine.trim() === "";
149
170
  }
150
171
 
151
172
  /** Returns true when this chunk completed a tool-call block. */
152
173
  message(chunk: string): boolean {
153
174
  if (this.toolCalled) return false;
154
- // agy only retries before the model has answered; once real text flowed, a matching line is the model's own.
155
- const notice = this.producedOutput ? undefined : parseApiRetryNotice(chunk);
156
- if (notice) {
175
+ // Before the model has answered, every retry notice is agy's (a 429 one is acted on by the caller).
176
+ const notice = parseApiRetryNotice(chunk);
177
+ if (notice && !this.producedOutput) {
157
178
  this.retryNotice = notice;
158
179
  return false;
159
180
  }
181
+ // agy also retries transient backend errors mid-answer ("stream reading error: unexpected EOF", 503): such a
182
+ // notice arrives as its own chunk on its own line and is not model text. A model quoting one does so inside a
183
+ // code fence or mid-line, and a quoted 429 notice is kept as text (the `quote` contract). Idea from
184
+ // patlux/pi-antigravity-thin-client (QuotaSoftErrorFilter, MIT).
185
+ if (notice && !notice.exhausted) {
186
+ // agy's notice brings its own leading line break, so it starts a line even right after a sentence that was cut
187
+ // off; that break also completes a pending ``` marker, which then opens or closes a fence before the notice.
188
+ const ownLine = /^\r?\n/.test(chunk);
189
+ const fenceClosedHere = ownLine && /^\s*```/.test(this.#partialLine);
190
+ const inFence = fenceClosedHere ? !this.#inFence : this.#inFence;
191
+ if (!inFence && (this.#atLineStart || ownLine)) {
192
+ // Keep the line structure: the text before the notice ends its line, as agy's own break would have done.
193
+ return this.#partialLine ? this.message("\n") : false;
194
+ }
195
+ }
196
+ this.#track(chunk);
160
197
  // After its last retry agy sends one more line, "⚠ <the same error>", and ends the turn. Not model text either.
161
198
  if (this.retryNotice && !this.producedOutput && /^\s*\u26A0/u.test(chunk) && chunk.includes(this.retryNotice.detail.slice(0, 40))) {
162
199
  return false;
@@ -242,11 +279,13 @@ class Translator {
242
279
  /** `exhausted`: agy's RESOURCE_EXHAUSTED notice arrived (agy <= 1.5.12 sends one per retry). `refused`: a fresh session
243
280
  * with the appended system prompt produced nothing within the refusal probe window (agy 1.5.14 retries silently and
244
281
  * sends one notice only after ~140 s). Both mean "retry inline" in auto mode. */
245
- type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted" | "refused";
282
+ type CancelReason = "tool" | "abort" | "stall" | "timeout" | "exhausted" | "refused" | "backend";
246
283
 
247
284
  interface TurnResult {
248
285
  result: AcpPromptResult | undefined;
249
286
  cancelReason: CancelReason | undefined;
287
+ /** With cancelReason "backend": agy's failed attempts seen in its conversation store, and the last error. */
288
+ backend?: { attempts: number; detail: string };
250
289
  /** The prompt did not settle within the grace period after a cancel. */
251
290
  wedged: boolean;
252
291
  }
@@ -334,6 +373,10 @@ async function runReplayPart(
334
373
  translator.finish();
335
374
  replayStream.end();
336
375
  if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
376
+ if (turn.cancelReason === "backend") {
377
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "backend failed and ignored cancel");
378
+ throw backendFailedError(turn.backend?.attempts ?? 0, turn.backend?.detail ?? "unknown", `${model.id}, replay part ${index}/${total}`);
379
+ }
337
380
  if (turn.cancelReason === "stall") {
338
381
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay stalled and ignored cancel");
339
382
  throw stalledError(runtime.config.silenceMs);
@@ -535,6 +578,11 @@ async function run(
535
578
  );
536
579
 
537
580
  if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
581
+ if (turn.cancelReason === "backend") {
582
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "backend failed and ignored cancel");
583
+ output.content = [];
584
+ throw backendFailedError(turn.backend?.attempts ?? 0, turn.backend?.detail ?? "unknown", `${model.id}, ${lease.reused ? "continued session" : "fresh session"}`);
585
+ }
538
586
  if (turn.cancelReason === "stall") {
539
587
  if (turn.wedged) await runtime.pool.killProcess(lease.process, "stalled and ignored cancel");
540
588
  throw stalledError(runtime.config.silenceMs);
@@ -702,6 +750,8 @@ async function runTurn(
702
750
  let graceTimer: NodeJS.Timeout | undefined;
703
751
  let silenceTimer: NodeJS.Timeout | undefined;
704
752
  let probeTimer: NodeJS.Timeout | undefined;
753
+ let backendTimer: NodeJS.Timeout | undefined;
754
+ let backend: { attempts: number; detail: string } | undefined;
705
755
  let settled = false;
706
756
  // Diagnostics for stalls and timeouts (PI_AGY_TRACE=1): what agy last sent, and when.
707
757
  const startedAt = Date.now();
@@ -726,6 +776,7 @@ async function runTurn(
726
776
  if (silenceTimer) clearTimeout(silenceTimer);
727
777
  if (totalTimer) clearTimeout(totalTimer);
728
778
  if (probeTimer) clearTimeout(probeTimer);
779
+ if (backendTimer) clearInterval(backendTimer);
729
780
  proc.cancel(acpSessionId);
730
781
  graceTimer = setTimeout(expire, graceMs);
731
782
  graceTimer.unref();
@@ -792,6 +843,36 @@ async function runTurn(
792
843
  }, refusalProbeMs);
793
844
  probeTimer.unref();
794
845
  }
846
+ // agy 1.5.18 retries a failing backend (503 "high demand", 429) silently for minutes and only its conversation
847
+ // store records each failed attempt. While the model has said nothing, read those attempts and stop after
848
+ // `backendRetries` of them in a row, so fallback chains move on in seconds instead of after the silence guard.
849
+ // Any model output ends the watch: agy only retries before the model has produced anything.
850
+ const retries = runtime.config.backendRetries;
851
+ const geminiDir = lease.geminiDir;
852
+ if (retries > 0 && geminiDir) {
853
+ const fromStep = (await stepCount(geminiDir, acpSessionId)) ?? 0;
854
+ let reading = false;
855
+ backendTimer = setInterval(() => {
856
+ if (reading || settled || cancelReason) return;
857
+ if (translator.producedOutput || translator.toolCalled) {
858
+ if (backendTimer) clearInterval(backendTimer);
859
+ return;
860
+ }
861
+ reading = true;
862
+ void readBackendAttempts(geminiDir, acpSessionId, fromStep)
863
+ .then((attempts) => {
864
+ if (!attempts || attempts.length < retries || settled || cancelReason || translator.producedOutput) return;
865
+ const last = attempts[attempts.length - 1] as BackendAttempt;
866
+ backend = { attempts: attempts.length, detail: last.detail };
867
+ runtime.trace(`turn: backend model=${model.id} failed ${attempts.length} attempts with no output; last: ${last.detail.slice(0, 160)}`);
868
+ requestCancel("backend");
869
+ })
870
+ .finally(() => {
871
+ reading = false;
872
+ });
873
+ }, BACKEND_POLL_MS);
874
+ backendTimer.unref();
875
+ }
795
876
  const promptPromise = proc.prompt(acpSessionId, prompt).then(
796
877
  (result) => ({ kind: "result" as const, result }),
797
878
  (error: unknown) => ({ kind: "error" as const, error }),
@@ -800,7 +881,7 @@ async function runTurn(
800
881
  if (first === "grace") {
801
882
  // The prompt ignored the cancel. Do not wait for it forever; the caller discards or kills the session.
802
883
  void promptPromise;
803
- return { result: undefined, cancelReason, wedged: true };
884
+ return { result: undefined, cancelReason, wedged: true, ...(backend ? { backend } : {}) };
804
885
  }
805
886
  if (first.kind === "error") {
806
887
  if (!proc.alive) {
@@ -809,12 +890,13 @@ async function runTurn(
809
890
  }
810
891
  throw first.error;
811
892
  }
812
- return { result: first.result, cancelReason, wedged: false };
893
+ return { result: first.result, cancelReason, wedged: false, ...(backend ? { backend } : {}) };
813
894
  } finally {
814
895
  settled = true;
815
896
  if (silenceTimer) clearTimeout(silenceTimer);
816
897
  if (totalTimer) clearTimeout(totalTimer);
817
898
  if (probeTimer) clearTimeout(probeTimer);
899
+ if (backendTimer) clearInterval(backendTimer);
818
900
  if (graceTimer) clearTimeout(graceTimer);
819
901
  options?.signal?.removeEventListener("abort", onAbort);
820
902
  stop();