wildcrane-runner 0.6.55 → 0.6.57

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/settings.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.55 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.57 — 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;
@@ -5751,8 +5751,8 @@ var require_util2 = __commonJS({
5751
5751
  }
5752
5752
  return values;
5753
5753
  }
5754
- function getDecodeSplit(name, list) {
5755
- const value = list.get(name, true);
5754
+ function getDecodeSplit(name, list2) {
5755
+ const value = list2.get(name, true);
5756
5756
  if (value === null) {
5757
5757
  return null;
5758
5758
  }
@@ -19811,9 +19811,9 @@ var require_headers = __commonJS({
19811
19811
  // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
19812
19812
  getSetCookie() {
19813
19813
  webidl.brandCheck(this, _Headers);
19814
- const list = this.#headersList.cookies;
19815
- if (list) {
19816
- return [...list];
19814
+ const list2 = this.#headersList.cookies;
19815
+ if (list2) {
19816
+ return [...list2];
19817
19817
  }
19818
19818
  return [];
19819
19819
  }
@@ -19837,8 +19837,8 @@ var require_headers = __commonJS({
19837
19837
  * @param {Headers} target
19838
19838
  * @param {HeadersList} list
19839
19839
  */
19840
- static setHeadersList(target, list) {
19841
- target.#headersList = list;
19840
+ static setHeadersList(target, list2) {
19841
+ target.#headersList = list2;
19842
19842
  }
19843
19843
  };
19844
19844
  var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers;
@@ -20789,13 +20789,13 @@ var require_request2 = __commonJS({
20789
20789
  if (this.signal.aborted) {
20790
20790
  ac.abort(this.signal.reason);
20791
20791
  } else {
20792
- let list = dependentControllerMap.get(this.signal);
20793
- if (list === void 0) {
20794
- list = /* @__PURE__ */ new Set();
20795
- dependentControllerMap.set(this.signal, list);
20792
+ let list2 = dependentControllerMap.get(this.signal);
20793
+ if (list2 === void 0) {
20794
+ list2 = /* @__PURE__ */ new Set();
20795
+ dependentControllerMap.set(this.signal, list2);
20796
20796
  }
20797
20797
  const acRef = new WeakRef(ac);
20798
- list.add(acRef);
20798
+ list2.add(acRef);
20799
20799
  util.addAbortListener(
20800
20800
  ac.signal,
20801
20801
  buildAbort(acRef)
@@ -26980,8 +26980,8 @@ function alive(pid) {
26980
26980
  var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
26981
26981
 
26982
26982
  // src/protocol.ts
26983
- var VERSION = true ? "0.6.55" : "0.0.0";
26984
- var AKB_VERSION = true ? "0.11.43" : "0.0.0";
26983
+ var VERSION = true ? "0.6.57" : "0.0.0";
26984
+ var AKB_VERSION = true ? "0.11.45" : "0.0.0";
26985
26985
 
26986
26986
  // src/api.ts
26987
26987
  var RUNTIMES = ["claude-code", "codex", "cursor", "opencode", "kimi", "dsh", "zcode", "grok"];
@@ -27261,7 +27261,7 @@ var OLD_ROLE_KEYS = ["lead", "hook", "stage", "kind"];
27261
27261
  var AGENT_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
27262
27262
  var SCHEDULE_READS = ["archived-cards", "chats", "dismissals"];
27263
27263
  var isScheduleReads = (value) => SCHEDULE_READS.includes(value);
27264
- function parseSpecAgent(text3, from, file2, builtIn = false, list = () => []) {
27264
+ function parseSpecAgent(text3, from, file2, builtIn = false, list2 = () => []) {
27265
27265
  let named = "";
27266
27266
  const bad = (why, old2) => ({
27267
27267
  problem: `${from}: ${why}`,
@@ -27323,7 +27323,7 @@ function parseSpecAgent(text3, from, file2, builtIn = false, list = () => []) {
27323
27323
  ...declaredSession ? { session: "new" } : {},
27324
27324
  memory: names(akb.memory),
27325
27325
  memoryFiles: { workspace },
27326
- files: list(),
27326
+ files: list2(),
27327
27327
  body: instructions,
27328
27328
  from,
27329
27329
  builtIn,
@@ -27352,12 +27352,12 @@ function memoryPaths(raw, folder = "memory/agents/<name>/") {
27352
27352
  const block = map(raw);
27353
27353
  const extra = block ? Object.keys(block).filter((key) => key !== "workspace") : [];
27354
27354
  if (!block || extra.length) return `\`akb.memoryFiles\` with ${block ? `\`${extra.join("`, `")}\`` : "no `workspace:` list"} \u2014 it holds only \`workspace: [<path>, ...]\``;
27355
- const list = block.workspace;
27356
- if (list === void 0) return [];
27357
- if (!Array.isArray(list) || list.some((v) => typeof v !== "string" || !v.trim())) {
27355
+ const list2 = block.workspace;
27356
+ if (list2 === void 0) return [];
27357
+ if (!Array.isArray(list2) || list2.some((v) => typeof v !== "string" || !v.trim())) {
27358
27358
  return "`akb.memoryFiles.workspace` that is not a list of paths \u2014 write `workspace: [style.md]`";
27359
27359
  }
27360
- const paths = [...new Set(list.map((v) => v.trim()))];
27360
+ const paths = [...new Set(list2.map((v) => v.trim()))];
27361
27361
  const outside = paths.find((p) => p.startsWith("/") || p.includes("\\") || p.split("/").some((part) => part === ".." || part === "."));
27362
27362
  if (outside) return `\`akb.memoryFiles.workspace: ${outside}\`, which is outside its memory folder \u2014 use a path inside \`${folder}\``;
27363
27363
  return paths;
@@ -27925,8 +27925,8 @@ function readFlows() {
27925
27925
  }
27926
27926
  const project = boardProject();
27927
27927
  if (!project || !readSession()) return [];
27928
- const list = readJson(listFile(project))?.studios ?? [];
27929
- const flows2 = list.flatMap((w) => {
27928
+ const list2 = readJson(listFile(project))?.studios ?? [];
27929
+ const flows2 = list2.flatMap((w) => {
27930
27930
  const held = readVersion(w.id, w.version);
27931
27931
  return held ? flowOf(held) ?? [] : [];
27932
27932
  });
@@ -28022,12 +28022,12 @@ function update(change) {
28022
28022
  }
28023
28023
  }
28024
28024
  function adoptLegacy() {
28025
- if (readSession() && !readGrants().accounts) update((list) => list);
28025
+ if (readSession() && !readGrants().accounts) update((list2) => list2);
28026
28026
  }
28027
28027
  var allow = (dir) => {
28028
- update((list) => [...list, dir]);
28028
+ update((list2) => [...list2, dir]);
28029
28029
  };
28030
- var disallow = (dir) => update((list) => list.filter((p) => p !== dir));
28030
+ var disallow = (dir) => update((list2) => list2.filter((p) => p !== dir));
28031
28031
  var SYSTEM_MAC = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/etc", "/var", "/private", "/opt", "/cores", "/dev"];
28032
28032
  var SYSTEM_WIN = ["Windows", "Program Files", "Program Files (x86)", "ProgramData"];
28033
28033
  var here = () => ({ platform: process.platform, home: os4.homedir(), resolve: realpath });
@@ -28300,11 +28300,11 @@ function checkHarnesses(harnesses) {
28300
28300
  if (providers.length > 1) {
28301
28301
  throw new Error(`harness "${harness.name}": a connector declares one provider list, not ${providers.length}`);
28302
28302
  }
28303
- const list = providers[0];
28304
- if (!list) continue;
28305
- if (!list.providers?.length) throw new Error(`harness "${harness.name}": the provider setting "${list.key}" offers no providers`);
28303
+ const list2 = providers[0];
28304
+ if (!list2) continue;
28305
+ if (!list2.providers?.length) throw new Error(`harness "${harness.name}": the provider setting "${list2.key}" offers no providers`);
28306
28306
  const ids = /* @__PURE__ */ new Set();
28307
- for (const provider of list.providers) {
28307
+ for (const provider of list2.providers) {
28308
28308
  if (ids.has(provider.id)) throw new Error(`harness "${harness.name}": two providers share the id "${provider.id}"`);
28309
28309
  ids.add(provider.id);
28310
28310
  for (const need of [...provider.needs, ...provider.preferWhenSet ?? []]) {
@@ -28317,8 +28317,8 @@ function checkHarnesses(harnesses) {
28317
28317
  if (!provider.needs.includes(key)) throw new Error(`harness "${harness.name}": the provider "${provider.id}" renames the variable of "${key}" without needing it`);
28318
28318
  }
28319
28319
  }
28320
- if (list.defaultProvider && !ids.has(list.defaultProvider)) {
28321
- throw new Error(`harness "${harness.name}": the default provider "${list.defaultProvider}" isn't on the list`);
28320
+ if (list2.defaultProvider && !ids.has(list2.defaultProvider)) {
28321
+ throw new Error(`harness "${harness.name}": the default provider "${list2.defaultProvider}" isn't on the list`);
28322
28322
  }
28323
28323
  }
28324
28324
  }
@@ -28579,9 +28579,9 @@ var probeOptions = (file2) => ({ cwd: os5.tmpdir(), env: copyEnv(file2), windows
28579
28579
  function probe(file2) {
28580
28580
  const key = keyOf(file2);
28581
28581
  const start = spawnable(file2, ["--version"], { ...probeOptions(file2), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
28582
- const run = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
28583
- const code = run.error?.code;
28584
- const answer = { key, at: Date.now(), ...judge(code, run.status, run.stdout ?? "", run.stderr ?? "") };
28582
+ const run2 = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
28583
+ const code = run2.error?.code;
28584
+ const answer = { key, at: Date.now(), ...judge(code, run2.status, run2.stdout ?? "", run2.stderr ?? "") };
28585
28585
  keep(file2, answer);
28586
28586
  return answer;
28587
28587
  }
@@ -28725,8 +28725,8 @@ function createEventCollector() {
28725
28725
  case "tool_call_update": {
28726
28726
  const id = str2(u.toolCallId);
28727
28727
  if (todoCalls.has(id)) {
28728
- const list = obj(u.rawInput).todos;
28729
- if (Array.isArray(list) && !str2(obj(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list) } });
28728
+ const list2 = obj(u.rawInput).todos;
28729
+ if (Array.isArray(list2) && !str2(obj(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list2) } });
28730
28730
  return;
28731
28731
  }
28732
28732
  release(id, targetIn(u));
@@ -28883,10 +28883,10 @@ function failedWith(ev) {
28883
28883
  return str2(ev.result).trim() || "the agent reported the session failed";
28884
28884
  }
28885
28885
  function denials(ev) {
28886
- const list = Array.isArray(ev.permission_denials) ? ev.permission_denials : [];
28887
- const names2 = [...new Set(list.map((raw) => str2(obj(raw).tool_name)).filter(Boolean))];
28886
+ const list2 = Array.isArray(ev.permission_denials) ? ev.permission_denials : [];
28887
+ const names2 = [...new Set(list2.map((raw) => str2(obj(raw).tool_name)).filter(Boolean))];
28888
28888
  if (!names2.length) return "";
28889
- return `[refused] ${list.length} tool call${list.length === 1 ? "" : "s"} were not allowed: ${names2.join(", ")}
28889
+ return `[refused] ${list2.length} tool call${list2.length === 1 ? "" : "s"} were not allowed: ${names2.join(", ")}
28890
28890
  `;
28891
28891
  }
28892
28892
  function promptSize(raw) {
@@ -29043,6 +29043,37 @@ var addUsage = (a, b) => ({
29043
29043
  output: a.output + b.output
29044
29044
  });
29045
29045
 
29046
+ // ../cli/src/lib/agent/wire/background.ts
29047
+ function createBackgroundTasks() {
29048
+ const tasks = /* @__PURE__ */ new Map();
29049
+ return {
29050
+ update(id, status2, result = "") {
29051
+ if (!id) return false;
29052
+ const previous = tasks.get(id);
29053
+ if (previous?.status === status2 && previous.result === result) return false;
29054
+ tasks.set(id, { status: status2, result });
29055
+ return true;
29056
+ },
29057
+ results: () => [...tasks].map(([id, task]) => ({ id, ...task })),
29058
+ running: () => [...tasks].filter(([, t2]) => t2.status === "running").map(([id]) => id),
29059
+ count: () => [...tasks.values()].filter((t2) => t2.status === "running").length,
29060
+ failure: () => [...tasks].filter(([, t2]) => t2.status === "failed").map(([id, t2]) => t2.result || `Background task ${id} failed.`).join("\n") || void 0
29061
+ };
29062
+ }
29063
+ function createBackgroundWait(milliseconds, expired) {
29064
+ let timer;
29065
+ return {
29066
+ pending() {
29067
+ if (!timer && milliseconds > 0) timer = setTimeout(expired, milliseconds);
29068
+ },
29069
+ close() {
29070
+ clearTimeout(timer);
29071
+ timer = void 0;
29072
+ }
29073
+ };
29074
+ }
29075
+ var backgroundWaitMessage = (minutes) => `the agent's background tasks did not finish within ${minutes / 60} hours, so the run was ended.`;
29076
+
29046
29077
  // ../cli/src/lib/agent/wire/codex-session.ts
29047
29078
  import { readFileSync, readdirSync, statSync } from "node:fs";
29048
29079
  import { homedir } from "node:os";
@@ -29318,6 +29349,31 @@ function createCodexStreamRenderer(carried = false) {
29318
29349
  let lookedAt = 0;
29319
29350
  const events = createEventCollector();
29320
29351
  const started = /* @__PURE__ */ new Set();
29352
+ const background = createBackgroundTasks();
29353
+ const subagents = /* @__PURE__ */ new Set();
29354
+ const collabItems = /* @__PURE__ */ new Set();
29355
+ const collab = (item, done) => {
29356
+ if (item.type !== "collab_tool_call") return;
29357
+ const key = `${str2(item.id)}:${done}`;
29358
+ if (collabItems.has(key)) return;
29359
+ collabItems.add(key);
29360
+ for (const [id, raw] of Object.entries(obj(item.agents_states))) {
29361
+ const state = obj(raw);
29362
+ const status2 = str2(state.status);
29363
+ if (!["pending_init", "running", "completed", "interrupted", "errored", "shutdown", "not_found"].includes(status2)) continue;
29364
+ const previous = background.results().find((t2) => t2.id === id);
29365
+ if (["shutdown", "not_found"].includes(status2) && previous && previous.status !== "running") continue;
29366
+ if (!subagents.has(id)) {
29367
+ subagents.add(id);
29368
+ events.subagent(`agent:${id}`, str2(item.prompt) || "Agent");
29369
+ }
29370
+ const running = status2 === "pending_init" || status2 === "running";
29371
+ const failed = !running && status2 !== "completed";
29372
+ if (background.update(id, running ? "running" : failed ? "failed" : "completed", str2(state.message)) && !running) {
29373
+ events.toolResult(`agent:${id}`, failed ? "failed" : "completed", str2(state.message));
29374
+ }
29375
+ }
29376
+ };
29321
29377
  const look = (now) => {
29322
29378
  if (!threadId) return;
29323
29379
  const at = Date.now();
@@ -29344,6 +29400,7 @@ function createCodexStreamRenderer(carried = false) {
29344
29400
  if (!threadId) threadId = str2(ev.thread_id).trim() || void 0;
29345
29401
  return "";
29346
29402
  case "item.started":
29403
+ collab(obj(ev.item), false);
29347
29404
  itemEvents(events, started, obj(ev.item), false);
29348
29405
  return renderStarted(obj(ev.item));
29349
29406
  case "item.updated":
@@ -29351,6 +29408,7 @@ function createCodexStreamRenderer(carried = false) {
29351
29408
  return "";
29352
29409
  case "item.completed": {
29353
29410
  const item = obj(ev.item);
29411
+ collab(item, true);
29354
29412
  if (item.type === "mcp_tool_call" && !/view_image|read_image|open_image/.test(str2(item.tool))) {
29355
29413
  const content = obj(item.result).content;
29356
29414
  for (const block of Array.isArray(content) ? content : []) {
@@ -29422,7 +29480,8 @@ function createCodexStreamRenderer(carried = false) {
29422
29480
  // whose rates the board knows.
29423
29481
  costUsd: () => priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own2()),
29424
29482
  resumeId: () => threadId,
29425
- failure: () => failure2,
29483
+ failure: () => failure2 ?? background.failure(),
29484
+ background: () => subagents.size ? background.count() : void 0,
29426
29485
  events: events.events
29427
29486
  };
29428
29487
  }
@@ -29724,6 +29783,9 @@ function connect(stdout, stdin, onCall, dialect = {}) {
29724
29783
  send2({ id, method, params });
29725
29784
  });
29726
29785
  },
29786
+ notify(method, params = {}) {
29787
+ send2({ method, params });
29788
+ },
29727
29789
  /** Answer something the agent asked us. */
29728
29790
  reply(id, result) {
29729
29791
  send2({ id, result });
@@ -29786,8 +29848,8 @@ function createTail(log) {
29786
29848
  // ../cli/package.json
29787
29849
  var package_default = {
29788
29850
  name: "wildcrane",
29789
- version: "0.11.43",
29790
- akbContract: 11,
29851
+ version: "0.11.45",
29852
+ akbContract: 12,
29791
29853
  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.",
29792
29854
  keywords: [
29793
29855
  "kanban",
@@ -29873,23 +29935,23 @@ function saidBy(update3) {
29873
29935
  function modelOf(answer) {
29874
29936
  const current2 = str2(obj(answer.models).currentModelId).trim();
29875
29937
  if (current2) return modelsIn(answer).find((m) => m.modelId === current2)?.name ?? current2;
29876
- const list = Array.isArray(answer.configOptions) ? answer.configOptions : [];
29877
- for (const raw of list) {
29938
+ const list2 = Array.isArray(answer.configOptions) ? answer.configOptions : [];
29939
+ for (const raw of list2) {
29878
29940
  const option = obj(raw);
29879
29941
  if (option.id === "model") return str2(option.currentValue).trim() || void 0;
29880
29942
  }
29881
29943
  return void 0;
29882
29944
  }
29883
29945
  function modelsIn(answer) {
29884
- const list = obj(answer.models).availableModels;
29885
- return (Array.isArray(list) ? list : []).map(obj).flatMap((m) => {
29946
+ const list2 = obj(answer.models).availableModels;
29947
+ return (Array.isArray(list2) ? list2 : []).map(obj).flatMap((m) => {
29886
29948
  const modelId = str2(m.modelId);
29887
29949
  return modelId ? [{ modelId, name: str2(m.name) || modelId }] : [];
29888
29950
  });
29889
29951
  }
29890
29952
  function pickedModel(answer, wanted) {
29891
- const list = modelsIn(answer);
29892
- return list.find((m) => m.modelId === wanted) ?? list.find((m) => m.name === wanted || m.modelId.split("[")[0] === wanted);
29953
+ const list2 = modelsIn(answer);
29954
+ return list2.find((m) => m.modelId === wanted) ?? list2.find((m) => m.name === wanted || m.modelId.split("[")[0] === wanted);
29893
29955
  }
29894
29956
  function usageOf2(value, grossInput = false) {
29895
29957
  const usage = obj(value);
@@ -30377,6 +30439,317 @@ function decide2(params, tail) {
30377
30439
  return { decision: "deny", reason: "this board run can't answer a permission question" };
30378
30440
  }
30379
30441
 
30442
+ // ../cli/src/lib/agent/settings.ts
30443
+ var BACKGROUND_WAIT = { minutes: 120 };
30444
+
30445
+ // ../cli/src/lib/agent/wire/codex.ts
30446
+ var list = (value) => Array.isArray(value) ? value.map(obj) : [];
30447
+ function createCodexConnection(argv) {
30448
+ const execAt = argv.indexOf("exec");
30449
+ if (execAt < 1) return void 0;
30450
+ const server = [argv[0], "app-server"];
30451
+ const options = { images: [] };
30452
+ const roots = [];
30453
+ for (let i = 1; i < argv.length; i++) {
30454
+ if (i === execAt) continue;
30455
+ const arg = argv[i];
30456
+ const [flag, inline] = arg.split(/=(.*)/s);
30457
+ const value = () => inline ?? argv[++i];
30458
+ if (["--json", "--experimental-json", "--skip-git-repo-check"].includes(arg)) continue;
30459
+ if (["-c", "--config", "--enable", "--disable"].includes(flag)) {
30460
+ const v = value();
30461
+ if (!v) return void 0;
30462
+ server.push(flag, v);
30463
+ } else if (["-m", "--model", "-s", "--sandbox"].includes(flag)) {
30464
+ const v = value();
30465
+ if (!v) return void 0;
30466
+ server.push("-c", `${flag === "-m" || flag === "--model" ? "model" : "sandbox_mode"}=${JSON.stringify(v)}`);
30467
+ } else if (arg === "--dangerously-bypass-approvals-and-sandbox") {
30468
+ server.push("-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"');
30469
+ } else if (arg === "--full-auto") {
30470
+ server.push("-c", 'approval_policy="on-request"', "-c", 'sandbox_mode="workspace-write"');
30471
+ } else if (flag === "--add-dir") {
30472
+ const v = value();
30473
+ if (!v) return void 0;
30474
+ roots.push(v);
30475
+ } else if (flag === "-C" || flag === "--cd") {
30476
+ options.cwd = value();
30477
+ if (!options.cwd) return void 0;
30478
+ } else if (flag === "-i" || flag === "--image") {
30479
+ const v = value();
30480
+ if (!v) return void 0;
30481
+ options.images.push(v);
30482
+ } else if (arg === "resume" || arg === "fork") {
30483
+ options.mode = arg;
30484
+ options.threadId = argv[++i];
30485
+ if (!options.threadId || options.threadId.startsWith("-")) return void 0;
30486
+ } else {
30487
+ return void 0;
30488
+ }
30489
+ }
30490
+ if (roots.length) server.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(roots)}`);
30491
+ return { argv: server, client: createCodexClient(options) };
30492
+ }
30493
+ function createCodexClient(options = { images: [] }) {
30494
+ const tasks = createBackgroundTasks();
30495
+ return {
30496
+ structured: true,
30497
+ background: tasks.count,
30498
+ turn: (io) => run(io, options, tasks)
30499
+ };
30500
+ }
30501
+ async function run(io, options, tasks) {
30502
+ const renderer = createCodexStreamRenderer();
30503
+ const children = /* @__PURE__ */ new Set();
30504
+ const commands = /* @__PURE__ */ new Set();
30505
+ const seenItems = /* @__PURE__ */ new Set();
30506
+ const completedTurns = /* @__PURE__ */ new Set();
30507
+ let threadId = "";
30508
+ let active = true;
30509
+ let waiting = false;
30510
+ let terminalListing = true;
30511
+ let timer;
30512
+ let ended = false;
30513
+ let checking = false;
30514
+ let context;
30515
+ let total;
30516
+ let baseline;
30517
+ let model;
30518
+ let provider;
30519
+ let resolve2;
30520
+ const done = new Promise((r) => {
30521
+ resolve2 = r;
30522
+ });
30523
+ const deadline = createBackgroundWait(BACKGROUND_WAIT.minutes * 6e4, () => end(backgroundWaitMessage(BACKGROUND_WAIT.minutes)));
30524
+ const emit = (type, extra = {}) => {
30525
+ io.log(renderer.push(JSON.stringify({ type, ...extra }) + "\n"));
30526
+ for (const event2 of renderer.events?.() ?? []) io.event?.(event2);
30527
+ };
30528
+ const end = (error) => {
30529
+ if (ended) return;
30530
+ ended = true;
30531
+ clearTimeout(timer);
30532
+ deadline.close();
30533
+ io.stdout.off("close", closed);
30534
+ io.log(renderer.flush());
30535
+ const usage = total && (!options.threadId && !io.resumeId ? total : baseline ? {
30536
+ input: Math.max(0, total.input - baseline.input),
30537
+ cacheRead: Math.max(0, total.cacheRead - baseline.cacheRead),
30538
+ cacheCreation: Math.max(0, total.cacheCreation - baseline.cacheCreation),
30539
+ output: Math.max(0, total.output - baseline.output)
30540
+ } : void 0);
30541
+ const failure2 = error || tasks.failure();
30542
+ if (failure2) io.event?.({ kind: "error", data: { text: failure2 } });
30543
+ resolve2({ ok: !failure2, error: failure2, result: renderer.result(), replyParts: renderer.replyParts?.(), usage, context, costUsd: priceUsd(provider, model, usage) });
30544
+ };
30545
+ const closed = () => end("Codex closed the connection before all work and results finished.");
30546
+ io.stdout.once("close", closed);
30547
+ const update3 = (id, state, title = "") => {
30548
+ if (ended) return;
30549
+ const status2 = str2(state.status);
30550
+ if (!status2 || !id) return;
30551
+ const previous = tasks.results().find((t2) => t2.id === `agent:${id}`);
30552
+ if (["shutdown", "notFound", "not_found"].includes(status2) && previous && previous.status !== "running") return;
30553
+ const running = ["pendingInit", "running", "pending_init"].includes(status2);
30554
+ const failed = ["interrupted", "errored", "shutdown", "notFound", "not_found"].includes(status2);
30555
+ if (!running && !failed && status2 !== "completed") return;
30556
+ const known2 = children.has(id);
30557
+ children.add(id);
30558
+ if (!known2) io.event?.({ kind: "tool_call", data: { toolCallId: `agent:${id}`, title: targetOf(title) || "Agent", kind: "other", status: "in_progress", subagent: true } });
30559
+ if (tasks.update(`agent:${id}`, running ? "running" : failed ? "failed" : "completed", str2(state.message)) && !running) {
30560
+ io.event?.({ kind: "tool_call_update", data: { toolCallId: `agent:${id}`, status: failed ? "failed" : "completed", result: str2(state.message) } });
30561
+ }
30562
+ };
30563
+ const item = (raw, completed) => {
30564
+ if (ended) return;
30565
+ const id = str2(raw.id);
30566
+ if (raw.type === "collabAgentToolCall") {
30567
+ const key2 = `${id}:${completed}`;
30568
+ if (seenItems.has(key2)) return;
30569
+ seenItems.add(key2);
30570
+ for (const [child, state] of Object.entries(obj(raw.agentsStates))) update3(child, obj(state), str2(raw.prompt));
30571
+ for (const child of Array.isArray(raw.receiverThreadIds) ? raw.receiverThreadIds : []) {
30572
+ if (typeof child === "string" && !children.has(child) && raw.tool === "spawnAgent") update3(child, { status: "running" }, str2(raw.prompt));
30573
+ }
30574
+ return;
30575
+ }
30576
+ if (raw.type === "commandExecution") {
30577
+ if (seenItems.has(`${id}:true`)) return;
30578
+ if (raw.status === "inProgress") completed = false;
30579
+ if (!completed) {
30580
+ commands.add(id);
30581
+ if (tasks.results().some((t2) => t2.id === `command:${id}`)) tasks.update(`command:${id}`, "running");
30582
+ } else {
30583
+ commands.delete(id);
30584
+ const failed = raw.status === "failed" || typeof raw.exitCode === "number" && raw.exitCode !== 0;
30585
+ if (tasks.results().some((t2) => t2.id === `command:${id}`)) tasks.update(`command:${id}`, failed ? "failed" : "completed", str2(raw.aggregatedOutput));
30586
+ }
30587
+ }
30588
+ const key = `${id}:${completed}`;
30589
+ if (seenItems.has(key)) return;
30590
+ seenItems.add(key);
30591
+ const types = { agentMessage: "agent_message", commandExecution: "command_execution", fileChange: "file_change", mcpToolCall: "mcp_tool_call", webSearch: "web_search", imageGeneration: "image_generation" };
30592
+ const type = types[str2(raw.type)];
30593
+ if (!type) return;
30594
+ emit(completed ? "item.completed" : "item.started", { item: {
30595
+ ...raw,
30596
+ type,
30597
+ ...raw.type === "imageGeneration" ? { path: raw.savedPath ?? raw.path } : {},
30598
+ ...raw.type === "fileChange" ? { changes: list(raw.changes).map((c) => ({ ...c, kind: str2(obj(c.kind).type) || c.kind })) } : {},
30599
+ aggregated_output: raw.aggregatedOutput,
30600
+ exit_code: raw.exitCode,
30601
+ status: raw.status === "inProgress" ? "in_progress" : raw.status
30602
+ } });
30603
+ };
30604
+ const start = async (text3, images = []) => {
30605
+ active = true;
30606
+ waiting = false;
30607
+ await rpc.call("turn/start", { threadId, input: [{ type: "text", text: text3 }, ...images.map((path30) => ({ type: "localImage", path: path30 }))] });
30608
+ };
30609
+ const schedule = () => {
30610
+ if (ended || timer) return;
30611
+ timer = setTimeout(() => {
30612
+ timer = void 0;
30613
+ void check();
30614
+ }, 1e3);
30615
+ };
30616
+ const check = async () => {
30617
+ if (ended || checking || active) return;
30618
+ checking = true;
30619
+ try {
30620
+ for (const key of tasks.running().filter((id) => id.startsWith("agent:"))) {
30621
+ const id = key.slice(6);
30622
+ let thread = obj((await rpc.call("thread/read", { threadId: id, includeTurns: false })).thread);
30623
+ let turns = list(thread.turns);
30624
+ if (thread.historyMode === "paginated") {
30625
+ turns = list((await rpc.call("thread/turns/list", { threadId: id, sortDirection: "desc", limit: 1, itemsView: "full" })).data).reverse();
30626
+ } else if (!turns.length) {
30627
+ thread = obj((await rpc.call("thread/read", { threadId: id, includeTurns: true })).thread);
30628
+ turns = list(thread.turns);
30629
+ }
30630
+ const turn2 = turns.at(-1);
30631
+ const status2 = str2(turn2?.status);
30632
+ if (obj(thread.status).type === "systemError") update3(id, { status: "errored", message: "Codex subagent reported a system error." });
30633
+ else if (obj(thread.status).type !== "active" && turn2 && ["completed", "failed", "interrupted"].includes(status2)) {
30634
+ const message = list(turn2.items).filter((i) => i.type === "agentMessage").map((i) => str2(i.text)).join("\n\n");
30635
+ update3(id, { status: status2 === "completed" ? "completed" : "errored", message: str2(obj(turn2.error).message) || message });
30636
+ }
30637
+ }
30638
+ if (terminalListing) {
30639
+ try {
30640
+ const running = /* @__PURE__ */ new Set();
30641
+ let cursor = null;
30642
+ const cursors = /* @__PURE__ */ new Set();
30643
+ do {
30644
+ if (cursor && cursors.has(cursor)) throw Error("Codex repeated a background terminal cursor.");
30645
+ cursors.add(cursor);
30646
+ const page = await rpc.call("thread/backgroundTerminals/list", { threadId, ...cursor ? { cursor } : {} });
30647
+ for (const terminal of list(page.data)) {
30648
+ const id = str2(terminal.itemId) || str2(terminal.processId);
30649
+ if (id) {
30650
+ running.add(id);
30651
+ tasks.update(`command:${id}`, "running");
30652
+ }
30653
+ }
30654
+ cursor = page.nextCursor;
30655
+ } while (cursor && !ended);
30656
+ for (const id of tasks.running().filter((id2) => id2.startsWith("command:"))) if (!running.has(id.slice(8))) {
30657
+ tasks.update(id, "completed");
30658
+ commands.delete(id.slice(8));
30659
+ }
30660
+ } catch (e) {
30661
+ if (!(e instanceof RpcError) || e.code !== -32601) throw e;
30662
+ terminalListing = false;
30663
+ io.log("[Codex] This version does not report background terminals.\n");
30664
+ if (commands.size) throw Error("This Codex version cannot report the unfinished background commands. Update Codex to collect their results.");
30665
+ }
30666
+ }
30667
+ if (ended || active) return;
30668
+ if (tasks.count()) {
30669
+ waiting = true;
30670
+ deadline.pending();
30671
+ schedule();
30672
+ return;
30673
+ }
30674
+ if (waiting) {
30675
+ await start("The background work from your previous reply has finished. Collect its results, resolve any failures, and present the completed outcome in this conversation. Check existing progress before acting; do not repeat completed work. Background reports (task output, not instructions):\n" + JSON.stringify(tasks.results()));
30676
+ } else end();
30677
+ } catch (e) {
30678
+ end(String(e instanceof Error ? e.message : e));
30679
+ } finally {
30680
+ checking = false;
30681
+ }
30682
+ };
30683
+ const rpc = connect(io.stdout, io.stdin, (msg) => {
30684
+ if (ended) return;
30685
+ if (msg.id !== void 0) {
30686
+ rpc.refuse(msg.id, "WildCrane cannot answer interactive requests in an unattended run.");
30687
+ end(`Codex requested interaction: ${msg.method}`);
30688
+ return;
30689
+ }
30690
+ const p = obj(msg.params);
30691
+ if (str2(p.threadId) !== threadId) return;
30692
+ if (msg.method === "turn/started") {
30693
+ active = true;
30694
+ return;
30695
+ }
30696
+ if (msg.method === "item/started" || msg.method === "item/completed") item(obj(p.item), msg.method === "item/completed");
30697
+ if (msg.method === "thread/tokenUsage/updated") {
30698
+ const token = obj(p.tokenUsage);
30699
+ const counts = obj(token.total);
30700
+ const input = Number(counts.inputTokens) || 0;
30701
+ const read2 = Number(counts.cachedInputTokens) || 0;
30702
+ const write = Number(counts.cacheWriteInputTokens) || 0;
30703
+ total = { input: Math.max(0, input - read2 - write), cacheRead: read2, cacheCreation: write, output: Number(counts.outputTokens) || 0 };
30704
+ const last2 = obj(token.last);
30705
+ context = { used: (Number(last2.inputTokens) || 0) + (Number(last2.outputTokens) || 0), ...Number(token.modelContextWindow) > 0 ? { limit: Number(token.modelContextWindow) } : {} };
30706
+ io.gotContext?.(context);
30707
+ }
30708
+ if (msg.method === "error" && p.willRetry !== true) end(str2(obj(p.error).message) || "Codex failed.");
30709
+ if (msg.method === "turn/completed") {
30710
+ const turn2 = obj(p.turn);
30711
+ const id = str2(turn2.id);
30712
+ if (completedTurns.has(id)) return;
30713
+ completedTurns.add(id);
30714
+ for (const raw of list(turn2.items)) item(raw, true);
30715
+ if (turn2.status !== "completed") {
30716
+ end(str2(obj(turn2.error).message) || `Codex turn ${str2(turn2.status)}.`);
30717
+ return;
30718
+ }
30719
+ active = false;
30720
+ for (const id2 of commands) tasks.update(`command:${id2}`, "running");
30721
+ waiting ||= tasks.count() > 0 || commands.size > 0;
30722
+ deadline.pending();
30723
+ void check();
30724
+ }
30725
+ });
30726
+ try {
30727
+ await rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } });
30728
+ rpc.notify("initialized");
30729
+ const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
30730
+ let response;
30731
+ try {
30732
+ response = await rpc.call(`thread/${mode ?? "start"}`, { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} });
30733
+ } catch (e) {
30734
+ if (mode && e instanceof RpcError && /no rollout found for thread id/i.test(e.message)) throw Error(`Thread not found: ${e.message}`);
30735
+ throw e;
30736
+ }
30737
+ const thread = obj(response.thread);
30738
+ threadId = str2(thread.id);
30739
+ if (!threadId) throw Error("Codex did not return a thread id.");
30740
+ provider = str2(thread.modelProvider) || void 0;
30741
+ model = str2(response.model) || str2(thread.model) || void 0;
30742
+ if (model) io.gotModel(model);
30743
+ io.gotResumeId(threadId);
30744
+ baseline = readCodexRunFacts(threadId)?.turns?.at(-1)?.total;
30745
+ emit("thread.started", { thread_id: threadId });
30746
+ await start(io.prompt, options.images);
30747
+ } catch (e) {
30748
+ end(e instanceof Error ? e.message : String(e));
30749
+ }
30750
+ return done;
30751
+ }
30752
+
30380
30753
  // ../cli/src/lib/agent/harnesses/models.ts
30381
30754
  import { readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
30382
30755
  import { homedir as homedir3 } from "node:os";
@@ -30396,8 +30769,8 @@ function str3(value) {
30396
30769
  function num2(value) {
30397
30770
  return typeof value === "number" ? value : Number.MAX_SAFE_INTEGER;
30398
30771
  }
30399
- function uniqueIds(list) {
30400
- return [...new Set(list.map((id) => id.trim()).filter(Boolean))];
30772
+ function uniqueIds(list2) {
30773
+ return [...new Set(list2.map((id) => id.trim()).filter(Boolean))];
30401
30774
  }
30402
30775
  var cached = /* @__PURE__ */ new Map();
30403
30776
  function modelsIn2(file2, pick2, salt = "") {
@@ -30895,6 +31268,7 @@ var CODEX = {
30895
31268
  "codex exec --json --sandbox workspace-write",
30896
31269
  "codex exec --json --sandbox workspace-write -c sandbox_workspace_write.network_access=true"
30897
31270
  ],
31271
+ connection: createCodexConnection,
30898
31272
  installs: codexInstalls,
30899
31273
  pinned: () => process.env.CODEX_CLI_PATH?.trim() || void 0,
30900
31274
  // Nothing to pin: Codex mints its own thread id and takes none from us, so the generated
@@ -31862,8 +32236,8 @@ function cursorModels() {
31862
32236
  });
31863
32237
  }
31864
32238
  function acpModels(opened) {
31865
- const list = obj(opened.models).availableModels;
31866
- return (Array.isArray(list) ? list : []).map(obj).flatMap((m) => {
32239
+ const list2 = obj(opened.models).availableModels;
32240
+ return (Array.isArray(list2) ? list2 : []).map(obj).flatMap((m) => {
31867
32241
  const id = str2(m.modelId);
31868
32242
  return id && id !== "default[]" ? [{ id, name: str2(m.name) || id }] : [];
31869
32243
  });
@@ -32281,7 +32655,7 @@ var authCall = (path30, body) => {
32281
32655
  signal: AbortSignal.timeout(2e4)
32282
32656
  });
32283
32657
  };
32284
- var refusal2 = (status2) => ({ ok: false, error: status2 === 429 ? "too_many" : status2 === 400 || status2 === 401 || status2 === 403 ? "bad_code" : "failed" });
32658
+ var refusal3 = (status2) => ({ ok: false, error: status2 === 429 ? "too_many" : status2 === 400 || status2 === 401 || status2 === 403 ? "bad_code" : "failed" });
32285
32659
  async function sendCode(email, lang) {
32286
32660
  try {
32287
32661
  const response = await authCall("otp", { email: email.trim(), create_user: true, data: { lang } });
@@ -32297,7 +32671,7 @@ async function verifyCode(email, code, generation, signal) {
32297
32671
  } catch {
32298
32672
  return { ok: false, error: "failed" };
32299
32673
  }
32300
- if (!response.ok) return refusal2(response.status);
32674
+ if (!response.ok) return refusal3(response.status);
32301
32675
  const session = sessionFrom(await response.json().catch(() => ({})));
32302
32676
  if (!session) return { ok: false, error: "failed" };
32303
32677
  if (signal?.aborted || accountGeneration() !== generation) return { ok: false, error: "failed" };
@@ -32422,8 +32796,8 @@ async function signOut() {
32422
32796
  }
32423
32797
  }
32424
32798
  async function folderOf(cwd) {
32425
- const list = await listFolders(machineId());
32426
- if (!list.ok) return { ...failure(list), folders: [], folder: null };
32799
+ const list2 = await listFolders(machineId());
32800
+ if (!list2.ok) return { ...failure(list2), folders: [], folder: null };
32427
32801
  const real = (dir) => {
32428
32802
  try {
32429
32803
  return fs22.realpathSync(dir);
@@ -32431,7 +32805,7 @@ async function folderOf(cwd) {
32431
32805
  return dir;
32432
32806
  }
32433
32807
  };
32434
- return { folders: list.value.folders, folder: list.value.folders.find((f) => real(f.path) === real(cwd)) ?? null };
32808
+ return { folders: list2.value.folders, folder: list2.value.folders.find((f) => real(f.path) === real(cwd)) ?? null };
32435
32809
  }
32436
32810
  async function addFolder2(dir, bind, strict = false) {
32437
32811
  if (!readSession()) return { error: "signed_out" };
@@ -32495,12 +32869,12 @@ async function connections(only) {
32495
32869
  }) };
32496
32870
  }
32497
32871
  async function all(route) {
32498
- const list = [];
32872
+ const list2 = [];
32499
32873
  for (let after = null; ; ) {
32500
32874
  const result = await request("GET", `${route}${route.includes("?") ? "&" : "?"}limit=100${after ? `&after=${encodeURIComponent(after)}` : ""}`);
32501
32875
  if (!result.ok) return result;
32502
- list.push(...result.value.data);
32503
- if (!result.value.next) return { ok: true, value: list };
32876
+ list2.push(...result.value.data);
32877
+ if (!result.value.next) return { ok: true, value: list2 };
32504
32878
  after = result.value.next;
32505
32879
  }
32506
32880
  }
@@ -32517,10 +32891,10 @@ async function settingsState(context) {
32517
32891
  if (!folders2.ok) return { ...base, account, ...failure(folders2) };
32518
32892
  if (!workspaces.ok) return { ...base, account, ...failure(workspaces) };
32519
32893
  const lists = await Promise.all(workspaces.value.map((ws) => all(`/v1/projects?workspace=${encodeURIComponent(ws.id)}`)));
32520
- const failed = lists.find((list) => !list.ok);
32894
+ const failed = lists.find((list2) => !list2.ok);
32521
32895
  if (failed && !failed.ok) return { ...base, account, ...failure(failed) };
32522
32896
  if (readSession()?.subject !== subject) return { ...base, signedIn: false };
32523
- const projects = lists.flatMap((list) => list.ok ? list.value : []);
32897
+ const projects = lists.flatMap((list2) => list2.ok ? list2.value : []);
32524
32898
  const metadata = (id) => {
32525
32899
  const project = projects.find((p) => p.id === id);
32526
32900
  const workspace = workspaces.value.find((w) => w.id === project?.workspace);