@mycompbox/compbox-cli 1.21.14 → 1.21.16

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.
Files changed (71) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/commands/configure.d.ts.map +1 -1
  3. package/commands/configure.js +3 -3
  4. package/commands/configure.js.map +1 -1
  5. package/commands/doctor.d.ts +21 -3
  6. package/commands/doctor.d.ts.map +1 -1
  7. package/commands/doctor.js +93 -8
  8. package/commands/doctor.js.map +1 -1
  9. package/commands/run.d.ts +2 -0
  10. package/commands/run.d.ts.map +1 -1
  11. package/commands/run.js +22 -7
  12. package/commands/run.js.map +1 -1
  13. package/commands/service.d.ts +10 -19
  14. package/commands/service.d.ts.map +1 -1
  15. package/commands/service.js +107 -73
  16. package/commands/service.js.map +1 -1
  17. package/commands/workspace.d.ts +18 -1
  18. package/commands/workspace.d.ts.map +1 -1
  19. package/commands/workspace.js +122 -12
  20. package/commands/workspace.js.map +1 -1
  21. package/index.js +1925 -533
  22. package/package.json +1 -1
  23. package/utils/agent-invoker.d.ts +103 -3
  24. package/utils/agent-invoker.d.ts.map +1 -1
  25. package/utils/agent-invoker.js +426 -123
  26. package/utils/agent-invoker.js.map +1 -1
  27. package/utils/claude-runtime.d.ts +63 -7
  28. package/utils/claude-runtime.d.ts.map +1 -1
  29. package/utils/claude-runtime.js +203 -67
  30. package/utils/claude-runtime.js.map +1 -1
  31. package/utils/claude-stream.d.ts +38 -0
  32. package/utils/claude-stream.d.ts.map +1 -0
  33. package/utils/claude-stream.js +125 -0
  34. package/utils/claude-stream.js.map +1 -0
  35. package/utils/config-store.d.ts.map +1 -1
  36. package/utils/config-store.js +7 -4
  37. package/utils/config-store.js.map +1 -1
  38. package/utils/mailbox-client.d.ts +61 -2
  39. package/utils/mailbox-client.d.ts.map +1 -1
  40. package/utils/mailbox-client.js +131 -3
  41. package/utils/mailbox-client.js.map +1 -1
  42. package/utils/mcp-config-writer.d.ts +30 -4
  43. package/utils/mcp-config-writer.d.ts.map +1 -1
  44. package/utils/mcp-config-writer.js +33 -6
  45. package/utils/mcp-config-writer.js.map +1 -1
  46. package/utils/package-manager-shims.d.ts +20 -4
  47. package/utils/package-manager-shims.d.ts.map +1 -1
  48. package/utils/package-manager-shims.js +84 -13
  49. package/utils/package-manager-shims.js.map +1 -1
  50. package/utils/process-group.d.ts +9 -2
  51. package/utils/process-group.d.ts.map +1 -1
  52. package/utils/process-group.js +14 -4
  53. package/utils/process-group.js.map +1 -1
  54. package/utils/process-spawn.d.ts +68 -0
  55. package/utils/process-spawn.d.ts.map +1 -0
  56. package/utils/process-spawn.js +119 -0
  57. package/utils/process-spawn.js.map +1 -0
  58. package/utils/project-checks.d.ts +28 -0
  59. package/utils/project-checks.d.ts.map +1 -1
  60. package/utils/project-checks.js +58 -50
  61. package/utils/project-checks.js.map +1 -1
  62. package/utils/repo-setup.js +3 -3
  63. package/utils/repo-setup.js.map +1 -1
  64. package/utils/windows-runner.d.ts +136 -0
  65. package/utils/windows-runner.d.ts.map +1 -0
  66. package/utils/windows-runner.js +407 -0
  67. package/utils/windows-runner.js.map +1 -0
  68. package/utils/wrap-up.d.ts +81 -3
  69. package/utils/wrap-up.d.ts.map +1 -1
  70. package/utils/wrap-up.js +240 -8
  71. package/utils/wrap-up.js.map +1 -1
package/index.js CHANGED
@@ -1831,6 +1831,7 @@ var SessionEventType;
1831
1831
  })(SessionEventType || (SessionEventType = {}));
1832
1832
 
1833
1833
  // ../shared/dist/types/mailbox.js
1834
+ var CHECK_MODES = ["every", "smart", "end"];
1834
1835
  var START_EXECUTION_KINDS = ["plan", "orchestrate", "refine", "follow_up"];
1835
1836
  function normalizeGitRemote(raw) {
1836
1837
  const input = (raw ?? "").trim();
@@ -5978,6 +5979,18 @@ var skillPackManifestSchema = external_exports.object({
5978
5979
  dependencies: external_exports.record(external_exports.string()).optional().describe("Other skill pack dependencies (pack-name: version)")
5979
5980
  });
5980
5981
 
5982
+ // ../shared/dist/model-catalog.js
5983
+ var CONVERSATION_CHAT_MODELS = [
5984
+ { id: "claude-haiku-5-5", label: "Haiku 5.5" },
5985
+ { id: "claude-sonnet-5-5", label: "Sonnet 5.5" },
5986
+ { id: "claude-opus-5-5", label: "Opus 5.5" },
5987
+ { id: "claude-fable-5-1", label: "Fable 5.1" }
5988
+ ];
5989
+ var CONVERSATION_CHAT_MODEL_IDS = CONVERSATION_CHAT_MODELS.map((m) => m.id);
5990
+ function isConversationChatModel(value) {
5991
+ return typeof value === "string" && CONVERSATION_CHAT_MODEL_IDS.includes(value);
5992
+ }
5993
+
5981
5994
  // ../shared/dist/pxpipe/config.js
5982
5995
  var PXPIPE_DEFAULT_PROXY_URL = "http://127.0.0.1:47821";
5983
5996
  function currentEnv(env) {
@@ -6404,10 +6417,11 @@ async function runConversationStep(input, deps) {
6404
6417
  let createdHere = false;
6405
6418
  let qualityRounds = 0;
6406
6419
  let repairs = 0;
6420
+ let kind = "chat";
6407
6421
  for (; ; ) {
6408
6422
  let reply;
6409
6423
  try {
6410
- reply = await deps.reply(system, messages);
6424
+ reply = await deps.reply(system, messages, kind);
6411
6425
  } catch (error) {
6412
6426
  if (savedNow)
6413
6427
  return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow };
@@ -6420,12 +6434,22 @@ Send another message (for example "try again") when you're ready and I'll pick u
6420
6434
  };
6421
6435
  }
6422
6436
  const draft = extractCompletionJson(reply);
6437
+ if (!draft && !looksLikeCompletionAttempt(reply)) {
6438
+ const text = reply.trim();
6439
+ if (savedNow) {
6440
+ return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created, text || void 0), ...savedNow };
6441
+ }
6442
+ if (!text)
6443
+ return { kind: "error", text: "I didn't get a reply that time. Send another message and I'll try again." };
6444
+ return { kind: "message", text };
6445
+ }
6423
6446
  if (draft) {
6424
6447
  if (lockReason) {
6425
6448
  const why = lockReason === "ownership" ? "Only the request's creator can change it, and I'm not its creator." : "That request is locked and can't be changed.";
6426
6449
  messages.push({ role: "assistant", content: reply }, { role: "user", content: `${why} Reply to me in plain text instead.` });
6427
6450
  if (++repairs > JSON_REPAIRS)
6428
6451
  return { kind: "error", text: lockedRequestMessage(lockReason) };
6452
+ kind = "repair";
6429
6453
  continue;
6430
6454
  }
6431
6455
  let saved;
@@ -6450,22 +6474,14 @@ Reply "try again" and I'll retry.` };
6450
6474
 
6451
6475
  The request IS already saved, and the person will be shown its score. If you ask them something, ask it as a way to improve the saved request; never say it hasn't been saved.`
6452
6476
  });
6477
+ kind = "save";
6453
6478
  continue;
6454
6479
  }
6455
- if (looksLikeCompletionAttempt(reply)) {
6456
- if (++repairs > JSON_REPAIRS) {
6457
- return savedNow ? { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow } : { kind: "error", text: `I had trouble writing up the request. Reply "try again" and I'll have another go.` };
6458
- }
6459
- messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
6460
- continue;
6461
- }
6462
- const text = reply.trim();
6463
- if (savedNow) {
6464
- return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created, text || void 0), ...savedNow };
6480
+ if (++repairs > JSON_REPAIRS) {
6481
+ return savedNow ? { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow } : { kind: "error", text: `I had trouble writing up the request. Reply "try again" and I'll have another go.` };
6465
6482
  }
6466
- if (!text)
6467
- return { kind: "error", text: "I didn't get a reply that time. Send another message and I'll try again." };
6468
- return { kind: "message", text };
6483
+ messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
6484
+ kind = "repair";
6469
6485
  }
6470
6486
  }
6471
6487
  function savedContextFromRecord(record, access) {
@@ -6590,6 +6606,22 @@ def handler(event, context):
6590
6606
  // ../shared/dist/stack-cost.js
6591
6607
  var MONTH_SECONDS = 30 * 24 * 60 * 60;
6592
6608
 
6609
+ // ../shared/dist/github-repo.js
6610
+ function canonicalRemoteKey(remote) {
6611
+ if (typeof remote !== "string")
6612
+ return null;
6613
+ const normalized = normalizeGitRemote(remote);
6614
+ if (normalized === "")
6615
+ return null;
6616
+ return normalized.toLowerCase();
6617
+ }
6618
+ function sameGitRemote(a, b) {
6619
+ const keyA = canonicalRemoteKey(a);
6620
+ if (keyA === null)
6621
+ return false;
6622
+ return keyA === canonicalRemoteKey(b);
6623
+ }
6624
+
6593
6625
  // ../shared/dist/machineVersion.js
6594
6626
  var MIN_MACHINE_VERSION = Object.freeze({
6595
6627
  default: "0.0.0",
@@ -6917,7 +6949,7 @@ function resolveProjectDirForJob(projectRemote, opts) {
6917
6949
  if (remote.length === 0) {
6918
6950
  return { status: "no-remote" };
6919
6951
  }
6920
- const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
6952
+ const entry = (opts.config?.projectDirs ?? []).find((e) => sameGitRemote(e.remote, remote));
6921
6953
  return entry ? { status: "registered", path: entry.path } : { status: "unregistered", remote };
6922
6954
  }
6923
6955
  function unusedLegacyProjectDir(config, env = process.env) {
@@ -6964,7 +6996,7 @@ function addProjectDir(path3, readOrigin = readOriginRemote) {
6964
6996
  );
6965
6997
  }
6966
6998
  const entry = { remote, path: target };
6967
- const next = listProjectDirs().filter((e) => e.remote !== remote);
6999
+ const next = listProjectDirs().filter((e) => !sameGitRemote(e.remote, remote));
6968
7000
  next.push(entry);
6969
7001
  updateConfig({ projectDirs: next });
6970
7002
  return entry;
@@ -6975,7 +7007,7 @@ function removeProjectDir(remoteOrPath) {
6975
7007
  const normalizedNeedle = normalizeGitRemote(needle);
6976
7008
  const current = listProjectDirs();
6977
7009
  const next = current.filter(
6978
- (e) => e.path !== needle && e.remote !== needle && e.remote !== normalizedNeedle
7010
+ (e) => e.path !== needle && e.remote !== needle && e.remote !== normalizedNeedle && !sameGitRemote(e.remote, needle)
6979
7011
  );
6980
7012
  if (next.length === current.length) {
6981
7013
  return false;
@@ -7308,7 +7340,7 @@ var cached;
7308
7340
  function resolveCliVersion() {
7309
7341
  if (cached !== void 0) return cached;
7310
7342
  if (true) {
7311
- cached = "1.21.14";
7343
+ cached = "1.21.16";
7312
7344
  return cached;
7313
7345
  }
7314
7346
  const require2 = createRequire(import.meta.url);
@@ -7624,13 +7656,16 @@ var MailboxClient = class {
7624
7656
  }
7625
7657
  return { cancelJobIds: parseCancelJobIds(res.data), ownerNotes: parseOwnerNotes(res.data) };
7626
7658
  }
7627
- /** Posts an agent turn (a question/status update) to a job's interview log. */
7628
- async postTurn(machineToken, jobId, content) {
7659
+ /**
7660
+ * Posts an agent turn (a question/status update) to a job's interview log.
7661
+ * `metrics` (ENG-392) carries how long the turn took; omitted when absent.
7662
+ */
7663
+ async postTurn(machineToken, jobId, content, metrics) {
7629
7664
  let res;
7630
7665
  try {
7631
7666
  res = await this.http.post(
7632
7667
  `/api/v1/jobs/${jobId}/turns`,
7633
- { content },
7668
+ metrics ? { content, metrics } : { content },
7634
7669
  { headers: { Authorization: `Bearer ${machineToken}` } }
7635
7670
  );
7636
7671
  } catch (error) {
@@ -7642,6 +7677,15 @@ var MailboxClient = class {
7642
7677
  const data = res.data;
7643
7678
  return data.data;
7644
7679
  }
7680
+ /**
7681
+ * Posts one slice of in-progress reply text for a claimed job (ENG-388).
7682
+ * `seq` orders slices within the job. The server publishes the slice to the
7683
+ * job's owner and stores nothing, so callers should treat this as
7684
+ * best-effort; see JobStreamPublisher, which batches and swallows failures.
7685
+ */
7686
+ async postStreamDelta(machineToken, jobId, seq, delta) {
7687
+ await this.send("post", `/api/v1/jobs/${jobId}/stream`, machineToken, { seq, delta }, "stream-delta");
7688
+ }
7645
7689
  /**
7646
7690
  * Marks a claimed job done or failed, with an optional structured result.
7647
7691
  * `waiting` (ENG-333) parks a usage-limited job to resume later: `resumeAt`
@@ -7793,7 +7837,7 @@ var MailboxClient = class {
7793
7837
 
7794
7838
  // src/utils/mcp-config-writer.ts
7795
7839
  import { existsSync as existsSync8, readFileSync as readFileSync4, writeFileSync as writeFileSync5, mkdirSync as mkdirSync4 } from "fs";
7796
- import { basename, dirname as dirname3, join as join8 } from "path";
7840
+ import { basename, dirname as dirname3, join as join8, win32 } from "path";
7797
7841
  var DEFAULT_MCP_CONFIG_FILENAME = ".mcp.json";
7798
7842
  var DEFAULT_SERVER_KEY = "compbox";
7799
7843
  var MCP_SERVER_PACKAGE = "@mycompbox/compbox-mcp";
@@ -7817,6 +7861,18 @@ function resolveInstalledMcpBundle(opts) {
7817
7861
  }
7818
7862
  return void 0;
7819
7863
  }
7864
+ function isNodeCommand(command) {
7865
+ return /^node(\.exe)?$/i.test(win32.basename(command));
7866
+ }
7867
+ function isNpxLaunch(command, args) {
7868
+ const base = win32.basename(command).toLowerCase();
7869
+ if (base === "npx" || base === "npx.cmd") return true;
7870
+ if (base === "cmd" || base === "cmd.exe") {
7871
+ const a = (args ?? []).map((x) => x.toLowerCase());
7872
+ return a[0] === "/c" && (a[1] === "npx" || a[1] === "npx.cmd");
7873
+ }
7874
+ return false;
7875
+ }
7820
7876
  function defaultMcpConfigPath(projectRoot = process.cwd()) {
7821
7877
  return join8(projectRoot, DEFAULT_MCP_CONFIG_FILENAME);
7822
7878
  }
@@ -7829,7 +7885,10 @@ function buildCompboxServerEntry(spec) {
7829
7885
  if (!explicitLaunch) {
7830
7886
  const bundlePath = (spec.resolveInstalledBundle ?? resolveInstalledMcpBundle)();
7831
7887
  if (bundlePath !== void 0) {
7832
- return { command: "node", args: [bundlePath], env };
7888
+ return { command: spec.execPath ?? process.execPath, args: [bundlePath], env };
7889
+ }
7890
+ if ((spec.platform ?? process.platform) === "win32") {
7891
+ return { command: "cmd", args: ["/c", "npx", "-y", MCP_SERVER_PACKAGE], env };
7833
7892
  }
7834
7893
  }
7835
7894
  return {
@@ -8070,9 +8129,9 @@ Device already paired as "${config.machineName ?? config.machineId}".`));
8070
8129
  console.log(chalk7.yellow(`
8071
8130
  \u26A0 ${LOOPBACK_NOTICE}`));
8072
8131
  }
8073
- if (result.entry.command === "node") {
8132
+ if (isNodeCommand(result.entry.command)) {
8074
8133
  console.log(
8075
- chalk7.green(`\u2714 MCP server: brew-installed bundle at ${result.entry.args[0] ?? "(unknown)"}`)
8134
+ chalk7.green(`\u2714 MCP server: installed bundle at ${result.entry.args[0] ?? "(unknown)"}`)
8076
8135
  );
8077
8136
  console.log(chalk7.gray(" No download needed \u2014 the launch uses the locally installed bundle."));
8078
8137
  } else {
@@ -8201,37 +8260,109 @@ import { spawn as spawn3 } from "node:child_process";
8201
8260
  import { execFileSync as execFileSync5 } from "node:child_process";
8202
8261
  import { accessSync, constants as fsConstants, statSync as statSync2 } from "node:fs";
8203
8262
  import { homedir as homedir5 } from "node:os";
8204
- import { delimiter, join as join9 } from "node:path";
8263
+ import { posix as posixPath, win32 as win32Path } from "node:path";
8264
+ function pathFor(platform) {
8265
+ return platform === "win32" ? win32Path : posixPath;
8266
+ }
8267
+ function readEnvPath(env, platform) {
8268
+ if (platform !== "win32") {
8269
+ return env.PATH;
8270
+ }
8271
+ if (env.PATH !== void 0) {
8272
+ return env.PATH;
8273
+ }
8274
+ const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
8275
+ return key === void 0 ? void 0 : env[key];
8276
+ }
8277
+ var DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
8278
+ function pathExtensions(env) {
8279
+ const raw = env.PATHEXT ?? DEFAULT_PATHEXT;
8280
+ const exts = raw.split(";").map((e) => e.trim().toLowerCase()).filter((e) => e.length > 1 && e.startsWith("."));
8281
+ return exts.length > 0 ? exts : DEFAULT_PATHEXT.toLowerCase().split(";");
8282
+ }
8283
+ function claudeCandidateNames(platform = process.platform, env = process.env) {
8284
+ if (platform !== "win32") {
8285
+ return ["claude"];
8286
+ }
8287
+ const exts = pathExtensions(env);
8288
+ const ordered = [];
8289
+ for (const ext of [".exe", ".cmd", ...exts]) {
8290
+ if (exts.includes(ext) && !ordered.includes(ext)) {
8291
+ ordered.push(ext);
8292
+ }
8293
+ }
8294
+ return ordered.map((ext) => `claude${ext}`);
8295
+ }
8205
8296
  var WELL_KNOWN_DIRS = buildWellKnownDirs();
8206
- function buildWellKnownDirs() {
8207
- const home = homedir5();
8297
+ function buildWellKnownDirs(options = {}) {
8298
+ const platform = options.platform ?? process.platform;
8299
+ const env = options.env ?? process.env;
8300
+ if (platform === "win32") {
8301
+ return buildWin32WellKnownDirs(env, options.home);
8302
+ }
8303
+ const join19 = (...parts) => posixPath.join(...parts);
8304
+ const home = options.home ?? homedir5();
8208
8305
  const dirs = [
8209
- join9(home, ".local", "bin"),
8306
+ join19(home, ".local", "bin"),
8210
8307
  // default Claude Code install location
8211
8308
  "/opt/homebrew/bin",
8212
8309
  // Homebrew on Apple Silicon
8213
8310
  "/usr/local/bin"
8214
8311
  // Homebrew on Intel / common Unix prefix
8215
8312
  ];
8216
- if (process.env.npm_config_prefix) {
8217
- dirs.push(join9(process.env.npm_config_prefix, "bin"));
8313
+ if (env.npm_config_prefix) {
8314
+ dirs.push(join19(env.npm_config_prefix, "bin"));
8315
+ }
8316
+ dirs.push(join19(home, ".npm-global", "bin"));
8317
+ if (env.PNPM_HOME) {
8318
+ dirs.push(env.PNPM_HOME);
8319
+ }
8320
+ dirs.push(join19(home, "Library", "pnpm"));
8321
+ dirs.push(join19(home, ".local", "share", "pnpm"));
8322
+ return dirs;
8323
+ }
8324
+ function buildWin32WellKnownDirs(env, homeOverride) {
8325
+ const join19 = (...parts) => win32Path.join(...parts);
8326
+ const dirs = [];
8327
+ const userProfile = env.USERPROFILE ?? homeOverride;
8328
+ if (userProfile) {
8329
+ dirs.push(join19(userProfile, ".local", "bin"));
8330
+ }
8331
+ if (env.APPDATA) {
8332
+ dirs.push(join19(env.APPDATA, "npm"));
8218
8333
  }
8219
- dirs.push(join9(home, ".npm-global", "bin"));
8220
- if (process.env.PNPM_HOME) {
8221
- dirs.push(process.env.PNPM_HOME);
8334
+ if (env.LOCALAPPDATA) {
8335
+ dirs.push(join19(env.LOCALAPPDATA, "Programs", "claude"));
8336
+ dirs.push(join19(env.LOCALAPPDATA, "pnpm"));
8337
+ }
8338
+ if (env.npm_config_prefix) {
8339
+ dirs.push(env.npm_config_prefix);
8340
+ }
8341
+ if (env.PNPM_HOME) {
8342
+ dirs.push(env.PNPM_HOME);
8222
8343
  }
8223
- dirs.push(join9(home, "Library", "pnpm"));
8224
- dirs.push(join9(home, ".local", "share", "pnpm"));
8225
8344
  return dirs;
8226
8345
  }
8346
+ function wellKnownDirsFor(platform, env) {
8347
+ if (platform === process.platform && env === process.env) {
8348
+ return WELL_KNOWN_DIRS;
8349
+ }
8350
+ return buildWellKnownDirs({ platform, env });
8351
+ }
8352
+ function dirKey(dir, platform) {
8353
+ return platform === "win32" ? dir.toLowerCase() : dir;
8354
+ }
8227
8355
  var LOGIN_SHELL_PATH_TIMEOUT_MS = 2e3;
8228
8356
  var cachedLoginShellPath = null;
8229
- function getLoginShellPath(exec = defaultExecFileSync) {
8357
+ function getLoginShellPath(exec = defaultExecFileSync, platform = process.platform, env = process.env) {
8358
+ if (platform === "win32") {
8359
+ return readEnvPath(env, platform) ?? "";
8360
+ }
8230
8361
  if (cachedLoginShellPath !== null) {
8231
8362
  return cachedLoginShellPath;
8232
8363
  }
8233
- const shell = process.env.SHELL;
8234
- const fallback = process.env.PATH ?? "";
8364
+ const shell = env.SHELL;
8365
+ const fallback = env.PATH ?? "";
8235
8366
  if (!shell) {
8236
8367
  cachedLoginShellPath = fallback;
8237
8368
  return cachedLoginShellPath;
@@ -8255,23 +8386,28 @@ function defaultExecFileSync(file, args, options) {
8255
8386
  stdio: ["ignore", "pipe", "ignore"]
8256
8387
  });
8257
8388
  }
8258
- function claudeSearchDirs(getPath = getLoginShellPath) {
8259
- const pathDirs = getPath().split(delimiter).map((d) => d.trim()).filter((d) => d.length > 0);
8389
+ function claudeSearchDirs(getPath, platform = process.platform, env = process.env) {
8390
+ const readPath = getPath ?? (() => getLoginShellPath(void 0, platform, env));
8391
+ const pathDirs = readPath().split(pathFor(platform).delimiter).map((d) => d.trim()).filter((d) => d.length > 0);
8260
8392
  const seen = /* @__PURE__ */ new Set();
8261
8393
  const out = [];
8262
- for (const dir of [...pathDirs, ...WELL_KNOWN_DIRS]) {
8263
- if (!seen.has(dir)) {
8264
- seen.add(dir);
8394
+ for (const dir of [...pathDirs, ...wellKnownDirsFor(platform, env)]) {
8395
+ const key = dirKey(dir, platform);
8396
+ if (!seen.has(key)) {
8397
+ seen.add(key);
8265
8398
  out.push(dir);
8266
8399
  }
8267
8400
  }
8268
8401
  return out;
8269
8402
  }
8270
- function isExecutableFile(p) {
8403
+ function isExecutableFile(p, platform = process.platform, env = process.env) {
8271
8404
  try {
8272
8405
  if (!statSync2(p).isFile()) {
8273
8406
  return false;
8274
8407
  }
8408
+ if (platform === "win32") {
8409
+ return pathExtensions(env).includes(win32Path.extname(p).toLowerCase());
8410
+ }
8275
8411
  accessSync(p, fsConstants.X_OK);
8276
8412
  return true;
8277
8413
  } catch {
@@ -8279,37 +8415,52 @@ function isExecutableFile(p) {
8279
8415
  }
8280
8416
  }
8281
8417
  function resolveClaudeBinary(deps = {}) {
8282
- const dirs = deps.dirs ?? claudeSearchDirs();
8283
- const isExec = deps.isExecutableFile ?? isExecutableFile;
8418
+ const platform = deps.platform ?? process.platform;
8419
+ const env = deps.env ?? process.env;
8420
+ const dirs = deps.dirs ?? claudeSearchDirs(void 0, platform, env);
8421
+ const isExec = deps.isExecutableFile ?? ((p) => isExecutableFile(p, platform, env));
8422
+ const names = claudeCandidateNames(platform, env);
8423
+ const pathImpl = pathFor(platform);
8284
8424
  const seen = /* @__PURE__ */ new Set();
8285
8425
  for (const dir of dirs) {
8286
- if (!dir || seen.has(dir)) {
8426
+ if (!dir) {
8287
8427
  continue;
8288
8428
  }
8289
- seen.add(dir);
8290
- const candidate = join9(dir, "claude");
8291
- if (isExec(candidate)) {
8292
- return candidate;
8429
+ const key = dirKey(dir, platform);
8430
+ if (seen.has(key)) {
8431
+ continue;
8432
+ }
8433
+ seen.add(key);
8434
+ for (const name of names) {
8435
+ const candidate = pathImpl.join(dir, name);
8436
+ if (isExec(candidate)) {
8437
+ return candidate;
8438
+ }
8293
8439
  }
8294
8440
  }
8295
8441
  return null;
8296
8442
  }
8297
- function claudeChildEnvPath(currentPath = process.env.PATH) {
8298
- const existing = (currentPath ?? "").split(delimiter).map((d) => d.trim()).filter((d) => d.length > 0);
8443
+ function claudeChildEnvPath(currentPath, options = {}) {
8444
+ const platform = options.platform ?? process.platform;
8445
+ const env = options.env ?? process.env;
8446
+ const { delimiter: delimiter2 } = pathFor(platform);
8447
+ const existing = (currentPath ?? readEnvPath(env, platform) ?? "").split(delimiter2).map((d) => d.trim()).filter((d) => d.length > 0);
8299
8448
  const seen = /* @__PURE__ */ new Set();
8300
8449
  const merged = [];
8301
- for (const dir of [...claudeSearchDirs(), ...existing]) {
8302
- if (!seen.has(dir)) {
8303
- seen.add(dir);
8450
+ for (const dir of [...claudeSearchDirs(void 0, platform, env), ...existing]) {
8451
+ const key = dirKey(dir, platform);
8452
+ if (!seen.has(key)) {
8453
+ seen.add(key);
8304
8454
  merged.push(dir);
8305
8455
  }
8306
8456
  }
8307
- return merged.join(delimiter);
8457
+ return merged.join(delimiter2);
8308
8458
  }
8309
- function claudeNotFoundMessage() {
8459
+ function claudeNotFoundMessage(platform = process.platform, env = process.env) {
8460
+ const pathLabel = platform === "win32" ? "PATH" : "login-shell PATH";
8310
8461
  return [
8311
- "The `claude` CLI could not be located. Searched every directory on the login-shell PATH, plus these well-known install locations:",
8312
- ...WELL_KNOWN_DIRS.map((d) => ` - ${d}`),
8462
+ `The \`claude\` CLI could not be located. Searched every directory on the ${pathLabel}, plus these well-known install locations:`,
8463
+ ...wellKnownDirsFor(platform, env).map((d) => ` - ${d}`),
8313
8464
  "Install Claude Code to use subscription mode: https://code.claude.com"
8314
8465
  ].join("\n");
8315
8466
  }
@@ -8382,6 +8533,340 @@ function probeAgentRuntime(deps = {}) {
8382
8533
  });
8383
8534
  }
8384
8535
 
8536
+ // src/utils/windows-runner.ts
8537
+ import { execFile as execFile2 } from "node:child_process";
8538
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "node:fs";
8539
+ import { homedir as homedir6, tmpdir as tmpdir2, userInfo } from "node:os";
8540
+ import { join as join9 } from "node:path";
8541
+ import { promisify as promisify2 } from "node:util";
8542
+ var execFileAsync2 = promisify2(execFile2);
8543
+ var RUNNER_TASK_NAME = "CompBoxAgentRunner";
8544
+ var LEGACY_SERVICE_NAME = "CompBoxAgentRunner";
8545
+ var RUNNER_DISPLAY_NAME = "CompBox Agent Runner";
8546
+ var LEGACY_ELEVATED_COMMANDS = [
8547
+ `sc.exe stop ${LEGACY_SERVICE_NAME}`,
8548
+ `sc.exe delete ${LEGACY_SERVICE_NAME}`
8549
+ ];
8550
+ var defaultExec = async (file, args) => {
8551
+ const r = await execFileAsync2(file, args, { windowsHide: true });
8552
+ return { stdout: r.stdout, stderr: r.stderr };
8553
+ };
8554
+ var defaultSleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
8555
+ function describeExecError(err) {
8556
+ const e = err ?? {};
8557
+ const code = typeof e.code === "number" || typeof e.code === "string" ? e.code : void 0;
8558
+ return {
8559
+ code,
8560
+ stdout: typeof e.stdout === "string" ? e.stdout : "",
8561
+ stderr: typeof e.stderr === "string" ? e.stderr : "",
8562
+ message: err instanceof Error ? err.message : String(err)
8563
+ };
8564
+ }
8565
+ function failureText(f) {
8566
+ return `${f.stdout}
8567
+ ${f.stderr}
8568
+ ${f.message}`;
8569
+ }
8570
+ function isAccessDenied(f) {
8571
+ return f.code === 5 || /FAILED 5\b|access is denied/i.test(failureText(f));
8572
+ }
8573
+ function failureSummary(f) {
8574
+ const text = (f.stderr.trim() || f.stdout.trim() || f.message).replace(/\s+/g, " ");
8575
+ return text.length > 300 ? `${text.slice(0, 300)}\u2026` : text;
8576
+ }
8577
+ function currentUserId(env = process.env) {
8578
+ let user = env.USERNAME;
8579
+ if (!user) {
8580
+ try {
8581
+ user = userInfo().username;
8582
+ } catch {
8583
+ user = "";
8584
+ }
8585
+ }
8586
+ const domain = env.USERDOMAIN;
8587
+ return domain ? `${domain}\\${user}` : user;
8588
+ }
8589
+ function sameUser(a, b) {
8590
+ const norm2 = (s) => s.trim().toLowerCase();
8591
+ const bare = (s) => norm2(s).split("\\").pop() ?? "";
8592
+ const x = norm2(a);
8593
+ const y = norm2(b);
8594
+ if (!x || !y) return false;
8595
+ if (x === y) return true;
8596
+ if (!x.includes("\\") || !y.includes("\\")) return bare(x) === bare(y);
8597
+ return false;
8598
+ }
8599
+ function xmlEscape2(s) {
8600
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
8601
+ }
8602
+ function defaultTaskSpec() {
8603
+ return {
8604
+ nodeExe: process.execPath,
8605
+ scriptPath: process.argv[1] ?? "",
8606
+ workingDirectory: join9(homedir6(), ".compbox"),
8607
+ userId: currentUserId()
8608
+ };
8609
+ }
8610
+ function buildTaskXml(spec) {
8611
+ const x = xmlEscape2;
8612
+ return [
8613
+ '<?xml version="1.0" encoding="UTF-16"?>',
8614
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
8615
+ " <RegistrationInfo>",
8616
+ ` <Description>${RUNNER_DISPLAY_NAME}: runs compbox run for the signed-in user.</Description>`,
8617
+ " </RegistrationInfo>",
8618
+ " <Triggers>",
8619
+ " <LogonTrigger>",
8620
+ " <Enabled>true</Enabled>",
8621
+ ` <UserId>${x(spec.userId)}</UserId>`,
8622
+ " </LogonTrigger>",
8623
+ " </Triggers>",
8624
+ " <Principals>",
8625
+ ' <Principal id="Author">',
8626
+ ` <UserId>${x(spec.userId)}</UserId>`,
8627
+ " <LogonType>InteractiveToken</LogonType>",
8628
+ " <RunLevel>LeastPrivilege</RunLevel>",
8629
+ " </Principal>",
8630
+ " </Principals>",
8631
+ " <Settings>",
8632
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
8633
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
8634
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
8635
+ " <AllowHardTerminate>true</AllowHardTerminate>",
8636
+ " <StartWhenAvailable>true</StartWhenAvailable>",
8637
+ " <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>",
8638
+ " <IdleSettings>",
8639
+ " <StopOnIdleEnd>false</StopOnIdleEnd>",
8640
+ " <RestartOnIdle>false</RestartOnIdle>",
8641
+ " </IdleSettings>",
8642
+ " <AllowStartOnDemand>true</AllowStartOnDemand>",
8643
+ " <Enabled>true</Enabled>",
8644
+ " <Hidden>false</Hidden>",
8645
+ " <RunOnlyIfIdle>false</RunOnlyIfIdle>",
8646
+ " <WakeToRun>false</WakeToRun>",
8647
+ " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>",
8648
+ " <Priority>7</Priority>",
8649
+ " <RestartOnFailure>",
8650
+ " <Interval>PT1M</Interval>",
8651
+ " <Count>99</Count>",
8652
+ " </RestartOnFailure>",
8653
+ " </Settings>",
8654
+ ' <Actions Context="Author">',
8655
+ " <Exec>",
8656
+ ` <Command>${x(spec.nodeExe)}</Command>`,
8657
+ ` <Arguments>${x(`"${spec.scriptPath}" run`)}</Arguments>`,
8658
+ ` <WorkingDirectory>${x(spec.workingDirectory)}</WorkingDirectory>`,
8659
+ " </Exec>",
8660
+ " </Actions>",
8661
+ "</Task>",
8662
+ ""
8663
+ ].join("\r\n");
8664
+ }
8665
+ function encodeTaskXml(xml) {
8666
+ return Buffer.concat([Buffer.from([255, 254]), Buffer.from(xml, "utf16le")]);
8667
+ }
8668
+ function writeTaskXmlFile(xml) {
8669
+ const dir = mkdtempSync2(join9(tmpdir2(), "compbox-task-"));
8670
+ const path3 = join9(dir, "runner-task.xml");
8671
+ writeFileSync6(path3, encodeTaskXml(xml));
8672
+ return {
8673
+ path: path3,
8674
+ cleanup: () => {
8675
+ rmSync3(dir, { recursive: true, force: true });
8676
+ }
8677
+ };
8678
+ }
8679
+ function parseCsv(text) {
8680
+ const rows = [];
8681
+ let row = [];
8682
+ let field = "";
8683
+ let inQuotes = false;
8684
+ const endRow = () => {
8685
+ row.push(field);
8686
+ field = "";
8687
+ if (row.some((f) => f !== "")) rows.push(row);
8688
+ row = [];
8689
+ };
8690
+ for (let i = 0; i < text.length; i++) {
8691
+ const c = text.charAt(i);
8692
+ if (inQuotes) {
8693
+ if (c === '"') {
8694
+ if (text.charAt(i + 1) === '"') {
8695
+ field += '"';
8696
+ i++;
8697
+ } else {
8698
+ inQuotes = false;
8699
+ }
8700
+ } else {
8701
+ field += c;
8702
+ }
8703
+ } else if (c === '"') {
8704
+ inQuotes = true;
8705
+ } else if (c === ",") {
8706
+ row.push(field);
8707
+ field = "";
8708
+ } else if (c === "\r" || c === "\n") {
8709
+ if (c === "\r" && text.charAt(i + 1) === "\n") i++;
8710
+ endRow();
8711
+ } else {
8712
+ field += c;
8713
+ }
8714
+ }
8715
+ endRow();
8716
+ return rows;
8717
+ }
8718
+ function parseTaskQueryCsv(stdout2) {
8719
+ const rows = parseCsv(stdout2);
8720
+ const header = rows[0];
8721
+ if (!header) return { exists: false };
8722
+ const data = rows.slice(1).find((r) => r.join("\0") !== header.join("\0"));
8723
+ if (!data) return { exists: false };
8724
+ const get = (name) => {
8725
+ const idx = header.findIndex((h) => h.trim().toLowerCase() === name.toLowerCase());
8726
+ if (idx < 0) return void 0;
8727
+ const v = data[idx]?.trim();
8728
+ return v === void 0 || v === "" ? void 0 : v;
8729
+ };
8730
+ return {
8731
+ exists: true,
8732
+ status: get("Status"),
8733
+ runAsUser: get("Run As User"),
8734
+ scheduledState: get("Scheduled Task State"),
8735
+ taskToRun: get("Task To Run")
8736
+ };
8737
+ }
8738
+ async function queryRunnerTask(exec = defaultExec) {
8739
+ try {
8740
+ const { stdout: stdout2 } = await exec("schtasks.exe", [
8741
+ "/Query",
8742
+ "/TN",
8743
+ RUNNER_TASK_NAME,
8744
+ "/FO",
8745
+ "CSV",
8746
+ "/V"
8747
+ ]);
8748
+ return parseTaskQueryCsv(stdout2);
8749
+ } catch (err) {
8750
+ const f = describeExecError(err);
8751
+ if (/cannot find|does not exist/i.test(failureText(f))) return { exists: false };
8752
+ return { exists: false, error: failureSummary(f) };
8753
+ }
8754
+ }
8755
+ function parseScState(stdout2) {
8756
+ const m = /STATE\s*:\s*(\d+)/.exec(stdout2);
8757
+ if (!m) return "unknown";
8758
+ return m[1] === "1" ? "stopped" : "running";
8759
+ }
8760
+ async function queryLegacyService(exec = defaultExec) {
8761
+ try {
8762
+ const { stdout: stdout2 } = await exec("sc.exe", ["query", LEGACY_SERVICE_NAME]);
8763
+ return parseScState(stdout2);
8764
+ } catch (err) {
8765
+ const f = describeExecError(err);
8766
+ if (f.code === 1060 || /\b1060\b|does not exist/i.test(failureText(f))) return "absent";
8767
+ return "unknown";
8768
+ }
8769
+ }
8770
+ async function migrateLegacyService(deps = {}) {
8771
+ const exec = deps.exec ?? defaultExec;
8772
+ const sleep2 = deps.sleep ?? defaultSleep;
8773
+ const polls = deps.stopPolls ?? 15;
8774
+ const interval = deps.stopPollIntervalMs ?? 1e3;
8775
+ const state = await queryLegacyService(exec);
8776
+ if (state === "absent") return { outcome: "absent", stillRunning: false };
8777
+ if (state === "unknown") {
8778
+ return {
8779
+ outcome: "unknown",
8780
+ stillRunning: false,
8781
+ detail: `could not query the legacy "${LEGACY_SERVICE_NAME}" service with sc.exe`
8782
+ };
8783
+ }
8784
+ let running = state === "running";
8785
+ if (running) {
8786
+ try {
8787
+ await exec("sc.exe", ["stop", LEGACY_SERVICE_NAME]);
8788
+ } catch (err) {
8789
+ const f = describeExecError(err);
8790
+ if (isAccessDenied(f)) {
8791
+ return { outcome: "access-denied", stillRunning: true, detail: failureSummary(f) };
8792
+ }
8793
+ if (!(f.code === 1062 || /\b1062\b/.test(failureText(f)))) {
8794
+ return { outcome: "failed", stillRunning: true, detail: failureSummary(f) };
8795
+ }
8796
+ }
8797
+ for (let i = 0; i < polls; i++) {
8798
+ const now = await queryLegacyService(exec);
8799
+ if (now === "stopped" || now === "absent") {
8800
+ running = false;
8801
+ break;
8802
+ }
8803
+ await sleep2(interval);
8804
+ }
8805
+ if (running) {
8806
+ return {
8807
+ outcome: "failed",
8808
+ stillRunning: true,
8809
+ detail: `the legacy service did not stop within ${String(Math.round(polls * interval / 1e3))}s`
8810
+ };
8811
+ }
8812
+ }
8813
+ try {
8814
+ await exec("sc.exe", ["delete", LEGACY_SERVICE_NAME]);
8815
+ } catch (err) {
8816
+ const f = describeExecError(err);
8817
+ return {
8818
+ outcome: isAccessDenied(f) ? "access-denied" : "failed",
8819
+ stillRunning: false,
8820
+ detail: failureSummary(f)
8821
+ };
8822
+ }
8823
+ return { outcome: "removed", stillRunning: false };
8824
+ }
8825
+ async function installRunnerTask(deps = {}) {
8826
+ const exec = deps.exec ?? defaultExec;
8827
+ const migration = await migrateLegacyService({ ...deps, exec });
8828
+ const xml = buildTaskXml(deps.spec ?? defaultTaskSpec());
8829
+ const file = (deps.writeXml ?? writeTaskXmlFile)(xml);
8830
+ try {
8831
+ await exec("schtasks.exe", ["/Create", "/TN", RUNNER_TASK_NAME, "/XML", file.path, "/F"]);
8832
+ } finally {
8833
+ file.cleanup();
8834
+ }
8835
+ if (migration.stillRunning) {
8836
+ return { migration, started: false, notStartedReason: "legacy-running" };
8837
+ }
8838
+ try {
8839
+ await exec("schtasks.exe", ["/Run", "/TN", RUNNER_TASK_NAME]);
8840
+ return { migration, started: true };
8841
+ } catch (err) {
8842
+ return {
8843
+ migration,
8844
+ started: false,
8845
+ notStartedReason: "start-failed",
8846
+ startError: failureSummary(describeExecError(err))
8847
+ };
8848
+ }
8849
+ }
8850
+ async function startRunnerTask(exec = defaultExec) {
8851
+ if (await queryLegacyService(exec) === "running") {
8852
+ return { started: false, reason: "legacy-running" };
8853
+ }
8854
+ try {
8855
+ await exec("schtasks.exe", ["/Run", "/TN", RUNNER_TASK_NAME]);
8856
+ return { started: true };
8857
+ } catch (err) {
8858
+ return { started: false, reason: "failed", error: failureSummary(describeExecError(err)) };
8859
+ }
8860
+ }
8861
+ async function stopRunnerTask(exec = defaultExec) {
8862
+ await exec("schtasks.exe", ["/End", "/TN", RUNNER_TASK_NAME]);
8863
+ }
8864
+ async function uninstallRunnerTask(exec = defaultExec) {
8865
+ await exec("schtasks.exe", ["/End", "/TN", RUNNER_TASK_NAME]).catch(() => {
8866
+ });
8867
+ await exec("schtasks.exe", ["/Delete", "/TN", RUNNER_TASK_NAME, "/F"]);
8868
+ }
8869
+
8385
8870
  // src/commands/doctor.ts
8386
8871
  function printResult(result) {
8387
8872
  const marker = result.warning ? chalk8.yellow("WARN") : result.skipped ? chalk8.yellow("SKIP") : result.passed ? chalk8.green("PASS") : chalk8.red("FAIL");
@@ -8500,14 +8985,22 @@ async function launchTargetCheck(mcpStatus, deps = {}) {
8500
8985
  detail: mcpStatus.entryPresent ? "Skipped \u2014 MCP entry present but has no launch command. Re-run `compbox configure` to rewrite it." : "Skipped \u2014 no CompBox MCP entry to verify. Run `compbox configure` to write one."
8501
8986
  };
8502
8987
  }
8503
- if (mcpStatus.command === "npx") {
8988
+ const platform = deps.platform ?? process.platform;
8989
+ if (platform === "win32" && mcpStatus.command === "npx") {
8990
+ return {
8991
+ name,
8992
+ passed: false,
8993
+ detail: "Launch target is bare `npx`, which Claude Code cannot spawn on Windows (npx is a .cmd shim and MCP servers are launched without a shell). Run `compbox configure` to rewrite the entry."
8994
+ };
8995
+ }
8996
+ if (isNpxLaunch(mcpStatus.command, mcpStatus.args)) {
8504
8997
  return {
8505
8998
  name,
8506
8999
  passed: true,
8507
9000
  detail: `Launch target is \`npx\` \u2014 ${MCP_SERVER_PACKAGE} resolves from registry.npmjs.org on first use; nothing installed locally to verify.`
8508
9001
  };
8509
9002
  }
8510
- if (mcpStatus.command !== "node") {
9003
+ if (!isNodeCommand(mcpStatus.command)) {
8511
9004
  return {
8512
9005
  name,
8513
9006
  passed: true,
@@ -8520,7 +9013,7 @@ async function launchTargetCheck(mcpStatus, deps = {}) {
8520
9013
  return {
8521
9014
  name,
8522
9015
  passed: false,
8523
- detail: "Launch command is `node` but no bundle path is configured \u2014 re-run `compbox configure` to rewrite the entry."
9016
+ detail: "Launch command is Node but no bundle path is configured \u2014 re-run `compbox configure` to rewrite the entry."
8524
9017
  };
8525
9018
  }
8526
9019
  if (!fileExists(bundlePath)) {
@@ -8530,7 +9023,7 @@ async function launchTargetCheck(mcpStatus, deps = {}) {
8530
9023
  detail: `Configured MCP bundle not found at ${bundlePath} \u2014 run \`brew reinstall compbox\` (or re-run \`compbox configure\`) to restore it.`
8531
9024
  };
8532
9025
  }
8533
- const probeResult = await probe("node", [bundlePath]);
9026
+ const probeResult = await probe(mcpStatus.command, [bundlePath]);
8534
9027
  if (probeResult.status === "answered") {
8535
9028
  return {
8536
9029
  name,
@@ -8606,6 +9099,65 @@ function checkBrewService(deps = {}) {
8606
9099
  detail: started ? "CompBox Agent Runner is running under `brew services`." : "CompBox service is registered but not running \u2014 run `brew services start compbox`."
8607
9100
  };
8608
9101
  }
9102
+ async function checkWindowsRunner(deps = {}) {
9103
+ const userId = deps.userId ?? currentUserId();
9104
+ const queryTask = deps.queryTask ?? queryRunnerTask;
9105
+ const queryLegacy = deps.queryLegacy ?? queryLegacyService;
9106
+ const [task, legacy] = await Promise.all([queryTask(deps.exec), queryLegacy(deps.exec)]);
9107
+ const elevated = LEGACY_ELEVATED_COMMANDS.join(" && ");
9108
+ const taskName = "Agent Runner task (Windows)";
9109
+ let taskResult;
9110
+ if (task.error) {
9111
+ taskResult = {
9112
+ name: taskName,
9113
+ passed: false,
9114
+ detail: `Could not query Scheduled Task "${RUNNER_TASK_NAME}" (${task.error}) \u2014 run \`compbox service status\` for details.`
9115
+ };
9116
+ } else if (!task.exists) {
9117
+ taskResult = {
9118
+ name: taskName,
9119
+ passed: false,
9120
+ detail: `Scheduled Task "${RUNNER_TASK_NAME}" is not registered \u2014 run \`compbox service install\`.`
9121
+ };
9122
+ } else if (task.runAsUser && !sameUser(task.runAsUser, userId)) {
9123
+ taskResult = {
9124
+ name: taskName,
9125
+ passed: false,
9126
+ detail: `Scheduled Task "${RUNNER_TASK_NAME}" runs as ${task.runAsUser}, not ${userId} \u2014 run \`compbox service install\` as ${userId} to re-register it.`
9127
+ };
9128
+ } else if (!task.status || !/^running$/i.test(task.status)) {
9129
+ taskResult = {
9130
+ name: taskName,
9131
+ passed: false,
9132
+ detail: `Scheduled Task "${RUNNER_TASK_NAME}" is registered but not running (status: ${task.status ?? "unknown"}) \u2014 run \`compbox service start\`.`
9133
+ };
9134
+ } else {
9135
+ taskResult = {
9136
+ name: taskName,
9137
+ passed: true,
9138
+ detail: `Agent Runner is running as ${task.runAsUser ?? userId} (Scheduled Task "${RUNNER_TASK_NAME}").`
9139
+ };
9140
+ }
9141
+ const legacyName = "Legacy LocalSystem service (Windows)";
9142
+ let legacyResult;
9143
+ if (legacy === "absent") {
9144
+ legacyResult = { name: legacyName, passed: true, detail: "No leftover LocalSystem service." };
9145
+ } else if (legacy === "unknown") {
9146
+ legacyResult = {
9147
+ name: legacyName,
9148
+ passed: true,
9149
+ warning: true,
9150
+ detail: `Could not query the legacy "${LEGACY_SERVICE_NAME}" service with sc.exe \u2014 check with \`sc.exe query ${LEGACY_SERVICE_NAME}\`.`
9151
+ };
9152
+ } else {
9153
+ legacyResult = {
9154
+ name: legacyName,
9155
+ passed: false,
9156
+ detail: `The old LocalSystem service "${LEGACY_SERVICE_NAME}" is still installed (${legacy}) \u2014 from an Administrator terminal run: ${elevated}`
9157
+ };
9158
+ }
9159
+ return [taskResult, legacyResult];
9160
+ }
8609
9161
  async function checkPxpipe() {
8610
9162
  if (!isPxpipeEnabled()) {
8611
9163
  return {
@@ -8850,6 +9402,9 @@ var doctorCommand = new Command7("doctor").description("Diagnose config, connect
8850
9402
  if (process.platform === "darwin") {
8851
9403
  results.push(checkBrewService());
8852
9404
  }
9405
+ if (process.platform === "win32") {
9406
+ results.push(...await checkWindowsRunner());
9407
+ }
8853
9408
  results.push(await checkPxpipe());
8854
9409
  results.forEach(printResult);
8855
9410
  const failedCount = countFailures(results);
@@ -9181,81 +9736,233 @@ async function finishMergeApproval(approval, merge) {
9181
9736
 
9182
9737
  // src/commands/run.ts
9183
9738
  import { Command as Command8 } from "commander";
9184
- import { delimiter as delimiter3 } from "node:path";
9739
+ import { delimiter } from "node:path";
9185
9740
  import chalk9 from "chalk";
9186
9741
 
9187
9742
  // src/utils/agent-invoker.ts
9188
9743
  import Anthropic from "@anthropic-ai/sdk";
9189
- import { execFile as execFile2, spawn as spawn7, spawnSync } from "node:child_process";
9190
- import { randomUUID } from "node:crypto";
9191
- import { mkdirSync as mkdirSync9 } from "node:fs";
9192
- import { mkdir as mkdir2, mkdtemp, realpath, rm, writeFile as writeFile2 } from "node:fs/promises";
9193
- import { homedir as homedir7, tmpdir as tmpdir2 } from "node:os";
9194
- import { join as join16 } from "node:path";
9744
+ import { execFile as execFile3, spawn as spawn6, spawnSync } from "node:child_process";
9195
9745
 
9196
- // src/utils/run-timings.ts
9197
- function durationsOf(value) {
9198
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
9199
- const r = value;
9200
- const api = r.duration_api_ms;
9201
- const total = r.duration_ms;
9202
- if (typeof api !== "number" || typeof total !== "number") return null;
9203
- if (!Number.isFinite(api) || !Number.isFinite(total) || api < 0 || total < 0) return null;
9204
- return { apiMs: api, totalMs: total };
9746
+ // src/utils/process-spawn.ts
9747
+ import { spawn as nodeSpawn2 } from "node:child_process";
9748
+ import { existsSync as existsSync10 } from "node:fs";
9749
+ import { win32 as win32Path2 } from "node:path";
9750
+
9751
+ // src/utils/process-group.ts
9752
+ import { spawn as nodeSpawn } from "node:child_process";
9753
+ var CANCEL_GRACE_MS = 1e4;
9754
+ function groupSpawnOptions(platform = process.platform) {
9755
+ return platform === "win32" ? {} : { detached: true };
9205
9756
  }
9206
- function parseClaudeDurations(stdout2) {
9207
- const trimmed = stdout2.trim();
9208
- if (!trimmed) return null;
9757
+ function taskkillTree(pid, spawn9 = nodeSpawn) {
9209
9758
  try {
9210
- const whole = durationsOf(JSON.parse(trimmed));
9211
- if (whole) return whole;
9759
+ const killer = spawn9("taskkill", ["/pid", String(pid), "/T", "/F"], {
9760
+ stdio: "ignore",
9761
+ windowsHide: true
9762
+ });
9763
+ killer.on("error", () => {
9764
+ });
9212
9765
  } catch {
9213
9766
  }
9214
- const lines = trimmed.split("\n");
9215
- for (let i = lines.length - 1; i >= 0; i--) {
9216
- const line = lines[i]?.trim() ?? "";
9217
- if (!line.startsWith("{")) continue;
9767
+ }
9768
+ function windowsKillTree(pid, deps) {
9769
+ if (deps.killTree) deps.killTree(pid);
9770
+ else taskkillTree(pid, deps.spawn);
9771
+ }
9772
+ function signalGroup(child, signal, deps) {
9773
+ const pid = child.pid;
9774
+ if (pid === void 0) {
9218
9775
  try {
9219
- const found = durationsOf(JSON.parse(line));
9220
- if (found) return found;
9776
+ child.kill(signal);
9221
9777
  } catch {
9222
9778
  }
9779
+ return;
9223
9780
  }
9224
- return null;
9225
- }
9226
- function aggregateRunDurations(runs) {
9227
- if (runs.length === 0 || runs.some((r) => r === null)) return { modelMs: null, toolMs: null };
9228
- let modelMs = 0;
9229
- let toolMs = 0;
9230
- for (const run of runs) {
9231
- modelMs += run.apiMs;
9232
- toolMs += Math.max(0, run.totalMs - run.apiMs);
9781
+ const kill = deps.kill ?? ((p, s) => process.kill(p, s));
9782
+ try {
9783
+ kill(-pid, signal);
9784
+ } catch (error) {
9785
+ if (error.code === "ESRCH") return;
9786
+ try {
9787
+ child.kill(signal);
9788
+ } catch {
9789
+ }
9233
9790
  }
9234
- return { modelMs, toolMs };
9235
9791
  }
9236
- var CI_START = /\[compbox:ci-wait start(?:\s+ts=(\d+))?\]/;
9237
- var CI_END = /\[compbox:ci-wait end(?:\s+ts=(\d+))?\]([^\n]*)/;
9238
- var CiWaitTracker = class {
9239
- partial = "";
9240
- openAtMs = null;
9241
- totalMs = 0;
9242
- waits = 0;
9243
- /** Feeds a stdout chunk that arrived at `nowMs` (epoch ms). */
9244
- feed(chunk, nowMs) {
9245
- const text = this.partial + chunk;
9246
- const lines = text.split("\n");
9247
- this.partial = lines.pop() ?? "";
9248
- for (const line of lines) this.line(line, nowMs);
9249
- }
9250
- /** Processes a trailing line without a newline (call once the run ends). */
9251
- flush(nowMs) {
9252
- if (this.partial) this.line(this.partial, nowMs);
9253
- this.partial = "";
9792
+ function terminateProcessGroup(child, deps = {}) {
9793
+ const platform = deps.platform ?? process.platform;
9794
+ if (platform === "win32") {
9795
+ if (child.pid !== void 0) windowsKillTree(child.pid, deps);
9796
+ else child.kill("SIGKILL");
9797
+ return () => void 0;
9254
9798
  }
9255
- line(line, nowMs) {
9256
- const start = CI_START.exec(line);
9257
- if (start) {
9258
- this.openAtMs = start[1] ? Number(start[1]) * 1e3 : nowMs;
9799
+ signalGroup(child, "SIGTERM", deps);
9800
+ const escalate = setTimeout(() => {
9801
+ signalGroup(child, "SIGKILL", deps);
9802
+ }, deps.graceMs ?? CANCEL_GRACE_MS);
9803
+ escalate.unref();
9804
+ return () => {
9805
+ clearTimeout(escalate);
9806
+ };
9807
+ }
9808
+ function killProcessGroupNow(child, deps = {}) {
9809
+ const platform = deps.platform ?? process.platform;
9810
+ if (platform === "win32") {
9811
+ if (child.pid !== void 0) windowsKillTree(child.pid, deps);
9812
+ else child.kill("SIGKILL");
9813
+ return;
9814
+ }
9815
+ signalGroup(child, "SIGKILL", deps);
9816
+ }
9817
+ function killGroupOnAbort(signal, child, onAbort, deps = {}) {
9818
+ if (!signal) return () => void 0;
9819
+ const handler = () => {
9820
+ onAbort();
9821
+ terminateProcessGroup(child, deps);
9822
+ };
9823
+ if (signal.aborted) {
9824
+ handler();
9825
+ } else {
9826
+ signal.addEventListener("abort", handler, { once: true });
9827
+ }
9828
+ return () => {
9829
+ signal.removeEventListener("abort", handler);
9830
+ };
9831
+ }
9832
+ function cancelledRunResult(what) {
9833
+ return {
9834
+ status: "failed",
9835
+ result: { cancelled: true, message: `Cancelled from the website; the ${what} was stopped.` }
9836
+ };
9837
+ }
9838
+
9839
+ // src/utils/process-spawn.ts
9840
+ var CMD_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
9841
+ function isBatchFile(command) {
9842
+ return /\.(cmd|bat)$/i.test(command.trim());
9843
+ }
9844
+ function escapeCmdMeta(value) {
9845
+ return value.replace(CMD_META_CHARS, "^$1");
9846
+ }
9847
+ function escapeArgument(arg, doubleEscape) {
9848
+ let quoted = arg.replace(/(\\*)"/g, '$1$1\\"');
9849
+ quoted = quoted.replace(/(\\*)$/, "$1$1");
9850
+ quoted = escapeCmdMeta(`"${quoted}"`);
9851
+ return doubleEscape ? escapeCmdMeta(quoted) : quoted;
9852
+ }
9853
+ function buildWindowsCmdLine(command, args) {
9854
+ const doubleEscape = isBatchFile(command);
9855
+ const escapedCommand = escapeCmdMeta(command.replace(/"/g, ""));
9856
+ return [escapedCommand, ...args.map((arg) => escapeArgument(arg, doubleEscape))].join(" ");
9857
+ }
9858
+ function envValue(env, name) {
9859
+ const upper = name.toUpperCase();
9860
+ const key = Object.keys(env).find((k) => k.toUpperCase() === upper);
9861
+ return key === void 0 ? void 0 : env[key];
9862
+ }
9863
+ function resolveWindowsCommand(command, env, exists = existsSync10) {
9864
+ if (/[\\/:]/.test(command) || win32Path2.extname(command) !== "") return command;
9865
+ const exts = (envValue(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((ext) => ext !== "");
9866
+ const dirs = (envValue(env, "PATH") ?? "").split(";").filter((dir) => dir !== "");
9867
+ for (const dir of dirs) {
9868
+ for (const ext of exts) {
9869
+ const candidate = win32Path2.join(dir.replace(/"/g, ""), command + ext.toLowerCase());
9870
+ if (exists(candidate)) return candidate;
9871
+ }
9872
+ }
9873
+ return command;
9874
+ }
9875
+ function planCrossPlatformSpawn(command, args, options = {}, planEnv = {}) {
9876
+ const platform = planEnv.platform ?? process.platform;
9877
+ const { shell: _shell, ...rest } = options;
9878
+ if (platform !== "win32") return { command, args: [...args], options: rest };
9879
+ const env = options.env ?? planEnv.env ?? process.env;
9880
+ const resolved = resolveWindowsCommand(command, env, planEnv.exists);
9881
+ if (!isBatchFile(resolved)) return { command, args: [...args], options: rest };
9882
+ return {
9883
+ command: envValue(env, "ComSpec") ?? "cmd.exe",
9884
+ args: ["/d", "/s", "/c", `"${buildWindowsCmdLine(resolved, args)}"`],
9885
+ options: { ...rest, windowsVerbatimArguments: true, windowsHide: true }
9886
+ };
9887
+ }
9888
+ function spawnCrossPlatform(command, args = [], options = {}, deps = {}) {
9889
+ const plan = planCrossPlatformSpawn(command, args, options, deps);
9890
+ return (deps.spawn ?? nodeSpawn2)(plan.command, plan.args, plan.options);
9891
+ }
9892
+ function killProcessTree(child, deps = {}) {
9893
+ killProcessGroupNow(child, deps);
9894
+ }
9895
+
9896
+ // src/utils/agent-invoker.ts
9897
+ import { randomUUID } from "node:crypto";
9898
+ import { copyFileSync as copyFileSync3, existsSync as existsSync15, mkdirSync as mkdirSync10, mkdtempSync as mkdtempSync4 } from "node:fs";
9899
+ import { mkdir as mkdir2, mkdtemp, realpath, rm, writeFile as writeFile2 } from "node:fs/promises";
9900
+ import { homedir as homedir8, tmpdir as tmpdir4 } from "node:os";
9901
+ import { join as join16 } from "node:path";
9902
+
9903
+ // src/utils/run-timings.ts
9904
+ function durationsOf(value) {
9905
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
9906
+ const r = value;
9907
+ const api = r.duration_api_ms;
9908
+ const total = r.duration_ms;
9909
+ if (typeof api !== "number" || typeof total !== "number") return null;
9910
+ if (!Number.isFinite(api) || !Number.isFinite(total) || api < 0 || total < 0) return null;
9911
+ return { apiMs: api, totalMs: total };
9912
+ }
9913
+ function parseClaudeDurations(stdout2) {
9914
+ const trimmed = stdout2.trim();
9915
+ if (!trimmed) return null;
9916
+ try {
9917
+ const whole = durationsOf(JSON.parse(trimmed));
9918
+ if (whole) return whole;
9919
+ } catch {
9920
+ }
9921
+ const lines = trimmed.split("\n");
9922
+ for (let i = lines.length - 1; i >= 0; i--) {
9923
+ const line = lines[i]?.trim() ?? "";
9924
+ if (!line.startsWith("{")) continue;
9925
+ try {
9926
+ const found = durationsOf(JSON.parse(line));
9927
+ if (found) return found;
9928
+ } catch {
9929
+ }
9930
+ }
9931
+ return null;
9932
+ }
9933
+ function aggregateRunDurations(runs) {
9934
+ if (runs.length === 0 || runs.some((r) => r === null)) return { modelMs: null, toolMs: null };
9935
+ let modelMs = 0;
9936
+ let toolMs = 0;
9937
+ for (const run of runs) {
9938
+ modelMs += run.apiMs;
9939
+ toolMs += Math.max(0, run.totalMs - run.apiMs);
9940
+ }
9941
+ return { modelMs, toolMs };
9942
+ }
9943
+ var CI_START = /\[compbox:ci-wait start(?:\s+ts=(\d+))?\]/;
9944
+ var CI_END = /\[compbox:ci-wait end(?:\s+ts=(\d+))?\]([^\n]*)/;
9945
+ var CiWaitTracker = class {
9946
+ partial = "";
9947
+ openAtMs = null;
9948
+ totalMs = 0;
9949
+ waits = 0;
9950
+ /** Feeds a stdout chunk that arrived at `nowMs` (epoch ms). */
9951
+ feed(chunk, nowMs) {
9952
+ const text = this.partial + chunk;
9953
+ const lines = text.split("\n");
9954
+ this.partial = lines.pop() ?? "";
9955
+ for (const line of lines) this.line(line, nowMs);
9956
+ }
9957
+ /** Processes a trailing line without a newline (call once the run ends). */
9958
+ flush(nowMs) {
9959
+ if (this.partial) this.line(this.partial, nowMs);
9960
+ this.partial = "";
9961
+ }
9962
+ line(line, nowMs) {
9963
+ const start = CI_START.exec(line);
9964
+ if (start) {
9965
+ this.openAtMs = start[1] ? Number(start[1]) * 1e3 : nowMs;
9259
9966
  return;
9260
9967
  }
9261
9968
  const end = CI_END.exec(line);
@@ -9299,18 +10006,34 @@ import {
9299
10006
  readdirSync,
9300
10007
  renameSync,
9301
10008
  statSync as statSync3,
9302
- writeFileSync as writeFileSync7
10009
+ writeFileSync as writeFileSync8
9303
10010
  } from "node:fs";
9304
10011
  import { isAbsolute as isAbsolute2, join as join11 } from "node:path";
9305
10012
 
9306
10013
  // src/utils/package-manager-shims.ts
9307
- import { accessSync as accessSync2, chmodSync as chmodSync3, constants, existsSync as existsSync10, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "node:fs";
9308
- import { homedir as homedir6 } from "node:os";
9309
- import { delimiter as delimiter2, dirname as dirname4, join as join10 } from "node:path";
10014
+ import { accessSync as accessSync2, chmodSync as chmodSync3, constants, existsSync as existsSync11, mkdirSync as mkdirSync5, writeFileSync as writeFileSync7 } from "node:fs";
10015
+ import { homedir as homedir7 } from "node:os";
10016
+ import { dirname as dirname4, join as join10, posix as posixPath2, win32 as win32Path3 } from "node:path";
9310
10017
  var STAND_INS = { pnpm: "pnpm@10", yarn: "yarn@1" };
9311
- function isOnPath(command, path3) {
9312
- for (const dir of path3.split(delimiter2)) {
10018
+ function delimiterFor(platform) {
10019
+ return platform === "win32" ? win32Path3.delimiter : posixPath2.delimiter;
10020
+ }
10021
+ function sameDir(a, b, platform) {
10022
+ if (platform !== "win32") return posixPath2.resolve(a) === posixPath2.resolve(b);
10023
+ const norm2 = (d) => d.replace(/[\\/]+$/, "").replace(/\//g, "\\").toLowerCase();
10024
+ return norm2(a) === norm2(b);
10025
+ }
10026
+ function pathWithout(path3, exclude, platform = process.platform) {
10027
+ const delim = delimiterFor(platform);
10028
+ return path3.split(delim).filter((d) => d && !sameDir(d, exclude, platform)).join(delim);
10029
+ }
10030
+ function isOnPath(command, path3, platform = process.platform, env = process.env) {
10031
+ for (const dir of path3.split(delimiterFor(platform))) {
9313
10032
  if (!dir) continue;
10033
+ if (platform === "win32") {
10034
+ if (findWin32Executable(command, dir, env)) return true;
10035
+ continue;
10036
+ }
9314
10037
  try {
9315
10038
  accessSync2(join10(dir, command), constants.X_OK);
9316
10039
  return true;
@@ -9319,6 +10042,18 @@ function isOnPath(command, path3) {
9319
10042
  }
9320
10043
  return false;
9321
10044
  }
10045
+ function win32Extensions(env) {
10046
+ const raw = env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD";
10047
+ return raw.split(";").map((e) => e.trim().toLowerCase()).filter((e) => e.length > 1 && e.startsWith("."));
10048
+ }
10049
+ function findWin32Executable(command, dir, env) {
10050
+ const names = win32Path3.extname(command) ? [command] : win32Extensions(env).map((ext) => command + ext);
10051
+ for (const name of names) {
10052
+ const candidate = join10(dir, name);
10053
+ if (isExecutableFile(candidate, "win32", env)) return candidate;
10054
+ }
10055
+ return null;
10056
+ }
9322
10057
  function shimScript(tool, nodeBinDir, npx) {
9323
10058
  return [
9324
10059
  "#!/bin/sh",
@@ -9330,19 +10065,42 @@ function shimScript(tool, nodeBinDir, npx) {
9330
10065
  ""
9331
10066
  ].join("\n");
9332
10067
  }
10068
+ function shimCmdScript(tool, nodeBinDir, npx) {
10069
+ return [
10070
+ "@echo off",
10071
+ `rem Written by CompBox: ${tool} isn't installed on this computer, so it runs`,
10072
+ "rem through Node's npx. Installing it yourself makes CompBox use that instead.",
10073
+ `set "PATH=${nodeBinDir};%PATH%"`,
10074
+ `"${npx}" --yes ${STAND_INS[tool]} %*`,
10075
+ "exit /b %ERRORLEVEL%",
10076
+ ""
10077
+ ].join("\r\n");
10078
+ }
9333
10079
  function ensurePackageManagerShims(opts = {}) {
9334
- if ((opts.platform ?? process.platform) === "win32") return null;
9335
- const path3 = (opts.searchPath ?? claudeChildEnvPath)(opts.path ?? process.env.PATH);
9336
- const missing = Object.keys(STAND_INS).filter((tool) => !isOnPath(tool, path3));
10080
+ const platform = opts.platform ?? process.platform;
10081
+ const env = opts.env ?? process.env;
10082
+ const dir = join10(opts.home ?? homedir7(), ".compbox", "shims");
10083
+ const searchPath = opts.searchPath ?? ((p) => claudeChildEnvPath(p, { platform, env }));
10084
+ const path3 = pathWithout(searchPath(opts.path ?? process.env.PATH), dir, platform);
10085
+ const missing = Object.keys(STAND_INS).filter((tool) => !isOnPath(tool, path3, platform, env));
9337
10086
  if (missing.length === 0) return null;
9338
10087
  const nodeBinDir = opts.nodeBinDir ?? dirname4(process.execPath);
9339
- const npx = existsSync10(join10(nodeBinDir, "npx")) ? join10(nodeBinDir, "npx") : "npx";
9340
- const dir = join10(opts.home ?? homedir6(), ".compbox", "shims");
10088
+ const win322 = platform === "win32";
10089
+ let npx;
10090
+ if (win322) {
10091
+ npx = findWin32Executable("npx", nodeBinDir, env) ?? "npx";
10092
+ } else {
10093
+ npx = existsSync11(join10(nodeBinDir, "npx")) ? join10(nodeBinDir, "npx") : "npx";
10094
+ }
9341
10095
  try {
9342
10096
  mkdirSync5(dir, { recursive: true });
9343
10097
  for (const tool of missing) {
10098
+ if (win322) {
10099
+ writeFileSync7(join10(dir, `${tool}.cmd`), shimCmdScript(tool, nodeBinDir, npx));
10100
+ continue;
10101
+ }
9344
10102
  const file = join10(dir, tool);
9345
- writeFileSync6(file, shimScript(tool, nodeBinDir, npx));
10103
+ writeFileSync7(file, shimScript(tool, nodeBinDir, npx));
9346
10104
  chmodSync3(file, 493);
9347
10105
  }
9348
10106
  } catch {
@@ -9423,7 +10181,7 @@ function ghShimCmd(realGhPath) {
9423
10181
  }
9424
10182
  function writeAtomic(file, content, mode) {
9425
10183
  const tmp = `${file}.${String(process.pid)}.${String(Date.now())}.tmp`;
9426
- writeFileSync7(tmp, content);
10184
+ writeFileSync8(tmp, content);
9427
10185
  chmodSync4(tmp, mode);
9428
10186
  renameSync(tmp, file);
9429
10187
  }
@@ -9600,90 +10358,6 @@ function parseClaudeJsonResult(stdout2, fallbackModel) {
9600
10358
  return { text: typeof data.result === "string" ? data.result : "", usage };
9601
10359
  }
9602
10360
 
9603
- // src/utils/process-group.ts
9604
- import { spawn as nodeSpawn } from "node:child_process";
9605
- var CANCEL_GRACE_MS = 1e4;
9606
- function groupSpawnOptions(platform = process.platform) {
9607
- return platform === "win32" ? {} : { detached: true };
9608
- }
9609
- function defaultKillTree(pid) {
9610
- try {
9611
- const killer = nodeSpawn("taskkill", ["/PID", String(pid), "/T", "/F"], {
9612
- stdio: "ignore",
9613
- windowsHide: true
9614
- });
9615
- killer.on("error", () => {
9616
- });
9617
- } catch {
9618
- }
9619
- }
9620
- function signalGroup(child, signal, deps) {
9621
- const pid = child.pid;
9622
- if (pid === void 0) {
9623
- try {
9624
- child.kill(signal);
9625
- } catch {
9626
- }
9627
- return;
9628
- }
9629
- const kill = deps.kill ?? ((p, s) => process.kill(p, s));
9630
- try {
9631
- kill(-pid, signal);
9632
- } catch (error) {
9633
- if (error.code === "ESRCH") return;
9634
- try {
9635
- child.kill(signal);
9636
- } catch {
9637
- }
9638
- }
9639
- }
9640
- function terminateProcessGroup(child, deps = {}) {
9641
- const platform = deps.platform ?? process.platform;
9642
- if (platform === "win32") {
9643
- if (child.pid !== void 0) (deps.killTree ?? defaultKillTree)(child.pid);
9644
- else child.kill("SIGKILL");
9645
- return () => void 0;
9646
- }
9647
- signalGroup(child, "SIGTERM", deps);
9648
- const escalate = setTimeout(() => {
9649
- signalGroup(child, "SIGKILL", deps);
9650
- }, deps.graceMs ?? CANCEL_GRACE_MS);
9651
- escalate.unref();
9652
- return () => {
9653
- clearTimeout(escalate);
9654
- };
9655
- }
9656
- function killProcessGroupNow(child, deps = {}) {
9657
- const platform = deps.platform ?? process.platform;
9658
- if (platform === "win32") {
9659
- if (child.pid !== void 0) (deps.killTree ?? defaultKillTree)(child.pid);
9660
- else child.kill("SIGKILL");
9661
- return;
9662
- }
9663
- signalGroup(child, "SIGKILL", deps);
9664
- }
9665
- function killGroupOnAbort(signal, child, onAbort, deps = {}) {
9666
- if (!signal) return () => void 0;
9667
- const handler = () => {
9668
- onAbort();
9669
- terminateProcessGroup(child, deps);
9670
- };
9671
- if (signal.aborted) {
9672
- handler();
9673
- } else {
9674
- signal.addEventListener("abort", handler, { once: true });
9675
- }
9676
- return () => {
9677
- signal.removeEventListener("abort", handler);
9678
- };
9679
- }
9680
- function cancelledRunResult(what) {
9681
- return {
9682
- status: "failed",
9683
- result: { cancelled: true, message: `Cancelled from the website; the ${what} was stopped.` }
9684
- };
9685
- }
9686
-
9687
10361
  // src/utils/progress-watcher.ts
9688
10362
  var PROGRESS_WATCHER_TICK_MS = 6e4;
9689
10363
  async function readProbe(probe) {
@@ -9764,6 +10438,108 @@ function startProgressWatcher(options) {
9764
10438
  };
9765
10439
  }
9766
10440
 
10441
+ // src/utils/claude-stream.ts
10442
+ import { StringDecoder } from "node:string_decoder";
10443
+ function isObject(v) {
10444
+ return typeof v === "object" && v !== null && !Array.isArray(v);
10445
+ }
10446
+ function assistantText(message) {
10447
+ if (!isObject(message) || !Array.isArray(message.content)) return "";
10448
+ let out = "";
10449
+ for (const block of message.content) {
10450
+ if (isObject(block) && block.type === "text" && typeof block.text === "string") {
10451
+ out += block.text;
10452
+ }
10453
+ }
10454
+ return out;
10455
+ }
10456
+ function parseClaudeStream() {
10457
+ const decoder = new StringDecoder("utf8");
10458
+ let buffer = "";
10459
+ let accumulated = "";
10460
+ let sawPartial = false;
10461
+ let finalText = null;
10462
+ let sessionId = null;
10463
+ let done = false;
10464
+ let isError = false;
10465
+ const handleLine = (line, deltas) => {
10466
+ const trimmed = line.trim();
10467
+ if (!trimmed) return;
10468
+ let evt;
10469
+ try {
10470
+ evt = JSON.parse(trimmed);
10471
+ } catch {
10472
+ return;
10473
+ }
10474
+ if (!isObject(evt)) return;
10475
+ if (typeof evt.session_id === "string") sessionId = evt.session_id;
10476
+ switch (evt.type) {
10477
+ case "stream_event": {
10478
+ const inner = evt.event;
10479
+ if (!isObject(inner) || inner.type !== "content_block_delta") return;
10480
+ const delta = inner.delta;
10481
+ if (isObject(delta) && delta.type === "text_delta" && typeof delta.text === "string") {
10482
+ sawPartial = true;
10483
+ if (delta.text) {
10484
+ accumulated += delta.text;
10485
+ deltas.push(delta.text);
10486
+ }
10487
+ }
10488
+ return;
10489
+ }
10490
+ case "assistant": {
10491
+ if (sawPartial) return;
10492
+ const text = assistantText(evt.message);
10493
+ if (text) {
10494
+ accumulated += text;
10495
+ deltas.push(text);
10496
+ }
10497
+ return;
10498
+ }
10499
+ case "result": {
10500
+ done = true;
10501
+ isError = evt.is_error === true;
10502
+ if (typeof evt.result === "string") finalText = evt.result;
10503
+ return;
10504
+ }
10505
+ default:
10506
+ return;
10507
+ }
10508
+ };
10509
+ const snapshot = () => ({
10510
+ text: finalText ?? accumulated,
10511
+ sessionId,
10512
+ done,
10513
+ isError
10514
+ });
10515
+ return {
10516
+ push(chunk) {
10517
+ buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
10518
+ const deltas = [];
10519
+ let nl;
10520
+ while ((nl = buffer.indexOf("\n")) !== -1) {
10521
+ const line = buffer.slice(0, nl);
10522
+ buffer = buffer.slice(nl + 1);
10523
+ handleLine(line, deltas);
10524
+ }
10525
+ return deltas;
10526
+ },
10527
+ finish() {
10528
+ const deltas = [];
10529
+ buffer += decoder.end();
10530
+ if (buffer) {
10531
+ const line = buffer;
10532
+ buffer = "";
10533
+ handleLine(line, deltas);
10534
+ }
10535
+ return { deltas, result: snapshot() };
10536
+ },
10537
+ get result() {
10538
+ return snapshot();
10539
+ }
10540
+ };
10541
+ }
10542
+
9767
10543
  // src/utils/usage-limit.ts
9768
10544
  var TAIL_CHARS = 4096;
9769
10545
  var CLI_LIMIT_PATTERNS = [
@@ -9886,21 +10662,21 @@ function nextZonedOccurrence(now, hour, minute, zone) {
9886
10662
  import { spawn as spawn5 } from "node:child_process";
9887
10663
  import {
9888
10664
  copyFileSync,
9889
- existsSync as existsSync11,
10665
+ existsSync as existsSync12,
9890
10666
  mkdirSync as mkdirSync8,
9891
10667
  readdirSync as readdirSync2,
9892
10668
  readFileSync as readFileSync6,
9893
10669
  realpathSync as realpathSync3,
9894
- rmSync as rmSync3,
10670
+ rmSync as rmSync4,
9895
10671
  statSync as statSync4,
9896
10672
  utimesSync,
9897
- writeFileSync as writeFileSync9
10673
+ writeFileSync as writeFileSync10
9898
10674
  } from "node:fs";
9899
10675
  import { basename as basename3, dirname as dirname5, join as join13 } from "node:path";
9900
10676
 
9901
10677
  // src/utils/install-cache.ts
9902
10678
  import { createHash } from "node:crypto";
9903
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync5, writeFileSync as writeFileSync8 } from "node:fs";
10679
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync5, writeFileSync as writeFileSync9 } from "node:fs";
9904
10680
  import { basename as basename2, join as join12 } from "node:path";
9905
10681
  var LOCKFILES = [
9906
10682
  ["pnpm-lock.yaml", "pnpm"],
@@ -9967,7 +10743,7 @@ function readInstallMarker(storeDir) {
9967
10743
  }
9968
10744
  function writeInstallMarker(storeDir, marker) {
9969
10745
  mkdirSync7(storeDir, { recursive: true });
9970
- writeFileSync8(join12(storeDir, MARKER_FILE), `${JSON.stringify(marker, null, 2)}
10746
+ writeFileSync9(join12(storeDir, MARKER_FILE), `${JSON.stringify(marker, null, 2)}
9971
10747
  `);
9972
10748
  }
9973
10749
  function markerMatches(marker, lockHash, pmVersion) {
@@ -10113,6 +10889,10 @@ function gitReason(text) {
10113
10889
  );
10114
10890
  return notProgress.at(-1) ?? lines.at(-1) ?? "";
10115
10891
  }
10892
+ function installCommand2(dir, exists = existsSync12, opts = {}) {
10893
+ const found = detectLockfile(dir, exists);
10894
+ return found ? [found.pm, installArgs(found.pm, opts)] : null;
10895
+ }
10116
10896
  function githubCompareUrl(remoteUrl, baseBranch, branch) {
10117
10897
  const m = /^https?:\/\/(?:[^@/]+@)?github\.com\/([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(remoteUrl.trim()) ?? /^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(remoteUrl.trim());
10118
10898
  if (!m) return null;
@@ -10149,7 +10929,7 @@ var RunWorkspaceManager = class {
10149
10929
  this.run = deps.run ?? defaultCommandRunner;
10150
10930
  this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
10151
10931
  this.runsRoot = deps.runsRoot ?? join13(getConfigDir(), "runs");
10152
- this.exists = deps.exists ?? existsSync11;
10932
+ this.exists = deps.exists ?? existsSync12;
10153
10933
  this.copyFile = deps.copyFile ?? ((from, to) => {
10154
10934
  mkdirSync8(dirname5(to), { recursive: true });
10155
10935
  copyFileSync(from, to);
@@ -10185,7 +10965,7 @@ var RunWorkspaceManager = class {
10185
10965
  */
10186
10966
  markActive(dir) {
10187
10967
  try {
10188
- writeFileSync9(
10968
+ writeFileSync10(
10189
10969
  activeMarkerPath(dir),
10190
10970
  formatActiveMarker({ pid: this.pid, startedAt: this.now().toISOString() })
10191
10971
  );
@@ -10198,7 +10978,7 @@ var RunWorkspaceManager = class {
10198
10978
  }
10199
10979
  }
10200
10980
  clearActive(dir) {
10201
- rmSync3(activeMarkerPath(dir), { force: true });
10981
+ rmSync4(activeMarkerPath(dir), { force: true });
10202
10982
  }
10203
10983
  /** Whether a `.active` marker still protects this folder from pruning. */
10204
10984
  activeByMarker(dir) {
@@ -10229,7 +11009,7 @@ var RunWorkspaceManager = class {
10229
11009
  }
10230
11010
  for (const name of orphanMarkers(entries)) {
10231
11011
  try {
10232
- rmSync3(join13(this.runsRoot, name), { force: true });
11012
+ rmSync4(join13(this.runsRoot, name), { force: true });
10233
11013
  } catch {
10234
11014
  }
10235
11015
  }
@@ -10357,7 +11137,7 @@ var RunWorkspaceManager = class {
10357
11137
  if (removed.status === 0) {
10358
11138
  pruned += 1;
10359
11139
  this.clearActive(dir);
10360
- rmSync3(waitingMarkerPath(dir), { force: true });
11140
+ rmSync4(waitingMarkerPath(dir), { force: true });
10361
11141
  }
10362
11142
  }
10363
11143
  return pruned;
@@ -10453,7 +11233,7 @@ var RunWorkspaceManager = class {
10453
11233
  const result = await this.reopenLocked(input);
10454
11234
  if (result.ok) {
10455
11235
  this.markActive(result.workspace.dir);
10456
- rmSync3(waitingMarkerPath(result.workspace.dir), { force: true });
11236
+ rmSync4(waitingMarkerPath(result.workspace.dir), { force: true });
10457
11237
  }
10458
11238
  return result;
10459
11239
  });
@@ -10719,7 +11499,7 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
10719
11499
  const result = await this.finishLocked(input);
10720
11500
  if (input.waiting?.keepRunCopy && result.keptWorktree) {
10721
11501
  try {
10722
- writeFileSync9(waitingMarkerPath(result.keptWorktree), `${input.jobId}
11502
+ writeFileSync10(waitingMarkerPath(result.keptWorktree), `${input.jobId}
10723
11503
  `);
10724
11504
  } catch {
10725
11505
  }
@@ -11112,12 +11892,12 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
11112
11892
  };
11113
11893
 
11114
11894
  // src/utils/wrap-up.ts
11115
- import { readFileSync as readFileSync8 } from "node:fs";
11116
- import { join as join15 } from "node:path";
11895
+ import { copyFileSync as copyFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync3, readFileSync as readFileSync8, rmSync as rmSync5 } from "node:fs";
11896
+ import { tmpdir as tmpdir3 } from "node:os";
11897
+ import { dirname as dirname6, join as join15 } from "node:path";
11117
11898
 
11118
11899
  // src/utils/project-checks.ts
11119
- import { spawn as spawn6 } from "node:child_process";
11120
- import { existsSync as existsSync12, readdirSync as readdirSync3, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
11900
+ import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
11121
11901
  import { join as join14, relative as relative2 } from "node:path";
11122
11902
  var DEFAULT_CHECK_SCRIPTS = ["typecheck", "lint", "test"];
11123
11903
  var CHECKS_CONFIG_FILE = join14(".compbox", "checks.json");
@@ -11131,8 +11911,8 @@ function isRecord(value) {
11131
11911
  return typeof value === "object" && value !== null && !Array.isArray(value);
11132
11912
  }
11133
11913
  function packageManagerFor(rootDir) {
11134
- if (existsSync12(join14(rootDir, "pnpm-lock.yaml"))) return "pnpm";
11135
- if (existsSync12(join14(rootDir, "yarn.lock"))) return "yarn";
11914
+ if (existsSync13(join14(rootDir, "pnpm-lock.yaml"))) return "pnpm";
11915
+ if (existsSync13(join14(rootDir, "yarn.lock"))) return "yarn";
11136
11916
  return "npm";
11137
11917
  }
11138
11918
  function workspacePatterns(rootDir, rootPkg) {
@@ -11143,7 +11923,7 @@ function workspacePatterns(rootDir, rootPkg) {
11143
11923
  patterns.push(...ws.packages.filter((p) => typeof p === "string"));
11144
11924
  }
11145
11925
  const pnpmFile = join14(rootDir, "pnpm-workspace.yaml");
11146
- if (existsSync12(pnpmFile)) {
11926
+ if (existsSync13(pnpmFile)) {
11147
11927
  let inPackages = false;
11148
11928
  for (const raw of readFileSync7(pnpmFile, "utf-8").split("\n")) {
11149
11929
  const line = raw.replace(/#.*$/, "").trimEnd();
@@ -11167,16 +11947,16 @@ function expandPatterns(rootDir, patterns) {
11167
11947
  const clean = pattern.replace(/\/+$/, "");
11168
11948
  if (clean.endsWith("/*") || clean.endsWith("/**")) {
11169
11949
  const parent = join14(rootDir, clean.replace(/\/\*\*?$/, ""));
11170
- if (!existsSync12(parent)) continue;
11950
+ if (!existsSync13(parent)) continue;
11171
11951
  for (const entry of readdirSync3(parent).sort()) {
11172
11952
  const dir = join14(parent, entry);
11173
- if (entry !== "node_modules" && statSync5(dir).isDirectory() && existsSync12(join14(dir, "package.json"))) {
11953
+ if (entry !== "node_modules" && statSync5(dir).isDirectory() && existsSync13(join14(dir, "package.json"))) {
11174
11954
  dirs.add(dir);
11175
11955
  }
11176
11956
  }
11177
11957
  } else if (!clean.includes("*")) {
11178
11958
  const dir = join14(rootDir, clean);
11179
- if (existsSync12(join14(dir, "package.json"))) dirs.add(dir);
11959
+ if (existsSync13(join14(dir, "package.json"))) dirs.add(dir);
11180
11960
  }
11181
11961
  }
11182
11962
  return [...dirs];
@@ -11222,7 +12002,7 @@ function checksFromConfig(config, warnings) {
11222
12002
  function resolveProjectChecks(rootDir) {
11223
12003
  const warnings = [];
11224
12004
  const configPath = join14(rootDir, CHECKS_CONFIG_FILE);
11225
- if (existsSync12(configPath)) {
12005
+ if (existsSync13(configPath)) {
11226
12006
  let config;
11227
12007
  try {
11228
12008
  config = readJson(configPath);
@@ -11234,7 +12014,7 @@ function resolveProjectChecks(rootDir) {
11234
12014
  }
11235
12015
  let rootPkg = null;
11236
12016
  try {
11237
- const value = existsSync12(join14(rootDir, "package.json")) ? readJson(join14(rootDir, "package.json")) : null;
12017
+ const value = existsSync13(join14(rootDir, "package.json")) ? readJson(join14(rootDir, "package.json")) : null;
11238
12018
  rootPkg = isRecord(value) ? value : null;
11239
12019
  } catch {
11240
12020
  rootPkg = null;
@@ -11269,50 +12049,59 @@ function outputTail(output, lines = OUTPUT_TAIL_LINES) {
11269
12049
  const tail = output.trimEnd().split("\n").slice(-lines).join("\n");
11270
12050
  return tail.length > OUTPUT_TAIL_CHARS ? tail.slice(-OUTPUT_TAIL_CHARS) : tail;
11271
12051
  }
11272
- var defaultCheckRunner = (command, args, cwd, timeoutMs) => new Promise((resolve4) => {
11273
- let output = "";
11274
- let settled = false;
11275
- const done = (result) => {
11276
- if (settled) return;
11277
- settled = true;
11278
- clearTimeout(timer);
11279
- resolve4(result);
11280
- };
11281
- const child = spawn6(command, args, {
11282
- cwd,
11283
- stdio: ["ignore", "pipe", "pipe"],
11284
- // CI=1 keeps test runners out of watch mode and interactive prompts.
11285
- env: {
11286
- ...process.env,
11287
- PATH: claudeChildEnvPath(process.env.PATH),
11288
- CI: "1",
11289
- GIT_TERMINAL_PROMPT: "0"
11290
- },
11291
- detached: process.platform !== "win32"
11292
- });
11293
- const append = (chunk) => {
11294
- output += chunk.toString("utf-8");
11295
- if (output.length > 2e5) output = output.slice(-1e5);
11296
- };
11297
- const timer = setTimeout(() => {
11298
- try {
11299
- if (child.pid && process.platform !== "win32") process.kill(-child.pid, "SIGKILL");
11300
- else child.kill("SIGKILL");
11301
- } catch {
11302
- child.kill("SIGKILL");
11303
- }
11304
- done({ exitCode: 1, output, timedOut: true });
11305
- }, timeoutMs);
11306
- child.stdout.on("data", append);
11307
- child.stderr.on("data", append);
11308
- child.on("error", (error) => {
11309
- done({ exitCode: 1, output: `${output}
12052
+ function createCheckRunner(deps = {}) {
12053
+ const platform = deps.platform ?? process.platform;
12054
+ const killDeps = { ...deps.processGroup, platform };
12055
+ return (command, args, cwd, timeoutMs) => new Promise((resolve4) => {
12056
+ let output = "";
12057
+ let settled = false;
12058
+ const done = (result) => {
12059
+ if (settled) return;
12060
+ settled = true;
12061
+ clearTimeout(timer);
12062
+ resolve4(result);
12063
+ };
12064
+ const child = spawnCrossPlatform(
12065
+ command,
12066
+ args,
12067
+ {
12068
+ cwd,
12069
+ stdio: ["ignore", "pipe", "pipe"],
12070
+ // CI=1 keeps test runners out of watch mode and interactive prompts.
12071
+ env: {
12072
+ ...process.env,
12073
+ PATH: claudeChildEnvPath(process.env.PATH),
12074
+ CI: "1",
12075
+ GIT_TERMINAL_PROMPT: "0"
12076
+ },
12077
+ ...groupSpawnOptions(platform)
12078
+ },
12079
+ {
12080
+ platform,
12081
+ ...deps.spawn ? { spawn: deps.spawn } : {},
12082
+ ...deps.exists ? { exists: deps.exists } : {}
12083
+ }
12084
+ );
12085
+ const append = (chunk) => {
12086
+ output += chunk.toString("utf-8");
12087
+ if (output.length > 2e5) output = output.slice(-1e5);
12088
+ };
12089
+ const timer = setTimeout(() => {
12090
+ killProcessTree(child, killDeps);
12091
+ done({ exitCode: 1, output, timedOut: true });
12092
+ }, timeoutMs);
12093
+ child.stdout?.on("data", append);
12094
+ child.stderr?.on("data", append);
12095
+ child.on("error", (error) => {
12096
+ done({ exitCode: 1, output: `${output}
11310
12097
  ${error.message}`, timedOut: false });
12098
+ });
12099
+ child.on("close", (code) => {
12100
+ done({ exitCode: code ?? 1, output, timedOut: false });
12101
+ });
11311
12102
  });
11312
- child.on("close", (code) => {
11313
- done({ exitCode: code ?? 1, output, timedOut: false });
11314
- });
11315
- });
12103
+ }
12104
+ var defaultCheckRunner = createCheckRunner();
11316
12105
  async function runProjectChecks(rootDir, checks, deps = {}) {
11317
12106
  const runner = deps.runner ?? defaultCheckRunner;
11318
12107
  const now = deps.now ?? Date.now;
@@ -11339,6 +12128,11 @@ Timed out after ${String(Math.round(check.timeoutMs / 1e3))}s.`.trim() : tail
11339
12128
  var WRAP_UP_MAX_MIGRATION_SQL = 2e5;
11340
12129
  var WRAP_UP_MAX_COMMENT = 5e4;
11341
12130
  var MIGRATION_FILE = /prisma\/migrations[^/]*\/[^/]+\/migration\.sql$/;
12131
+ var BASE_COMPARE_BUDGET_MS = 15 * 60 * 1e3;
12132
+ function checkGroup(check) {
12133
+ if (check.passed) return "passed";
12134
+ return check.classification ?? "caused";
12135
+ }
11342
12136
  function parseNameStatus(output) {
11343
12137
  const files = [];
11344
12138
  for (const line of output.split("\n")) {
@@ -11362,6 +12156,162 @@ function defaultRunChecks(dir) {
11362
12156
  warnings: resolved.warnings
11363
12157
  }));
11364
12158
  }
12159
+ function defaultRetryChecks(dir, failed) {
12160
+ const names = new Set(failed.map((c) => c.name));
12161
+ return runProjectChecks(
12162
+ dir,
12163
+ resolveProjectChecks(dir).checks.filter((c) => names.has(c.name))
12164
+ );
12165
+ }
12166
+ function firstLine(text) {
12167
+ return text.trim().split("\n")[0]?.trim() ?? "";
12168
+ }
12169
+ async function compareWithBase(input, deps) {
12170
+ if (input.failed.length === 0) return { failingOnBase: /* @__PURE__ */ new Set() };
12171
+ const now = deps.now ?? Date.now;
12172
+ const budgetMs = deps.budgetMs ?? BASE_COMPARE_BUDGET_MS;
12173
+ const exists = deps.exists ?? existsSync14;
12174
+ const removeDir = deps.removeDir ?? ((path3) => {
12175
+ rmSync5(path3, { recursive: true, force: true });
12176
+ });
12177
+ const copyFile = deps.copyFile ?? ((from, to) => {
12178
+ mkdirSync9(dirname6(to), { recursive: true });
12179
+ copyFileSync2(from, to);
12180
+ });
12181
+ const resolveChecks = deps.resolveChecks ?? ((dir) => resolveProjectChecks(dir).checks);
12182
+ const started = now();
12183
+ const skipped = (why) => ({
12184
+ failingOnBase: null,
12185
+ note: `The failing checks weren't compared with \`${input.baseRef}\`: ${why}`
12186
+ });
12187
+ const mergeBase = await deps.run("git", ["merge-base", "HEAD", input.baseRef], input.dir);
12188
+ const sha = mergeBase.stdout.trim();
12189
+ if (mergeBase.status !== 0 || !sha) {
12190
+ return skipped(`git merge-base failed (${firstLine(mergeBase.stderr) || "no common commit"}).`);
12191
+ }
12192
+ let baseDir;
12193
+ try {
12194
+ baseDir = (deps.makeTempDir ?? (() => mkdtempSync3(join15(tmpdir3(), "compbox-base-"))))();
12195
+ } catch (error) {
12196
+ return skipped(`couldn't create a temporary folder (${errorText(error)}).`);
12197
+ }
12198
+ let added = false;
12199
+ try {
12200
+ const add = await deps.run("git", ["worktree", "add", "--detach", baseDir, sha], input.dir);
12201
+ if (add.status !== 0) {
12202
+ return skipped(`git worktree add failed (${firstLine(add.stderr) || "unknown error"}).`);
12203
+ }
12204
+ added = true;
12205
+ const ignored = await deps.run(
12206
+ "git",
12207
+ ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory"],
12208
+ input.dir
12209
+ );
12210
+ const untracked = await deps.run("git", ["ls-files", "--others", "--exclude-standard"], input.dir);
12211
+ const candidates = new Set(
12212
+ `${ignored.status === 0 ? ignored.stdout : ""}
12213
+ ${untracked.status === 0 ? untracked.stdout : ""}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.endsWith("/") && isLocalConfigFile(p))
12214
+ );
12215
+ for (const path3 of candidates) {
12216
+ try {
12217
+ copyFile(join15(input.dir, path3), join15(baseDir, path3));
12218
+ } catch {
12219
+ }
12220
+ }
12221
+ const install = installCommand2(baseDir, exists);
12222
+ if (install) {
12223
+ const res = await deps.run(install[0], install[1], baseDir);
12224
+ if (res.status !== 0) {
12225
+ return skipped(`installing dependencies failed (${firstLine(res.stderr) || "unknown error"}).`);
12226
+ }
12227
+ }
12228
+ const available = new Map(resolveChecks(baseDir).map((c) => [c.name, c]));
12229
+ const failingOnBase = /* @__PURE__ */ new Set();
12230
+ const notRun = [];
12231
+ for (const failed of input.failed) {
12232
+ const check = available.get(failed.name);
12233
+ const remaining = budgetMs - (now() - started);
12234
+ if (!check || remaining <= 0) {
12235
+ notRun.push(failed.name);
12236
+ continue;
12237
+ }
12238
+ const [result] = await runProjectChecks(
12239
+ baseDir,
12240
+ [{ ...check, timeoutMs: Math.min(check.timeoutMs, remaining) }],
12241
+ { ...deps.checkRunner ? { runner: deps.checkRunner } : {}, now }
12242
+ );
12243
+ if (result && !result.passed && !result.timedOut) failingOnBase.add(failed.name);
12244
+ else if (result?.timedOut) notRun.push(failed.name);
12245
+ }
12246
+ return notRun.length > 0 ? {
12247
+ failingOnBase,
12248
+ note: `Couldn't tell whether ${notRun.map((n) => `\`${n}\``).join(", ")} also ${notRun.length === 1 ? "fails" : "fail"} on \`${input.baseRef}\` (missing there, or out of time), so ${notRun.length === 1 ? "it counts" : "they count"} as caused by this build.`
12249
+ } : { failingOnBase };
12250
+ } catch (error) {
12251
+ return skipped(`${errorText(error)}.`);
12252
+ } finally {
12253
+ let removed = false;
12254
+ if (added) {
12255
+ try {
12256
+ const res = await deps.run("git", ["worktree", "remove", "--force", baseDir], input.dir);
12257
+ removed = res.status === 0;
12258
+ } catch {
12259
+ removed = false;
12260
+ }
12261
+ }
12262
+ if (!removed) {
12263
+ try {
12264
+ removeDir(baseDir);
12265
+ } catch {
12266
+ }
12267
+ if (added) {
12268
+ try {
12269
+ await deps.run("git", ["worktree", "prune"], input.dir);
12270
+ } catch {
12271
+ }
12272
+ }
12273
+ }
12274
+ }
12275
+ }
12276
+ async function classifyChecks(input, deps) {
12277
+ const warnings = [];
12278
+ const retryable = input.checks.filter((c) => !c.passed && !c.timedOut);
12279
+ const retried = /* @__PURE__ */ new Map();
12280
+ if (deps.retryChecks && retryable.length > 0) {
12281
+ try {
12282
+ for (const result of await deps.retryChecks(input.dir, retryable)) retried.set(result.name, result);
12283
+ } catch (error) {
12284
+ warnings.push(`The failed checks couldn't be run again: ${errorText(error)}.`);
12285
+ }
12286
+ }
12287
+ let checks = input.checks.map((check) => {
12288
+ if (check.passed) return check;
12289
+ const again = retried.get(check.name);
12290
+ if (!again) return { ...check, classification: "caused" };
12291
+ if (again.passed) return { ...check, retried: true, classification: "flaky" };
12292
+ return { ...again, retried: true, classification: "caused" };
12293
+ });
12294
+ const stillFailing = checks.filter((c) => c.classification === "caused" && !c.timedOut);
12295
+ if (deps.compareWithBase && stillFailing.length > 0) {
12296
+ try {
12297
+ const comparison = await deps.compareWithBase({
12298
+ dir: input.dir,
12299
+ baseRef: input.baseRef,
12300
+ failed: stillFailing
12301
+ });
12302
+ const onBase = comparison.failingOnBase;
12303
+ if (onBase) {
12304
+ checks = checks.map(
12305
+ (c) => c.classification === "caused" && !c.timedOut && onBase.has(c.name) ? { ...c, classification: "base" } : c
12306
+ );
12307
+ }
12308
+ if (comparison.note) warnings.push(comparison.note);
12309
+ } catch (error) {
12310
+ warnings.push(`The failing checks couldn't be compared with \`${input.baseRef}\`: ${errorText(error)}.`);
12311
+ }
12312
+ }
12313
+ return { checks, warnings };
12314
+ }
11365
12315
  function migrationLine(entry) {
11366
12316
  if (typeof entry !== "object" || entry === null) return null;
11367
12317
  const m = entry;
@@ -11371,7 +12321,8 @@ function migrationLine(entry) {
11371
12321
  return `- \`${m.path}\` \u2014 ${safety}${reasons.length > 0 ? `: ${reasons.join("; ")}` : ""}`;
11372
12322
  }
11373
12323
  function buildReviewComment(input) {
11374
- const heading = input.status === "ready" ? "\u2705 **Ready for you** \u2014 every check passed and no gaps were found." : input.status === "needs_decision" ? "\u26A0\uFE0F **Needs a decision** \u2014 this pull request stays a draft." : "\u274C **Wrap-up failed** \u2014 this pull request stays a draft.";
12324
+ const allPassed = input.checks.every((c) => c.passed);
12325
+ const heading = input.status === "ready" ? allPassed ? "\u2705 **Ready for you** \u2014 every check passed and no gaps were found." : "\u2705 **Ready for you** \u2014 no check failures were caused by this build and no gaps were found." : input.status === "needs_decision" ? "\u26A0\uFE0F **Needs a decision** \u2014 this pull request stays a draft." : "\u274C **Wrap-up failed** \u2014 this pull request stays a draft.";
11375
12326
  const lines = ["## CompBox build wrap-up", "", heading];
11376
12327
  if (input.reasons.length > 0) {
11377
12328
  lines.push("", ...input.reasons.map((r) => `- ${r}`));
@@ -11389,13 +12340,38 @@ function buildReviewComment(input) {
11389
12340
  else lines.push(merge.reason);
11390
12341
  lines.push("", "### Checks");
11391
12342
  if (input.checks.length === 0) lines.push("No checks were found to run.");
11392
- for (const check of input.checks) {
11393
- const mark = check.passed ? "\u2705" : check.timedOut ? "\u23F1\uFE0F" : "\u274C";
12343
+ const checkLine = (check) => {
12344
+ const mark = check.passed ? "\u2705" : check.timedOut ? "\u23F1\uFE0F" : checkGroup(check) === "flaky" ? "\u{1F501}" : "\u274C";
11394
12345
  const where = check.cwd === "." ? "" : ` (${check.cwd})`;
11395
- lines.push(`- ${mark} \`${check.name}\`${where} \u2014 ${String(Math.round(check.durationMs / 1e3))}s`);
12346
+ return `- ${mark} \`${check.name}\`${where} \u2014 ${String(Math.round(check.durationMs / 1e3))}s`;
12347
+ };
12348
+ const group = (g) => input.checks.filter((c) => checkGroup(c) === g);
12349
+ const caused = group("caused");
12350
+ const onBase = group("base");
12351
+ const flaky = group("flaky");
12352
+ lines.push(...group("passed").map(checkLine));
12353
+ if (caused.length > 0) {
12354
+ lines.push("", "#### Caused by this build", ...caused.map(checkLine));
12355
+ }
12356
+ if (onBase.length > 0) {
12357
+ lines.push(
12358
+ "",
12359
+ `#### Already failing on \`${input.baseBranch}\``,
12360
+ "These fail on the base branch too, so they don't hold this pull request back.",
12361
+ ...onBase.map(checkLine)
12362
+ );
11396
12363
  }
12364
+ if (flaky.length > 0) {
12365
+ lines.push(
12366
+ "",
12367
+ "#### Flaky",
12368
+ "These failed, then passed when run again.",
12369
+ ...flaky.map(checkLine)
12370
+ );
12371
+ }
12372
+ if (input.checkWarnings.length > 0) lines.push("");
11397
12373
  for (const warning of input.checkWarnings) lines.push(`- \u26A0\uFE0F ${warning}`);
11398
- for (const check of input.checks.filter((c) => !c.passed && c.outputTail)) {
12374
+ for (const check of [...caused, ...onBase, ...flaky].filter((c) => c.outputTail)) {
11399
12375
  lines.push(
11400
12376
  "",
11401
12377
  `<details><summary>${check.name} output</summary>`,
@@ -11421,6 +12397,8 @@ function buildReviewComment(input) {
11421
12397
  function createWrapUp(deps) {
11422
12398
  const { client } = deps;
11423
12399
  const runChecks = deps.runChecks ?? defaultRunChecks;
12400
+ const retryChecks = deps.retryChecks ?? (deps.runChecks ? void 0 : defaultRetryChecks);
12401
+ const compare = deps.compareWithBase ?? (deps.runChecks ? void 0 : (i) => compareWithBase(i, { run: deps.run }));
11424
12402
  const readFile3 = deps.readFile ?? ((path3) => readFileSync8(path3, "utf-8"));
11425
12403
  return async (input) => {
11426
12404
  const reasons = [];
@@ -11452,7 +12430,15 @@ function createWrapUp(deps) {
11452
12430
  } catch (error) {
11453
12431
  failures.push(`The project checks couldn't be run: ${errorText(error)}.`);
11454
12432
  }
11455
- for (const check of checks.filter((c) => !c.passed)) {
12433
+ if (checks.some((c) => !c.passed)) {
12434
+ const classified = await classifyChecks(
12435
+ { dir: input.dir, baseRef: input.baseRef, checks },
12436
+ { ...retryChecks ? { retryChecks } : {}, ...compare ? { compareWithBase: compare } : {} }
12437
+ );
12438
+ checks = classified.checks;
12439
+ checkWarnings = [...checkWarnings, ...classified.warnings];
12440
+ }
12441
+ for (const check of checks.filter((c) => checkGroup(c) === "caused")) {
11456
12442
  failures.push(
11457
12443
  check.timedOut ? `The \`${check.name}\` check took too long and was stopped.` : `The \`${check.name}\` check failed.`
11458
12444
  );
@@ -11560,7 +12546,32 @@ function createWrapUp(deps) {
11560
12546
  }
11561
12547
 
11562
12548
  // src/utils/agent-invoker.ts
12549
+ function spawnPiped(spawnImpl, command, args, options, platform) {
12550
+ return spawnCrossPlatform(command, args, options, {
12551
+ spawn: spawnImpl,
12552
+ ...platform ? { platform } : {}
12553
+ });
12554
+ }
11563
12555
  var ANTHROPIC_MODEL = "claude-fable-5";
12556
+ var CHAT_MODEL = "claude-haiku-5-5";
12557
+ var SAVE_MODEL = ANTHROPIC_MODEL;
12558
+ function modelForTurn(kind, chosenChatModel = null) {
12559
+ if (kind !== "chat") return SAVE_MODEL;
12560
+ return chosenChatModel ?? CHAT_MODEL;
12561
+ }
12562
+ function chosenChatModelOf(payload) {
12563
+ let p = payload;
12564
+ if (typeof p === "string") {
12565
+ try {
12566
+ p = JSON.parse(p);
12567
+ } catch {
12568
+ return null;
12569
+ }
12570
+ }
12571
+ if (typeof p !== "object" || p === null) return null;
12572
+ const model = p.model;
12573
+ return isConversationChatModel(model) ? model : null;
12574
+ }
11564
12575
  var CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1e3;
11565
12576
  function anthropicClientOptions(apiKey, routing) {
11566
12577
  return routing.mode === "proxy" ? { apiKey, baseURL: routing.anthropicBaseUrl } : { apiKey };
@@ -11568,6 +12579,34 @@ function anthropicClientOptions(apiKey, routing) {
11568
12579
  function claudeSpawnEnv(base, routing) {
11569
12580
  return routing.mode === "proxy" ? { ...base, ANTHROPIC_BASE_URL: routing.anthropicBaseUrl } : base;
11570
12581
  }
12582
+ function withHooksDisabled(env, hooksDir) {
12583
+ const raw = env.GIT_CONFIG_COUNT?.trim();
12584
+ if (raw && !/^\d+$/.test(raw)) return env;
12585
+ const n = raw ? Number(raw) : 0;
12586
+ return {
12587
+ ...env,
12588
+ GIT_CONFIG_COUNT: String(n + 1),
12589
+ [`GIT_CONFIG_KEY_${String(n)}`]: "core.hooksPath",
12590
+ [`GIT_CONFIG_VALUE_${String(n)}`]: hooksDir
12591
+ };
12592
+ }
12593
+ function makeAgentHooksDir(runDir) {
12594
+ try {
12595
+ const dir = mkdtempSync4(join16(tmpdir4(), "compbox-nohooks-"));
12596
+ if (runDir) {
12597
+ const res = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-dir"], {
12598
+ cwd: runDir,
12599
+ encoding: "utf-8"
12600
+ });
12601
+ const gitDir = res.status === 0 ? res.stdout.trim() : "";
12602
+ const guard = gitDir ? join16(gitDir, "compbox-hooks", "pre-push") : "";
12603
+ if (guard && existsSync15(guard)) copyFileSync3(guard, join16(dir, "pre-push"));
12604
+ }
12605
+ return dir;
12606
+ } catch {
12607
+ return void 0;
12608
+ }
12609
+ }
11571
12610
  var SUPPORTED_IMAGE_MEDIA_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
11572
12611
  var MAX_IMAGE_BYTES_PER_TURN = 20 * 1024 * 1024;
11573
12612
  var defaultWarn = (message) => {
@@ -11620,7 +12659,9 @@ function selectAttachments(attachments, warn = defaultWarn) {
11620
12659
  continue;
11621
12660
  }
11622
12661
  if (selected.length >= MAX_ATTACHMENTS_PER_TURN) {
11623
- warn(`Skipping attachment ${att.id}: more than ${String(MAX_ATTACHMENTS_PER_TURN)} on one message.`);
12662
+ warn(
12663
+ `Skipping attachment ${att.id}: more than ${String(MAX_ATTACHMENTS_PER_TURN)} on one message.`
12664
+ );
11624
12665
  continue;
11625
12666
  }
11626
12667
  const size = typeof att.sizeBytes === "number" && att.sizeBytes > 0 ? att.sizeBytes : 0;
@@ -11710,7 +12751,10 @@ async function materializeAttachments(dir, attachments, fetchImpl = fetch, warn
11710
12751
  if (fetched.length > 0) await mkdir2(dir, { recursive: true });
11711
12752
  for (const f of fetched) {
11712
12753
  const mimeType = baseMime(f.attachment.mimeType);
11713
- const path3 = join16(dir, `attachment-${String(files.length + 1)}.${EXTENSION_BY_MIME[mimeType] ?? "bin"}`);
12754
+ const path3 = join16(
12755
+ dir,
12756
+ `attachment-${String(files.length + 1)}.${EXTENSION_BY_MIME[mimeType] ?? "bin"}`
12757
+ );
11714
12758
  try {
11715
12759
  await writeFile2(path3, f.bytes);
11716
12760
  files.push({ path: path3, mimeType });
@@ -11777,9 +12821,9 @@ async function submitAndScore(ctx, currentErId, draft) {
11777
12821
  return { erId: created.id, compliance: created.compliance };
11778
12822
  }
11779
12823
  function claudeCliSessionCwd() {
11780
- const dir = join16(homedir7(), ".compbox", "claude-sessions");
12824
+ const dir = join16(homedir8(), ".compbox", "claude-sessions");
11781
12825
  try {
11782
- mkdirSync9(dir, { recursive: true });
12826
+ mkdirSync10(dir, { recursive: true });
11783
12827
  } catch {
11784
12828
  }
11785
12829
  return dir;
@@ -11795,85 +12839,152 @@ function claudeToolArgs(attachmentsDir) {
11795
12839
  `Read(/${attachmentsDir}/**)`
11796
12840
  ];
11797
12841
  }
12842
+ function rejectsPartialMessagesFlag(stderr) {
12843
+ return stderr.includes("--include-partial-messages") && /unknown|unrecognized|invalid|unexpected|not supported/i.test(stderr);
12844
+ }
11798
12845
  function runClaudeCliTurn(prompt, opts) {
11799
12846
  return new Promise((resolve4, reject) => {
11800
12847
  const model = opts.model === void 0 ? ANTHROPIC_MODEL : opts.model;
11801
- const args = [
11802
- "-p",
11803
- prompt,
11804
- ...model ? ["--model", model] : [],
11805
- "--output-format",
11806
- "json",
11807
- ...claudeToolArgs(opts.attachmentsDir),
11808
- "--permission-mode",
11809
- "dontAsk",
11810
- "--safe-mode",
11811
- "--system-prompt",
11812
- opts.systemPrompt
11813
- ];
11814
- if (opts.resumeSessionId) {
11815
- args.push("--resume", opts.resumeSessionId);
11816
- }
12848
+ const onText = opts.onText;
12849
+ const streaming = typeof onText === "function";
12850
+ const buildArgs = (withPartial) => {
12851
+ const args = [
12852
+ "-p",
12853
+ prompt,
12854
+ ...model ? ["--model", model] : [],
12855
+ "--output-format",
12856
+ ...streaming ? ["stream-json", "--verbose", ...withPartial ? ["--include-partial-messages"] : []] : ["json"],
12857
+ ...claudeToolArgs(opts.attachmentsDir),
12858
+ "--permission-mode",
12859
+ "dontAsk",
12860
+ "--safe-mode",
12861
+ "--system-prompt",
12862
+ opts.systemPrompt
12863
+ ];
12864
+ if (opts.resumeSessionId) {
12865
+ args.push("--resume", opts.resumeSessionId);
12866
+ }
12867
+ return args;
12868
+ };
11817
12869
  const command = resolveClaudeBinary() ?? "claude";
11818
12870
  const pxpipeEnv = claudeSpawnEnv(process.env, opts.routing);
11819
- const child = spawn7(command, args, {
11820
- cwd: claudeCliSessionCwd(),
11821
- stdio: ["ignore", "pipe", "pipe"],
11822
- env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) }
11823
- });
11824
- let stdout2 = "";
11825
- let stderr = "";
11826
- let settled = false;
11827
- const timer = setTimeout(() => {
11828
- if (settled) return;
11829
- settled = true;
11830
- child.kill("SIGKILL");
11831
- reject(new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1e3)}s`));
11832
- }, CLAUDE_CLI_TURN_TIMEOUT_MS);
11833
- child.stdout.on("data", (chunk) => {
11834
- stdout2 += chunk.toString("utf-8");
11835
- });
11836
- child.stderr.on("data", (chunk) => {
11837
- stderr += chunk.toString("utf-8");
11838
- });
11839
- child.on("error", (error) => {
11840
- if (settled) return;
11841
- settled = true;
11842
- clearTimeout(timer);
11843
- if (error.code === "ENOENT") {
11844
- reject(new Error(claudeNotFoundMessage()));
11845
- return;
11846
- }
11847
- reject(error);
11848
- });
11849
- child.on("close", (code) => {
11850
- if (settled) return;
11851
- settled = true;
11852
- clearTimeout(timer);
11853
- if (code !== 0) {
11854
- reject(new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`));
11855
- return;
11856
- }
11857
- let parsed;
11858
- try {
11859
- parsed = JSON.parse(stdout2);
11860
- } catch {
11861
- reject(new Error(`claude CLI returned non-JSON output: ${stdout2.slice(0, 500)}`));
11862
- return;
11863
- }
11864
- const shaped = parsed;
11865
- if (shaped.is_error) {
11866
- reject(new Error(shaped.result ?? "claude CLI reported an error"));
11867
- return;
11868
- }
11869
- if (typeof shaped.result !== "string" || typeof shaped.session_id !== "string") {
12871
+ const attempt = (withPartial) => {
12872
+ const child = spawnPiped(
12873
+ spawn6,
12874
+ command,
12875
+ buildArgs(withPartial),
12876
+ {
12877
+ cwd: claudeCliSessionCwd(),
12878
+ stdio: ["ignore", "pipe", "pipe"],
12879
+ env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) }
12880
+ },
12881
+ void 0
12882
+ );
12883
+ let stdout2 = "";
12884
+ let stderr = "";
12885
+ let settled = false;
12886
+ let sawStdout = false;
12887
+ const stream = streaming ? parseClaudeStream() : null;
12888
+ const emit = (deltas) => {
12889
+ if (!onText || settled) return;
12890
+ for (const delta of deltas) {
12891
+ try {
12892
+ onText(delta);
12893
+ } catch {
12894
+ }
12895
+ }
12896
+ };
12897
+ const timer = setTimeout(() => {
12898
+ if (settled) return;
12899
+ settled = true;
12900
+ killProcessGroupNow(child);
11870
12901
  reject(
11871
- new Error("claude CLI returned an unexpected JSON shape (missing result/session_id).")
12902
+ new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1e3)}s`)
11872
12903
  );
11873
- return;
11874
- }
11875
- resolve4({ text: shaped.result, sessionId: shaped.session_id });
11876
- });
12904
+ }, CLAUDE_CLI_TURN_TIMEOUT_MS);
12905
+ child.stdout.on("data", (chunk) => {
12906
+ if (chunk.length > 0) sawStdout = true;
12907
+ if (stream) {
12908
+ emit(stream.push(chunk));
12909
+ return;
12910
+ }
12911
+ stdout2 += chunk.toString("utf-8");
12912
+ });
12913
+ child.stderr.on("data", (chunk) => {
12914
+ stderr += chunk.toString("utf-8");
12915
+ });
12916
+ child.on("error", (error) => {
12917
+ if (settled) return;
12918
+ settled = true;
12919
+ clearTimeout(timer);
12920
+ if (error.code === "ENOENT") {
12921
+ reject(new Error(claudeNotFoundMessage()));
12922
+ return;
12923
+ }
12924
+ reject(error);
12925
+ });
12926
+ child.on("close", (code) => {
12927
+ if (settled) return;
12928
+ if (stream) {
12929
+ const { deltas, result } = stream.finish();
12930
+ emit(deltas);
12931
+ settled = true;
12932
+ clearTimeout(timer);
12933
+ if (code !== 0) {
12934
+ if (withPartial && !sawStdout && rejectsPartialMessagesFlag(stderr)) {
12935
+ attempt(false);
12936
+ return;
12937
+ }
12938
+ reject(
12939
+ new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`)
12940
+ );
12941
+ return;
12942
+ }
12943
+ if (result.isError) {
12944
+ reject(new Error(result.text || "claude CLI reported an error"));
12945
+ return;
12946
+ }
12947
+ if (!result.done || result.sessionId === null) {
12948
+ reject(
12949
+ new Error(
12950
+ "claude CLI stream ended without a result event (missing result/session_id)."
12951
+ )
12952
+ );
12953
+ return;
12954
+ }
12955
+ resolve4({ text: result.text, sessionId: result.sessionId });
12956
+ return;
12957
+ }
12958
+ settled = true;
12959
+ clearTimeout(timer);
12960
+ if (code !== 0) {
12961
+ reject(
12962
+ new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`)
12963
+ );
12964
+ return;
12965
+ }
12966
+ let parsed;
12967
+ try {
12968
+ parsed = JSON.parse(stdout2);
12969
+ } catch {
12970
+ reject(new Error(`claude CLI returned non-JSON output: ${stdout2.slice(0, 500)}`));
12971
+ return;
12972
+ }
12973
+ const shaped = parsed;
12974
+ if (shaped.is_error) {
12975
+ reject(new Error(shaped.result ?? "claude CLI reported an error"));
12976
+ return;
12977
+ }
12978
+ if (typeof shaped.result !== "string" || typeof shaped.session_id !== "string") {
12979
+ reject(
12980
+ new Error("claude CLI returned an unexpected JSON shape (missing result/session_id).")
12981
+ );
12982
+ return;
12983
+ }
12984
+ resolve4({ text: shaped.result, sessionId: shaped.session_id });
12985
+ });
12986
+ };
12987
+ attempt(streaming);
11877
12988
  });
11878
12989
  }
11879
12990
  async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId, discussed) {
@@ -11896,6 +13007,30 @@ function needsDefaultModel(error) {
11896
13007
  message
11897
13008
  );
11898
13009
  }
13010
+ var MAX_CONVERSATION_SESSIONS = 50;
13011
+ var conversationSessions = /* @__PURE__ */ new Map();
13012
+ function rememberConversationSession(jobId, session) {
13013
+ conversationSessions.delete(jobId);
13014
+ conversationSessions.set(jobId, session);
13015
+ while (conversationSessions.size > MAX_CONVERSATION_SESSIONS) {
13016
+ const oldest = conversationSessions.keys().next().value;
13017
+ if (oldest === void 0) break;
13018
+ conversationSessions.delete(oldest);
13019
+ }
13020
+ }
13021
+ function sessionMessageKey(m) {
13022
+ return `${m.role}\0${contentText(m.content)}`;
13023
+ }
13024
+ function extendsSession(seen, next) {
13025
+ if (next.length <= seen.length) return false;
13026
+ return seen.every((key, i) => next[i] === key);
13027
+ }
13028
+ function renderResumePrompt(fresh) {
13029
+ const lines = fresh.map((m) => `${m.role === "assistant" ? "You" : "Them"}: ${contentText(m.content)}`);
13030
+ return `${lines.join("\n\n")}
13031
+
13032
+ Write your next reply to them.`;
13033
+ }
11899
13034
  function savedRequestIdOf(job) {
11900
13035
  const result = job.result;
11901
13036
  if (typeof result?.epicRequestId === "string") return result.epicRequestId;
@@ -11917,6 +13052,7 @@ Send another message (for example "try again") and I'll pick up where we left of
11917
13052
  }
11918
13053
  }
11919
13054
  async function takeConversationStep(job, ctx) {
13055
+ const timer = startTurnTimer();
11920
13056
  const routing = await resolveRouting();
11921
13057
  const requestId = savedRequestIdOf(job);
11922
13058
  const discussed = requestId !== null && parseSeedPayload(job.payload)?.targetEpicRequestId === requestId;
@@ -11925,20 +13061,41 @@ async function takeConversationStep(job, ctx) {
11925
13061
  const hasAttachments = job.turns.some(
11926
13062
  (t) => t.role === "user" && (t.attachments?.length ?? 0) > 0
11927
13063
  );
11928
- const attachmentsDir = !anthropic && hasAttachments ? await realpath(await mkdtemp(join16(tmpdir2(), "compbox-attachments-"))) : void 0;
13064
+ const attachmentsDir = !anthropic && hasAttachments ? await realpath(await mkdtemp(join16(tmpdir4(), "compbox-attachments-"))) : void 0;
11929
13065
  try {
11930
13066
  return await converseWithAttachments(job, ctx, {
11931
13067
  routing,
11932
13068
  saved,
11933
13069
  anthropic,
11934
- attachmentsDir
13070
+ attachmentsDir,
13071
+ timer
11935
13072
  });
11936
13073
  } finally {
11937
13074
  if (attachmentsDir) await rm(attachmentsDir, { recursive: true, force: true });
11938
13075
  }
11939
13076
  }
13077
+ function startTurnTimer(now = () => performance.now()) {
13078
+ const startedAt = now();
13079
+ let firstTextAt = null;
13080
+ const elapsed = (at) => Math.max(0, Math.round(at - startedAt));
13081
+ return {
13082
+ markFirstText() {
13083
+ firstTextAt ??= now();
13084
+ },
13085
+ finish(model) {
13086
+ const metrics = {
13087
+ firstTokenMs: firstTextAt === null ? null : elapsed(firstTextAt),
13088
+ totalMs: elapsed(now())
13089
+ };
13090
+ if (model) metrics.model = model;
13091
+ return metrics;
13092
+ }
13093
+ };
13094
+ }
11940
13095
  async function converseWithAttachments(job, ctx, step) {
11941
13096
  const { routing, saved, anthropic, attachmentsDir } = step;
13097
+ const timer = step.timer ?? startTurnTimer();
13098
+ let replyModel = null;
11942
13099
  let usedFiles = false;
11943
13100
  const turns = [];
11944
13101
  for (const [index, t] of job.turns.entries()) {
@@ -11958,41 +13115,75 @@ async function converseWithAttachments(job, ctx, step) {
11958
13115
  }
11959
13116
  }
11960
13117
  const readDir = usedFiles ? attachmentsDir : void 0;
11961
- let cliModel = ANTHROPIC_MODEL;
13118
+ let useDefaultModel = false;
13119
+ const chosenChatModel = chosenChatModelOf(job.payload);
11962
13120
  const outcome = await runConversationStep(
11963
13121
  { turns, saved },
11964
13122
  {
11965
- reply: async (system, messages) => {
13123
+ reply: async (system, messages, kind) => {
13124
+ const model = modelForTurn(kind, chosenChatModel);
11966
13125
  if (anthropic) {
11967
13126
  const response = await anthropic.messages.create({
11968
- model: ANTHROPIC_MODEL,
13127
+ model,
11969
13128
  max_tokens: 4096,
11970
13129
  system,
11971
13130
  messages
11972
13131
  });
11973
13132
  const text = response.content.find((b) => b.type === "text");
11974
- return text?.type === "text" ? text.text : "";
13133
+ const reply = text?.type === "text" ? text.text : "";
13134
+ replyModel = response.model || model;
13135
+ if (reply) timer.markFirstText();
13136
+ return reply;
11975
13137
  }
11976
- const prompt = renderConversationPrompt(messages);
11977
- try {
11978
- return (await runClaudeCliTurn(prompt, {
11979
- systemPrompt: system,
11980
- resumeSessionId: void 0,
11981
- routing,
11982
- model: cliModel,
11983
- attachmentsDir: readDir
11984
- })).text;
11985
- } catch (error) {
11986
- if (cliModel === null || !needsDefaultModel(error)) throw error;
11987
- cliModel = null;
11988
- return (await runClaudeCliTurn(prompt, {
11989
- systemPrompt: system,
11990
- resumeSessionId: void 0,
11991
- routing,
11992
- model: null,
11993
- attachmentsDir: readDir
11994
- })).text;
13138
+ const sent = messages.map(sessionMessageKey);
13139
+ const runFresh = async () => {
13140
+ const prompt = renderConversationPrompt(messages);
13141
+ try {
13142
+ return await runClaudeCliTurn(prompt, {
13143
+ systemPrompt: system,
13144
+ resumeSessionId: void 0,
13145
+ routing,
13146
+ model: useDefaultModel ? null : model,
13147
+ attachmentsDir: readDir
13148
+ });
13149
+ } catch (error) {
13150
+ if (useDefaultModel || !needsDefaultModel(error)) throw error;
13151
+ useDefaultModel = true;
13152
+ return await runClaudeCliTurn(prompt, {
13153
+ systemPrompt: system,
13154
+ resumeSessionId: void 0,
13155
+ routing,
13156
+ model: null,
13157
+ attachmentsDir: readDir
13158
+ });
13159
+ }
13160
+ };
13161
+ const session = conversationSessions.get(job.id);
13162
+ let turn = null;
13163
+ if (session && extendsSession(session.sent, sent)) {
13164
+ try {
13165
+ turn = await runClaudeCliTurn(renderResumePrompt(messages.slice(session.sent.length)), {
13166
+ systemPrompt: system,
13167
+ resumeSessionId: session.sessionId,
13168
+ routing,
13169
+ model: useDefaultModel ? null : model,
13170
+ attachmentsDir: readDir
13171
+ });
13172
+ } catch {
13173
+ turn = null;
13174
+ }
13175
+ }
13176
+ if (!turn) {
13177
+ conversationSessions.delete(job.id);
13178
+ turn = await runFresh();
11995
13179
  }
13180
+ rememberConversationSession(job.id, {
13181
+ sessionId: turn.sessionId,
13182
+ sent: [...sent, sessionMessageKey({ role: "assistant", content: turn.text })]
13183
+ });
13184
+ replyModel = useDefaultModel ? null : model;
13185
+ if (turn.text) timer.markFirstText();
13186
+ return turn.text;
11996
13187
  },
11997
13188
  save: async (existingId, draft) => {
11998
13189
  const submitted = await submitAndScore(ctx, existingId, draft);
@@ -12003,7 +13194,7 @@ async function converseWithAttachments(job, ctx, step) {
12003
13194
  if (outcome.kind === "saved") {
12004
13195
  await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
12005
13196
  }
12006
- await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text);
13197
+ await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text, timer.finish(replyModel));
12007
13198
  return { status: "yield" };
12008
13199
  }
12009
13200
  var PLANNER_RUN_TIMEOUT_MS = 30 * 60 * 1e3;
@@ -12204,7 +13395,7 @@ function buildPlannerFinalTurn(outcome) {
12204
13395
  }
12205
13396
  async function invokeStartExecutionPlan(ctx, deps = {}) {
12206
13397
  if (ctx.signal?.aborted) return cancelledRunResult("planner");
12207
- const spawnImpl = deps.spawnImpl ?? spawn7;
13398
+ const spawnImpl = deps.spawnImpl ?? spawn6;
12208
13399
  const fetchImpl = deps.fetchImpl ?? fetch;
12209
13400
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
12210
13401
  const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
@@ -12241,13 +13432,19 @@ async function invokeStartExecutionPlan(ctx, deps = {}) {
12241
13432
  let stdout2 = "";
12242
13433
  let stderr = "";
12243
13434
  let settled = false;
12244
- const child = spawnImpl(command, args, {
12245
- cwd: ctx.projectDir,
12246
- stdio: ["ignore", "pipe", "pipe"],
12247
- env: childEnv,
12248
- // ENG-300: lead its own process group so a cancel can stop everything it started.
12249
- ...groupSpawnOptions(deps.processGroup?.platform)
12250
- });
13435
+ const child = spawnPiped(
13436
+ spawnImpl,
13437
+ command,
13438
+ args,
13439
+ {
13440
+ cwd: ctx.projectDir,
13441
+ stdio: ["ignore", "pipe", "pipe"],
13442
+ env: childEnv,
13443
+ // ENG-300: lead its own process group so a cancel can stop everything it started.
13444
+ ...groupSpawnOptions(deps.processGroup?.platform)
13445
+ },
13446
+ deps.processGroup?.platform
13447
+ );
12251
13448
  let cancelled = false;
12252
13449
  const disposeAbort = killGroupOnAbort(
12253
13450
  ctx.signal,
@@ -12419,7 +13616,7 @@ function buildRefineFinalTurn(outcome) {
12419
13616
  }
12420
13617
  async function invokeStartExecutionRefine(ctx, deps = {}) {
12421
13618
  if (ctx.signal?.aborted) return cancelledRunResult("planner");
12422
- const spawnImpl = deps.spawnImpl ?? spawn7;
13619
+ const spawnImpl = deps.spawnImpl ?? spawn6;
12423
13620
  const fetchImpl = deps.fetchImpl ?? fetch;
12424
13621
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
12425
13622
  const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
@@ -12448,13 +13645,19 @@ async function invokeStartExecutionRefine(ctx, deps = {}) {
12448
13645
  let stdout2 = "";
12449
13646
  let stderr = "";
12450
13647
  let settled = false;
12451
- const child = spawnImpl(command, args, {
12452
- cwd: ctx.projectDir,
12453
- stdio: ["ignore", "pipe", "pipe"],
12454
- env: childEnv,
12455
- // ENG-300: lead its own process group so a cancel can stop everything it started.
12456
- ...groupSpawnOptions(deps.processGroup?.platform)
12457
- });
13648
+ const child = spawnPiped(
13649
+ spawnImpl,
13650
+ command,
13651
+ args,
13652
+ {
13653
+ cwd: ctx.projectDir,
13654
+ stdio: ["ignore", "pipe", "pipe"],
13655
+ env: childEnv,
13656
+ // ENG-300: lead its own process group so a cancel can stop everything it started.
13657
+ ...groupSpawnOptions(deps.processGroup?.platform)
13658
+ },
13659
+ deps.processGroup?.platform
13660
+ );
12458
13661
  let cancelled = false;
12459
13662
  const disposeAbort = killGroupOnAbort(
12460
13663
  ctx.signal,
@@ -12574,7 +13777,7 @@ ${stderr}`;
12574
13777
  }
12575
13778
  function gitHead(dir) {
12576
13779
  return new Promise((resolve4, reject) => {
12577
- execFile2("git", ["rev-parse", "HEAD"], { cwd: dir, timeout: 15e3 }, (error, stdout2) => {
13780
+ execFile3("git", ["rev-parse", "HEAD"], { cwd: dir, timeout: 15e3 }, (error, stdout2) => {
12578
13781
  if (error) reject(new Error(`git rev-parse HEAD failed: ${error.message}`));
12579
13782
  else resolve4(stdout2.trim());
12580
13783
  });
@@ -12641,16 +13844,22 @@ function buildConflictResolveArgs(files, baseBranch) {
12641
13844
  ];
12642
13845
  }
12643
13846
  function createClaudeConflictResolver(opts) {
12644
- const spawnImpl = opts.spawnImpl ?? spawn7;
13847
+ const spawnImpl = opts.spawnImpl ?? spawn6;
12645
13848
  const timeoutMs = opts.timeoutMs ?? CONFLICT_RESOLVE_TIMEOUT_MS;
12646
13849
  return ({ dir, files, baseBranch, signal }) => new Promise((resolve4) => {
12647
13850
  let settled = false;
12648
- const child = spawnImpl(opts.command, buildConflictResolveArgs(files, baseBranch), {
12649
- cwd: dir,
12650
- stdio: ["ignore", "ignore", "pipe"],
12651
- env: opts.env,
12652
- ...groupSpawnOptions(opts.processGroup?.platform)
12653
- });
13851
+ const child = spawnPiped(
13852
+ spawnImpl,
13853
+ opts.command,
13854
+ buildConflictResolveArgs(files, baseBranch),
13855
+ {
13856
+ cwd: dir,
13857
+ stdio: ["ignore", "ignore", "pipe"],
13858
+ env: opts.env,
13859
+ ...groupSpawnOptions(opts.processGroup?.platform)
13860
+ },
13861
+ opts.processGroup?.platform
13862
+ );
12654
13863
  let stderr = "";
12655
13864
  child.stderr.on("data", (chunk) => {
12656
13865
  stderr += chunk.toString("utf-8");
@@ -12704,7 +13913,9 @@ ${followUpContext(extra.followUp)}` : "") + (extra?.ownerNote ? `
12704
13913
 
12705
13914
  ${ownerNoteContext(extra.ownerNote)}` : "") + (extra?.deferred && extra.deferred.length > 0 ? `
12706
13915
 
12707
- ${deferredFeaturesText(extra.deferred)}` : ""),
13916
+ ${deferredFeaturesText(extra.deferred)}` : "") + (extra?.checkMode ? `
13917
+
13918
+ ${checkModeText(extra.checkMode)}` : ""),
12708
13919
  // A known session id lets the runner resume this same conversation when
12709
13920
  // the agent ends its turn early (see buildOrchestratorContinueArgs).
12710
13921
  ...sessionId ? ["--session-id", sessionId] : [],
@@ -12722,14 +13933,18 @@ ${deferredFeaturesText(extra.deferred)}` : ""),
12722
13933
  ];
12723
13934
  }
12724
13935
  var MAX_ORCHESTRATOR_CONTINUES = 5;
12725
- function orchestratorContinuePrompt(epicId, done, total, deferred = []) {
13936
+ function orchestratorContinuePrompt(epicId, done, total, deferred = [], checkMode) {
12726
13937
  return [
12727
13938
  `Continue executing epic ${epicId} in non-interactive mode. CompBox shows ${String(done)} of ${String(total)} features done.`,
12728
13939
  "You ended your turn early, which stopped the run. Do not announce the next step: take it.",
12729
13940
  "Keep going until every feature is done and recorded in CompBox, or a hard gate stops the run.",
12730
- ...deferred.length > 0 ? [deferredFeaturesText(deferred)] : []
13941
+ ...deferred.length > 0 ? [deferredFeaturesText(deferred)] : [],
13942
+ ...checkMode ? [checkModeText(checkMode)] : []
12731
13943
  ].join(" ");
12732
13944
  }
13945
+ function checkModeText(checkMode) {
13946
+ return `Check mode: ${checkMode}`;
13947
+ }
12733
13948
  function deferredFeaturesText(deferred) {
12734
13949
  return `The owner deferred these features: skip them and don't ask about them: ${deferred.map((f) => `${f.identifier} (${f.title})`).join(", ")}.`;
12735
13950
  }
@@ -12765,7 +13980,8 @@ function parseReplyAttachments(raw) {
12765
13980
  for (const item of raw) {
12766
13981
  if (typeof item !== "object" || item === null) continue;
12767
13982
  const a = item;
12768
- if (typeof a.id !== "string" || typeof a.mimeType !== "string" || typeof a.signedUrl !== "string") continue;
13983
+ if (typeof a.id !== "string" || typeof a.mimeType !== "string" || typeof a.signedUrl !== "string")
13984
+ continue;
12769
13985
  if (a.signedUrl.trim() === "") continue;
12770
13986
  out.push({
12771
13987
  id: a.id,
@@ -12883,10 +14099,11 @@ function defaultWorktreeCapable(dir) {
12883
14099
  function defaultToolchainPresent(_dir) {
12884
14100
  for (const pm of ["pnpm", "npm"]) {
12885
14101
  try {
12886
- const res = spawnSync(pm, ["--version"], {
14102
+ const plan = planCrossPlatformSpawn(pm, ["--version"], {
12887
14103
  stdio: "ignore",
12888
14104
  env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH) }
12889
14105
  });
14106
+ const res = spawnSync(plan.command, plan.args, plan.options);
12890
14107
  if (res.status === 0) return true;
12891
14108
  } catch {
12892
14109
  }
@@ -12898,7 +14115,9 @@ function mergePullRequestsRequest(prs) {
12898
14115
  return {
12899
14116
  question: `${count} your review and merge before the build can continue.`,
12900
14117
  why: "The rest of the build builds on this work, so continuing now would redo it or conflict with it.",
12901
- steps: prs.map((pr, i) => `${String(i + 1)}. Merge #${String(pr.number)}${pr.title ? ` ${pr.title}` : ""}: ${pr.htmlUrl}`),
14118
+ steps: prs.map(
14119
+ (pr, i) => `${String(i + 1)}. Merge #${String(pr.number)}${pr.title ? ` ${pr.title}` : ""}: ${pr.htmlUrl}`
14120
+ ),
12902
14121
  afterAnswer: `The build continues by itself once they're merged. You can also press "All merged \u2014 continue".`,
12903
14122
  kind: "merge_prs",
12904
14123
  prNumbers: prs.map((pr) => pr.number)
@@ -12996,7 +14215,7 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
12996
14215
  if (ctx.signal?.aborted) return cancelledRunResult("orchestrator");
12997
14216
  const clockMs = deps.clockMs ?? Date.now;
12998
14217
  const startedAtMs = clockMs();
12999
- const spawnImpl = deps.spawnImpl ?? spawn7;
14218
+ const spawnImpl = deps.spawnImpl ?? spawn6;
13000
14219
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
13001
14220
  const worktreeCapable = deps.worktreeCapable ?? defaultWorktreeCapable;
13002
14221
  const toolchainPresent = deps.toolchainPresent ?? defaultToolchainPresent;
@@ -13078,7 +14297,9 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13078
14297
  const replyAttachments = resume?.attachments ?? [];
13079
14298
  if (replyAttachments.length > 0) {
13080
14299
  try {
13081
- replyAttachmentsDir = await realpath(await mkdtemp(join16(tmpdir2(), "compbox-reply-attachments-")));
14300
+ replyAttachmentsDir = await realpath(
14301
+ await mkdtemp(join16(tmpdir4(), "compbox-reply-attachments-"))
14302
+ );
13082
14303
  const { files, failed } = await materializeAttachments(
13083
14304
  replyAttachmentsDir,
13084
14305
  replyAttachments,
@@ -13097,12 +14318,20 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13097
14318
  replyResumePrompt(ctx.epicId, resume.reply, attachmentsNote),
13098
14319
  workspace?.baseBranch,
13099
14320
  ctx.fastMode
13100
- ) : buildOrchestratorArgs(ctx.epicId, sessionId, resume?.reply, workspace?.baseBranch, ctx.fastMode, {
13101
- ...ctx.ownerNote && { ownerNote: ctx.ownerNote },
13102
- ...ctx.deferredFeatures && { deferred: ctx.deferredFeatures },
13103
- ...ctx.followUp && { followUp: ctx.followUp },
13104
- ...attachmentsNote && { replyAttachmentsNote: attachmentsNote }
13105
- });
14321
+ ) : buildOrchestratorArgs(
14322
+ ctx.epicId,
14323
+ sessionId,
14324
+ resume?.reply,
14325
+ workspace?.baseBranch,
14326
+ ctx.fastMode,
14327
+ {
14328
+ ...ctx.ownerNote && { ownerNote: ctx.ownerNote },
14329
+ ...ctx.deferredFeatures && { deferred: ctx.deferredFeatures },
14330
+ ...ctx.followUp && { followUp: ctx.followUp },
14331
+ ...attachmentsNote && { replyAttachmentsNote: attachmentsNote },
14332
+ ...ctx.checkMode && { checkMode: ctx.checkMode }
14333
+ }
14334
+ );
13106
14335
  const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
13107
14336
  const routedEnv = claudeSpawnEnv(process.env, routing);
13108
14337
  const baseEnv = {
@@ -13119,6 +14348,8 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13119
14348
  deps.mergeGuardDir === void 0 ? join16(getConfigDir(), "merge-guard") : deps.mergeGuardDir
13120
14349
  )
13121
14350
  };
14351
+ const agentHooksDir = makeAgentHooksDir(runDir);
14352
+ if (agentHooksDir) Object.assign(baseEnv, withHooksDisabled(baseEnv, agentHooksDir));
13122
14353
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
13123
14354
  try {
13124
14355
  if (resume) {
@@ -13131,11 +14362,12 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13131
14362
  } catch {
13132
14363
  }
13133
14364
  try {
13134
- if (!resumeSessionId) await ctx.mailboxClient.postTurn(
13135
- ctx.machineToken,
13136
- ctx.jobId,
13137
- (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(" ")}` : "")
13138
- );
14365
+ if (!resumeSessionId)
14366
+ await ctx.mailboxClient.postTurn(
14367
+ ctx.machineToken,
14368
+ ctx.jobId,
14369
+ (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(" ")}` : "")
14370
+ );
13139
14371
  } catch {
13140
14372
  }
13141
14373
  const stopped = { reason: null };
@@ -13158,13 +14390,19 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13158
14390
  let stderr = "";
13159
14391
  let outputBytes = 0;
13160
14392
  let settled = false;
13161
- const child = spawnImpl(command, runArgsNow, {
13162
- cwd: runDir,
13163
- stdio: ["ignore", "pipe", "pipe"],
13164
- env: childEnv,
13165
- // ENG-300: lead its own process group so a cancel can stop everything it started.
13166
- ...groupSpawnOptions(deps.processGroup?.platform)
13167
- });
14393
+ const child = spawnPiped(
14394
+ spawnImpl,
14395
+ command,
14396
+ runArgsNow,
14397
+ {
14398
+ cwd: runDir,
14399
+ stdio: ["ignore", "pipe", "pipe"],
14400
+ env: childEnv,
14401
+ // ENG-300: lead its own process group so a cancel can stop everything it started.
14402
+ ...groupSpawnOptions(deps.processGroup?.platform)
14403
+ },
14404
+ deps.processGroup?.platform
14405
+ );
13168
14406
  let cancelled = false;
13169
14407
  const disposeAbort = killGroupOnAbort(
13170
14408
  ctx.signal,
@@ -13378,7 +14616,10 @@ ${stderr}`;
13378
14616
  let stalls = 0;
13379
14617
  while (sessionId && unfinished(progress) && continues < maxContinues && !ctx.signal?.aborted) {
13380
14618
  if (progress.waitingPullRequests && progress.waitingPullRequests.length > 0) {
13381
- outcome = needsInputRunResult(ctx.epicId, mergePullRequestsRequest(progress.waitingPullRequests));
14619
+ outcome = needsInputRunResult(
14620
+ ctx.epicId,
14621
+ mergePullRequestsRequest(progress.waitingPullRequests)
14622
+ );
13382
14623
  break;
13383
14624
  }
13384
14625
  if (deadline - Date.now() <= 6e4) {
@@ -13401,7 +14642,8 @@ ${stderr}`;
13401
14642
  ctx.epicId,
13402
14643
  progress.completedFeatures,
13403
14644
  progress.totalFeatures,
13404
- ctx.deferredFeatures
14645
+ ctx.deferredFeatures,
14646
+ ctx.checkMode
13405
14647
  ),
13406
14648
  workspace?.baseBranch,
13407
14649
  ctx.fastMode
@@ -13434,7 +14676,9 @@ ${stderr}`;
13434
14676
  outcome.result = {
13435
14677
  ...outcome.result,
13436
14678
  fastMode: { requested: true, used: fastModeUsed },
13437
- ...fastModeUsed === false ? { fastModeNote: "Fast mode was requested but isn't available on this computer's Claude account, so the run used standard speed." } : {}
14679
+ ...fastModeUsed === false ? {
14680
+ fastModeNote: "Fast mode was requested but isn't available on this computer's Claude account, so the run used standard speed."
14681
+ } : {}
13438
14682
  };
13439
14683
  }
13440
14684
  const keepRunCopy = needsInput !== null && !ctx.keyRun && !ctx.fix && sessionId !== void 0;
@@ -13513,7 +14757,9 @@ ${stderr}`;
13513
14757
  }
13514
14758
  }
13515
14759
  if (workspace) deps.activeRunDirs?.delete(workspace.dir);
13516
- if (replyAttachmentsDir) await rm(replyAttachmentsDir, { recursive: true, force: true }).catch(() => void 0);
14760
+ if (replyAttachmentsDir)
14761
+ await rm(replyAttachmentsDir, { recursive: true, force: true }).catch(() => void 0);
14762
+ if (agentHooksDir) await rm(agentHooksDir, { recursive: true, force: true }).catch(() => void 0);
13517
14763
  const timings = buildJobTimings({
13518
14764
  install: workspace?.install,
13519
14765
  runs: runDurations,
@@ -13623,14 +14869,14 @@ async function updatePersonalEpicRequest(apiBaseUrl, userApiToken, epicRequestId
13623
14869
  }
13624
14870
 
13625
14871
  // src/utils/repo-setup.ts
13626
- import { spawn as spawn8 } from "node:child_process";
13627
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readdirSync as readdirSync4 } from "node:fs";
13628
- import { homedir as homedir8 } from "node:os";
13629
- import { dirname as dirname6, isAbsolute as isAbsolute3, join as join17, resolve as resolve3 } from "node:path";
14872
+ import { spawn as spawn7 } from "node:child_process";
14873
+ import { existsSync as existsSync16, mkdirSync as mkdirSync11, readdirSync as readdirSync4 } from "node:fs";
14874
+ import { homedir as homedir9 } from "node:os";
14875
+ import { dirname as dirname7, isAbsolute as isAbsolute3, join as join17, resolve as resolve3 } from "node:path";
13630
14876
  var CLONE_TIMEOUT_MS = 15 * 60 * 1e3;
13631
14877
  var defaultGitCloner = (url, target) => new Promise((done) => {
13632
14878
  let stderr = "";
13633
- const child = spawn8("git", ["clone", "--quiet", url, target], {
14879
+ const child = spawn7("git", ["clone", "--quiet", url, target], {
13634
14880
  stdio: ["ignore", "ignore", "pipe"],
13635
14881
  // Never hang on a username/password prompt: fail and explain instead.
13636
14882
  env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH), GIT_TERMINAL_PROMPT: "0" }
@@ -13679,13 +14925,13 @@ function parsePayload(payload) {
13679
14925
  ...typeof p.projectName === "string" ? { projectName: p.projectName } : {}
13680
14926
  };
13681
14927
  }
13682
- function firstLine(text) {
14928
+ function firstLine2(text) {
13683
14929
  return text.trim().split("\n").filter(Boolean).pop() ?? "";
13684
14930
  }
13685
14931
  async function invokeConnectRepo(payload, deps = {}) {
13686
14932
  const clone = deps.clone ?? defaultGitCloner;
13687
- const home = deps.home ?? homedir8();
13688
- const exists = deps.exists ?? existsSync13;
14933
+ const home = deps.home ?? homedir9();
14934
+ const exists = deps.exists ?? existsSync16;
13689
14935
  const isEmptyDir = deps.isEmptyDir ?? ((path3) => {
13690
14936
  try {
13691
14937
  return readdirSync4(path3).length === 0;
@@ -13697,14 +14943,14 @@ async function invokeConnectRepo(payload, deps = {}) {
13697
14943
  const readOrigin = deps.readOrigin ?? readOriginRemote;
13698
14944
  const listDirs = deps.listDirs ?? listProjectDirs;
13699
14945
  const addDir = deps.addDir ?? ((path3) => addProjectDir(path3));
13700
- const mkdir3 = deps.mkdir ?? ((path3) => void mkdirSync10(path3, { recursive: true }));
14946
+ const mkdir3 = deps.mkdir ?? ((path3) => void mkdirSync11(path3, { recursive: true }));
13701
14947
  const p = parsePayload(payload);
13702
14948
  if (!p) {
13703
14949
  return { status: "failed", result: { error: "The job was missing the project repository. Try again from the project page." } };
13704
14950
  }
13705
14951
  const remote = normalizeGitRemote(p.projectRemote);
13706
14952
  const name = p.projectName ?? repoFolderName(remote);
13707
- const existing = listDirs().find((entry) => entry.remote === remote && exists(entry.path));
14953
+ const existing = listDirs().find((entry) => sameGitRemote(entry.remote, remote) && exists(entry.path));
13708
14954
  if (existing) {
13709
14955
  return {
13710
14956
  status: "done",
@@ -13720,7 +14966,7 @@ async function invokeConnectRepo(payload, deps = {}) {
13720
14966
  } catch {
13721
14967
  origin = "";
13722
14968
  }
13723
- if (origin !== remote) {
14969
+ if (!sameGitRemote(origin, remote)) {
13724
14970
  return {
13725
14971
  status: "failed",
13726
14972
  result: {
@@ -13734,7 +14980,7 @@ async function invokeConnectRepo(payload, deps = {}) {
13734
14980
  result: { path: entry2.path, remote, outcome: "adopted", message: `Found an existing copy of ${name} at ${entry2.path} and set it up.` }
13735
14981
  };
13736
14982
  }
13737
- mkdir3(dirname6(target));
14983
+ mkdir3(dirname7(target));
13738
14984
  const errors = [];
13739
14985
  let cloned = false;
13740
14986
  for (const url of cloneUrls(remote)) {
@@ -13743,7 +14989,7 @@ async function invokeConnectRepo(payload, deps = {}) {
13743
14989
  cloned = true;
13744
14990
  break;
13745
14991
  }
13746
- errors.push(firstLine(res.stderr));
14992
+ errors.push(firstLine2(res.stderr));
13747
14993
  }
13748
14994
  if (!cloned) {
13749
14995
  return {
@@ -13770,11 +15016,11 @@ async function invokeConnectRepo(payload, deps = {}) {
13770
15016
  }
13771
15017
 
13772
15018
  // src/utils/keep-awake.ts
13773
- import { spawn as spawn9 } from "node:child_process";
15019
+ import { spawn as spawn8 } from "node:child_process";
13774
15020
  function startKeepAwake(opts) {
13775
15021
  const platform = opts.platform ?? process.platform;
13776
15022
  if (opts.enabled === false || platform !== "darwin") return null;
13777
- const spawnFn = opts.spawnFn ?? spawn9;
15023
+ const spawnFn = opts.spawnFn ?? spawn8;
13778
15024
  try {
13779
15025
  const child = spawnFn("/usr/bin/caffeinate", ["-i", "-s", "-w", String(opts.pid ?? process.pid)], {
13780
15026
  stdio: "ignore"
@@ -13792,13 +15038,16 @@ var POLL_WAIT_MS = 0;
13792
15038
  var IDLE_POLL_INTERVAL_MS = 15e3;
13793
15039
  var ACTIVE_POLL_INTERVAL_MS = 2e3;
13794
15040
  var ACTIVE_WINDOW_MS = 6e4;
15041
+ var CONVERSATION_LIVE_POLL_MS = 750;
15042
+ var CONVERSATION_LIVE_WINDOW_MS = 2 * 6e4;
13795
15043
  var CONVERSATION_POLL_INTERVAL_MS = 3e3;
13796
15044
  var CONVERSATION_WINDOW_MS = 10 * 6e4;
13797
15045
  function idleDelay(now, lastJobAt, lastConversationAt = 0) {
15046
+ const sinceReply = lastConversationAt > 0 ? now - lastConversationAt : Infinity;
15047
+ if (sinceReply < CONVERSATION_LIVE_WINDOW_MS) return CONVERSATION_LIVE_POLL_MS;
13798
15048
  const warm = lastJobAt > 0 && now - lastJobAt < ACTIVE_WINDOW_MS;
13799
15049
  if (warm) return ACTIVE_POLL_INTERVAL_MS;
13800
- const talking = lastConversationAt > 0 && now - lastConversationAt < CONVERSATION_WINDOW_MS;
13801
- return talking ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
15050
+ return sinceReply < CONVERSATION_WINDOW_MS ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
13802
15051
  }
13803
15052
  var DEFAULT_MAX_PARALLEL_JOBS = 3;
13804
15053
  var MAX_JOBS_ENV = "COMPBOX_MAX_JOBS";
@@ -13992,6 +15241,8 @@ function parseStartExecutionPayload(payload) {
13992
15241
  ...fix && { fix },
13993
15242
  // ENG-350: fast mode only when explicitly true.
13994
15243
  ...p.fastMode === true && { fastMode: true },
15244
+ // ENG-395: check cadence; an absent/unknown value leaves the orchestrator's default.
15245
+ ...CHECK_MODES.includes(p.checkMode) && { checkMode: p.checkMode },
13995
15246
  // ER-130: the owner's note and deferred features from "All merged — continue" / "Restart".
13996
15247
  ...typeof p.ownerNote === "string" && p.ownerNote.trim().length > 0 && { ownerNote: p.ownerNote },
13997
15248
  ...parseDeferredFeatures(p.deferredFeatures).length > 0 && {
@@ -14167,6 +15418,7 @@ async function handleStartExecution(ctx, job) {
14167
15418
  ...keyRun && { keyRun },
14168
15419
  ...orch?.fix && { fix: orch.fix },
14169
15420
  ...orch?.fastMode === true && { fastMode: true },
15421
+ ...orch?.checkMode && { checkMode: orch.checkMode },
14170
15422
  ...orch?.ownerNote && { ownerNote: orch.ownerNote },
14171
15423
  ...orch?.deferredFeatures && { deferredFeatures: orch.deferredFeatures },
14172
15424
  ...orch?.freshBranch === true && { freshBranch: true },
@@ -14370,7 +15622,7 @@ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error
14370
15622
  const legacyDir = unusedLegacyProjectDir(config);
14371
15623
  const shims = ensurePackageManagerShims();
14372
15624
  if (shims) {
14373
- process.env.PATH = [shims.dir, process.env.PATH ?? ""].filter(Boolean).join(delimiter3);
15625
+ process.env.PATH = [shims.dir, process.env.PATH ?? ""].filter(Boolean).join(delimiter);
14374
15626
  console.log(chalk9.gray(` ${shims.tools.join(" and ")} not installed \u2014 builds will run ${shims.tools.length > 1 ? "them" : "it"} through npx.`));
14375
15627
  }
14376
15628
  if (startKeepAwake({ enabled: config.keepAwake })) {
@@ -14521,11 +15773,6 @@ Received ${signal}, shutting down...`));
14521
15773
  // src/commands/service.ts
14522
15774
  import { Command as Command9 } from "commander";
14523
15775
  import chalk10 from "chalk";
14524
- import { execFile as execFile3 } from "node:child_process";
14525
- import { promisify as promisify2 } from "node:util";
14526
- var execFileAsync2 = promisify2(execFile3);
14527
- var SERVICE_NAME = "CompBoxAgentRunner";
14528
- var SERVICE_DISPLAY_NAME = "CompBox Agent Runner";
14529
15776
  function requireWindows() {
14530
15777
  if (process.platform !== "win32") {
14531
15778
  console.error(
@@ -14540,93 +15787,159 @@ function requireWindows() {
14540
15787
  }
14541
15788
  return true;
14542
15789
  }
14543
- async function runSc(args) {
14544
- return execFileAsync2("sc.exe", args);
15790
+ function printElevatedCommands() {
15791
+ console.error(chalk10.yellow(" From an Administrator terminal, run:"));
15792
+ for (const cmd of LEGACY_ELEVATED_COMMANDS) console.error(chalk10.yellow(` ${cmd}`));
15793
+ }
15794
+ function reportMigration(m) {
15795
+ switch (m.outcome) {
15796
+ case "absent":
15797
+ return;
15798
+ case "removed":
15799
+ console.log(chalk10.green(`\u2714 Removed the old LocalSystem service "${LEGACY_SERVICE_NAME}".`));
15800
+ return;
15801
+ case "access-denied":
15802
+ console.error(
15803
+ chalk10.yellow(
15804
+ `
15805
+ \u26A0 The old LocalSystem service "${LEGACY_SERVICE_NAME}" is still installed and removing it needs Administrator rights.`
15806
+ )
15807
+ );
15808
+ printElevatedCommands();
15809
+ return;
15810
+ case "failed":
15811
+ console.error(
15812
+ chalk10.yellow(`
15813
+ \u26A0 Could not remove the old service "${LEGACY_SERVICE_NAME}": ${m.detail ?? "unknown error"}`)
15814
+ );
15815
+ printElevatedCommands();
15816
+ return;
15817
+ case "unknown":
15818
+ console.error(chalk10.yellow(`
15819
+ \u26A0 ${m.detail ?? "Could not check for the old service."}`));
15820
+ return;
15821
+ }
14545
15822
  }
14546
15823
  var serviceCommand = new Command9("service").description(
14547
- "Manage the Agent Runner as a Windows Service (macOS/Linux: use `brew services` instead)"
15824
+ "Manage the Agent Runner as a per-user Windows Scheduled Task (macOS/Linux: use `brew services` instead)"
14548
15825
  );
14549
- serviceCommand.command("install").description("Register the Agent Runner as an always-on Windows Service (auto-start on boot)").action(async () => {
15826
+ serviceCommand.command("install").description("Register the Agent Runner to start at logon as the current user, and start it now").action(async () => {
14550
15827
  if (!requireWindows()) {
14551
15828
  process.exit(1);
14552
15829
  return;
14553
15830
  }
14554
- const nodeExe = process.execPath;
14555
- const scriptPath = process.argv[1] ?? "";
14556
- const binPath = `"${nodeExe}" "${scriptPath}" run`;
14557
15831
  try {
14558
- await runSc([
14559
- "create",
14560
- SERVICE_NAME,
14561
- "binPath=",
14562
- binPath,
14563
- "start=",
14564
- "auto",
14565
- "DisplayName=",
14566
- SERVICE_DISPLAY_NAME
14567
- ]);
14568
- console.log(chalk10.green(`
14569
- \u2714 Service "${SERVICE_DISPLAY_NAME}" registered (starts automatically on boot).`));
14570
- console.log(chalk10.gray(` Start it now with: compbox service start`));
15832
+ const result = await installRunnerTask();
15833
+ reportMigration(result.migration);
15834
+ console.log(
15835
+ chalk10.green(`
15836
+ \u2714 "${RUNNER_DISPLAY_NAME}" registered as Scheduled Task "${RUNNER_TASK_NAME}" (starts when you sign in).`)
15837
+ );
15838
+ if (result.started) {
15839
+ console.log(chalk10.green("\u2714 Agent Runner started."));
15840
+ } else if (result.notStartedReason === "legacy-running") {
15841
+ console.error(
15842
+ chalk10.yellow(
15843
+ " Not started: the old service is still running. Remove it with the commands above, then run: compbox service start"
15844
+ )
15845
+ );
15846
+ } else {
15847
+ console.error(chalk10.yellow(` Not started: ${result.startError ?? "schtasks /Run failed"}`));
15848
+ console.error(chalk10.gray(" Retry with: compbox service start"));
15849
+ }
14571
15850
  } catch (error) {
14572
- const message = error instanceof Error ? error.message : "sc.exe create failed";
14573
- const stderr = error.stderr?.trim();
15851
+ const f = describeExecError(error);
14574
15852
  console.error(chalk10.red(`
14575
- Failed to install the service: ${message}`));
14576
- if (stderr) console.error(chalk10.red(` sc.exe: ${stderr}`));
14577
- console.error(chalk10.gray(" If this is a permissions error, run the terminal as Administrator."));
15853
+ Failed to register the Scheduled Task: ${failureSummary(f)}`));
14578
15854
  process.exit(1);
14579
15855
  }
14580
15856
  });
14581
- serviceCommand.command("uninstall").description("Stop and remove the Windows Service").action(async () => {
15857
+ serviceCommand.command("uninstall").description("Stop and remove the Agent Runner Scheduled Task").action(async () => {
14582
15858
  if (!requireWindows()) {
14583
15859
  process.exit(1);
14584
15860
  return;
14585
15861
  }
14586
15862
  try {
14587
- await runSc(["stop", SERVICE_NAME]).catch(() => {
14588
- });
14589
- await runSc(["delete", SERVICE_NAME]);
15863
+ await uninstallRunnerTask();
14590
15864
  console.log(chalk10.green(`
14591
- \u2714 Service "${SERVICE_DISPLAY_NAME}" removed.`));
15865
+ \u2714 Scheduled Task "${RUNNER_TASK_NAME}" removed.`));
14592
15866
  } catch (error) {
14593
- const message = error instanceof Error ? error.message : "sc.exe delete failed";
14594
15867
  console.error(chalk10.red(`
14595
- Failed to remove the service: ${message}`));
14596
- console.error(chalk10.gray(" Try running this terminal as Administrator."));
15868
+ Failed to remove the Scheduled Task: ${failureSummary(describeExecError(error))}`));
14597
15869
  process.exit(1);
14598
15870
  }
15871
+ if (await queryLegacyService() !== "absent") {
15872
+ console.error(chalk10.yellow(`
15873
+ \u26A0 The old LocalSystem service "${LEGACY_SERVICE_NAME}" is still installed.`));
15874
+ printElevatedCommands();
15875
+ }
14599
15876
  });
14600
- serviceCommand.command("start").description("Start the registered Windows Service").action(async () => {
15877
+ serviceCommand.command("start").description("Start the Agent Runner Scheduled Task now").action(async () => {
14601
15878
  if (!requireWindows()) {
14602
15879
  process.exit(1);
14603
15880
  return;
14604
15881
  }
14605
- try {
14606
- await runSc(["start", SERVICE_NAME]);
15882
+ const r = await startRunnerTask();
15883
+ if (r.started) {
14607
15884
  console.log(chalk10.green(`
14608
- \u2714 Service "${SERVICE_DISPLAY_NAME}" started.`));
14609
- } catch (error) {
14610
- const message = error instanceof Error ? error.message : "sc.exe start failed";
15885
+ \u2714 "${RUNNER_DISPLAY_NAME}" started.`));
15886
+ return;
15887
+ }
15888
+ if (r.reason === "legacy-running") {
15889
+ console.error(
15890
+ chalk10.red(`
15891
+ Not started: the old LocalSystem service "${LEGACY_SERVICE_NAME}" is running, and only one runner may run.`)
15892
+ );
15893
+ printElevatedCommands();
15894
+ } else {
14611
15895
  console.error(chalk10.red(`
14612
- Failed to start the service: ${message}`));
14613
- process.exit(1);
15896
+ Failed to start: ${r.error}`));
15897
+ console.error(chalk10.gray(" If the task is not registered yet, run: compbox service install"));
14614
15898
  }
15899
+ process.exit(1);
14615
15900
  });
14616
- serviceCommand.command("stop").description("Stop the running Windows Service").action(async () => {
15901
+ serviceCommand.command("stop").description("Stop the running Agent Runner").action(async () => {
14617
15902
  if (!requireWindows()) {
14618
15903
  process.exit(1);
14619
15904
  return;
14620
15905
  }
14621
15906
  try {
14622
- await runSc(["stop", SERVICE_NAME]);
15907
+ await stopRunnerTask();
14623
15908
  console.log(chalk10.green(`
14624
- \u2714 Service "${SERVICE_DISPLAY_NAME}" stopped.`));
15909
+ \u2714 "${RUNNER_DISPLAY_NAME}" stopped.`));
14625
15910
  } catch (error) {
14626
- const message = error instanceof Error ? error.message : "sc.exe stop failed";
14627
15911
  console.error(chalk10.red(`
14628
- Failed to stop the service: ${message}`));
15912
+ Failed to stop: ${failureSummary(describeExecError(error))}`));
15913
+ process.exit(1);
15914
+ }
15915
+ });
15916
+ serviceCommand.command("status").description("Show whether the Agent Runner task is registered and running").action(async () => {
15917
+ if (!requireWindows()) {
15918
+ process.exit(1);
15919
+ return;
15920
+ }
15921
+ const task = await queryRunnerTask();
15922
+ if (task.error) {
15923
+ console.error(chalk10.red(`
15924
+ Could not query the Scheduled Task: ${task.error}`));
14629
15925
  process.exit(1);
15926
+ return;
15927
+ }
15928
+ if (!task.exists) {
15929
+ console.log(chalk10.yellow(`
15930
+ Scheduled Task "${RUNNER_TASK_NAME}" is not registered \u2014 run: compbox service install`));
15931
+ } else {
15932
+ console.log(`
15933
+ Scheduled Task "${RUNNER_TASK_NAME}"`);
15934
+ console.log(` Status: ${task.status ?? "unknown"}`);
15935
+ console.log(` Runs as: ${task.runAsUser ?? "unknown"}`);
15936
+ if (task.taskToRun) console.log(` Command: ${task.taskToRun}`);
15937
+ }
15938
+ const legacy = await queryLegacyService();
15939
+ if (legacy !== "absent") {
15940
+ console.log(chalk10.yellow(`
15941
+ \u26A0 Old LocalSystem service "${LEGACY_SERVICE_NAME}" is still installed (${legacy}).`));
15942
+ printElevatedCommands();
14630
15943
  }
14631
15944
  });
14632
15945
 
@@ -14892,8 +16205,8 @@ Setting up ${match.name} (${match.gitRemote})...`));
14892
16205
  import { Command as Command13 } from "commander";
14893
16206
  import chalk14 from "chalk";
14894
16207
  import { spawnSync as spawnSync2 } from "node:child_process";
14895
- import { mkdirSync as mkdirSync11, writeFileSync as writeFileSync10 } from "node:fs";
14896
- import { homedir as homedir9 } from "node:os";
16208
+ import { mkdirSync as mkdirSync12, readdirSync as readdirSync5, readFileSync as readFileSync9, statSync as statSync6, writeFileSync as writeFileSync11 } from "node:fs";
16209
+ import { homedir as homedir10 } from "node:os";
14897
16210
  import { join as join18 } from "node:path";
14898
16211
  function readWorkspaceEnv(env = process.env) {
14899
16212
  const apiUrl = env.COMPBOX_API_URL?.trim();
@@ -14902,15 +16215,15 @@ function readWorkspaceEnv(env = process.env) {
14902
16215
  if (!apiUrl || !jobId || !token) return null;
14903
16216
  return { apiUrl: apiUrl.replace(/\/+$/, ""), jobId, token };
14904
16217
  }
14905
- async function workspaceApi(env, path3, method, fetchFn) {
16218
+ async function workspaceApi(env, path3, method, fetchFn, body = {}) {
14906
16219
  const res = await fetchFn(`${env.apiUrl}/api/v1/cloud-runs/workspace/${path3}`, {
14907
16220
  method,
14908
16221
  headers: { Authorization: `Bearer ${env.token}`, ...method === "POST" && { "Content-Type": "application/json" } },
14909
- ...method === "POST" && { body: "{}" }
16222
+ ...method === "POST" && { body: JSON.stringify(body) }
14910
16223
  });
14911
16224
  if (!res.ok) {
14912
- const body = await res.json().catch(() => null);
14913
- throw new Error(body?.error?.message ?? `CompBox returned ${String(res.status)} for ${path3}`);
16225
+ const body2 = await res.json().catch(() => null);
16226
+ throw new Error(body2?.error?.message ?? `CompBox returned ${String(res.status)} for ${path3}`);
14914
16227
  }
14915
16228
  return (await res.json()).data;
14916
16229
  }
@@ -14938,7 +16251,7 @@ async function runWorkspace(deps = {}) {
14938
16251
  }
14939
16252
  const fetchFn = deps.fetchFn ?? fetch;
14940
16253
  const run = deps.run ?? defaultRunner;
14941
- const home = deps.home ?? homedir9();
16254
+ const home = deps.home ?? homedir10();
14942
16255
  const agentsDir = deps.agentsDir ?? "/opt/compbox/.github/agents/claude";
14943
16256
  const workDir = deps.workDir ?? "/workspace";
14944
16257
  const client = deps.client ?? new MailboxClient(env.apiUrl);
@@ -14968,7 +16281,7 @@ async function runWorkspace(deps = {}) {
14968
16281
  run("git", ["config", "--global", "credential.helper", "!compbox workspace git-credential"]);
14969
16282
  run("git", ["config", "--global", "user.name", "CompBox"]);
14970
16283
  run("git", ["config", "--global", "user.email", "bot@mycompbox.com"]);
14971
- mkdirSync11(workDir, { recursive: true });
16284
+ mkdirSync12(workDir, { recursive: true });
14972
16285
  run("git", ["clone", "--branch", git.defaultBranch, git.cloneUrl, repoDir]);
14973
16286
  run("claude", [
14974
16287
  "mcp",
@@ -14983,8 +16296,8 @@ async function runWorkspace(deps = {}) {
14983
16296
  "--",
14984
16297
  "compbox-mcp"
14985
16298
  ]);
14986
- mkdirSync11(join18(home, ".claude"), { recursive: true });
14987
- writeFileSync10(join18(home, ".claude", "CLAUDE.md"), agentRoutingInstructions(agentsDir));
16299
+ mkdirSync12(join18(home, ".claude"), { recursive: true });
16300
+ writeFileSync11(join18(home, ".claude", "CLAUDE.md"), agentRoutingInstructions(agentsDir));
14988
16301
  } catch (error) {
14989
16302
  return fail(`Setting up the cloud workspace failed: ${error instanceof Error ? error.message : String(error)}`);
14990
16303
  }
@@ -15061,17 +16374,96 @@ async function runWorkspace(deps = {}) {
15061
16374
  }
15062
16375
  if (cancelled()) return finishCancelled();
15063
16376
  if (outcome.status === "waiting") {
15064
- const resetAt = outcome.resumeAt ? ` (it resets at ${outcome.resumeAt.toISOString()})` : "";
15065
- await client.completeJob(env.token, job.id, "failed", {
15066
- ...outcome.result,
15067
- error: `The AI usage limit was reached${resetAt}. Cloud runs can't wait for the reset \u2014 start the run again once the limit resets.`
15068
- });
16377
+ return parkWorkspace({ env, jobId: job.id, outcome, home, run, fetchFn, client });
15069
16378
  } else {
15070
16379
  await client.completeJob(env.token, job.id, outcome.status, outcome.result);
15071
16380
  }
15072
16381
  console.log(outcome.status === "done" ? chalk14.green("Finished.") : chalk14.yellow(`Stopped: ${JSON.stringify(outcome.result)}`));
15073
16382
  return outcome.status === "done" ? 0 : 1;
15074
16383
  }
16384
+ var MAX_TRANSCRIPT_BYTES = 5 * 1024 * 1024;
16385
+ function findSessionTranscript(home) {
16386
+ const root = join18(home, ".claude", "projects");
16387
+ let newest = null;
16388
+ let folders;
16389
+ try {
16390
+ folders = readdirSync5(root);
16391
+ } catch {
16392
+ return null;
16393
+ }
16394
+ for (const folder of folders) {
16395
+ let files;
16396
+ try {
16397
+ files = readdirSync5(join18(root, folder));
16398
+ } catch {
16399
+ continue;
16400
+ }
16401
+ for (const file of files) {
16402
+ if (!file.endsWith(".jsonl")) continue;
16403
+ const path3 = join18(root, folder, file);
16404
+ const stat = statSync6(path3, { throwIfNoEntry: false });
16405
+ if (!stat?.isFile()) continue;
16406
+ if (!newest || stat.mtimeMs > newest.mtime) {
16407
+ newest = { path: path3, folder, sessionId: file.slice(0, -".jsonl".length), mtime: stat.mtimeMs, bytes: stat.size };
16408
+ }
16409
+ }
16410
+ }
16411
+ if (!newest) return null;
16412
+ return {
16413
+ sessionId: newest.sessionId,
16414
+ projectFolder: newest.folder,
16415
+ transcript: newest.bytes > MAX_TRANSCRIPT_BYTES ? "" : readFileSync9(newest.path, "utf-8"),
16416
+ bytes: newest.bytes
16417
+ };
16418
+ }
16419
+ async function parkWorkspace({ env, jobId, outcome, home, run, fetchFn, client }) {
16420
+ const result = outcome.result;
16421
+ const needsInput = result.stopReason === "needs_input";
16422
+ const failPark = async (why) => {
16423
+ const resetAt = outcome.resumeAt ? ` (it resets at ${outcome.resumeAt.toISOString()})` : "";
16424
+ const error = needsInput ? `The run stopped to ask you something, but it couldn't be paused: ${why}. Start the run again.` : `The AI usage limit was reached${resetAt}, but the run couldn't be paused: ${why}. Start the run again once the limit resets.`;
16425
+ console.error(chalk14.red(error));
16426
+ await client.completeJob(env.token, jobId, "failed", { ...result, error }).catch(() => void 0);
16427
+ return 1;
16428
+ };
16429
+ const branch = typeof result.branch === "string" ? result.branch : void 0;
16430
+ const commits = typeof result.commits === "number" ? result.commits : 0;
16431
+ const keptWorktree = typeof result.keptWorktree === "string" ? result.keptWorktree : void 0;
16432
+ let pushed = result.pushed === true;
16433
+ if (branch && commits > 0 && !pushed) {
16434
+ if (!keptWorktree) return failPark(`its branch ${branch} wasn't pushed`);
16435
+ try {
16436
+ run("git", ["push", "--set-upstream", "origin", `HEAD:refs/heads/${branch}`], keptWorktree);
16437
+ pushed = true;
16438
+ } catch (error) {
16439
+ return failPark(`pushing its branch ${branch} failed (${error instanceof Error ? error.message : String(error)})`);
16440
+ }
16441
+ }
16442
+ const session = findSessionTranscript(home);
16443
+ if (!session) return failPark("its Claude session couldn't be found");
16444
+ if (session.bytes > MAX_TRANSCRIPT_BYTES) {
16445
+ return failPark(`its Claude session is too large to keep (${String(Math.ceil(session.bytes / 1024 / 1024))} MB, the limit is 5 MB)`);
16446
+ }
16447
+ try {
16448
+ await workspaceApi(env, "park", "POST", fetchFn, {
16449
+ jobId,
16450
+ reason: needsInput ? "needs_input" : "usage_limit",
16451
+ result: { ...result, ...branch && { pushed } },
16452
+ ...outcome.resumeAt && { resumeAt: outcome.resumeAt.toISOString() },
16453
+ sessionId: session.sessionId,
16454
+ projectFolder: session.projectFolder,
16455
+ transcript: session.transcript
16456
+ });
16457
+ } catch (error) {
16458
+ return failPark(error instanceof Error ? error.message : String(error));
16459
+ }
16460
+ console.log(
16461
+ chalk14.yellow(
16462
+ needsInput ? "Paused: waiting for your reply. The run picks up again when you answer." : `Paused: the AI usage limit was reached. The run picks up again${outcome.resumeAt ? ` at ${outcome.resumeAt.toISOString()}` : " once it resets"}.`
16463
+ )
16464
+ );
16465
+ return 0;
16466
+ }
15075
16467
  async function gitCredential(action, deps = {}) {
15076
16468
  if (action !== "get") return;
15077
16469
  const env = readWorkspaceEnv(deps.env);