wildcrane-runner 0.6.57 → 0.6.59

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/runner.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.57 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.59 — 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;
@@ -111420,8 +111420,8 @@ function status(line) {
111420
111420
  }
111421
111421
 
111422
111422
  // src/protocol.ts
111423
- var VERSION = true ? "0.6.57" : "0.0.0";
111424
- var AKB_VERSION = true ? "0.11.45" : "0.0.0";
111423
+ var VERSION = true ? "0.6.59" : "0.0.0";
111424
+ var AKB_VERSION = true ? "0.11.46" : "0.0.0";
111425
111425
  var AKB_CONTRACT = true ? 12 : 0;
111426
111426
  var EXIT_REFUSED = 10;
111427
111427
  var EXIT_OUTDATED = 11;
@@ -111939,7 +111939,7 @@ function argHint(input, keys) {
111939
111939
  }
111940
111940
 
111941
111941
  // ../cli/src/lib/agent/wire/events.ts
111942
- var EVENT_KINDS = ["message", "tool_call", "tool_call_update", "plan", "error", "log", "context"];
111942
+ var EVENT_KINDS = ["message", "tool_call", "tool_call_update", "plan", "error", "log", "context", "phase"];
111943
111943
  var TOOL_KINDS = ["read", "edit", "delete", "move", "search", "execute", "fetch", "other"];
111944
111944
  var toolKind = (v) => TOOL_KINDS.includes(str(v)) ? v : "other";
111945
111945
  function targetOf(raw) {
@@ -113016,6 +113016,21 @@ function createKimiStreamRenderer(cwd) {
113016
113016
  };
113017
113017
  }
113018
113018
 
113019
+ // ../cli/src/lib/shared/conversation.ts
113020
+ var CONVERSATION_MS = { send: 15e3, claim: 3e4, prepare: 6e4, start: 15e3, startup: 12e4, quiet: 6e4, stop: 1e4 };
113021
+ function bounded(work, ms, reason) {
113022
+ return new Promise((resolve2, reject) => {
113023
+ const timer = setTimeout(() => reject(new Error(reason)), Math.max(0, ms));
113024
+ work.then((value) => {
113025
+ clearTimeout(timer);
113026
+ resolve2(value);
113027
+ }, (error) => {
113028
+ clearTimeout(timer);
113029
+ reject(error);
113030
+ });
113031
+ });
113032
+ }
113033
+
113019
113034
  // ../cli/src/lib/agent/wire/acp.ts
113020
113035
  import fs6 from "node:fs";
113021
113036
 
@@ -113150,7 +113165,7 @@ function createTail(log) {
113150
113165
  // ../cli/package.json
113151
113166
  var package_default = {
113152
113167
  name: "wildcrane",
113153
- version: "0.11.45",
113168
+ version: "0.11.46",
113154
113169
  akbContract: 12,
113155
113170
  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.",
113156
113171
  keywords: [
@@ -113309,6 +113324,11 @@ function createAcpClient(options = {}) {
113309
113324
  }
113310
113325
  async function oneTurn(io, options) {
113311
113326
  const tail = createTail(io.log);
113327
+ const preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
113328
+ const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
113329
+ let started = false;
113330
+ let contentAt = 0;
113331
+ let currentSession = "";
113312
113332
  const events = createEventCollector();
113313
113333
  const emit = () => {
113314
113334
  for (const e2 of events.events()) io.event?.(e2);
@@ -113321,7 +113341,16 @@ async function oneTurn(io, options) {
113321
113341
  io.stdin,
113322
113342
  (msg) => {
113323
113343
  if (msg.method === "session/update") {
113324
- if (live) {
113344
+ if (live && (!obj(msg.params).sessionId || obj(msg.params).sessionId === currentSession)) {
113345
+ const kind = str(obj(obj(msg.params).update).sessionUpdate);
113346
+ if (!started && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
113347
+ started = true;
113348
+ phase("started");
113349
+ }
113350
+ if (kind === "agent_message_chunk" && Date.now() - contentAt >= 1e3) {
113351
+ contentAt = Date.now();
113352
+ io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
113353
+ }
113325
113354
  update(obj(msg.params).update, tail, (usd) => costUsd = usd, (window2) => context = window2);
113326
113355
  events.update(obj(msg.params).update);
113327
113356
  emit();
@@ -113349,20 +113378,22 @@ async function oneTurn(io, options) {
113349
113378
  );
113350
113379
  try {
113351
113380
  const mcpServers = options.mcpConfig ? mcpServersIn(options.mcpConfig) : [];
113352
- await rpc.call("initialize", {
113381
+ phase("preparing");
113382
+ await bounded(rpc.call("initialize", {
113353
113383
  protocolVersion: PROTOCOL_VERSION,
113354
113384
  clientCapabilities: CLIENT_CAPABILITIES,
113355
113385
  clientInfo: { name: "ai4kanban", version: SKILL_VERSION }
113356
- });
113386
+ }), preparingUntil - Date.now(), "ACP initialize timed out.");
113387
+ phase("initialized");
113357
113388
  let sessionId = io.resumeId ?? "";
113358
113389
  let prompt = io.prompt;
113359
113390
  let opened;
113360
113391
  if (sessionId) {
113361
113392
  try {
113362
- opened = await rpc.call("session/load", { sessionId, cwd: io.cwd, mcpServers });
113393
+ opened = await bounded(rpc.call("session/load", { sessionId, cwd: io.cwd, mcpServers }), preparingUntil - Date.now(), "ACP session/load timed out.");
113363
113394
  } catch (e2) {
113364
113395
  if (!sessionGone(e2) || !io.restartPrompt) throw e2;
113365
- const fresh = await newSession(rpc, io.cwd, mcpServers);
113396
+ const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
113366
113397
  opened = fresh.opened;
113367
113398
  sessionId = fresh.sessionId;
113368
113399
  prompt = io.restartPrompt;
@@ -113372,7 +113403,7 @@ async function oneTurn(io, options) {
113372
113403
  emit();
113373
113404
  }
113374
113405
  } else {
113375
- const fresh = await newSession(rpc, io.cwd, mcpServers);
113406
+ const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
113376
113407
  opened = fresh.opened;
113377
113408
  sessionId = fresh.sessionId;
113378
113409
  io.gotResumeId(sessionId);
@@ -113381,11 +113412,15 @@ async function oneTurn(io, options) {
113381
113412
  if (options.model) {
113382
113413
  const listed2 = obj(opened.models).currentModelId !== void 0;
113383
113414
  const picked = listed2 ? pickedModel(opened, options.model) : void 0;
113384
- const set = listed2 ? await rpc.call("session/set_model", { sessionId, modelId: picked?.modelId ?? options.model }) : await rpc.call("session/set_config_option", { sessionId, configId: "model", value: options.model });
113415
+ const set = listed2 ? await bounded(rpc.call("session/set_model", { sessionId, modelId: picked?.modelId ?? options.model }), preparingUntil - Date.now(), "ACP session/set_model timed out.") : await bounded(rpc.call("session/set_config_option", { sessionId, configId: "model", value: options.model }), preparingUntil - Date.now(), "ACP session/set_config_option timed out.");
113385
113416
  model = picked?.name ?? modelOf(set) ?? options.model;
113386
113417
  }
113387
113418
  if (model) io.gotModel(model);
113419
+ if (Date.now() >= preparingUntil) throw Error("ACP preparation timed out.");
113420
+ phase("ready");
113421
+ currentSession = sessionId;
113388
113422
  live = true;
113423
+ phase("submitted");
113389
113424
  const done = await rpc.call("session/prompt", {
113390
113425
  sessionId,
113391
113426
  prompt: [{ type: "text", text: prompt }]
@@ -114082,10 +114117,24 @@ function createCodexClient(options = { images: [] }) {
114082
114117
  }
114083
114118
  async function run(io, options, tasks) {
114084
114119
  const renderer = createCodexStreamRenderer();
114120
+ const preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
114121
+ const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
114122
+ let submitted = false;
114123
+ let started = false;
114124
+ let contentAt = 0;
114125
+ let startupTimer;
114126
+ const began = () => {
114127
+ if (!submitted || started || ended2) return;
114128
+ started = true;
114129
+ clearTimeout(startupTimer);
114130
+ phase("started");
114131
+ };
114085
114132
  const children = /* @__PURE__ */ new Set();
114086
114133
  const commands = /* @__PURE__ */ new Set();
114087
114134
  const seenItems = /* @__PURE__ */ new Set();
114088
114135
  const completedTurns = /* @__PURE__ */ new Set();
114136
+ const historicalTurns = /* @__PURE__ */ new Set();
114137
+ let currentTurn2 = "";
114089
114138
  let threadId = "";
114090
114139
  let active = true;
114091
114140
  let waiting = false;
@@ -114111,6 +114160,7 @@ async function run(io, options, tasks) {
114111
114160
  if (ended2) return;
114112
114161
  ended2 = true;
114113
114162
  clearTimeout(timer);
114163
+ clearTimeout(startupTimer);
114114
114164
  deadline.close();
114115
114165
  io.stdout.off("close", closed);
114116
114166
  io.log(renderer.flush());
@@ -114142,10 +114192,11 @@ async function run(io, options, tasks) {
114142
114192
  io.event?.({ kind: "tool_call_update", data: { toolCallId: `agent:${id}`, status: failed ? "failed" : "completed", result: str(state.message) } });
114143
114193
  }
114144
114194
  };
114145
- const item = (raw, completed) => {
114195
+ const item = (raw, completed, proof = true) => {
114146
114196
  if (ended2) return;
114147
114197
  const id = str(raw.id);
114148
114198
  if (raw.type === "collabAgentToolCall") {
114199
+ if (proof) began();
114149
114200
  const key2 = `${id}:${completed}`;
114150
114201
  if (seenItems.has(key2)) return;
114151
114202
  seenItems.add(key2);
@@ -114173,6 +114224,7 @@ async function run(io, options, tasks) {
114173
114224
  const types = { agentMessage: "agent_message", commandExecution: "command_execution", fileChange: "file_change", mcpToolCall: "mcp_tool_call", webSearch: "web_search", imageGeneration: "image_generation" };
114174
114225
  const type = types[str(raw.type)];
114175
114226
  if (!type) return;
114227
+ if (proof) began();
114176
114228
  emit(completed ? "item.completed" : "item.started", { item: {
114177
114229
  ...raw,
114178
114230
  type,
@@ -114186,7 +114238,16 @@ async function run(io, options, tasks) {
114186
114238
  const start = async (text3, images = []) => {
114187
114239
  active = true;
114188
114240
  waiting = false;
114189
- await rpc.call("turn/start", { threadId, input: [{ type: "text", text: text3 }, ...images.map((path52) => ({ type: "localImage", path: path52 }))] });
114241
+ submitted = true;
114242
+ currentTurn2 = "";
114243
+ started = false;
114244
+ phase("submitted");
114245
+ startupTimer = setTimeout(() => {
114246
+ if (!started) io.event?.({ kind: "log", data: { text: "[conversation] start_unconfirmed" } });
114247
+ }, CONVERSATION_MS.start);
114248
+ await bounded(rpc.call("turn/start", { threadId, input: [{ type: "text", text: text3 }, ...images.map((path52) => ({ type: "localImage", path: path52 }))] }), CONVERSATION_MS.start, "Codex turn/start timed out; submission outcome is unknown.").catch((error) => {
114249
+ if (!started) throw error;
114250
+ });
114190
114251
  };
114191
114252
  const schedule = () => {
114192
114253
  if (ended2 || timer) return;
@@ -114271,11 +114332,21 @@ async function run(io, options, tasks) {
114271
114332
  }
114272
114333
  const p2 = obj(msg.params);
114273
114334
  if (str(p2.threadId) !== threadId) return;
114335
+ const turnId = str(p2.turnId) || str(obj(p2.turn).id);
114336
+ if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
114274
114337
  if (msg.method === "turn/started") {
114338
+ if (!submitted || completedTurns.has(turnId)) return;
114339
+ currentTurn2 = turnId;
114275
114340
  active = true;
114341
+ began();
114276
114342
  return;
114277
114343
  }
114278
- if (msg.method === "item/started" || msg.method === "item/completed") item(obj(p2.item), msg.method === "item/completed");
114344
+ if (submitted && msg.method === "item/agentMessage/delta" && Date.now() - contentAt >= 1e3) {
114345
+ began();
114346
+ contentAt = Date.now();
114347
+ io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
114348
+ }
114349
+ if (msg.method === "item/started" || msg.method === "item/completed") item(obj(p2.item), msg.method === "item/completed", !completedTurns.has(turnId));
114279
114350
  if (msg.method === "thread/tokenUsage/updated") {
114280
114351
  const token = obj(p2.tokenUsage);
114281
114352
  const counts2 = obj(token.total);
@@ -114306,17 +114377,20 @@ async function run(io, options, tasks) {
114306
114377
  }
114307
114378
  });
114308
114379
  try {
114309
- await rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } });
114380
+ phase("preparing");
114381
+ await bounded(rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } }), preparingUntil - Date.now(), "Codex initialize timed out.");
114382
+ phase("initialized");
114310
114383
  rpc.notify("initialized");
114311
114384
  const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
114312
114385
  let response;
114313
114386
  try {
114314
- response = await rpc.call(`thread/${mode ?? "start"}`, { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} });
114387
+ 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.`);
114315
114388
  } catch (e2) {
114316
114389
  if (mode && e2 instanceof RpcError && /no rollout found for thread id/i.test(e2.message)) throw Error(`Thread not found: ${e2.message}`);
114317
114390
  throw e2;
114318
114391
  }
114319
114392
  const thread = obj(response.thread);
114393
+ for (const turn2 of list(thread.turns)) historicalTurns.add(str(turn2.id));
114320
114394
  threadId = str(thread.id);
114321
114395
  if (!threadId) throw Error("Codex did not return a thread id.");
114322
114396
  provider = str(thread.modelProvider) || void 0;
@@ -114325,6 +114399,8 @@ async function run(io, options, tasks) {
114325
114399
  io.gotResumeId(threadId);
114326
114400
  baseline = readCodexRunFacts(threadId)?.turns?.at(-1)?.total;
114327
114401
  emit("thread.started", { thread_id: threadId });
114402
+ if (Date.now() >= preparingUntil) throw Error("Codex preparation timed out.");
114403
+ phase("ready");
114328
114404
  await start(io.prompt, options.images);
114329
114405
  } catch (e2) {
114330
114406
  end(e2 instanceof Error ? e2.message : String(e2));
@@ -116075,7 +116151,7 @@ var release = (machineId2) => request("POST", "/v1/runner/release", { machineId:
116075
116151
  var listJobs = (machineId2) => request("GET", `/v1/runner/jobs?machine=${encodeURIComponent(machineId2)}`);
116076
116152
  var move = (job, what, body) => request("POST", `/v1/runner/jobs/${encodeURIComponent(job)}/${what}`, body);
116077
116153
  var claimJob = (machineId2, job) => move(job, "claim", { machineId: machineId2 });
116078
- var renewJob = (machineId2, job) => move(job, "renew", { machineId: machineId2 });
116154
+ var renewJob = (machineId2, job, progress) => move(job, "renew", { machineId: machineId2, ...progress ? { progress } : {} });
116079
116155
  async function openLog(machineId2, job) {
116080
116156
  const token = await accessToken();
116081
116157
  if (!token.ok) return null;
@@ -116206,10 +116282,11 @@ function plan(runtime, prompt, cwd, resume, model, given = {}, fork = false, lan
116206
116282
  command: started[0],
116207
116283
  args: started.slice(1),
116208
116284
  env: env2,
116209
- converse: (child, event2, restart = true) => client.turn({
116285
+ converse: (child, event2, restart = true, prepareUntil) => client.turn({
116210
116286
  stdout: child.stdout,
116211
116287
  stdin: child.stdin,
116212
116288
  prompt,
116289
+ prepareUntil,
116213
116290
  restartPrompt: restart ? prompt : void 0,
116214
116291
  cwd,
116215
116292
  resumeId: resume ?? void 0,
@@ -119269,15 +119346,6 @@ function assetsOf(text3) {
119269
119346
  return {};
119270
119347
  }
119271
119348
  }
119272
- function taskAssetFiles(ws) {
119273
- if (!ws.number) return [];
119274
- const state = stateDir(ws);
119275
- const roots = [
119276
- path34.join(ws.board, "assets", String(ws.number)),
119277
- ...state ? ["assets", "mockups"].map((folder) => path34.join(state, folder, String(ws.number))) : []
119278
- ];
119279
- return roots.filter((root2) => fs30.lstatSync(root2, { throwIfNoEntry: false })?.isDirectory()).flatMap((root2) => filesUnder(root2).filter((p2) => !p2.split("/").some((part) => part.startsWith(".") || part === "node_modules")).map((p2) => path34.join(root2, p2)));
119280
- }
119281
119349
  var assetsText = (assets) => `${JSON.stringify(Object.fromEntries(Object.entries(assets).sort(([a2], [b2]) => a2 < b2 ? -1 : a2 > b2 ? 1 : 0)), null, 2)}
119282
119350
  `;
119283
119351
  function pull(ws, machineId2) {
@@ -119290,7 +119358,7 @@ function pull(ws, machineId2) {
119290
119358
  return readCloud(ws);
119291
119359
  });
119292
119360
  }
119293
- var replyAssetsSynced = (ws) => !readRecord(ws).pendingAssets?.length && !readBase(ws).pendingAssets?.includes(ws.task);
119361
+ var replyAssetsSynced = (ws) => !readBase(ws).pendingAssets?.includes(ws.task);
119294
119362
  function syncedCardVersion(ws) {
119295
119363
  const base = readBase(ws);
119296
119364
  const card = Object.entries(base.files).find(([p2]) => p2.startsWith(rootOf(ws) + "todo/") && numberOfCard(p2.slice(rootOf(ws).length)) === ws.number);
@@ -119402,13 +119470,9 @@ async function pullAssets(ws, record, assets) {
119402
119470
  record.number = ws.number;
119403
119471
  }
119404
119472
  const file3 = cardFile(ws);
119405
- const out = Object.fromEntries((record.pendingAssets ?? []).flatMap((key) => record.assets[key] ? [[key, record.assets[key]]] : []));
119473
+ const out = {};
119406
119474
  for (const [name, ref] of Object.entries(assets)) {
119407
119475
  const held4 = record.assets[name];
119408
- if (record.pendingAssets?.includes(name) && held4) {
119409
- out[name] = held4;
119410
- continue;
119411
- }
119412
119476
  if (ref.error && !ref.version) {
119413
119477
  if (held4?.artifact === ref.artifact) out[name] = held4;
119414
119478
  continue;
@@ -119547,7 +119611,6 @@ async function uploadAsset(artifact, { bytes: bytes2, type }) {
119547
119611
  async function pushAssets(ws, record, before) {
119548
119612
  const started = performance.now();
119549
119613
  logSync("assets.start", { project: ws.project, task: ws.task, entries: Object.keys(record.assets).length });
119550
- const errors = [];
119551
119614
  if (ws.cloudTask && ws.number && (record.task !== ws.cloudTask || record.number !== ws.number)) {
119552
119615
  record.task = ws.cloudTask;
119553
119616
  record.number = ws.number;
@@ -119555,7 +119618,7 @@ async function pushAssets(ws, record, before) {
119555
119618
  }
119556
119619
  const file3 = cardFile(ws);
119557
119620
  const body = readText(file3);
119558
- if (body === null) return { ok: true, value: { errors } };
119621
+ if (body === null) return { ok: true, value: void 0 };
119559
119622
  const refs = {};
119560
119623
  const canonical = (target) => {
119561
119624
  const real = (file4) => fs30.existsSync(file4) ? fs30.realpathSync(file4) : path34.dirname(file4) === file4 ? file4 : path34.join(real(path34.dirname(file4)), path34.basename(file4));
@@ -119658,6 +119721,8 @@ async function pushAssets(ws, record, before) {
119658
119721
  const made = await createArtifact(ws.cloudTask, node.key.slice(0, 200), out.kind);
119659
119722
  if (!made.ok) return { ...made, error: `${node.key}: ${made.error}` };
119660
119723
  artifact = made.value.id;
119724
+ for (const alias of node.aliases) record.assets[alias] = { artifact, kind: out.kind, version: 0, hash: "" };
119725
+ writeRecord(ws, record);
119661
119726
  }
119662
119727
  const sent = await uploadAsset(artifact, out);
119663
119728
  if (!sent.ok) return { ...sent, error: `${node.key}: ${sent.error}` };
@@ -119666,108 +119731,14 @@ async function pushAssets(ws, record, before) {
119666
119731
  entry = { ...entry, localHash: localHash ?? void 0, dependencies: [...node.dependencies.values()] };
119667
119732
  let changed = false;
119668
119733
  for (const alias of node.aliases) {
119669
- if (!isDeepStrictEqual(record.assets[alias], entry) || record.pendingAssets?.includes(alias)) {
119734
+ if (!isDeepStrictEqual(record.assets[alias], entry)) {
119670
119735
  record.assets[alias] = entry;
119671
- record.pendingAssets = record.pendingAssets?.filter((key) => key !== alias);
119672
119736
  changed = true;
119673
119737
  }
119674
119738
  refs[alias] = { artifact: entry.artifact, version: entry.version };
119675
119739
  }
119676
119740
  if (changed) writeRecord(ws, record);
119677
119741
  }
119678
- const sendResource = async (file4) => {
119679
- const key = canonical(file4);
119680
- if (refs[key]) return { ok: true, value: void 0 };
119681
- assetPath(ws, key, cardFile(ws));
119682
- const sendFile = async () => {
119683
- const previous = record.assets[key];
119684
- const size = fs30.statSync(file4).size;
119685
- if (size > ASSET_FILE_LIMIT) return { ok: false, code: "too_large", error: `${key}: This asset is over 100 MiB.` };
119686
- const digest2 = crypto5.createHash("sha256");
119687
- for await (const chunk of fs30.createReadStream(file4)) digest2.update(chunk);
119688
- const hash = digest2.digest("hex");
119689
- let entry = previous;
119690
- if (!entry?.version || entry.kind !== "asset" || entry.hash !== hash) {
119691
- if (!ws.cloudTask) return { ok: true, value: void 0 };
119692
- let artifact = entry?.kind === "asset" ? entry.artifact : void 0;
119693
- if (!artifact) {
119694
- const made = await createArtifact(ws.cloudTask, key.slice(0, 200), "asset");
119695
- if (!made.ok) return { ...made, error: `${key}: ${made.error}` };
119696
- artifact = made.value.id;
119697
- record.assets[key] = { artifact, kind: "asset", version: 0, hash: "" };
119698
- writeRecord(ws, record);
119699
- }
119700
- const type = TYPES[path34.extname(file4).toLowerCase()] ?? "application/octet-stream";
119701
- const upload2 = await createUpload(artifact, type, Math.max(size, 1));
119702
- if (!upload2.ok) return { ...upload2, error: `${key}: ${upload2.error}` };
119703
- const route = `/v1/uploads/${encodeURIComponent(upload2.value.id)}`;
119704
- if (upload2.value.parts) {
119705
- const { count: count2, size: partSize, url: partUrl } = upload2.value.parts;
119706
- const source = await fs30.promises.open(file4, "r");
119707
- try {
119708
- for (let part = 1; part <= count2; part++) {
119709
- const bytes2 = Buffer.alloc(Math.min(partSize, size - (part - 1) * partSize));
119710
- let offset = 0;
119711
- while (offset < bytes2.length) {
119712
- const read4 = await source.read(bytes2, offset, bytes2.length - offset, (part - 1) * partSize + offset);
119713
- if (!read4.bytesRead) throw new Error(`${key}: file changed during upload`);
119714
- offset += read4.bytesRead;
119715
- }
119716
- const put = await upload(partUrl.replace("{part}", String(part)), bytes2, type);
119717
- if (!put.ok) return { ...put, error: `${key}: ${put.error}` };
119718
- }
119719
- } finally {
119720
- await source.close();
119721
- }
119722
- const completed = await completeUpload(upload2.value.url ?? `${route}/complete`);
119723
- if (!completed.ok) return { ...completed, error: `${key}: ${completed.error}` };
119724
- } else {
119725
- const put = await upload(upload2.value.url ?? route, fs30.readFileSync(file4), type);
119726
- if (!put.ok) return { ...put, error: `${key}: ${put.error}` };
119727
- }
119728
- const sent2 = await createVersion(artifact, upload2.value.id);
119729
- if (!sent2.ok) return { ...sent2, error: `${key}: ${sent2.error}` };
119730
- entry = { artifact, version: sent2.value.version, hash, localHash: hash, kind: "asset" };
119731
- }
119732
- refs[key] = { artifact: entry.artifact, version: entry.version };
119733
- if (record.assets[key] !== entry || record.pendingAssets?.includes(key)) {
119734
- record.assets[key] = entry;
119735
- record.pendingAssets = record.pendingAssets?.filter((p2) => p2 !== key);
119736
- writeRecord(ws, record);
119737
- }
119738
- return { ok: true, value: void 0 };
119739
- };
119740
- let sent;
119741
- try {
119742
- sent = await sendFile();
119743
- } catch (error) {
119744
- sent = { ok: false, error: `${key}: ${renderError(error)}` };
119745
- }
119746
- if (!sent.ok) {
119747
- if (sent.code && !["too_large", "payload_too_large", "storage_limit", "storage_limit_reached", "service_unavailable"].includes(sent.code)) return sent;
119748
- record.pendingAssets = [.../* @__PURE__ */ new Set([...record.pendingAssets ?? [], key])];
119749
- writeRecord(ws, record);
119750
- errors.push({ error: sent.error, ...!sent.code || sent.code === "service_unavailable" ? { offline: true } : {} });
119751
- console.error(`runner: asset upload pending: ${sent.error}`);
119752
- if (before[key]) refs[key] = before[key];
119753
- }
119754
- return { ok: true, value: void 0 };
119755
- };
119756
- const files = [...new Map(taskAssetFiles(ws).map((file4) => [canonical(file4), file4])).values()];
119757
- logSync("assets.files", { project: ws.project, task: ws.task, graph: graph.length, files: files.length, ms: Math.round(performance.now() - started) });
119758
- let next = 0;
119759
- let failure2;
119760
- await Promise.all(Array.from({ length: Math.min(4, files.length) }, async () => {
119761
- while (!failure2 && next < files.length) {
119762
- try {
119763
- const sent = await sendResource(files[next++]);
119764
- if (!sent.ok) failure2 ??= sent;
119765
- } catch (error) {
119766
- failure2 ??= { ok: false, code: "bad_request", error: renderError(error) };
119767
- }
119768
- }
119769
- }));
119770
- if (failure2) return failure2;
119771
119742
  } catch (error) {
119772
119743
  return { ok: false, code: "bad_request", error: error instanceof Error ? error.message : String(error) };
119773
119744
  }
@@ -119776,7 +119747,7 @@ async function pushAssets(ws, record, before) {
119776
119747
  if (!isDeepStrictEqual(assetsOf(readText(list2)), refs)) write(list2, assetsText(refs));
119777
119748
  }
119778
119749
  logSync("assets.end", { project: ws.project, task: ws.task, ms: Math.round(performance.now() - started) });
119779
- return { ok: true, value: { errors } };
119750
+ return { ok: true, value: void 0 };
119780
119751
  }
119781
119752
  function resetSorted(ws) {
119782
119753
  for (const sub of ["dismissed", "archived"]) fs30.rmSync(path34.join(ws.board, "triage", sub), { recursive: true, force: true });
@@ -119853,8 +119824,6 @@ async function send2(ws, job) {
119853
119824
  if (!archived) {
119854
119825
  const assets = await pushAssets(item.folder, item.record, assetsOf(assetsListOf(item.folder, base)));
119855
119826
  if (assets.ok) {
119856
- const error = assets.value.errors[0];
119857
- if (error) assetErrors[item.folder.task] = { ...error, blocking: false };
119858
119827
  writeRecord(item.folder, item.record);
119859
119828
  continue;
119860
119829
  }
@@ -121187,6 +121156,7 @@ function clearCheckpoint(id) {
121187
121156
  fs38.rmSync(fileOf(id), { force: true });
121188
121157
  }
121189
121158
  function checkpointEvent(checkpoint, event2) {
121159
+ if (event2.kind === "phase" && event2.data.phase === "submitted") checkpoint.submitted = true;
121190
121160
  if (event2.kind === "tool_call") {
121191
121161
  const { toolCallId, status: status2, kind } = event2.data;
121192
121162
  if (!["read", "search", "fetch"].includes(kind)) checkpoint.effects = true;
@@ -121217,7 +121187,7 @@ function replyRetry(checkpoint, reason, now = Date.now(), backoff = backoffMs) {
121217
121187
  return at2 <= retry2.since + 12e4 ? at2 : null;
121218
121188
  }
121219
121189
  function replayable(checkpoint) {
121220
- return (checkpoint.effects === false || checkpoint.started === false) && !checkpoint.pending.length && !checkpoint.opaque;
121190
+ return checkpoint.submitted !== true && (checkpoint.effects === false || checkpoint.started === false) && !checkpoint.pending.length && !checkpoint.opaque;
121221
121191
  }
121222
121192
  function resumable(checkpoint) {
121223
121193
  return !!checkpoint.session && !checkpoint.pending.length && !checkpoint.opaque;
@@ -121933,7 +121903,7 @@ function toWire(events, first) {
121933
121903
  continue;
121934
121904
  }
121935
121905
  endLog();
121936
- const data = { ...e2.data };
121906
+ const data = { ...e2.data, eventAt: "eventAt" in e2.data ? e2.data.eventAt : (/* @__PURE__ */ new Date()).toISOString() };
121937
121907
  for (const key of ["text", "result"]) if (typeof data[key] === "string") data[key] = cut(data[key]);
121938
121908
  out.push({ seq: first + out.length, kind: e2.kind, text: "", data });
121939
121909
  }
@@ -122077,7 +122047,7 @@ function streamOut(deps, id, lease) {
122077
122047
  const event2 = (e2) => {
122078
122048
  if (!valid()) return;
122079
122049
  if (e2.kind === "message") messages.push(e2.data.text);
122080
- pending.push(e2);
122050
+ pending.push(Object.assign({}, e2, { data: { ...e2.data, eventAt: (/* @__PURE__ */ new Date()).toISOString() } }));
122081
122051
  size += JSON.stringify(e2.data).length;
122082
122052
  if (log.watched && size >= FLUSH_CHARS) flush();
122083
122053
  };
@@ -122146,6 +122116,7 @@ function streamOut(deps, id, lease) {
122146
122116
  return true;
122147
122117
  },
122148
122118
  stop: loseLease,
122119
+ requestStop: ask,
122149
122120
  lost: () => !valid(),
122150
122121
  asked: () => asked,
122151
122122
  whenAsked: askedOnce,
@@ -122387,7 +122358,7 @@ ${prompt}` : prompt;
122387
122358
  }
122388
122359
  if (deps.authorize && !await deps.authorize(job)) return finishClaimed("failed", "\u9879\u76EE\u76EE\u5F55\u6388\u6743\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u540E\u91CD\u8BD5\u3002");
122389
122360
  if (!held3(deps, lease)) return;
122390
- if (reply && recovering) {
122361
+ if (reply) {
122391
122362
  const renewed = await deps.api.renewJob(deps.machineId, id);
122392
122363
  if (!renewed.ok || !renewed.value.renewed) return;
122393
122364
  if (renewed.value.stop) return finishClaimed("stopped", "", { stopped: true });
@@ -122411,10 +122382,24 @@ ${prompt}` : prompt;
122411
122382
  return { ...rest, ...replySpent(checkpoint, job.runtime) };
122412
122383
  };
122413
122384
  let replyProgress = false;
122385
+ let evidence = Promise.resolve();
122386
+ let lastEvidence = 0;
122414
122387
  const subagents = trackSubagents();
122415
122388
  const remember = (event2) => {
122416
122389
  if (["message", "tool_call", "tool_call_update"].includes(event2.kind)) replyProgress = true;
122417
122390
  if (stream.lost()) return;
122391
+ const content = ["message", "tool_call", "tool_call_update", "plan"].includes(event2.kind) || event2.kind === "phase" && !!event2.data.contentAt;
122392
+ if (reply && (event2.kind === "phase" && !event2.data.contentAt || content && Date.now() - lastEvidence >= 5e3)) {
122393
+ if (content) lastEvidence = Date.now();
122394
+ const progress = { attempt: checkpoint.retry?.attempt ?? 1, ...event2.kind === "phase" ? { phase: event2.data.phase } : {}, ...content ? { contentAt: (/* @__PURE__ */ new Date()).toISOString() } : {} };
122395
+ evidence = evidence.then(async () => {
122396
+ if (stream.asked() || stream.lost()) return;
122397
+ const result = await deps.api.renewJob(deps.machineId, id, progress);
122398
+ if (result.ok && !result.value.renewed) await stream.stop();
122399
+ else if (result.ok && result.value.stop) stream.requestStop();
122400
+ }).catch(() => {
122401
+ });
122402
+ }
122418
122403
  subagents.event(event2);
122419
122404
  checkpointEvent(checkpoint, event2);
122420
122405
  const session = run3?.session();
@@ -122425,6 +122410,8 @@ ${prompt}` : prompt;
122425
122410
  };
122426
122411
  const retry2 = async (reason) => {
122427
122412
  if (!reply || !reason || stream.asked() || stream.lost()) return false;
122413
+ if ((checkpoint.retry?.attempt ?? 1) >= 2 || !/timed out|ECONNRESET|ETIMEDOUT|temporar|overload|capacity|rate.limit|429|503|network|connection.*(reset|closed)/i.test(reason)) return false;
122414
+ if (/timed out|start_unconfirmed/i.test(reason) && (!/initialize|session\/(new|load)|thread\/(start|resume|fork)/i.test(reason) || Date.now() >= checkpoint.retry.since + CONVERSATION_MS.prepare)) return false;
122428
122415
  checkpoint.approvalCancelled = true;
122429
122416
  persist();
122430
122417
  if (job.chat && checkpoint.approvalRequested) await cancelReplyApproval(deps.machineId, id);
@@ -122514,8 +122501,8 @@ ${prompt}` : prompt;
122514
122501
  await stream.end();
122515
122502
  if (stream.lost()) return;
122516
122503
  const boardStopped = await confirmFlowStopped(ws, job, deps);
122517
- const evidence = job.handoff?.action === "continue" || job.handoff?.action === "restart" ? progressEvidence(job, ws.cwd) : null;
122518
- const proof = boardStopped && await stream.confirmed() ? { processesStopped: true, ...evidence ? { evidence } : {} } : {};
122504
+ const evidence2 = job.handoff?.action === "continue" || job.handoff?.action === "restart" ? progressEvidence(job, ws.cwd) : null;
122505
+ const proof = boardStopped && await stream.confirmed() ? { processesStopped: true, ...evidence2 ? { evidence: evidence2 } : {} } : {};
122519
122506
  if (ended3.ok) complete("done", { ...ended3.report, ...proof });
122520
122507
  if (stopped3) return finishClaimed("stopped", "", proof);
122521
122508
  if (!ended3.ok) return finishClaimed("failed", ended3.reason, proof);
@@ -122542,7 +122529,7 @@ ${prompt}` : prompt;
122542
122529
  child.stderr.on("data", (chunk) => stream.out(quietLines(plan3, chunk)));
122543
122530
  const spawned = new Promise((resolve2) => child.on("error", (e2) => resolve2(e2.message)));
122544
122531
  const end = await Promise.race([
122545
- converse(child, remember, false),
122532
+ converse(child, remember, false, reply ? checkpoint.retry.since + CONVERSATION_MS.prepare : void 0),
122546
122533
  spawned.then((error) => ({ ok: false, error })),
122547
122534
  // Killed, the turn ends with what it said so far; one that never does is not waited on.
122548
122535
  stream.whenAsked.then(() => wait2(KILL_GRACE_MS * 2)).then(() => ({ ok: true }))
@@ -122576,8 +122563,13 @@ ${prompt}` : prompt;
122576
122563
  persist();
122577
122564
  }
122578
122565
  if (await retry2(end.ok ? void 0 : end.error)) return;
122566
+ await evidence;
122579
122567
  const stopped3 = await stopReply(id, deps.stopMs);
122580
122568
  stop(child);
122569
+ if (stream.asked() && (!stopped3 || !await stream.confirmed())) {
122570
+ await stream.end();
122571
+ return;
122572
+ }
122581
122573
  const ok = end.ok || stream.asked();
122582
122574
  const unsafe2 = reply && !ok && (!stopped3 || !replayable(checkpoint) && !resumable(checkpoint));
122583
122575
  const said2 = {
@@ -122681,6 +122673,10 @@ ${plan2.renderer.failure?.() ?? ""}`)) && (checkpoint.retry?.attempt ?? 1) < 3 &
122681
122673
  }
122682
122674
  if (await retry2(rawFailure)) return;
122683
122675
  const stopped2 = await stopReply(id, deps.stopMs);
122676
+ if (stream.asked() && (!stopped2 || !await stream.confirmed())) {
122677
+ await stream.end();
122678
+ return;
122679
+ }
122684
122680
  const unsafe = reply && !!rawFailure && (!stopped2 || !replayable(checkpoint) && !resumable(checkpoint));
122685
122681
  const failure2 = stream.asked() ? void 0 : unsafe ? "recovery_unsafe" : replyReason(ended2.error ?? renderer.failure?.() ?? (ended2.code === 0 ? void 0 : `Exited with code ${ended2.code}.`), job);
122686
122682
  const said = {