wildcrane-runner 0.6.91 → 0.6.93

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.73 — built by runner/scripts/build.mjs. Do not edit.
2
+ // ai4kanban 0.11.75 — built by runner/scripts/build.mjs. Do not edit.
3
3
  import { createRequire as __ai4kanbanRequire } from 'node:module'
4
4
  const require = __ai4kanbanRequire(import.meta.url)
5
5
  var __create = Object.create;
@@ -58,6 +58,11 @@ function insideRun() {
58
58
  function runEnv(env2, value) {
59
59
  return { ...env2, [RUN_ENV]: value };
60
60
  }
61
+ function taskReviewContext() {
62
+ const { AI4KANBAN_TASK_REVIEW: review, AI4KANBAN_REVIEW_STAGES: assigned } = process.env;
63
+ if (!review) return void 0;
64
+ return { review: JSON.parse(review), assigned: assigned ? JSON.parse(assigned) : void 0 };
65
+ }
61
66
  var RUN_ENV, SCHEDULED_AGENTS_ENV, SESSION_COST_ENV, STOP_ENV, SESSION_VARS;
62
67
  var init_env = __esm({
63
68
  "../cli/src/lib/agent/env.ts"() {
@@ -20848,11 +20853,52 @@ function parseReviewPlan(value, previews) {
20848
20853
  }
20849
20854
  return plan;
20850
20855
  }
20856
+ function readReviewPlan(plan) {
20857
+ return plan?.map(({ id: id2, after: after2, previews }) => ({ id: id2, after: after2, previews })) ?? null;
20858
+ }
20859
+ function reviewAuthorization(review, assigned, dispatchRevision) {
20860
+ if (review.pending_plan) return { kind: "pending" };
20861
+ const states2 = new Map(review.stages.map((stage) => [stage.id, stage]));
20862
+ const nodes = (review.plan ?? []).filter((node2) => {
20863
+ const stage = states2.get(node2.id);
20864
+ if (!stage || assigned && !assigned.includes(node2.id)) return false;
20865
+ return stage.status === "running" || stage.status === "available" && (dispatchRevision === void 0 || stage.revision <= dispatchRevision);
20866
+ });
20867
+ if (assigned?.some((id2) => !nodes.some((node2) => node2.id === id2))) return { kind: "changed" };
20868
+ if (review.plan === null) return { kind: "plan" };
20869
+ if (review.plan.length === 0) return { kind: "unreviewed" };
20870
+ if (nodes.length) return { kind: "stages", nodes };
20871
+ if (review.plan.every((node2) => states2.get(node2.id)?.status === "approved")) return { kind: "delivery" };
20872
+ return { kind: "waiting" };
20873
+ }
20874
+ function reviewAllows(authorization, action) {
20875
+ return action === "refine" ? authorization.kind === "plan" || authorization.kind === "stages" : authorization.kind === "unreviewed" || authorization.kind === "delivery";
20876
+ }
20877
+ function reviewInstruction(authorization) {
20878
+ switch (authorization.kind) {
20879
+ case "plan":
20880
+ return "Planning only. Propose a review plan; wait for explicit plan approval.";
20881
+ case "pending":
20882
+ return "Wait for the proposed plan decision. Do not start new stages.";
20883
+ case "unreviewed":
20884
+ return "No extra review. Complete the authorized work and Studio delivery checks.";
20885
+ case "stages":
20886
+ return [
20887
+ "Work only on these unlocked stages: " + authorization.nodes.map((node2) => node2.id).join(", "),
20888
+ ...authorization.nodes.map((node2) => `- ${node2.id}: ${node2.previews.length ? node2.previews.join(", ") : "card body"}`)
20889
+ ].join("\n");
20890
+ case "delivery":
20891
+ return "Stages complete. Follow Studio delivery checks.";
20892
+ case "changed":
20893
+ return "Review authorization changed. Read the task again.";
20894
+ case "waiting":
20895
+ return "Wait for review. Do not execute locked stages.";
20896
+ }
20897
+ }
20851
20898
  function reviewBoundary(review, assigned) {
20852
- const allowed = review.pending_plan ? [] : review.stages.filter((s) => (s.status === "available" || s.status === "running") && (!assigned || assigned.includes(s.id)));
20853
20899
  return [
20854
20900
  "Task review: " + JSON.stringify(review),
20855
- review.plan === null ? "Planning only. Propose a review plan; wait for explicit plan approval." : review.pending_plan ? "Wait for the proposed plan decision. Do not start new stages." : !review.plan.length ? "No extra review. Complete the authorized work and Studio delivery checks." : allowed.length ? "Work only on these unlocked stages: " + allowed.map((s) => s.id).join(", ") : review.stages.every((s) => s.status === "approved") ? "Stages complete. Follow Studio delivery checks." : "Wait for review. Do not execute locked stages.",
20901
+ reviewInstruction(reviewAuthorization(review, assigned)),
20856
20902
  "Read akb task review before reporting running/done with its revision. Sync content and assets before done. Revise a stage before changing its approved output. Questions and plan approval never approve outputs."
20857
20903
  ].join("\n");
20858
20904
  }
@@ -20864,7 +20910,6 @@ var init_review_plan = __esm({
20864
20910
  id = external_exports.string().trim().min(1).max(100);
20865
20911
  reviewNodeSchema = external_exports.object({
20866
20912
  id,
20867
- title: external_exports.string().trim().min(1).max(200),
20868
20913
  after: external_exports.array(id).max(50).default([]),
20869
20914
  previews: external_exports.array(id).max(50).default([])
20870
20915
  }).strict();
@@ -20931,8 +20976,8 @@ function deferRefresh(session, error62, after2) {
20931
20976
  const attempt2 = Math.min((readRetry(session)?.attempt ?? 0) + 1, 4);
20932
20977
  const seconds = after2?.trim() ? Number(after2) : NaN;
20933
20978
  const serverDelay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(after2 ?? "") - Date.now();
20934
- const delay2 = Math.max(Math.min(REFRESH_BACKOFF_MS * 2 ** (attempt2 - 1), 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
20935
- const retry2 = { key: refreshKey(session), until: Date.now() + delay2, attempt: attempt2, error: error62 };
20979
+ const delay3 = Math.max(Math.min(REFRESH_BACKOFF_MS * 2 ** (attempt2 - 1), 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
20980
+ const retry2 = { key: refreshKey(session), until: Date.now() + delay3, attempt: attempt2, error: error62 };
20936
20981
  const temporary = `${retryFile()}.${process.pid}.tmp`;
20937
20982
  fs3.writeFileSync(temporary, JSON.stringify(retry2), { mode: 384 });
20938
20983
  fs3.renameSync(temporary, retryFile());
@@ -36764,7 +36809,7 @@ var init_preview_blocks = __esm({
36764
36809
  });
36765
36810
 
36766
36811
  // ../cli/src/lib/agent/studio-def.ts
36767
- function parseStudioFile(id2, source2, from) {
36812
+ function parseStudioFile(id2, source2, from, requirePreviewCopy = false) {
36768
36813
  const problems = [];
36769
36814
  const fail = (offset, path86, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source2, offset), path: path86, code, message, hint: hint2 });
36770
36815
  const result = () => ({ problem: problems.map((p) => `${p.file}:${p.line}:${p.column} ${p.path}: ${p.code} \u2014 ${p.message}. ${p.hint}`).join("\n"), problems });
@@ -36792,7 +36837,7 @@ function parseStudioFile(id2, source2, from) {
36792
36837
  const key = error62.params.additionalProperty ?? error62.params.missingProperty;
36793
36838
  if (key) parts.push(String(key));
36794
36839
  const node2 = parts.length ? document.getIn(parts, true) : document.contents;
36795
- fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, icon?}} with the declared field types.");
36840
+ fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
36796
36841
  }
36797
36842
  }
36798
36843
  const body = source2.slice(bodyOffset);
@@ -36802,6 +36847,20 @@ function parseStudioFile(id2, source2, from) {
36802
36847
  const map3 = raw.previews ?? {};
36803
36848
  for (const block of parsed.blocks) if (!Object.hasOwn(map3, 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.");
36804
36849
  for (const key of Object.keys(map3)) 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.");
36850
+ if (requirePreviewCopy) for (const block of parsed.blocks) {
36851
+ const metadata = Object.hasOwn(map3, block.id) ? map3[block.id] : void 0;
36852
+ if (!metadata) continue;
36853
+ for (const field2 of ["title", "description"]) for (const lang of ["en", "zh"]) {
36854
+ if (metadata[field2]?.[lang]) continue;
36855
+ fail(
36856
+ bodyOffset + block.start,
36857
+ `previews.${block.id}.${field2}.${lang}`,
36858
+ "preview-display-missing",
36859
+ `Preview ${block.id} needs a ${lang} ${field2}`,
36860
+ "Add non-blank en and zh display text in the Preview metadata."
36861
+ );
36862
+ }
36863
+ }
36805
36864
  if (problems.length) return result();
36806
36865
  let rules = "", at = 0;
36807
36866
  for (const block of parsed.blocks) {
@@ -36854,7 +36913,7 @@ var init_studio_def = __esm({
36854
36913
  previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
36855
36914
  type: "object",
36856
36915
  additionalProperties: false,
36857
- properties: { title: titles, icon }
36916
+ properties: { title: titles, description: titles, icon }
36858
36917
  } }
36859
36918
  }
36860
36919
  };
@@ -36896,12 +36955,12 @@ function mcpProblem(text5) {
36896
36955
  }
36897
36956
  return null;
36898
36957
  }
36899
- function checkStudioFiles(value, official = false) {
36900
- const read5 = inspect(value, official);
36958
+ function checkStudioFiles(value, official = false, allowLegacyPreviewCopy = false) {
36959
+ const read5 = inspect(value, official, allowLegacyPreviewCopy);
36901
36960
  const first = read5.problems[0];
36902
36961
  return first ? { ok: false, ...first, problems: read5.problems } : { ok: true, def: read5.def, files: read5.files };
36903
36962
  }
36904
- function inspect(value, official) {
36963
+ function inspect(value, official, allowLegacyPreviewCopy = false) {
36905
36964
  const problems = [];
36906
36965
  const fail = (file2, reason, tooLarge = false) => {
36907
36966
  problems.push({ file: file2, reason, ...tooLarge ? { tooLarge } : {} });
@@ -36946,7 +37005,7 @@ function inspect(value, official) {
36946
37005
  if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
36947
37006
  }
36948
37007
  const source2 = files[STUDIO_FILE];
36949
- const read5 = typeof source2 === "string" ? parseStudioFile("studio", source2, STUDIO_FILE) : null;
37008
+ const read5 = typeof source2 === "string" ? parseStudioFile("studio", source2, STUDIO_FILE, !official && !allowLegacyPreviewCopy) : null;
36950
37009
  if (!read5) fail(STUDIO_FILE, "is missing");
36951
37010
  else if ("problem" in read5) for (const problem of read5.problems) problems.push({ ...problem, reason: problem.message });
36952
37011
  if (!read5 || "problem" in read5) return { problems };
@@ -37531,6 +37590,7 @@ function loadGoals() {
37531
37590
  if (held4.goals !== void 0 && held4.ideas !== void 0 && JSON.stringify(held4.goals) !== JSON.stringify(held4.ideas)) die("goals and ideas do not match.");
37532
37591
  const goals = held4.goals ?? held4.ideas;
37533
37592
  if (!Array.isArray(goals)) die("The goals array is missing or invalid.");
37593
+ for (const goal of goals) if (goal.review_plan !== void 0) goal.review_plan = readReviewPlan(goal.review_plan);
37534
37594
  return { file: file2, held: { ...held4, studios: held4.studios ?? [], goals } };
37535
37595
  }
37536
37596
  function studioOf(held4, asked) {
@@ -41156,6 +41216,16 @@ var init_card_studio_backfill = __esm({
41156
41216
  }
41157
41217
  });
41158
41218
 
41219
+ // ../cli/src/lib/agent/wire/codex-background-types.ts
41220
+ function idleStopConfirmed(cleanup, session) {
41221
+ return !!session && cleanup?.status === "confirmed" && !!cleanup.instance && Array.isArray(cleanup.kept) && cleanup.kept.length === 0 && cleanup.idleStop?.threadId === session && typeof cleanup.idleStop.turnId === "string" && !!cleanup.idleStop.turnId;
41222
+ }
41223
+ var init_codex_background_types = __esm({
41224
+ "../cli/src/lib/agent/wire/codex-background-types.ts"() {
41225
+ "use strict";
41226
+ }
41227
+ });
41228
+
41159
41229
  // ../cli/src/lib/lock.ts
41160
41230
  import { randomUUID } from "node:crypto";
41161
41231
  import fs18 from "node:fs";
@@ -41374,17 +41444,17 @@ function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs) {
41374
41444
  if (!Number.isSafeInteger(attempt2) || attempt2 < 1 || failure2.level === 3) return { pause: "needs-review" };
41375
41445
  const of = failure2.level === 1 ? 2 : 4;
41376
41446
  if (attempt2 >= of) return { pause: "limit" };
41377
- const delay2 = failure2.retryAfterMs;
41378
- const valid = delay2 !== void 0 && !Number.isNaN(delay2) && delay2 >= 0;
41379
- const wait = valid ? delay2 : failure2.level === 1 ? 0 : backoff(attempt2 + 1);
41447
+ const delay3 = failure2.retryAfterMs;
41448
+ const valid = delay3 !== void 0 && !Number.isNaN(delay3) && delay3 >= 0;
41449
+ const wait = valid ? delay3 : failure2.level === 1 ? 0 : backoff(attempt2 + 1);
41380
41450
  if (wait > CAP_MS) return { pause: "wait-too-long" };
41381
41451
  return { plan: { at: now + wait, of, failure: failure2 } };
41382
41452
  }
41383
41453
  function readFailure(raw) {
41384
41454
  if (!raw || typeof raw !== "object") return;
41385
- const { code, level: level2, reason, retryAfterMs: retryAfterMs2 } = raw;
41455
+ const { code, level: level2, reason, source: source2, retryAfterMs: retryAfterMs2 } = raw;
41386
41456
  if (typeof code !== "string" || !code || typeof reason !== "string" || level2 !== 1 && level2 !== 2 && level2 !== 3) return;
41387
- return { code, level: level2, reason, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
41457
+ return { code, level: level2, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source2) ? { source: source2 } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
41388
41458
  }
41389
41459
  function readRetryPlan(raw, attempt2) {
41390
41460
  if (!raw || typeof raw !== "object") return;
@@ -41412,6 +41482,11 @@ function retryLine(plan, attempt2, now = Date.now()) {
41412
41482
  const seconds = Math.max(0, Math.ceil((plan.at - now) / 1e3));
41413
41483
  return `${plan.failure.reason} \u2014 retrying ${seconds ? `in ${seconds}s` : "now"} (attempt ${attempt2 + 1} of ${plan.of}).`;
41414
41484
  }
41485
+ function syncRepairPrompt(reason) {
41486
+ return `The Harness could not synchronize the saved result. Correct the diagnostics below, verify the original result and its attachments, then continue from the saved work. Preserve completed work and archive state. Read the task review before changing an approved output and revise its stage first.
41487
+
41488
+ ${reason}`;
41489
+ }
41415
41490
  var BASE_MS, CAP_MS;
41416
41491
  var init_retry = __esm({
41417
41492
  "../cli/src/lib/agent/retry.ts"() {
@@ -41739,8 +41814,8 @@ var init_package = __esm({
41739
41814
  "../cli/package.json"() {
41740
41815
  package_default = {
41741
41816
  name: "wildcrane",
41742
- version: "0.11.73",
41743
- akbContract: 20,
41817
+ version: "0.11.75",
41818
+ akbContract: 22,
41744
41819
  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.",
41745
41820
  keywords: [
41746
41821
  "kanban",
@@ -43501,6 +43576,7 @@ function executionFailure(error62) {
43501
43576
  return {
43502
43577
  code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
43503
43578
  level: NETWORK.has(code) ? 2 : 3,
43579
+ source: "harness",
43504
43580
  reason
43505
43581
  };
43506
43582
  }
@@ -43518,17 +43594,19 @@ function providerFailure(error62, reason) {
43518
43594
  const headers = obj2(info.headers);
43519
43595
  const wait = retryAfterMs(headers["retry-after"] ?? headers["Retry-After"]);
43520
43596
  const code = info.code ?? info.type;
43521
- if (code === "session_not_found") return { code, level: 3, reason };
43597
+ if (code === "session_not_found") return { code, source: "provider", level: 3, reason };
43522
43598
  if (status === 401 || status === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str2(code))) {
43523
- return { code: "provider_refused", level: 3, reason };
43599
+ return { code: "provider_refused", source: "provider", level: 3, reason };
43524
43600
  }
43525
- if (code === "rate_limit_error") return { code: "rate_limited", level: 2, reason, retryAfterMs: wait };
43526
- if (TEMPORARY_HTTP.has(status ?? 0) || code === "overloaded_error") return { code: "service_overloaded", level: 2, reason, retryAfterMs: wait };
43527
- if (NETWORK.has(str2(code))) return { code: "connection_lost", level: 2, reason, retryAfterMs: wait };
43528
- return { code: "provider_failed", level: 3, reason };
43601
+ if (code === "rate_limit_error") return { code: "rate_limited", source: "provider", level: 2, reason, retryAfterMs: wait };
43602
+ if (TEMPORARY_HTTP.has(status ?? 0) || code === "overloaded_error") return { code: "service_overloaded", source: "provider", level: 2, reason, retryAfterMs: wait };
43603
+ if (NETWORK.has(str2(code))) return { code: "connection_lost", source: "provider", level: 2, reason, retryAfterMs: wait };
43604
+ return { code: "provider_failed", source: "provider", level: 3, reason };
43529
43605
  }
43530
43606
  function codexFailure(raw, fallback) {
43531
43607
  const error62 = obj2(raw);
43608
+ const failure2 = readFailure(error62.wildcraneFailure);
43609
+ if (failure2?.source === "harness" || failure2?.source === "invariant") return failure2;
43532
43610
  const reason = str2(error62.message) || fallback;
43533
43611
  const info = error62.codexErrorInfo;
43534
43612
  if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason);
@@ -43546,6 +43624,7 @@ var ExecutionError, NETWORK, TEMPORARY_HTTP;
43546
43624
  var init_failures = __esm({
43547
43625
  "../cli/src/lib/agent/wire/failures.ts"() {
43548
43626
  "use strict";
43627
+ init_retry();
43549
43628
  init_json();
43550
43629
  ExecutionError = class extends Error {
43551
43630
  constructor(failure2) {
@@ -43695,7 +43774,7 @@ function createStreamRenderer() {
43695
43774
  const turnUsage = usageOf2(ev.usage);
43696
43775
  if (turnUsage) usage3 = usage3 ? addUsage(usage3, turnUsage) : turnUsage;
43697
43776
  failure2 = ev.is_error === true ? whyItFailed(ev) : void 0;
43698
- 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;
43777
+ classified = failure2 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, source: "validation", reason: failure2 } : { ...apiFailure ?? providerFailure(ev.error, failure2), reason: failure2 } : void 0;
43699
43778
  apiFailure = void 0;
43700
43779
  if (failure2) events.error(failure2);
43701
43780
  turns.push({
@@ -44806,6 +44885,8 @@ async function oneTurn(io, options) {
44806
44885
  const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
44807
44886
  let started = false;
44808
44887
  let contentAt = 0;
44888
+ let thinkingAt = 0;
44889
+ let thinking = false;
44809
44890
  let currentSession = "";
44810
44891
  const events = createEventCollector();
44811
44892
  const emit = () => {
@@ -44835,7 +44916,20 @@ async function oneTurn(io, options) {
44835
44916
  }
44836
44917
  if (live && (!obj2(msg.params).sessionId || obj2(msg.params).sessionId === currentSession)) {
44837
44918
  const kind = str2(obj2(obj2(msg.params).update).sessionUpdate);
44838
- if (["agent_message_chunk", "agent_thought_chunk"].includes(kind)) io.activity?.();
44919
+ if (["agent_message_chunk", "agent_thought_chunk"].includes(kind) && str2(obj2(obj2(obj2(msg.params).update).content).text)) {
44920
+ io.activity?.();
44921
+ if (kind === "agent_thought_chunk") {
44922
+ if (!thinking || Date.now() - thinkingAt >= 1e3) {
44923
+ io.event?.({ kind: "status", data: { state: "thinking", source: "acp" } });
44924
+ thinkingAt = Date.now();
44925
+ }
44926
+ thinking = true;
44927
+ }
44928
+ }
44929
+ if (thinking && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
44930
+ thinking = false;
44931
+ io.event?.({ kind: "status", data: { state: "running", source: "acp" } });
44932
+ }
44839
44933
  if (!started && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
44840
44934
  started = true;
44841
44935
  phase("started");
@@ -45348,6 +45442,90 @@ var init_zcode = __esm({
45348
45442
  }
45349
45443
  });
45350
45444
 
45445
+ // ../cli/src/lib/agent/idle.ts
45446
+ function createIdleWatchdog(expired, busy = () => false, milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now) {
45447
+ const calls = /* @__PURE__ */ new Set();
45448
+ const local = /* @__PURE__ */ new Set();
45449
+ const seen = /* @__PURE__ */ new Map();
45450
+ let last = now();
45451
+ let working = false;
45452
+ let closed2 = false;
45453
+ let recoveringAt;
45454
+ let retryUntil = 0;
45455
+ const touch = () => {
45456
+ if (!closed2) {
45457
+ last = now();
45458
+ recoveringAt = void 0;
45459
+ retryUntil = 0;
45460
+ }
45461
+ };
45462
+ const check2 = () => {
45463
+ if (closed2) return;
45464
+ if (retryUntil > now()) return;
45465
+ const active3 = calls.size > 0 || busy();
45466
+ if (active3 || working) last = now();
45467
+ working = active3;
45468
+ if (!active3 && now() - last >= milliseconds) {
45469
+ close();
45470
+ expired();
45471
+ }
45472
+ };
45473
+ const timer = setInterval(check2, Math.min(1e3, milliseconds));
45474
+ timer.unref?.();
45475
+ const close = () => {
45476
+ closed2 = true;
45477
+ clearInterval(timer);
45478
+ calls.clear();
45479
+ local.clear();
45480
+ seen.clear();
45481
+ };
45482
+ return {
45483
+ touch,
45484
+ check: check2,
45485
+ close,
45486
+ event(e) {
45487
+ if (closed2) return;
45488
+ if (e.kind === "status") {
45489
+ if (e.data.state !== "retrying") touch();
45490
+ else {
45491
+ recoveringAt ??= now();
45492
+ retryUntil = Math.min(now() + PROVIDER_RETRY_MS.announcement, recoveringAt + PROVIDER_RETRY_MS.episode);
45493
+ }
45494
+ check2();
45495
+ return;
45496
+ }
45497
+ if (e.kind === "log" || e.kind === "context") return;
45498
+ if (e.kind === "phase" && !e.data.contentAt) return;
45499
+ const key = e.kind === "tool_call" || e.kind === "tool_call_update" ? `${e.kind}:${e.data.toolCallId}` : e.kind;
45500
+ const value = JSON.stringify(e.data);
45501
+ if (seen.get(key) === value) return;
45502
+ seen.set(key, value);
45503
+ if (e.kind === "tool_call" && (e.data.kind === "execute" || e.data.subagent)) local.add(e.data.toolCallId);
45504
+ if (e.kind === "tool_call" || e.kind === "tool_call_update") {
45505
+ const { toolCallId, status } = e.data;
45506
+ if (local.has(toolCallId) && ["in_progress", "running"].includes(status)) calls.add(toolCallId);
45507
+ if (["completed", "failed"].includes(status)) {
45508
+ calls.delete(toolCallId);
45509
+ local.delete(toolCallId);
45510
+ }
45511
+ }
45512
+ touch();
45513
+ check2();
45514
+ }
45515
+ };
45516
+ }
45517
+ var IDLE_MS, IDLE_TIMEOUT, IDLE_ERROR, IDLE_FAILURE, PROVIDER_RETRY_MS;
45518
+ var init_idle = __esm({
45519
+ "../cli/src/lib/agent/idle.ts"() {
45520
+ "use strict";
45521
+ IDLE_MS = 5 * 6e4;
45522
+ IDLE_TIMEOUT = { milliseconds: IDLE_MS };
45523
+ IDLE_ERROR = "No response for 5 minutes (idle timeout).";
45524
+ IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
45525
+ PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
45526
+ }
45527
+ });
45528
+
45351
45529
  // ../cli/src/guide/settle-background.md
45352
45530
  var settle_background_default;
45353
45531
  var init_settle_background = __esm({
@@ -45557,6 +45735,7 @@ var init_codex_work = __esm({
45557
45735
 
45558
45736
  // ../cli/src/lib/agent/wire/codex.ts
45559
45737
  import { randomUUID as randomUUID4 } from "node:crypto";
45738
+ import { setTimeout as delay } from "node:timers/promises";
45560
45739
  function createCodexConnection(argv) {
45561
45740
  const execAt = argv.indexOf("exec");
45562
45741
  if (execAt < 1) return void 0;
@@ -45609,6 +45788,7 @@ function createCodexClient(options = { images: [] }) {
45609
45788
  return {
45610
45789
  structured: true,
45611
45790
  managedProcess: true,
45791
+ idleRecovery: true,
45612
45792
  background: () => background,
45613
45793
  turn: (io) => run(io, options, (count3) => {
45614
45794
  background = count3;
@@ -45618,11 +45798,26 @@ function createCodexClient(options = { images: [] }) {
45618
45798
  async function run(io, options, count3) {
45619
45799
  const since = Date.now();
45620
45800
  const renderer = createCodexStreamRenderer();
45621
- const preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
45801
+ let idling = false;
45802
+ let preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
45622
45803
  const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
45623
45804
  let submitted = false;
45624
45805
  let started = false;
45625
45806
  let contentAt = 0;
45807
+ let status;
45808
+ let statusAt = 0;
45809
+ const thinking = () => {
45810
+ if (status !== "thinking" || Date.now() - statusAt >= 1e3) {
45811
+ io.event?.({ kind: "status", data: { state: "thinking", source: "codex" } });
45812
+ statusAt = Date.now();
45813
+ }
45814
+ status = "thinking";
45815
+ };
45816
+ const recovered = () => {
45817
+ if (!status) return;
45818
+ io.event?.({ kind: "status", data: { state: "running", source: "codex" } });
45819
+ status = void 0;
45820
+ };
45626
45821
  let startupTimer;
45627
45822
  const began = () => {
45628
45823
  if (!submitted || started || ended) return;
@@ -45673,11 +45868,12 @@ async function run(io, options, count3) {
45673
45868
  clearTimeout(startupTimer);
45674
45869
  clearTimeout(settleTimer);
45675
45870
  io.signal?.removeEventListener("abort", cancelled);
45871
+ io.idleSignal?.removeEventListener("abort", idle);
45676
45872
  count3(0);
45677
45873
  io.stdout.off("close", closed2);
45678
45874
  io.stdin.off("error", inputFailed);
45679
45875
  if (settlement) flushMessages(work.work().some((w) => !w.intentionalStop && !["running", "unknown"].includes(w.status) && presented.get(w.id) !== snapshot2(w)));
45680
- cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status, disposition }) => ({ id: id2, threadId: threadId2, processId, status, disposition }));
45876
+ cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status: status2, disposition }) => ({ id: id2, threadId: threadId2, processId, status: status2, disposition }));
45681
45877
  io.log(renderer.flush());
45682
45878
  const usage3 = ownUsage(total, baseline);
45683
45879
  const child = childSpend(children, since);
@@ -45707,10 +45903,32 @@ async function run(io, options, count3) {
45707
45903
  };
45708
45904
  const cancelled = () => {
45709
45905
  work.freeze();
45710
- note("Execution stopped; no further cleanup turn was submitted.");
45906
+ if (submitted || threadId) note("Execution stopped; no further cleanup turn was submitted.");
45711
45907
  end2("Codex execution stopped.");
45712
45908
  };
45713
45909
  io.signal?.addEventListener("abort", cancelled, { once: true });
45910
+ const idle = async () => {
45911
+ if (ended || idling) return;
45912
+ idling = true;
45913
+ const unknownWork = () => [...work.entries.values()].some((item2) => ["running", "unknown", "interrupted"].includes(item2.status));
45914
+ const uncertain = unknownWork();
45915
+ const ownedTurn = currentTurn2;
45916
+ try {
45917
+ if (host2.idleRecovery !== true || !threadId || !ownedTurn || !active3 || settlement) throw Error("Codex did not confirm that this turn can be interrupted for recovery.");
45918
+ const receipt = await bounded(
45919
+ rpc.call("wildcrane/stopForRetry", { threadId, turnId: ownedTurn, instance: host2.instance, lease: host2.lease }),
45920
+ CONVERSATION_MS.prepare,
45921
+ "Codex did not confirm stopping the idle turn."
45922
+ );
45923
+ if (receipt.instance !== host2.instance || receipt.lease !== host2.lease || receipt.threadId !== threadId || receipt.turnId !== ownedTurn) throw Error("Codex returned a different turn or owner.");
45924
+ if (uncertain || unknownWork()) throw Error("Codex has operations with unconfirmed results.");
45925
+ cleanup.idleStop = { threadId, turnId: ownedTurn };
45926
+ } catch (error62) {
45927
+ if (!ended) note(error62 instanceof Error ? error62.message : String(error62));
45928
+ }
45929
+ if (!ended) end2(IDLE_FAILURE.reason, IDLE_FAILURE);
45930
+ };
45931
+ io.idleSignal?.addEventListener("abort", idle, { once: true });
45714
45932
  const childUpdates = () => {
45715
45933
  for (const w of work.entries.values()) {
45716
45934
  if (w.kind !== "agent" || childEvents.get(w.id) === w.status) continue;
@@ -45924,9 +46142,13 @@ async function run(io, options, count3) {
45924
46142
  childUpdates();
45925
46143
  return;
45926
46144
  }
45927
- if (submitted && /\/delta$/.test(msg.method ?? "") && str2(p.delta)) io.activity?.();
45928
46145
  const turnId = str2(p.turnId) || str2(obj2(p.turn).id);
45929
46146
  if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
46147
+ if (submitted && ["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "") && str2(p.delta)) {
46148
+ if (msg.method?.startsWith("item/reasoning/")) thinking();
46149
+ else recovered();
46150
+ io.activity?.();
46151
+ }
45930
46152
  if (msg.method === "turn/started") {
45931
46153
  if (!submitted || completedTurns.has(turnId)) return;
45932
46154
  currentTurn2 = turnId;
@@ -45939,7 +46161,10 @@ async function run(io, options, count3) {
45939
46161
  contentAt = Date.now();
45940
46162
  io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
45941
46163
  }
45942
- if (msg.method === "item/started" || msg.method === "item/completed") item(obj2(p.item), msg.method === "item/completed", !completedTurns.has(turnId));
46164
+ if (msg.method === "item/started" || msg.method === "item/completed") {
46165
+ recovered();
46166
+ item(obj2(p.item), msg.method === "item/completed", !completedTurns.has(turnId));
46167
+ }
45943
46168
  if (msg.method === "thread/tokenUsage/updated") {
45944
46169
  if (!submitted) return;
45945
46170
  const token2 = obj2(p.tokenUsage);
@@ -45957,9 +46182,14 @@ async function run(io, options, count3) {
45957
46182
  context = { used: (Number(last.inputTokens) || 0) + (Number(last.outputTokens) || 0), ...Number(token2.modelContextWindow) > 0 ? { limit: Number(token2.modelContextWindow) } : {} };
45958
46183
  io.gotContext?.(context);
45959
46184
  }
45960
- if (msg.method === "error" && p.willRetry !== true) {
46185
+ if (msg.method === "error") {
45961
46186
  const failure2 = codexFailure(p.error, "Codex failed.");
45962
- end2(failure2.reason, failure2);
46187
+ if (p.willRetry === true && submitted && active3 && !idling) {
46188
+ status = "retrying";
46189
+ io.log(`[Codex recovery] ${failure2.code}: ${failure2.reason}
46190
+ `);
46191
+ io.event?.({ kind: "status", data: { state: "retrying", source: "codex", code: failure2.code } });
46192
+ } else if (p.willRetry !== true) end2(failure2.reason, failure2);
45963
46193
  }
45964
46194
  if (msg.method === "turn/completed") {
45965
46195
  const turn2 = obj2(p.turn);
@@ -45970,6 +46200,7 @@ async function run(io, options, count3) {
45970
46200
  work.observe(threadId, raw);
45971
46201
  item(raw, true);
45972
46202
  }
46203
+ if (idling) return;
45973
46204
  if (turn2.status !== "completed") {
45974
46205
  const reason = str2(obj2(turn2.error).message) || `Codex turn ${str2(turn2.status)}.`;
45975
46206
  const failure2 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : { code: "turn_stopped", level: 3, reason };
@@ -45990,6 +46221,10 @@ async function run(io, options, count3) {
45990
46221
  cancelled();
45991
46222
  return done;
45992
46223
  }
46224
+ if (io.idleSignal?.aborted) {
46225
+ void idle();
46226
+ return done;
46227
+ }
45993
46228
  phase("preparing");
45994
46229
  const initialized = await bounded(rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } }), preparingUntil - Date.now(), "Codex initialize timed out.");
45995
46230
  host2 = obj2(initialized.wildcrane);
@@ -45997,11 +46232,31 @@ async function run(io, options, count3) {
45997
46232
  phase("initialized");
45998
46233
  rpc.notify("initialized");
45999
46234
  const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
46000
- 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.`);
46235
+ const method = `thread/${mode ?? "start"}`;
46236
+ const params = { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} };
46237
+ let response;
46238
+ let waiting = false;
46239
+ while (!ended && !response) {
46240
+ try {
46241
+ response = await bounded(rpc.call(method, params), preparingUntil - Date.now(), `Codex ${method} timed out.`);
46242
+ } catch (error62) {
46243
+ const failure2 = error62 instanceof RpcError ? codexFailure(error62.data, error62.message) : void 0;
46244
+ if (mode !== "fork" || failure2?.source !== "harness" || failure2.code !== "codex_source_busy") throw error62;
46245
+ if (!waiting) {
46246
+ waiting = true;
46247
+ io.event?.({ kind: "log", data: { text: failure2.reason } });
46248
+ }
46249
+ io.activity?.();
46250
+ await delay(500, void 0, { signal: io.signal });
46251
+ preparingUntil = Date.now() + CONVERSATION_MS.prepare;
46252
+ }
46253
+ }
46254
+ if (ended || !response) return done;
46001
46255
  const thread = obj2(response.thread);
46002
46256
  for (const turn2 of list2(thread.turns)) historicalTurns.add(str2(turn2.id));
46003
46257
  threadId = str2(thread.id);
46004
46258
  if (!threadId) throw Error("Codex did not return a thread id.");
46259
+ if (mode === "resume" && threadId !== params.threadId) throw Error("Codex did not return the requested session.");
46005
46260
  work.root(threadId, list2(response.retainedThreads).map((t) => str2(t.id)));
46006
46261
  for (const terminal of list2(response.retainedTerminals)) retained.set(`terminal:${str2(terminal.threadId)}:${str2(terminal.itemId)}`, str2(terminal.processId));
46007
46262
  provider = str2(thread.modelProvider) || void 0;
@@ -46023,6 +46278,7 @@ var list2;
46023
46278
  var init_codex = __esm({
46024
46279
  "../cli/src/lib/agent/wire/codex.ts"() {
46025
46280
  "use strict";
46281
+ init_idle();
46026
46282
  init_failures();
46027
46283
  init_conversation();
46028
46284
  init_codex_background();
@@ -52159,7 +52415,10 @@ async function openResume(id2, options) {
52159
52415
  if (pending) {
52160
52416
  const root2 = prev.agentPid ? { pid: prev.agentPid, since: prev.agentStartedAt ?? prev.startedAt, identity: prev.agentIdentity } : void 0;
52161
52417
  const stopped2 = prev.managedProcess ? connectionStopped(root2) : processesStopped(runMark(prev.sessionId, prev.agentStartedAt), root2);
52162
- if (!stopped2 || !resumeSessionId(prev)) return retryRefusal(prev, "unsafe");
52418
+ const session2 = resumeSessionId(prev);
52419
+ if (!stopped2 || !session2 || prev.managedProcess && pending.failure.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session2)) {
52420
+ return retryRefusal(prev, "unsafe");
52421
+ }
52163
52422
  await new Promise((resolve2) => setTimeout(resolve2, Math.max(0, pending.at - Date.now())));
52164
52423
  if (!await executionHeld(executionOf())) return retryRefusal(prev, "authorization");
52165
52424
  }
@@ -52539,6 +52798,7 @@ var INDEX_ACTIONS, SINGLETON_ACTIONS, VERB, SINGLETON_BUSY, RUN_STATUS, specPath
52539
52798
  var init_sessions = __esm({
52540
52799
  "../cli/src/lib/agent/sessions.ts"() {
52541
52800
  "use strict";
52801
+ init_codex_background_types();
52542
52802
  init_connection_process();
52543
52803
  init_retry();
52544
52804
  init_execution();
@@ -52837,8 +53097,8 @@ var init_inbox = __esm({
52837
53097
  META_LINE = /^\s+("(?:[^"\\]|\\.)*"|[^:]+):\s*(.*)$/;
52838
53098
  slugOf = (said2) => said2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 56).replace(/-+$/, "");
52839
53099
  fileName = (title, slug = "") => `${slugOf(slug) || slugOf(title) || "item"}.md`;
52840
- readArchived = () => readFolder(SIGNALS_ARCHIVED);
52841
- readAllDismissed = () => readFolder(SIGNALS_DISMISSED, true);
53100
+ readArchived = (dir = SIGNALS_ARCHIVED) => readFolder(dir);
53101
+ readAllDismissed = (dir = SIGNALS_DISMISSED) => readFolder(dir, true);
52842
53102
  }
52843
53103
  });
52844
53104
 
@@ -55471,7 +55731,7 @@ function cmdValidate(id2) {
55471
55731
  const reason = errors.length ? formatContractErrors(errors) : void 0;
55472
55732
  const session = insideRun();
55473
55733
  if (session) patch(session, (run3) => {
55474
- run3.validationFailure = reason ? { code: "validation_failed", level: 1, reason } : void 0;
55734
+ run3.validationFailure = reason ? { code: "validation_failed", level: 1, source: "validation", reason } : void 0;
55475
55735
  });
55476
55736
  if (reason) die(reason, { kind: "spec-contract", errors });
55477
55737
  say(`Spec format valid (${cards.length} card${cards.length === 1 ? "" : "s"}).`);
@@ -61501,7 +61761,7 @@ var init_reply_log = __esm({
61501
61761
  });
61502
61762
 
61503
61763
  // ../cli/src/commands/task-chat.ts
61504
- import { setTimeout as delay } from "node:timers/promises";
61764
+ import { setTimeout as delay2 } from "node:timers/promises";
61505
61765
  function validateChatOptions(message, opts) {
61506
61766
  if (opts.limit !== void 0 && opts.all || message.length && (opts.limit !== void 0 || opts.all || opts.follow || opts.stop) || opts.stop && (opts.limit !== void 0 || opts.all || opts.follow)) {
61507
61767
  throw new BoardError("Use a message, history options [--limit <n> | --all] [--follow], or --stop separately.", { kind: "bad-args" });
@@ -61637,7 +61897,7 @@ async function taskChatFollow(id2, opts) {
61637
61897
  if (!active2(reply)) {
61638
61898
  break;
61639
61899
  }
61640
- await delay(1e3, void 0, { signal: controller.signal });
61900
+ await delay2(1e3, void 0, { signal: controller.signal });
61641
61901
  }
61642
61902
  } else {
61643
61903
  body = first.chat.messages.at(-1)?.role === "agent" ? first.chat.messages.at(-1).body : null;
@@ -61735,7 +61995,7 @@ var init_describe_project = __esm({
61735
61995
  var discuss_goal_default;
61736
61996
  var init_discuss_goal = __esm({
61737
61997
  "../cli/src/guide/discuss-goal.md"() {
61738
- discuss_goal_default = "# Discuss a goal\n\nExplain feasible options and key tradeoffs, then save the result the user can choose to start.\n\n- **Investigations**: finish checks and diagnosis here; save a change only when findings establish it. Report unverified work plainly.\n- **Goals**: save independent deliverables separately with a title, outcome (at most 150 words), and verifiable `## Done when` criteria. Update existing goals rather than duplicate them.\n- **Studio**: choose the fitting installed Studio, preferring the user's choice; read its Additional Notes with `akb studio rule <studio>` and honor their scope. Its Preview IDs name outputs, not agents.\n- **Review**: before saving a Goal, choose the human review points and save them with the Goal using `--review-file <json>` (`{id,title,after?,previews?}`). Use stable IDs and `after` for dependencies. Require approval only where downstream work needs it.\n- **Review state**: save `[]` when no extra review is needed and `null` only while a decision is missing. Keep the saved arrangement when editing other details.\n- **Decisions**: explain the proposed outcome and review arrangement before saving. Ask only for choices the user must make, with a recommendation.\n- **Start**: the user starts each Goal from the page; starting accepts its arrangement, never skips its review gates. Changing the arrangement after starting requires plan confirmation.\n- **Communication**: the remote user sees tasks and previews. Use plain words and button labels, omitting internal paths, commands and tools.\n";
61998
+ discuss_goal_default = "# Discuss a goal\n\nExplain feasible options and key tradeoffs, then save the result the user can choose to start.\n\n- **Investigations**: finish checks and diagnosis here; save a change only when findings establish it. Report unverified work plainly.\n- **Goals**: save independent deliverables separately with a title, outcome (at most 150 words), and verifiable `## Done when` criteria. Update existing goals rather than duplicate them.\n- **Studio**: choose the fitting installed Studio, preferring the user's choice; read its Additional Notes with `akb studio rule <studio>` and honor their scope. Its Preview IDs name outputs, not agents.\n- **Review**: before saving a Goal, choose the human review points and save them with the Goal using `--review-file <json>` (`{id,after?,previews?}`). Use the Studio\u2019s Preview IDs, stable node IDs and `after` for dependencies. Require approval only where downstream work needs it.\n- **Review state**: save `[]` when no extra review is needed and `null` only while a decision is missing. Keep the saved arrangement when editing other details.\n- **Decisions**: explain the proposed outcome and review arrangement before saving. Ask only for choices the user must make, with a recommendation.\n- **Start**: the user starts each Goal from the page; starting accepts its arrangement, never skips its review gates. Changing the arrangement after starting requires plan confirmation.\n- **Communication**: the remote user sees tasks and previews. Use plain words and button labels, omitting internal paths, commands and tools.\n";
61739
61999
  }
61740
62000
  });
61741
62001
 
@@ -62587,7 +62847,8 @@ var init_memory_review = __esm({
62587
62847
  import fs77 from "node:fs";
62588
62848
  import path78 from "node:path";
62589
62849
  function rejectionsToReview() {
62590
- const dir = path78.join(ARCHIVE, REJECTIONS_TO_REVIEW);
62850
+ const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
62851
+ const dir = path78.join(scratch ? path78.join(scratch, ".archive") : ARCHIVE, REJECTIONS_TO_REVIEW);
62591
62852
  if (!fs77.existsSync(dir)) return [];
62592
62853
  const found2 = [];
62593
62854
  for (const file2 of walkMd(dir)) {
@@ -62604,7 +62865,7 @@ function rejectionsToReview() {
62604
62865
  return found2.sort((a, b) => a.rejectedAt.localeCompare(b.rejectedAt) || a.id - b.id);
62605
62866
  }
62606
62867
  function dismissalsToReview() {
62607
- return readAllDismissed().filter((s) => s.dismissedBy === "user" && s.dismissedReason.trim()).sort((a, b) => a.dismissedAt.localeCompare(b.dismissedAt)).map((s) => ({
62868
+ return reviewDismissed().filter((s) => s.dismissedBy === "user" && s.dismissedReason.trim()).sort((a, b) => a.dismissedAt.localeCompare(b.dismissedAt)).map((s) => ({
62608
62869
  sourceId: s.sourceId,
62609
62870
  title: s.title,
62610
62871
  file: s.relPath,
@@ -62630,11 +62891,12 @@ function withdrawnSources() {
62630
62891
  }
62631
62892
  }))];
62632
62893
  if (cited.length === 0) return [];
62633
- const dismissed = new Set(readAllDismissed().map((s) => s.sourceId));
62634
- const restored = new Set([...readInbox(), ...readArchived()].map((s) => s.sourceId));
62894
+ const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
62895
+ const dismissed = new Set(reviewDismissed().map((s) => s.sourceId));
62896
+ const restored = new Set([...readInbox(), ...readArchived(scratch ? path78.join(scratch, "triage", "archived") : void 0)].map((s) => s.sourceId));
62635
62897
  return cited.filter((id2) => restored.has(id2) && !dismissed.has(id2));
62636
62898
  }
62637
- var SOURCES;
62899
+ var reviewDismissed, SOURCES;
62638
62900
  var init_dismissal_review = __esm({
62639
62901
  "../cli/src/lib/agent/dismissal-review.ts"() {
62640
62902
  "use strict";
@@ -62644,6 +62906,10 @@ var init_dismissal_review = __esm({
62644
62906
  init_paths();
62645
62907
  init_inbox();
62646
62908
  init_archive();
62909
+ reviewDismissed = () => {
62910
+ const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
62911
+ return readAllDismissed(scratch ? path78.join(scratch, "triage", "dismissed") : void 0);
62912
+ };
62647
62913
  SOURCES = /\(([^()]+)\)\s*$/;
62648
62914
  }
62649
62915
  });
@@ -63214,18 +63480,15 @@ function refinementStep(card) {
63214
63480
  function refinementRequest(req) {
63215
63481
  const card = req.id === void 0 ? null : currentCard(req.id);
63216
63482
  if (!card) return { error: `task #${req.id} does not exist` };
63217
- const context = process.env.AI4KANBAN_TASK_REVIEW;
63218
- const review = context ? JSON.parse(context) : void 0;
63219
- const assigned = process.env.AI4KANBAN_REVIEW_STAGES ? JSON.parse(process.env.AI4KANBAN_REVIEW_STAGES) : void 0;
63220
- const authorized = review && !review.pending_plan && (review.plan === null || review.stages.some((s) => ["available", "running"].includes(s.status) && (!assigned || assigned.includes(s.id))));
63221
- const step = review ? authorized && !card.questions.some((q) => q.options?.length) ? "clarify" : "done" : refinementStep(card);
63222
- if (step === "done") {
63483
+ const context = taskReviewContext();
63484
+ const canStart = context ? reviewAllows(reviewAuthorization(context.review, context.assigned), "refine") && !card.questions.some((q) => q.options?.length) : refinementStep(card) === "clarify";
63485
+ if (!canStart) {
63223
63486
  const waiting = card.questions.length > 0 && canRefine({ ...card, questions: [] });
63224
63487
  return {
63225
63488
  error: waiting ? `#${card.id} is waiting for the user to answer its open questions, so there is nothing to refine yet \u2014 the board refines it on its own once they are answered.` : `a refine would not move #${card.id}`
63226
63489
  };
63227
63490
  }
63228
- return { action: step, id: card.id, title: card.title, notes: req.notes, refineRound: 1, ...req.carry ? { carry: req.carry } : {} };
63491
+ return { action: "clarify", id: card.id, title: card.title, notes: req.notes, refineRound: 1, ...req.carry ? { carry: req.carry } : {} };
63229
63492
  }
63230
63493
  async function startRefinement(req) {
63231
63494
  const next = refinementRequest(req);
@@ -63291,6 +63554,8 @@ var init_refine2 = __esm({
63291
63554
  "use strict";
63292
63555
  init_read();
63293
63556
  init_rules();
63557
+ init_review_plan();
63558
+ init_env();
63294
63559
  init_start();
63295
63560
  init_stage_end();
63296
63561
  init_stages();
@@ -63404,72 +63669,6 @@ var init_propose = __esm({
63404
63669
  }
63405
63670
  });
63406
63671
 
63407
- // ../cli/src/lib/agent/idle.ts
63408
- function createIdleWatchdog(expired, busy = () => false, milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now) {
63409
- const calls = /* @__PURE__ */ new Set();
63410
- const local = /* @__PURE__ */ new Set();
63411
- const seen = /* @__PURE__ */ new Map();
63412
- let last = now();
63413
- let working = false;
63414
- let closed2 = false;
63415
- const touch = () => {
63416
- if (!closed2) last = now();
63417
- };
63418
- const check2 = () => {
63419
- if (closed2) return;
63420
- const active3 = calls.size > 0 || busy();
63421
- if (active3 || working) last = now();
63422
- working = active3;
63423
- if (!active3 && now() - last >= milliseconds) {
63424
- close();
63425
- expired();
63426
- }
63427
- };
63428
- const timer = setInterval(check2, Math.min(1e3, milliseconds));
63429
- timer.unref?.();
63430
- const close = () => {
63431
- closed2 = true;
63432
- clearInterval(timer);
63433
- calls.clear();
63434
- local.clear();
63435
- seen.clear();
63436
- };
63437
- return {
63438
- touch,
63439
- check: check2,
63440
- close,
63441
- event(e) {
63442
- if (closed2 || e.kind === "log" || e.kind === "context") return;
63443
- if (e.kind === "phase" && !e.data.contentAt) return;
63444
- const key = e.kind === "tool_call" || e.kind === "tool_call_update" ? `${e.kind}:${e.data.toolCallId}` : e.kind;
63445
- const value = JSON.stringify(e.data);
63446
- if (seen.get(key) === value) return;
63447
- seen.set(key, value);
63448
- if (e.kind === "tool_call" && (e.data.kind === "execute" || e.data.subagent)) local.add(e.data.toolCallId);
63449
- if (e.kind === "tool_call" || e.kind === "tool_call_update") {
63450
- const { toolCallId, status } = e.data;
63451
- if (local.has(toolCallId) && ["in_progress", "running"].includes(status)) calls.add(toolCallId);
63452
- if (["completed", "failed"].includes(status)) {
63453
- calls.delete(toolCallId);
63454
- local.delete(toolCallId);
63455
- }
63456
- }
63457
- touch();
63458
- check2();
63459
- }
63460
- };
63461
- }
63462
- var IDLE_MS, IDLE_TIMEOUT, IDLE_ERROR, IDLE_FAILURE;
63463
- var init_idle = __esm({
63464
- "../cli/src/lib/agent/idle.ts"() {
63465
- "use strict";
63466
- IDLE_MS = 5 * 6e4;
63467
- IDLE_TIMEOUT = { milliseconds: IDLE_MS };
63468
- IDLE_ERROR = "No response for 5 minutes (idle timeout).";
63469
- IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
63470
- }
63471
- });
63472
-
63473
63672
  // ../cli/src/lib/agent/watch.ts
63474
63673
  var watch_exports = {};
63475
63674
  __export(watch_exports, {
@@ -63477,7 +63676,7 @@ __export(watch_exports, {
63477
63676
  });
63478
63677
  import { spawn as spawn3 } from "node:child_process";
63479
63678
  import fs79 from "node:fs";
63480
- async function watchRun(sessionId, resume = startResume) {
63679
+ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffMs) {
63481
63680
  const spec = readSpec(sessionId);
63482
63681
  const run3 = peekRun(sessionId);
63483
63682
  if (!run3 || !spec) {
@@ -63546,8 +63745,9 @@ async function watchRun(sessionId, resume = startResume) {
63546
63745
  `);
63547
63746
  const basePrompt = record2.resumedFrom ? spec.prompt || resumePrompt(record2.deliveryId, record2.action) : spec.prompt;
63548
63747
  const recoveryPrompt = record2.harness === "antigravity" && record2.resumedFrom ? "First verify existing progress and operation results. Preserve user decisions and completed work; do not repeat completed operations. Check actual state before continuing any operation whose result is uncertain." : "";
63549
- const boundary = process.env.AI4KANBAN_TASK_REVIEW ? reviewBoundary(JSON.parse(process.env.AI4KANBAN_TASK_REVIEW), process.env.AI4KANBAN_REVIEW_STAGES ? JSON.parse(process.env.AI4KANBAN_REVIEW_STAGES) : void 0) : "";
63550
- const prompt = [record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, recoveryPrompt, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
63748
+ const reviewContext = taskReviewContext();
63749
+ const boundary = reviewContext ? reviewBoundary(reviewContext.review, reviewContext.assigned) : "";
63750
+ const prompt = [process.env.AI4KANBAN_SYNC_DIAGNOSTIC ? syncRepairPrompt(process.env.AI4KANBAN_SYNC_DIAGNOSTIC) : "", record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, recoveryPrompt, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
63551
63751
  const before = markBoard();
63552
63752
  const takes = active3.images;
63553
63753
  active3.renderer?.setRequiredImages?.(record2.pictures ?? []);
@@ -63715,6 +63915,7 @@ async function watchRun(sessionId, resume = startResume) {
63715
63915
  let done = false;
63716
63916
  let spoken;
63717
63917
  let silent = false;
63918
+ let uncertainAtIdle = false;
63718
63919
  let watchdog;
63719
63920
  let wakeUp;
63720
63921
  const sleep4 = (ms) => new Promise((wake) => {
@@ -63767,9 +63968,9 @@ async function watchRun(sessionId, resume = startResume) {
63767
63968
  let retrying = false;
63768
63969
  if (failure2 && !sub && !taskCompleted) {
63769
63970
  const attempt2 = held4.retry?.attempt ?? 1;
63770
- const decision = planRetry(failure2, attempt2);
63971
+ const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff);
63771
63972
  if ("pause" in decision) retryPause = decision.pause;
63772
- else if (blocker || pendingOperations.size || !structured || !resumeSessionId(held4) || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent) retryPause = "unsafe";
63973
+ else if (blocker || pendingOperations.size || !structured || !resumeSessionId(held4) || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, resumeSessionId(held4)))) retryPause = "unsafe";
63773
63974
  else {
63774
63975
  const mark = runMark(sessionId, agentStartedAt);
63775
63976
  const root2 = child.pid ? { pid: child.pid, since: agentStartedAt, identity: held4.agentIdentity } : void 0;
@@ -63794,7 +63995,7 @@ async function watchRun(sessionId, resume = startResume) {
63794
63995
  }
63795
63996
  asked ||= stoppedByUser();
63796
63997
  retrying &&= !asked;
63797
- const error62 = asked ? void 0 : joinNotes(said2 ?? failure2?.reason, retryPause ? pauseLine(retryPause) : void 0);
63998
+ const error62 = asked ? void 0 : joinNotes(said2 ?? failure2?.reason, retryPause && failure2?.source !== "invariant" ? pauseLine(retryPause) : void 0);
63798
63999
  const status = asked ? "stopped" : failed2 || code !== 0 ? "error" : "done";
63799
64000
  const reported = spoken ? spoken.costUsd : renderer?.costUsd?.();
63800
64001
  const totals = reportsSessionTotal(record2.harness);
@@ -63843,7 +64044,7 @@ ${result}
63843
64044
  errorWhy,
63844
64045
  endedAt
63845
64046
  });
63846
- resolve2(status === "done" ? 0 : 1);
64047
+ finishWatch(status === "done" ? 0 : 1);
63847
64048
  return;
63848
64049
  }
63849
64050
  await closeRun(sessionId, {
@@ -63874,7 +64075,7 @@ ${result}
63874
64075
  }
63875
64076
  if (status === "done") queueCompleted(before.keys());
63876
64077
  if (status === "done") await followUp(sessionId, record2.flowId, settled?.runs ?? []);
63877
- resolve2(status === "done" ? 0 : 1);
64078
+ finishWatch(status === "done" ? 0 : 1);
63878
64079
  };
63879
64080
  let ending = false;
63880
64081
  const endChild = () => {
@@ -63894,6 +64095,7 @@ ${result}
63894
64095
  const giveUp = (asked) => {
63895
64096
  endChild();
63896
64097
  after(STOP_GRACE_MS + STOP_CLOSE_MS, () => {
64098
+ if (done) return;
63897
64099
  after(STOP_FINISH_MS, () => process.exit(0));
63898
64100
  void finish(null, asked).finally(() => process.exit(0));
63899
64101
  });
@@ -63903,6 +64105,7 @@ ${result}
63903
64105
  giveUp(false);
63904
64106
  };
63905
64107
  const cancellation = new AbortController();
64108
+ const idle = new AbortController();
63906
64109
  let stopped2 = false;
63907
64110
  const stoppedByUser = () => stopped2 || peekRun(sessionId)?.stopping === true;
63908
64111
  const askToStop = () => {
@@ -63916,6 +64119,11 @@ ${result}
63916
64119
  if (done) return;
63917
64120
  giveUp(true);
63918
64121
  };
64122
+ const finishWatch = (code) => {
64123
+ process.off("SIGTERM", askToStop);
64124
+ process.off("SIGINT", askToStop);
64125
+ resolve2(code);
64126
+ };
63919
64127
  process.on("SIGTERM", askToStop);
63920
64128
  process.on("SIGINT", askToStop);
63921
64129
  watchdog = createIdleWatchdog(() => {
@@ -63924,7 +64132,15 @@ ${result}
63924
64132
  log.write(`
63925
64133
  [board] ${silenceSaid(silenceFor)}
63926
64134
  `);
63927
- giveUp(false);
64135
+ if (!client?.idleRecovery) {
64136
+ giveUp(false);
64137
+ return;
64138
+ }
64139
+ uncertainAtIdle = pendingOperations.size > 0;
64140
+ patch(sessionId, (run4) => {
64141
+ run4.cleanup = { status: "unconfirmed", execution: sessionId, kept: [] };
64142
+ });
64143
+ idle.abort();
63928
64144
  }, () => !!(client?.background?.() ?? renderer?.background?.()) || liveSubRuns(sessionId).length > 0);
63929
64145
  touch = watchdog.touch;
63930
64146
  observeActivity = watchdog.event;
@@ -63952,12 +64168,13 @@ ${result}
63952
64168
  gotContext,
63953
64169
  completed,
63954
64170
  activity: touch,
63955
- signal: cancellation.signal
64171
+ signal: cancellation.signal,
64172
+ idleSignal: idle.signal
63956
64173
  }).then((end2) => {
63957
64174
  if (done) return;
63958
64175
  spoken = end2;
63959
64176
  if (end2.cleanup) patch(sessionId, (r) => {
63960
- r.cleanup = end2.cleanup;
64177
+ r.cleanup = uncertainAtIdle || silent && pendingOperations.size ? { ...end2.cleanup, status: "unconfirmed" } : end2.cleanup;
63961
64178
  });
63962
64179
  endChild();
63963
64180
  void finish(end2.ok ? 0 : 1, peekRun(sessionId)?.stopping === true || stopped2);
@@ -64012,6 +64229,7 @@ var init_watch = __esm({
64012
64229
  "../cli/src/lib/agent/watch.ts"() {
64013
64230
  "use strict";
64014
64231
  init_review_plan();
64232
+ init_env();
64015
64233
  init_connection_process();
64016
64234
  init_deliveries();
64017
64235
  init_board_conflicts();
@@ -64031,6 +64249,7 @@ var init_watch = __esm({
64031
64249
  init_prompts();
64032
64250
  init_resolve();
64033
64251
  init_idle();
64252
+ init_codex_background_types();
64034
64253
  init_retry();
64035
64254
  init_failures();
64036
64255
  init_execution();
@@ -64498,11 +64717,21 @@ function deliveryOutcome(deliveryId) {
64498
64717
  id: deliveryId,
64499
64718
  status: delivery.status,
64500
64719
  line,
64720
+ ...delivery.status === "cancelled" ? {
64721
+ ending: { kind: delivery.steps.some((s) => s.step === "discarded") ? "discarded" : "stopped" }
64722
+ } : {},
64501
64723
  ...commit ? { commit, ...delivery.targetBranch ? { branch: delivery.targetBranch } : {} } : {}
64502
64724
  };
64503
64725
  }
64504
64726
  const state = deliveryState(delivery, delivery.cardId === null ? 0 : openQuestions(delivery.cardId));
64505
- return { id: deliveryId, status: delivery.status, stage: state.stage, line: state.line };
64727
+ const reason = delivery.review?.stopped?.why;
64728
+ return {
64729
+ id: deliveryId,
64730
+ status: delivery.status,
64731
+ stage: state.stage,
64732
+ line: state.line,
64733
+ ...reason ? { ending: { kind: "blocked", reason } } : {}
64734
+ };
64506
64735
  }
64507
64736
  function runLine(r, program2 = "akb", indent2 = "") {
64508
64737
  const sub = r.action === "sub";