wildcrane-runner 0.6.91 → 0.6.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.91 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.92 — 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;
@@ -30705,9 +30705,9 @@ var require_timers = __commonJS({
30705
30705
  * before the specified function or code is executed.
30706
30706
  * @param {*} arg
30707
30707
  */
30708
- constructor(callback2, delay, arg) {
30708
+ constructor(callback2, delay2, arg) {
30709
30709
  this._onTimeout = callback2;
30710
- this._idleTimeout = delay;
30710
+ this._idleTimeout = delay2;
30711
30711
  this._timerArg = arg;
30712
30712
  this.refresh();
30713
30713
  }
@@ -30752,8 +30752,8 @@ var require_timers = __commonJS({
30752
30752
  * when the timer expires.
30753
30753
  * @returns {NodeJS.Timeout|FastTimer}
30754
30754
  */
30755
- setTimeout(callback2, delay, arg) {
30756
- return delay <= RESOLUTION_MS ? setTimeout(callback2, delay, arg) : new FastTimer(callback2, delay, arg);
30755
+ setTimeout(callback2, delay2, arg) {
30756
+ return delay2 <= RESOLUTION_MS ? setTimeout(callback2, delay2, arg) : new FastTimer(callback2, delay2, arg);
30757
30757
  },
30758
30758
  /**
30759
30759
  * The clearTimeout method cancels an instantiated Timer previously created
@@ -30779,8 +30779,8 @@ var require_timers = __commonJS({
30779
30779
  * when the timer expires.
30780
30780
  * @returns {FastTimer}
30781
30781
  */
30782
- setFastTimeout(callback2, delay, arg) {
30783
- return new FastTimer(callback2, delay, arg);
30782
+ setFastTimeout(callback2, delay2, arg) {
30783
+ return new FastTimer(callback2, delay2, arg);
30784
30784
  },
30785
30785
  /**
30786
30786
  * The clearTimeout method cancels an instantiated FastTimer previously
@@ -30806,8 +30806,8 @@ var require_timers = __commonJS({
30806
30806
  * @deprecated
30807
30807
  * @param {number} [delay=0] The delay in milliseconds to add to the now value.
30808
30808
  */
30809
- tick(delay = 0) {
30810
- fastNow += delay - RESOLUTION_MS + 1;
30809
+ tick(delay2 = 0) {
30810
+ fastNow += delay2 - RESOLUTION_MS + 1;
30811
30811
  onTick();
30812
30812
  onTick();
30813
30813
  },
@@ -37325,21 +37325,21 @@ var require_client_h1 = __commonJS({
37325
37325
  this.connection = "";
37326
37326
  this.maxResponseSize = client[kMaxResponseSize];
37327
37327
  }
37328
- setTimeout(delay, type) {
37329
- if (delay !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
37328
+ setTimeout(delay2, type) {
37329
+ if (delay2 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
37330
37330
  if (this.timeout) {
37331
37331
  timers.clearTimeout(this.timeout);
37332
37332
  this.timeout = null;
37333
37333
  }
37334
- if (delay) {
37334
+ if (delay2) {
37335
37335
  if (type & USE_FAST_TIMER) {
37336
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
37336
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay2, this.timeoutWeakRef);
37337
37337
  } else {
37338
- this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
37338
+ this.timeout = setTimeout(onParserTimeout, delay2, this.timeoutWeakRef);
37339
37339
  this.timeout?.unref();
37340
37340
  }
37341
37341
  }
37342
- this.timeoutValue = delay;
37342
+ this.timeoutValue = delay2;
37343
37343
  } else if (this.timeout) {
37344
37344
  if (this.timeout.refresh) {
37345
37345
  this.timeout.refresh();
@@ -43505,7 +43505,7 @@ var require_mock_utils = __commonJS({
43505
43505
  if (mockDispatch2.data.callback) {
43506
43506
  mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
43507
43507
  }
43508
- const { data: { statusCode, data, headers, trailers, error: error63 }, delay, persist } = mockDispatch2;
43508
+ const { data: { statusCode, data, headers, trailers, error: error63 }, delay: delay2, persist } = mockDispatch2;
43509
43509
  const { timesInvoked, times } = mockDispatch2;
43510
43510
  mockDispatch2.consumed = !persist && timesInvoked >= times;
43511
43511
  mockDispatch2.pending = timesInvoked < times;
@@ -43528,11 +43528,11 @@ var require_mock_utils = __commonJS({
43528
43528
  handler.onError(err);
43529
43529
  }
43530
43530
  handler.onConnect?.(abort, null);
43531
- if (typeof delay === "number" && delay > 0) {
43531
+ if (typeof delay2 === "number" && delay2 > 0) {
43532
43532
  timer = setTimeout(() => {
43533
43533
  timer = null;
43534
43534
  handleReply(this[kDispatches]);
43535
- }, delay);
43535
+ }, delay2);
43536
43536
  } else {
43537
43537
  handleReply(this[kDispatches]);
43538
43538
  }
@@ -91121,7 +91121,6 @@ function date4(params) {
91121
91121
  var id = external_exports.string().trim().min(1).max(100);
91122
91122
  var reviewNodeSchema = external_exports.object({
91123
91123
  id,
91124
- title: external_exports.string().trim().min(1).max(200),
91125
91124
  after: external_exports.array(id).max(50).default([]),
91126
91125
  previews: external_exports.array(id).max(50).default([])
91127
91126
  }).strict();
@@ -91152,6 +91151,9 @@ var reviewPlanSchema = external_exports.array(reviewNodeSchema).max(50).superRef
91152
91151
  ctx.addIssue({ code: "custom", message: e.message });
91153
91152
  }
91154
91153
  }).nullable();
91154
+ function readReviewPlan(plan) {
91155
+ return plan?.map(({ id: id2, after, previews }) => ({ id: id2, after, previews })) ?? null;
91156
+ }
91155
91157
 
91156
91158
  // src/plugin.ts
91157
91159
  import crypto10 from "node:crypto";
@@ -107511,8 +107513,8 @@ function deferRefresh(session, error63, after) {
107511
107513
  const attempt = Math.min((readRetry(session)?.attempt ?? 0) + 1, 4);
107512
107514
  const seconds = after?.trim() ? Number(after) : NaN;
107513
107515
  const serverDelay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(after ?? "") - Date.now();
107514
- const delay = Math.max(Math.min(REFRESH_BACKOFF_MS * 2 ** (attempt - 1), 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
107515
- const retry2 = { key: refreshKey(session), until: Date.now() + delay, attempt, error: error63 };
107516
+ const delay2 = Math.max(Math.min(REFRESH_BACKOFF_MS * 2 ** (attempt - 1), 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
107517
+ const retry2 = { key: refreshKey(session), until: Date.now() + delay2, attempt, error: error63 };
107516
107518
  const temporary = `${retryFile()}.${process.pid}.tmp`;
107517
107519
  fs.writeFileSync(temporary, JSON.stringify(retry2), { mode: 384 });
107518
107520
  fs.renameSync(temporary, retryFile());
@@ -107837,8 +107839,8 @@ function machineId() {
107837
107839
  var machineName = () => os3.hostname().replace(/\.local$/, "");
107838
107840
 
107839
107841
  // src/protocol.ts
107840
- var VERSION = true ? "0.6.91" : "0.0.0";
107841
- var AKB_VERSION = true ? "0.11.73" : "0.0.0";
107842
+ var VERSION = true ? "0.6.92" : "0.0.0";
107843
+ var AKB_VERSION = true ? "0.11.74" : "0.0.0";
107842
107844
  var EXIT_REFUSED = 10;
107843
107845
  var EXIT_OUTDATED = 11;
107844
107846
  var EXIT_UPDATE = 12;
@@ -108095,6 +108097,14 @@ function connectionStopped(root2) {
108095
108097
  return !!root2.identity && !!identity && identity !== root2.identity;
108096
108098
  }
108097
108099
 
108100
+ // ../cli/src/lib/agent/retry.ts
108101
+ function readFailure(raw) {
108102
+ if (!raw || typeof raw !== "object") return;
108103
+ const { code, level, reason, source, retryAfterMs: retryAfterMs2 } = raw;
108104
+ if (typeof code !== "string" || !code || typeof reason !== "string" || level !== 1 && level !== 2 && level !== 3) return;
108105
+ return { code, level, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source) ? { source } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
108106
+ }
108107
+
108098
108108
  // ../cli/src/lib/agent/wire/json.ts
108099
108109
  function obj(value) {
108100
108110
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -108136,6 +108146,7 @@ function executionFailure(error63) {
108136
108146
  return {
108137
108147
  code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
108138
108148
  level: NETWORK.has(code) ? 2 : 3,
108149
+ source: "harness",
108139
108150
  reason
108140
108151
  };
108141
108152
  }
@@ -108153,17 +108164,19 @@ function providerFailure(error63, reason) {
108153
108164
  const headers = obj(info.headers);
108154
108165
  const wait = retryAfterMs(headers["retry-after"] ?? headers["Retry-After"]);
108155
108166
  const code = info.code ?? info.type;
108156
- if (code === "session_not_found") return { code, level: 3, reason };
108167
+ if (code === "session_not_found") return { code, source: "provider", level: 3, reason };
108157
108168
  if (status2 === 401 || status2 === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str(code))) {
108158
- return { code: "provider_refused", level: 3, reason };
108169
+ return { code: "provider_refused", source: "provider", level: 3, reason };
108159
108170
  }
108160
- if (code === "rate_limit_error") return { code: "rate_limited", level: 2, reason, retryAfterMs: wait };
108161
- if (TEMPORARY_HTTP.has(status2 ?? 0) || code === "overloaded_error") return { code: "service_overloaded", level: 2, reason, retryAfterMs: wait };
108162
- if (NETWORK.has(str(code))) return { code: "connection_lost", level: 2, reason, retryAfterMs: wait };
108163
- return { code: "provider_failed", level: 3, reason };
108171
+ if (code === "rate_limit_error") return { code: "rate_limited", source: "provider", level: 2, reason, retryAfterMs: wait };
108172
+ if (TEMPORARY_HTTP.has(status2 ?? 0) || code === "overloaded_error") return { code: "service_overloaded", source: "provider", level: 2, reason, retryAfterMs: wait };
108173
+ if (NETWORK.has(str(code))) return { code: "connection_lost", source: "provider", level: 2, reason, retryAfterMs: wait };
108174
+ return { code: "provider_failed", source: "provider", level: 3, reason };
108164
108175
  }
108165
108176
  function codexFailure(raw, fallback) {
108166
108177
  const error63 = obj(raw);
108178
+ const failure5 = readFailure(error63.wildcraneFailure);
108179
+ if (failure5?.source === "harness" || failure5?.source === "invariant") return failure5;
108167
108180
  const reason = str(error63.message) || fallback;
108168
108181
  const info = error63.codexErrorInfo;
108169
108182
  if (info === "serverOverloaded") return providerFailure({ ...error63, type: "overloaded_error" }, reason);
@@ -108598,12 +108611,12 @@ var STUDIO_SCHEMA = {
108598
108611
  previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
108599
108612
  type: "object",
108600
108613
  additionalProperties: false,
108601
- properties: { title: titles, icon }
108614
+ properties: { title: titles, description: titles, icon }
108602
108615
  } }
108603
108616
  }
108604
108617
  };
108605
108618
  var validate3 = new import_ajv2.Ajv({ allErrors: true, meta: false, validateSchema: false }).compile(STUDIO_SCHEMA);
108606
- function parseStudioFile(id2, source, from) {
108619
+ function parseStudioFile(id2, source, from, requirePreviewCopy = false) {
108607
108620
  const problems = [];
108608
108621
  const fail = (offset, path38, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source, offset), path: path38, code, message, hint: hint2 });
108609
108622
  const result = () => ({ problem: problems.map((p) => `${p.file}:${p.line}:${p.column} ${p.path}: ${p.code} \u2014 ${p.message}. ${p.hint}`).join("\n"), problems });
@@ -108631,7 +108644,7 @@ function parseStudioFile(id2, source, from) {
108631
108644
  const key = error63.params.additionalProperty ?? error63.params.missingProperty;
108632
108645
  if (key) parts.push(String(key));
108633
108646
  const node3 = parts.length ? document.getIn(parts, true) : document.contents;
108634
- fail(metaOffset + (node3?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error63.message}`, "Use only Studio metadata and previews: {id: {title?, icon?}} with the declared field types.");
108647
+ fail(metaOffset + (node3?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error63.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
108635
108648
  }
108636
108649
  }
108637
108650
  const body = source.slice(bodyOffset);
@@ -108641,6 +108654,20 @@ function parseStudioFile(id2, source, from) {
108641
108654
  const map2 = raw.previews ?? {};
108642
108655
  for (const block of parsed.blocks) if (!Object.hasOwn(map2, block.id)) fail(bodyOffset + block.start, `previews.${block.id}`, "preview-metadata-missing", `Preview ${block.id} has no metadata entry`, "Add the ID under previews, using {} if needed.");
108643
108656
  for (const key of Object.keys(map2)) if (!parsed.blocks.some((b) => b.id === key)) fail(metaOffset + (document.getIn(["previews", key], true)?.range?.[0] ?? 0), `previews.${key}`, "preview-body-missing", `Preview ${key} has no body`, "Add its block or remove unused metadata.");
108657
+ if (requirePreviewCopy) for (const block of parsed.blocks) {
108658
+ const metadata = Object.hasOwn(map2, block.id) ? map2[block.id] : void 0;
108659
+ if (!metadata) continue;
108660
+ for (const field of ["title", "description"]) for (const lang of ["en", "zh"]) {
108661
+ if (metadata[field]?.[lang]) continue;
108662
+ fail(
108663
+ bodyOffset + block.start,
108664
+ `previews.${block.id}.${field}.${lang}`,
108665
+ "preview-display-missing",
108666
+ `Preview ${block.id} needs a ${lang} ${field}`,
108667
+ "Add non-blank en and zh display text in the Preview metadata."
108668
+ );
108669
+ }
108670
+ }
108644
108671
  if (problems.length) return result();
108645
108672
  let rules = "", at = 0;
108646
108673
  for (const block of parsed.blocks) {
@@ -108708,12 +108735,12 @@ function mcpProblem(text3) {
108708
108735
  }
108709
108736
  return null;
108710
108737
  }
108711
- function checkStudioFiles(value, official = false) {
108712
- const read3 = inspect(value, official);
108738
+ function checkStudioFiles(value, official = false, allowLegacyPreviewCopy = false) {
108739
+ const read3 = inspect(value, official, allowLegacyPreviewCopy);
108713
108740
  const first = read3.problems[0];
108714
108741
  return first ? { ok: false, ...first, problems: read3.problems } : { ok: true, def: read3.def, files: read3.files };
108715
108742
  }
108716
- function inspect(value, official) {
108743
+ function inspect(value, official, allowLegacyPreviewCopy = false) {
108717
108744
  const problems = [];
108718
108745
  const fail = (file3, reason, tooLarge = false) => {
108719
108746
  problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
@@ -108758,7 +108785,7 @@ function inspect(value, official) {
108758
108785
  if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
108759
108786
  }
108760
108787
  const source = files[STUDIO_FILE];
108761
- const read3 = typeof source === "string" ? parseStudioFile("studio", source, STUDIO_FILE) : null;
108788
+ const read3 = typeof source === "string" ? parseStudioFile("studio", source, STUDIO_FILE, !official && !allowLegacyPreviewCopy) : null;
108762
108789
  if (!read3) fail(STUDIO_FILE, "is missing");
108763
108790
  else if ("problem" in read3) for (const problem of read3.problems) problems.push({ ...problem, reason: problem.message });
108764
108791
  if (!read3 || "problem" in read3) return { problems };
@@ -110911,7 +110938,7 @@ function createStreamRenderer() {
110911
110938
  const turnUsage = usageOf2(ev.usage);
110912
110939
  if (turnUsage) usage = usage ? addUsage(usage, turnUsage) : turnUsage;
110913
110940
  failure5 = ev.is_error === true ? whyItFailed(ev) : void 0;
110914
- classified = failure5 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, reason: failure5 } : { ...apiFailure ?? providerFailure(ev.error, failure5), reason: failure5 } : void 0;
110941
+ classified = failure5 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, source: "validation", reason: failure5 } : { ...apiFailure ?? providerFailure(ev.error, failure5), reason: failure5 } : void 0;
110915
110942
  apiFailure = void 0;
110916
110943
  if (failure5) events.error(failure5);
110917
110944
  turns.push({
@@ -111740,8 +111767,8 @@ function createTail(log) {
111740
111767
  // ../cli/package.json
111741
111768
  var package_default = {
111742
111769
  name: "wildcrane",
111743
- version: "0.11.73",
111744
- akbContract: 20,
111770
+ version: "0.11.74",
111771
+ akbContract: 21,
111745
111772
  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.",
111746
111773
  keywords: [
111747
111774
  "kanban",
@@ -111904,6 +111931,8 @@ async function oneTurn(io, options) {
111904
111931
  const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
111905
111932
  let started = false;
111906
111933
  let contentAt = 0;
111934
+ let thinkingAt = 0;
111935
+ let thinking = false;
111907
111936
  let currentSession = "";
111908
111937
  const events = createEventCollector();
111909
111938
  const emit = () => {
@@ -111933,7 +111962,20 @@ async function oneTurn(io, options) {
111933
111962
  }
111934
111963
  if (live && (!obj(msg.params).sessionId || obj(msg.params).sessionId === currentSession)) {
111935
111964
  const kind = str(obj(obj(msg.params).update).sessionUpdate);
111936
- if (["agent_message_chunk", "agent_thought_chunk"].includes(kind)) io.activity?.();
111965
+ if (["agent_message_chunk", "agent_thought_chunk"].includes(kind) && str(obj(obj(obj(msg.params).update).content).text)) {
111966
+ io.activity?.();
111967
+ if (kind === "agent_thought_chunk") {
111968
+ if (!thinking || Date.now() - thinkingAt >= 1e3) {
111969
+ io.event?.({ kind: "status", data: { state: "thinking", source: "acp" } });
111970
+ thinkingAt = Date.now();
111971
+ }
111972
+ thinking = true;
111973
+ }
111974
+ }
111975
+ if (thinking && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
111976
+ thinking = false;
111977
+ io.event?.({ kind: "status", data: { state: "running", source: "acp" } });
111978
+ }
111937
111979
  if (!started && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
111938
111980
  started = true;
111939
111981
  phase("started");
@@ -112407,8 +112449,15 @@ function decide2(params, tail) {
112407
112449
  return { decision: "deny", reason: "this board run can't answer a permission question" };
112408
112450
  }
112409
112451
 
112452
+ // ../cli/src/lib/agent/idle.ts
112453
+ var IDLE_MS2 = 5 * 6e4;
112454
+ var IDLE_ERROR = "No response for 5 minutes (idle timeout).";
112455
+ var IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
112456
+ var PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
112457
+
112410
112458
  // ../cli/src/lib/agent/wire/codex.ts
112411
112459
  import { randomUUID } from "node:crypto";
112460
+ import { setTimeout as delay } from "node:timers/promises";
112412
112461
 
112413
112462
  // ../cli/src/guide/settle-background.md
112414
112463
  var settle_background_default = "Wait for and collect needed results from this task's listed background work, stop what is no longer needed, and keep services the user still needs.\nInclude new task results and unresolved failures in your final reply; do not repeat results already shared or add a routine cleanup report.\n";
@@ -112650,6 +112699,7 @@ function createCodexClient(options = { images: [] }) {
112650
112699
  return {
112651
112700
  structured: true,
112652
112701
  managedProcess: true,
112702
+ idleRecovery: true,
112653
112703
  background: () => background,
112654
112704
  turn: (io) => run(io, options, (count2) => {
112655
112705
  background = count2;
@@ -112659,11 +112709,26 @@ function createCodexClient(options = { images: [] }) {
112659
112709
  async function run(io, options, count2) {
112660
112710
  const since = Date.now();
112661
112711
  const renderer = createCodexStreamRenderer();
112662
- const preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
112712
+ let idling = false;
112713
+ let preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
112663
112714
  const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
112664
112715
  let submitted = false;
112665
112716
  let started = false;
112666
112717
  let contentAt = 0;
112718
+ let status2;
112719
+ let statusAt = 0;
112720
+ const thinking = () => {
112721
+ if (status2 !== "thinking" || Date.now() - statusAt >= 1e3) {
112722
+ io.event?.({ kind: "status", data: { state: "thinking", source: "codex" } });
112723
+ statusAt = Date.now();
112724
+ }
112725
+ status2 = "thinking";
112726
+ };
112727
+ const recovered = () => {
112728
+ if (!status2) return;
112729
+ io.event?.({ kind: "status", data: { state: "running", source: "codex" } });
112730
+ status2 = void 0;
112731
+ };
112667
112732
  let startupTimer;
112668
112733
  const began = () => {
112669
112734
  if (!submitted || started || ended) return;
@@ -112714,11 +112779,12 @@ async function run(io, options, count2) {
112714
112779
  clearTimeout(startupTimer);
112715
112780
  clearTimeout(settleTimer);
112716
112781
  io.signal?.removeEventListener("abort", cancelled);
112782
+ io.idleSignal?.removeEventListener("abort", idle);
112717
112783
  count2(0);
112718
112784
  io.stdout.off("close", closed);
112719
112785
  io.stdin.off("error", inputFailed);
112720
112786
  if (settlement) flushMessages(work.work().some((w) => !w.intentionalStop && !["running", "unknown"].includes(w.status) && presented.get(w.id) !== snapshot(w)));
112721
- cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status: status2, disposition }) => ({ id: id2, threadId: threadId2, processId, status: status2, disposition }));
112787
+ cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status: status3, disposition }) => ({ id: id2, threadId: threadId2, processId, status: status3, disposition }));
112722
112788
  io.log(renderer.flush());
112723
112789
  const usage = ownUsage(total, baseline);
112724
112790
  const child = childSpend(children, since);
@@ -112748,10 +112814,32 @@ async function run(io, options, count2) {
112748
112814
  };
112749
112815
  const cancelled = () => {
112750
112816
  work.freeze();
112751
- note("Execution stopped; no further cleanup turn was submitted.");
112817
+ if (submitted || threadId) note("Execution stopped; no further cleanup turn was submitted.");
112752
112818
  end("Codex execution stopped.");
112753
112819
  };
112754
112820
  io.signal?.addEventListener("abort", cancelled, { once: true });
112821
+ const idle = async () => {
112822
+ if (ended || idling) return;
112823
+ idling = true;
112824
+ const unknownWork = () => [...work.entries.values()].some((item2) => ["running", "unknown", "interrupted"].includes(item2.status));
112825
+ const uncertain = unknownWork();
112826
+ const ownedTurn = currentTurn2;
112827
+ try {
112828
+ if (host2.idleRecovery !== true || !threadId || !ownedTurn || !active || settlement) throw Error("Codex did not confirm that this turn can be interrupted for recovery.");
112829
+ const receipt = await bounded(
112830
+ rpc.call("wildcrane/stopForRetry", { threadId, turnId: ownedTurn, instance: host2.instance, lease: host2.lease }),
112831
+ CONVERSATION_MS.prepare,
112832
+ "Codex did not confirm stopping the idle turn."
112833
+ );
112834
+ if (receipt.instance !== host2.instance || receipt.lease !== host2.lease || receipt.threadId !== threadId || receipt.turnId !== ownedTurn) throw Error("Codex returned a different turn or owner.");
112835
+ if (uncertain || unknownWork()) throw Error("Codex has operations with unconfirmed results.");
112836
+ cleanup.idleStop = { threadId, turnId: ownedTurn };
112837
+ } catch (error63) {
112838
+ if (!ended) note(error63 instanceof Error ? error63.message : String(error63));
112839
+ }
112840
+ if (!ended) end(IDLE_FAILURE.reason, IDLE_FAILURE);
112841
+ };
112842
+ io.idleSignal?.addEventListener("abort", idle, { once: true });
112755
112843
  const childUpdates = () => {
112756
112844
  for (const w of work.entries.values()) {
112757
112845
  if (w.kind !== "agent" || childEvents.get(w.id) === w.status) continue;
@@ -112965,9 +113053,13 @@ async function run(io, options, count2) {
112965
113053
  childUpdates();
112966
113054
  return;
112967
113055
  }
112968
- if (submitted && /\/delta$/.test(msg.method ?? "") && str(p.delta)) io.activity?.();
112969
113056
  const turnId = str(p.turnId) || str(obj(p.turn).id);
112970
113057
  if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
113058
+ if (submitted && ["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "") && str(p.delta)) {
113059
+ if (msg.method?.startsWith("item/reasoning/")) thinking();
113060
+ else recovered();
113061
+ io.activity?.();
113062
+ }
112971
113063
  if (msg.method === "turn/started") {
112972
113064
  if (!submitted || completedTurns.has(turnId)) return;
112973
113065
  currentTurn2 = turnId;
@@ -112980,7 +113072,10 @@ async function run(io, options, count2) {
112980
113072
  contentAt = Date.now();
112981
113073
  io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
112982
113074
  }
112983
- if (msg.method === "item/started" || msg.method === "item/completed") item(obj(p.item), msg.method === "item/completed", !completedTurns.has(turnId));
113075
+ if (msg.method === "item/started" || msg.method === "item/completed") {
113076
+ recovered();
113077
+ item(obj(p.item), msg.method === "item/completed", !completedTurns.has(turnId));
113078
+ }
112984
113079
  if (msg.method === "thread/tokenUsage/updated") {
112985
113080
  if (!submitted) return;
112986
113081
  const token = obj(p.tokenUsage);
@@ -112998,9 +113093,14 @@ async function run(io, options, count2) {
112998
113093
  context = { used: (Number(last2.inputTokens) || 0) + (Number(last2.outputTokens) || 0), ...Number(token.modelContextWindow) > 0 ? { limit: Number(token.modelContextWindow) } : {} };
112999
113094
  io.gotContext?.(context);
113000
113095
  }
113001
- if (msg.method === "error" && p.willRetry !== true) {
113096
+ if (msg.method === "error") {
113002
113097
  const failure5 = codexFailure(p.error, "Codex failed.");
113003
- end(failure5.reason, failure5);
113098
+ if (p.willRetry === true && submitted && active && !idling) {
113099
+ status2 = "retrying";
113100
+ io.log(`[Codex recovery] ${failure5.code}: ${failure5.reason}
113101
+ `);
113102
+ io.event?.({ kind: "status", data: { state: "retrying", source: "codex", code: failure5.code } });
113103
+ } else if (p.willRetry !== true) end(failure5.reason, failure5);
113004
113104
  }
113005
113105
  if (msg.method === "turn/completed") {
113006
113106
  const turn2 = obj(p.turn);
@@ -113011,6 +113111,7 @@ async function run(io, options, count2) {
113011
113111
  work.observe(threadId, raw);
113012
113112
  item(raw, true);
113013
113113
  }
113114
+ if (idling) return;
113014
113115
  if (turn2.status !== "completed") {
113015
113116
  const reason = str(obj(turn2.error).message) || `Codex turn ${str(turn2.status)}.`;
113016
113117
  const failure5 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : { code: "turn_stopped", level: 3, reason };
@@ -113031,6 +113132,10 @@ async function run(io, options, count2) {
113031
113132
  cancelled();
113032
113133
  return done;
113033
113134
  }
113135
+ if (io.idleSignal?.aborted) {
113136
+ void idle();
113137
+ return done;
113138
+ }
113034
113139
  phase("preparing");
113035
113140
  const initialized = await bounded(rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } }), preparingUntil - Date.now(), "Codex initialize timed out.");
113036
113141
  host2 = obj(initialized.wildcrane);
@@ -113038,11 +113143,31 @@ async function run(io, options, count2) {
113038
113143
  phase("initialized");
113039
113144
  rpc.notify("initialized");
113040
113145
  const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
113041
- 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.`);
113146
+ const method = `thread/${mode ?? "start"}`;
113147
+ const params = { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} };
113148
+ let response;
113149
+ let waiting2 = false;
113150
+ while (!ended && !response) {
113151
+ try {
113152
+ response = await bounded(rpc.call(method, params), preparingUntil - Date.now(), `Codex ${method} timed out.`);
113153
+ } catch (error63) {
113154
+ const failure5 = error63 instanceof RpcError ? codexFailure(error63.data, error63.message) : void 0;
113155
+ if (mode !== "fork" || failure5?.source !== "harness" || failure5.code !== "codex_source_busy") throw error63;
113156
+ if (!waiting2) {
113157
+ waiting2 = true;
113158
+ io.event?.({ kind: "log", data: { text: failure5.reason } });
113159
+ }
113160
+ io.activity?.();
113161
+ await delay(500, void 0, { signal: io.signal });
113162
+ preparingUntil = Date.now() + CONVERSATION_MS.prepare;
113163
+ }
113164
+ }
113165
+ if (ended || !response) return done;
113042
113166
  const thread = obj(response.thread);
113043
113167
  for (const turn2 of list2(thread.turns)) historicalTurns.add(str(turn2.id));
113044
113168
  threadId = str(thread.id);
113045
113169
  if (!threadId) throw Error("Codex did not return a thread id.");
113170
+ if (mode === "resume" && threadId !== params.threadId) throw Error("Codex did not return the requested session.");
113046
113171
  work.root(threadId, list2(response.retainedThreads).map((t2) => str(t2.id)));
113047
113172
  for (const terminal of list2(response.retainedTerminals)) retained.set(`terminal:${str(terminal.threadId)}:${str(terminal.itemId)}`, str(terminal.processId));
113048
113173
  provider = str(thread.modelProvider) || void 0;
@@ -115458,7 +115583,7 @@ var goalOf = (i) => ({
115458
115583
  outcome: i.outcome,
115459
115584
  acceptance: i.acceptance,
115460
115585
  studio: i.studio,
115461
- review_plan: i.review_plan ?? null,
115586
+ review_plan: readReviewPlan(i.review_plan),
115462
115587
  task: i.task ? { ...i.task, url: taskUrl(i.task.key || i.task.id) } : null
115463
115588
  });
115464
115589
  async function studiosOf(workspace) {