wildcrane-runner 0.6.89 → 0.6.90

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.
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.89 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.90 — built by runner/scripts/build.mjs. Do not edit.
2
2
  import { createRequire as __ai4kanbanRequire } from 'node:module'
3
3
  const require = __ai4kanbanRequire(import.meta.url)
4
4
  var __create = Object.create;
@@ -126179,14 +126179,75 @@ function argHint(input2, keys) {
126179
126179
  return "";
126180
126180
  }
126181
126181
 
126182
+ // ../cli/src/lib/agent/wire/failures.ts
126183
+ var ExecutionError = class extends Error {
126184
+ constructor(failure2) {
126185
+ super(failure2.reason);
126186
+ this.failure = failure2;
126187
+ }
126188
+ failure;
126189
+ };
126190
+ var NETWORK = /* @__PURE__ */ new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "ENETUNREACH", "EAI_AGAIN", "UND_ERR_SOCKET"]);
126191
+ var TEMPORARY_HTTP = /* @__PURE__ */ new Set([502, 503, 504, 529]);
126192
+ function executionFailure(error62) {
126193
+ if (error62 instanceof ExecutionError) return error62.failure;
126194
+ const code = str(obj(error62).code);
126195
+ const reason = error62 instanceof Error ? error62.message : String(error62);
126196
+ return {
126197
+ code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
126198
+ level: NETWORK.has(code) ? 2 : 3,
126199
+ reason
126200
+ };
126201
+ }
126202
+ function retryAfterMs(value, now = Date.now()) {
126203
+ if (typeof value !== "string") return;
126204
+ const header = value.trim();
126205
+ if (/^\d+$/.test(header)) return Math.min(Number(header) * 1e3, Number.MAX_SAFE_INTEGER);
126206
+ if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header)) return;
126207
+ const date5 = Date.parse(header);
126208
+ if (Number.isFinite(date5)) return Math.max(0, date5 - now);
126209
+ }
126210
+ function providerFailure(error62, reason) {
126211
+ const info = obj(error62);
126212
+ const status = typeof info.status === "number" ? info.status : void 0;
126213
+ const headers = obj(info.headers);
126214
+ const wait3 = retryAfterMs(headers["retry-after"] ?? headers["Retry-After"]);
126215
+ const code = info.code ?? info.type;
126216
+ if (code === "session_not_found") return { code, level: 3, reason };
126217
+ if (status === 401 || status === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str(code))) {
126218
+ return { code: "provider_refused", level: 3, reason };
126219
+ }
126220
+ if (code === "rate_limit_error") return { code: "rate_limited", level: 2, reason, retryAfterMs: wait3 };
126221
+ if (TEMPORARY_HTTP.has(status ?? 0) || code === "overloaded_error") return { code: "service_overloaded", level: 2, reason, retryAfterMs: wait3 };
126222
+ if (NETWORK.has(str(code))) return { code: "connection_lost", level: 2, reason, retryAfterMs: wait3 };
126223
+ return { code: "provider_failed", level: 3, reason };
126224
+ }
126225
+ function codexFailure(raw, fallback) {
126226
+ const error62 = obj(raw);
126227
+ const reason = str(error62.message) || fallback;
126228
+ const info = error62.codexErrorInfo;
126229
+ if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason);
126230
+ if (info === "rateLimitExceeded") return providerFailure({ ...error62, type: "rate_limit_error" }, reason);
126231
+ const types = obj(info);
126232
+ for (const kind of ["httpConnectionFailed", "responseStreamConnectionFailed", "responseStreamDisconnected", "responseTooManyFailedAttempts"]) {
126233
+ if (!(kind in types)) continue;
126234
+ const status = obj(types[kind]).httpStatusCode;
126235
+ if (typeof status === "number") return providerFailure({ ...error62, status }, reason);
126236
+ if (kind !== "responseTooManyFailedAttempts") return providerFailure({ ...error62, code: "ECONNRESET" }, reason);
126237
+ }
126238
+ return providerFailure(error62, reason);
126239
+ }
126240
+
126182
126241
  // ../cli/src/lib/agent/wire/rpc.ts
126183
126242
  var RpcError = class extends Error {
126184
- constructor(message, code) {
126243
+ constructor(message, code, data) {
126185
126244
  super(message);
126186
126245
  this.code = code;
126246
+ this.data = data;
126187
126247
  this.name = "RpcError";
126188
126248
  }
126189
126249
  code;
126250
+ data;
126190
126251
  };
126191
126252
  function connect(stdout, stdin, onCall, dialect = {}) {
126192
126253
  let buf = "";
@@ -126204,7 +126265,7 @@ function connect(stdout, stdin, onCall, dialect = {}) {
126204
126265
  const closed = (why2) => {
126205
126266
  if (gone) return;
126206
126267
  gone = why2;
126207
- for (const { fail } of waiting.values()) fail(new Error(why2));
126268
+ for (const { fail } of waiting.values()) fail(why2);
126208
126269
  waiting.clear();
126209
126270
  };
126210
126271
  stdout.on("data", (chunk) => {
@@ -126229,17 +126290,17 @@ function connect(stdout, stdin, onCall, dialect = {}) {
126229
126290
  waiting.delete(String(msg.id));
126230
126291
  if (msg.error) {
126231
126292
  const said = [str(msg.error.message), str(obj(msg.error.data).message)].filter(Boolean).join(": ");
126232
- pending.fail(new RpcError(said || `the agent refused (${msg.error.code ?? "no code"})`, msg.error.code));
126293
+ pending.fail(new RpcError(said || `the agent refused (${msg.error.code ?? "no code"})`, msg.error.code, msg.error.data));
126233
126294
  } else pending.ok(obj(msg.result));
126234
126295
  }
126235
126296
  });
126236
- stdout.on("close", () => closed("the agent closed the connection"));
126237
- stdout.on("error", (err) => closed(String(err)));
126238
- stdin.on("error", (err) => closed(String(err)));
126297
+ stdout.on("close", () => closed(new ExecutionError({ code: "connection_lost", level: 2, reason: "The agent closed the connection." })));
126298
+ stdout.on("error", (err) => closed(new ExecutionError(executionFailure(err))));
126299
+ stdin.on("error", (err) => closed(new ExecutionError(executionFailure(err))));
126239
126300
  return {
126240
126301
  /** Ask the agent something. Rejects with the agent's own words when it says no. */
126241
126302
  call(method, params) {
126242
- if (gone) return Promise.reject(new Error(gone));
126303
+ if (gone) return Promise.reject(gone);
126243
126304
  const id2 = dialect.stringIds ? String(nextId++) : nextId++;
126244
126305
  return new Promise((ok, fail) => {
126245
126306
  waiting.set(String(id2), { ok, fail });
@@ -126358,8 +126419,8 @@ async function studioSnapshot(workspace, catalog, list3) {
126358
126419
  }
126359
126420
 
126360
126421
  // src/protocol.ts
126361
- var AKB_VERSION = true ? "0.11.72" : "0.0.0";
126362
- var AKB_CONTRACT = true ? 19 : 0;
126422
+ var AKB_VERSION = true ? "0.11.73" : "0.0.0";
126423
+ var AKB_CONTRACT = true ? 20 : 0;
126363
126424
 
126364
126425
  // src/secrets.ts
126365
126426
  import fs8 from "node:fs";
@@ -126498,9 +126559,17 @@ var readBoard = (project, since) => request("GET", `/v1/projects/${q(project)}/b
126498
126559
  async function commitBoard(project, job, machine, files) {
126499
126560
  const sent = await send("POST", `/v1/projects/${q(project)}/board/commits`, { job, machine, files }, true, TIMEOUT_MS);
126500
126561
  if (!sent.ok) return sent;
126501
- if (sent.value.status !== 409) return answerOf(sent.value);
126562
+ if (sent.value.status !== 409 && sent.value.status !== 400) return answerOf(sent.value);
126563
+ const status = sent.value.status;
126502
126564
  const answer = await sent.value.json().catch(() => null);
126503
- return { ok: false, error: answer?.error?.message ?? "Cloud answered 409", code: answer?.error?.code ?? "refused", ...answer?.files ? { files: answer.files } : {} };
126565
+ const problems = answer?.error?.details?.problems;
126566
+ return {
126567
+ ok: false,
126568
+ error: answer?.error?.message ?? `Cloud answered ${status}`,
126569
+ code: answer?.error?.code ?? "refused",
126570
+ ...status === 409 && answer?.files ? { files: answer.files } : {},
126571
+ ...status === 400 && Array.isArray(problems) ? { previewProblems: problems } : {}
126572
+ };
126504
126573
  }
126505
126574
  var readTaskStudio = (task) => request("GET", `/v1/tasks/${q(task)}/studio`);
126506
126575
  var listStudios = (workspace, after) => request("GET", `/v1/studios?workspace=${q(workspace)}&limit=100${after ? `&after=${q(after)}` : ""}`);
@@ -128187,7 +128256,8 @@ function createStreamRenderer() {
128187
128256
  let context;
128188
128257
  let limit;
128189
128258
  let failure2;
128190
- let offStream;
128259
+ let apiFailure;
128260
+ let classified;
128191
128261
  let background;
128192
128262
  const turns2 = [];
128193
128263
  const backgrounded = /* @__PURE__ */ new Set();
@@ -128203,16 +128273,14 @@ function createStreamRenderer() {
128203
128273
  const renderLine = (line) => {
128204
128274
  if (!line.trim()) return "";
128205
128275
  const ev = frame(line);
128206
- if (!ev) {
128207
- offStream = line.trim();
128208
- return `${line}
128276
+ if (!ev) return `${line}
128209
128277
  `;
128210
- }
128211
128278
  if (model === void 0) model = eventModel(ev);
128212
128279
  if (str(ev.parent_tool_use_id)) return "";
128213
128280
  if (ev.type === "assistant" || ev.type === "stream_event" && obj(ev.event).type === "content_block_delta") events.progress();
128214
128281
  switch (ev.type) {
128215
128282
  case "assistant": {
128283
+ apiFailure = typeof ev.error === "string" ? providerFailure({ type: ev.error }, "Claude could not complete the request.") : void 0;
128216
128284
  const msg = ev.message;
128217
128285
  const holding = promptSize(msg?.usage);
128218
128286
  if (holding) context = { used: holding };
@@ -128265,6 +128333,8 @@ function createStreamRenderer() {
128265
128333
  const turnUsage = usageOf(ev.usage);
128266
128334
  if (turnUsage) usage = usage ? addUsage(usage, turnUsage) : turnUsage;
128267
128335
  failure2 = ev.is_error === true ? whyItFailed(ev) : void 0;
128336
+ classified = failure2 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, reason: failure2 } : { ...apiFailure ?? providerFailure(ev.error, failure2), reason: failure2 } : void 0;
128337
+ apiFailure = void 0;
128268
128338
  if (failure2) events.error(failure2);
128269
128339
  turns2.push({
128270
128340
  ...typeof ev.result === "string" ? { result: ev.result } : {},
@@ -128299,7 +128369,7 @@ function createStreamRenderer() {
128299
128369
  context: () => context && limit ? { ...context, limit } : context,
128300
128370
  model: () => model,
128301
128371
  failure: () => failure2,
128302
- offStream: () => offStream,
128372
+ executionFailure: () => classified,
128303
128373
  background: () => background,
128304
128374
  turns: () => turns2,
128305
128375
  events: events.events,
@@ -128761,15 +128831,15 @@ function createCodexStreamRenderer(carried = false) {
128761
128831
  return "";
128762
128832
  // 最终失败保留;连接提示只在没有后续成功完成时才作为失败。
128763
128833
  case "turn.failed": {
128764
- const said = str(obj(ev.error).message) || failure2 || "Codex \u6267\u884C\u5931\u8D25";
128765
- failure2 = said;
128834
+ const said = str(obj(ev.error).message) || failure2?.reason || "Codex execution failed.";
128835
+ failure2 = codexFailure(ev.error, said);
128766
128836
  events.error(said);
128767
128837
  return `[error] ${said}
128768
128838
  `;
128769
128839
  }
128770
128840
  case "error": {
128771
128841
  const said = str(ev.message);
128772
- failure2 = said || failure2;
128842
+ if (ev.willRetry !== true && ev.will_retry !== true && said) failure2 = codexFailure(ev.error ?? ev, said);
128773
128843
  events.log(`[Codex] ${said}
128774
128844
  `);
128775
128845
  return `[Codex] ${said}
@@ -128816,7 +128886,8 @@ function createCodexStreamRenderer(carried = false) {
128816
128886
  },
128817
128887
  costIncomplete: () => childSpend(subagents, since).costIncomplete || childSpend(subagents, since).costUsd !== void 0 && priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own2()) === void 0 || void 0,
128818
128888
  resumeId: () => threadId,
128819
- failure: () => failure2 ?? background.failure(),
128889
+ failure: () => failure2?.reason ?? background.failure(),
128890
+ executionFailure: () => failure2,
128820
128891
  background: () => subagents.size ? background.count() : void 0,
128821
128892
  events: events.events,
128822
128893
  activity: events.activity
@@ -129145,8 +129216,8 @@ function createTail(log) {
129145
129216
  // ../cli/package.json
129146
129217
  var package_default = {
129147
129218
  name: "wildcrane",
129148
- version: "0.11.72",
129149
- akbContract: 19,
129219
+ version: "0.11.73",
129220
+ akbContract: 20,
129150
129221
  description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
129151
129222
  keywords: [
129152
129223
  "kanban",
@@ -129270,10 +129341,6 @@ function usageOf2(value, grossInput = false) {
129270
129341
  const sum = counts2.input + counts2.cacheCreation + counts2.cacheRead + counts2.output;
129271
129342
  return sum > 0 ? counts2 : void 0;
129272
129343
  }
129273
- var INVALID_PARAMS = -32602;
129274
- function sessionGone(e2) {
129275
- return e2 instanceof RpcError && e2.code === INVALID_PARAMS && /session\b.*\bnot found/i.test(e2.message);
129276
- }
129277
129344
  var RESTARTED = "[board] that conversation is gone \u2014 the task was restarted in a new session\n";
129278
129345
  async function newSession(rpc, cwd, mcpServers) {
129279
129346
  const opened = await rpc.call("session/new", { cwd, mcpServers });
@@ -129392,7 +129459,10 @@ async function oneTurn(io, options) {
129392
129459
  try {
129393
129460
  opened = await bounded(rpc.call("session/load", { sessionId, cwd: io.cwd, mcpServers }), preparingUntil - Date.now(), "ACP session/load timed out.");
129394
129461
  } catch (e2) {
129395
- if (!sessionGone(e2) || !io.restartPrompt) throw e2;
129462
+ const reason = e2 instanceof Error ? e2.message : String(e2);
129463
+ const failure2 = e2 instanceof RpcError ? providerFailure(e2.data, reason) : executionFailure(e2);
129464
+ if (failure2.code !== "session_not_found") throw e2;
129465
+ if (!io.restartPrompt) throw new ExecutionError(failure2);
129396
129466
  const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
129397
129467
  opened = fresh.opened;
129398
129468
  sessionId = fresh.sessionId;
@@ -129439,7 +129509,7 @@ async function oneTurn(io, options) {
129439
129509
  `);
129440
129510
  events.error(why2);
129441
129511
  emit();
129442
- return { ok: false, result, error: why2, usage, context, costUsd };
129512
+ return { ok: false, result, error: why2, failure: { code: stopReason, level: 3, reason: why2 }, usage, context, costUsd };
129443
129513
  }
129444
129514
  emit();
129445
129515
  return { ok: true, result, usage, context, costUsd };
@@ -129452,7 +129522,7 @@ async function oneTurn(io, options) {
129452
129522
  events.error(error62);
129453
129523
  emit();
129454
129524
  if (currentSession) saveAcpCost(acpCostFile(options.tool ?? "acp", io.cwd, currentSession), costUsd);
129455
- return { ok: false, result, error: error62, usage: void 0, costUsd: costUsd === void 0 || costBefore === void 0 ? void 0 : costUsd < costBefore ? costUsd : costUsd - costBefore };
129525
+ return { ok: false, result, error: error62, failure: e2 instanceof RpcError ? providerFailure(e2.data, error62) : executionFailure(e2), usage: void 0, costUsd: costUsd === void 0 || costBefore === void 0 ? void 0 : costUsd < costBefore ? costUsd : costUsd - costBefore };
129456
129526
  } finally {
129457
129527
  io.signal?.removeEventListener("abort", cancelled);
129458
129528
  }
@@ -129743,14 +129813,14 @@ async function oneTurn2(io, options) {
129743
129813
  if (!done.ok) {
129744
129814
  const why2 = done.error ?? "the agent stopped without saying why";
129745
129815
  stopped(io, why2);
129746
- return { ok: false, result, error: why2, usage, context };
129816
+ return { ok: false, result, error: why2, failure: done.failure, usage, context };
129747
129817
  }
129748
129818
  return { ok: true, result, usage, context };
129749
129819
  } catch (e2) {
129750
129820
  const error62 = e2 instanceof Error ? e2.message : String(e2);
129751
129821
  const result = tail.end();
129752
129822
  stopped(io, error62);
129753
- return { ok: false, result, error: error62 };
129823
+ return { ok: false, result, error: error62, failure: executionFailure(e2) };
129754
129824
  } finally {
129755
129825
  io.signal?.removeEventListener("abort", cancelled);
129756
129826
  }
@@ -129798,7 +129868,8 @@ function event(envelope, parts, tail, live, ended2) {
129798
129868
  }
129799
129869
  case "turn.failed": {
129800
129870
  const error62 = obj(payload.error);
129801
- return ended2({ ok: false, error: str(error62.message) || "the turn failed" });
129871
+ const failure2 = providerFailure(error62, str(error62.message) || "the turn failed");
129872
+ return ended2({ ok: false, error: failure2.reason, failure: failure2 });
129802
129873
  }
129803
129874
  case "session.closed":
129804
129875
  return ended2({ ok: false, error: str(payload.reason) || "the agent closed the session" });
@@ -130112,7 +130183,7 @@ async function run(io, options, count2) {
130112
130183
  io.log(renderer.push(JSON.stringify({ type, ...extra }) + "\n"));
130113
130184
  for (const event2 of renderer.events?.() ?? []) io.event?.(event2);
130114
130185
  };
130115
- const end = (error62) => {
130186
+ const end = (error62, classified) => {
130116
130187
  if (ended2) return;
130117
130188
  ended2 = true;
130118
130189
  clearTimeout(timer);
@@ -130132,15 +130203,16 @@ async function run(io, options, count2) {
130132
130203
  const costUsd = cost === void 0 ? child.costUsd : cost + (child.costUsd ?? 0);
130133
130204
  const failure2 = error62 || (cleanup.status === "unconfirmed" ? cleanup.detail : void 0) || work.work().filter((w2) => !w2.intentionalStop && ["failed", "interrupted"].includes(w2.status)).map((w2) => w2.result || `Background work ${w2.id} ${w2.status}.`).join("\n") || void 0;
130134
130205
  if (failure2) io.event?.({ kind: "error", data: { text: failure2 } });
130135
- resolve2({ ok: !failure2, error: failure2, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
130206
+ resolve2({ ok: !failure2, error: failure2, failure: failure2 ? classified ?? { code: "execution_failed", level: 3, reason: failure2 } : void 0, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
130136
130207
  };
130137
130208
  const closed = () => {
130138
- note("Connection lost; managed cleanup is unconfirmed.");
130139
- end("Codex connection closed before all work and results finished.");
130209
+ const reason = "Codex connection closed before all work and results finished.";
130210
+ if (work.work().some((w2) => ["running", "unknown"].includes(w2.status))) note("Connection lost; managed cleanup is unconfirmed.");
130211
+ end(reason, { code: "connection_lost", level: 2, reason });
130140
130212
  };
130141
130213
  const inputFailed = (e2) => {
130142
- note("Connection input failed; managed cleanup is unconfirmed.");
130143
- end(e2.message);
130214
+ if (work.work().some((w2) => ["running", "unknown"].includes(w2.status))) note("Connection input failed; managed cleanup is unconfirmed.");
130215
+ end(e2.message, executionFailure(e2));
130144
130216
  };
130145
130217
  io.stdout.once("close", closed);
130146
130218
  io.stdin.once("error", inputFailed);
@@ -130402,7 +130474,10 @@ async function run(io, options, count2) {
130402
130474
  context = { used: (Number(last.inputTokens) || 0) + (Number(last.outputTokens) || 0), ...Number(token.modelContextWindow) > 0 ? { limit: Number(token.modelContextWindow) } : {} };
130403
130475
  io.gotContext?.(context);
130404
130476
  }
130405
- if (msg.method === "error" && p2.willRetry !== true) end(str(obj(p2.error).message) || "Codex failed.");
130477
+ if (msg.method === "error" && p2.willRetry !== true) {
130478
+ const failure2 = codexFailure(p2.error, "Codex failed.");
130479
+ end(failure2.reason, failure2);
130480
+ }
130406
130481
  if (msg.method === "turn/completed") {
130407
130482
  const turn2 = obj(p2.turn);
130408
130483
  const id2 = str(turn2.id);
@@ -130413,7 +130488,9 @@ async function run(io, options, count2) {
130413
130488
  item(raw, true);
130414
130489
  }
130415
130490
  if (turn2.status !== "completed") {
130416
- end(str(obj(turn2.error).message) || `Codex turn ${str(turn2.status)}.`);
130491
+ const reason = str(obj(turn2.error).message) || `Codex turn ${str(turn2.status)}.`;
130492
+ const failure2 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : { code: "turn_stopped", level: 3, reason };
130493
+ end(reason, failure2);
130417
130494
  return;
130418
130495
  }
130419
130496
  active = false;
@@ -130437,13 +130514,7 @@ async function run(io, options, count2) {
130437
130514
  phase("initialized");
130438
130515
  rpc.notify("initialized");
130439
130516
  const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
130440
- let response;
130441
- try {
130442
- response = await bounded(rpc.call(`thread/${mode ?? "start"}`, { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} }), preparingUntil - Date.now(), `Codex thread/${mode ?? "start"} timed out.`);
130443
- } catch (e2) {
130444
- if (mode && e2 instanceof RpcError && /no rollout found for thread id/i.test(e2.message)) throw Error(`Thread not found: ${e2.message}`);
130445
- throw e2;
130446
- }
130517
+ const response = await bounded(rpc.call(`thread/${mode ?? "start"}`, { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} }), preparingUntil - Date.now(), `Codex thread/${mode ?? "start"} timed out.`);
130447
130518
  const thread = obj(response.thread);
130448
130519
  for (const turn2 of list2(thread.turns)) historicalTurns.add(str(turn2.id));
130449
130520
  threadId = str(thread.id);
@@ -130460,7 +130531,8 @@ async function run(io, options, count2) {
130460
130531
  phase("ready");
130461
130532
  await start(io.prompt, options.images);
130462
130533
  } catch (e2) {
130463
- end(e2 instanceof Error ? e2.message : String(e2));
130534
+ const failure2 = e2 instanceof RpcError ? codexFailure(e2.data, e2.message) : executionFailure(e2);
130535
+ end(failure2.reason, failure2);
130464
130536
  }
130465
130537
  return done;
130466
130538
  }
@@ -130991,65 +131063,6 @@ function modelsIn2(file3, pick3, salt = "") {
130991
131063
  return found.length ? found : hit?.found ?? [];
130992
131064
  }
130993
131065
 
130994
- // ../cli/src/lib/agent/harnesses/transient.ts
130995
- var MANUAL = [
130996
- /\b(401|403)\b/,
130997
- /unauthorized|forbidden|permission (?:denied|required|check failed)|permission_denied|soft.denied|auto-denied|权限拒绝/,
130998
- /authenticat|invalid api key|api[_ ]key|not (?:logged|signed) in|please (?:log|sign) in|\/login|oauth/,
130999
- /usage limit|quota|balance|credits?|insufficient|out of tokens|resource[ _-]?exhausted/,
131000
- /cancell?ed|aborted by|interrupted by the user/,
131001
- /maximum budget|max(imum)? turns|exceeded the budget/,
131002
- /model not found|unknown model|invalid model|model (?:is )?unavailable|model[^\n]+ is (?:unavailable|not recognized)|unsupported|invalid[_ ]request/
131003
- ];
131004
- var PASSING = [
131005
- // 502/503/529 are distinctive enough to read as a status wherever they appear. A bare
131006
- // 500 is not — a failure line counting something would match it — so it is left to the
131007
- // words below, which is how that status is actually written out.
131008
- /\b(502|503|529)\b/,
131009
- /at capacity|overloaded|service unavailable|bad gateway|internal server error|server_error/,
131010
- /connection (lost|dropped|reset|error|closed)|socket hang up|stream (error|disconnected)/,
131011
- /econnreset|econnrefused|etimedout|enetunreach|enotfound|eai_again/,
131012
- /fetch failed|request timed out|network (?:error|failure)|temporary network failure/,
131013
- /(?:initialize|connection|connect|response)[^\n]*timed out|idle[_ -]?timeout|stream[^\n]*timed out|no (?:response|events?) for 5 minutes/,
131014
- /request failed:[^\n]*\b(?:unexpected )?eof\b/,
131015
- /rpc error: code = (?:unavailable|deadlineexceeded)\b|deadline_exceeded|dial tcp[^\n]*(?:timeout|refused|no such host)/
131016
- ];
131017
- var RETRY_AFTER = /retry[-_\s]?after["':=\s]+(\d+)/i;
131018
- var REASON_MAX = 140;
131019
- function reasonLine(text4, rule) {
131020
- const line = text4.split("\n").find((l2) => rule.test(l2.toLowerCase())) ?? text4;
131021
- const said = line.trim().replace(/\s+/g, " ");
131022
- return said.length > REASON_MAX ? `${said.slice(0, REASON_MAX - 1)}\u2026` : said;
131023
- }
131024
- function manualFailure(text4) {
131025
- return MANUAL.some((rule) => rule.test(text4.toLowerCase()));
131026
- }
131027
- function providerBlip(...said) {
131028
- for (const text4 of said) {
131029
- if (!text4?.trim()) continue;
131030
- const lower = text4.toLowerCase();
131031
- if (manualFailure(text4)) return void 0;
131032
- const limited2 = /\b429\b|rate[ _-]?limit/.test(lower);
131033
- const hit = limited2 && RETRY_AFTER.test(text4) ? RETRY_AFTER : limited2 ? void 0 : PASSING.find((rule) => rule.test(lower));
131034
- if (!hit) continue;
131035
- const asked = RETRY_AFTER.exec(text4);
131036
- const seconds = asked ? Number(asked[1]) : NaN;
131037
- return {
131038
- reason: reasonLine(text4, hit),
131039
- ...Number.isFinite(seconds) && seconds > 0 ? { retryAfterMs: seconds * 1e3 } : {}
131040
- };
131041
- }
131042
- return void 0;
131043
- }
131044
- function recoveryFailure(text4) {
131045
- const temporary = providerBlip(text4);
131046
- if (temporary) return { ...temporary, handler: "execution" };
131047
- if (!manualFailure(text4) && /(?:verification|validation|test|compilation|build) failed|syntax error|type error/i.test(text4)) {
131048
- return { reason: text4, handler: "agent", retryAfterMs: 0 };
131049
- }
131050
- return void 0;
131051
- }
131052
-
131053
131066
  // ../cli/src/lib/agent/wire/antigravity.ts
131054
131067
  import path26 from "node:path";
131055
131068
  var KINDS = {
@@ -131080,7 +131093,6 @@ function failureHint(reason) {
131080
131093
  return hint2 ? `${reason}
131081
131094
  ${hint2}` : reason;
131082
131095
  }
131083
- var limited = (reason) => /\b429\b|rate[ _-]?limit|resource[ _-]?exhausted|quota[^\n]*\b(?:exceeded|exhausted|depleted|reached)\b|(?:exceed|exhaust|deplet)[^\n]*quota|(?:insufficient|exhausted|out of|no remaining) (?:credits?|quota)|credits?[^\n]*(?:exhaust|deplet|exceed)/i.test(reason);
131084
131096
  var imagePath = (target) => /\.(?:png|jpe?g|gif|webp|bmp|tiff?|svg)$/i.test(target);
131085
131097
  function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
131086
131098
  let session = expectedSession;
@@ -131088,7 +131100,7 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
131088
131100
  let partial2 = "";
131089
131101
  let final;
131090
131102
  let failure2;
131091
- let rateLimit;
131103
+ let classified;
131092
131104
  let imageFailure;
131093
131105
  let requiredImages = [];
131094
131106
  const readImages = /* @__PURE__ */ new Set();
@@ -131120,24 +131132,22 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
131120
131132
  const calls = /* @__PURE__ */ new Set();
131121
131133
  const closed = /* @__PURE__ */ new Set();
131122
131134
  const events = createEventCollector();
131123
- const fail = (reason) => {
131124
- if (limited(reason)) rateLimit = failureHint(reason);
131125
- if (failure2 && manualFailure(failure2) && !(limited(failure2) && limited(reason))) return;
131135
+ const fail = (reason, code = "provider_failed") => {
131126
131136
  failure2 = failureHint(reason);
131137
+ classified = { code, level: 3, reason: failure2 };
131127
131138
  events.error(failure2);
131128
131139
  };
131129
131140
  const reader = createLineReader((line) => {
131130
131141
  const e2 = frame(line);
131131
131142
  if (!e2) {
131132
131143
  offStream = line.trim() || offStream;
131133
- if (/^(?:error:|rpc error:)/i.test(line.trim()) && limited(line)) fail(line.trim());
131134
131144
  return `${line}
131135
131145
  `;
131136
131146
  }
131137
131147
  if (e2.event === "init") {
131138
131148
  const got = str(e2.conversation_id);
131139
131149
  if (expectedSession && got !== expectedSession) {
131140
- fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.");
131150
+ fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.", "session_mismatch");
131141
131151
  return "";
131142
131152
  }
131143
131153
  session = got || session;
@@ -131184,7 +131194,6 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
131184
131194
  }
131185
131195
  const error62 = obj(tool.error);
131186
131196
  const reason = str(error62.message) || str(error62.type);
131187
- if (reason && /permission|denied|soft.den/i.test(reason)) fail(reason);
131188
131197
  if (["DONE", "ERROR", "CANCELED", "INTERRUPTED"].includes(str(step.state)) && !closed.has(id2)) {
131189
131198
  closed.add(id2);
131190
131199
  const failed = !!reason || step.state !== "DONE";
@@ -131209,7 +131218,7 @@ ${imageError(target, reason || str(step.state))}
131209
131218
  if (e2.event === "result") {
131210
131219
  const result = obj(e2.result);
131211
131220
  if (expectedSession && str(result.conversation_id) && result.conversation_id !== expectedSession) {
131212
- fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.");
131221
+ fail(translating() ? "Antigravity \u672A\u7EED\u63A5\u6307\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u539F\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002" : "Antigravity did not resume the requested conversation.", "session_mismatch");
131213
131222
  terminal = true;
131214
131223
  return "";
131215
131224
  }
@@ -131225,8 +131234,8 @@ ${imageError(target, reason || str(step.state))}
131225
131234
  if (imageFailure) events.error(imageFailure);
131226
131235
  readImages.clear();
131227
131236
  imageErrors.clear();
131228
- if (Array.isArray(result.denied_actions) && result.denied_actions.length) fail(translating() ? "Antigravity \u6743\u9650\u62D2\u7EDD\uFF0C\u8BF7\u68C0\u67E5\u6743\u9650\u89C4\u5219\u540E\u91CD\u8BD5\u3002" : "Antigravity permission denied. Check permission rules, then retry.");
131229
- if (typeof result.response !== "string" || result.status !== "SUCCESS" || str(result.error) || result.finished_reason && result.finished_reason !== "completed" && result.finished_reason !== "success") {
131237
+ if (Array.isArray(result.denied_actions) && result.denied_actions.length) fail(translating() ? "Antigravity \u6743\u9650\u62D2\u7EDD\uFF0C\u8BF7\u68C0\u67E5\u6743\u9650\u89C4\u5219\u540E\u91CD\u8BD5\u3002" : "Antigravity permission denied. Check permission rules, then retry.", "permission_denied");
131238
+ else if (!failure2 && (typeof result.response !== "string" || result.status !== "SUCCESS" || str(result.error) || result.finished_reason && result.finished_reason !== "completed" && result.finished_reason !== "success")) {
131230
131239
  fail(result.status === "CANCELED" ? `Antigravity: CANCELED${result.error ? `: ${str(result.error)}` : ""}` : str(result.error) || `Antigravity: ${str(result.status) || "missing status"}`);
131231
131240
  }
131232
131241
  events.end();
@@ -131248,17 +131257,13 @@ ${imageError(target, reason || str(step.state))}
131248
131257
  if (!terminal) {
131249
131258
  incomplete = true;
131250
131259
  const diagnostics = [stderr.trim(), offStream?.match(/^(?:error:|rpc error:|API error\b)/i) ? offStream : void 0];
131251
- const diagnostic = diagnostics.find((text5) => text5 && manualFailure(text5)) ?? diagnostics.find((text5) => text5 && providerBlip(text5));
131252
- if (diagnostic) fail(diagnostic);
131253
- if (!failure2) fail(translating() ? "Antigravity \u672A\u8FD4\u56DE\u6700\u7EC8\u7ED3\u679C\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u540E\u91CD\u8BD5\u3002" : "Antigravity returned no final result. Check the log, then retry.");
131260
+ if (!failure2) fail(diagnostics.find(Boolean) || (translating() ? "Antigravity \u672A\u8FD4\u56DE\u6700\u7EC8\u7ED3\u679C\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u540E\u91CD\u8BD5\u3002" : "Antigravity returned no final result. Check the log, then retry."), "result_missing");
131254
131261
  }
131255
131262
  events.end();
131256
131263
  return text4;
131257
131264
  },
131258
131265
  stderr(chunk) {
131259
131266
  stderr = (stderr + chunk).slice(-16e3);
131260
- if (limited(stderr)) fail(stderr.trim());
131261
- if (/soft.denied|auto-denied|permission (?:denied|required)|denied by.*(?:policy|rule)|requires? (?:user )?(?:approval|permission)/i.test(stderr)) fail(stderr.trim());
131262
131267
  },
131263
131268
  result: () => final || (failure2 ? partial2 || void 0 : final),
131264
131269
  resumeId: () => session,
@@ -131268,8 +131273,8 @@ ${imageError(target, reason || str(step.state))}
131268
131273
  costIncomplete: () => incomplete || void 0,
131269
131274
  context: () => context,
131270
131275
  failure: () => failure2 || imageFailure,
131271
- rateLimit: () => rateLimit,
131272
- offStream: () => offStream,
131276
+ terminalFailure: () => terminal && !!classified,
131277
+ executionFailure: () => classified ?? (imageFailure ? { code: "image_read_failed", level: 3, reason: imageFailure } : void 0),
131273
131278
  events: events.events,
131274
131279
  activity: events.activity
131275
131280
  };
@@ -131363,11 +131368,10 @@ ${rule}
131363
131368
  `);
131364
131369
  return { args: ["--add-dir", root2] };
131365
131370
  },
131366
- transient: ({ failure: failure2 }) => providerBlip(failure2),
131367
131371
  reports: ["cost", "tokens", "model", "context"],
131368
131372
  adoptsSessionId: false,
131369
131373
  savesSessionAtOpen: true,
131370
- stopsOnRateLimit: true,
131374
+ stopsOnRateLimit: false,
131371
131375
  // `models` is read-only. Only explicit authentication errors mean signed out.
131372
131376
  login: {
131373
131377
  args: ["models"],
@@ -131459,7 +131463,6 @@ function checkHarnesses(harnesses) {
131459
131463
 
131460
131464
  // ../cli/src/lib/agent/harnesses/claude-code.ts
131461
131465
  import path28 from "node:path";
131462
- var cliSaid = (said) => /^\s*API Error\b/i.test(said ?? "") ? said : void 0;
131463
131466
  var MODEL_ALIASES = ["opus", "sonnet", "haiku", "fable"];
131464
131467
  function claudeStreamArgs(argv) {
131465
131468
  if (argv.includes("--output-format")) return [];
@@ -131698,18 +131701,6 @@ var CLAUDE_CODE = {
131698
131701
  reports: ["cost", "tokens", "model", "context"],
131699
131702
  // The variable above is the switch: the first 429 exits non-zero and the card is free.
131700
131703
  stopsOnRateLimit: true,
131701
- // A provider that stumbled, in the three ways `claude -p` reports one (#525).
131702
- //
131703
- // `failure` is a `result` event marked `is_error`, which the renderer already reads for
131704
- // its own reason. `offStream` is a line the CLI printed outside its events, and it is how
131705
- // BOTH failures this board captured arrived — "API Error: Connection dropped
131706
- // (ECONNRESET)" and "API Error: Connection lost mid-response.": the connection goes and
131707
- // no `result` event is ever written. `result` is the agent's own last message, read for
131708
- // the same words in case a future CLI puts them there.
131709
- //
131710
- // The last two only behind the `API Error:` prefix the CLI writes them under: everything
131711
- // else on those two is the agent's prose, and prose quoting an error is not a failure.
131712
- transient: ({ failure: failure2, result, offStream }) => providerBlip(failure2, cliSaid(offStream), cliSaid(result)),
131713
131704
  renderer: createStreamRenderer,
131714
131705
  stdinPrompt: (argv) => readsStdin(argv) ? userMessage : void 0,
131715
131706
  // `--session-id` above makes Claude Code run under the id we generated, so our key IS
@@ -132050,7 +132041,6 @@ var CODEX = {
132050
132041
  // failed: its `turn.failed` and `error` events, which the renderer keeps as this run's
132051
132042
  // failure (#525). Its final message is not read the way Claude Code's is — Codex puts the
132052
132043
  // reason on the stream, so a message that merely mentions one is the agent's prose.
132053
- transient: ({ failure: failure2 }) => providerBlip(failure2),
132054
132044
  // resumeArgs/forkArgs end on the subcommand and the thread id.
132055
132045
  renderer: (_cwd, _binary, argv = []) => createCodexStreamRenderer(["resume", "fork"].includes(argv.at(-2) ?? "")),
132056
132046
  // Codex re-reads its model list on a timer and traces the attempt to stderr every time,
@@ -133215,6 +133205,52 @@ var shared_default = "A Studio is the workbench for one kind of work. A Preview
133215
133205
  import { fileURLToPath as fileURLToPath3 } from "node:url";
133216
133206
  var SELF = fileURLToPath3(import.meta.url);
133217
133207
 
133208
+ // ../cli/src/lib/agent/retry.ts
133209
+ var BASE_MS = 15e3;
133210
+ var CAP_MS = 12e4;
133211
+ function backoffMs(attempt, random = Math.random) {
133212
+ const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt - 2));
133213
+ return Math.round(step * (1 - 0.25 * random()));
133214
+ }
133215
+ function planRetry(failure2, attempt, now = Date.now(), backoff = backoffMs) {
133216
+ if (!Number.isSafeInteger(attempt) || attempt < 1 || failure2.level === 3) return { pause: "needs-review" };
133217
+ const of = failure2.level === 1 ? 2 : 4;
133218
+ if (attempt >= of) return { pause: "limit" };
133219
+ const delay = failure2.retryAfterMs;
133220
+ const valid = delay !== void 0 && !Number.isNaN(delay) && delay >= 0;
133221
+ const wait3 = valid ? delay : failure2.level === 1 ? 0 : backoff(attempt + 1);
133222
+ if (wait3 > CAP_MS) return { pause: "wait-too-long" };
133223
+ return { plan: { at: now + wait3, of, failure: failure2 } };
133224
+ }
133225
+ function readFailure(raw) {
133226
+ if (!raw || typeof raw !== "object") return;
133227
+ const { code, level, reason, retryAfterMs: retryAfterMs2 } = raw;
133228
+ if (typeof code !== "string" || !code || typeof reason !== "string" || level !== 1 && level !== 2 && level !== 3) return;
133229
+ return { code, level, reason, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
133230
+ }
133231
+ function readRetryPlan(raw, attempt) {
133232
+ if (!raw || typeof raw !== "object") return;
133233
+ const { at: at2, of, failure: rawFailure } = raw;
133234
+ const failure2 = readFailure(rawFailure);
133235
+ if (!failure2 || typeof at2 !== "number" || !Number.isFinite(at2)) return;
133236
+ const decision = planRetry(failure2, attempt);
133237
+ if ("plan" in decision && of === decision.plan.of) return { at: at2, of, failure: failure2 };
133238
+ }
133239
+ function pauseLine(pause, zh = translating()) {
133240
+ switch (pause) {
133241
+ case "needs-review":
133242
+ return zh ? "\u5DF2\u6682\u505C\uFF0C\u8BF7\u68C0\u67E5\u5931\u8D25\u539F\u56E0\u540E\u7EED\u8DD1\u3002" : "Paused. Review the failure before resuming.";
133243
+ case "limit":
133244
+ return zh ? "\u5DF2\u8FBE\u5230\u81EA\u52A8\u91CD\u8BD5\u6B21\u6570\u4E0A\u9650\u3002" : "The automatic retry limit was reached.";
133245
+ case "wait-too-long":
133246
+ return zh ? "\u6240\u9700\u7B49\u5F85\u65F6\u95F4\u8D85\u8FC7\u4E24\u5206\u949F\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because the required wait exceeds two minutes.";
133247
+ case "unsafe":
133248
+ return zh ? "\u65E0\u6CD5\u786E\u8BA4\u53EF\u4EE5\u5B89\u5168\u7EED\u8DD1\uFF0C\u8BF7\u5148\u6838\u5BF9\u5DF2\u6709\u8FDB\u5EA6\u548C\u64CD\u4F5C\u7ED3\u679C\u3002" : "Check saved progress and operation results before resuming safely.";
133249
+ case "authorization":
133250
+ return zh ? "\u65E0\u6CD5\u786E\u8BA4\u7EED\u8DD1\u6388\u6743\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because authorization to resume could not be confirmed.";
133251
+ }
133252
+ }
133253
+
133218
133254
  // ../cli/src/lib/cloud/execution.ts
133219
133255
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
133220
133256
  function executionOf(value = process.env.AI4KANBAN_EXECUTION) {
@@ -133311,6 +133347,9 @@ function parseStore() {
133311
133347
  ok: typeof entry.ok === "boolean" ? entry.ok : void 0,
133312
133348
  code: entry.code ?? null,
133313
133349
  error: typeof entry.error === "string" ? entry.error : void 0,
133350
+ failure: readFailure(entry.failure),
133351
+ validationFailure: readFailure(entry.validationFailure),
133352
+ retryPause: entry.retryPause,
133314
133353
  blocker: readBlocker(entry.blocker),
133315
133354
  // A run that never reported a cost shows none, rather than a zero it didn't earn.
133316
133355
  costUsd: typeof entry.costUsd === "number" && entry.costUsd >= 0 ? entry.costUsd : void 0,
@@ -133393,7 +133432,7 @@ function readRetry2(raw) {
133393
133432
  if (!raw || typeof raw !== "object") return void 0;
133394
133433
  const r2 = raw;
133395
133434
  const whole = Number.isInteger(r2.attempt) && r2.attempt > 0 && Number.isInteger(r2.of) && r2.of > 0 && typeof r2.reason === "string" && !!r2.reason && typeof r2.at === "number" && typeof r2.since === "number";
133396
- return whole ? { attempt: r2.attempt, of: r2.of, reason: r2.reason, at: r2.at, since: r2.since } : void 0;
133435
+ return whole ? { attempt: r2.attempt, of: r2.of, reason: r2.reason, at: r2.at, since: r2.since, pending: readRetryPlan(r2.pending, r2.attempt), launching: r2.launching === true || void 0 } : void 0;
133397
133436
  }
133398
133437
  function readMarks(raw) {
133399
133438
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
@@ -134584,6 +134623,9 @@ function diff3Merge(a2, o3, b2, options) {
134584
134623
  return results;
134585
134624
  }
134586
134625
 
134626
+ // ../cli/src/lib/shared/task-preview-validation.ts
134627
+ var describeTaskPreviewProblems = (problems) => problems.map((p2) => `#${numberOfCard(p2.file)} ${p2.file}:${p2.line}:${p2.column} \u2014 ${p2.message}. ${p2.hint}`).join("\n");
134628
+
134587
134629
  // ../cli/src/lib/shared/triage-files.ts
134588
134630
  var ITEM = /^triage\/(?:(dismissed|archived)\/)?([^/]+)\.md$/;
134589
134631
  function itemAt(path52) {
@@ -134920,8 +134962,7 @@ function viewOf(ws, base, shared) {
134920
134962
  for (const [p2, f2] of Object.entries(base.files)) if (p2.startsWith(MEMORY2) && shared(p2.slice(MEMORY2.length))) view.set(p2, f2.content);
134921
134963
  return view;
134922
134964
  }
134923
- function assetFiles(ws, list3) {
134924
- const card = cardFile(ws);
134965
+ function assetFiles(ws, list3, card = cardFile(ws)) {
134925
134966
  const at2 = (name) => {
134926
134967
  try {
134927
134968
  return assetPath(ws, name, card);
@@ -135058,7 +135099,9 @@ function pull(ws, machineId) {
135058
135099
  if (busy(preparationKey(ws))) return { ok: false, error: "This board is preparing task content. Try again after it finishes." };
135059
135100
  const sent = await sendBoard(boardFolder(ws), machineId);
135060
135101
  if (!sent.ok) {
135061
- const refused = sent.tasks ? sent.tasks[ws.cloudTask ?? ""] : { ...sent, blocking: true };
135102
+ const previews = sent.previews?.filter((p2) => numberOfCard(p2.file) === ws.number);
135103
+ if (previews?.length) return { ok: false, code: "bad_request", error: describeTaskPreviewProblems(previews) };
135104
+ const refused = sent.tasks?.[ws.cloudTask ?? ""] ?? (sent.tasks || sent.previews ? void 0 : { ...sent, blocking: true });
135062
135105
  if (refused && refused.blocking !== false) {
135063
135106
  if (sent.conflict) {
135064
135107
  const prepared = await prepareConflictTask(ws);
@@ -135152,10 +135195,11 @@ function applyRestorations(ws, base, files) {
135152
135195
  function observeConflicts(ws, base, files) {
135153
135196
  const shared = sharedMemory(ws.board);
135154
135197
  const root2 = rootOf(ws);
135198
+ const pending = new Set(base.pendingPreviews);
135155
135199
  const conflicting = files.some((f2) => {
135156
135200
  const own2 = f2.path.startsWith(root2);
135157
135201
  const p2 = own2 ? f2.path.slice(root2.length) : f2.path;
135158
- if (!kept3(p2) || (p2.startsWith(MEMORY2) && shared(p2.slice(MEMORY2.length))) !== !own2) return false;
135202
+ if (pending.has(p2) || !kept3(p2) || (p2.startsWith(MEMORY2) && shared(p2.slice(MEMORY2.length))) !== !own2) return false;
135159
135203
  return !!mergeFile(base.files[f2.path]?.content ?? null, readText(path39.join(ws.board, p2)), f2.content).conflict;
135160
135204
  });
135161
135205
  if (!conflicting) return false;
@@ -135163,6 +135207,7 @@ function observeConflicts(ws, base, files) {
135163
135207
  const candidates = /* @__PURE__ */ new Set([...localFiles(ws, base), ...viewOf(ws, base, shared).keys()]);
135164
135208
  const facts = [];
135165
135209
  for (const p2 of candidates) {
135210
+ if (pending.has(p2)) continue;
135166
135211
  const remotePath = remoteOf(ws, shared, p2);
135167
135212
  const before = base.files[remotePath]?.content ?? null;
135168
135213
  const here = readText(path39.join(ws.board, p2));
@@ -135569,12 +135614,8 @@ async function pushAssets(ws, record2, before) {
135569
135614
  } catch (error62) {
135570
135615
  return { ok: false, code: "bad_request", error: error62 instanceof Error ? error62.message : String(error62) };
135571
135616
  }
135572
- const list3 = path39.join(ws.board, assetsFile(ws.task));
135573
- if (Object.keys(refs).length || fs35.existsSync(list3)) {
135574
- if (!isDeepStrictEqual(assetsOf(readText(list3)), refs)) write(list3, assetsText(refs));
135575
- }
135576
135617
  logSync("assets.end", { project: ws.project, task: ws.task, ms: Math.round(performance.now() - started) });
135577
- return { ok: true, value: void 0 };
135618
+ return { ok: true, value: refs };
135578
135619
  }
135579
135620
  function resetSorted(ws) {
135580
135621
  if (pendingConflicts(ws.board).length) return;
@@ -135633,7 +135674,8 @@ async function sendBoard(ws, machineId, paths) {
135633
135674
  }
135634
135675
  async function sendMarked(ws, job, paths) {
135635
135676
  const pushed = pendingConflicts(ws.board).length ? conflictFailure(ws) : await send2(ws, job, paths);
135636
- markUnsent(ws.cwd, !pushed.ok || !!readBase(ws).pendingAssets?.length);
135677
+ const base = readBase(ws);
135678
+ markUnsent(ws.cwd, !pushed.ok || !!base.pendingAssets?.length || !!base.pendingPreviews?.length);
135637
135679
  return pushed;
135638
135680
  }
135639
135681
  var boardIdentity = (ws) => {
@@ -135710,7 +135752,7 @@ async function send2(ws, job, paths) {
135710
135752
  const base = readBase(ws);
135711
135753
  const fail = (error62, conflict = false, code) => ({ ok: false, conflict, error: error62, ...code ? {} : { offline: true } });
135712
135754
  if (!syncIndex(ws)?.ready) paths = void 0;
135713
- const selected = paths && new Set(paths);
135755
+ const selected = paths && /* @__PURE__ */ new Set([...paths, ...base.pendingPreviews ?? []]);
135714
135756
  const names2 = selected ? new Set(base.pendingAssets ?? []) : null;
135715
135757
  if (selected) for (const task of affectedTasks(ws, selected)) names2.add(task);
135716
135758
  const retired = await cleanRecords(ws, base, [], names2 ?? void 0);
@@ -135739,6 +135781,8 @@ async function send2(ws, job, paths) {
135739
135781
  const deferredLists = /* @__PURE__ */ new Set();
135740
135782
  const assetErrors = {};
135741
135783
  const processed = /* @__PURE__ */ new Set();
135784
+ const assetLists = /* @__PURE__ */ new Map();
135785
+ const generatedAssets = /* @__PURE__ */ new Set();
135742
135786
  const cards = !selected && !ws.cloudTask ? new Map(
135743
135787
  [".archive", "todo"].flatMap((dir) => filesUnder(path39.join(ws.board, dir), ws.board)).flatMap((p2) => {
135744
135788
  const number4 = numberOfCard(p2);
@@ -135766,12 +135810,19 @@ async function send2(ws, job, paths) {
135766
135810
  });
135767
135811
  const archived = !selected && boardSync && card.startsWith(".archive/") && readText(path39.join(ws.board, card)) === base.files[rootOf(ws) + card]?.content && !newer && clean();
135768
135812
  if (!archived && !item.record.deleted) {
135769
- const refreshed = newer && clean() ? await pullAssets(item.folder, item.record, before) : { ok: true, value: void 0 };
135813
+ const refreshed = newer && clean() ? await pullAssets(item.folder, item.record, before, true) : { ok: true, value: void 0 };
135770
135814
  const assets = refreshed.ok ? await pushAssets(item.folder, item.record, before) : refreshed;
135771
135815
  if (assets.ok) {
135772
135816
  writeRecord(item.folder, item.record);
135773
135817
  indexTask(item.folder, item.record);
135774
- selected?.add(assetsFile(item.folder.task));
135818
+ const list3 = assetsFile(item.folder.task);
135819
+ const local2 = readText(path39.join(ws.board, list3));
135820
+ if (assets.value && (local2 !== null || Object.keys(assets.value).length)) {
135821
+ const content = isDeepStrictEqual(assetsOf(local2), assets.value) && local2 !== null ? local2 : assetsText(assets.value);
135822
+ assetLists.set(list3, { local: local2, content });
135823
+ for (const file3 of assetFiles(item.folder, content, path39.join(ws.board, card))) generatedAssets.add(file3);
135824
+ }
135825
+ selected?.add(list3);
135775
135826
  continue;
135776
135827
  }
135777
135828
  if (!boardSync) return fail(assets.error, false, assets.code);
@@ -135804,29 +135855,39 @@ async function send2(ws, job, paths) {
135804
135855
  deferred.add(p2);
135805
135856
  return true;
135806
135857
  };
135858
+ const previews = [];
135859
+ const heldPreviews = /* @__PURE__ */ new Set();
135807
135860
  const success2 = (changed) => {
135808
135861
  const refreshDeferred = deferred.size !== (base.deferred?.length ?? 0) || base.deferred?.some((p2) => !deferred.has(p2));
135809
135862
  const pendingAssets = [.../* @__PURE__ */ new Set([...(base.pendingAssets ?? []).filter((task) => !processed.has(task)), ...Object.keys(assetErrors)])];
135810
135863
  const refreshPending = JSON.stringify(pendingAssets) !== JSON.stringify(base.pendingAssets ?? []);
135811
135864
  if (refreshDeferred) base.deferred = [...deferred];
135812
135865
  if (refreshPending) base.pendingAssets = pendingAssets;
135813
- if (changed || refreshDeferred || refreshPending) writeBase(ws, base);
135866
+ const pendingPreviews = [.../* @__PURE__ */ new Set([...heldPreviews, ...(base.pendingPreviews ?? []).filter((p2) => deferred.has(p2))])];
135867
+ const refreshPreviews = !isDeepStrictEqual(pendingPreviews, base.pendingPreviews ?? []);
135868
+ if (refreshPreviews) base.pendingPreviews = pendingPreviews;
135869
+ if (changed || refreshDeferred || refreshPending || refreshPreviews) writeBase(ws, base);
135870
+ const reported = boardSync ? previews : previews.filter((p2) => numberOfCard(p2.file) === ws.number);
135814
135871
  const firstError = Object.values(assetErrors)[0];
135872
+ if (reported.length) return { ok: false, conflict: false, error: describeTaskPreviewProblems(reported), previews: reported, tasks: assetErrors };
135815
135873
  if (firstError && boardSync) return { ok: false, conflict: false, ...firstError, tasks: assetErrors };
135816
135874
  return { ok: true, changed };
135817
135875
  };
135818
- const local = scoped ?? localFiles(ws, base);
135876
+ const local = /* @__PURE__ */ new Set([...scoped ?? localFiles(ws, base), ...assetLists.keys()]);
135819
135877
  const localOf = /* @__PURE__ */ new Map();
135878
+ const localBefore = /* @__PURE__ */ new Map();
135820
135879
  const changes = [];
135821
135880
  const owed = (p2) => !job.id && busy(ws.cwd) && itemAt(p2)?.state === "open" && !base.files[rootOf(ws) + p2];
135822
135881
  for (const p2 of local) {
135823
- if (defer(p2) || owed(p2)) continue;
135882
+ if (defer(p2) || owed(p2) || generatedAssets.has(p2)) continue;
135824
135883
  if (selected && tasks.some((item) => assetFiles(item.folder, assetsListOf(item.folder, base)).has(p2))) continue;
135825
- const content = fs35.readFileSync(path39.join(ws.board, p2), "utf8");
135884
+ const list3 = assetLists.get(p2);
135885
+ const content = list3?.content ?? fs35.readFileSync(path39.join(ws.board, p2), "utf8");
135826
135886
  const remote2 = remoteOf(ws, shared, p2);
135827
135887
  localOf.set(remote2, p2);
135888
+ localBefore.set(remote2, list3 ? list3.local : content);
135828
135889
  const held5 = base.files[remote2];
135829
- if (held5?.content === content) continue;
135890
+ if (held5?.content === content && (!list3 || list3.local === content)) continue;
135830
135891
  if (Buffer.byteLength(content) > BOARD_FILE_LIMIT) return fail(`${p2} is over ${BOARD_FILE_LIMIT / 1024} KB; keep large files as assets.`, false, "too_large");
135831
135892
  changes.push({ path: remote2, content, base_seq: held5?.seq ?? base.deleted?.[remote2] ?? 0 });
135832
135893
  }
@@ -135839,6 +135900,7 @@ async function send2(ws, job, paths) {
135839
135900
  const remote2 = remoteOf(ws, shared, p2);
135840
135901
  if (!defer(p2) && kept3(p2) && !localOf.has(remote2) && base.files[remote2]) {
135841
135902
  localOf.set(remote2, p2);
135903
+ localBefore.set(remote2, null);
135842
135904
  changes.push({ path: remote2, content: null, base_seq: base.files[remote2].seq });
135843
135905
  }
135844
135906
  }
@@ -135846,29 +135908,58 @@ async function send2(ws, job, paths) {
135846
135908
  const stale2 = new Set(Object.keys(base.files).filter((p2) => p2.startsWith(memory) && shared(p2.slice(memory.length))));
135847
135909
  for (const p2 of stale2) changes.push({ path: p2, content: null, base_seq: base.files[p2].seq });
135848
135910
  if (!changes.length) return success2(false);
135849
- const original = changes.map((c2) => ({ ...c2 }));
135850
- let sent = await commitBoard(ws.project, job.id, job.machineId, changes);
135911
+ const commit = async () => {
135912
+ while (changes.length) {
135913
+ const sent2 = await commitBoard(ws.project, job.id, job.machineId, changes);
135914
+ if (sent2.ok || !sent2.previewProblems?.length) return sent2;
135915
+ const problems = sent2.previewProblems;
135916
+ const submitted = new Set(changes.filter((f2) => f2.content !== null).map((f2) => localOf.get(f2.path)));
135917
+ if (problems.some((p2) => typeof p2?.file !== "string" || numberOfCard(p2.file) === null || !submitted.has(p2.file))) return sent2;
135918
+ const numbers = new Set(problems.map((p2) => numberOfCard(p2.file)));
135919
+ for (const problem of problems) previews.push(problem);
135920
+ const index = syncIndex(ws);
135921
+ for (const task of index.tasks.values()) if (numbers.has(task.number)) heldPreviews.add(assetsFile(task.task));
135922
+ for (let i = changes.length - 1; i >= 0; i--) {
135923
+ const remote2 = changes[i].path;
135924
+ const file3 = localOf.get(remote2);
135925
+ if (!file3) continue;
135926
+ const task = taskOfAssets(file3);
135927
+ const number4 = task ? index.tasks.get(task)?.number ?? readRecord({ ...ws, task }).number : numberOfCard(file3);
135928
+ if (number4 == null || !numbers.has(number4)) continue;
135929
+ heldPreviews.add(file3);
135930
+ changes.splice(i, 1);
135931
+ }
135932
+ const pendingPreviews = [.../* @__PURE__ */ new Set([...base.pendingPreviews ?? [], ...heldPreviews])];
135933
+ if (!isDeepStrictEqual(pendingPreviews, base.pendingPreviews ?? [])) {
135934
+ base.pendingPreviews = pendingPreviews;
135935
+ writeBase(ws, base);
135936
+ }
135937
+ const own2 = previews.filter((p2) => numberOfCard(p2.file) === ws.number);
135938
+ if (job.id && own2.length) return { ...sent2, error: describeTaskPreviewProblems(own2) };
135939
+ }
135940
+ return null;
135941
+ };
135942
+ let sent = await commit();
135943
+ if (sent === null) return success2(false);
135851
135944
  if (!sent.ok && sent.files) {
135852
135945
  for (const f2 of sent.files) if (stale2.has(f2.path)) {
135853
135946
  const at2 = changes.findIndex((c2) => c2.path === f2.path);
135854
- if (at2 >= 0) {
135855
- changes.splice(at2, 1);
135856
- original.splice(at2, 1);
135857
- }
135947
+ if (at2 >= 0) changes.splice(at2, 1);
135858
135948
  }
135859
135949
  if (!changes.length) return success2(false);
135860
135950
  const remote2 = new Map(sent.files.map((f2) => [f2.path, f2]));
135861
- const facts = original.map((c2) => {
135951
+ const facts = changes.map((c2) => {
135862
135952
  const theirs = remote2.get(c2.path) ?? { content: base.files[c2.path]?.content ?? null, seq: c2.base_seq };
135863
135953
  const before = base.files[c2.path]?.content ?? null;
135864
135954
  const merged = mergeFile(before, c2.content, theirs.content);
135865
135955
  const p2 = localOf.get(c2.path) ?? c2.path.slice(rootOf(ws).length);
135866
- const lifecycle = theirs.content === null && c2.content !== null && numberOfCard(p2) !== null;
135956
+ const lifecycle = remote2.has(c2.path) && theirs.content === null && c2.content !== null && numberOfCard(p2) !== null;
135957
+ const local2 = localBefore.get(c2.path);
135867
135958
  return {
135868
135959
  path: p2,
135869
135960
  remotePath: c2.path,
135870
135961
  base: { content: before, seq: c2.base_seq },
135871
- local: { content: c2.content },
135962
+ local: { content: local2 === void 0 ? c2.content : local2 },
135872
135963
  remote: { content: theirs.content, seq: theirs.seq },
135873
135964
  automatic: { content: merged.content },
135874
135965
  conflicted: !!merged.conflict || lifecycle,
@@ -135879,11 +135970,13 @@ async function send2(ws, job, paths) {
135879
135970
  captureConflict(ws.board, ws.project, facts);
135880
135971
  return conflictFailure(ws);
135881
135972
  }
135882
- for (const [i, f2] of facts.entries()) changes[i] = { path: f2.remotePath, content: mergeFile(f2.base.content, f2.local.content, f2.remote.content).content, base_seq: f2.remote.seq };
135973
+ for (const [i, f2] of facts.entries()) changes[i] = { path: f2.remotePath, content: f2.automatic.content, base_seq: f2.remote.seq };
135883
135974
  if (facts.some((f2) => readText(path39.join(ws.board, f2.path)) !== f2.local.content)) return fail("Local files changed during synchronization. Try again.", false, "local_changed");
135884
- sent = await commitBoard(ws.project, job.id, job.machineId, changes);
135975
+ sent = await commit();
135976
+ if (sent === null) return success2(false);
135885
135977
  if (!sent.ok && sent.files) {
135886
- for (const f2 of facts) {
135978
+ const remaining = facts.filter((f2) => !heldPreviews.has(f2.path));
135979
+ for (const f2 of remaining) {
135887
135980
  const newer = sent.files.find((v) => v.path === f2.remotePath);
135888
135981
  if (newer) {
135889
135982
  f2.remote = { content: newer.content, seq: newer.seq };
@@ -135891,7 +135984,7 @@ async function send2(ws, job, paths) {
135891
135984
  f2.reason = "both-modified";
135892
135985
  }
135893
135986
  }
135894
- captureConflict(ws.board, ws.project, facts);
135987
+ captureConflict(ws.board, ws.project, remaining);
135895
135988
  return conflictFailure(ws);
135896
135989
  }
135897
135990
  }
@@ -135907,7 +136000,7 @@ async function send2(ws, job, paths) {
135907
136000
  delete base.deleted[c2.path];
135908
136001
  }
135909
136002
  const p2 = localOf.get(c2.path);
135910
- if (p2 && readText(path39.join(ws.board, p2)) === original.find((f2) => f2.path === c2.path)?.content) {
136003
+ if (p2 && readText(path39.join(ws.board, p2)) === localBefore.get(c2.path)) {
135911
136004
  if (c2.content === null) fs35.rmSync(path39.join(ws.board, p2), { force: true });
135912
136005
  else write(path39.join(ws.board, p2), c2.content);
135913
136006
  }
@@ -136583,32 +136676,17 @@ async function confirmFlowStopped(ws, job, deps) {
136583
136676
  // src/recovery.ts
136584
136677
  import fs39 from "node:fs";
136585
136678
  import path43 from "node:path";
136586
-
136587
- // ../cli/src/lib/agent/retry.ts
136588
- var RETRY_ATTEMPTS = 2;
136589
- var BASE_MS = 15e3;
136590
- var CAP_MS = 12e4;
136591
- var JITTER = 0.25;
136592
- function backoffMs(attempt, random = Math.random) {
136593
- const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt - 2));
136594
- return Math.round(step * (1 - JITTER * random()));
136595
- }
136596
- function planRetry(prev, failure2, startedAt, now = Date.now(), random = Math.random) {
136597
- const attempt = (prev?.attempt ?? 1) + 1;
136598
- if (attempt > RETRY_ATTEMPTS) return null;
136599
- const since = prev?.since ?? startedAt;
136600
- const wait3 = failure2.retryAfterMs ?? backoffMs(attempt, random);
136601
- const at2 = now + wait3;
136602
- if (wait3 > CAP_MS || wait3 < 0 || !Number.isFinite(wait3)) return null;
136603
- return { attempt, of: RETRY_ATTEMPTS, reason: failure2.reason, at: at2, since };
136604
- }
136605
-
136606
- // src/recovery.ts
136607
136679
  var fileOf2 = (id2) => path43.join(runnerHome(), "checkpoints", `${encodeURIComponent(id2)}.json`);
136608
136680
  function readCheckpoint(id2) {
136609
136681
  try {
136610
136682
  const held5 = JSON.parse(fs39.readFileSync(fileOf2(id2), "utf8"));
136611
136683
  if (!held5 || !Array.isArray(held5.pending) || !held5.pending.every((id3) => typeof id3 === "string")) throw new Error("\u8FDB\u5EA6\u683C\u5F0F\u9519\u8BEF");
136684
+ held5.failure = readFailure(held5.failure);
136685
+ if (held5.retry?.pending) {
136686
+ const pending = readRetryPlan(held5.retry.pending, held5.retry.attempt);
136687
+ if (!pending) held5.retry.at = held5.retry.pending.at ?? 0;
136688
+ held5.retry.pending = pending;
136689
+ }
136612
136690
  return held5;
136613
136691
  } catch (e2) {
136614
136692
  if (e2.code === "ENOENT") return null;
@@ -136648,23 +136726,11 @@ async function stopReply(id2, timeout) {
136648
136726
  }
136649
136727
  return true;
136650
136728
  }
136651
- function replyRetry(checkpoint, reason, now = Date.now(), backoff = backoffMs) {
136652
- const retry2 = checkpoint.retry;
136653
- const failure2 = recoveryFailure(reason);
136654
- if (!retry2 || !failure2) return null;
136655
- const planned = planRetry(
136656
- { ...retry2, of: 2, reason, at: retry2.at ?? now },
136657
- { ...failure2, retryAfterMs: failure2.retryAfterMs ?? backoff(retry2.attempt + 1) },
136658
- retry2.since,
136659
- now
136660
- );
136661
- return planned?.at ?? null;
136662
- }
136663
136729
  function replayable(checkpoint) {
136664
136730
  return checkpoint.submitted !== true && (checkpoint.effects === false || checkpoint.started === false) && !checkpoint.pending.length && !checkpoint.opaque;
136665
136731
  }
136666
136732
  function resumable(checkpoint) {
136667
- return !!checkpoint.session && !checkpoint.pending.length && !checkpoint.opaque;
136733
+ return !!checkpoint.session && !checkpoint.pending.length && !checkpoint.opaque && checkpoint.cleanup?.status !== "unconfirmed";
136668
136734
  }
136669
136735
  function replySpent(checkpoint, runtime) {
136670
136736
  const attempts = checkpoint.attempts ?? [];
@@ -156454,6 +156520,7 @@ import { createHash as createHash7 } from "node:crypto";
156454
156520
  var IDLE_MS2 = 5 * 6e4;
156455
156521
  var IDLE_TIMEOUT = { milliseconds: IDLE_MS2 };
156456
156522
  var IDLE_ERROR = "No response for 5 minutes (idle timeout).";
156523
+ var IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
156457
156524
  function createIdleWatchdog(expired, busy2 = () => false, milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now) {
156458
156525
  const calls = /* @__PURE__ */ new Set();
156459
156526
  const local = /* @__PURE__ */ new Set();
@@ -157594,6 +157661,7 @@ async function runClaimed(job, deps, track, keep2, lease, replyStream) {
157594
157661
  } finally {
157595
157662
  scope.progress?.cancel();
157596
157663
  scope.bridge?.close();
157664
+ await scope.waitingStream?.end();
157597
157665
  }
157598
157666
  }
157599
157667
  async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream) {
@@ -157620,55 +157688,66 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
157620
157688
  }
157621
157689
  return finish(deps, id2, lease, outcome, reason, report2);
157622
157690
  };
157623
- const replay = !(job.runtime === "antigravity" && previous?.session) && (job.manualRecovery === true && !!previous && replayable(previous) || job.retryReplay === true && (!local || replayable(local)) || !!previous?.retry?.at && replayable(previous));
157624
- if (reply) checkpoint.retry ??= { since: Date.now(), attempt: 1 };
157625
- if (reply && !job.manualRecovery && checkpoint.completed?.outcome === "failed" && (checkpoint.retry?.attempt ?? 1) >= 2) {
157626
- return finishClaimed("failed", checkpoint.completed.reason ?? "recovery_failed", checkpoint.completed.report);
157627
- }
157628
- const updating = checkpoint.updating === true && !checkpoint.retry?.at;
157629
- const recovering = checkpoint.updating === true || !!job.recoveryOf;
157630
- if (checkpoint.updating) {
157631
- delete checkpoint.updating;
157632
- saveCheckpoint(id2, checkpoint);
157633
- }
157691
+ const manual = job.manualRecovery === true;
157692
+ const updating = checkpoint.updating === true;
157693
+ const recovering = updating || !!job.recoveryOf || !!checkpoint.retry?.pending;
157634
157694
  const persist = () => {
157635
157695
  checkpoint.updating ||= readCheckpoint(id2)?.updating;
157636
157696
  saveCheckpoint(id2, checkpoint);
157637
157697
  };
157638
- const manual = job.manualRecovery === true;
157639
157698
  if (manual && !local && checkpoint.completed?.outcome === "failed") {
157640
157699
  delete checkpoint.completed;
157641
157700
  delete checkpoint.attempts;
157642
157701
  delete checkpoint.partialReply;
157643
157702
  }
157644
157703
  checkpoint.session ??= job.resume ?? void 0;
157645
- if (reply && previous?.started && checkpoint.completed?.outcome !== "done" && !await stopReply(readCheckpoint(id2) ? id2 : job.recoveryOf ?? id2, deps.stopMs)) {
157646
- return finishClaimed("failed", "recovery_unsafe");
157647
- }
157648
- if (reply && recovering && job.runtime === "antigravity" && checkpoint.started && !checkpoint.session && !checkpoint.completed) {
157649
- return finishClaimed("failed", "Antigravity did not record a conversation ID before interruption. The original session cannot be resumed.");
157650
- }
157651
- if (reply && recovering && !replyStream && previous?.started && !checkpoint.completed && !checkpoint.retry?.at && (checkpoint.retry?.attempt ?? 1) >= 2) {
157652
- return finishClaimed("failed", checkpoint.retry?.reason ?? "recovery_failed", {
157653
- recovery: { safe: replayable(checkpoint), stopped: true, resumable: resumable(checkpoint) }
157654
- });
157655
- }
157656
- if (reply && recovering && !updating && !replyStream && previous?.started && !checkpoint.completed && !checkpoint.retry?.at && !(manual && !local)) {
157657
- if (checkpoint.retry.attempt === 1) checkpoint.retry.since = Date.now();
157658
- if (checkpoint.retry.attempt >= 2) {
157659
- return finishClaimed("failed", "recovery_failed", {
157660
- recovery: { safe: replayable(checkpoint), stopped: true, resumable: resumable(checkpoint) }
157661
- });
157662
- }
157663
- checkpoint.retry.attempt++;
157704
+ const pauseRecovery = (pause, stopped3) => {
157705
+ checkpoint.retryPause = pause;
157706
+ if (checkpoint.retry) delete checkpoint.retry.pending;
157664
157707
  persist();
157665
- }
157708
+ const reason = [checkpoint.failure?.reason, pauseLine(pause, cloudLanguage(job) === "zh")].filter(Boolean).join("\n");
157709
+ return finishClaimed("failed", pause === "unsafe" ? "recovery_unsafe" : reason, {
157710
+ recovery: { safe: replayable(checkpoint), stopped: stopped3, resumable: resumable(checkpoint) }
157711
+ });
157712
+ };
157713
+ if (reply) {
157714
+ const hadRetryCount = !!checkpoint.retry;
157715
+ checkpoint.retry ??= { since: Date.now(), attempt: 1 };
157716
+ if (!replyStream && previous?.started && checkpoint.completed?.outcome !== "done" && !await stopReply(local ? id2 : job.recoveryOf ?? id2, deps.stopMs)) return pauseRecovery("unsafe", false);
157717
+ if (!checkpoint.completed && (!manual || local)) {
157718
+ if (!previous && job.recoveryOf) return pauseRecovery("unsafe", true);
157719
+ const retry3 = checkpoint.retry;
157720
+ if (checkpoint.launching || retry3.at !== void 0 || !Number.isSafeInteger(retry3.attempt) || retry3.attempt < 1) return pauseRecovery("unsafe", true);
157721
+ if (job.runtime === "antigravity" && recovering && checkpoint.started && !checkpoint.session) {
157722
+ return finishClaimed("failed", "Antigravity did not record a conversation ID before interruption. The original session cannot be resumed.");
157723
+ }
157724
+ if (!replyStream && !retry3.pending && previous?.started && (updating || job.recoveryOf)) {
157725
+ if (!hadRetryCount) return pauseRecovery("unsafe", true);
157726
+ const failure3 = checkpoint.failure ?? { code: "runner_interrupted", level: 2, reason: "The Runner was interrupted." };
157727
+ checkpoint.failure = failure3;
157728
+ const decision = planRetry(failure3, retry3.attempt, Date.now(), deps.replyBackoff);
157729
+ if ("pause" in decision) return pauseRecovery(decision.pause, true);
157730
+ retry3.pending = decision.plan;
157731
+ } else if (!replyStream && !recovering && previous?.started && !checkpoint.boardContinuation) {
157732
+ return pauseRecovery("unsafe", true);
157733
+ }
157734
+ if (retry3.pending) {
157735
+ checkpoint.failure = retry3.pending.failure;
157736
+ if (!canRetryReply(checkpoint, retry3.pending.failure, job.runtime)) return pauseRecovery("unsafe", true);
157737
+ }
157738
+ }
157739
+ }
157740
+ const pendingRetry = reply && checkpoint.retry?.pending || void 0;
157741
+ const replay = !(job.runtime === "antigravity" && checkpoint.session) && (manual && !!previous && replayable(previous) || job.retryReplay === true && !local || !!pendingRetry && pendingRetry.failure.level === 2 && replayable(checkpoint) && (pendingRetry.failure.code !== "runner_interrupted" || !checkpoint.session));
157666
157742
  if (recovering && checkpoint.session && !replay) job = { ...job, resume: checkpoint.session, fork: false };
157667
- if (replay) {
157668
- job = { ...job, resume: null, fork: false };
157669
- checkpoint.session = void 0;
157743
+ if (replay) job = { ...job, resume: null, fork: false };
157744
+ if (updating) {
157745
+ delete checkpoint.updating;
157746
+ saveCheckpoint(id2, checkpoint);
157747
+ } else if (reply || !recovering) persist();
157748
+ if (!reply && !job.flow && updating && checkpoint.started && !checkpoint.completed && !resumable(checkpoint)) {
157749
+ return finishClaimed("failed", "recovery_unsafe");
157670
157750
  }
157671
- if (!recovering) persist();
157672
157751
  if (job.handoff?.kind === "execution") {
157673
157752
  if (recovering) job = { ...job, handoff: { ...job.handoff, recovering: true } };
157674
157753
  const handoff2 = job.handoff;
@@ -157695,6 +157774,38 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
157695
157774
  if (job.secret) return runSecret(job, deps);
157696
157775
  if (job.test) return runTest(job, deps, lease);
157697
157776
  if (job.agent) return runAgentJob(job, deps, track, keep2, lease, checkpoint, persist);
157777
+ const waitingStream = pendingRetry ? replyStream ?? (scope.waitingStream = streamOut(deps, id2, lease)) : void 0;
157778
+ if (pendingRetry && waitingStream) {
157779
+ const stream2 = waitingStream;
157780
+ track(stream2.stop);
157781
+ stream2.event({ kind: "log", data: { text: "[chat-recovery] waiting" } });
157782
+ let timer;
157783
+ await Promise.race([new Promise((resolve2) => {
157784
+ timer = setTimeout(resolve2, Math.max(0, pendingRetry.at - Date.now()));
157785
+ }), stream2.whenAsked]);
157786
+ clearTimeout(timer);
157787
+ const finishWait = async (pause) => {
157788
+ await stream2.end();
157789
+ if (stream2.lost()) return;
157790
+ if (stream2.asked()) {
157791
+ if (checkpoint.retry) delete checkpoint.retry.pending;
157792
+ persist();
157793
+ return finishClaimed(job.runtime === "antigravity" ? "stopped" : "done", "", {
157794
+ session: checkpoint.session,
157795
+ ...checkpoint.partialReply ? { reply: checkpoint.partialReply } : {},
157796
+ stopped: true
157797
+ });
157798
+ }
157799
+ return pauseRecovery(pause, true);
157800
+ };
157801
+ if (stream2.asked() || stream2.lost()) return finishWait("authorization");
157802
+ if (deps.authorize && !await deps.authorize(job)) return finishWait("authorization");
157803
+ const requestedAt = leaseNow();
157804
+ const renewed = await deps.api.renewJob(deps.machineId, id2);
157805
+ if (renewed.ok && renewed.value.stop) stream2.requestStop();
157806
+ if (!renewed.ok || !renewed.value.renewed || stream2.asked() || stream2.lost()) return finishWait("authorization");
157807
+ Object.assign(lease, requestedAt);
157808
+ }
157698
157809
  const task = job.task ?? job.review?.tasks[0] ?? null;
157699
157810
  const folder2 = task && !job.projectDir ? { refused: NO_FOLDER } : folderFor(job);
157700
157811
  if (folder2 && "refused" in folder2) {
@@ -157789,7 +157900,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
157789
157900
  This task came out of a discussion. Read it for what the card leaves out: ${file3}` : "";
157790
157901
  const promptOf = (said2) => {
157791
157902
  const lines = (head2 + said2).trim();
157792
- const prompt = recovering && !replay && (checkpoint.started || job.recoveryOf) ? [job.runtime === "antigravity" ? job.prompt : "", "\u8FDE\u63A5\u6062\u590D\u540E\u7EE7\u7EED\u4E4B\u524D\u4E2D\u65AD\u7684\u56DE\u590D\u3002\u5148\u6838\u5BF9\u5DF2\u6709\u8FDB\u5EA6\u548C\u64CD\u4F5C\u7ED3\u679C\uFF0C\u4FDD\u7559\u5B8C\u6210\u7684\u5DE5\u4F5C\u4E0E\u7528\u6237\u51B3\u5B9A\uFF0C\u4E0D\u8981\u91CD\u590D\u5DF2\u7ECF\u6267\u884C\u7684\u64CD\u4F5C\uFF1B\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\u65F6\u5148\u68C0\u67E5\u5B9E\u9645\u72B6\u6001\u3002", checkpoint.retry?.reason ? `Previous execution failed: ${checkpoint.retry.reason}` : ""].filter(Boolean).join("\n\n") : job.prompt;
157903
+ const prompt = recovering && !replay && (checkpoint.started || job.recoveryOf) ? [job.runtime === "antigravity" ? job.prompt : "", "\u8FDE\u63A5\u6062\u590D\u540E\u7EE7\u7EED\u4E4B\u524D\u4E2D\u65AD\u7684\u56DE\u590D\u3002\u5148\u6838\u5BF9\u5DF2\u6709\u8FDB\u5EA6\u548C\u64CD\u4F5C\u7ED3\u679C\uFF0C\u4FDD\u7559\u5B8C\u6210\u7684\u5DE5\u4F5C\u4E0E\u7528\u6237\u51B3\u5B9A\uFF0C\u4E0D\u8981\u91CD\u590D\u5DF2\u7ECF\u6267\u884C\u7684\u64CD\u4F5C\uFF1B\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\u65F6\u5148\u68C0\u67E5\u5B9E\u9645\u72B6\u6001\u3002", pendingRetry ? `Previous execution failed: ${pendingRetry.failure.reason}` : ""].filter(Boolean).join("\n\n") : job.prompt;
157793
157904
  return lines ? `${lines}
157794
157905
 
157795
157906
  ---
@@ -157811,9 +157922,13 @@ ${prompt}` : prompt;
157811
157922
  if (!carried) job = { ...job, resume: null, fork: false };
157812
157923
  }
157813
157924
  } catch (e2) {
157925
+ await waitingStream?.end();
157814
157926
  return finishClaimed("failed", e2 instanceof Error ? e2.message : String(e2));
157815
157927
  }
157816
- if (deps.authorize && !await deps.authorize(job)) return finishClaimed("failed", "\u9879\u76EE\u76EE\u5F55\u6388\u6743\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u540E\u91CD\u8BD5\u3002");
157928
+ if (deps.authorize && !await deps.authorize(job)) {
157929
+ await waitingStream?.end();
157930
+ return pendingRetry ? pauseRecovery("authorization", true) : finishClaimed("failed", "\u9879\u76EE\u76EE\u5F55\u6388\u6743\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u540E\u91CD\u8BD5\u3002");
157931
+ }
157817
157932
  if (!held4(deps, lease)) return;
157818
157933
  if (reply) {
157819
157934
  for (let check2 = 0; ; check2++) {
@@ -157828,10 +157943,15 @@ ${prompt}` : prompt;
157828
157943
  const wrote = await writeGoals({ ...job, discussion: job.discussion }, deps.api.listStudios, true);
157829
157944
  if ("error" in wrote) return finishClaimed("failed", wrote.error);
157830
157945
  goalFile = wrote.file;
157831
- if (deps.authorize && !await deps.authorize(job)) return finishClaimed("failed", "\u9879\u76EE\u76EE\u5F55\u6388\u6743\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u540E\u91CD\u8BD5\u3002");
157946
+ if (deps.authorize && !await deps.authorize(job)) {
157947
+ return pendingRetry ? pauseRecovery("authorization", true) : finishClaimed("failed", "\u9879\u76EE\u76EE\u5F55\u6388\u6743\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u540E\u91CD\u8BD5\u3002");
157948
+ }
157832
157949
  }
157833
157950
  }
157834
- const stream = replyStream ?? streamOut(deps, id2, lease);
157951
+ if (waitingStream?.lost()) return;
157952
+ if (waitingStream?.asked()) return finishClaimed("stopped", "", { stopped: true });
157953
+ const stream = waitingStream ?? replyStream ?? streamOut(deps, id2, lease);
157954
+ if (pendingRetry) stream.event({ kind: "log", data: { text: "[chat-recovery] running" } });
157835
157955
  if (run3?.startNote) stream.out(`${run3.startNote}
157836
157956
  `);
157837
157957
  let attempt;
@@ -157849,7 +157969,6 @@ ${prompt}` : prompt;
157849
157969
  const { usage: _usage, costUsd: _cost, ...rest } = said2;
157850
157970
  return { ...rest, ...replySpent(checkpoint, job.runtime) };
157851
157971
  };
157852
- let replyProgress = false;
157853
157972
  const messages = [];
157854
157973
  const retainReply = (report2, failed) => {
157855
157974
  if (!reply) return report2;
@@ -157862,7 +157981,7 @@ ${prompt}` : prompt;
157862
157981
  };
157863
157982
  const account = readSession()?.subject;
157864
157983
  const generation = accountGeneration();
157865
- const evidence = scope.progress = conversationProgress(checkpoint.retry?.attempt ?? 1, async (progress) => {
157984
+ const evidence = scope.progress = conversationProgress((checkpoint.retry?.attempt ?? 1) + Number(!!pendingRetry), async (progress) => {
157866
157985
  const result = await deps.api.renewJob(deps.machineId, id2, { ...progress, ...job.claim ? { claim: job.claim } : {} });
157867
157986
  if (!evidence.active()) return;
157868
157987
  if (!result.ok) throw new Error(result.error);
@@ -157874,7 +157993,6 @@ ${prompt}` : prompt;
157874
157993
  let idleWatch;
157875
157994
  const remember = (event2) => {
157876
157995
  idleWatch?.event(event2);
157877
- if (["message", "tool_call", "tool_call_update"].includes(event2.kind)) replyProgress = true;
157878
157996
  if (stream.lost()) return;
157879
157997
  const at2 = (/* @__PURE__ */ new Date()).toISOString();
157880
157998
  event2 = Object.assign({}, event2, { data: { ...event2.data, eventAt: at2 } });
@@ -157891,37 +158009,29 @@ ${prompt}` : prompt;
157891
158009
  persist();
157892
158010
  stream.event(event2);
157893
158011
  };
157894
- const retry2 = async (reason) => {
157895
- if (!reply || !reason || stream.asked() || stream.lost()) return false;
157896
- if (job.runtime === "antigravity" && manualFailure(reason)) return false;
157897
- const at2 = replyRetry(checkpoint, reason, Date.now(), deps.replyBackoff);
157898
- if (at2 === null) return false;
158012
+ const retry2 = async (failure3) => {
158013
+ if (!reply || !failure3 || stream.asked() || stream.lost()) return false;
158014
+ checkpoint.failure = failure3;
158015
+ const decision = planRetry(failure3, checkpoint.retry.attempt, Date.now(), deps.replyBackoff);
158016
+ if ("pause" in decision) {
158017
+ checkpoint.retryPause = decision.pause;
158018
+ persist();
158019
+ return false;
158020
+ }
157899
158021
  checkpoint.approvalCancelled = true;
157900
158022
  persist();
157901
158023
  if (job.chat && checkpoint.approvalRequested) await cancelReplyApproval(deps.machineId, id2);
157902
- const safe3 = replayable(checkpoint);
157903
- if (sessionMissing(reason)) return false;
157904
- if (checkpoint.opaque || checkpoint.pending.length || !safe3 && (!checkpoint.session || sessionMissing(reason))) return false;
157905
- if (!await stopReply(id2, deps.stopMs) || !await stream.confirmed()) return false;
157906
- checkpoint.retry.reason = reason;
157907
- checkpoint.retry.handler = recoveryFailure(reason)?.handler;
157908
- checkpoint.retry.at = at2;
157909
- persist();
157910
- stream.event({ kind: "log", data: { text: "[chat-recovery] waiting" } });
157911
- await Promise.race([wait2(Math.max(0, at2 - Date.now())), stream.whenAsked]);
158024
+ if (!await stopReply(id2, deps.stopMs) || !await stream.confirmed() || !canRetryReply(checkpoint, failure3, job.runtime)) {
158025
+ checkpoint.retryPause = "unsafe";
158026
+ persist();
158027
+ return false;
158028
+ }
157912
158029
  if (stream.asked() || stream.lost()) return false;
157913
- if (deps.authorize && !await deps.authorize(job)) return false;
157914
- const requestedAt = leaseNow();
157915
- const renewed = await deps.api.renewJob(deps.machineId, id2);
157916
- if (!renewed.ok || !renewed.value.renewed || renewed.value.stop || stream.asked() || stream.lost()) return false;
157917
- Object.assign(lease, requestedAt);
157918
- checkpoint.retry.attempt++;
157919
- delete checkpoint.retry.at;
157920
- checkpoint.updating = true;
158030
+ checkpoint.retry.pending = decision.plan;
157921
158031
  persist();
157922
- stream.event({ kind: "log", data: { text: "[chat-recovery] running" } });
157923
158032
  evidence.cancel();
157924
- await runClaimed({ ...job, manualRecovery: false, retryReplay: safe3 && !job.resume }, deps, track, keep2, lease, stream);
158033
+ scope.bridge?.close();
158034
+ await runClaimed({ ...job, manualRecovery: false }, deps, track, keep2, lease, stream);
157925
158035
  await stream.end();
157926
158036
  return true;
157927
158037
  };
@@ -157939,19 +158049,6 @@ ${prompt}` : prompt;
157939
158049
  return savedGoals ? { ...said2, ...job.discussion?.goals !== void 0 ? { goals: savedGoals } : { ideas: savedGoals } } : said2;
157940
158050
  };
157941
158051
  track(stream.stop);
157942
- if (reply && checkpoint.retry?.at) {
157943
- stream.event({ kind: "log", data: { text: "[chat-recovery] waiting" } });
157944
- await Promise.race([wait2(Math.max(0, checkpoint.retry.at - Date.now())), stream.whenAsked]);
157945
- if (stream.asked() || stream.lost() || checkpoint.retry.attempt >= 2) {
157946
- await stream.end();
157947
- if (stream.lost()) return;
157948
- return finishClaimed(stream.asked() ? "stopped" : "failed", stream.asked() ? "" : "recovery_failed");
157949
- }
157950
- checkpoint.retry.attempt++;
157951
- delete checkpoint.retry.at;
157952
- persist();
157953
- stream.event({ kind: "log", data: { text: "[chat-recovery] running" } });
157954
- }
157955
158052
  const io = { show: stream.out, event: remember, track: stream.adopt, onStop: stream.onStop, lost: stream.lost };
157956
158053
  if (job.review) {
157957
158054
  checkpoint.started = true;
@@ -158000,27 +158097,39 @@ ${prompt}` : prompt;
158000
158097
  if (!ended3.ok) return finishClaimed("failed", ended3.reason, proof);
158001
158098
  return sendResult({ ...ended3.report, ...proof }, () => keepChat(job, ended3.report.reply));
158002
158099
  }
158003
- checkpoint.managedProcess = run3.managedProcess;
158004
- checkpoint.mark = stopMark();
158005
- checkpoint.started = true;
158006
- checkpoint.opaque = !run3.converse && !run3.renderer?.events;
158007
- checkpoint.session = run3.session() ?? checkpoint.session;
158008
- persist();
158009
- if (run3.converse) {
158010
- beginAttempt();
158011
- const plan3 = run3;
158012
- const converse = run3.converse;
158100
+ const launchAttempt = (plan3) => {
158101
+ checkpoint.managedProcess = plan3.managedProcess;
158102
+ checkpoint.mark = stopMark();
158103
+ checkpoint.started = true;
158104
+ checkpoint.opaque = !plan3.converse && !plan3.renderer?.events;
158105
+ checkpoint.session = plan3.session() ?? (replay ? void 0 : checkpoint.session);
158106
+ checkpoint.launching = true;
158107
+ delete checkpoint.process;
158108
+ delete checkpoint.cleanup;
158109
+ persist();
158013
158110
  const child = launch(plan3.command, plan3.args, { cwd, env: markEnv(plan3.env, checkpoint.mark), detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"] });
158014
158111
  if (child.pid) {
158015
158112
  checkpoint.process = { pid: child.pid, since: Date.now(), ...plan3.managedProcess ? { identity: connectionIdentity(child.pid) } : {} };
158016
- persist();
158113
+ if (pendingRetry) checkpoint.retry.attempt++;
158017
158114
  }
158115
+ if (checkpoint.retry) delete checkpoint.retry.pending;
158116
+ delete checkpoint.launching;
158117
+ delete checkpoint.failure;
158118
+ delete checkpoint.retryPause;
158119
+ beginAttempt();
158120
+ persist();
158121
+ return child;
158122
+ };
158123
+ if (run3.converse) {
158124
+ const plan3 = run3;
158125
+ const converse = run3.converse;
158126
+ const child = launchAttempt(plan3);
158018
158127
  stream.adopt(child, plan3.managedProcess);
158019
158128
  child.stdin.on("error", () => {
158020
158129
  });
158021
158130
  child.stderr.setEncoding("utf8");
158022
158131
  child.stderr.on("data", (chunk) => stream.out(quietLines(plan3, chunk)));
158023
- const spawned = new Promise((resolve2) => child.on("error", (e2) => resolve2(e2.message)));
158132
+ const spawned = new Promise((resolve2) => child.on("error", (e2) => resolve2(executionFailure(e2))));
158024
158133
  const cancellation = new AbortController();
158025
158134
  void stream.whenAsked.then(() => cancellation.abort());
158026
158135
  let timedOut;
@@ -158028,14 +158137,19 @@ ${prompt}` : prompt;
158028
158137
  timedOut = resolve2;
158029
158138
  });
158030
158139
  idleWatch = createIdleWatchdog(() => {
158031
- timedOut({ ok: false, error: IDLE_ERROR });
158140
+ timedOut({
158141
+ ok: false,
158142
+ error: IDLE_FAILURE.reason,
158143
+ failure: IDLE_FAILURE,
158144
+ ...plan3.managedProcess ? { cleanup: { status: "unconfirmed", execution: id2, kept: [] } } : {}
158145
+ });
158032
158146
  cancellation.abort();
158033
158147
  stop(child, plan3.managedProcess);
158034
158148
  }, () => !!plan3.background?.());
158035
158149
  const end = await Promise.race([
158036
158150
  timeout,
158037
158151
  converse(child, remember, false, Date.now() + CONVERSATION_MS.prepare, cancellation.signal, () => idleWatch?.touch()),
158038
- spawned.then((error62) => ({ ok: false, error: error62 })),
158152
+ spawned.then((failure4) => ({ ok: false, error: failure4.reason, failure: failure4 })),
158039
158153
  // Killed, the turn ends with what it said so far; one that never does is not waited on.
158040
158154
  stream.whenAsked.then(() => wait2(KILL_GRACE_MS * 2)).then(() => ({ ok: true }))
158041
158155
  ]);
@@ -158052,12 +158166,10 @@ ${prompt}` : prompt;
158052
158166
  });
158053
158167
  if (parts) measured2 = { ...measured2, parts, reply: parts.filter((p2) => p2.type === "text").map((p2) => p2.text).join("") };
158054
158168
  }
158055
- if (!end.ok && sessionMissing(end.error ?? "") && !replayable(checkpoint)) {
158056
- checkpoint.session = void 0;
158057
- persist();
158058
- }
158169
+ const rawFailure2 = end.ok ? void 0 : end.failure ?? { code: "execution_failed", level: 3, reason: end.error ?? "The agent did not complete the reply." };
158170
+ if (rawFailure2?.code === "session_not_found") checkpoint.session = void 0;
158059
158171
  measured2 = retainReply(measured2, !end.ok);
158060
- if (await retry2(end.ok ? void 0 : end.error ?? "The agent did not complete the reply.")) return;
158172
+ if (await retry2(rawFailure2)) return;
158061
158173
  await evidence.drain(deps.endMs);
158062
158174
  const stopped3 = await stopReply(id2, deps.stopMs);
158063
158175
  stop(child, plan3.managedProcess);
@@ -158071,18 +158183,16 @@ ${prompt}` : prompt;
158071
158183
  ...told(stream.asked() ? cutShort(measured2, stream.said()) : measured2),
158072
158184
  ...reply ? { recovery: { safe: replayable(checkpoint), stopped: stopped3, resumable: resumable(checkpoint) } } : {}
158073
158185
  };
158074
- if (!stream.asked()) complete(ok ? "done" : "failed", said2, unsafe2 ? "recovery_unsafe" : end.ok ? void 0 : end.error);
158186
+ const failure3 = replyReason(rawFailure2, checkpoint.retryPause, job, unsafe2);
158187
+ if (!stream.asked()) complete(ok ? "done" : "failed", said2, failure3);
158188
+ if (!ok && rawFailure2 && unsafe2) stream.event({ kind: "error", data: { text: rawFailure2.reason } });
158075
158189
  await stream.end();
158076
158190
  if (stream.lost()) return;
158077
- if (!ok || !ws) return finishClaimed(ok ? "done" : "failed", ok ? "" : unsafe2 ? "recovery_unsafe" : replyReason(end.ok ? void 0 : end.error, job), said2);
158191
+ if (!ok || !ws) return finishClaimed(ok ? "done" : "failed", ok ? "" : failure3, said2);
158078
158192
  return sendResult(said2, () => keepChat(job, said2.reply));
158079
158193
  }
158080
158194
  const printed = async (plan3) => {
158081
- const child = launch(plan3.command, plan3.args, { cwd, env: markEnv(plan3.env, checkpoint.mark), detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"] });
158082
- if (child.pid) {
158083
- checkpoint.process = { pid: child.pid, since: Date.now(), ...plan3.managedProcess ? { identity: connectionIdentity(child.pid) } : {} };
158084
- persist();
158085
- }
158195
+ const child = launchAttempt(plan3);
158086
158196
  stream.adopt(child, plan3.managedProcess);
158087
158197
  child.stdin.on("error", () => {
158088
158198
  });
@@ -158091,11 +158201,9 @@ ${prompt}` : prompt;
158091
158201
  else child.stdin.end();
158092
158202
  child.stdout.setEncoding("utf8");
158093
158203
  const structured = !!renderer2.events;
158094
- let stderr = "";
158095
- let acted = false;
158096
- let backgroundError;
158204
+ let backgroundFailure;
158097
158205
  idleWatch = createIdleWatchdog(() => {
158098
- backgroundError = IDLE_ERROR;
158206
+ backgroundFailure = IDLE_FAILURE;
158099
158207
  stop(child, plan3.managedProcess);
158100
158208
  }, () => !!renderer2.background?.());
158101
158209
  let activityVersion = 0;
@@ -158111,18 +158219,19 @@ ${prompt}` : prompt;
158111
158219
  persist();
158112
158220
  }
158113
158221
  if (!structured) {
158114
- if (text4.trim()) acted = true;
158115
158222
  stream.out(text4);
158116
158223
  }
158117
158224
  if (attempt) measure(report(job, plan3));
158118
158225
  for (const e2 of renderer2.events?.() ?? []) {
158119
- if (e2.kind === "message" || e2.kind === "tool_call" || e2.kind === "tool_call_update") acted = true;
158120
158226
  remember(e2);
158121
158227
  }
158122
158228
  };
158123
158229
  child.stdout.on("data", (chunk) => {
158124
158230
  fromAgent(renderer2.push(chunk));
158125
- if (renderer2.rateLimit?.()) stop(child, plan3.managedProcess);
158231
+ if (renderer2.terminalFailure?.()) {
158232
+ idleWatch?.close();
158233
+ stop(child, plan3.managedProcess);
158234
+ }
158126
158235
  if (plan3.stdin && streamFinished(renderer2) && !child.stdin.writableEnded) {
158127
158236
  idleWatch?.close();
158128
158237
  child.stdin.end();
@@ -158131,22 +158240,19 @@ ${prompt}` : prompt;
158131
158240
  child.stderr.setEncoding("utf8");
158132
158241
  child.stderr.on("data", (chunk) => {
158133
158242
  renderer2.stderr?.(chunk);
158134
- if (renderer2.rateLimit?.()) stop(child, plan3.managedProcess);
158135
- stderr = (stderr + chunk).slice(-EVENT_CHARS);
158136
158243
  stream.out(quietLines(plan3, chunk));
158137
158244
  });
158138
158245
  const ended3 = await new Promise((resolve2) => {
158139
- child.on("error", (e2) => resolve2({ code: null, error: e2.message }));
158246
+ child.on("error", (e2) => resolve2({ code: null, failure: executionFailure(e2) }));
158140
158247
  child.on("close", (code) => resolve2({ code }));
158141
158248
  });
158142
158249
  idleWatch?.close();
158143
158250
  fromAgent(renderer2.flush());
158144
- const pending = renderer2.background?.() ? "The agent exited with unfinished background tasks." : void 0;
158145
- return { ...ended3, error: ended3.error ?? backgroundError ?? pending, stderr, acted };
158251
+ const pending = renderer2.background?.() ? { code: "background_unfinished", level: 3, reason: "The agent exited with unfinished background tasks." } : void 0;
158252
+ return { ...ended3, failure: ended3.failure ?? backgroundFailure ?? pending };
158146
158253
  };
158147
- let plan2 = run3;
158148
- beginAttempt();
158149
- let ended2 = await printed(plan2);
158254
+ const plan2 = run3;
158255
+ const ended2 = await printed(plan2);
158150
158256
  let measured = measure(report(job, plan2));
158151
158257
  const renderer = plan2.renderer;
158152
158258
  if (reply && job.runtime === "codex") {
@@ -158162,12 +158268,10 @@ ${prompt}` : prompt;
158162
158268
  );
158163
158269
  if (parts) measured = { ...measured, parts, reply: parts.filter((p2) => p2.type === "text").map((p2) => p2.text).join("") };
158164
158270
  }
158165
- const rawFailure = ended2.error ?? renderer.failure?.() ?? (ended2.code === 0 ? void 0 : `Exited with code ${ended2.code}.`);
158271
+ const diagnostic = renderer.failure?.() ?? (ended2.code === 0 ? void 0 : `Exited with code ${ended2.code}.`);
158272
+ const rawFailure = ended2.failure ?? renderer.executionFailure?.() ?? (diagnostic ? { code: "execution_failed", level: 3, reason: diagnostic } : void 0);
158166
158273
  measured = retainReply(measured, !!rawFailure);
158167
- if (job.runtime !== "antigravity" && sessionMissing(rawFailure ?? "") && !replayable(checkpoint)) {
158168
- checkpoint.session = void 0;
158169
- persist();
158170
- }
158274
+ if (rawFailure?.code === "session_not_found" || rawFailure?.code === "session_mismatch") checkpoint.session = void 0;
158171
158275
  if (await retry2(rawFailure)) return;
158172
158276
  const stopped2 = await stopReply(id2, deps.stopMs);
158173
158277
  if (stream.asked() && (!stopped2 || !await stream.confirmed())) {
@@ -158175,7 +158279,8 @@ ${prompt}` : prompt;
158175
158279
  return;
158176
158280
  }
158177
158281
  const unsafe = reply && !!rawFailure && (!stopped2 || !replayable(checkpoint) && !resumable(checkpoint));
158178
- const failure2 = stream.asked() ? void 0 : unsafe ? "recovery_unsafe" : replyReason(ended2.error ?? renderer.failure?.() ?? (ended2.code === 0 ? void 0 : `Exited with code ${ended2.code}.`), job);
158282
+ const failure2 = stream.asked() ? void 0 : replyReason(rawFailure, checkpoint.retryPause, job, unsafe);
158283
+ if (rawFailure && unsafe) stream.event({ kind: "error", data: { text: rawFailure.reason } });
158179
158284
  const said = {
158180
158285
  ...told(stream.asked() ? cutShort(measured, stream.said()) : measured),
158181
158286
  ...reply ? { recovery: { safe: replayable(checkpoint), stopped: stopped2, resumable: resumable(checkpoint) } } : {}
@@ -158222,12 +158327,18 @@ async function runAgentJob(job, deps, track, keep2, lease, checkpoint, persist)
158222
158327
  }
158223
158328
  var quietLines = (plan2, chunk) => chunk.split("\n").filter((line) => line && !plan2.quiet(line)).map((line) => `${line}
158224
158329
  `).join("");
158225
- var replyReason = (reason, job) => {
158226
- if (!reason) return reason;
158227
- if (job.sessionFallback && !/auth|login|log.in|permission|directory|ENOENT|not installed|rate.limit|network|connect|登录|权限|目录/i.test(reason)) return "session_unavailable";
158228
- return reason;
158229
- };
158230
- var sessionMissing = (text4) => !/auth|unauthorized|forbidden|login|log.in|登录|权限/i.test(text4) && (/\b(?:session|conversation|thread)\b[^\n]*(?:\bnot found\b|\bdoes not exist\b)/i.test(text4) || /\bno (?:conversation|session|thread) found\b/i.test(text4));
158330
+ function canRetryReply(checkpoint, failure2, runtime) {
158331
+ if (checkpoint.cleanup?.status === "unconfirmed") return false;
158332
+ if (resumable(checkpoint)) return true;
158333
+ return failure2.level === 2 && runtime !== "antigravity" && replayable(checkpoint);
158334
+ }
158335
+ function replyReason(failure2, pause, job, unsafe) {
158336
+ if (!failure2) return;
158337
+ if (unsafe || pause === "unsafe") return "recovery_unsafe";
158338
+ if (failure2.code === "session_not_found" && job.sessionFallback) return "session_unavailable";
158339
+ return pause ? `${failure2.reason}
158340
+ ${pauseLine(pause, cloudLanguage(job) === "zh")}` : failure2.reason;
158341
+ }
158231
158342
  function launch(command, args2, options) {
158232
158343
  const start = spawnable(command, args2, options);
158233
158344
  return spawn4(start.command, start.args, start.options);
@@ -158357,13 +158468,11 @@ async function runTest(job, deps, lease) {
158357
158468
  child.stdout.setEncoding("utf8");
158358
158469
  child.stdout.on("data", (chunk) => {
158359
158470
  renderer.push(chunk);
158360
- if (renderer.rateLimit?.()) stop(child, run3.managedProcess);
158361
158471
  if (run3.stdin && streamFinished(renderer) && !child.stdin.writableEnded) child.stdin.end();
158362
158472
  });
158363
158473
  child.stderr.setEncoding("utf8");
158364
158474
  child.stderr.on("data", (chunk) => {
158365
158475
  renderer.stderr?.(chunk);
158366
- if (renderer.rateLimit?.()) stop(child, run3.managedProcess);
158367
158476
  said += chunk.split("\n").filter((line) => line && !run3.quiet(line)).map((line) => `${line}
158368
158477
  `).join("");
158369
158478
  });