toc-ocra 0.2.34 → 0.2.36

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 (74) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +129 -121
  3. package/assets/icon.svg +1 -1
  4. package/dist/cli/cli.mjs +747 -395
  5. package/dist/plugin/renderer.css.map +1 -1
  6. package/dist/plugin/renderer.js.map +1 -1
  7. package/dist/service/agent.mjs +734 -383
  8. package/dist/src/exec/script-runner.js +9 -5
  9. package/dist/src/exec/script-runner.js.map +1 -1
  10. package/dist/src/health/server.js +8 -8
  11. package/dist/src/index.js +6 -2
  12. package/dist/src/index.js.map +1 -1
  13. package/dist/src/platform/common.d.ts +20 -0
  14. package/dist/src/platform/common.js +40 -0
  15. package/dist/src/platform/common.js.map +1 -0
  16. package/dist/src/platform/index.d.ts +10 -0
  17. package/dist/src/platform/index.js +20 -0
  18. package/dist/src/platform/index.js.map +1 -0
  19. package/dist/src/platform/posix.d.ts +2 -0
  20. package/dist/src/platform/posix.js +210 -0
  21. package/dist/src/platform/posix.js.map +1 -0
  22. package/dist/src/platform/types.d.ts +61 -0
  23. package/dist/src/platform/types.js +2 -0
  24. package/dist/src/platform/types.js.map +1 -0
  25. package/dist/src/platform/win32.d.ts +4 -0
  26. package/dist/src/platform/win32.js +162 -0
  27. package/dist/src/platform/win32.js.map +1 -0
  28. package/dist/src/providers/cli/claude.js +3 -2
  29. package/dist/src/providers/cli/claude.js.map +1 -1
  30. package/dist/src/providers/cli/codex.js +3 -2
  31. package/dist/src/providers/cli/codex.js.map +1 -1
  32. package/dist/src/providers/cli/gemini.js +2 -2
  33. package/dist/src/providers/cli/gemini.js.map +1 -1
  34. package/dist/src/providers/cli/grok.js +2 -2
  35. package/dist/src/providers/cli/grok.js.map +1 -1
  36. package/dist/src/providers/cli/kiro-session-log.d.ts +53 -0
  37. package/dist/src/providers/cli/kiro-session-log.js +155 -0
  38. package/dist/src/providers/cli/kiro-session-log.js.map +1 -0
  39. package/dist/src/providers/cli/kiro.d.ts +8 -2
  40. package/dist/src/providers/cli/kiro.js +100 -13
  41. package/dist/src/providers/cli/kiro.js.map +1 -1
  42. package/dist/src/providers/cli/opencode.js +2 -2
  43. package/dist/src/providers/cli/opencode.js.map +1 -1
  44. package/dist/src/providers/codex-quota.js +3 -2
  45. package/dist/src/providers/codex-quota.js.map +1 -1
  46. package/dist/src/providers/detection.js +3 -1
  47. package/dist/src/providers/detection.js.map +1 -1
  48. package/dist/src/providers/kiro-models.js +3 -2
  49. package/dist/src/providers/kiro-models.js.map +1 -1
  50. package/dist/src/providers/model-catalog.js +3 -1
  51. package/dist/src/providers/model-catalog.js.map +1 -1
  52. package/dist/src/providers/provider.d.ts +55 -4
  53. package/dist/src/providers/provider.js +51 -15
  54. package/dist/src/providers/provider.js.map +1 -1
  55. package/dist/src/runs/orphan-registry.js +2 -8
  56. package/dist/src/runs/orphan-registry.js.map +1 -1
  57. package/dist/src/runs/process-tree.d.ts +5 -14
  58. package/dist/src/runs/process-tree.js +7 -83
  59. package/dist/src/runs/process-tree.js.map +1 -1
  60. package/dist/src/runs/run-supervisor.d.ts +2 -0
  61. package/dist/src/runs/run-supervisor.js +56 -10
  62. package/dist/src/runs/run-supervisor.js.map +1 -1
  63. package/dist/src/runtime/cli/hydrate-shell-path.d.ts +9 -22
  64. package/dist/src/runtime/cli/hydrate-shell-path.js +17 -148
  65. package/dist/src/runtime/cli/hydrate-shell-path.js.map +1 -1
  66. package/dist/src/shared/node-cli-command-resolution.d.ts +5 -0
  67. package/dist/src/shared/node-cli-command-resolution.js +28 -81
  68. package/dist/src/shared/node-cli-command-resolution.js.map +1 -1
  69. package/locales/en.json +202 -202
  70. package/locales/zh-CN.json +202 -202
  71. package/package.json +100 -100
  72. package/scripts/installation.cjs +239 -239
  73. package/scripts/postinstall.cjs +22 -22
  74. package/scripts/service.mjs +253 -253
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
 
8
8
  // src/plugin-service.ts
9
9
  import { existsSync as existsSync6 } from "node:fs";
10
- import { delimiter as delimiter5, join as join12 } from "node:path";
10
+ import { delimiter as delimiter5, join as join15 } from "node:path";
11
11
 
12
12
  // src/config.ts
13
13
  import { randomUUID } from "node:crypto";
@@ -20322,46 +20322,109 @@ function createDiagnosticLogger(filePath, options = {}) {
20322
20322
  }
20323
20323
 
20324
20324
  // src/providers/detection.ts
20325
- import { spawn as spawn2 } from "node:child_process";
20325
+ import { spawn as spawn3 } from "node:child_process";
20326
20326
 
20327
20327
  // src/runtime/cli/hydrate-shell-path.ts
20328
- import { spawn } from "node:child_process";
20329
- import { delimiter as delimiter2 } from "node:path";
20330
- var DELIMITER = "__ORCA_SHELL_PATH__";
20331
- var PROXY_DELIMITER = "__ECHO_SHELL_PROXY__";
20328
+ import { delimiter as delimiter3 } from "node:path";
20329
+
20330
+ // src/platform/common.ts
20331
+ import { join as join3 } from "node:path";
20332
20332
  var PROXY_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"];
20333
- var SPAWN_TIMEOUT_MS = 5e3;
20334
- var ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
20335
- var cached2 = null;
20336
- function pickShell() {
20337
- if (process.platform === "win32") {
20338
- return null;
20333
+ var NODE_SCRIPT = /\.(c|m)?js$/i;
20334
+ function isNodeScript(path) {
20335
+ return NODE_SCRIPT.test(path);
20336
+ }
20337
+ function sharedUserBinDirectoriesHead(home) {
20338
+ return [
20339
+ join3(home, ".volta", "bin"),
20340
+ join3(home, ".asdf", "shims"),
20341
+ join3(home, ".fnm", "aliases", "default", "bin"),
20342
+ // Why: mise (formerly rtx) exposes managed tool binaries via a shims
20343
+ // directory, similar to asdf.
20344
+ join3(home, ".local", "share", "mise", "shims")
20345
+ ];
20346
+ }
20347
+ function sharedUserBinDirectoriesTail(home) {
20348
+ return [join3(home, ".bun", "bin")];
20349
+ }
20350
+ function directLaunch(platform2, path, args, nodePath = process.execPath) {
20351
+ const target = platform2.unwrapLauncher(path) ?? path;
20352
+ if (isNodeScript(target)) return { executable: nodePath, args: [target, ...args] };
20353
+ return { executable: target, args: [...args] };
20354
+ }
20355
+ function commandLineLength(executable, args) {
20356
+ return [executable, ...args].reduce((total, value) => total + value.length + (value.match(/["\\]/g)?.length ?? 0) + 3, 0);
20357
+ }
20358
+
20359
+ // src/platform/posix.ts
20360
+ import { execFile, spawn } from "node:child_process";
20361
+ import { accessSync, constants, statSync as statSync2 } from "node:fs";
20362
+ import { delimiter as delimiter2, join as join4 } from "node:path";
20363
+ function readProcessTable() {
20364
+ return new Promise((resolve7) => {
20365
+ execFile("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
20366
+ if (error62) return resolve7([]);
20367
+ resolve7(stdout.split("\n").flatMap((line) => {
20368
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
20369
+ return pid && ppid !== void 0 && Number.isFinite(ppid) ? [{ pid, ppid }] : [];
20370
+ }));
20371
+ });
20372
+ });
20373
+ }
20374
+ async function listDescendants(rootPid) {
20375
+ const rows = await readProcessTable();
20376
+ const children = /* @__PURE__ */ new Map();
20377
+ for (const row of rows) children.set(row.ppid, [...children.get(row.ppid) ?? [], row.pid]);
20378
+ const out = [];
20379
+ const queue = [...children.get(rootPid) ?? []];
20380
+ while (queue.length > 0) {
20381
+ const pid = queue.shift();
20382
+ if (out.includes(pid)) continue;
20383
+ out.push(pid);
20384
+ queue.push(...children.get(pid) ?? []);
20339
20385
  }
20340
- const shell = process.env.SHELL;
20341
- if (shell && shell.length > 0) {
20342
- return shell;
20386
+ return out;
20387
+ }
20388
+ function signal(pid, sig) {
20389
+ try {
20390
+ process.kill(pid, sig);
20391
+ } catch {
20343
20392
  }
20344
- return process.platform === "darwin" ? "/bin/zsh" : "/bin/bash";
20345
20393
  }
20394
+ function alive(pid) {
20395
+ try {
20396
+ process.kill(pid, 0);
20397
+ return true;
20398
+ } catch {
20399
+ return false;
20400
+ }
20401
+ }
20402
+ var sleep = (ms) => new Promise((resolve7) => setTimeout(resolve7, ms));
20403
+ async function killPosixTree(rootPid, graceMs) {
20404
+ const descendants = await listDescendants(rootPid);
20405
+ signal(-rootPid, "SIGTERM");
20406
+ signal(rootPid, "SIGTERM");
20407
+ for (const pid of descendants) signal(pid, "SIGTERM");
20408
+ const members2 = [rootPid, ...descendants];
20409
+ const deadline = Date.now() + graceMs;
20410
+ while (Date.now() < deadline && members2.some(alive)) await sleep(100);
20411
+ const late = alive(rootPid) ? await listDescendants(rootPid) : [];
20412
+ signal(-rootPid, "SIGKILL");
20413
+ for (const pid of [...members2, ...late]) if (alive(pid)) signal(pid, "SIGKILL");
20414
+ }
20415
+ var PATH_DELIMITER = "__ORCA_SHELL_PATH__";
20416
+ var PROXY_DELIMITER = "__ECHO_SHELL_PROXY__";
20417
+ var SHELL_TIMEOUT_MS = 5e3;
20418
+ var ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
20346
20419
  function parseCapturedPath(stdout) {
20347
20420
  const cleaned = stdout.replace(ANSI_RE, "");
20348
- const first = cleaned.indexOf(DELIMITER);
20349
- if (first < 0) {
20350
- return [];
20351
- }
20352
- const second = cleaned.indexOf(DELIMITER, first + DELIMITER.length);
20353
- if (second < 0) {
20354
- return [];
20355
- }
20356
- const value = cleaned.slice(first + DELIMITER.length, second).trim();
20357
- if (!value) {
20358
- return [];
20359
- }
20360
- return [
20361
- ...new Set(
20362
- value.split(delimiter2).map((s) => s.trim()).filter(Boolean)
20363
- )
20364
- ];
20421
+ const first = cleaned.indexOf(PATH_DELIMITER);
20422
+ if (first < 0) return [];
20423
+ const second = cleaned.indexOf(PATH_DELIMITER, first + PATH_DELIMITER.length);
20424
+ if (second < 0) return [];
20425
+ const value = cleaned.slice(first + PATH_DELIMITER.length, second).trim();
20426
+ if (!value) return [];
20427
+ return [...new Set(value.split(delimiter2).map((s) => s.trim()).filter(Boolean))];
20365
20428
  }
20366
20429
  function parseCapturedProxy(stdout) {
20367
20430
  const start = stdout.indexOf(PROXY_DELIMITER);
@@ -20370,48 +20433,28 @@ function parseCapturedProxy(stdout) {
20370
20433
  const values = stdout.slice(start + PROXY_DELIMITER.length, end).split("\0");
20371
20434
  return Object.fromEntries(PROXY_KEYS.flatMap((key, index) => values[index] ? [[key, values[index]]] : []));
20372
20435
  }
20373
- function mergeShellProxyEnvironment(hydration, baseline = process.env) {
20374
- const environment = { ...baseline };
20375
- if (!hydration.ok) return environment;
20376
- for (const key of PROXY_KEYS.slice(0, 4)) {
20377
- const upper = key.toUpperCase();
20378
- if (baseline[key] !== void 0 || baseline[upper] !== void 0) continue;
20379
- const value = hydration.proxyEnv?.[key] ?? hydration.proxyEnv?.[upper];
20380
- if (value) environment[key] = value;
20381
- }
20382
- return environment;
20383
- }
20384
- function spawnShellAndReadPath(shell) {
20436
+ function readLoginShell(shell) {
20385
20437
  return new Promise((resolve7) => {
20386
20438
  const proxyValues = PROXY_KEYS.map((key) => `"\${${key}-}"`).join(" ");
20387
- const command = `printf '%s' '${DELIMITER}'; printf '%s' "$PATH"; printf '%s' '${DELIMITER}'; printf '%s' '${PROXY_DELIMITER}'; printf '%s\\0' ${proxyValues}; printf '%s' '${PROXY_DELIMITER}'`;
20439
+ const command = `printf '%s' '${PATH_DELIMITER}'; printf '%s' "$PATH"; printf '%s' '${PATH_DELIMITER}'; printf '%s' '${PROXY_DELIMITER}'; printf '%s\\0' ${proxyValues}; printf '%s' '${PROXY_DELIMITER}'`;
20388
20440
  let finished = false;
20389
20441
  let stdout = "";
20390
20442
  let timer = null;
20391
20443
  const child = spawn(shell, ["-ilc", command], {
20392
20444
  // Why: inherit current env so the shell sees the same baseline, then let
20393
20445
  // it layer its own rc files on top. Do NOT forward stdio — some shells
20394
- // (oh-my-zsh setups, powerlevel10k) print a lot to stderr on startup,
20395
- // and we don't want that in Orca's console.
20446
+ // (oh-my-zsh setups, powerlevel10k) print a lot to stderr on startup.
20396
20447
  env: process.env,
20397
20448
  stdio: ["ignore", "pipe", "ignore"],
20398
20449
  detached: false
20399
20450
  });
20400
- const cleanup = () => {
20401
- if (timer) {
20402
- clearTimeout(timer);
20403
- timer = null;
20404
- }
20405
- child.stdout.off("data", onStdoutData);
20406
- child.off("error", onError);
20407
- child.off("close", onClose);
20408
- };
20409
20451
  const finish = (result) => {
20410
- if (finished) {
20411
- return;
20412
- }
20452
+ if (finished) return;
20413
20453
  finished = true;
20414
- cleanup();
20454
+ if (timer) clearTimeout(timer);
20455
+ child.stdout.removeAllListeners("data");
20456
+ child.removeAllListeners("error");
20457
+ child.removeAllListeners("close");
20415
20458
  resolve7(result);
20416
20459
  };
20417
20460
  timer = setTimeout(() => {
@@ -20420,44 +20463,229 @@ function spawnShellAndReadPath(shell) {
20420
20463
  } catch {
20421
20464
  }
20422
20465
  finish({ segments: [], ok: false, failureReason: "timeout" });
20423
- }, SPAWN_TIMEOUT_MS);
20424
- const onStdoutData = (chunk) => {
20466
+ }, SHELL_TIMEOUT_MS);
20467
+ child.stdout.on("data", (chunk) => {
20425
20468
  stdout += chunk.toString("utf8");
20426
- };
20427
- const onError = () => {
20428
- finish({ segments: [], ok: false, failureReason: "spawn_error" });
20429
- };
20430
- const onClose = () => {
20469
+ });
20470
+ child.on("error", () => finish({ segments: [], ok: false, failureReason: "spawn_error" }));
20471
+ child.on("close", () => {
20431
20472
  const segments = parseCapturedPath(stdout);
20432
20473
  if (segments.length === 0) {
20433
20474
  finish({ segments: [], ok: false, failureReason: "empty_path" });
20434
20475
  return;
20435
20476
  }
20436
20477
  finish({ segments, proxyEnv: parseCapturedProxy(stdout), ok: true, failureReason: "none" });
20437
- };
20438
- child.stdout.on("data", onStdoutData);
20439
- child.on("error", onError);
20440
- child.on("close", onClose);
20478
+ });
20441
20479
  });
20442
20480
  }
20443
- function hydrateShellPath(options = {}) {
20444
- if (cached2 && !options.force) {
20445
- return cached2;
20481
+ function createPosixPlatform(id) {
20482
+ return {
20483
+ id,
20484
+ executableNames: (command) => [command],
20485
+ isRunnableFile(path) {
20486
+ try {
20487
+ if (!statSync2(path).isFile()) return false;
20488
+ accessSync(path, constants.X_OK);
20489
+ return true;
20490
+ } catch {
20491
+ return false;
20492
+ }
20493
+ },
20494
+ userBinDirectories: (home) => [
20495
+ join4(home, ".local", "bin"),
20496
+ // Why: pnpm uses platform-specific global bin directories that differ
20497
+ // from npm's ~/.local/bin.
20498
+ id === "darwin" ? join4(home, "Library", "pnpm") : join4(home, ".local", "share", "pnpm"),
20499
+ join4(home, ".yarn", "bin")
20500
+ ],
20501
+ fallbackBinDirectories: (home) => ["/opt/homebrew/bin", "/usr/local/bin", join4(home, ".local", "bin")],
20502
+ normalizeEnvironment: (env) => ({ ...env }),
20503
+ // Shebang scripts and symlinks start directly.
20504
+ unwrapLauncher: () => void 0,
20505
+ // Linux caps a single argument at 128 KiB (MAX_ARG_STRLEN); macOS caps
20506
+ // the whole command line plus environment at 1 MiB (ARG_MAX).
20507
+ maxCommandLineLength: id === "linux" ? 12e4 : 9e5,
20508
+ runsInOwnProcessGroup: true,
20509
+ killProcessTree: killPosixTree,
20510
+ stopHelper: (child) => {
20511
+ child.kill("SIGTERM");
20512
+ },
20513
+ processCommandLine(pid) {
20514
+ return new Promise((resolve7) => {
20515
+ execFile("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
20516
+ resolve7(error62 ? void 0 : stdout.trim() || void 0);
20517
+ });
20518
+ });
20519
+ },
20520
+ scriptShell: (command) => ({ executable: "/bin/sh", args: ["-lc", command] }),
20521
+ readLoginEnvironment() {
20522
+ const shell = process.env.SHELL || (id === "darwin" ? "/bin/zsh" : "/bin/bash");
20523
+ return readLoginShell(shell);
20524
+ }
20525
+ };
20526
+ }
20527
+
20528
+ // src/platform/win32.ts
20529
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
20530
+ import { readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
20531
+ import { join as join5, win32 } from "node:path";
20532
+ var SYSTEM_ROOT = process.env.SystemRoot || process.env.windir || "C:\\Windows";
20533
+ var POWERSHELL = join5(SYSTEM_ROOT, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
20534
+ var HELPER_TIMEOUT_MS = 5e3;
20535
+ var SHIM_TARGET_RE = /%~?dp0%?\\?([^"%\r\n]+)/gi;
20536
+ var SHIM_TARGET_EXTENSIONS = /\.(c|m)?js$|\.exe$/i;
20537
+ var MAX_SHIM_BYTES = 64 * 1024;
20538
+ function resolveWindowsCommandShim(shimPath) {
20539
+ if (!/\.(cmd|bat)$/i.test(shimPath)) return void 0;
20540
+ let content;
20541
+ try {
20542
+ if (statSync3(shimPath).size > MAX_SHIM_BYTES) return void 0;
20543
+ content = readFileSync4(shimPath, "utf8");
20544
+ } catch {
20545
+ return void 0;
20546
+ }
20547
+ const base = win32.dirname(shimPath);
20548
+ const targets = [...content.matchAll(SHIM_TARGET_RE)].map((match) => match[1].trim()).filter((target) => SHIM_TARGET_EXTENSIONS.test(target) && !/(^|\\)node\.exe$/i.test(target));
20549
+ for (const target of targets.reverse()) {
20550
+ const absolute = win32.isAbsolute(target) ? target : win32.resolve(base, target);
20551
+ try {
20552
+ if (statSync3(absolute).isFile()) return absolute;
20553
+ } catch {
20554
+ }
20446
20555
  }
20447
- const shell = options.shellOverride !== void 0 ? options.shellOverride : pickShell();
20448
- if (!shell) {
20449
- cached2 = Promise.resolve({ segments: [], ok: false, failureReason: "no_shell" });
20450
- return cached2;
20556
+ return void 0;
20557
+ }
20558
+ function taskkillTree(rootPid) {
20559
+ return new Promise((resolve7) => {
20560
+ const child = spawn2(join5(SYSTEM_ROOT, "System32", "taskkill.exe"), ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
20561
+ child.once("error", () => resolve7());
20562
+ child.once("close", () => resolve7());
20563
+ });
20564
+ }
20565
+ function runPowerShell(script) {
20566
+ const prelude = '$ProgressPreference="SilentlyContinue";[Console]::OutputEncoding=[Text.Encoding]::UTF8;';
20567
+ const encoded = Buffer.from(prelude + script, "utf16le").toString("base64");
20568
+ return new Promise((resolve7) => {
20569
+ execFile2(
20570
+ POWERSHELL,
20571
+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
20572
+ { timeout: HELPER_TIMEOUT_MS, windowsHide: true, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 },
20573
+ (error62, stdout) => {
20574
+ if (!error62) return resolve7({ ok: true, stdout });
20575
+ resolve7({ ok: false, reason: error62.killed ? "timeout" : "spawn_error" });
20576
+ }
20577
+ );
20578
+ });
20579
+ }
20580
+ function expandVariables(value) {
20581
+ return value.replace(/%([^%;]+)%/g, (whole, name) => process.env[name] ?? whole);
20582
+ }
20583
+ async function readRegistryEnvironment() {
20584
+ const names = [...new Set(PROXY_KEYS.map((key) => key.toLowerCase()))];
20585
+ const script = [
20586
+ "$r=@{};",
20587
+ "$r.path=@([Environment]::GetEnvironmentVariable('Path','Machine'),[Environment]::GetEnvironmentVariable('Path','User'));",
20588
+ "$r.proxy=@{};",
20589
+ `foreach($k in @(${names.map((name) => `'${name}'`).join(",")})){`,
20590
+ "$v=[Environment]::GetEnvironmentVariable($k,'User');if(-not $v){$v=[Environment]::GetEnvironmentVariable($k,'Machine')};if($v){$r.proxy[$k]=$v}};",
20591
+ "$r|ConvertTo-Json -Compress -Depth 4"
20592
+ ].join("");
20593
+ const result = await runPowerShell(script);
20594
+ if (!result.ok) return { ok: false, segments: [], failureReason: result.reason };
20595
+ let parsed;
20596
+ try {
20597
+ parsed = JSON.parse(result.stdout.trim());
20598
+ } catch {
20599
+ return { ok: false, segments: [], failureReason: "empty_path" };
20600
+ }
20601
+ const raw = (Array.isArray(parsed.path) ? parsed.path : [parsed.path]).filter((value) => typeof value === "string");
20602
+ const segments = [...new Set(raw.flatMap((value) => value.split(";")).map((segment) => expandVariables(segment.trim())).filter(Boolean))];
20603
+ if (segments.length === 0) return { ok: false, segments: [], failureReason: "empty_path" };
20604
+ const proxyEnv = Object.fromEntries(Object.entries(parsed.proxy ?? {}).filter((entry) => typeof entry[1] === "string" && entry[1].length > 0));
20605
+ return { ok: true, segments, proxyEnv, failureReason: "none" };
20606
+ }
20607
+ var win32Platform = {
20608
+ id: "win32",
20609
+ executableNames: (command) => [`${command}.cmd`, `${command}.exe`, `${command}.bat`, command],
20610
+ isRunnableFile(path) {
20611
+ try {
20612
+ return statSync3(path).isFile();
20613
+ } catch {
20614
+ return false;
20615
+ }
20616
+ },
20617
+ userBinDirectories: (home) => [
20618
+ // Why: Anthropic's native Windows installer places claude.exe here, and
20619
+ // GUI-launched processes may not inherit the user's PATH entry for it.
20620
+ join5(home, ".local", "bin"),
20621
+ join5(home, "AppData", "Roaming", "npm"),
20622
+ join5(home, "AppData", "Local", "pnpm"),
20623
+ join5(home, "AppData", "Local", "Yarn", "bin")
20624
+ ],
20625
+ fallbackBinDirectories: (home) => [join5(home, ".local", "bin")],
20626
+ normalizeEnvironment(env) {
20627
+ const copy = { ...env };
20628
+ const keys = Object.keys(copy).filter((key) => key.toUpperCase() === "PATH");
20629
+ const value = keys.map((key) => copy[key]).find((entry) => entry);
20630
+ for (const key of keys) delete copy[key];
20631
+ if (value) copy.PATH = value;
20632
+ return copy;
20633
+ },
20634
+ unwrapLauncher: resolveWindowsCommandShim,
20635
+ // CreateProcess limit is 32 767 UTF-16 units; keep a margin for the
20636
+ // wrapper that relaunches the native binary with the same arguments.
20637
+ maxCommandLineLength: 3e4,
20638
+ runsInOwnProcessGroup: false,
20639
+ killProcessTree: (rootPid) => taskkillTree(rootPid),
20640
+ stopHelper(child) {
20641
+ child.stdin?.end();
20642
+ if (child.pid) void taskkillTree(child.pid);
20643
+ else child.kill();
20644
+ },
20645
+ async processCommandLine(pid) {
20646
+ if (!Number.isInteger(pid) || pid <= 0) return void 0;
20647
+ const result = await runPowerShell(`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`);
20648
+ return result.ok ? result.stdout.trim() || void 0 : void 0;
20649
+ },
20650
+ scriptShell: (command) => ({ executable: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", command] }),
20651
+ readLoginEnvironment: readRegistryEnvironment
20652
+ };
20653
+
20654
+ // src/platform/index.ts
20655
+ var darwinPlatform = createPosixPlatform("darwin");
20656
+ var linuxPlatform = createPosixPlatform("linux");
20657
+ function platformFor(id) {
20658
+ if (id === "win32") return win32Platform;
20659
+ if (id === "darwin") return darwinPlatform;
20660
+ return linuxPlatform;
20661
+ }
20662
+ var currentPlatform = platformFor(process.platform);
20663
+ function directLaunch2(path, args, nodePath = process.execPath) {
20664
+ return directLaunch(currentPlatform, path, args, nodePath);
20665
+ }
20666
+
20667
+ // src/runtime/cli/hydrate-shell-path.ts
20668
+ var cached2 = null;
20669
+ function mergeShellProxyEnvironment(hydration, baseline = process.env) {
20670
+ const environment = { ...baseline };
20671
+ if (!hydration.ok) return environment;
20672
+ for (const key of PROXY_KEYS.slice(0, 4)) {
20673
+ const upper = key.toUpperCase();
20674
+ if (baseline[key] !== void 0 || baseline[upper] !== void 0) continue;
20675
+ const value = hydration.proxyEnv?.[key] ?? hydration.proxyEnv?.[upper];
20676
+ if (value) environment[key] = value;
20451
20677
  }
20452
- cached2 = (options.spawner ?? spawnShellAndReadPath)(shell);
20678
+ return environment;
20679
+ }
20680
+ function hydrateShellPath(options = {}) {
20681
+ if (cached2 && !options.force) return cached2;
20682
+ cached2 = (options.reader ?? (() => currentPlatform.readLoginEnvironment()))();
20453
20683
  return cached2;
20454
20684
  }
20455
20685
  function mergePathSegments(segments) {
20456
- if (segments.length === 0) {
20457
- return [];
20458
- }
20686
+ if (segments.length === 0) return [];
20459
20687
  const current = process.env.PATH ?? "";
20460
- const currentSegments = current.split(delimiter2).filter(Boolean);
20688
+ const currentSegments = current.split(delimiter3).filter(Boolean);
20461
20689
  const shellSegments = [...new Set(segments)];
20462
20690
  const shellSegmentSet = new Set(shellSegments);
20463
20691
  const existing = new Set(currentSegments);
@@ -20466,39 +20694,32 @@ function mergePathSegments(segments) {
20466
20694
  ...shellSegments,
20467
20695
  ...currentSegments.filter((segment) => !shellSegmentSet.has(segment))
20468
20696
  ];
20469
- const next = merged.join(delimiter2);
20470
- if (next === current) {
20471
- return [];
20472
- }
20697
+ const next = merged.join(delimiter3);
20698
+ if (next === current) return [];
20473
20699
  process.env.PATH = next;
20474
20700
  return added;
20475
20701
  }
20476
20702
 
20477
20703
  // src/providers/cli/claude.ts
20478
- import { readFileSync as readFileSync4 } from "node:fs";
20704
+ import { readFileSync as readFileSync5 } from "node:fs";
20479
20705
  import { homedir as homedir4 } from "node:os";
20480
- import { join as join5 } from "node:path";
20706
+ import { join as join7 } from "node:path";
20481
20707
 
20482
20708
  // src/providers/provider.ts
20483
20709
  import { realpathSync } from "node:fs";
20484
20710
  import { homedir as homedir3 } from "node:os";
20485
- import { delimiter as delimiter4, dirname as dirname4, join as join4 } from "node:path";
20711
+ import { delimiter as delimiter4, dirname as dirname4 } from "node:path";
20486
20712
 
20487
20713
  // src/shared/node-cli-command-resolution.ts
20488
- import { accessSync, constants, existsSync as existsSync4, readdirSync, statSync as statSync2 } from "node:fs";
20714
+ import { existsSync as existsSync4, readdirSync } from "node:fs";
20489
20715
  import { homedir as homedir2 } from "node:os";
20490
- import { delimiter as delimiter3, dirname as dirname3, join as join3 } from "node:path";
20491
- function getExecutableNames(platform2, commandName) {
20492
- if (platform2 === "win32") {
20493
- return [`${commandName}.cmd`, `${commandName}.exe`, `${commandName}.bat`, commandName];
20494
- }
20495
- return [commandName];
20716
+ import { dirname as dirname3, join as join6 } from "node:path";
20717
+ function adapterOf(options) {
20718
+ return platformFor(options.platform ?? process.platform);
20496
20719
  }
20497
- function splitPath(pathEnv) {
20498
- if (!pathEnv) {
20499
- return [];
20500
- }
20501
- return pathEnv.split(delimiter3).map((entry) => entry.trim()).filter(Boolean);
20720
+ function splitPath(platform2, pathEnv) {
20721
+ if (!pathEnv) return [];
20722
+ return pathEnv.split(platform2.id === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean);
20502
20723
  }
20503
20724
  function parseVersionSegment(raw) {
20504
20725
  return raw.replace(/^v/i, "").split(".").map((segment) => Number.parseInt(segment, 10)).map((segment) => Number.isFinite(segment) ? segment : 0);
@@ -20509,116 +20730,58 @@ function compareVersionDesc(left, right) {
20509
20730
  const length = Math.max(leftParts.length, rightParts.length);
20510
20731
  for (let index = 0; index < length; index += 1) {
20511
20732
  const delta = (rightParts[index] ?? 0) - (leftParts[index] ?? 0);
20512
- if (delta !== 0) {
20513
- return delta;
20514
- }
20733
+ if (delta !== 0) return delta;
20515
20734
  }
20516
20735
  return right.localeCompare(left);
20517
20736
  }
20518
20737
  function findFirstExecutable(platform2, directories, executableNames) {
20519
20738
  for (const directory of directories) {
20520
20739
  for (const executableName of executableNames) {
20521
- const candidate = join3(directory, executableName);
20522
- if (isRunnableCommand(platform2, candidate)) {
20523
- return candidate;
20524
- }
20740
+ const candidate = join6(directory, executableName);
20741
+ if (platform2.isRunnableFile(candidate)) return candidate;
20525
20742
  }
20526
20743
  }
20527
20744
  return null;
20528
20745
  }
20529
- function isRunnableCommand(platform2, candidate) {
20530
- try {
20531
- const stats = statSync2(candidate);
20532
- if (!stats.isFile()) {
20533
- return false;
20534
- }
20535
- if (platform2 === "win32") {
20536
- return true;
20537
- }
20538
- accessSync(candidate, constants.X_OK);
20539
- return true;
20540
- } catch {
20541
- return false;
20542
- }
20543
- }
20544
20746
  function getBaseVersionManagerDirectories(platform2, homePath) {
20545
- const directories = [
20546
- join3(homePath, ".volta", "bin"),
20547
- join3(homePath, ".asdf", "shims"),
20548
- join3(homePath, ".fnm", "aliases", "default", "bin"),
20549
- // Why: mise (formerly rtx) exposes managed tool binaries via a shims
20550
- // directory, similar to asdf.
20551
- join3(homePath, ".local", "share", "mise", "shims")
20747
+ return [
20748
+ ...sharedUserBinDirectoriesHead(homePath),
20749
+ ...platform2.userBinDirectories(homePath),
20750
+ ...sharedUserBinDirectoriesTail(homePath)
20552
20751
  ];
20553
- if (platform2 === "win32") {
20554
- directories.push(join3(homePath, ".local", "bin"));
20555
- directories.push(join3(homePath, "AppData", "Roaming", "npm"));
20556
- directories.push(join3(homePath, "AppData", "Local", "pnpm"));
20557
- directories.push(join3(homePath, "AppData", "Local", "Yarn", "bin"));
20558
- } else {
20559
- directories.push(join3(homePath, ".local", "bin"));
20560
- if (platform2 === "darwin") {
20561
- directories.push(join3(homePath, "Library", "pnpm"));
20562
- } else {
20563
- directories.push(join3(homePath, ".local", "share", "pnpm"));
20564
- }
20565
- directories.push(join3(homePath, ".yarn", "bin"));
20566
- }
20567
- directories.push(join3(homePath, ".bun", "bin"));
20568
- return directories;
20569
20752
  }
20570
20753
  function getNvmVersionDirectories(homePath) {
20571
- const nvmVersionsDir = join3(homePath, ".nvm", "versions", "node");
20572
- if (!existsSync4(nvmVersionsDir)) {
20573
- return [];
20574
- }
20575
- return readdirSync(nvmVersionsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionDesc).map((entry) => join3(nvmVersionsDir, entry, "bin"));
20754
+ const nvmVersionsDir = join6(homePath, ".nvm", "versions", "node");
20755
+ if (!existsSync4(nvmVersionsDir)) return [];
20756
+ return readdirSync(nvmVersionsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionDesc).map((entry) => join6(nvmVersionsDir, entry, "bin"));
20576
20757
  }
20577
20758
  function getVersionManagerDirectories(platform2, homePath, executableNames) {
20578
20759
  const directories = getBaseVersionManagerDirectories(platform2, homePath);
20579
- const firstNvmMatch = findFirstExecutable(
20580
- platform2,
20581
- getNvmVersionDirectories(homePath),
20582
- executableNames
20583
- );
20584
- if (firstNvmMatch) {
20585
- directories.unshift(dirname3(firstNvmMatch));
20586
- }
20760
+ const firstNvmMatch = findFirstExecutable(platform2, getNvmVersionDirectories(homePath), executableNames);
20761
+ if (firstNvmMatch) directories.unshift(dirname3(firstNvmMatch));
20587
20762
  return directories;
20588
20763
  }
20589
20764
  function resolveCliCommand(commandName, options = {}) {
20590
20765
  return findCliCommand(commandName, options) ?? commandName;
20591
20766
  }
20592
20767
  function findCliCommand(commandName, options = {}) {
20593
- const platform2 = options.platform ?? process.platform;
20594
- const executableNames = getExecutableNames(platform2, commandName);
20768
+ const platform2 = adapterOf(options);
20769
+ const executableNames = platform2.executableNames(commandName);
20595
20770
  const pathEnv = options.pathEnv ?? process.env.PATH ?? process.env.Path ?? null;
20596
- const pathCandidate = findFirstExecutable(platform2, splitPath(pathEnv), executableNames);
20597
- if (pathCandidate) {
20598
- return pathCandidate;
20599
- }
20771
+ const pathCandidate = findFirstExecutable(platform2, splitPath(platform2, pathEnv), executableNames);
20772
+ if (pathCandidate) return pathCandidate;
20600
20773
  const homePath = options.homePath ?? homedir2();
20601
- const nvmCandidate = findFirstExecutable(
20602
- platform2,
20603
- getNvmVersionDirectories(homePath),
20604
- executableNames
20605
- );
20606
- const versionManagerCandidate = nvmCandidate ?? findFirstExecutable(
20607
- platform2,
20608
- getBaseVersionManagerDirectories(platform2, homePath),
20609
- executableNames
20610
- );
20611
- return versionManagerCandidate;
20774
+ const nvmCandidate = findFirstExecutable(platform2, getNvmVersionDirectories(homePath), executableNames);
20775
+ return nvmCandidate ?? findFirstExecutable(platform2, getBaseVersionManagerDirectories(platform2, homePath), executableNames);
20612
20776
  }
20613
20777
  function resolveCliCommandDetailed(commandName, options = {}) {
20614
20778
  const resolved = findCliCommand(commandName, options);
20615
20779
  return resolved ? { command: resolved, found: true, path: resolved } : { command: commandName, found: false };
20616
20780
  }
20617
20781
  function getVersionManagerBinPaths(options = {}) {
20618
- const platform2 = options.platform ?? process.platform;
20782
+ const platform2 = adapterOf(options);
20619
20783
  const homePath = options.homePath ?? homedir2();
20620
- const nodeNames = getExecutableNames(platform2, "node");
20621
- return getVersionManagerDirectories(platform2, homePath, nodeNames);
20784
+ return getVersionManagerDirectories(platform2, homePath, platform2.executableNames("node"));
20622
20785
  }
20623
20786
 
20624
20787
  // src/providers/provider.ts
@@ -20659,14 +20822,12 @@ function toolCallRows(name, path) {
20659
20822
  return [runLog.tool("tool_call")];
20660
20823
  }
20661
20824
  function providerEnvironment() {
20662
- const env = { ...process.env };
20825
+ const env = currentPlatform.normalizeEnvironment(process.env);
20663
20826
  const commandPaths = [
20664
20827
  dirname4(process.execPath),
20665
- ...getVersionManagerBinPaths(env.PATH === void 0 ? {} : { pathEnv: env.PATH }),
20828
+ ...getVersionManagerBinPaths(),
20666
20829
  env.PATH,
20667
- "/opt/homebrew/bin",
20668
- "/usr/local/bin",
20669
- join4(homedir3(), ".local", "bin")
20830
+ ...currentPlatform.fallbackBinDirectories(homedir3())
20670
20831
  ].filter((value) => Boolean(value));
20671
20832
  env.PATH = [...new Set(commandPaths)].join(delimiter4);
20672
20833
  return env;
@@ -20674,15 +20835,30 @@ function providerEnvironment() {
20674
20835
  function resolveExecutable(command, args, env, override) {
20675
20836
  const candidate = override?.trim() || resolveCliCommand(command, env.PATH === void 0 ? {} : { pathEnv: env.PATH });
20676
20837
  if (!candidate) return { executable: command, args, env };
20838
+ let resolved = candidate;
20677
20839
  try {
20678
- const resolved = realpathSync(candidate);
20679
- if (resolved.endsWith(".js") || resolved.endsWith(".mjs") || resolved.endsWith(".cjs")) {
20680
- return { executable: process.env.TOC_OCRA_NODE_PATH || process.execPath, args: [resolved, ...args], env };
20681
- }
20682
- return { executable: resolved, args, env };
20840
+ resolved = realpathSync(candidate);
20683
20841
  } catch {
20684
- return { executable: candidate, args, env };
20685
20842
  }
20843
+ return { ...directLaunch2(resolved, args, process.env.TOC_OCRA_NODE_PATH || process.execPath), env };
20844
+ }
20845
+ function launchCli(options) {
20846
+ const launch = resolveExecutable(options.command, options.args, options.env ?? providerEnvironment(), process.env[options.overrideEnv]);
20847
+ return options.prompt && options.promptStdin ? fitPromptOnCommandLine(launch, options.prompt, options.promptStdin) : launch;
20848
+ }
20849
+ function fitsCommandLine(launch) {
20850
+ return commandLineLength(launch.executable, launch.args) <= currentPlatform.maxCommandLineLength;
20851
+ }
20852
+ function fitPromptOnCommandLine(launch, prompt, stdin) {
20853
+ if (!prompt || fitsCommandLine(launch)) return launch;
20854
+ const index = launch.args.lastIndexOf(prompt);
20855
+ if (index < 0) return launch;
20856
+ const args = [...launch.args];
20857
+ if (stdin === "omit") {
20858
+ const separator = index > 0 && args[index - 1] === "--" && index === args.length - 1;
20859
+ args.splice(separator ? index - 1 : index, separator ? 2 : 1);
20860
+ } else args[index] = stdin.replaceWith;
20861
+ return { ...launch, args, stdin: prompt };
20686
20862
  }
20687
20863
  function tryJson(line) {
20688
20864
  const start = line.indexOf("{");
@@ -20718,7 +20894,7 @@ var claudeProvider = {
20718
20894
  else {
20719
20895
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*", "--settings", '{"disableAllHooks":true}');
20720
20896
  try {
20721
- const settings = JSON.parse(readFileSync4(join5(homedir4(), ".claude", "settings.json"), "utf8"));
20897
+ const settings = JSON.parse(readFileSync5(join7(homedir4(), ".claude", "settings.json"), "utf8"));
20722
20898
  for (const [key, value] of Object.entries(settings.env ?? {})) {
20723
20899
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
20724
20900
  }
@@ -20728,7 +20904,7 @@ var claudeProvider = {
20728
20904
  if (request.model) args.push("--model", request.model);
20729
20905
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20730
20906
  if (request.sessionId) args.push("--resume", request.sessionId);
20731
- return resolveExecutable("claude", args, env, process.env.TOC_OCRA_CLAUDE_PATH);
20907
+ return launchCli({ command: "claude", overrideEnv: "TOC_OCRA_CLAUDE_PATH", args, env, prompt: request.prompt, promptStdin: "omit" });
20732
20908
  },
20733
20909
  parseLine(line) {
20734
20910
  return claudeLineParser()(line);
@@ -20829,7 +21005,7 @@ var codexProvider = {
20829
21005
  if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
20830
21006
  if (request.sessionId) args.push("resume", request.sessionId);
20831
21007
  args.push("--", request.prompt);
20832
- return resolveExecutable("codex", args, providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
21008
+ return launchCli({ command: "codex", overrideEnv: "TOC_OCRA_CODEX_PATH", args, prompt: request.prompt, promptStdin: { replaceWith: "-" } });
20833
21009
  },
20834
21010
  parseLine(line) {
20835
21011
  const event = tryJson(line);
@@ -20885,7 +21061,7 @@ var geminiProvider = {
20885
21061
  const args = ["-p", request.prompt, "--output-format", "json", "--yolo"];
20886
21062
  if (request.model) args.push("--model", request.model);
20887
21063
  if (request.sessionId) args.push("--resume", request.sessionId);
20888
- return resolveExecutable("gemini", args, providerEnvironment(), process.env.TOC_OCRA_GEMINI_PATH);
21064
+ return launchCli({ command: "gemini", overrideEnv: "TOC_OCRA_GEMINI_PATH", args });
20889
21065
  },
20890
21066
  parseLine(line) {
20891
21067
  const event = tryJson(line);
@@ -20910,7 +21086,7 @@ var grokProvider = {
20910
21086
  if (request.model) args.push("--model", request.model);
20911
21087
  if (request.reasoningEffort) args.push("--reasoning-effort", request.reasoningEffort);
20912
21088
  if (request.sessionId) args.push("--resume", request.sessionId);
20913
- return resolveExecutable("grok", args, providerEnvironment(), process.env.TOC_OCRA_GROK_PATH);
21089
+ return launchCli({ command: "grok", overrideEnv: "TOC_OCRA_GROK_PATH", args });
20914
21090
  },
20915
21091
  parseLine(line) {
20916
21092
  const event = tryJson(line);
@@ -20926,12 +21102,151 @@ var grokProvider = {
20926
21102
  };
20927
21103
 
20928
21104
  // src/providers/cli/kiro.ts
20929
- import { execFile } from "node:child_process";
21105
+ import { execFile as execFile3 } from "node:child_process";
20930
21106
  import { promisify } from "node:util";
20931
- var execFileAsync = promisify(execFile);
21107
+
21108
+ // src/providers/cli/kiro-session-log.ts
21109
+ import { open as open2, readdir, readFile as readFile3, stat } from "node:fs/promises";
21110
+ import { homedir as homedir5 } from "node:os";
21111
+ import { join as join8 } from "node:path";
21112
+ var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
21113
+ function kiroSessionsDirectory() {
21114
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join8(homedir5(), ".kiro", "sessions", "cli");
21115
+ }
21116
+ var KiroSessionLog = class {
21117
+ constructor(options) {
21118
+ this.options = options;
21119
+ }
21120
+ options;
21121
+ path;
21122
+ offset = 0;
21123
+ partial = "";
21124
+ steps = [];
21125
+ results = /* @__PURE__ */ new Map();
21126
+ claimed = /* @__PURE__ */ new Set();
21127
+ get directory() {
21128
+ return this.options.directory ?? kiroSessionsDirectory();
21129
+ }
21130
+ /** Called before the CLI starts: a resumed log is followed from its current end. */
21131
+ async begin() {
21132
+ if (!this.options.sessionId) return;
21133
+ this.path = join8(this.directory, `${this.options.sessionId}.jsonl`);
21134
+ this.offset = await stat(this.path).then((info) => info.size, () => 0);
21135
+ }
21136
+ /**
21137
+ * A fresh turn's chat has no known id: the one log for this folder created
21138
+ * after the turn started. Several candidates (another turn starting a chat
21139
+ * in the same folder) leave it unknown.
21140
+ */
21141
+ async findFreshLog() {
21142
+ const names = await readdir(this.directory).catch(() => []);
21143
+ const found = [];
21144
+ for (const name of names) {
21145
+ if (!name.endsWith(".json")) continue;
21146
+ const meta3 = await readFile3(join8(this.directory, name), "utf8").then((text) => JSON.parse(text), () => void 0);
21147
+ const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
21148
+ if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
21149
+ }
21150
+ if (found.length === 1) this.path = join8(this.directory, `${found[0]}.jsonl`);
21151
+ }
21152
+ /** Reads entries appended since the last call. */
21153
+ async refresh() {
21154
+ if (!this.path) await this.findFreshLog();
21155
+ if (!this.path) return;
21156
+ const file2 = await open2(this.path, "r").catch(() => void 0);
21157
+ if (!file2) return;
21158
+ try {
21159
+ const { size } = await file2.stat();
21160
+ if (size <= this.offset) return;
21161
+ const buffer = Buffer.alloc(size - this.offset);
21162
+ await file2.read(buffer, 0, buffer.length, this.offset);
21163
+ this.offset = size;
21164
+ const lines = (this.partial + buffer.toString("utf8")).split("\n");
21165
+ this.partial = lines.pop() ?? "";
21166
+ for (const line of lines) this.take(line);
21167
+ } finally {
21168
+ await file2.close();
21169
+ }
21170
+ }
21171
+ take(line) {
21172
+ let entry;
21173
+ try {
21174
+ entry = JSON.parse(line);
21175
+ } catch {
21176
+ return;
21177
+ }
21178
+ for (const part of entry.data?.content ?? []) {
21179
+ const data = part.data ?? {};
21180
+ if (part.kind === "toolUse" && SHELL_TOOLS.has(String(data.name))) {
21181
+ const command = data.input?.command;
21182
+ if (typeof data.toolUseId === "string" && typeof command === "string") this.steps.push({ id: data.toolUseId, command });
21183
+ } else if (part.kind === "toolResult" && typeof data.toolUseId === "string") {
21184
+ this.results.set(data.toolUseId, resultOf(data));
21185
+ }
21186
+ }
21187
+ }
21188
+ /** The shell step a `[tool] Running:` row announced (its text may be cut short). */
21189
+ async step(shown, waitMs = 2e3) {
21190
+ const prefix = shown.replace(/\.\.\.$|…$/, "").trim();
21191
+ const deadline = Date.now() + waitMs;
21192
+ for (; ; ) {
21193
+ await this.refresh();
21194
+ const step = this.steps.find((item) => !this.claimed.has(item.id) && item.command.trim().startsWith(prefix));
21195
+ if (step) {
21196
+ this.claimed.add(step.id);
21197
+ return step;
21198
+ }
21199
+ if (Date.now() >= deadline) return void 0;
21200
+ await new Promise((resolve7) => setTimeout(resolve7, 150));
21201
+ }
21202
+ }
21203
+ /** The first of `ids` whose result is in the log, waiting up to `waitMs`. */
21204
+ async firstFinished(ids, waitMs) {
21205
+ const deadline = Date.now() + waitMs;
21206
+ for (; ; ) {
21207
+ await this.refresh();
21208
+ const id = ids.find((item) => this.results.has(item));
21209
+ if (id || Date.now() >= deadline) return id;
21210
+ await new Promise((resolve7) => setTimeout(resolve7, 150));
21211
+ }
21212
+ }
21213
+ async result(id, waitMs = 3e3) {
21214
+ const deadline = Date.now() + waitMs;
21215
+ for (; ; ) {
21216
+ await this.refresh();
21217
+ const result = this.results.get(id);
21218
+ if (result || Date.now() >= deadline) return result;
21219
+ await new Promise((resolve7) => setTimeout(resolve7, 200));
21220
+ }
21221
+ }
21222
+ };
21223
+ function resultOf(data) {
21224
+ const parts = Array.isArray(data.content) ? data.content : [];
21225
+ const texts = [];
21226
+ let exitCode;
21227
+ for (const part of parts) {
21228
+ if (part.kind === "json" && part.data && typeof part.data === "object") {
21229
+ const value = part.data;
21230
+ const code = /(-?\d+)/.exec(String(value.exit_status ?? ""))?.[1];
21231
+ if (code !== void 0) exitCode = Number(code);
21232
+ for (const text of [value.stdout, value.stderr]) if (typeof text === "string" && text.trim()) texts.push(text.replace(/\s+$/, ""));
21233
+ } else if (part.kind === "text" && typeof part.data === "string" && part.data.trim()) {
21234
+ texts.push(part.data.replace(/\s+$/, ""));
21235
+ }
21236
+ }
21237
+ if (exitCode === void 0 && data.status === "error") exitCode = 1;
21238
+ return { ...exitCode === void 0 ? {} : { exitCode }, output: texts.join("\n") };
21239
+ }
21240
+ function sameFolder(a, b) {
21241
+ const normal = (path) => path.replace(/\/+$/, "").replace(/^\/private(?=\/)/, "");
21242
+ return normal(a) === normal(b);
21243
+ }
21244
+
21245
+ // src/providers/cli/kiro.ts
21246
+ var execFileAsync = promisify(execFile3);
20932
21247
  var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
20933
21248
  function kiroLaunch(args) {
20934
- return resolveExecutable("kiro-cli", args, providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
21249
+ return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args });
20935
21250
  }
20936
21251
  var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
20937
21252
  function parseKiroSessions(stdout) {
@@ -20951,13 +21266,13 @@ function describeListSessionsError(error62, timeoutMs) {
20951
21266
  return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
20952
21267
  }
20953
21268
  async function listKiroSessions(workdir, options = {}) {
20954
- const timeoutMs = options.timeoutMs ?? KIRO_LIST_SESSIONS_TIMEOUT_MS;
21269
+ const timeoutMs = options.timeoutMs ?? (Number(process.env.TOC_OCRA_KIRO_LIST_TIMEOUT_MS) || KIRO_LIST_SESSIONS_TIMEOUT_MS);
20955
21270
  const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20956
21271
  let lastError;
20957
21272
  for (let attempt = 0; attempt < 2; attempt++) {
20958
21273
  if (attempt) await new Promise((resolve7) => setTimeout(resolve7, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
20959
21274
  try {
20960
- const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
21275
+ const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
20961
21276
  return parseKiroSessions(stdout);
20962
21277
  } catch (error62) {
20963
21278
  lastError = error62;
@@ -20983,12 +21298,34 @@ function kiroToolRows(text) {
20983
21298
  return [runLog.tool("tool_call")];
20984
21299
  }
20985
21300
  function isKiroNoise(text) {
20986
- return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text);
21301
+ return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text) || /^Warning: Kiro CLI is running as\b/i.test(text) || /^Hide this warning: kiro-cli settings\b/i.test(text);
20987
21302
  }
20988
- function kiroRunParser() {
21303
+ function kiroRunParser(context) {
20989
21304
  let pending = "";
20990
21305
  let started = false;
20991
21306
  let segment = [];
21307
+ const log = context ? new KiroSessionLog({ sessionId: context.sessionId, workdir: context.workdir, startedAt: context.startedAt }) : void 0;
21308
+ const ready = log?.begin().catch(() => void 0);
21309
+ let queue = Promise.resolve();
21310
+ const openSteps = [];
21311
+ let lastHeader;
21312
+ const out = (parsed) => {
21313
+ if (!context) return typeof parsed === "function" ? { display: [] } : parsed;
21314
+ queue = queue.then(async () => {
21315
+ const value = typeof parsed === "function" ? await parsed().catch(() => ({ display: [] })) : parsed;
21316
+ if (value.display.length && typeof parsed !== "function") lastHeader = void 0;
21317
+ context.emit(value);
21318
+ });
21319
+ return { display: [] };
21320
+ };
21321
+ const finishShell = async (step, status) => {
21322
+ const found = await step.shell.lookup;
21323
+ const result = found ? await log.result(found.id, 1e3) : void 0;
21324
+ const header = step.shell.headerShown && lastHeader === step ? [] : [runLog.command(found?.command ?? step.shell.shown)];
21325
+ lastHeader = void 0;
21326
+ if (!result) return { display: [...header, ...status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : []] };
21327
+ return { display: [...header, ...runLog.commandOutput(result.output), runLog.commandExit(result.exitCode ?? (status === "failed" ? 1 : 0))] };
21328
+ };
20992
21329
  const replyRows = (lines) => {
20993
21330
  const display = [];
20994
21331
  for (const raw of lines) {
@@ -21016,18 +21353,58 @@ function kiroRunParser() {
21016
21353
  stdout(chunk) {
21017
21354
  const lines = (pending + chunk).split(/\r?\n/);
21018
21355
  pending = lines.pop() ?? "";
21019
- return replyRows(lines);
21356
+ return out(replyRows(lines));
21020
21357
  },
21021
21358
  stderr(raw) {
21022
21359
  const text = raw.replace(ANSI, "").trim();
21023
21360
  if (!text || isKiroNoise(text)) return { display: [] };
21024
- const rows = kiroToolRows(text) ?? [runLog.error(text)];
21025
21361
  const closed = closeSegment();
21026
- return { ...closed, display: [...closed.display, ...rows] };
21362
+ const status = /^\[tool\]\s*status:\s*(\w+)/i.exec(text)?.[1]?.toLowerCase();
21363
+ if (!log) {
21364
+ const rows2 = kiroToolRows(text) ?? [runLog.error(text)];
21365
+ return out({ ...closed, display: [...closed.display, ...rows2] });
21366
+ }
21367
+ out(closed);
21368
+ const running = /^\[tool\]\s*Running:\s*(.+)$/.exec(text)?.[1]?.trim();
21369
+ if (running && !running.startsWith("@")) {
21370
+ const step = { shell: { shown: running, lookup: (async () => {
21371
+ await ready;
21372
+ return log.step(running);
21373
+ })(), headerShown: !openSteps.some((item) => item.shell) } };
21374
+ openSteps.push(step);
21375
+ if (!step.shell.headerShown) return { display: [] };
21376
+ return out(async () => {
21377
+ const found = await step.shell.lookup;
21378
+ lastHeader = step;
21379
+ return { display: [runLog.command(found?.command ?? running)] };
21380
+ });
21381
+ }
21382
+ if (status) {
21383
+ return out(async () => {
21384
+ const shells = openSteps.filter((item) => item.shell);
21385
+ const ids = (await Promise.all(shells.map((item) => item.shell.lookup))).map((found) => found?.id ?? "");
21386
+ const others = openSteps.some((item) => !item.shell);
21387
+ const id = shells.length ? await log.firstFinished(ids.filter(Boolean), others ? 1200 : 3e3) : void 0;
21388
+ const step = id ? shells[ids.indexOf(id)] : openSteps.find((item) => !item.shell) ?? openSteps[0];
21389
+ if (step) openSteps.splice(openSteps.indexOf(step), 1);
21390
+ if (step?.shell) return finishShell(step, status);
21391
+ lastHeader = void 0;
21392
+ return { display: status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [] };
21393
+ });
21394
+ }
21395
+ if (/^\[tool\]/.test(text)) openSteps.push({});
21396
+ const rows = kiroToolRows(text) ?? [runLog.error(text)];
21397
+ return out({ display: rows });
21027
21398
  },
21028
- end: closeSegment
21399
+ end: async () => {
21400
+ const rest = out(closeSegment());
21401
+ if (!context) return rest;
21402
+ await queue;
21403
+ return { display: [] };
21404
+ }
21029
21405
  };
21030
21406
  }
21407
+ var KIRO_IMAGE_LIMIT = "\u56FE\u7247\u8D85\u9650\uFF1A\u8FD9\u4E2A\u4F1A\u8BDD\u91CC\u7D2F\u8BA1\u7684\u56FE\u7247\u5DF2\u8D85\u8FC7\u6A21\u578B\u5355\u6B21\u5BF9\u8BDD\u7684\u4E0A\u9650\uFF08100 \u5F20\uFF09\uFF0C\u5728\u8FD9\u4E2A\u4F1A\u8BDD\u91CC\u7EE7\u7EED\u67E5\u770B\u56FE\u7247\u90FD\u4F1A\u5931\u8D25";
21031
21408
  var kiroProvider = {
21032
21409
  id: "kiro",
21033
21410
  buildLaunch(request) {
@@ -21038,23 +21415,25 @@ var kiroProvider = {
21038
21415
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
21039
21416
  if (request.sessionId && !request.sessionId.startsWith("sess_")) args.push("--resume-id", request.sessionId);
21040
21417
  args.push("--", request.prompt);
21041
- return kiroLaunch(args);
21418
+ return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args, prompt: request.prompt, promptStdin: "omit" });
21042
21419
  },
21043
21420
  listSessions: (workdir) => listKiroSessions(workdir),
21044
21421
  isMissingSession: (stderr) => isKiroMissingSession(stderr),
21045
21422
  inspectExit(context) {
21046
21423
  const businessError = kiroStderrError(context.stderr);
21047
- return businessError ? { turnError: businessError } : {};
21424
+ if (!businessError) return {};
21425
+ return businessError === KIRO_IMAGE_LIMIT ? { turnError: businessError, display: [runLog.error(businessError)] } : { turnError: businessError };
21048
21426
  },
21049
21427
  /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
21050
21428
  parseLine(line) {
21051
21429
  return kiroRunParser().stdout(`${line}
21052
21430
  `);
21053
21431
  },
21054
- createRunParser: () => kiroRunParser()
21432
+ createRunParser: (context) => kiroRunParser(context)
21055
21433
  };
21056
21434
  function kiroStderrError(stderrLines) {
21057
21435
  const text = stderrLines.join("\n");
21436
+ if (/too many inline media segments/i.test(text)) return KIRO_IMAGE_LIMIT;
21058
21437
  if (/Monthly request limit reached|request limit reached/i.test(text)) {
21059
21438
  return "Kiro \u672C\u6708\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u5347\u7EA7\u5957\u9910\u6216\u7B49\u5F85\u989D\u5EA6\u91CD\u7F6E\u540E\u518D\u8BD5";
21060
21439
  }
@@ -21077,7 +21456,7 @@ var opencodeProvider = {
21077
21456
  if (request.model) args.push("--model", request.model);
21078
21457
  if (request.sessionId) args.push("--session", request.sessionId);
21079
21458
  args.push(request.prompt);
21080
- return resolveExecutable("opencode", args, providerEnvironment(), process.env.TOC_OCRA_OPENCODE_PATH);
21459
+ return launchCli({ command: "opencode", overrideEnv: "TOC_OCRA_OPENCODE_PATH", args });
21081
21460
  },
21082
21461
  parseLine(line) {
21083
21462
  const event = tryJson(line);
@@ -21146,7 +21525,8 @@ function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COM
21146
21525
  function probeVersion(path, args) {
21147
21526
  if (args.length === 0) return Promise.resolve({});
21148
21527
  return new Promise((resolve7) => {
21149
- const child = spawn2(path, [...args], { stdio: ["ignore", "pipe", "pipe"], shell: false });
21528
+ const launch = directLaunch2(path, args);
21529
+ const child = spawn3(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
21150
21530
  let stdout = "";
21151
21531
  let stderr = "";
21152
21532
  let settled = false;
@@ -21227,16 +21607,24 @@ var cliDetection = new CliDetectionService();
21227
21607
 
21228
21608
  // src/runtime/agent-runtime.ts
21229
21609
  import { randomUUID as randomUUID3 } from "node:crypto";
21230
- import { join as join11 } from "node:path";
21610
+ import { join as join14 } from "node:path";
21611
+
21612
+ // src/exec/script-runner.ts
21613
+ import { spawn as spawn4 } from "node:child_process";
21614
+
21615
+ // src/runs/process-tree.ts
21616
+ var KILL_GRACE_MS = 3e3;
21617
+ async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
21618
+ if (!Number.isInteger(rootPid) || rootPid <= 1) return;
21619
+ await currentPlatform.killProcessTree(rootPid, graceMs);
21620
+ }
21231
21621
 
21232
21622
  // src/exec/script-runner.ts
21233
- import { spawn as spawn3 } from "node:child_process";
21234
21623
  var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
21235
21624
  function executeScript(command, workdir, timeoutSeconds) {
21236
21625
  return new Promise((resolveExecution) => {
21237
- const windows = process.platform === "win32";
21238
- const executable = windows ? process.env.ComSpec ?? "cmd.exe" : "/bin/sh";
21239
- const args = windows ? ["/d", "/s", "/c", command] : ["-lc", command];
21626
+ const ownGroup = currentPlatform.runsInOwnProcessGroup;
21627
+ const { executable, args } = currentPlatform.scriptShell(command);
21240
21628
  const startedAt = Date.now();
21241
21629
  const stdout = [];
21242
21630
  const stderr = [];
@@ -21262,11 +21650,12 @@ function executeScript(command, workdir, timeoutSeconds) {
21262
21650
  };
21263
21651
  let child;
21264
21652
  try {
21265
- child = spawn3(executable, args, {
21653
+ child = spawn4(executable, args, {
21266
21654
  cwd: workdir,
21267
21655
  env: process.env,
21268
- detached: !windows,
21656
+ detached: ownGroup,
21269
21657
  shell: false,
21658
+ windowsHide: true,
21270
21659
  stdio: ["ignore", "pipe", "pipe"]
21271
21660
  });
21272
21661
  } catch (error62) {
@@ -21283,7 +21672,8 @@ function executeScript(command, workdir, timeoutSeconds) {
21283
21672
  const kill = () => {
21284
21673
  if (child.exitCode !== null || child.killed) return;
21285
21674
  try {
21286
- if (!windows && child.pid) process.kill(-child.pid, "SIGKILL");
21675
+ if (ownGroup && child.pid) process.kill(-child.pid, "SIGKILL");
21676
+ else if (child.pid) void killProcessTree(child.pid, 0);
21287
21677
  else child.kill("SIGKILL");
21288
21678
  } catch {
21289
21679
  try {
@@ -21632,19 +22022,19 @@ function resolveChatProvider(type, request, attachments) {
21632
22022
 
21633
22023
  // src/providers/model-catalog-collector.ts
21634
22024
  import { createHash } from "node:crypto";
21635
- import { stat } from "node:fs/promises";
22025
+ import { stat as stat2 } from "node:fs/promises";
21636
22026
 
21637
22027
  // src/providers/model-catalog.ts
21638
- import { spawn as spawn5 } from "node:child_process";
21639
- import { readFile as readFile3 } from "node:fs/promises";
21640
- import { homedir as homedir5 } from "node:os";
21641
- import { isAbsolute, join as join6, resolve as resolve2 } from "node:path";
22028
+ import { spawn as spawn6 } from "node:child_process";
22029
+ import { readFile as readFile4 } from "node:fs/promises";
22030
+ import { homedir as homedir6 } from "node:os";
22031
+ import { isAbsolute, join as join9, resolve as resolve2 } from "node:path";
21642
22032
 
21643
22033
  // src/providers/kiro-models.ts
21644
- import { spawn as spawn4 } from "node:child_process";
22034
+ import { spawn as spawn5 } from "node:child_process";
21645
22035
  import { createInterface } from "node:readline";
21646
22036
  async function readKiroNativeModels(launch, cwd, options = {}) {
21647
- const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, stdio: ["pipe", "pipe", "pipe"] });
22037
+ const child = spawn5(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
21648
22038
  const lines = createInterface({ input: child.stdout });
21649
22039
  let nextId = 0;
21650
22040
  let failure2;
@@ -21716,7 +22106,7 @@ async function readKiroNativeModels(launch, cwd, options = {}) {
21716
22106
  clearTimeout(timer);
21717
22107
  lines.close();
21718
22108
  child.stdin.end();
21719
- child.kill("SIGTERM");
22109
+ currentPlatform.stopHelper(child);
21720
22110
  const killTimer = setTimeout(() => {
21721
22111
  if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
21722
22112
  }, 1e3);
@@ -21760,15 +22150,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
21760
22150
  if (defaultModel) catalog.default_model = defaultModel;
21761
22151
  return catalog;
21762
22152
  }
21763
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir5(), ".claude");
21764
- var codexHome = () => process.env.CODEX_HOME?.trim() || join6(homedir5(), ".codex");
21765
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join6(homedir5(), ".gemini");
21766
- var grokHome = () => process.env.GROK_HOME?.trim() || join6(homedir5(), ".grok");
21767
- var opencodeHome = () => join6(process.env.XDG_CONFIG_HOME?.trim() || join6(homedir5(), ".config"), "opencode");
21768
- var kiroHome = () => join6(homedir5(), ".kiro");
22153
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir6(), ".claude");
22154
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join9(homedir6(), ".codex");
22155
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join9(homedir6(), ".gemini");
22156
+ var grokHome = () => process.env.GROK_HOME?.trim() || join9(homedir6(), ".grok");
22157
+ var opencodeHome = () => join9(process.env.XDG_CONFIG_HOME?.trim() || join9(homedir6(), ".config"), "opencode");
22158
+ var kiroHome = () => join9(homedir6(), ".kiro");
21769
22159
  async function readClaudeModelCatalog() {
21770
22160
  const home = claudeHome();
21771
- const content = await readFile3(join6(home, "settings.json"), "utf8").catch(() => "");
22161
+ const content = await readFile4(join9(home, "settings.json"), "utf8").catch(() => "");
21772
22162
  let settings = {};
21773
22163
  if (content) {
21774
22164
  try {
@@ -21824,16 +22214,16 @@ async function readCodexModels(codexHome2, config2) {
21824
22214
  const configuredCatalog = configValue(config2, "model_catalog_json");
21825
22215
  if (configuredCatalog) {
21826
22216
  const catalogPath = isAbsolute(configuredCatalog) ? configuredCatalog : resolve2(codexHome2, configuredCatalog);
21827
- const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
22217
+ const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
21828
22218
  if (configuredModels?.length) return configuredModels;
21829
22219
  }
21830
22220
  return parseCodexModels(
21831
- await readFile3(join6(codexHome2, "models_cache.json"), "utf8").catch(() => "")
22221
+ await readFile4(join9(codexHome2, "models_cache.json"), "utf8").catch(() => "")
21832
22222
  ) ?? [];
21833
22223
  }
21834
22224
  async function readCodexModelCatalog() {
21835
22225
  const home = codexHome();
21836
- const config2 = await readFile3(join6(home, "config.toml"), "utf8").catch(() => "");
22226
+ const config2 = await readFile4(join9(home, "config.toml"), "utf8").catch(() => "");
21837
22227
  const models = await readCodexModels(home, config2);
21838
22228
  const defaultModel = configValue(config2, "model");
21839
22229
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -21879,7 +22269,8 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
21879
22269
  var MODEL_LIST_TIMEOUT_MS = 2e4;
21880
22270
  function runModelListCommand(executable, args, label, environment) {
21881
22271
  return new Promise((resolve7, reject) => {
21882
- const child = spawn5(executable, [...args], { shell: false, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
22272
+ const launch = directLaunch2(executable, args);
22273
+ const child = spawn6(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
21883
22274
  let stdout = "";
21884
22275
  let stderr = "";
21885
22276
  const timer = setTimeout(() => {
@@ -21923,8 +22314,8 @@ async function readKiroModelCatalog() {
21923
22314
  };
21924
22315
  const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
21925
22316
  const [payload, content] = await Promise.all([
21926
- readKiroNativeModels(launch, homedir5(), { catalog: base }),
21927
- readFile3(join6(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
22317
+ readKiroNativeModels(launch, homedir6(), { catalog: base }),
22318
+ readFile4(join9(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21928
22319
  ]);
21929
22320
  let settings;
21930
22321
  try {
@@ -21981,7 +22372,7 @@ function geminiModelsUrl(baseUrl) {
21981
22372
  }
21982
22373
  async function readGeminiModelCatalog() {
21983
22374
  const fileEnvironment = parseEnvFile(
21984
- await readFile3(join6(geminiHome(), ".env"), "utf8").catch(() => "")
22375
+ await readFile4(join9(geminiHome(), ".env"), "utf8").catch(() => "")
21985
22376
  );
21986
22377
  const environment = { ...fileEnvironment, ...process.env };
21987
22378
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -22026,7 +22417,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
22026
22417
  return catalog;
22027
22418
  }
22028
22419
  async function readGrokModelCatalog() {
22029
- const config2 = await readFile3(join6(grokHome(), "config.toml"), "utf8").catch(() => "");
22420
+ const config2 = await readFile4(join9(grokHome(), "config.toml"), "utf8").catch(() => "");
22030
22421
  const output2 = await runModelListCommand(resolveCliCommand("grok"), ["models"], "grok");
22031
22422
  const catalog = parseGrokModelCatalog(output2, config2);
22032
22423
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22045,7 +22436,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
22045
22436
  return catalog;
22046
22437
  }
22047
22438
  async function readOpencodeModelCatalog() {
22048
- const config2 = await readFile3(join6(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join6(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22439
+ const config2 = await readFile4(join9(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join9(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22049
22440
  const output2 = await runModelListCommand(resolveCliCommand("opencode"), ["models"], "opencode");
22050
22441
  const catalog = parseOpencodeModelCatalog(output2, config2);
22051
22442
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22053,22 +22444,22 @@ async function readOpencodeModelCatalog() {
22053
22444
  }
22054
22445
  var TEN_MINUTES = 10 * 60 * 1e3;
22055
22446
  var MODEL_SOURCES = {
22056
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join6(claudeHome(), "settings.json")] },
22447
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join9(claudeHome(), "settings.json")] },
22057
22448
  codex: {
22058
22449
  read: readCodexModelCatalog,
22059
22450
  watchFiles: () => {
22060
22451
  const home = codexHome();
22061
- return [join6(home, "config.toml"), join6(home, "models_cache.json")];
22452
+ return [join9(home, "config.toml"), join9(home, "models_cache.json")];
22062
22453
  },
22063
22454
  // model_catalog_json may point anywhere; a periodic re-read covers it.
22064
22455
  refreshEveryMs: TEN_MINUTES
22065
22456
  },
22066
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join6(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22067
- grok: { read: readGrokModelCatalog, watchFiles: () => [join6(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22068
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join6(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22457
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join9(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22458
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join9(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22459
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join9(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22069
22460
  opencode: {
22070
22461
  read: readOpencodeModelCatalog,
22071
- watchFiles: () => [join6(opencodeHome(), "opencode.json"), join6(opencodeHome(), "opencode.jsonc")],
22462
+ watchFiles: () => [join9(opencodeHome(), "opencode.json"), join9(opencodeHome(), "opencode.jsonc")],
22072
22463
  refreshEveryMs: TEN_MINUTES
22073
22464
  }
22074
22465
  };
@@ -22076,7 +22467,7 @@ var MODEL_SOURCES = {
22076
22467
  // src/providers/model-catalog-collector.ts
22077
22468
  async function fileStamp(path) {
22078
22469
  try {
22079
- const info = await stat(path);
22470
+ const info = await stat2(path);
22080
22471
  return `${path}:${info.mtimeMs}:${info.size}`;
22081
22472
  } catch {
22082
22473
  return `${path}:-`;
@@ -22126,11 +22517,11 @@ var ModelCatalogCollector = class {
22126
22517
  };
22127
22518
 
22128
22519
  // src/providers/codex-quota.ts
22129
- import { spawn as spawn6 } from "node:child_process";
22520
+ import { spawn as spawn7 } from "node:child_process";
22130
22521
  import { createInterface as createInterface2 } from "node:readline";
22131
22522
  async function readCodexQuotaWindows() {
22132
22523
  const launch = resolveExecutable("codex", ["app-server", "--stdio"], providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
22133
- const child = spawn6(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"] });
22524
+ const child = spawn7(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
22134
22525
  let nextId = 0;
22135
22526
  const pending = /* @__PURE__ */ new Map();
22136
22527
  const lines = createInterface2({ input: child.stdout });
@@ -22218,15 +22609,15 @@ async function readCodexQuotaWindows() {
22218
22609
  for (const waiter of pending.values()) waiter.reject(new Error("Codex app-server \u5DF2\u5173\u95ED"));
22219
22610
  pending.clear();
22220
22611
  lines.close();
22221
- child.kill("SIGTERM");
22612
+ currentPlatform.stopHelper(child);
22222
22613
  }
22223
22614
  }
22224
22615
 
22225
22616
  // src/providers/kiro-quota.ts
22226
- import { execFile as execFile2 } from "node:child_process";
22617
+ import { execFile as execFile4 } from "node:child_process";
22227
22618
  import { tmpdir } from "node:os";
22228
22619
  import { promisify as promisify2, stripVTControlCharacters } from "node:util";
22229
- var execFileAsync2 = promisify2(execFile2);
22620
+ var execFileAsync2 = promisify2(execFile4);
22230
22621
  var amount = (value) => Number(value.replace(/,/g, ""));
22231
22622
  var rounded = (value) => Math.round(value * 100) / 100;
22232
22623
  function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
@@ -22311,16 +22702,16 @@ async function readCLIQuotaReport(agentType) {
22311
22702
  }
22312
22703
 
22313
22704
  // src/providers/tb-switch-control.ts
22314
- import { readFile as readFile4 } from "node:fs/promises";
22315
- import { homedir as homedir6 } from "node:os";
22316
- import { join as join7 } from "node:path";
22705
+ import { readFile as readFile5 } from "node:fs/promises";
22706
+ import { homedir as homedir7 } from "node:os";
22707
+ import { join as join10 } from "node:path";
22317
22708
  function dataDir() {
22318
- return process.env.TB_SWITCH_HOME?.trim() || join7(homedir6(), ".tb-switch");
22709
+ return process.env.TB_SWITCH_HOME?.trim() || join10(homedir7(), ".tb-switch");
22319
22710
  }
22320
22711
  async function readLocalService() {
22321
22712
  let discovery;
22322
22713
  try {
22323
- discovery = JSON.parse(await readFile4(join7(dataDir(), "api.json"), "utf8"));
22714
+ discovery = JSON.parse(await readFile5(join10(dataDir(), "api.json"), "utf8"));
22324
22715
  } catch {
22325
22716
  throw new Error("\u8FD9\u53F0\u8BBE\u5907\u4E0A\u7684 TB Switch \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u8BF7\u6253\u5F00\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
22326
22717
  }
@@ -22336,7 +22727,7 @@ async function readLocalService() {
22336
22727
  }
22337
22728
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
22338
22729
  try {
22339
- token = (await readFile4(join7(dataDir(), "api-token"), "utf8")).trim();
22730
+ token = (await readFile5(join10(dataDir(), "api-token"), "utf8")).trim();
22340
22731
  } catch {
22341
22732
  }
22342
22733
  if (!token) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 TB Switch \u672C\u673A\u670D\u52A1\u51ED\u636E\uFF0C\u8BF7\u91CD\u542F\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
@@ -22426,76 +22817,8 @@ async function controlTbSwitch(payload) {
22426
22817
  }
22427
22818
 
22428
22819
  // src/runs/orphan-registry.ts
22429
- import { execFile as execFile4 } from "node:child_process";
22430
- import { mkdir as mkdir3, readFile as readFile5, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22820
+ import { mkdir as mkdir3, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22431
22821
  import { basename, dirname as dirname5 } from "node:path";
22432
-
22433
- // src/runs/process-tree.ts
22434
- import { execFile as execFile3, spawn as spawn7 } from "node:child_process";
22435
- var KILL_GRACE_MS = 3e3;
22436
- function readProcessTable() {
22437
- return new Promise((resolve7) => {
22438
- execFile3("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
22439
- if (error62) return resolve7([]);
22440
- resolve7(stdout.split("\n").flatMap((line) => {
22441
- const [pid, ppid] = line.trim().split(/\s+/).map(Number);
22442
- return pid && ppid !== void 0 && Number.isFinite(ppid) ? [{ pid, ppid }] : [];
22443
- }));
22444
- });
22445
- });
22446
- }
22447
- async function listDescendants(rootPid) {
22448
- const rows = await readProcessTable();
22449
- const children = /* @__PURE__ */ new Map();
22450
- for (const row of rows) children.set(row.ppid, [...children.get(row.ppid) ?? [], row.pid]);
22451
- const out = [];
22452
- const queue = [...children.get(rootPid) ?? []];
22453
- while (queue.length > 0) {
22454
- const pid = queue.shift();
22455
- if (out.includes(pid)) continue;
22456
- out.push(pid);
22457
- queue.push(...children.get(pid) ?? []);
22458
- }
22459
- return out;
22460
- }
22461
- function signal(pid, sig) {
22462
- try {
22463
- process.kill(pid, sig);
22464
- } catch {
22465
- }
22466
- }
22467
- function alive(pid) {
22468
- try {
22469
- process.kill(pid, 0);
22470
- return true;
22471
- } catch {
22472
- return false;
22473
- }
22474
- }
22475
- var sleep = (ms) => new Promise((resolve7) => setTimeout(resolve7, ms));
22476
- async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
22477
- if (!Number.isInteger(rootPid) || rootPid <= 1) return;
22478
- if (process.platform === "win32") {
22479
- await new Promise((resolve7) => {
22480
- const child = spawn7("taskkill", ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
22481
- child.once("error", () => resolve7());
22482
- child.once("close", () => resolve7());
22483
- });
22484
- return;
22485
- }
22486
- const descendants = await listDescendants(rootPid);
22487
- signal(-rootPid, "SIGTERM");
22488
- signal(rootPid, "SIGTERM");
22489
- for (const pid of descendants) signal(pid, "SIGTERM");
22490
- const members2 = [rootPid, ...descendants];
22491
- const deadline = Date.now() + graceMs;
22492
- while (Date.now() < deadline && members2.some(alive)) await sleep(100);
22493
- const late = alive(rootPid) ? await listDescendants(rootPid) : [];
22494
- signal(-rootPid, "SIGKILL");
22495
- for (const pid of [...members2, ...late]) if (alive(pid)) signal(pid, "SIGKILL");
22496
- }
22497
-
22498
- // src/runs/orphan-registry.ts
22499
22822
  var OrphanRegistry = class {
22500
22823
  constructor(file2) {
22501
22824
  this.file = file2;
@@ -22523,7 +22846,7 @@ var OrphanRegistry = class {
22523
22846
  async reapPrevious() {
22524
22847
  let previous = [];
22525
22848
  try {
22526
- previous = JSON.parse(await readFile5(this.file, "utf8"));
22849
+ previous = JSON.parse(await readFile6(this.file, "utf8"));
22527
22850
  } catch {
22528
22851
  return [];
22529
22852
  }
@@ -22543,18 +22866,13 @@ var OrphanRegistry = class {
22543
22866
  }
22544
22867
  };
22545
22868
  function commandOf(pid) {
22546
- if (process.platform === "win32") return Promise.resolve(void 0);
22547
- return new Promise((resolve7) => {
22548
- execFile4("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
22549
- resolve7(error62 ? void 0 : stdout.trim() || void 0);
22550
- });
22551
- });
22869
+ return currentPlatform.processCommandLine(pid);
22552
22870
  }
22553
22871
 
22554
22872
  // src/runs/run-supervisor.ts
22555
22873
  import { spawn as spawn8 } from "node:child_process";
22556
- import { mkdir as mkdir5, realpath as realpath2, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
22557
- import { basename as basename3, isAbsolute as isAbsolute3, join as join9, relative as relative2, resolve as resolve3 } from "node:path";
22874
+ import { mkdir as mkdir5, realpath as realpath2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
22875
+ import { basename as basename3, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3 } from "node:path";
22558
22876
  import { createInterface as createInterface3 } from "node:readline";
22559
22877
 
22560
22878
  // src/session/terminal-line-sanitizer.ts
@@ -22680,8 +22998,8 @@ function clipToCharacterBudget(rows, budget) {
22680
22998
  // src/runs/task-attachments.ts
22681
22999
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
22682
23000
  import { constants as constants2 } from "node:fs";
22683
- import { lstat, mkdir as mkdir4, open as open2, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22684
- import { basename as basename2, isAbsolute as isAbsolute2, join as join8, relative } from "node:path";
23001
+ import { lstat, mkdir as mkdir4, open as open3, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
23002
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join11, relative } from "node:path";
22685
23003
  function within(root, path) {
22686
23004
  const segment = relative(root, path);
22687
23005
  return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
@@ -22689,7 +23007,7 @@ function within(root, path) {
22689
23007
  async function attachmentDirectory(workdir, messageId) {
22690
23008
  let directory = workdir;
22691
23009
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
22692
- directory = join8(directory, segment);
23010
+ directory = join11(directory, segment);
22693
23011
  await mkdir4(directory, { mode: 448 }).catch((error62) => {
22694
23012
  if (error62.code !== "EEXIST") throw error62;
22695
23013
  });
@@ -22697,7 +23015,7 @@ async function attachmentDirectory(workdir, messageId) {
22697
23015
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
22698
23016
  throw new Error("\u9644\u4EF6\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E CLI \u5DE5\u4F5C\u76EE\u5F55\u5185\uFF0C\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5");
22699
23017
  }
22700
- if (segment === ".echo") await writeFile4(join8(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
23018
+ if (segment === ".echo") await writeFile4(join11(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
22701
23019
  if (error62.code !== "EEXIST") throw error62;
22702
23020
  });
22703
23021
  }
@@ -22706,7 +23024,7 @@ async function attachmentDirectory(workdir, messageId) {
22706
23024
  async function matches(path, size, sha256, signal2) {
22707
23025
  const metadata = await lstat(path).catch(() => void 0);
22708
23026
  if (!metadata?.isFile() || metadata.isSymbolicLink() || metadata.size !== size) return false;
22709
- const file2 = await open2(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
23027
+ const file2 = await open3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
22710
23028
  try {
22711
23029
  const hash2 = createHash2("sha256");
22712
23030
  let read = 0;
@@ -22734,9 +23052,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
22734
23052
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
22735
23053
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
22736
23054
  const name = characters.join("") || "attachment";
22737
- const path = join8(directory, `${file2.file_id}-${name}`);
23055
+ const path = join11(directory, `${file2.file_id}-${name}`);
22738
23056
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
22739
- const temporary = join8(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
23057
+ const temporary = join11(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
22740
23058
  try {
22741
23059
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
22742
23060
  signal2.throwIfAborted();
@@ -22761,6 +23079,7 @@ ${paths.join("\n")}`;
22761
23079
 
22762
23080
  // src/runs/run-supervisor.ts
22763
23081
  var COMPLETION_EXIT_GRACE_MS = 15e3;
23082
+ var EXIT_OUTPUT_GRACE_MS = 2e3;
22764
23083
  var RECENT_RUN_TTL_MS = 10 * 6e4;
22765
23084
  var MAX_RECENT_RUNS = 100;
22766
23085
  var MAX_ERROR_ROWS = 40;
@@ -22950,15 +23269,16 @@ var RunSupervisor = class {
22950
23269
  reasoningEffort: payload.reasoning_effort,
22951
23270
  workdir
22952
23271
  });
23272
+ if (!fitsCommandLine(launch)) return refuse(`\u6D88\u606F\u8FC7\u957F\uFF0C\u8D85\u51FA\u672C\u673A\u547D\u4EE4\u884C\u957F\u5EA6\u4E0A\u9650\uFF0C${provider.id} \u6682\u4E0D\u652F\u6301\u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6\u63D0\u793A\u8BCD\uFF0C\u8BF7\u7F29\u77ED\u6D88\u606F\u540E\u91CD\u8BD5`);
22953
23273
  let child;
22954
23274
  try {
22955
23275
  child = spawn8(launch.executable, launch.args, {
22956
23276
  cwd: workdir,
22957
23277
  env: launch.env,
22958
- detached: process.platform !== "win32",
23278
+ detached: currentPlatform.runsInOwnProcessGroup,
22959
23279
  shell: false,
22960
23280
  windowsHide: true,
22961
- stdio: [provider.startInput ? "pipe" : "ignore", "pipe", "pipe"]
23281
+ stdio: [provider.startInput || launch.stdin !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
22962
23282
  });
22963
23283
  } catch (error62) {
22964
23284
  return refuse(`\u65E0\u6CD5\u542F\u52A8 ${provider.id}\uFF1A${errorMessage(error62)}`);
@@ -22977,7 +23297,6 @@ var RunSupervisor = class {
22977
23297
  agentType: provider.id,
22978
23298
  provider,
22979
23299
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
22980
- ...provider.createRunParser ? { stream: provider.createRunParser() } : {},
22981
23300
  ...sessionsBefore ? { sessionsBefore } : {},
22982
23301
  ...unverifiedResume ? { unverifiedResume: payload } : {},
22983
23302
  prompt: payload.prompt,
@@ -23000,6 +23319,16 @@ var RunSupervisor = class {
23000
23319
  lastLine: "",
23001
23320
  lastOutputAt: Date.now()
23002
23321
  };
23322
+ if (provider.createRunParser) {
23323
+ run.stream = provider.createRunParser({
23324
+ workdir,
23325
+ sessionId,
23326
+ startedAt: run.startedAt,
23327
+ emit: (parsed) => {
23328
+ if (this.active.has(run.runId)) this.applyParsed(run, parsed, "");
23329
+ }
23330
+ });
23331
+ }
23003
23332
  this.active.set(run.runId, run);
23004
23333
  this.preparing.delete(run.runId);
23005
23334
  this.unreported.add(run.runId);
@@ -23012,6 +23341,7 @@ var RunSupervisor = class {
23012
23341
  this.logger.info("run-started", { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
23013
23342
  let spawnError = "";
23014
23343
  child.stdin?.on("error", () => void 0);
23344
+ if (launch.stdin !== void 0 && !provider.startInput) child.stdin?.end(launch.stdin, "utf8");
23015
23345
  child.once("error", (error62) => {
23016
23346
  spawnError = error62.message;
23017
23347
  });
@@ -23039,7 +23369,22 @@ var RunSupervisor = class {
23039
23369
  }
23040
23370
  }
23041
23371
  });
23042
- child.once("close", (code, signal3) => void this.onExit(run, code, signal3, spawnError));
23372
+ let exited = false;
23373
+ const finish = (code, signal3) => {
23374
+ if (exited) return;
23375
+ exited = true;
23376
+ void this.onExit(run, code, signal3, spawnError);
23377
+ };
23378
+ child.once("exit", (code, signal3) => {
23379
+ run.timers.push(setTimeout(() => {
23380
+ if (exited) return;
23381
+ this.logger.warn("run-output-held", { runId: run.runId, pid: run.pid });
23382
+ child.stdout?.destroy();
23383
+ child.stderr?.destroy();
23384
+ finish(code, signal3);
23385
+ }, EXIT_OUTPUT_GRACE_MS));
23386
+ });
23387
+ child.once("close", (code, signal3) => finish(code, signal3));
23043
23388
  if (provider.startInput) {
23044
23389
  child.once("spawn", () => {
23045
23390
  try {
@@ -23115,7 +23460,8 @@ var RunSupervisor = class {
23115
23460
  }
23116
23461
  async onExit(run, code, signal2, spawnError) {
23117
23462
  for (const timer of run.timers) clearTimeout(timer);
23118
- if (run.stream) this.applyParsed(run, run.stream.end(), "");
23463
+ run.timers = [];
23464
+ if (run.stream) this.applyParsed(run, await run.stream.end(), "");
23119
23465
  this.active.delete(run.runId);
23120
23466
  this.orphans?.remove(run.runId);
23121
23467
  if (run.eventTimer) clearTimeout(run.eventTimer);
@@ -23251,13 +23597,13 @@ var RunSupervisor = class {
23251
23597
  async prepareChatAttachments(payload) {
23252
23598
  if (!payload.attachments?.length) return [];
23253
23599
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
23254
- const directory = join9(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23600
+ const directory = join12(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23255
23601
  await mkdir5(directory, { recursive: true, mode: 448 });
23256
23602
  const files = [];
23257
23603
  for (const attachment of payload.attachments) {
23258
23604
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
23259
- const path = join9(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23260
- const existing = await stat2(path).catch(() => void 0);
23605
+ const path = join12(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23606
+ const existing = await stat3(path).catch(() => void 0);
23261
23607
  if (!existing?.isFile()) {
23262
23608
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
23263
23609
  await writeFile5(path, data, { mode: 384 });
@@ -23295,10 +23641,15 @@ var RunSupervisor = class {
23295
23641
  if (live) return live;
23296
23642
  return [...this.recent.values()].filter((run) => run.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
23297
23643
  };
23298
- const target = byId(query.runId) ?? byWorkstation(query.workstationId);
23299
- if (!target) {
23300
- return { status: "idle", lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23301
- }
23644
+ const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23645
+ if (query.runId) {
23646
+ const run = byId(query.runId);
23647
+ if (!run) return { ...empty, status: this.preparing.has(query.runId) ? "running" : "idle", run_id: query.runId };
23648
+ const read2 = run.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23649
+ return { ...read2, status: this.active.has(run.runId) ? "running" : "finished", run_id: run.runId };
23650
+ }
23651
+ const target = byWorkstation(query.workstationId);
23652
+ if (!target) return { ...empty, status: "idle" };
23302
23653
  const read = target.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23303
23654
  return { ...read, status: this.active.has(target.runId) ? "running" : "finished", run_id: target.runId };
23304
23655
  }
@@ -23488,17 +23839,17 @@ var GatewayClient = class {
23488
23839
  };
23489
23840
 
23490
23841
  // src/workspace/directory-browser.ts
23491
- import { readdir, realpath as realpath3, stat as stat3 } from "node:fs/promises";
23492
- import { homedir as homedir7 } from "node:os";
23842
+ import { readdir as readdir2, realpath as realpath3, stat as stat4 } from "node:fs/promises";
23843
+ import { homedir as homedir8 } from "node:os";
23493
23844
  import { dirname as dirname6, parse as parse3, resolve as resolve4 } from "node:path";
23494
23845
  var MAX_ENTRIES = 1e3;
23495
23846
  async function listDirectory(requested, allowedRoots) {
23496
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir7()) || homedir7();
23847
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir8()) || homedir8();
23497
23848
  const directory = await realpath3(resolve4(raw)).catch(() => {
23498
23849
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
23499
23850
  });
23500
- if (!(await stat3(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23501
- const entries = await readdir(directory, { withFileTypes: true }).catch((error62) => {
23851
+ if (!(await stat4(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23852
+ const entries = await readdir2(directory, { withFileTypes: true }).catch((error62) => {
23502
23853
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
23503
23854
  });
23504
23855
  const byName = (a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base", numeric: true });
@@ -23511,8 +23862,8 @@ async function listDirectory(requested, allowedRoots) {
23511
23862
  else if (entry.isFile()) files.push(item);
23512
23863
  }
23513
23864
  const parent = dirname6(directory);
23514
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir7() }];
23515
- for (const root of allowedRoots) if (root !== homedir7()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23865
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir8() }];
23866
+ for (const root of allowedRoots) if (root !== homedir8()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23516
23867
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
23517
23868
  return {
23518
23869
  path: directory,
@@ -23526,9 +23877,9 @@ async function listDirectory(requested, allowedRoots) {
23526
23877
 
23527
23878
  // src/workspace/workspace-manager.ts
23528
23879
  import { spawn as spawn9 } from "node:child_process";
23529
- import { chmod as chmod3, mkdir as mkdir6, mkdtemp, opendir, realpath as realpath4, rm as rm3, stat as stat4, writeFile as writeFile6 } from "node:fs/promises";
23530
- import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
23531
- import { isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5 } from "node:path";
23880
+ import { chmod as chmod3, mkdir as mkdir6, mkdtemp, opendir, realpath as realpath4, rm as rm3, stat as stat5, writeFile as writeFile6 } from "node:fs/promises";
23881
+ import { homedir as homedir9, tmpdir as tmpdir2 } from "node:os";
23882
+ import { isAbsolute as isAbsolute4, join as join13, relative as relative3, resolve as resolve5 } from "node:path";
23532
23883
  var MAX_NODES = 2e3;
23533
23884
  var MAX_DIRECTORY_ENTRIES = 12e3;
23534
23885
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -23576,7 +23927,7 @@ var WorkspaceManager = class {
23576
23927
  };
23577
23928
  }
23578
23929
  validateRootPath(value) {
23579
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir8());
23930
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir9());
23580
23931
  const root = resolve5(raw);
23581
23932
  if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
23582
23933
  if (relative3(root, resolve5(root, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -23593,7 +23944,7 @@ var WorkspaceManager = class {
23593
23944
  requestedPaths.add(relativePath);
23594
23945
  const target = this.resolveWithinRoot(rootPath, relativePath);
23595
23946
  try {
23596
- const metadata = await stat4(target).catch(() => void 0);
23947
+ const metadata = await stat5(target).catch(() => void 0);
23597
23948
  if (metadata) {
23598
23949
  if (!metadata.isDirectory()) {
23599
23950
  throw new Error("The existing workspace path is not a directory");
@@ -23651,7 +24002,7 @@ var WorkspaceManager = class {
23651
24002
  let created = false;
23652
24003
  let metadata;
23653
24004
  try {
23654
- metadata = await stat4(target);
24005
+ metadata = await stat5(target);
23655
24006
  } catch {
23656
24007
  }
23657
24008
  if (!metadata) {
@@ -23751,7 +24102,7 @@ var WorkspaceManager = class {
23751
24102
  }
23752
24103
  async scanTree(rootPath, maxDepth, scanRoots) {
23753
24104
  const resolvedRoot = await realpath4(rootPath);
23754
- const rootMetadata = await stat4(resolvedRoot);
24105
+ const rootMetadata = await stat5(resolvedRoot);
23755
24106
  if (!rootMetadata.isDirectory()) throw new Error("The workspace root is not a directory");
23756
24107
  const nodes = [];
23757
24108
  let entriesRead = 0;
@@ -23806,7 +24157,7 @@ var WorkspaceManager = class {
23806
24157
  const target = this.resolveWithinRoot(resolvedRoot, relativePath);
23807
24158
  let metadata;
23808
24159
  try {
23809
- metadata = await stat4(target);
24160
+ metadata = await stat5(target);
23810
24161
  } catch (error62) {
23811
24162
  this.logger.warn("workspace-scan-root-missing", {
23812
24163
  rootPath: target,
@@ -23903,12 +24254,12 @@ var WorkspaceManager = class {
23903
24254
  }
23904
24255
  async createGitAuthEnvironment(auth) {
23905
24256
  if (!auth) return void 0;
23906
- const directory = await mkdtemp(join10(tmpdir2(), "toc-ocra-git-auth-"));
24257
+ const directory = await mkdtemp(join13(tmpdir2(), "toc-ocra-git-auth-"));
23907
24258
  const isWindows = process.platform === "win32";
23908
- const scriptPath = join10(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24259
+ const scriptPath = join13(directory, isWindows ? "askpass.cmd" : "askpass.sh");
23909
24260
  let script;
23910
24261
  if (isWindows) {
23911
- const helperPath = join10(directory, "askpass.cjs");
24262
+ const helperPath = join13(directory, "askpass.cjs");
23912
24263
  await writeFile6(
23913
24264
  helperPath,
23914
24265
  'const prompt = process.argv.slice(2).join(" ");\nprocess.stdout.write(/username/i.test(prompt) ? process.env.ECHO_GIT_USERNAME ?? "" : process.env.ECHO_GIT_PASSWORD ?? "");\n',
@@ -24058,7 +24409,7 @@ var AgentRuntime = class {
24058
24409
  }
24059
24410
  };
24060
24411
  this.workspaces = new WorkspaceManager(config2, this.logger);
24061
- this.orphans = new OrphanRegistry(join11(config2.dataDir, "active-runs.json"));
24412
+ this.orphans = new OrphanRegistry(join14(config2.dataDir, "active-runs.json"));
24062
24413
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
24063
24414
  }
24064
24415
  config;
@@ -24698,7 +25049,7 @@ function errorMessage2(error62) {
24698
25049
  }
24699
25050
 
24700
25051
  // src/runtime/run-service.ts
24701
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
25052
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
24702
25053
  import { dirname as dirname7, resolve as resolve6 } from "node:path";
24703
25054
  import { fileURLToPath } from "node:url";
24704
25055
  var PACKAGE_NAME = "toc-ocra";
@@ -24708,7 +25059,7 @@ function agentPackageRoot() {
24708
25059
  const packagePath = resolve6(directory, "package.json");
24709
25060
  if (existsSync5(packagePath)) {
24710
25061
  try {
24711
- const info = JSON.parse(readFileSync5(packagePath, "utf8"));
25062
+ const info = JSON.parse(readFileSync6(packagePath, "utf8"));
24712
25063
  if (info.name === PACKAGE_NAME && typeof info.version === "string") return directory;
24713
25064
  } catch {
24714
25065
  }
@@ -24720,7 +25071,7 @@ function agentPackageRoot() {
24720
25071
  }
24721
25072
  function agentVersion() {
24722
25073
  const root = agentPackageRoot();
24723
- return root ? JSON.parse(readFileSync5(resolve6(root, "package.json"), "utf8")).version : "unknown";
25074
+ return root ? JSON.parse(readFileSync6(resolve6(root, "package.json"), "utf8")).version : "unknown";
24724
25075
  }
24725
25076
  async function runService(options = {}) {
24726
25077
  const version2 = agentVersion();
@@ -24776,7 +25127,7 @@ function preferSystemNode() {
24776
25127
  const names = process.platform === "win32" ? ["node.exe"] : ["node"];
24777
25128
  for (const directory of (process.env.PATH ?? "").split(delimiter5)) {
24778
25129
  for (const name of names) {
24779
- const candidate = directory && join12(directory, name);
25130
+ const candidate = directory && join15(directory, name);
24780
25131
  if (candidate && existsSync6(candidate)) {
24781
25132
  process.env.TOC_OCRA_NODE_PATH = candidate;
24782
25133
  return;