@mycompbox/compbox-cli 1.21.5 → 1.21.7

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/index.js CHANGED
@@ -6470,6 +6470,12 @@ function errorFromResponse(res, fallback) {
6470
6470
  const message = extractServerMessage(res.data) ?? fallback;
6471
6471
  return new MailboxClientError(message, res.status);
6472
6472
  }
6473
+ function parseCancelJobIds(body) {
6474
+ if (typeof body !== "object" || body === null) return [];
6475
+ const raw = body.cancelJobIds;
6476
+ if (!Array.isArray(raw)) return [];
6477
+ return raw.filter((id) => typeof id === "string" && id.length > 0);
6478
+ }
6473
6479
  var MailboxClient = class {
6474
6480
  http;
6475
6481
  baseUrl;
@@ -6594,6 +6600,14 @@ var MailboxClient = class {
6594
6600
  * new work instead of resuming one of them.
6595
6601
  */
6596
6602
  async nextJob(machineToken, waitMs = 0, runningIds = []) {
6603
+ return (await this.pollNextJob(machineToken, waitMs, runningIds)).job;
6604
+ }
6605
+ /**
6606
+ * Same as {@link nextJob}, but also returns `cancelJobIds` (ENG-299): the ids
6607
+ * of this machine's jobs someone asked to cancel. A 204 means no job and no
6608
+ * cancels; a 200 may carry `{ data: null, cancelJobIds }` (cancels only).
6609
+ */
6610
+ async pollNextJob(machineToken, waitMs = 0, runningIds = []) {
6597
6611
  let res;
6598
6612
  try {
6599
6613
  res = await this.http.get("/api/v1/machines/next-job", {
@@ -6606,13 +6620,13 @@ var MailboxClient = class {
6606
6620
  throw toMailboxError(error, "next-job request failed");
6607
6621
  }
6608
6622
  if (res.status === 204) {
6609
- return null;
6623
+ return { job: null, cancelJobIds: [] };
6610
6624
  }
6611
6625
  if (res.status < 200 || res.status >= 300) {
6612
6626
  throw errorFromResponse(res, "next-job failed");
6613
6627
  }
6614
- const data = res.data;
6615
- return data.data;
6628
+ const body = res.data;
6629
+ return { job: body?.data ?? null, cancelJobIds: parseCancelJobIds(body) };
6616
6630
  }
6617
6631
  /**
6618
6632
  * Explicit heartbeat ping (idle-period keepalive; next-job itself also
@@ -6630,6 +6644,8 @@ var MailboxClient = class {
6630
6644
  * Both extras are independent and optional: calling `heartbeat(token)` with
6631
6645
  * neither is backward-compatible and sends `{}`; passing only `runtime`
6632
6646
  * preserves the exact ENG-136 wire shape (no `servicedRemotes` key).
6647
+ *
6648
+ * Resolves with the response's `cancelJobIds` (ENG-299) — `[]` when absent.
6633
6649
  */
6634
6650
  async heartbeat(machineToken, runtime, servicedRemotes) {
6635
6651
  const body = {};
@@ -6654,6 +6670,7 @@ var MailboxClient = class {
6654
6670
  if (res.status < 200 || res.status >= 300) {
6655
6671
  throw errorFromResponse(res, "Heartbeat failed");
6656
6672
  }
6673
+ return { cancelJobIds: parseCancelJobIds(res.data) };
6657
6674
  }
6658
6675
  /** Posts an agent turn (a question/status update) to a job's interview log. */
6659
6676
  async postTurn(machineToken, jobId, content) {
@@ -8038,6 +8055,90 @@ function parseClaudeJsonResult(stdout2, fallbackModel) {
8038
8055
  return { text: typeof data.result === "string" ? data.result : "", usage };
8039
8056
  }
8040
8057
 
8058
+ // src/utils/process-group.ts
8059
+ import { spawn as nodeSpawn } from "node:child_process";
8060
+ var CANCEL_GRACE_MS = 1e4;
8061
+ function groupSpawnOptions(platform = process.platform) {
8062
+ return platform === "win32" ? {} : { detached: true };
8063
+ }
8064
+ function defaultKillTree(pid) {
8065
+ try {
8066
+ const killer = nodeSpawn("taskkill", ["/PID", String(pid), "/T", "/F"], {
8067
+ stdio: "ignore",
8068
+ windowsHide: true
8069
+ });
8070
+ killer.on("error", () => {
8071
+ });
8072
+ } catch {
8073
+ }
8074
+ }
8075
+ function signalGroup(child, signal, deps) {
8076
+ const pid = child.pid;
8077
+ if (pid === void 0) {
8078
+ try {
8079
+ child.kill(signal);
8080
+ } catch {
8081
+ }
8082
+ return;
8083
+ }
8084
+ const kill = deps.kill ?? ((p, s) => process.kill(p, s));
8085
+ try {
8086
+ kill(-pid, signal);
8087
+ } catch (error) {
8088
+ if (error.code === "ESRCH") return;
8089
+ try {
8090
+ child.kill(signal);
8091
+ } catch {
8092
+ }
8093
+ }
8094
+ }
8095
+ function terminateProcessGroup(child, deps = {}) {
8096
+ const platform = deps.platform ?? process.platform;
8097
+ if (platform === "win32") {
8098
+ if (child.pid !== void 0) (deps.killTree ?? defaultKillTree)(child.pid);
8099
+ else child.kill("SIGKILL");
8100
+ return () => void 0;
8101
+ }
8102
+ signalGroup(child, "SIGTERM", deps);
8103
+ const escalate = setTimeout(() => {
8104
+ signalGroup(child, "SIGKILL", deps);
8105
+ }, deps.graceMs ?? CANCEL_GRACE_MS);
8106
+ escalate.unref();
8107
+ return () => {
8108
+ clearTimeout(escalate);
8109
+ };
8110
+ }
8111
+ function killProcessGroupNow(child, deps = {}) {
8112
+ const platform = deps.platform ?? process.platform;
8113
+ if (platform === "win32") {
8114
+ if (child.pid !== void 0) (deps.killTree ?? defaultKillTree)(child.pid);
8115
+ else child.kill("SIGKILL");
8116
+ return;
8117
+ }
8118
+ signalGroup(child, "SIGKILL", deps);
8119
+ }
8120
+ function killGroupOnAbort(signal, child, onAbort, deps = {}) {
8121
+ if (!signal) return () => void 0;
8122
+ const handler = () => {
8123
+ onAbort();
8124
+ terminateProcessGroup(child, deps);
8125
+ };
8126
+ if (signal.aborted) {
8127
+ handler();
8128
+ } else {
8129
+ signal.addEventListener("abort", handler, { once: true });
8130
+ }
8131
+ return () => {
8132
+ signal.removeEventListener("abort", handler);
8133
+ };
8134
+ }
8135
+ function cancelledRunResult(what) {
8136
+ return {
8137
+ status: "failed",
8138
+ result: { cancelled: true, message: `Cancelled from the website; the ${what} was stopped.` }
8139
+ };
8140
+ }
8141
+
8041
8142
  // src/utils/agent-invoker.ts
8042
8143
  var ANTHROPIC_MODEL = "claude-fable-5";
8043
8144
  var CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1e3;
@@ -8243,17 +8344,32 @@ async function takeConversationStep(job, ctx) {
8243
8344
  {
8244
8345
  reply: async (system, messages) => {
8245
8346
  if (anthropic) {
8246
- const response = await anthropic.messages.create({ model: ANTHROPIC_MODEL, max_tokens: 4096, system, messages });
8347
+ const response = await anthropic.messages.create({
8348
+ model: ANTHROPIC_MODEL,
8349
+ max_tokens: 4096,
8350
+ system,
8351
+ messages
8352
+ });
8247
8353
  const text = response.content.find((b) => b.type === "text");
8248
8354
  return text?.type === "text" ? text.text : "";
8249
8355
  }
8250
8356
  const prompt = renderConversationPrompt(messages);
8251
8357
  try {
8252
- return (await runClaudeCliTurn(prompt, { systemPrompt: system, resumeSessionId: void 0, routing, model: cliModel })).text;
8358
+ return (await runClaudeCliTurn(prompt, {
8359
+ systemPrompt: system,
8360
+ resumeSessionId: void 0,
8361
+ routing,
8362
+ model: cliModel
8363
+ })).text;
8253
8364
  } catch (error) {
8254
8365
  if (cliModel === null || !needsDefaultModel(error)) throw error;
8255
8366
  cliModel = null;
8256
- return (await runClaudeCliTurn(prompt, { systemPrompt: system, resumeSessionId: void 0, routing, model: null })).text;
8367
+ return (await runClaudeCliTurn(prompt, {
8368
+ systemPrompt: system,
8369
+ resumeSessionId: void 0,
8370
+ routing,
8371
+ model: null
8372
+ })).text;
8257
8373
  }
8258
8374
  },
8259
8375
  save: async (existingId, draft) => {
@@ -8450,6 +8566,7 @@ function buildPlannerFinalTurn(outcome) {
8450
8566
  return `Planner run ended: ${JSON.stringify(r).slice(0, PLANNER_FINAL_TURN_MAX_CHARS)}`;
8451
8567
  }
8452
8568
  async function invokeStartExecutionPlan(ctx, deps = {}) {
8569
+ if (ctx.signal?.aborted) return cancelledRunResult("planner");
8453
8570
  const spawnImpl = deps.spawnImpl ?? spawn3;
8454
8571
  const fetchImpl = deps.fetchImpl ?? fetch;
8455
8572
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
@@ -8490,8 +8607,22 @@ async function invokeStartExecutionPlan(ctx, deps = {}) {
8490
8607
  const child = spawnImpl(command, args, {
8491
8608
  cwd: ctx.projectDir,
8492
8609
  stdio: ["ignore", "pipe", "pipe"],
8493
- env: childEnv
8494
- });
8610
+ env: childEnv,
8611
+ // ENG-300: lead its own process group so a cancel can stop everything it started.
8612
+ ...groupSpawnOptions(deps.processGroup?.platform)
8613
+ });
8614
+ let cancelled = false;
8615
+ const disposeAbort = killGroupOnAbort(
8616
+ ctx.signal,
8617
+ child,
8618
+ () => {
8619
+ cancelled = true;
8620
+ setTimeout(() => {
8621
+ finish(cancelledRunResult("planner"));
8622
+ }, (deps.processGroup?.graceMs ?? CANCEL_GRACE_MS) + 5e3).unref();
8623
+ },
8624
+ deps.processGroup
8625
+ );
8495
8626
  const heartbeatTimer = deps.heartbeat ? setInterval(() => {
8496
8627
  void Promise.resolve(deps.heartbeat?.()).catch(() => {
8497
8628
  });
@@ -8501,10 +8632,11 @@ async function invokeStartExecutionPlan(ctx, deps = {}) {
8501
8632
  settled = true;
8502
8633
  if (heartbeatTimer) clearInterval(heartbeatTimer);
8503
8634
  clearTimeout(timer);
8635
+ disposeAbort();
8504
8636
  resolve3(result);
8505
8637
  };
8506
8638
  const timer = setTimeout(() => {
8507
- child.kill("SIGKILL");
8639
+ killProcessGroupNow(child, deps.processGroup);
8508
8640
  finish({
8509
8641
  status: "failed",
8510
8642
  result: {
@@ -8519,6 +8651,10 @@ async function invokeStartExecutionPlan(ctx, deps = {}) {
8519
8651
  stderr += chunk.toString("utf-8");
8520
8652
  });
8521
8653
  child.on("error", (error) => {
8654
+ if (cancelled) {
8655
+ finish(cancelledRunResult("planner"));
8656
+ return;
8657
+ }
8522
8658
  finish({
8523
8659
  status: "failed",
8524
8660
  result: {
@@ -8529,6 +8665,10 @@ async function invokeStartExecutionPlan(ctx, deps = {}) {
8529
8665
  child.on("close", (code) => {
8530
8666
  void (async () => {
8531
8667
  if (ctx.keyRun) stdout2 = await settleKeyRun(ctx, ctx.keyRun, stdout2);
8668
+ if (cancelled) {
8669
+ finish(cancelledRunResult("planner"));
8670
+ return;
8671
+ }
8532
8672
  const combined = `${stdout2}
8533
8673
  ${stderr}`;
8534
8674
  const review = detectNeedsHumanReview(combined);
@@ -8632,6 +8772,7 @@ function buildRefineFinalTurn(outcome) {
8632
8772
  return `Refine run ended: ${text(r.error) ?? JSON.stringify(r)}`.slice(0, PLANNER_FINAL_TURN_MAX_CHARS);
8633
8773
  }
8634
8774
  async function invokeStartExecutionRefine(ctx, deps = {}) {
8775
+ if (ctx.signal?.aborted) return cancelledRunResult("planner");
8635
8776
  const spawnImpl = deps.spawnImpl ?? spawn3;
8636
8777
  const fetchImpl = deps.fetchImpl ?? fetch;
8637
8778
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
@@ -8664,8 +8805,22 @@ async function invokeStartExecutionRefine(ctx, deps = {}) {
8664
8805
  const child = spawnImpl(command, args, {
8665
8806
  cwd: ctx.projectDir,
8666
8807
  stdio: ["ignore", "pipe", "pipe"],
8667
- env: childEnv
8668
- });
8808
+ env: childEnv,
8809
+ // ENG-300: lead its own process group so a cancel can stop everything it started.
8810
+ ...groupSpawnOptions(deps.processGroup?.platform)
8811
+ });
8812
+ let cancelled = false;
8813
+ const disposeAbort = killGroupOnAbort(
8814
+ ctx.signal,
8815
+ child,
8816
+ () => {
8817
+ cancelled = true;
8818
+ setTimeout(() => {
8819
+ finish(cancelledRunResult("planner"));
8820
+ }, (deps.processGroup?.graceMs ?? CANCEL_GRACE_MS) + 5e3).unref();
8821
+ },
8822
+ deps.processGroup
8823
+ );
8669
8824
  const heartbeatTimer = deps.heartbeat ? setInterval(() => {
8670
8825
  void Promise.resolve(deps.heartbeat?.()).catch(() => {
8671
8826
  });
@@ -8675,10 +8830,11 @@ async function invokeStartExecutionRefine(ctx, deps = {}) {
8675
8830
  settled = true;
8676
8831
  if (heartbeatTimer) clearInterval(heartbeatTimer);
8677
8832
  clearTimeout(timer);
8833
+ disposeAbort();
8678
8834
  resolve3(result);
8679
8835
  };
8680
8836
  const timer = setTimeout(() => {
8681
- child.kill("SIGKILL");
8837
+ killProcessGroupNow(child, deps.processGroup);
8682
8838
  finish({
8683
8839
  status: "failed",
8684
8840
  result: {
@@ -8693,6 +8849,10 @@ async function invokeStartExecutionRefine(ctx, deps = {}) {
8693
8849
  stderr += chunk.toString("utf-8");
8694
8850
  });
8695
8851
  child.on("error", (error) => {
8852
+ if (cancelled) {
8853
+ finish(cancelledRunResult("planner"));
8854
+ return;
8855
+ }
8696
8856
  finish({
8697
8857
  status: "failed",
8698
8858
  result: {
@@ -8703,6 +8863,10 @@ async function invokeStartExecutionRefine(ctx, deps = {}) {
8703
8863
  child.on("close", (code) => {
8704
8864
  void (async () => {
8705
8865
  if (ctx.keyRun) stdout2 = await settleKeyRun(ctx, ctx.keyRun, stdout2);
8866
+ if (cancelled) {
8867
+ finish(cancelledRunResult("planner"));
8868
+ return;
8869
+ }
8706
8870
  const combined = `${stdout2}
8707
8871
  ${stderr}`;
8708
8872
  const review = detectNeedsHumanReview(combined);
@@ -8762,6 +8926,26 @@ ${stderr}`;
8762
8926
  var ORCHESTRATOR_RUN_TIMEOUT_MS = 3 * 60 * 60 * 1e3;
8763
8927
  var ORCHESTRATOR_HEARTBEAT_INTERVAL_MS = PLANNER_HEARTBEAT_INTERVAL_MS;
8764
8928
  var HEADLESS_ORCHESTRATE_REMINDER = "This is a non-interactive run: do NOT start sub-agents or reviews in the background and do not end your turn to wait for them. Run every step in this process and keep going until every feature is done or a hard gate stops the run.";
8929
+ var FIX_RUN_RULES = [
8930
+ "You are making a focused change to an open pull request, in a checkout of its branch. This is a non-interactive run.",
8931
+ "- Do only what the instructions below ask. Do not execute the epic's plan or start other work.",
8932
+ "- Never force-push, rebase, reset or otherwise rewrite the branch's existing history.",
8933
+ "- Do not open a new pull request; commits pushed to this branch update the existing one.",
8934
+ "- Run the project's tests before finishing, and fix anything your change broke.",
8935
+ "- Do not start sub-agents or reviews in the background, and do not end your turn to wait for them."
8936
+ ].join("\n");
8937
+ function buildFixArgs(fix) {
8938
+ return [
8939
+ "-p",
8940
+ `${FIX_RUN_RULES}
8941
+
8942
+ ${fix.instructions}`,
8943
+ "--append-system-prompt",
8944
+ HEADLESS_ORCHESTRATE_REMINDER,
8945
+ "--permission-mode",
8946
+ "bypassPermissions"
8947
+ ];
8948
+ }
8765
8949
  var ORCHESTRATOR_FINAL_TURN_MAX_CHARS = 4e3;
8766
8950
  function buildOrchestratorArgs(epicId) {
8767
8951
  return [
@@ -8832,6 +9016,9 @@ function buildIncompleteRunResult(epicId, progress) {
8832
9016
  };
8833
9017
  }
8834
9018
  function describeRunBranch(finish) {
9019
+ if (finish.cancelled) {
9020
+ return `Cancelled: nothing was pushed. The work is kept in ${finish.keptWorktree ?? "its run folder"} on branch ${finish.branch}.`;
9021
+ }
8835
9022
  if (finish.needsAttention) {
8836
9023
  return `Needs attention: the run's work was kept in ${finish.keptWorktree ?? "its run folder"} (branch ${finish.branch}) because it couldn't all be committed.`;
8837
9024
  }
@@ -8862,6 +9049,7 @@ function buildOrchestrateNeedsReviewResult(epicId, marker) {
8862
9049
  };
8863
9050
  }
8864
9051
  async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
9052
+ if (ctx.signal?.aborted) return cancelledRunResult("orchestrator");
8865
9053
  const spawnImpl = deps.spawnImpl ?? spawn3;
8866
9054
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
8867
9055
  const worktreeCapable = deps.worktreeCapable ?? defaultWorktreeCapable;
@@ -8885,7 +9073,7 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8885
9073
  let workspace = null;
8886
9074
  let workspaceNotes = [];
8887
9075
  if (deps.workspace) {
8888
- const prepared = await deps.workspace.prepare(projectDir, ctx.epicId);
9076
+ const prepared = ctx.fix ? await deps.workspace.prepare(projectDir, ctx.epicId, { branch: ctx.fix.branch }) : await deps.workspace.prepare(projectDir, ctx.epicId);
8889
9077
  if (!prepared.ok) {
8890
9078
  return { status: "failed", result: { error: prepared.error } };
8891
9079
  }
@@ -8895,7 +9083,8 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8895
9083
  const runDir = workspace?.dir ?? projectDir;
8896
9084
  const routing = await resolveRoutingImpl();
8897
9085
  const command = resolveClaudeBinary() ?? "claude";
8898
- const args = ctx.keyRun ? keyRunArgs(buildOrchestratorArgs(ctx.epicId)) : buildOrchestratorArgs(ctx.epicId);
9086
+ const runArgs = ctx.fix ? buildFixArgs(ctx.fix) : buildOrchestratorArgs(ctx.epicId);
9087
+ const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
8899
9088
  const routedEnv = claudeSpawnEnv(process.env, routing);
8900
9089
  const baseEnv = {
8901
9090
  ...routedEnv,
@@ -8910,7 +9099,7 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8910
9099
  await ctx.mailboxClient.postTurn(
8911
9100
  ctx.machineToken,
8912
9101
  ctx.jobId,
8913
- `Started the orchestrator for epic ${ctx.epicId} (headless, non-interactive). This executes the full epic \u2014 every phase and feature \u2014 and may take a long time.` + (workspace ? workspace.continued ? ` Continuing the earlier unfinished work on ${workspace.branch}, which ends as a pull request into ${workspace.baseBranch}.` : ` Working on a new branch, ${workspace.branch}, which will end as a pull request into ${workspace.baseBranch}.` : "") + (workspaceNotes.length > 0 ? ` Note: ${workspaceNotes.join(" ")}` : "")
9102
+ (ctx.fix ? `Started a fix run on the pull request's branch ${ctx.fix.branch}${ctx.fix.pullRequestUrl ? ` (${ctx.fix.pullRequestUrl})` : ""}. New commits are pushed to the same branch, so the existing pull request updates.` : `Started the orchestrator for epic ${ctx.epicId} (headless, non-interactive). This executes the full epic \u2014 every phase and feature \u2014 and may take a long time.` + (workspace ? workspace.continued ? ` Continuing the earlier unfinished work on ${workspace.branch}, which ends as a pull request into ${workspace.baseBranch}.` : ` Working on a new branch, ${workspace.branch}, which will end as a pull request into ${workspace.baseBranch}.` : "")) + (workspaceNotes.length > 0 ? ` Note: ${workspaceNotes.join(" ")}` : "")
8914
9103
  );
8915
9104
  } catch {
8916
9105
  }
@@ -8921,8 +9110,22 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8921
9110
  const child = spawnImpl(command, args, {
8922
9111
  cwd: runDir,
8923
9112
  stdio: ["ignore", "pipe", "pipe"],
8924
- env: childEnv
8925
- });
9113
+ env: childEnv,
9114
+ // ENG-300: lead its own process group so a cancel can stop everything it started.
9115
+ ...groupSpawnOptions(deps.processGroup?.platform)
9116
+ });
9117
+ let cancelled = false;
9118
+ const disposeAbort = killGroupOnAbort(
9119
+ ctx.signal,
9120
+ child,
9121
+ () => {
9122
+ cancelled = true;
9123
+ setTimeout(() => {
9124
+ finish(cancelledRunResult("orchestrator"));
9125
+ }, (deps.processGroup?.graceMs ?? CANCEL_GRACE_MS) + 5e3).unref();
9126
+ },
9127
+ deps.processGroup
9128
+ );
8926
9129
  const heartbeatTimer = deps.heartbeat ? setInterval(() => {
8927
9130
  void Promise.resolve(deps.heartbeat?.()).catch(() => {
8928
9131
  });
@@ -8932,10 +9135,11 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8932
9135
  settled = true;
8933
9136
  if (heartbeatTimer) clearInterval(heartbeatTimer);
8934
9137
  clearTimeout(timer);
9138
+ disposeAbort();
8935
9139
  resolve3(result);
8936
9140
  };
8937
9141
  const timer = setTimeout(() => {
8938
- child.kill("SIGKILL");
9142
+ killProcessGroupNow(child, deps.processGroup);
8939
9143
  finish({
8940
9144
  status: "failed",
8941
9145
  result: {
@@ -8950,6 +9154,10 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8950
9154
  stderr += chunk.toString("utf-8");
8951
9155
  });
8952
9156
  child.on("error", (error) => {
9157
+ if (cancelled) {
9158
+ finish(cancelledRunResult("orchestrator"));
9159
+ return;
9160
+ }
8953
9161
  finish({
8954
9162
  status: "failed",
8955
9163
  result: {
@@ -8959,6 +9167,10 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8959
9167
  });
8960
9168
  child.on("close", (code) => {
8961
9169
  if (ctx.keyRun) stdout2 = takeKeyRunResult(ctx, ctx.keyRun, stdout2).text;
9170
+ if (cancelled) {
9171
+ finish(cancelledRunResult("orchestrator"));
9172
+ return;
9173
+ }
8962
9174
  const combined = `${stdout2}
8963
9175
  ${stderr}`;
8964
9176
  const review = detectNeedsHumanReview(combined);
@@ -8978,10 +9190,18 @@ ${stderr}`;
8978
9190
  });
8979
9191
  return;
8980
9192
  }
8981
- finish({ status: "done", result: { epicId: ctx.epicId } });
9193
+ finish({
9194
+ status: "done",
9195
+ result: ctx.fix ? {
9196
+ epicId: ctx.epicId,
9197
+ fix: true,
9198
+ branch: ctx.fix.branch,
9199
+ ...ctx.fix.pullRequestUrl && { prUrl: ctx.fix.pullRequestUrl }
9200
+ } : { epicId: ctx.epicId }
9201
+ });
8982
9202
  });
8983
9203
  });
8984
- if (outcome.status === "done") {
9204
+ if (outcome.status === "done" && !ctx.fix) {
8985
9205
  const readProgress = deps.epicProgress ?? (async () => {
8986
9206
  try {
8987
9207
  const job = await ctx.mailboxClient.postTurn(
@@ -9009,7 +9229,9 @@ ${stderr}`;
9009
9229
  epicId: ctx.epicId,
9010
9230
  jobId: ctx.jobId,
9011
9231
  completed: outcome.status === "done",
9012
- ...stopReason ? { stopReason } : {}
9232
+ ...stopReason ? { stopReason } : {},
9233
+ // ENG-300: a cancelled run keeps its branch and worktree locally — no push, no PR.
9234
+ ...ctx.signal ? { signal: ctx.signal } : {}
9013
9235
  });
9014
9236
  branchLine = describeRunBranch(finished);
9015
9237
  outcome.result = {
@@ -9022,7 +9244,11 @@ ${stderr}`;
9022
9244
  ...finished.notes.length > 0 ? { branchNotes: finished.notes } : {},
9023
9245
  ...finished.keptWorktree ? { keptWorktree: finished.keptWorktree } : {}
9024
9246
  };
9025
- if (finished.needsAttention) {
9247
+ if (finished.cancelled) {
9248
+ outcome.status = "failed";
9249
+ outcome.result = { ...outcome.result, cancelled: true };
9250
+ }
9251
+ if (finished.needsAttention && !finished.cancelled) {
9026
9252
  outcome.status = "failed";
9027
9253
  outcome.result = {
9028
9254
  ...outcome.result,
@@ -9230,8 +9456,13 @@ var RunWorkspaceManager = class {
9230
9456
  return this.run("git", args, cwd);
9231
9457
  }
9232
9458
  /** Creates the branch + worktree for a run. Never touches the person's checkout. */
9233
- async prepare(projectDir, epicId) {
9234
- const created = await withRepoLock(projectDir, () => this.createWorktree(projectDir, epicId));
9459
+ /**
9460
+ * `opts.branch` makes this a fix run (ENG-296): work on that existing,
9461
+ * pushed branch (an open pull request's head) instead of a new one, and fail
9462
+ * rather than fall back to a fresh branch when it can't be checked out.
9463
+ */
9464
+ async prepare(projectDir, epicId, opts = {}) {
9465
+ const created = await withRepoLock(projectDir, () => this.createWorktree(projectDir, epicId, opts));
9235
9466
  if (!created.ok) return created;
9236
9467
  const { workspace, notes } = created;
9237
9468
  const { dir, branch } = workspace;
@@ -9280,12 +9511,16 @@ var RunWorkspaceManager = class {
9280
9511
  const ref = await this.git(["update-ref", "refs/heads/main", sha, ""], projectDir);
9281
9512
  if (ref.status !== 0) return fail("create the main branch", ref);
9282
9513
  await this.git(["symbolic-ref", "HEAD", "refs/heads/main"], projectDir);
9283
- if (!remote) return { ok: true, note: "The repository had no commits, so CompBox started main with an empty first commit." };
9514
+ if (!remote)
9515
+ return {
9516
+ ok: true,
9517
+ note: "The repository had no commits, so CompBox started main with an empty first commit."
9518
+ };
9284
9519
  const push = await this.git(["push", remote, "main"], projectDir);
9285
9520
  if (push.status !== 0) return fail(`push its first commit to ${remote}`, push);
9286
9521
  return { ok: true, note: `The repository had no commits, so CompBox started main with an empty first commit and pushed it to ${remote}.` };
9287
9522
  }
9288
- async createWorktree(projectDir, epicId) {
9523
+ async createWorktree(projectDir, epicId, opts = {}) {
9289
9524
  const notes = [];
9290
9525
  const remotes = (await this.git(["remote"], projectDir)).stdout.split("\n").map((r) => r.trim()).filter(Boolean);
9291
9526
  const remote = remotes.includes("origin") ? "origin" : remotes[0] ?? null;
@@ -9320,7 +9555,25 @@ var RunWorkspaceManager = class {
9320
9555
  mkdirSync6(this.runsRoot, { recursive: true });
9321
9556
  let branch = `compbox/epic-${slugForBranch(epicId)}-${when}`;
9322
9557
  let continued = false;
9323
- const previous = remote ? await this.unfinishedBranch(remote, slugForBranch(epicId), baseRef, projectDir) : null;
9558
+ if (opts.branch) {
9559
+ const target = opts.branch;
9560
+ const missing = (why) => ({
9561
+ ok: false,
9562
+ error: [
9563
+ `Couldn't open the pull request's branch ${target}: ${why}`,
9564
+ "The fix was not started, and your project folder was not changed."
9565
+ ].join("\n")
9566
+ });
9567
+ if (!remote) return missing("this project folder has no remote to fetch it from.");
9568
+ if ((await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${target}`], projectDir)).status !== 0) {
9569
+ return missing(`it isn't on ${remote} (was the pull request closed or the branch deleted?).`);
9570
+ }
9571
+ const checkout = await this.git(["worktree", "add", "-B", target, dir, `${remote}/${target}`], projectDir);
9572
+ if (checkout.status !== 0) return missing(gitReason(checkout.stderr) || "unknown error");
9573
+ branch = target;
9574
+ continued = true;
9575
+ }
9576
+ const previous = !opts.branch && remote ? await this.unfinishedBranch(remote, slugForBranch(epicId), baseRef, projectDir) : null;
9324
9577
  if (remote && previous) {
9325
9578
  const resume = await this.git(["worktree", "add", "-B", previous, dir, `${remote}/${previous}`], projectDir);
9326
9579
  if (resume.status === 0) {
@@ -9357,7 +9610,11 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9357
9610
  notes.push(`Couldn't copy ${path3} into the run workspace.`);
9358
9611
  }
9359
9612
  }
9360
- return { ok: true, workspace: { dir, projectDir, branch, baseRef, baseBranch, remote, continued }, notes };
9613
+ return {
9614
+ ok: true,
9615
+ workspace: { dir, projectDir, branch, baseRef, baseBranch, remote, continued },
9616
+ notes
9617
+ };
9361
9618
  }
9362
9619
  /** The newest pushed run branch for this epic that isn't merged into the base yet, if any. */
9363
9620
  async unfinishedBranch(remote, epicSlug, baseRef, projectDir) {
@@ -9370,6 +9627,19 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9370
9627
  if ((await this.git(["merge-base", "--is-ancestor", latest, baseRef], projectDir)).status === 0) return null;
9371
9628
  return latest.slice(remote.length + 1);
9372
9629
  }
9630
+ /** A cancelled run's result: the branch and worktree are kept locally, untouched. */
9631
+ async keepCancelled(ws, notes, commits) {
9632
+ const count = commits ?? (Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0);
9633
+ notes.push(`The run was cancelled, so nothing was pushed. Its work is kept in ${ws.dir} on branch ${ws.branch}.`);
9634
+ return {
9635
+ branch: ws.branch,
9636
+ commits: count,
9637
+ pushed: false,
9638
+ keptWorktree: ws.dir,
9639
+ cancelled: true,
9640
+ notes
9641
+ };
9642
+ }
9373
9643
  /** Commits, pushes and opens the pull request; then cleans up the worktree. */
9374
9644
  finish(input) {
9375
9645
  return withRepoLock(input.workspace.projectDir, () => this.finishLocked(input));
@@ -9377,6 +9647,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9377
9647
  async finishLocked(input) {
9378
9648
  const { workspace: ws } = input;
9379
9649
  const notes = [];
9650
+ if (input.signal?.aborted) return this.keepCancelled(ws, notes);
9380
9651
  const dirtyBefore = await this.isDirty(ws.dir);
9381
9652
  let commitFailed = false;
9382
9653
  if (dirtyBefore) {
@@ -9418,6 +9689,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9418
9689
  );
9419
9690
  return base;
9420
9691
  }
9692
+ if (input.signal?.aborted) return this.keepCancelled(ws, notes, commits);
9421
9693
  const push = await this.git(["push", "--set-upstream", ws.remote, ws.branch], ws.dir);
9422
9694
  if (push.status !== 0) {
9423
9695
  notes.push(
@@ -9699,20 +9971,84 @@ async function safeProbeAgentRuntime(probe, previous, log = (m) => {
9699
9971
  }
9700
9972
  async function runHeartbeatCycle(deps) {
9701
9973
  const runtime = await safeProbeAgentRuntime(deps.probe, deps.previous, deps.log);
9974
+ let result;
9702
9975
  try {
9703
9976
  if (deps.servicedRemotes !== void 0) {
9704
- await deps.client.heartbeat(deps.machineToken, runtime, deps.servicedRemotes);
9977
+ result = await deps.client.heartbeat(deps.machineToken, runtime, deps.servicedRemotes);
9705
9978
  } else {
9706
- await deps.client.heartbeat(deps.machineToken, runtime);
9979
+ result = await deps.client.heartbeat(deps.machineToken, runtime);
9707
9980
  }
9708
- return { runtime, sent: true };
9709
9981
  } catch {
9710
9982
  return { runtime, sent: false };
9711
9983
  }
9984
+ deps.onCancelJobIds?.(cancelIdsOf(result));
9985
+ return { runtime, sent: true };
9986
+ }
9987
+ function cancelIdsOf(result) {
9988
+ return parseCancelJobIds(result);
9989
+ }
9990
+ var CancelRegistry = class {
9991
+ constructor(log = (m) => {
9992
+ console.log(m);
9993
+ }) {
9994
+ this.log = log;
9995
+ }
9996
+ controllers = /* @__PURE__ */ new Map();
9997
+ /** Starts tracking a job; returns the signal its work should honor. */
9998
+ register(jobId) {
9999
+ const controller = new AbortController();
10000
+ this.controllers.set(jobId, controller);
10001
+ return controller.signal;
10002
+ }
10003
+ /** Stops tracking a job (call from a `finally` so entries never leak). */
10004
+ release(jobId) {
10005
+ this.controllers.delete(jobId);
10006
+ }
10007
+ /** Whether a job is currently tracked. */
10008
+ has(jobId) {
10009
+ return this.controllers.has(jobId);
10010
+ }
10011
+ /** Number of tracked jobs. */
10012
+ get size() {
10013
+ return this.controllers.size;
10014
+ }
10015
+ /**
10016
+ * Aborts every tracked job listed in `ids`. Returns the ids aborted by THIS
10017
+ * call (already-aborted and unknown ids are skipped).
10018
+ */
10019
+ handleCancelIds(ids) {
10020
+ const aborted = [];
10021
+ for (const id of ids) {
10022
+ const controller = this.controllers.get(id);
10023
+ if (!controller || controller.signal.aborted) continue;
10024
+ controller.abort(new Error("Job cancelled"));
10025
+ aborted.push(id);
10026
+ this.log(chalk9.yellow(` Job ${id}: cancel requested \u2014 stopping it.`));
10027
+ }
10028
+ return aborted;
10029
+ }
10030
+ };
10031
+ async function jobHeartbeat(ctx, servicedRemotes) {
10032
+ try {
10033
+ const result = servicedRemotes !== void 0 ? await ctx.client.heartbeat(ctx.machineToken, void 0, servicedRemotes) : await ctx.client.heartbeat(ctx.machineToken);
10034
+ ctx.onCancelJobIds?.(cancelIdsOf(result));
10035
+ } catch {
10036
+ }
9712
10037
  }
9713
10038
  function gatherServicedRemotes() {
9714
10039
  return listProjectDirs().map((dir) => dir.remote);
9715
10040
  }
10041
+ function parseFix(raw) {
10042
+ if (!raw || typeof raw !== "object") return void 0;
10043
+ const f = raw;
10044
+ const branch = typeof f.branch === "string" ? f.branch.trim() : "";
10045
+ const instructions = typeof f.instructions === "string" ? f.instructions.trim() : "";
10046
+ if (!instructions || !/^[A-Za-z0-9._/-]+$/.test(branch) || branch.startsWith("-") || branch.includes("..")) {
10047
+ return void 0;
10048
+ }
10049
+ const pullRequestUrl = typeof f.pullRequestUrl === "string" && f.pullRequestUrl.startsWith("https://") ? f.pullRequestUrl : void 0;
10050
+ return { branch, instructions, ...pullRequestUrl && { pullRequestUrl } };
10051
+ }
9716
10052
  function parseStartExecutionPayload(payload) {
9717
10053
  let parsed = payload;
9718
10054
  if (typeof payload === "string") {
@@ -9728,10 +10064,23 @@ function parseStartExecutionPayload(payload) {
9728
10064
  const projectRemote = typeof p.projectRemote === "string" && p.projectRemote.length > 0 ? p.projectRemote : void 0;
9729
10065
  const useAiKey = p.useAiKey === true;
9730
10066
  if (p.kind === "plan" && typeof p.epicRequestId === "string" && p.epicRequestId.length > 0) {
9731
- return { kind: "plan", epicRequestId: p.epicRequestId, ...projectRemote && { projectRemote }, ...useAiKey && { useAiKey } };
10067
+ return {
10068
+ kind: "plan",
10069
+ epicRequestId: p.epicRequestId,
10070
+ ...projectRemote && { projectRemote },
10071
+ ...useAiKey && { useAiKey }
10072
+ };
9732
10073
  }
9733
10074
  if (p.kind === "orchestrate" && typeof p.epicId === "string" && p.epicId.length > 0) {
9734
- return { kind: "orchestrate", epicId: p.epicId, ...projectRemote && { projectRemote }, ...useAiKey && { useAiKey } };
10075
+ const fix = parseFix(p.fix);
10076
+ if (p.fix !== void 0 && !fix) return null;
10077
+ return {
10078
+ kind: "orchestrate",
10079
+ epicId: p.epicId,
10080
+ ...projectRemote && { projectRemote },
10081
+ ...useAiKey && { useAiKey },
10082
+ ...fix && { fix }
10083
+ };
9735
10084
  }
9736
10085
  if (p.kind === "refine" && typeof p.epicId === "string" && p.epicId.length > 0) {
9737
10086
  const notes = typeof p.notes === "string" && p.notes.trim().length > 0 ? p.notes : void 0;
@@ -9796,6 +10145,7 @@ async function handleStartExecution(ctx, job) {
9796
10145
  mailboxClient: ctx.client,
9797
10146
  machineToken: ctx.machineToken,
9798
10147
  jobId: job.id,
10148
+ ...ctx.signal && { signal: ctx.signal },
9799
10149
  apiBaseUrl: ctx.apiBaseUrl,
9800
10150
  userApiToken: userApiToken2,
9801
10151
  epicRequestId: payload.epicRequestId,
@@ -9805,7 +10155,7 @@ async function handleStartExecution(ctx, job) {
9805
10155
  {
9806
10156
  // H4: keep this machine online during the long planner run — the poll
9807
10157
  // loop (its own heartbeat) is blocked for the whole job.
9808
- heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0)
10158
+ heartbeat: () => jobHeartbeat(ctx)
9809
10159
  }
9810
10160
  )
9811
10161
  );
@@ -9830,6 +10180,7 @@ async function handleStartExecution(ctx, job) {
9830
10180
  mailboxClient: ctx.client,
9831
10181
  machineToken: ctx.machineToken,
9832
10182
  jobId: job.id,
10183
+ ...ctx.signal && { signal: ctx.signal },
9833
10184
  apiBaseUrl: ctx.apiBaseUrl,
9834
10185
  userApiToken: userApiToken2,
9835
10186
  epicId: payload.epicId,
@@ -9838,7 +10189,7 @@ async function handleStartExecution(ctx, job) {
9838
10189
  ...keyRun && { keyRun }
9839
10190
  },
9840
10191
  {
9841
- heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0)
10192
+ heartbeat: () => jobHeartbeat(ctx)
9842
10193
  }
9843
10194
  )
9844
10195
  );
@@ -9862,14 +10213,16 @@ async function handleStartExecution(ctx, job) {
9862
10213
  mailboxClient: ctx.client,
9863
10214
  machineToken: ctx.machineToken,
9864
10215
  jobId: job.id,
10216
+ ...ctx.signal && { signal: ctx.signal },
9865
10217
  epicId: payload.epicId,
9866
10218
  projectDir: jobProjectDir,
9867
- ...keyRun && { keyRun }
10219
+ ...keyRun && { keyRun },
10220
+ ...payload.fix && { fix: payload.fix }
9868
10221
  },
9869
10222
  {
9870
10223
  // H4: keep this machine online during the long orchestrator run — the
9871
10224
  // poll loop (its own heartbeat) is blocked for the whole job.
9872
- heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0),
10225
+ heartbeat: () => jobHeartbeat(ctx),
9873
10226
  // Own branch + worktree per run, finishing with a pull request (opened
9874
10227
  // through CompBox's GitHub app when the project is connected to it).
9875
10228
  workspace: new RunWorkspaceManager({
@@ -9936,7 +10289,7 @@ async function handleJob(ctx, job) {
9936
10289
  await runInvokerAndComplete(ctx, job, async () => {
9937
10290
  const outcome = await invokeConnectRepo(job.payload);
9938
10291
  if (outcome.status === "done") {
9939
- await ctx.client.heartbeat(ctx.machineToken, void 0, gatherServicedRemotes()).catch(() => void 0);
10292
+ await jobHeartbeat(ctx, gatherServicedRemotes());
9940
10293
  }
9941
10294
  return outcome;
9942
10295
  });
@@ -10008,12 +10361,17 @@ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error
10008
10361
  }
10009
10362
  const waitMs = options.waitMs ? Number.parseInt(options.waitMs, 10) : POLL_WAIT_MS;
10010
10363
  const client = new MailboxClient(config.apiBaseUrl);
10364
+ const cancels = new CancelRegistry();
10365
+ const handleCancelIds = (ids) => {
10366
+ cancels.handleCancelIds(ids);
10367
+ };
10011
10368
  const jobContext = {
10012
10369
  client,
10013
10370
  machineToken,
10014
10371
  apiBaseUrl: config.apiBaseUrl,
10015
10372
  aiMode: config.aiMode,
10016
- userApiToken: config.apiToken
10373
+ userApiToken: config.apiToken,
10374
+ onCancelJobIds: handleCancelIds
10017
10375
  };
10018
10376
  const folders = config.projectDirs ?? [];
10019
10377
  const legacyDir = unusedLegacyProjectDir(config);
@@ -10052,8 +10410,9 @@ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error
10052
10410
  let lastRuntimeSentAt = 0;
10053
10411
  if (agentRuntime) {
10054
10412
  try {
10055
- await client.heartbeat(machineToken, agentRuntime, gatherServicedRemotes());
10413
+ const result = await client.heartbeat(machineToken, agentRuntime, gatherServicedRemotes());
10056
10414
  lastRuntimeSentAt = Date.now();
10415
+ handleCancelIds(cancelIdsOf(result));
10057
10416
  } catch {
10058
10417
  }
10059
10418
  }
@@ -10077,9 +10436,12 @@ Received ${signal}, shutting down...`));
10077
10436
  const inFlight = /* @__PURE__ */ new Map();
10078
10437
  do {
10079
10438
  let job = null;
10439
+ let pollCancelIds = [];
10080
10440
  try {
10081
10441
  if (inFlight.size < maxJobs) {
10082
- job = await client.nextJob(machineToken, waitMs, [...inFlight.keys()]);
10442
+ const polled = await client.pollNextJob(machineToken, waitMs, [...inFlight.keys()]);
10443
+ job = polled.job;
10444
+ pollCancelIds = polled.cancelJobIds;
10083
10445
  }
10084
10446
  consecutiveErrors = 0;
10085
10447
  } catch (error) {
@@ -10101,15 +10463,18 @@ Received ${signal}, shutting down...`));
10101
10463
  if (job) {
10102
10464
  const jobId = job.id;
10103
10465
  const isConversation = job.type === "epic_request";
10104
- const work = handleJob(jobContext, job).catch((error) => {
10466
+ const signal = cancels.register(jobId);
10467
+ const work = handleJob({ ...jobContext, signal }, job).catch((error) => {
10105
10468
  console.error(chalk9.red(` Job ${jobId} stopped unexpectedly: ${error instanceof Error ? error.message : String(error)}`));
10106
10469
  }).finally(() => {
10107
10470
  inFlight.delete(jobId);
10471
+ cancels.release(jobId);
10108
10472
  lastJobAt = Date.now();
10109
10473
  if (isConversation) lastConversationAt = lastJobAt;
10110
10474
  });
10111
10475
  inFlight.set(jobId, work);
10112
10476
  }
10477
+ handleCancelIds(pollCancelIds);
10113
10478
  if (runtimeHeartbeatDue(Date.now(), lastRuntimeSentAt)) {
10114
10479
  const cycle = await runHeartbeatCycle({
10115
10480
  client,
@@ -10118,7 +10483,8 @@ Received ${signal}, shutting down...`));
10118
10483
  previous: agentRuntime,
10119
10484
  // Re-read the allowlist each cycle so `machines dirs` edits between
10120
10485
  // polls are reflected without a daemon restart (ENG-177).
10121
- servicedRemotes: gatherServicedRemotes()
10486
+ servicedRemotes: gatherServicedRemotes(),
10487
+ onCancelJobIds: handleCancelIds
10122
10488
  });
10123
10489
  agentRuntime = cycle.runtime;
10124
10490
  if (cycle.sent) {
@@ -10520,6 +10886,10 @@ async function runWorkspace(deps = {}) {
10520
10886
  return 1;
10521
10887
  };
10522
10888
  const payload = job.payload ?? {};
10889
+ const fix = payload.kind === "orchestrate" ? parseFix(payload.fix) : void 0;
10890
+ if (payload.fix !== void 0 && !fix) {
10891
+ return fail("This fix job's pull request details couldn't be read, so nothing was run.");
10892
+ }
10523
10893
  const repoDir = join12(workDir, "repo");
10524
10894
  let userApiToken;
10525
10895
  let keyRun;
@@ -10551,7 +10921,23 @@ async function runWorkspace(deps = {}) {
10551
10921
  } catch (error) {
10552
10922
  return fail(`Setting up the cloud workspace failed: ${error instanceof Error ? error.message : String(error)}`);
10553
10923
  }
10554
- const heartbeat = () => client.heartbeat(env.token).then(() => void 0).catch(() => void 0);
10924
+ const controller = new AbortController();
10925
+ const heartbeat = () => client.heartbeat(env.token).then((res) => {
10926
+ const ids = res?.cancelJobIds;
10927
+ if (Array.isArray(ids) && ids.includes(job.id) && !controller.signal.aborted) {
10928
+ controller.abort(new Error("Job cancelled"));
10929
+ }
10930
+ }).catch(() => void 0);
10931
+ const cancelled = () => controller.signal.aborted;
10932
+ const finishCancelled = async () => {
10933
+ const { result } = cancelledRunResult("workspace");
10934
+ await client.completeJob(env.token, job.id, "failed", result).catch(() => void 0);
10935
+ console.log(chalk14.yellow("Cancelled."));
10936
+ return 1;
10937
+ };
10938
+ await heartbeat();
10939
+ if (cancelled()) return finishCancelled();
10940
+ const signal = controller.signal;
10555
10941
  let outcome;
10556
10942
  if (payload.kind === "plan" && payload.epicRequestId) {
10557
10943
  outcome = await (deps.plan ?? invokeStartExecutionPlan)(
@@ -10563,7 +10949,8 @@ async function runWorkspace(deps = {}) {
10563
10949
  userApiToken,
10564
10950
  epicRequestId: payload.epicRequestId,
10565
10951
  projectDir: repoDir,
10566
- keyRun
10952
+ keyRun,
10953
+ signal
10567
10954
  },
10568
10955
  { heartbeat }
10569
10956
  );
@@ -10575,7 +10962,9 @@ async function runWorkspace(deps = {}) {
10575
10962
  jobId: job.id,
10576
10963
  epicId: payload.epicId,
10577
10964
  projectDir: repoDir,
10578
- keyRun
10965
+ keyRun,
10966
+ signal,
10967
+ ...fix && { fix }
10579
10968
  },
10580
10969
  {
10581
10970
  heartbeat,
@@ -10595,13 +10984,15 @@ async function runWorkspace(deps = {}) {
10595
10984
  epicId: payload.epicId,
10596
10985
  notes: typeof payload.notes === "string" ? payload.notes : void 0,
10597
10986
  projectDir: repoDir,
10598
- keyRun
10987
+ keyRun,
10988
+ signal
10599
10989
  },
10600
10990
  { heartbeat }
10601
10991
  );
10602
10992
  } else {
10603
10993
  return fail("The job is missing what to plan or build.");
10604
10994
  }
10995
+ if (cancelled()) return finishCancelled();
10605
10996
  await client.completeJob(env.token, job.id, outcome.status, outcome.result);
10606
10997
  console.log(outcome.status === "done" ? chalk14.green("Finished.") : chalk14.yellow(`Stopped: ${JSON.stringify(outcome.result)}`));
10607
10998
  return outcome.status === "done" ? 0 : 1;
@@ -10708,7 +11099,7 @@ ${error instanceof Error ? error.message : String(error)}`));
10708
11099
  // src/index.ts
10709
11100
  function resolveCliVersion() {
10710
11101
  if (true) {
10711
- return "1.21.5";
11102
+ return "1.21.7";
10712
11103
  }
10713
11104
  const require2 = createRequire(import.meta.url);
10714
11105
  const pkg = require2("../package.json");