@mycompbox/compbox-cli 1.21.6 → 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);
@@ -8852,6 +9016,9 @@ function buildIncompleteRunResult(epicId, progress) {
8852
9016
  };
8853
9017
  }
8854
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
+ }
8855
9022
  if (finish.needsAttention) {
8856
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.`;
8857
9024
  }
@@ -8882,6 +9049,7 @@ function buildOrchestrateNeedsReviewResult(epicId, marker) {
8882
9049
  };
8883
9050
  }
8884
9051
  async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
9052
+ if (ctx.signal?.aborted) return cancelledRunResult("orchestrator");
8885
9053
  const spawnImpl = deps.spawnImpl ?? spawn3;
8886
9054
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
8887
9055
  const worktreeCapable = deps.worktreeCapable ?? defaultWorktreeCapable;
@@ -8942,8 +9110,22 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8942
9110
  const child = spawnImpl(command, args, {
8943
9111
  cwd: runDir,
8944
9112
  stdio: ["ignore", "pipe", "pipe"],
8945
- env: childEnv
8946
- });
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
+ );
8947
9129
  const heartbeatTimer = deps.heartbeat ? setInterval(() => {
8948
9130
  void Promise.resolve(deps.heartbeat?.()).catch(() => {
8949
9131
  });
@@ -8953,10 +9135,11 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8953
9135
  settled = true;
8954
9136
  if (heartbeatTimer) clearInterval(heartbeatTimer);
8955
9137
  clearTimeout(timer);
9138
+ disposeAbort();
8956
9139
  resolve3(result);
8957
9140
  };
8958
9141
  const timer = setTimeout(() => {
8959
- child.kill("SIGKILL");
9142
+ killProcessGroupNow(child, deps.processGroup);
8960
9143
  finish({
8961
9144
  status: "failed",
8962
9145
  result: {
@@ -8971,6 +9154,10 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8971
9154
  stderr += chunk.toString("utf-8");
8972
9155
  });
8973
9156
  child.on("error", (error) => {
9157
+ if (cancelled) {
9158
+ finish(cancelledRunResult("orchestrator"));
9159
+ return;
9160
+ }
8974
9161
  finish({
8975
9162
  status: "failed",
8976
9163
  result: {
@@ -8980,6 +9167,10 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
8980
9167
  });
8981
9168
  child.on("close", (code) => {
8982
9169
  if (ctx.keyRun) stdout2 = takeKeyRunResult(ctx, ctx.keyRun, stdout2).text;
9170
+ if (cancelled) {
9171
+ finish(cancelledRunResult("orchestrator"));
9172
+ return;
9173
+ }
8983
9174
  const combined = `${stdout2}
8984
9175
  ${stderr}`;
8985
9176
  const review = detectNeedsHumanReview(combined);
@@ -9001,7 +9192,12 @@ ${stderr}`;
9001
9192
  }
9002
9193
  finish({
9003
9194
  status: "done",
9004
- result: ctx.fix ? { epicId: ctx.epicId, fix: true, branch: ctx.fix.branch, ...ctx.fix.pullRequestUrl && { prUrl: ctx.fix.pullRequestUrl } } : { epicId: ctx.epicId }
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 }
9005
9201
  });
9006
9202
  });
9007
9203
  });
@@ -9033,7 +9229,9 @@ ${stderr}`;
9033
9229
  epicId: ctx.epicId,
9034
9230
  jobId: ctx.jobId,
9035
9231
  completed: outcome.status === "done",
9036
- ...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 } : {}
9037
9235
  });
9038
9236
  branchLine = describeRunBranch(finished);
9039
9237
  outcome.result = {
@@ -9046,7 +9244,11 @@ ${stderr}`;
9046
9244
  ...finished.notes.length > 0 ? { branchNotes: finished.notes } : {},
9047
9245
  ...finished.keptWorktree ? { keptWorktree: finished.keptWorktree } : {}
9048
9246
  };
9049
- 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) {
9050
9252
  outcome.status = "failed";
9051
9253
  outcome.result = {
9052
9254
  ...outcome.result,
@@ -9309,7 +9511,11 @@ var RunWorkspaceManager = class {
9309
9511
  const ref = await this.git(["update-ref", "refs/heads/main", sha, ""], projectDir);
9310
9512
  if (ref.status !== 0) return fail("create the main branch", ref);
9311
9513
  await this.git(["symbolic-ref", "HEAD", "refs/heads/main"], projectDir);
9312
- 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
+ };
9313
9519
  const push = await this.git(["push", remote, "main"], projectDir);
9314
9520
  if (push.status !== 0) return fail(`push its first commit to ${remote}`, push);
9315
9521
  return { ok: true, note: `The repository had no commits, so CompBox started main with an empty first commit and pushed it to ${remote}.` };
@@ -9404,7 +9610,11 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9404
9610
  notes.push(`Couldn't copy ${path3} into the run workspace.`);
9405
9611
  }
9406
9612
  }
9407
- 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
+ };
9408
9618
  }
9409
9619
  /** The newest pushed run branch for this epic that isn't merged into the base yet, if any. */
9410
9620
  async unfinishedBranch(remote, epicSlug, baseRef, projectDir) {
@@ -9417,6 +9627,19 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9417
9627
  if ((await this.git(["merge-base", "--is-ancestor", latest, baseRef], projectDir)).status === 0) return null;
9418
9628
  return latest.slice(remote.length + 1);
9419
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
+ }
9420
9643
  /** Commits, pushes and opens the pull request; then cleans up the worktree. */
9421
9644
  finish(input) {
9422
9645
  return withRepoLock(input.workspace.projectDir, () => this.finishLocked(input));
@@ -9424,6 +9647,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9424
9647
  async finishLocked(input) {
9425
9648
  const { workspace: ws } = input;
9426
9649
  const notes = [];
9650
+ if (input.signal?.aborted) return this.keepCancelled(ws, notes);
9427
9651
  const dirtyBefore = await this.isDirty(ws.dir);
9428
9652
  let commitFailed = false;
9429
9653
  if (dirtyBefore) {
@@ -9465,6 +9689,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
9465
9689
  );
9466
9690
  return base;
9467
9691
  }
9692
+ if (input.signal?.aborted) return this.keepCancelled(ws, notes, commits);
9468
9693
  const push = await this.git(["push", "--set-upstream", ws.remote, ws.branch], ws.dir);
9469
9694
  if (push.status !== 0) {
9470
9695
  notes.push(
@@ -9746,16 +9971,69 @@ async function safeProbeAgentRuntime(probe, previous, log = (m) => {
9746
9971
  }
9747
9972
  async function runHeartbeatCycle(deps) {
9748
9973
  const runtime = await safeProbeAgentRuntime(deps.probe, deps.previous, deps.log);
9974
+ let result;
9749
9975
  try {
9750
9976
  if (deps.servicedRemotes !== void 0) {
9751
- await deps.client.heartbeat(deps.machineToken, runtime, deps.servicedRemotes);
9977
+ result = await deps.client.heartbeat(deps.machineToken, runtime, deps.servicedRemotes);
9752
9978
  } else {
9753
- await deps.client.heartbeat(deps.machineToken, runtime);
9979
+ result = await deps.client.heartbeat(deps.machineToken, runtime);
9754
9980
  }
9755
- return { runtime, sent: true };
9756
9981
  } catch {
9757
9982
  return { runtime, sent: false };
9758
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
+ }
9759
10037
  }
9760
10038
  function gatherServicedRemotes() {
9761
10039
  return listProjectDirs().map((dir) => dir.remote);
@@ -9786,7 +10064,12 @@ function parseStartExecutionPayload(payload) {
9786
10064
  const projectRemote = typeof p.projectRemote === "string" && p.projectRemote.length > 0 ? p.projectRemote : void 0;
9787
10065
  const useAiKey = p.useAiKey === true;
9788
10066
  if (p.kind === "plan" && typeof p.epicRequestId === "string" && p.epicRequestId.length > 0) {
9789
- 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
+ };
9790
10073
  }
9791
10074
  if (p.kind === "orchestrate" && typeof p.epicId === "string" && p.epicId.length > 0) {
9792
10075
  const fix = parseFix(p.fix);
@@ -9862,6 +10145,7 @@ async function handleStartExecution(ctx, job) {
9862
10145
  mailboxClient: ctx.client,
9863
10146
  machineToken: ctx.machineToken,
9864
10147
  jobId: job.id,
10148
+ ...ctx.signal && { signal: ctx.signal },
9865
10149
  apiBaseUrl: ctx.apiBaseUrl,
9866
10150
  userApiToken: userApiToken2,
9867
10151
  epicRequestId: payload.epicRequestId,
@@ -9871,7 +10155,7 @@ async function handleStartExecution(ctx, job) {
9871
10155
  {
9872
10156
  // H4: keep this machine online during the long planner run — the poll
9873
10157
  // loop (its own heartbeat) is blocked for the whole job.
9874
- heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0)
10158
+ heartbeat: () => jobHeartbeat(ctx)
9875
10159
  }
9876
10160
  )
9877
10161
  );
@@ -9896,6 +10180,7 @@ async function handleStartExecution(ctx, job) {
9896
10180
  mailboxClient: ctx.client,
9897
10181
  machineToken: ctx.machineToken,
9898
10182
  jobId: job.id,
10183
+ ...ctx.signal && { signal: ctx.signal },
9899
10184
  apiBaseUrl: ctx.apiBaseUrl,
9900
10185
  userApiToken: userApiToken2,
9901
10186
  epicId: payload.epicId,
@@ -9904,7 +10189,7 @@ async function handleStartExecution(ctx, job) {
9904
10189
  ...keyRun && { keyRun }
9905
10190
  },
9906
10191
  {
9907
- heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0)
10192
+ heartbeat: () => jobHeartbeat(ctx)
9908
10193
  }
9909
10194
  )
9910
10195
  );
@@ -9928,6 +10213,7 @@ async function handleStartExecution(ctx, job) {
9928
10213
  mailboxClient: ctx.client,
9929
10214
  machineToken: ctx.machineToken,
9930
10215
  jobId: job.id,
10216
+ ...ctx.signal && { signal: ctx.signal },
9931
10217
  epicId: payload.epicId,
9932
10218
  projectDir: jobProjectDir,
9933
10219
  ...keyRun && { keyRun },
@@ -9936,7 +10222,7 @@ async function handleStartExecution(ctx, job) {
9936
10222
  {
9937
10223
  // H4: keep this machine online during the long orchestrator run — the
9938
10224
  // poll loop (its own heartbeat) is blocked for the whole job.
9939
- heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0),
10225
+ heartbeat: () => jobHeartbeat(ctx),
9940
10226
  // Own branch + worktree per run, finishing with a pull request (opened
9941
10227
  // through CompBox's GitHub app when the project is connected to it).
9942
10228
  workspace: new RunWorkspaceManager({
@@ -10003,7 +10289,7 @@ async function handleJob(ctx, job) {
10003
10289
  await runInvokerAndComplete(ctx, job, async () => {
10004
10290
  const outcome = await invokeConnectRepo(job.payload);
10005
10291
  if (outcome.status === "done") {
10006
- await ctx.client.heartbeat(ctx.machineToken, void 0, gatherServicedRemotes()).catch(() => void 0);
10292
+ await jobHeartbeat(ctx, gatherServicedRemotes());
10007
10293
  }
10008
10294
  return outcome;
10009
10295
  });
@@ -10075,12 +10361,17 @@ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error
10075
10361
  }
10076
10362
  const waitMs = options.waitMs ? Number.parseInt(options.waitMs, 10) : POLL_WAIT_MS;
10077
10363
  const client = new MailboxClient(config.apiBaseUrl);
10364
+ const cancels = new CancelRegistry();
10365
+ const handleCancelIds = (ids) => {
10366
+ cancels.handleCancelIds(ids);
10367
+ };
10078
10368
  const jobContext = {
10079
10369
  client,
10080
10370
  machineToken,
10081
10371
  apiBaseUrl: config.apiBaseUrl,
10082
10372
  aiMode: config.aiMode,
10083
- userApiToken: config.apiToken
10373
+ userApiToken: config.apiToken,
10374
+ onCancelJobIds: handleCancelIds
10084
10375
  };
10085
10376
  const folders = config.projectDirs ?? [];
10086
10377
  const legacyDir = unusedLegacyProjectDir(config);
@@ -10119,8 +10410,9 @@ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error
10119
10410
  let lastRuntimeSentAt = 0;
10120
10411
  if (agentRuntime) {
10121
10412
  try {
10122
- await client.heartbeat(machineToken, agentRuntime, gatherServicedRemotes());
10413
+ const result = await client.heartbeat(machineToken, agentRuntime, gatherServicedRemotes());
10123
10414
  lastRuntimeSentAt = Date.now();
10415
+ handleCancelIds(cancelIdsOf(result));
10124
10416
  } catch {
10125
10417
  }
10126
10418
  }
@@ -10144,9 +10436,12 @@ Received ${signal}, shutting down...`));
10144
10436
  const inFlight = /* @__PURE__ */ new Map();
10145
10437
  do {
10146
10438
  let job = null;
10439
+ let pollCancelIds = [];
10147
10440
  try {
10148
10441
  if (inFlight.size < maxJobs) {
10149
- 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;
10150
10445
  }
10151
10446
  consecutiveErrors = 0;
10152
10447
  } catch (error) {
@@ -10168,15 +10463,18 @@ Received ${signal}, shutting down...`));
10168
10463
  if (job) {
10169
10464
  const jobId = job.id;
10170
10465
  const isConversation = job.type === "epic_request";
10171
- const work = handleJob(jobContext, job).catch((error) => {
10466
+ const signal = cancels.register(jobId);
10467
+ const work = handleJob({ ...jobContext, signal }, job).catch((error) => {
10172
10468
  console.error(chalk9.red(` Job ${jobId} stopped unexpectedly: ${error instanceof Error ? error.message : String(error)}`));
10173
10469
  }).finally(() => {
10174
10470
  inFlight.delete(jobId);
10471
+ cancels.release(jobId);
10175
10472
  lastJobAt = Date.now();
10176
10473
  if (isConversation) lastConversationAt = lastJobAt;
10177
10474
  });
10178
10475
  inFlight.set(jobId, work);
10179
10476
  }
10477
+ handleCancelIds(pollCancelIds);
10180
10478
  if (runtimeHeartbeatDue(Date.now(), lastRuntimeSentAt)) {
10181
10479
  const cycle = await runHeartbeatCycle({
10182
10480
  client,
@@ -10185,7 +10483,8 @@ Received ${signal}, shutting down...`));
10185
10483
  previous: agentRuntime,
10186
10484
  // Re-read the allowlist each cycle so `machines dirs` edits between
10187
10485
  // polls are reflected without a daemon restart (ENG-177).
10188
- servicedRemotes: gatherServicedRemotes()
10486
+ servicedRemotes: gatherServicedRemotes(),
10487
+ onCancelJobIds: handleCancelIds
10189
10488
  });
10190
10489
  agentRuntime = cycle.runtime;
10191
10490
  if (cycle.sent) {
@@ -10622,7 +10921,23 @@ async function runWorkspace(deps = {}) {
10622
10921
  } catch (error) {
10623
10922
  return fail(`Setting up the cloud workspace failed: ${error instanceof Error ? error.message : String(error)}`);
10624
10923
  }
10625
- 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;
10626
10941
  let outcome;
10627
10942
  if (payload.kind === "plan" && payload.epicRequestId) {
10628
10943
  outcome = await (deps.plan ?? invokeStartExecutionPlan)(
@@ -10634,7 +10949,8 @@ async function runWorkspace(deps = {}) {
10634
10949
  userApiToken,
10635
10950
  epicRequestId: payload.epicRequestId,
10636
10951
  projectDir: repoDir,
10637
- keyRun
10952
+ keyRun,
10953
+ signal
10638
10954
  },
10639
10955
  { heartbeat }
10640
10956
  );
@@ -10647,6 +10963,7 @@ async function runWorkspace(deps = {}) {
10647
10963
  epicId: payload.epicId,
10648
10964
  projectDir: repoDir,
10649
10965
  keyRun,
10966
+ signal,
10650
10967
  ...fix && { fix }
10651
10968
  },
10652
10969
  {
@@ -10667,13 +10984,15 @@ async function runWorkspace(deps = {}) {
10667
10984
  epicId: payload.epicId,
10668
10985
  notes: typeof payload.notes === "string" ? payload.notes : void 0,
10669
10986
  projectDir: repoDir,
10670
- keyRun
10987
+ keyRun,
10988
+ signal
10671
10989
  },
10672
10990
  { heartbeat }
10673
10991
  );
10674
10992
  } else {
10675
10993
  return fail("The job is missing what to plan or build.");
10676
10994
  }
10995
+ if (cancelled()) return finishCancelled();
10677
10996
  await client.completeJob(env.token, job.id, outcome.status, outcome.result);
10678
10997
  console.log(outcome.status === "done" ? chalk14.green("Finished.") : chalk14.yellow(`Stopped: ${JSON.stringify(outcome.result)}`));
10679
10998
  return outcome.status === "done" ? 0 : 1;
@@ -10780,7 +11099,7 @@ ${error instanceof Error ? error.message : String(error)}`));
10780
11099
  // src/index.ts
10781
11100
  function resolveCliVersion() {
10782
11101
  if (true) {
10783
- return "1.21.6";
11102
+ return "1.21.7";
10784
11103
  }
10785
11104
  const require2 = createRequire(import.meta.url);
10786
11105
  const pkg = require2("../package.json");