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
package/dist/cli/cli.mjs CHANGED
@@ -12,7 +12,7 @@ import { createHash as createHash4 } from "node:crypto";
12
12
  import { existsSync as existsSync6, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
13
13
  import { tmpdir as tmpdir3 } from "node:os";
14
14
  import { createRequire } from "node:module";
15
- import { dirname as dirname8, join as join12, resolve as resolve7 } from "node:path";
15
+ import { dirname as dirname8, join as join15, resolve as resolve7 } from "node:path";
16
16
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
17
17
 
18
18
  // src/config.ts
@@ -19986,46 +19986,109 @@ function safeEqual(left, right) {
19986
19986
  }
19987
19987
 
19988
19988
  // src/providers/detection.ts
19989
- import { spawn as spawn2 } from "node:child_process";
19989
+ import { spawn as spawn3 } from "node:child_process";
19990
19990
 
19991
19991
  // src/runtime/cli/hydrate-shell-path.ts
19992
- import { spawn } from "node:child_process";
19993
- import { delimiter as delimiter2 } from "node:path";
19994
- var DELIMITER = "__ORCA_SHELL_PATH__";
19995
- var PROXY_DELIMITER = "__ECHO_SHELL_PROXY__";
19992
+ import { delimiter as delimiter3 } from "node:path";
19993
+
19994
+ // src/platform/common.ts
19995
+ import { join as join3 } from "node:path";
19996
19996
  var PROXY_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"];
19997
- var SPAWN_TIMEOUT_MS = 5e3;
19998
- var ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
19999
- var cached2 = null;
20000
- function pickShell() {
20001
- if (process.platform === "win32") {
20002
- return null;
19997
+ var NODE_SCRIPT = /\.(c|m)?js$/i;
19998
+ function isNodeScript(path) {
19999
+ return NODE_SCRIPT.test(path);
20000
+ }
20001
+ function sharedUserBinDirectoriesHead(home) {
20002
+ return [
20003
+ join3(home, ".volta", "bin"),
20004
+ join3(home, ".asdf", "shims"),
20005
+ join3(home, ".fnm", "aliases", "default", "bin"),
20006
+ // Why: mise (formerly rtx) exposes managed tool binaries via a shims
20007
+ // directory, similar to asdf.
20008
+ join3(home, ".local", "share", "mise", "shims")
20009
+ ];
20010
+ }
20011
+ function sharedUserBinDirectoriesTail(home) {
20012
+ return [join3(home, ".bun", "bin")];
20013
+ }
20014
+ function directLaunch(platform2, path, args, nodePath = process.execPath) {
20015
+ const target = platform2.unwrapLauncher(path) ?? path;
20016
+ if (isNodeScript(target)) return { executable: nodePath, args: [target, ...args] };
20017
+ return { executable: target, args: [...args] };
20018
+ }
20019
+ function commandLineLength(executable, args) {
20020
+ return [executable, ...args].reduce((total, value) => total + value.length + (value.match(/["\\]/g)?.length ?? 0) + 3, 0);
20021
+ }
20022
+
20023
+ // src/platform/posix.ts
20024
+ import { execFile, spawn } from "node:child_process";
20025
+ import { accessSync, constants, statSync } from "node:fs";
20026
+ import { delimiter as delimiter2, join as join4 } from "node:path";
20027
+ function readProcessTable() {
20028
+ return new Promise((resolve8) => {
20029
+ execFile("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
20030
+ if (error62) return resolve8([]);
20031
+ resolve8(stdout.split("\n").flatMap((line) => {
20032
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
20033
+ return pid && ppid !== void 0 && Number.isFinite(ppid) ? [{ pid, ppid }] : [];
20034
+ }));
20035
+ });
20036
+ });
20037
+ }
20038
+ async function listDescendants(rootPid) {
20039
+ const rows = await readProcessTable();
20040
+ const children = /* @__PURE__ */ new Map();
20041
+ for (const row of rows) children.set(row.ppid, [...children.get(row.ppid) ?? [], row.pid]);
20042
+ const out = [];
20043
+ const queue = [...children.get(rootPid) ?? []];
20044
+ while (queue.length > 0) {
20045
+ const pid = queue.shift();
20046
+ if (out.includes(pid)) continue;
20047
+ out.push(pid);
20048
+ queue.push(...children.get(pid) ?? []);
20003
20049
  }
20004
- const shell = process.env.SHELL;
20005
- if (shell && shell.length > 0) {
20006
- return shell;
20050
+ return out;
20051
+ }
20052
+ function signal(pid, sig) {
20053
+ try {
20054
+ process.kill(pid, sig);
20055
+ } catch {
20007
20056
  }
20008
- return process.platform === "darwin" ? "/bin/zsh" : "/bin/bash";
20009
20057
  }
20058
+ function alive(pid) {
20059
+ try {
20060
+ process.kill(pid, 0);
20061
+ return true;
20062
+ } catch {
20063
+ return false;
20064
+ }
20065
+ }
20066
+ var sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
20067
+ async function killPosixTree(rootPid, graceMs) {
20068
+ const descendants = await listDescendants(rootPid);
20069
+ signal(-rootPid, "SIGTERM");
20070
+ signal(rootPid, "SIGTERM");
20071
+ for (const pid of descendants) signal(pid, "SIGTERM");
20072
+ const members2 = [rootPid, ...descendants];
20073
+ const deadline = Date.now() + graceMs;
20074
+ while (Date.now() < deadline && members2.some(alive)) await sleep(100);
20075
+ const late = alive(rootPid) ? await listDescendants(rootPid) : [];
20076
+ signal(-rootPid, "SIGKILL");
20077
+ for (const pid of [...members2, ...late]) if (alive(pid)) signal(pid, "SIGKILL");
20078
+ }
20079
+ var PATH_DELIMITER = "__ORCA_SHELL_PATH__";
20080
+ var PROXY_DELIMITER = "__ECHO_SHELL_PROXY__";
20081
+ var SHELL_TIMEOUT_MS = 5e3;
20082
+ var ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
20010
20083
  function parseCapturedPath(stdout) {
20011
20084
  const cleaned = stdout.replace(ANSI_RE, "");
20012
- const first = cleaned.indexOf(DELIMITER);
20013
- if (first < 0) {
20014
- return [];
20015
- }
20016
- const second = cleaned.indexOf(DELIMITER, first + DELIMITER.length);
20017
- if (second < 0) {
20018
- return [];
20019
- }
20020
- const value = cleaned.slice(first + DELIMITER.length, second).trim();
20021
- if (!value) {
20022
- return [];
20023
- }
20024
- return [
20025
- ...new Set(
20026
- value.split(delimiter2).map((s) => s.trim()).filter(Boolean)
20027
- )
20028
- ];
20085
+ const first = cleaned.indexOf(PATH_DELIMITER);
20086
+ if (first < 0) return [];
20087
+ const second = cleaned.indexOf(PATH_DELIMITER, first + PATH_DELIMITER.length);
20088
+ if (second < 0) return [];
20089
+ const value = cleaned.slice(first + PATH_DELIMITER.length, second).trim();
20090
+ if (!value) return [];
20091
+ return [...new Set(value.split(delimiter2).map((s) => s.trim()).filter(Boolean))];
20029
20092
  }
20030
20093
  function parseCapturedProxy(stdout) {
20031
20094
  const start = stdout.indexOf(PROXY_DELIMITER);
@@ -20034,48 +20097,28 @@ function parseCapturedProxy(stdout) {
20034
20097
  const values = stdout.slice(start + PROXY_DELIMITER.length, end).split("\0");
20035
20098
  return Object.fromEntries(PROXY_KEYS.flatMap((key, index) => values[index] ? [[key, values[index]]] : []));
20036
20099
  }
20037
- function mergeShellProxyEnvironment(hydration, baseline = process.env) {
20038
- const environment = { ...baseline };
20039
- if (!hydration.ok) return environment;
20040
- for (const key of PROXY_KEYS.slice(0, 4)) {
20041
- const upper = key.toUpperCase();
20042
- if (baseline[key] !== void 0 || baseline[upper] !== void 0) continue;
20043
- const value = hydration.proxyEnv?.[key] ?? hydration.proxyEnv?.[upper];
20044
- if (value) environment[key] = value;
20045
- }
20046
- return environment;
20047
- }
20048
- function spawnShellAndReadPath(shell) {
20100
+ function readLoginShell(shell) {
20049
20101
  return new Promise((resolve8) => {
20050
20102
  const proxyValues = PROXY_KEYS.map((key) => `"\${${key}-}"`).join(" ");
20051
- const command = `printf '%s' '${DELIMITER}'; printf '%s' "$PATH"; printf '%s' '${DELIMITER}'; printf '%s' '${PROXY_DELIMITER}'; printf '%s\\0' ${proxyValues}; printf '%s' '${PROXY_DELIMITER}'`;
20103
+ 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}'`;
20052
20104
  let finished = false;
20053
20105
  let stdout = "";
20054
20106
  let timer = null;
20055
20107
  const child = spawn(shell, ["-ilc", command], {
20056
20108
  // Why: inherit current env so the shell sees the same baseline, then let
20057
20109
  // it layer its own rc files on top. Do NOT forward stdio — some shells
20058
- // (oh-my-zsh setups, powerlevel10k) print a lot to stderr on startup,
20059
- // and we don't want that in Orca's console.
20110
+ // (oh-my-zsh setups, powerlevel10k) print a lot to stderr on startup.
20060
20111
  env: process.env,
20061
20112
  stdio: ["ignore", "pipe", "ignore"],
20062
20113
  detached: false
20063
20114
  });
20064
- const cleanup = () => {
20065
- if (timer) {
20066
- clearTimeout(timer);
20067
- timer = null;
20068
- }
20069
- child.stdout.off("data", onStdoutData);
20070
- child.off("error", onError);
20071
- child.off("close", onClose);
20072
- };
20073
20115
  const finish = (result) => {
20074
- if (finished) {
20075
- return;
20076
- }
20116
+ if (finished) return;
20077
20117
  finished = true;
20078
- cleanup();
20118
+ if (timer) clearTimeout(timer);
20119
+ child.stdout.removeAllListeners("data");
20120
+ child.removeAllListeners("error");
20121
+ child.removeAllListeners("close");
20079
20122
  resolve8(result);
20080
20123
  };
20081
20124
  timer = setTimeout(() => {
@@ -20084,44 +20127,229 @@ function spawnShellAndReadPath(shell) {
20084
20127
  } catch {
20085
20128
  }
20086
20129
  finish({ segments: [], ok: false, failureReason: "timeout" });
20087
- }, SPAWN_TIMEOUT_MS);
20088
- const onStdoutData = (chunk) => {
20130
+ }, SHELL_TIMEOUT_MS);
20131
+ child.stdout.on("data", (chunk) => {
20089
20132
  stdout += chunk.toString("utf8");
20090
- };
20091
- const onError = () => {
20092
- finish({ segments: [], ok: false, failureReason: "spawn_error" });
20093
- };
20094
- const onClose = () => {
20133
+ });
20134
+ child.on("error", () => finish({ segments: [], ok: false, failureReason: "spawn_error" }));
20135
+ child.on("close", () => {
20095
20136
  const segments = parseCapturedPath(stdout);
20096
20137
  if (segments.length === 0) {
20097
20138
  finish({ segments: [], ok: false, failureReason: "empty_path" });
20098
20139
  return;
20099
20140
  }
20100
20141
  finish({ segments, proxyEnv: parseCapturedProxy(stdout), ok: true, failureReason: "none" });
20101
- };
20102
- child.stdout.on("data", onStdoutData);
20103
- child.on("error", onError);
20104
- child.on("close", onClose);
20142
+ });
20105
20143
  });
20106
20144
  }
20107
- function hydrateShellPath(options = {}) {
20108
- if (cached2 && !options.force) {
20109
- return cached2;
20145
+ function createPosixPlatform(id) {
20146
+ return {
20147
+ id,
20148
+ executableNames: (command) => [command],
20149
+ isRunnableFile(path) {
20150
+ try {
20151
+ if (!statSync(path).isFile()) return false;
20152
+ accessSync(path, constants.X_OK);
20153
+ return true;
20154
+ } catch {
20155
+ return false;
20156
+ }
20157
+ },
20158
+ userBinDirectories: (home) => [
20159
+ join4(home, ".local", "bin"),
20160
+ // Why: pnpm uses platform-specific global bin directories that differ
20161
+ // from npm's ~/.local/bin.
20162
+ id === "darwin" ? join4(home, "Library", "pnpm") : join4(home, ".local", "share", "pnpm"),
20163
+ join4(home, ".yarn", "bin")
20164
+ ],
20165
+ fallbackBinDirectories: (home) => ["/opt/homebrew/bin", "/usr/local/bin", join4(home, ".local", "bin")],
20166
+ normalizeEnvironment: (env) => ({ ...env }),
20167
+ // Shebang scripts and symlinks start directly.
20168
+ unwrapLauncher: () => void 0,
20169
+ // Linux caps a single argument at 128 KiB (MAX_ARG_STRLEN); macOS caps
20170
+ // the whole command line plus environment at 1 MiB (ARG_MAX).
20171
+ maxCommandLineLength: id === "linux" ? 12e4 : 9e5,
20172
+ runsInOwnProcessGroup: true,
20173
+ killProcessTree: killPosixTree,
20174
+ stopHelper: (child) => {
20175
+ child.kill("SIGTERM");
20176
+ },
20177
+ processCommandLine(pid) {
20178
+ return new Promise((resolve8) => {
20179
+ execFile("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
20180
+ resolve8(error62 ? void 0 : stdout.trim() || void 0);
20181
+ });
20182
+ });
20183
+ },
20184
+ scriptShell: (command) => ({ executable: "/bin/sh", args: ["-lc", command] }),
20185
+ readLoginEnvironment() {
20186
+ const shell = process.env.SHELL || (id === "darwin" ? "/bin/zsh" : "/bin/bash");
20187
+ return readLoginShell(shell);
20188
+ }
20189
+ };
20190
+ }
20191
+
20192
+ // src/platform/win32.ts
20193
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
20194
+ import { readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
20195
+ import { join as join5, win32 } from "node:path";
20196
+ var SYSTEM_ROOT = process.env.SystemRoot || process.env.windir || "C:\\Windows";
20197
+ var POWERSHELL = join5(SYSTEM_ROOT, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
20198
+ var HELPER_TIMEOUT_MS = 5e3;
20199
+ var SHIM_TARGET_RE = /%~?dp0%?\\?([^"%\r\n]+)/gi;
20200
+ var SHIM_TARGET_EXTENSIONS = /\.(c|m)?js$|\.exe$/i;
20201
+ var MAX_SHIM_BYTES = 64 * 1024;
20202
+ function resolveWindowsCommandShim(shimPath) {
20203
+ if (!/\.(cmd|bat)$/i.test(shimPath)) return void 0;
20204
+ let content;
20205
+ try {
20206
+ if (statSync2(shimPath).size > MAX_SHIM_BYTES) return void 0;
20207
+ content = readFileSync3(shimPath, "utf8");
20208
+ } catch {
20209
+ return void 0;
20210
+ }
20211
+ const base = win32.dirname(shimPath);
20212
+ const targets = [...content.matchAll(SHIM_TARGET_RE)].map((match) => match[1].trim()).filter((target) => SHIM_TARGET_EXTENSIONS.test(target) && !/(^|\\)node\.exe$/i.test(target));
20213
+ for (const target of targets.reverse()) {
20214
+ const absolute = win32.isAbsolute(target) ? target : win32.resolve(base, target);
20215
+ try {
20216
+ if (statSync2(absolute).isFile()) return absolute;
20217
+ } catch {
20218
+ }
20110
20219
  }
20111
- const shell = options.shellOverride !== void 0 ? options.shellOverride : pickShell();
20112
- if (!shell) {
20113
- cached2 = Promise.resolve({ segments: [], ok: false, failureReason: "no_shell" });
20114
- return cached2;
20220
+ return void 0;
20221
+ }
20222
+ function taskkillTree(rootPid) {
20223
+ return new Promise((resolve8) => {
20224
+ const child = spawn2(join5(SYSTEM_ROOT, "System32", "taskkill.exe"), ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
20225
+ child.once("error", () => resolve8());
20226
+ child.once("close", () => resolve8());
20227
+ });
20228
+ }
20229
+ function runPowerShell(script) {
20230
+ const prelude = '$ProgressPreference="SilentlyContinue";[Console]::OutputEncoding=[Text.Encoding]::UTF8;';
20231
+ const encoded = Buffer.from(prelude + script, "utf16le").toString("base64");
20232
+ return new Promise((resolve8) => {
20233
+ execFile2(
20234
+ POWERSHELL,
20235
+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
20236
+ { timeout: HELPER_TIMEOUT_MS, windowsHide: true, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 },
20237
+ (error62, stdout) => {
20238
+ if (!error62) return resolve8({ ok: true, stdout });
20239
+ resolve8({ ok: false, reason: error62.killed ? "timeout" : "spawn_error" });
20240
+ }
20241
+ );
20242
+ });
20243
+ }
20244
+ function expandVariables(value) {
20245
+ return value.replace(/%([^%;]+)%/g, (whole, name) => process.env[name] ?? whole);
20246
+ }
20247
+ async function readRegistryEnvironment() {
20248
+ const names = [...new Set(PROXY_KEYS.map((key) => key.toLowerCase()))];
20249
+ const script = [
20250
+ "$r=@{};",
20251
+ "$r.path=@([Environment]::GetEnvironmentVariable('Path','Machine'),[Environment]::GetEnvironmentVariable('Path','User'));",
20252
+ "$r.proxy=@{};",
20253
+ `foreach($k in @(${names.map((name) => `'${name}'`).join(",")})){`,
20254
+ "$v=[Environment]::GetEnvironmentVariable($k,'User');if(-not $v){$v=[Environment]::GetEnvironmentVariable($k,'Machine')};if($v){$r.proxy[$k]=$v}};",
20255
+ "$r|ConvertTo-Json -Compress -Depth 4"
20256
+ ].join("");
20257
+ const result = await runPowerShell(script);
20258
+ if (!result.ok) return { ok: false, segments: [], failureReason: result.reason };
20259
+ let parsed;
20260
+ try {
20261
+ parsed = JSON.parse(result.stdout.trim());
20262
+ } catch {
20263
+ return { ok: false, segments: [], failureReason: "empty_path" };
20264
+ }
20265
+ const raw = (Array.isArray(parsed.path) ? parsed.path : [parsed.path]).filter((value) => typeof value === "string");
20266
+ const segments = [...new Set(raw.flatMap((value) => value.split(";")).map((segment) => expandVariables(segment.trim())).filter(Boolean))];
20267
+ if (segments.length === 0) return { ok: false, segments: [], failureReason: "empty_path" };
20268
+ const proxyEnv = Object.fromEntries(Object.entries(parsed.proxy ?? {}).filter((entry) => typeof entry[1] === "string" && entry[1].length > 0));
20269
+ return { ok: true, segments, proxyEnv, failureReason: "none" };
20270
+ }
20271
+ var win32Platform = {
20272
+ id: "win32",
20273
+ executableNames: (command) => [`${command}.cmd`, `${command}.exe`, `${command}.bat`, command],
20274
+ isRunnableFile(path) {
20275
+ try {
20276
+ return statSync2(path).isFile();
20277
+ } catch {
20278
+ return false;
20279
+ }
20280
+ },
20281
+ userBinDirectories: (home) => [
20282
+ // Why: Anthropic's native Windows installer places claude.exe here, and
20283
+ // GUI-launched processes may not inherit the user's PATH entry for it.
20284
+ join5(home, ".local", "bin"),
20285
+ join5(home, "AppData", "Roaming", "npm"),
20286
+ join5(home, "AppData", "Local", "pnpm"),
20287
+ join5(home, "AppData", "Local", "Yarn", "bin")
20288
+ ],
20289
+ fallbackBinDirectories: (home) => [join5(home, ".local", "bin")],
20290
+ normalizeEnvironment(env) {
20291
+ const copy = { ...env };
20292
+ const keys = Object.keys(copy).filter((key) => key.toUpperCase() === "PATH");
20293
+ const value = keys.map((key) => copy[key]).find((entry) => entry);
20294
+ for (const key of keys) delete copy[key];
20295
+ if (value) copy.PATH = value;
20296
+ return copy;
20297
+ },
20298
+ unwrapLauncher: resolveWindowsCommandShim,
20299
+ // CreateProcess limit is 32 767 UTF-16 units; keep a margin for the
20300
+ // wrapper that relaunches the native binary with the same arguments.
20301
+ maxCommandLineLength: 3e4,
20302
+ runsInOwnProcessGroup: false,
20303
+ killProcessTree: (rootPid) => taskkillTree(rootPid),
20304
+ stopHelper(child) {
20305
+ child.stdin?.end();
20306
+ if (child.pid) void taskkillTree(child.pid);
20307
+ else child.kill();
20308
+ },
20309
+ async processCommandLine(pid) {
20310
+ if (!Number.isInteger(pid) || pid <= 0) return void 0;
20311
+ const result = await runPowerShell(`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`);
20312
+ return result.ok ? result.stdout.trim() || void 0 : void 0;
20313
+ },
20314
+ scriptShell: (command) => ({ executable: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", command] }),
20315
+ readLoginEnvironment: readRegistryEnvironment
20316
+ };
20317
+
20318
+ // src/platform/index.ts
20319
+ var darwinPlatform = createPosixPlatform("darwin");
20320
+ var linuxPlatform = createPosixPlatform("linux");
20321
+ function platformFor(id) {
20322
+ if (id === "win32") return win32Platform;
20323
+ if (id === "darwin") return darwinPlatform;
20324
+ return linuxPlatform;
20325
+ }
20326
+ var currentPlatform = platformFor(process.platform);
20327
+ function directLaunch2(path, args, nodePath = process.execPath) {
20328
+ return directLaunch(currentPlatform, path, args, nodePath);
20329
+ }
20330
+
20331
+ // src/runtime/cli/hydrate-shell-path.ts
20332
+ var cached2 = null;
20333
+ function mergeShellProxyEnvironment(hydration, baseline = process.env) {
20334
+ const environment = { ...baseline };
20335
+ if (!hydration.ok) return environment;
20336
+ for (const key of PROXY_KEYS.slice(0, 4)) {
20337
+ const upper = key.toUpperCase();
20338
+ if (baseline[key] !== void 0 || baseline[upper] !== void 0) continue;
20339
+ const value = hydration.proxyEnv?.[key] ?? hydration.proxyEnv?.[upper];
20340
+ if (value) environment[key] = value;
20115
20341
  }
20116
- cached2 = (options.spawner ?? spawnShellAndReadPath)(shell);
20342
+ return environment;
20343
+ }
20344
+ function hydrateShellPath(options = {}) {
20345
+ if (cached2 && !options.force) return cached2;
20346
+ cached2 = (options.reader ?? (() => currentPlatform.readLoginEnvironment()))();
20117
20347
  return cached2;
20118
20348
  }
20119
20349
  function mergePathSegments(segments) {
20120
- if (segments.length === 0) {
20121
- return [];
20122
- }
20350
+ if (segments.length === 0) return [];
20123
20351
  const current = process.env.PATH ?? "";
20124
- const currentSegments = current.split(delimiter2).filter(Boolean);
20352
+ const currentSegments = current.split(delimiter3).filter(Boolean);
20125
20353
  const shellSegments = [...new Set(segments)];
20126
20354
  const shellSegmentSet = new Set(shellSegments);
20127
20355
  const existing = new Set(currentSegments);
@@ -20130,39 +20358,32 @@ function mergePathSegments(segments) {
20130
20358
  ...shellSegments,
20131
20359
  ...currentSegments.filter((segment) => !shellSegmentSet.has(segment))
20132
20360
  ];
20133
- const next = merged.join(delimiter2);
20134
- if (next === current) {
20135
- return [];
20136
- }
20361
+ const next = merged.join(delimiter3);
20362
+ if (next === current) return [];
20137
20363
  process.env.PATH = next;
20138
20364
  return added;
20139
20365
  }
20140
20366
 
20141
20367
  // src/providers/cli/claude.ts
20142
- import { readFileSync as readFileSync3 } from "node:fs";
20368
+ import { readFileSync as readFileSync4 } from "node:fs";
20143
20369
  import { homedir as homedir4 } from "node:os";
20144
- import { join as join5 } from "node:path";
20370
+ import { join as join7 } from "node:path";
20145
20371
 
20146
20372
  // src/providers/provider.ts
20147
20373
  import { realpathSync } from "node:fs";
20148
20374
  import { homedir as homedir3 } from "node:os";
20149
- import { delimiter as delimiter4, dirname as dirname3, join as join4 } from "node:path";
20375
+ import { delimiter as delimiter4, dirname as dirname3 } from "node:path";
20150
20376
 
20151
20377
  // src/shared/node-cli-command-resolution.ts
20152
- import { accessSync, constants, existsSync as existsSync3, readdirSync, statSync } from "node:fs";
20378
+ import { existsSync as existsSync3, readdirSync } from "node:fs";
20153
20379
  import { homedir as homedir2 } from "node:os";
20154
- import { delimiter as delimiter3, dirname as dirname2, join as join3 } from "node:path";
20155
- function getExecutableNames(platform2, commandName) {
20156
- if (platform2 === "win32") {
20157
- return [`${commandName}.cmd`, `${commandName}.exe`, `${commandName}.bat`, commandName];
20158
- }
20159
- return [commandName];
20380
+ import { dirname as dirname2, join as join6 } from "node:path";
20381
+ function adapterOf(options) {
20382
+ return platformFor(options.platform ?? process.platform);
20160
20383
  }
20161
- function splitPath(pathEnv) {
20162
- if (!pathEnv) {
20163
- return [];
20164
- }
20165
- return pathEnv.split(delimiter3).map((entry) => entry.trim()).filter(Boolean);
20384
+ function splitPath(platform2, pathEnv) {
20385
+ if (!pathEnv) return [];
20386
+ return pathEnv.split(platform2.id === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean);
20166
20387
  }
20167
20388
  function parseVersionSegment(raw) {
20168
20389
  return raw.replace(/^v/i, "").split(".").map((segment) => Number.parseInt(segment, 10)).map((segment) => Number.isFinite(segment) ? segment : 0);
@@ -20173,116 +20394,58 @@ function compareVersionDesc(left, right) {
20173
20394
  const length = Math.max(leftParts.length, rightParts.length);
20174
20395
  for (let index = 0; index < length; index += 1) {
20175
20396
  const delta = (rightParts[index] ?? 0) - (leftParts[index] ?? 0);
20176
- if (delta !== 0) {
20177
- return delta;
20178
- }
20397
+ if (delta !== 0) return delta;
20179
20398
  }
20180
20399
  return right.localeCompare(left);
20181
20400
  }
20182
20401
  function findFirstExecutable(platform2, directories, executableNames) {
20183
20402
  for (const directory of directories) {
20184
20403
  for (const executableName of executableNames) {
20185
- const candidate = join3(directory, executableName);
20186
- if (isRunnableCommand(platform2, candidate)) {
20187
- return candidate;
20188
- }
20404
+ const candidate = join6(directory, executableName);
20405
+ if (platform2.isRunnableFile(candidate)) return candidate;
20189
20406
  }
20190
20407
  }
20191
20408
  return null;
20192
20409
  }
20193
- function isRunnableCommand(platform2, candidate) {
20194
- try {
20195
- const stats = statSync(candidate);
20196
- if (!stats.isFile()) {
20197
- return false;
20198
- }
20199
- if (platform2 === "win32") {
20200
- return true;
20201
- }
20202
- accessSync(candidate, constants.X_OK);
20203
- return true;
20204
- } catch {
20205
- return false;
20206
- }
20207
- }
20208
20410
  function getBaseVersionManagerDirectories(platform2, homePath) {
20209
- const directories = [
20210
- join3(homePath, ".volta", "bin"),
20211
- join3(homePath, ".asdf", "shims"),
20212
- join3(homePath, ".fnm", "aliases", "default", "bin"),
20213
- // Why: mise (formerly rtx) exposes managed tool binaries via a shims
20214
- // directory, similar to asdf.
20215
- join3(homePath, ".local", "share", "mise", "shims")
20411
+ return [
20412
+ ...sharedUserBinDirectoriesHead(homePath),
20413
+ ...platform2.userBinDirectories(homePath),
20414
+ ...sharedUserBinDirectoriesTail(homePath)
20216
20415
  ];
20217
- if (platform2 === "win32") {
20218
- directories.push(join3(homePath, ".local", "bin"));
20219
- directories.push(join3(homePath, "AppData", "Roaming", "npm"));
20220
- directories.push(join3(homePath, "AppData", "Local", "pnpm"));
20221
- directories.push(join3(homePath, "AppData", "Local", "Yarn", "bin"));
20222
- } else {
20223
- directories.push(join3(homePath, ".local", "bin"));
20224
- if (platform2 === "darwin") {
20225
- directories.push(join3(homePath, "Library", "pnpm"));
20226
- } else {
20227
- directories.push(join3(homePath, ".local", "share", "pnpm"));
20228
- }
20229
- directories.push(join3(homePath, ".yarn", "bin"));
20230
- }
20231
- directories.push(join3(homePath, ".bun", "bin"));
20232
- return directories;
20233
20416
  }
20234
20417
  function getNvmVersionDirectories(homePath) {
20235
- const nvmVersionsDir = join3(homePath, ".nvm", "versions", "node");
20236
- if (!existsSync3(nvmVersionsDir)) {
20237
- return [];
20238
- }
20239
- return readdirSync(nvmVersionsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionDesc).map((entry) => join3(nvmVersionsDir, entry, "bin"));
20418
+ const nvmVersionsDir = join6(homePath, ".nvm", "versions", "node");
20419
+ if (!existsSync3(nvmVersionsDir)) return [];
20420
+ return readdirSync(nvmVersionsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionDesc).map((entry) => join6(nvmVersionsDir, entry, "bin"));
20240
20421
  }
20241
20422
  function getVersionManagerDirectories(platform2, homePath, executableNames) {
20242
20423
  const directories = getBaseVersionManagerDirectories(platform2, homePath);
20243
- const firstNvmMatch = findFirstExecutable(
20244
- platform2,
20245
- getNvmVersionDirectories(homePath),
20246
- executableNames
20247
- );
20248
- if (firstNvmMatch) {
20249
- directories.unshift(dirname2(firstNvmMatch));
20250
- }
20424
+ const firstNvmMatch = findFirstExecutable(platform2, getNvmVersionDirectories(homePath), executableNames);
20425
+ if (firstNvmMatch) directories.unshift(dirname2(firstNvmMatch));
20251
20426
  return directories;
20252
20427
  }
20253
20428
  function resolveCliCommand(commandName, options = {}) {
20254
20429
  return findCliCommand(commandName, options) ?? commandName;
20255
20430
  }
20256
20431
  function findCliCommand(commandName, options = {}) {
20257
- const platform2 = options.platform ?? process.platform;
20258
- const executableNames = getExecutableNames(platform2, commandName);
20432
+ const platform2 = adapterOf(options);
20433
+ const executableNames = platform2.executableNames(commandName);
20259
20434
  const pathEnv = options.pathEnv ?? process.env.PATH ?? process.env.Path ?? null;
20260
- const pathCandidate = findFirstExecutable(platform2, splitPath(pathEnv), executableNames);
20261
- if (pathCandidate) {
20262
- return pathCandidate;
20263
- }
20435
+ const pathCandidate = findFirstExecutable(platform2, splitPath(platform2, pathEnv), executableNames);
20436
+ if (pathCandidate) return pathCandidate;
20264
20437
  const homePath = options.homePath ?? homedir2();
20265
- const nvmCandidate = findFirstExecutable(
20266
- platform2,
20267
- getNvmVersionDirectories(homePath),
20268
- executableNames
20269
- );
20270
- const versionManagerCandidate = nvmCandidate ?? findFirstExecutable(
20271
- platform2,
20272
- getBaseVersionManagerDirectories(platform2, homePath),
20273
- executableNames
20274
- );
20275
- return versionManagerCandidate;
20438
+ const nvmCandidate = findFirstExecutable(platform2, getNvmVersionDirectories(homePath), executableNames);
20439
+ return nvmCandidate ?? findFirstExecutable(platform2, getBaseVersionManagerDirectories(platform2, homePath), executableNames);
20276
20440
  }
20277
20441
  function resolveCliCommandDetailed(commandName, options = {}) {
20278
20442
  const resolved = findCliCommand(commandName, options);
20279
20443
  return resolved ? { command: resolved, found: true, path: resolved } : { command: commandName, found: false };
20280
20444
  }
20281
20445
  function getVersionManagerBinPaths(options = {}) {
20282
- const platform2 = options.platform ?? process.platform;
20446
+ const platform2 = adapterOf(options);
20283
20447
  const homePath = options.homePath ?? homedir2();
20284
- const nodeNames = getExecutableNames(platform2, "node");
20285
- return getVersionManagerDirectories(platform2, homePath, nodeNames);
20448
+ return getVersionManagerDirectories(platform2, homePath, platform2.executableNames("node"));
20286
20449
  }
20287
20450
 
20288
20451
  // src/providers/provider.ts
@@ -20323,14 +20486,12 @@ function toolCallRows(name, path) {
20323
20486
  return [runLog.tool("tool_call")];
20324
20487
  }
20325
20488
  function providerEnvironment() {
20326
- const env = { ...process.env };
20489
+ const env = currentPlatform.normalizeEnvironment(process.env);
20327
20490
  const commandPaths = [
20328
20491
  dirname3(process.execPath),
20329
- ...getVersionManagerBinPaths(env.PATH === void 0 ? {} : { pathEnv: env.PATH }),
20492
+ ...getVersionManagerBinPaths(),
20330
20493
  env.PATH,
20331
- "/opt/homebrew/bin",
20332
- "/usr/local/bin",
20333
- join4(homedir3(), ".local", "bin")
20494
+ ...currentPlatform.fallbackBinDirectories(homedir3())
20334
20495
  ].filter((value) => Boolean(value));
20335
20496
  env.PATH = [...new Set(commandPaths)].join(delimiter4);
20336
20497
  return env;
@@ -20338,15 +20499,30 @@ function providerEnvironment() {
20338
20499
  function resolveExecutable(command, args, env, override) {
20339
20500
  const candidate = override?.trim() || resolveCliCommand(command, env.PATH === void 0 ? {} : { pathEnv: env.PATH });
20340
20501
  if (!candidate) return { executable: command, args, env };
20502
+ let resolved = candidate;
20341
20503
  try {
20342
- const resolved = realpathSync(candidate);
20343
- if (resolved.endsWith(".js") || resolved.endsWith(".mjs") || resolved.endsWith(".cjs")) {
20344
- return { executable: process.env.TOC_OCRA_NODE_PATH || process.execPath, args: [resolved, ...args], env };
20345
- }
20346
- return { executable: resolved, args, env };
20504
+ resolved = realpathSync(candidate);
20347
20505
  } catch {
20348
- return { executable: candidate, args, env };
20349
20506
  }
20507
+ return { ...directLaunch2(resolved, args, process.env.TOC_OCRA_NODE_PATH || process.execPath), env };
20508
+ }
20509
+ function launchCli(options) {
20510
+ const launch = resolveExecutable(options.command, options.args, options.env ?? providerEnvironment(), process.env[options.overrideEnv]);
20511
+ return options.prompt && options.promptStdin ? fitPromptOnCommandLine(launch, options.prompt, options.promptStdin) : launch;
20512
+ }
20513
+ function fitsCommandLine(launch) {
20514
+ return commandLineLength(launch.executable, launch.args) <= currentPlatform.maxCommandLineLength;
20515
+ }
20516
+ function fitPromptOnCommandLine(launch, prompt, stdin) {
20517
+ if (!prompt || fitsCommandLine(launch)) return launch;
20518
+ const index = launch.args.lastIndexOf(prompt);
20519
+ if (index < 0) return launch;
20520
+ const args = [...launch.args];
20521
+ if (stdin === "omit") {
20522
+ const separator = index > 0 && args[index - 1] === "--" && index === args.length - 1;
20523
+ args.splice(separator ? index - 1 : index, separator ? 2 : 1);
20524
+ } else args[index] = stdin.replaceWith;
20525
+ return { ...launch, args, stdin: prompt };
20350
20526
  }
20351
20527
  function tryJson(line) {
20352
20528
  const start = line.indexOf("{");
@@ -20382,7 +20558,7 @@ var claudeProvider = {
20382
20558
  else {
20383
20559
  args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*", "--settings", '{"disableAllHooks":true}');
20384
20560
  try {
20385
- const settings = JSON.parse(readFileSync3(join5(homedir4(), ".claude", "settings.json"), "utf8"));
20561
+ const settings = JSON.parse(readFileSync4(join7(homedir4(), ".claude", "settings.json"), "utf8"));
20386
20562
  for (const [key, value] of Object.entries(settings.env ?? {})) {
20387
20563
  if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
20388
20564
  }
@@ -20392,7 +20568,7 @@ var claudeProvider = {
20392
20568
  if (request.model) args.push("--model", request.model);
20393
20569
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20394
20570
  if (request.sessionId) args.push("--resume", request.sessionId);
20395
- return resolveExecutable("claude", args, env, process.env.TOC_OCRA_CLAUDE_PATH);
20571
+ return launchCli({ command: "claude", overrideEnv: "TOC_OCRA_CLAUDE_PATH", args, env, prompt: request.prompt, promptStdin: "omit" });
20396
20572
  },
20397
20573
  parseLine(line) {
20398
20574
  return claudeLineParser()(line);
@@ -20493,7 +20669,7 @@ var codexProvider = {
20493
20669
  if (request.reasoningEffort) args.push("-c", `model_reasoning_effort=${JSON.stringify(request.reasoningEffort)}`);
20494
20670
  if (request.sessionId) args.push("resume", request.sessionId);
20495
20671
  args.push("--", request.prompt);
20496
- return resolveExecutable("codex", args, providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
20672
+ return launchCli({ command: "codex", overrideEnv: "TOC_OCRA_CODEX_PATH", args, prompt: request.prompt, promptStdin: { replaceWith: "-" } });
20497
20673
  },
20498
20674
  parseLine(line) {
20499
20675
  const event = tryJson(line);
@@ -20549,7 +20725,7 @@ var geminiProvider = {
20549
20725
  const args = ["-p", request.prompt, "--output-format", "json", "--yolo"];
20550
20726
  if (request.model) args.push("--model", request.model);
20551
20727
  if (request.sessionId) args.push("--resume", request.sessionId);
20552
- return resolveExecutable("gemini", args, providerEnvironment(), process.env.TOC_OCRA_GEMINI_PATH);
20728
+ return launchCli({ command: "gemini", overrideEnv: "TOC_OCRA_GEMINI_PATH", args });
20553
20729
  },
20554
20730
  parseLine(line) {
20555
20731
  const event = tryJson(line);
@@ -20574,7 +20750,7 @@ var grokProvider = {
20574
20750
  if (request.model) args.push("--model", request.model);
20575
20751
  if (request.reasoningEffort) args.push("--reasoning-effort", request.reasoningEffort);
20576
20752
  if (request.sessionId) args.push("--resume", request.sessionId);
20577
- return resolveExecutable("grok", args, providerEnvironment(), process.env.TOC_OCRA_GROK_PATH);
20753
+ return launchCli({ command: "grok", overrideEnv: "TOC_OCRA_GROK_PATH", args });
20578
20754
  },
20579
20755
  parseLine(line) {
20580
20756
  const event = tryJson(line);
@@ -20590,12 +20766,151 @@ var grokProvider = {
20590
20766
  };
20591
20767
 
20592
20768
  // src/providers/cli/kiro.ts
20593
- import { execFile } from "node:child_process";
20769
+ import { execFile as execFile3 } from "node:child_process";
20594
20770
  import { promisify } from "node:util";
20595
- var execFileAsync = promisify(execFile);
20771
+
20772
+ // src/providers/cli/kiro-session-log.ts
20773
+ import { open as open2, readdir, readFile as readFile2, stat } from "node:fs/promises";
20774
+ import { homedir as homedir5 } from "node:os";
20775
+ import { join as join8 } from "node:path";
20776
+ var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
20777
+ function kiroSessionsDirectory() {
20778
+ return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join8(homedir5(), ".kiro", "sessions", "cli");
20779
+ }
20780
+ var KiroSessionLog = class {
20781
+ constructor(options) {
20782
+ this.options = options;
20783
+ }
20784
+ options;
20785
+ path;
20786
+ offset = 0;
20787
+ partial = "";
20788
+ steps = [];
20789
+ results = /* @__PURE__ */ new Map();
20790
+ claimed = /* @__PURE__ */ new Set();
20791
+ get directory() {
20792
+ return this.options.directory ?? kiroSessionsDirectory();
20793
+ }
20794
+ /** Called before the CLI starts: a resumed log is followed from its current end. */
20795
+ async begin() {
20796
+ if (!this.options.sessionId) return;
20797
+ this.path = join8(this.directory, `${this.options.sessionId}.jsonl`);
20798
+ this.offset = await stat(this.path).then((info) => info.size, () => 0);
20799
+ }
20800
+ /**
20801
+ * A fresh turn's chat has no known id: the one log for this folder created
20802
+ * after the turn started. Several candidates (another turn starting a chat
20803
+ * in the same folder) leave it unknown.
20804
+ */
20805
+ async findFreshLog() {
20806
+ const names = await readdir(this.directory).catch(() => []);
20807
+ const found = [];
20808
+ for (const name of names) {
20809
+ if (!name.endsWith(".json")) continue;
20810
+ const meta3 = await readFile2(join8(this.directory, name), "utf8").then((text) => JSON.parse(text), () => void 0);
20811
+ const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
20812
+ if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
20813
+ }
20814
+ if (found.length === 1) this.path = join8(this.directory, `${found[0]}.jsonl`);
20815
+ }
20816
+ /** Reads entries appended since the last call. */
20817
+ async refresh() {
20818
+ if (!this.path) await this.findFreshLog();
20819
+ if (!this.path) return;
20820
+ const file2 = await open2(this.path, "r").catch(() => void 0);
20821
+ if (!file2) return;
20822
+ try {
20823
+ const { size } = await file2.stat();
20824
+ if (size <= this.offset) return;
20825
+ const buffer = Buffer.alloc(size - this.offset);
20826
+ await file2.read(buffer, 0, buffer.length, this.offset);
20827
+ this.offset = size;
20828
+ const lines = (this.partial + buffer.toString("utf8")).split("\n");
20829
+ this.partial = lines.pop() ?? "";
20830
+ for (const line of lines) this.take(line);
20831
+ } finally {
20832
+ await file2.close();
20833
+ }
20834
+ }
20835
+ take(line) {
20836
+ let entry;
20837
+ try {
20838
+ entry = JSON.parse(line);
20839
+ } catch {
20840
+ return;
20841
+ }
20842
+ for (const part of entry.data?.content ?? []) {
20843
+ const data = part.data ?? {};
20844
+ if (part.kind === "toolUse" && SHELL_TOOLS.has(String(data.name))) {
20845
+ const command = data.input?.command;
20846
+ if (typeof data.toolUseId === "string" && typeof command === "string") this.steps.push({ id: data.toolUseId, command });
20847
+ } else if (part.kind === "toolResult" && typeof data.toolUseId === "string") {
20848
+ this.results.set(data.toolUseId, resultOf(data));
20849
+ }
20850
+ }
20851
+ }
20852
+ /** The shell step a `[tool] Running:` row announced (its text may be cut short). */
20853
+ async step(shown, waitMs = 2e3) {
20854
+ const prefix = shown.replace(/\.\.\.$|…$/, "").trim();
20855
+ const deadline = Date.now() + waitMs;
20856
+ for (; ; ) {
20857
+ await this.refresh();
20858
+ const step = this.steps.find((item) => !this.claimed.has(item.id) && item.command.trim().startsWith(prefix));
20859
+ if (step) {
20860
+ this.claimed.add(step.id);
20861
+ return step;
20862
+ }
20863
+ if (Date.now() >= deadline) return void 0;
20864
+ await new Promise((resolve8) => setTimeout(resolve8, 150));
20865
+ }
20866
+ }
20867
+ /** The first of `ids` whose result is in the log, waiting up to `waitMs`. */
20868
+ async firstFinished(ids, waitMs) {
20869
+ const deadline = Date.now() + waitMs;
20870
+ for (; ; ) {
20871
+ await this.refresh();
20872
+ const id = ids.find((item) => this.results.has(item));
20873
+ if (id || Date.now() >= deadline) return id;
20874
+ await new Promise((resolve8) => setTimeout(resolve8, 150));
20875
+ }
20876
+ }
20877
+ async result(id, waitMs = 3e3) {
20878
+ const deadline = Date.now() + waitMs;
20879
+ for (; ; ) {
20880
+ await this.refresh();
20881
+ const result = this.results.get(id);
20882
+ if (result || Date.now() >= deadline) return result;
20883
+ await new Promise((resolve8) => setTimeout(resolve8, 200));
20884
+ }
20885
+ }
20886
+ };
20887
+ function resultOf(data) {
20888
+ const parts = Array.isArray(data.content) ? data.content : [];
20889
+ const texts = [];
20890
+ let exitCode;
20891
+ for (const part of parts) {
20892
+ if (part.kind === "json" && part.data && typeof part.data === "object") {
20893
+ const value = part.data;
20894
+ const code2 = /(-?\d+)/.exec(String(value.exit_status ?? ""))?.[1];
20895
+ if (code2 !== void 0) exitCode = Number(code2);
20896
+ for (const text of [value.stdout, value.stderr]) if (typeof text === "string" && text.trim()) texts.push(text.replace(/\s+$/, ""));
20897
+ } else if (part.kind === "text" && typeof part.data === "string" && part.data.trim()) {
20898
+ texts.push(part.data.replace(/\s+$/, ""));
20899
+ }
20900
+ }
20901
+ if (exitCode === void 0 && data.status === "error") exitCode = 1;
20902
+ return { ...exitCode === void 0 ? {} : { exitCode }, output: texts.join("\n") };
20903
+ }
20904
+ function sameFolder(a, b) {
20905
+ const normal = (path) => path.replace(/\/+$/, "").replace(/^\/private(?=\/)/, "");
20906
+ return normal(a) === normal(b);
20907
+ }
20908
+
20909
+ // src/providers/cli/kiro.ts
20910
+ var execFileAsync = promisify(execFile3);
20596
20911
  var ANSI = /\u001b(?:\][^\u0007]*?(?:\u0007|\u001b\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g;
20597
20912
  function kiroLaunch(args) {
20598
- return resolveExecutable("kiro-cli", args, providerEnvironment(), process.env.TOC_OCRA_KIRO_PATH);
20913
+ return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args });
20599
20914
  }
20600
20915
  var LIST_SESSIONS = ["chat", "--list-sessions", "--format", "json"];
20601
20916
  function parseKiroSessions(stdout) {
@@ -20615,13 +20930,13 @@ function describeListSessionsError(error62, timeoutMs) {
20615
20930
  return (failure2?.message || String(error62)).split("\n")[0].slice(0, 160);
20616
20931
  }
20617
20932
  async function listKiroSessions(workdir, options = {}) {
20618
- const timeoutMs = options.timeoutMs ?? KIRO_LIST_SESSIONS_TIMEOUT_MS;
20933
+ const timeoutMs = options.timeoutMs ?? (Number(process.env.TOC_OCRA_KIRO_LIST_TIMEOUT_MS) || KIRO_LIST_SESSIONS_TIMEOUT_MS);
20619
20934
  const { executable, args, env } = kiroLaunch(LIST_SESSIONS);
20620
20935
  let lastError;
20621
20936
  for (let attempt = 0; attempt < 2; attempt++) {
20622
20937
  if (attempt) await new Promise((resolve8) => setTimeout(resolve8, options.retryDelayMs ?? LIST_SESSIONS_RETRY_DELAY_MS));
20623
20938
  try {
20624
- const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
20939
+ const { stdout } = await execFileAsync(executable, args, { cwd: workdir, env, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
20625
20940
  return parseKiroSessions(stdout);
20626
20941
  } catch (error62) {
20627
20942
  lastError = error62;
@@ -20647,12 +20962,34 @@ function kiroToolRows(text) {
20647
20962
  return [runLog.tool("tool_call")];
20648
20963
  }
20649
20964
  function isKiroNoise(text) {
20650
- return /^\[(INFO|DEBUG|WARN|TRACE)\]/.test(text) || /^\[ERROR\] \(node:\d+\) ExperimentalWarning/.test(text) || /^\(Use `node --trace-warnings/.test(text);
20965
+ 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);
20651
20966
  }
20652
- function kiroRunParser() {
20967
+ function kiroRunParser(context) {
20653
20968
  let pending = "";
20654
20969
  let started = false;
20655
20970
  let segment = [];
20971
+ const log = context ? new KiroSessionLog({ sessionId: context.sessionId, workdir: context.workdir, startedAt: context.startedAt }) : void 0;
20972
+ const ready = log?.begin().catch(() => void 0);
20973
+ let queue = Promise.resolve();
20974
+ const openSteps = [];
20975
+ let lastHeader;
20976
+ const out = (parsed) => {
20977
+ if (!context) return typeof parsed === "function" ? { display: [] } : parsed;
20978
+ queue = queue.then(async () => {
20979
+ const value = typeof parsed === "function" ? await parsed().catch(() => ({ display: [] })) : parsed;
20980
+ if (value.display.length && typeof parsed !== "function") lastHeader = void 0;
20981
+ context.emit(value);
20982
+ });
20983
+ return { display: [] };
20984
+ };
20985
+ const finishShell = async (step, status) => {
20986
+ const found = await step.shell.lookup;
20987
+ const result = found ? await log.result(found.id, 1e3) : void 0;
20988
+ const header = step.shell.headerShown && lastHeader === step ? [] : [runLog.command(found?.command ?? step.shell.shown)];
20989
+ lastHeader = void 0;
20990
+ if (!result) return { display: [...header, ...status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : []] };
20991
+ return { display: [...header, ...runLog.commandOutput(result.output), runLog.commandExit(result.exitCode ?? (status === "failed" ? 1 : 0))] };
20992
+ };
20656
20993
  const replyRows = (lines) => {
20657
20994
  const display = [];
20658
20995
  for (const raw of lines) {
@@ -20680,18 +21017,58 @@ function kiroRunParser() {
20680
21017
  stdout(chunk) {
20681
21018
  const lines = (pending + chunk).split(/\r?\n/);
20682
21019
  pending = lines.pop() ?? "";
20683
- return replyRows(lines);
21020
+ return out(replyRows(lines));
20684
21021
  },
20685
21022
  stderr(raw) {
20686
21023
  const text = raw.replace(ANSI, "").trim();
20687
21024
  if (!text || isKiroNoise(text)) return { display: [] };
20688
- const rows = kiroToolRows(text) ?? [runLog.error(text)];
20689
21025
  const closed = closeSegment();
20690
- return { ...closed, display: [...closed.display, ...rows] };
21026
+ const status = /^\[tool\]\s*status:\s*(\w+)/i.exec(text)?.[1]?.toLowerCase();
21027
+ if (!log) {
21028
+ const rows2 = kiroToolRows(text) ?? [runLog.error(text)];
21029
+ return out({ ...closed, display: [...closed.display, ...rows2] });
21030
+ }
21031
+ out(closed);
21032
+ const running = /^\[tool\]\s*Running:\s*(.+)$/.exec(text)?.[1]?.trim();
21033
+ if (running && !running.startsWith("@")) {
21034
+ const step = { shell: { shown: running, lookup: (async () => {
21035
+ await ready;
21036
+ return log.step(running);
21037
+ })(), headerShown: !openSteps.some((item) => item.shell) } };
21038
+ openSteps.push(step);
21039
+ if (!step.shell.headerShown) return { display: [] };
21040
+ return out(async () => {
21041
+ const found = await step.shell.lookup;
21042
+ lastHeader = step;
21043
+ return { display: [runLog.command(found?.command ?? running)] };
21044
+ });
21045
+ }
21046
+ if (status) {
21047
+ return out(async () => {
21048
+ const shells = openSteps.filter((item) => item.shell);
21049
+ const ids = (await Promise.all(shells.map((item) => item.shell.lookup))).map((found) => found?.id ?? "");
21050
+ const others = openSteps.some((item) => !item.shell);
21051
+ const id = shells.length ? await log.firstFinished(ids.filter(Boolean), others ? 1200 : 3e3) : void 0;
21052
+ const step = id ? shells[ids.indexOf(id)] : openSteps.find((item) => !item.shell) ?? openSteps[0];
21053
+ if (step) openSteps.splice(openSteps.indexOf(step), 1);
21054
+ if (step?.shell) return finishShell(step, status);
21055
+ lastHeader = void 0;
21056
+ return { display: status === "failed" ? [runLog.error("\u4E0A\u4E00\u6B65\u6267\u884C\u5931\u8D25")] : [] };
21057
+ });
21058
+ }
21059
+ if (/^\[tool\]/.test(text)) openSteps.push({});
21060
+ const rows = kiroToolRows(text) ?? [runLog.error(text)];
21061
+ return out({ display: rows });
20691
21062
  },
20692
- end: closeSegment
21063
+ end: async () => {
21064
+ const rest = out(closeSegment());
21065
+ if (!context) return rest;
21066
+ await queue;
21067
+ return { display: [] };
21068
+ }
20693
21069
  };
20694
21070
  }
21071
+ 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";
20695
21072
  var kiroProvider = {
20696
21073
  id: "kiro",
20697
21074
  buildLaunch(request) {
@@ -20702,23 +21079,25 @@ var kiroProvider = {
20702
21079
  if (request.reasoningEffort) args.push("--effort", request.reasoningEffort);
20703
21080
  if (request.sessionId && !request.sessionId.startsWith("sess_")) args.push("--resume-id", request.sessionId);
20704
21081
  args.push("--", request.prompt);
20705
- return kiroLaunch(args);
21082
+ return launchCli({ command: "kiro-cli", overrideEnv: "TOC_OCRA_KIRO_PATH", args, prompt: request.prompt, promptStdin: "omit" });
20706
21083
  },
20707
21084
  listSessions: (workdir) => listKiroSessions(workdir),
20708
21085
  isMissingSession: (stderr) => isKiroMissingSession(stderr),
20709
21086
  inspectExit(context) {
20710
21087
  const businessError = kiroStderrError(context.stderr);
20711
- return businessError ? { turnError: businessError } : {};
21088
+ if (!businessError) return {};
21089
+ return businessError === KIRO_IMAGE_LIMIT ? { turnError: businessError, display: [runLog.error(businessError)] } : { turnError: businessError };
20712
21090
  },
20713
21091
  /** A single stdout line read as a complete reply (the supervisor uses `createRunParser`). */
20714
21092
  parseLine(line) {
20715
21093
  return kiroRunParser().stdout(`${line}
20716
21094
  `);
20717
21095
  },
20718
- createRunParser: () => kiroRunParser()
21096
+ createRunParser: (context) => kiroRunParser(context)
20719
21097
  };
20720
21098
  function kiroStderrError(stderrLines) {
20721
21099
  const text = stderrLines.join("\n");
21100
+ if (/too many inline media segments/i.test(text)) return KIRO_IMAGE_LIMIT;
20722
21101
  if (/Monthly request limit reached|request limit reached/i.test(text)) {
20723
21102
  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";
20724
21103
  }
@@ -20741,7 +21120,7 @@ var opencodeProvider = {
20741
21120
  if (request.model) args.push("--model", request.model);
20742
21121
  if (request.sessionId) args.push("--session", request.sessionId);
20743
21122
  args.push(request.prompt);
20744
- return resolveExecutable("opencode", args, providerEnvironment(), process.env.TOC_OCRA_OPENCODE_PATH);
21123
+ return launchCli({ command: "opencode", overrideEnv: "TOC_OCRA_OPENCODE_PATH", args });
20745
21124
  },
20746
21125
  parseLine(line) {
20747
21126
  const event = tryJson(line);
@@ -20810,7 +21189,8 @@ function resolveDetectedProviderCommands(foundCommands, commands = DETECTION_COM
20810
21189
  function probeVersion(path, args) {
20811
21190
  if (args.length === 0) return Promise.resolve({});
20812
21191
  return new Promise((resolve8) => {
20813
- const child = spawn2(path, [...args], { stdio: ["ignore", "pipe", "pipe"], shell: false });
21192
+ const launch = directLaunch2(path, args);
21193
+ const child = spawn3(launch.executable, launch.args, { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
20814
21194
  let stdout = "";
20815
21195
  let stderr = "";
20816
21196
  let settled = false;
@@ -20890,12 +21270,12 @@ var CliDetectionService = class {
20890
21270
  var cliDetection = new CliDetectionService();
20891
21271
 
20892
21272
  // src/runtime/run-service.ts
20893
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
21273
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
20894
21274
  import { dirname as dirname7, resolve as resolve6 } from "node:path";
20895
21275
  import { fileURLToPath } from "node:url";
20896
21276
 
20897
21277
  // src/health/server.ts
20898
- import { readFile as readFile2 } from "node:fs/promises";
21278
+ import { readFile as readFile3 } from "node:fs/promises";
20899
21279
  import { createServer } from "node:http";
20900
21280
  var ControlError = class extends Error {
20901
21281
  constructor(status, message, code2 = "bad_request") {
@@ -21076,7 +21456,7 @@ var HealthServer = class {
21076
21456
  }
21077
21457
  async recentEvents() {
21078
21458
  try {
21079
- const raw = await readFile2(this.logFile, "utf8");
21459
+ const raw = await readFile3(this.logFile, "utf8");
21080
21460
  return raw.trim().split("\n").slice(-60).flatMap((line) => {
21081
21461
  try {
21082
21462
  const parsed = JSON.parse(line);
@@ -21135,9 +21515,9 @@ import {
21135
21515
  chmodSync,
21136
21516
  existsSync as existsSync4,
21137
21517
  mkdirSync as mkdirSync2,
21138
- readFileSync as readFileSync4,
21518
+ readFileSync as readFileSync5,
21139
21519
  renameSync,
21140
- statSync as statSync2,
21520
+ statSync as statSync3,
21141
21521
  unlinkSync,
21142
21522
  writeFileSync as writeFileSync2
21143
21523
  } from "node:fs";
@@ -21167,7 +21547,7 @@ function createDiagnosticLogger(filePath, options = {}) {
21167
21547
  try {
21168
21548
  mkdirSync2(dirname4(filePath), { recursive: true });
21169
21549
  pruneExpired();
21170
- currentBytes = existsSync4(filePath) ? statSync2(filePath).size : 0;
21550
+ currentBytes = existsSync4(filePath) ? statSync3(filePath).size : 0;
21171
21551
  } catch {
21172
21552
  disabled = true;
21173
21553
  }
@@ -21193,7 +21573,7 @@ function createDiagnosticLogger(filePath, options = {}) {
21193
21573
  for (let index = 0; index <= maxRotatedFiles; index += 1) {
21194
21574
  const path = index === 0 ? filePath : `${filePath}.${index}`;
21195
21575
  if (!existsSync4(path)) continue;
21196
- const kept = readFileSync4(path, "utf8").split("\n").filter((line) => {
21576
+ const kept = readFileSync5(path, "utf8").split("\n").filter((line) => {
21197
21577
  if (!line.trim()) return false;
21198
21578
  try {
21199
21579
  const timestamp = Date.parse(JSON.parse(line).ts);
@@ -21253,16 +21633,24 @@ function createDiagnosticLogger(filePath, options = {}) {
21253
21633
 
21254
21634
  // src/runtime/agent-runtime.ts
21255
21635
  import { randomUUID as randomUUID3 } from "node:crypto";
21256
- import { join as join11 } from "node:path";
21636
+ import { join as join14 } from "node:path";
21637
+
21638
+ // src/exec/script-runner.ts
21639
+ import { spawn as spawn4 } from "node:child_process";
21640
+
21641
+ // src/runs/process-tree.ts
21642
+ var KILL_GRACE_MS = 3e3;
21643
+ async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
21644
+ if (!Number.isInteger(rootPid) || rootPid <= 1) return;
21645
+ await currentPlatform.killProcessTree(rootPid, graceMs);
21646
+ }
21257
21647
 
21258
21648
  // src/exec/script-runner.ts
21259
- import { spawn as spawn3 } from "node:child_process";
21260
21649
  var MAX_SCRIPT_OUTPUT_BYTES = 112 * 1024;
21261
21650
  function executeScript(command, workdir, timeoutSeconds) {
21262
21651
  return new Promise((resolveExecution) => {
21263
- const windows = process.platform === "win32";
21264
- const executable = windows ? process.env.ComSpec ?? "cmd.exe" : "/bin/sh";
21265
- const args = windows ? ["/d", "/s", "/c", command] : ["-lc", command];
21652
+ const ownGroup = currentPlatform.runsInOwnProcessGroup;
21653
+ const { executable, args } = currentPlatform.scriptShell(command);
21266
21654
  const startedAt = Date.now();
21267
21655
  const stdout = [];
21268
21656
  const stderr = [];
@@ -21288,11 +21676,12 @@ function executeScript(command, workdir, timeoutSeconds) {
21288
21676
  };
21289
21677
  let child;
21290
21678
  try {
21291
- child = spawn3(executable, args, {
21679
+ child = spawn4(executable, args, {
21292
21680
  cwd: workdir,
21293
21681
  env: process.env,
21294
- detached: !windows,
21682
+ detached: ownGroup,
21295
21683
  shell: false,
21684
+ windowsHide: true,
21296
21685
  stdio: ["ignore", "pipe", "pipe"]
21297
21686
  });
21298
21687
  } catch (error62) {
@@ -21309,7 +21698,8 @@ function executeScript(command, workdir, timeoutSeconds) {
21309
21698
  const kill = () => {
21310
21699
  if (child.exitCode !== null || child.killed) return;
21311
21700
  try {
21312
- if (!windows && child.pid) process.kill(-child.pid, "SIGKILL");
21701
+ if (ownGroup && child.pid) process.kill(-child.pid, "SIGKILL");
21702
+ else if (child.pid) void killProcessTree(child.pid, 0);
21313
21703
  else child.kill("SIGKILL");
21314
21704
  } catch {
21315
21705
  try {
@@ -21658,19 +22048,19 @@ function resolveChatProvider(type, request, attachments) {
21658
22048
 
21659
22049
  // src/providers/model-catalog-collector.ts
21660
22050
  import { createHash } from "node:crypto";
21661
- import { stat } from "node:fs/promises";
22051
+ import { stat as stat2 } from "node:fs/promises";
21662
22052
 
21663
22053
  // src/providers/model-catalog.ts
21664
- import { spawn as spawn5 } from "node:child_process";
21665
- import { readFile as readFile3 } from "node:fs/promises";
21666
- import { homedir as homedir5 } from "node:os";
21667
- import { isAbsolute, join as join6, resolve as resolve2 } from "node:path";
22054
+ import { spawn as spawn6 } from "node:child_process";
22055
+ import { readFile as readFile4 } from "node:fs/promises";
22056
+ import { homedir as homedir6 } from "node:os";
22057
+ import { isAbsolute, join as join9, resolve as resolve2 } from "node:path";
21668
22058
 
21669
22059
  // src/providers/kiro-models.ts
21670
- import { spawn as spawn4 } from "node:child_process";
22060
+ import { spawn as spawn5 } from "node:child_process";
21671
22061
  import { createInterface } from "node:readline";
21672
22062
  async function readKiroNativeModels(launch, cwd, options = {}) {
21673
- const child = spawn4(launch.executable, launch.args, { cwd, env: launch.env, shell: false, stdio: ["pipe", "pipe", "pipe"] });
22063
+ const child = spawn5(launch.executable, launch.args, { cwd, env: launch.env, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
21674
22064
  const lines = createInterface({ input: child.stdout });
21675
22065
  let nextId = 0;
21676
22066
  let failure2;
@@ -21742,7 +22132,7 @@ async function readKiroNativeModels(launch, cwd, options = {}) {
21742
22132
  clearTimeout(timer);
21743
22133
  lines.close();
21744
22134
  child.stdin.end();
21745
- child.kill("SIGTERM");
22135
+ currentPlatform.stopHelper(child);
21746
22136
  const killTimer = setTimeout(() => {
21747
22137
  if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
21748
22138
  }, 1e3);
@@ -21786,15 +22176,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
21786
22176
  if (defaultModel) catalog.default_model = defaultModel;
21787
22177
  return catalog;
21788
22178
  }
21789
- var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir5(), ".claude");
21790
- var codexHome = () => process.env.CODEX_HOME?.trim() || join6(homedir5(), ".codex");
21791
- var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join6(homedir5(), ".gemini");
21792
- var grokHome = () => process.env.GROK_HOME?.trim() || join6(homedir5(), ".grok");
21793
- var opencodeHome = () => join6(process.env.XDG_CONFIG_HOME?.trim() || join6(homedir5(), ".config"), "opencode");
21794
- var kiroHome = () => join6(homedir5(), ".kiro");
22179
+ var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir6(), ".claude");
22180
+ var codexHome = () => process.env.CODEX_HOME?.trim() || join9(homedir6(), ".codex");
22181
+ var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join9(homedir6(), ".gemini");
22182
+ var grokHome = () => process.env.GROK_HOME?.trim() || join9(homedir6(), ".grok");
22183
+ var opencodeHome = () => join9(process.env.XDG_CONFIG_HOME?.trim() || join9(homedir6(), ".config"), "opencode");
22184
+ var kiroHome = () => join9(homedir6(), ".kiro");
21795
22185
  async function readClaudeModelCatalog() {
21796
22186
  const home = claudeHome();
21797
- const content = await readFile3(join6(home, "settings.json"), "utf8").catch(() => "");
22187
+ const content = await readFile4(join9(home, "settings.json"), "utf8").catch(() => "");
21798
22188
  let settings = {};
21799
22189
  if (content) {
21800
22190
  try {
@@ -21850,16 +22240,16 @@ async function readCodexModels(codexHome2, config2) {
21850
22240
  const configuredCatalog = configValue(config2, "model_catalog_json");
21851
22241
  if (configuredCatalog) {
21852
22242
  const catalogPath = isAbsolute(configuredCatalog) ? configuredCatalog : resolve2(codexHome2, configuredCatalog);
21853
- const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
22243
+ const configuredModels = parseCodexModels(await readFile4(catalogPath, "utf8").catch(() => ""));
21854
22244
  if (configuredModels?.length) return configuredModels;
21855
22245
  }
21856
22246
  return parseCodexModels(
21857
- await readFile3(join6(codexHome2, "models_cache.json"), "utf8").catch(() => "")
22247
+ await readFile4(join9(codexHome2, "models_cache.json"), "utf8").catch(() => "")
21858
22248
  ) ?? [];
21859
22249
  }
21860
22250
  async function readCodexModelCatalog() {
21861
22251
  const home = codexHome();
21862
- const config2 = await readFile3(join6(home, "config.toml"), "utf8").catch(() => "");
22252
+ const config2 = await readFile4(join9(home, "config.toml"), "utf8").catch(() => "");
21863
22253
  const models = await readCodexModels(home, config2);
21864
22254
  const defaultModel = configValue(config2, "model");
21865
22255
  const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
@@ -21905,7 +22295,8 @@ function parseKiroModelCatalog(payload, fetchedAt = (/* @__PURE__ */ new Date())
21905
22295
  var MODEL_LIST_TIMEOUT_MS = 2e4;
21906
22296
  function runModelListCommand(executable, args, label, environment) {
21907
22297
  return new Promise((resolve8, reject) => {
21908
- const child = spawn5(executable, [...args], { shell: false, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
22298
+ const launch = directLaunch2(executable, args);
22299
+ const child = spawn6(launch.executable, launch.args, { shell: false, windowsHide: true, ...environment ? { env: environment } : {}, stdio: ["ignore", "pipe", "pipe"] });
21909
22300
  let stdout = "";
21910
22301
  let stderr = "";
21911
22302
  const timer = setTimeout(() => {
@@ -21949,8 +22340,8 @@ async function readKiroModelCatalog() {
21949
22340
  };
21950
22341
  const launch = resolveExecutable("kiro-cli", ["acp", "--trust-tools="], environment, override);
21951
22342
  const [payload, content] = await Promise.all([
21952
- readKiroNativeModels(launch, homedir5(), { catalog: base }),
21953
- readFile3(join6(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
22343
+ readKiroNativeModels(launch, homedir6(), { catalog: base }),
22344
+ readFile4(join9(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
21954
22345
  ]);
21955
22346
  let settings;
21956
22347
  try {
@@ -22007,7 +22398,7 @@ function geminiModelsUrl(baseUrl) {
22007
22398
  }
22008
22399
  async function readGeminiModelCatalog() {
22009
22400
  const fileEnvironment = parseEnvFile(
22010
- await readFile3(join6(geminiHome(), ".env"), "utf8").catch(() => "")
22401
+ await readFile4(join9(geminiHome(), ".env"), "utf8").catch(() => "")
22011
22402
  );
22012
22403
  const environment = { ...fileEnvironment, ...process.env };
22013
22404
  const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
@@ -22052,7 +22443,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
22052
22443
  return catalog;
22053
22444
  }
22054
22445
  async function readGrokModelCatalog() {
22055
- const config2 = await readFile3(join6(grokHome(), "config.toml"), "utf8").catch(() => "");
22446
+ const config2 = await readFile4(join9(grokHome(), "config.toml"), "utf8").catch(() => "");
22056
22447
  const output2 = await runModelListCommand(resolveCliCommand("grok"), ["models"], "grok");
22057
22448
  const catalog = parseGrokModelCatalog(output2, config2);
22058
22449
  if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22071,7 +22462,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
22071
22462
  return catalog;
22072
22463
  }
22073
22464
  async function readOpencodeModelCatalog() {
22074
- const config2 = await readFile3(join6(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join6(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22465
+ const config2 = await readFile4(join9(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile4(join9(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
22075
22466
  const output2 = await runModelListCommand(resolveCliCommand("opencode"), ["models"], "opencode");
22076
22467
  const catalog = parseOpencodeModelCatalog(output2, config2);
22077
22468
  if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
@@ -22079,22 +22470,22 @@ async function readOpencodeModelCatalog() {
22079
22470
  }
22080
22471
  var TEN_MINUTES = 10 * 60 * 1e3;
22081
22472
  var MODEL_SOURCES = {
22082
- claude: { read: readClaudeModelCatalog, watchFiles: () => [join6(claudeHome(), "settings.json")] },
22473
+ claude: { read: readClaudeModelCatalog, watchFiles: () => [join9(claudeHome(), "settings.json")] },
22083
22474
  codex: {
22084
22475
  read: readCodexModelCatalog,
22085
22476
  watchFiles: () => {
22086
22477
  const home = codexHome();
22087
- return [join6(home, "config.toml"), join6(home, "models_cache.json")];
22478
+ return [join9(home, "config.toml"), join9(home, "models_cache.json")];
22088
22479
  },
22089
22480
  // model_catalog_json may point anywhere; a periodic re-read covers it.
22090
22481
  refreshEveryMs: TEN_MINUTES
22091
22482
  },
22092
- gemini: { read: readGeminiModelCatalog, watchFiles: () => [join6(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22093
- grok: { read: readGrokModelCatalog, watchFiles: () => [join6(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22094
- kiro: { read: readKiroModelCatalog, watchFiles: () => [join6(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22483
+ gemini: { read: readGeminiModelCatalog, watchFiles: () => [join9(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
22484
+ grok: { read: readGrokModelCatalog, watchFiles: () => [join9(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
22485
+ kiro: { read: readKiroModelCatalog, watchFiles: () => [join9(kiroHome(), "settings", "cli.json")], refreshEveryMs: TEN_MINUTES },
22095
22486
  opencode: {
22096
22487
  read: readOpencodeModelCatalog,
22097
- watchFiles: () => [join6(opencodeHome(), "opencode.json"), join6(opencodeHome(), "opencode.jsonc")],
22488
+ watchFiles: () => [join9(opencodeHome(), "opencode.json"), join9(opencodeHome(), "opencode.jsonc")],
22098
22489
  refreshEveryMs: TEN_MINUTES
22099
22490
  }
22100
22491
  };
@@ -22102,7 +22493,7 @@ var MODEL_SOURCES = {
22102
22493
  // src/providers/model-catalog-collector.ts
22103
22494
  async function fileStamp(path) {
22104
22495
  try {
22105
- const info = await stat(path);
22496
+ const info = await stat2(path);
22106
22497
  return `${path}:${info.mtimeMs}:${info.size}`;
22107
22498
  } catch {
22108
22499
  return `${path}:-`;
@@ -22152,11 +22543,11 @@ var ModelCatalogCollector = class {
22152
22543
  };
22153
22544
 
22154
22545
  // src/providers/codex-quota.ts
22155
- import { spawn as spawn6 } from "node:child_process";
22546
+ import { spawn as spawn7 } from "node:child_process";
22156
22547
  import { createInterface as createInterface2 } from "node:readline";
22157
22548
  async function readCodexQuotaWindows() {
22158
22549
  const launch = resolveExecutable("codex", ["app-server", "--stdio"], providerEnvironment(), process.env.TOC_OCRA_CODEX_PATH);
22159
- const child = spawn6(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"] });
22550
+ const child = spawn7(launch.executable, launch.args, { env: launch.env, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
22160
22551
  let nextId = 0;
22161
22552
  const pending = /* @__PURE__ */ new Map();
22162
22553
  const lines = createInterface2({ input: child.stdout });
@@ -22244,15 +22635,15 @@ async function readCodexQuotaWindows() {
22244
22635
  for (const waiter of pending.values()) waiter.reject(new Error("Codex app-server \u5DF2\u5173\u95ED"));
22245
22636
  pending.clear();
22246
22637
  lines.close();
22247
- child.kill("SIGTERM");
22638
+ currentPlatform.stopHelper(child);
22248
22639
  }
22249
22640
  }
22250
22641
 
22251
22642
  // src/providers/kiro-quota.ts
22252
- import { execFile as execFile2 } from "node:child_process";
22643
+ import { execFile as execFile4 } from "node:child_process";
22253
22644
  import { tmpdir } from "node:os";
22254
22645
  import { promisify as promisify2, stripVTControlCharacters } from "node:util";
22255
- var execFileAsync2 = promisify2(execFile2);
22646
+ var execFileAsync2 = promisify2(execFile4);
22256
22647
  var amount = (value) => Number(value.replace(/,/g, ""));
22257
22648
  var rounded = (value) => Math.round(value * 100) / 100;
22258
22649
  function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
@@ -22337,16 +22728,16 @@ async function readCLIQuotaReport(agentType) {
22337
22728
  }
22338
22729
 
22339
22730
  // src/providers/tb-switch-control.ts
22340
- import { readFile as readFile4 } from "node:fs/promises";
22341
- import { homedir as homedir6 } from "node:os";
22342
- import { join as join7 } from "node:path";
22731
+ import { readFile as readFile5 } from "node:fs/promises";
22732
+ import { homedir as homedir7 } from "node:os";
22733
+ import { join as join10 } from "node:path";
22343
22734
  function dataDir() {
22344
- return process.env.TB_SWITCH_HOME?.trim() || join7(homedir6(), ".tb-switch");
22735
+ return process.env.TB_SWITCH_HOME?.trim() || join10(homedir7(), ".tb-switch");
22345
22736
  }
22346
22737
  async function readLocalService() {
22347
22738
  let discovery;
22348
22739
  try {
22349
- discovery = JSON.parse(await readFile4(join7(dataDir(), "api.json"), "utf8"));
22740
+ discovery = JSON.parse(await readFile5(join10(dataDir(), "api.json"), "utf8"));
22350
22741
  } catch {
22351
22742
  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");
22352
22743
  }
@@ -22362,7 +22753,7 @@ async function readLocalService() {
22362
22753
  }
22363
22754
  let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
22364
22755
  try {
22365
- token = (await readFile4(join7(dataDir(), "api-token"), "utf8")).trim();
22756
+ token = (await readFile5(join10(dataDir(), "api-token"), "utf8")).trim();
22366
22757
  } catch {
22367
22758
  }
22368
22759
  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");
@@ -22452,76 +22843,8 @@ async function controlTbSwitch(payload) {
22452
22843
  }
22453
22844
 
22454
22845
  // src/runs/orphan-registry.ts
22455
- import { execFile as execFile4 } from "node:child_process";
22456
- import { mkdir as mkdir3, readFile as readFile5, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22846
+ import { mkdir as mkdir3, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
22457
22847
  import { basename, dirname as dirname5 } from "node:path";
22458
-
22459
- // src/runs/process-tree.ts
22460
- import { execFile as execFile3, spawn as spawn7 } from "node:child_process";
22461
- var KILL_GRACE_MS = 3e3;
22462
- function readProcessTable() {
22463
- return new Promise((resolve8) => {
22464
- execFile3("ps", ["-axo", "pid=,ppid="], { maxBuffer: 32 * 1024 * 1024, timeout: 2e3 }, (error62, stdout) => {
22465
- if (error62) return resolve8([]);
22466
- resolve8(stdout.split("\n").flatMap((line) => {
22467
- const [pid, ppid] = line.trim().split(/\s+/).map(Number);
22468
- return pid && ppid !== void 0 && Number.isFinite(ppid) ? [{ pid, ppid }] : [];
22469
- }));
22470
- });
22471
- });
22472
- }
22473
- async function listDescendants(rootPid) {
22474
- const rows = await readProcessTable();
22475
- const children = /* @__PURE__ */ new Map();
22476
- for (const row of rows) children.set(row.ppid, [...children.get(row.ppid) ?? [], row.pid]);
22477
- const out = [];
22478
- const queue = [...children.get(rootPid) ?? []];
22479
- while (queue.length > 0) {
22480
- const pid = queue.shift();
22481
- if (out.includes(pid)) continue;
22482
- out.push(pid);
22483
- queue.push(...children.get(pid) ?? []);
22484
- }
22485
- return out;
22486
- }
22487
- function signal(pid, sig) {
22488
- try {
22489
- process.kill(pid, sig);
22490
- } catch {
22491
- }
22492
- }
22493
- function alive(pid) {
22494
- try {
22495
- process.kill(pid, 0);
22496
- return true;
22497
- } catch {
22498
- return false;
22499
- }
22500
- }
22501
- var sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
22502
- async function killProcessTree(rootPid, graceMs = KILL_GRACE_MS) {
22503
- if (!Number.isInteger(rootPid) || rootPid <= 1) return;
22504
- if (process.platform === "win32") {
22505
- await new Promise((resolve8) => {
22506
- const child = spawn7("taskkill", ["/PID", String(rootPid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
22507
- child.once("error", () => resolve8());
22508
- child.once("close", () => resolve8());
22509
- });
22510
- return;
22511
- }
22512
- const descendants = await listDescendants(rootPid);
22513
- signal(-rootPid, "SIGTERM");
22514
- signal(rootPid, "SIGTERM");
22515
- for (const pid of descendants) signal(pid, "SIGTERM");
22516
- const members2 = [rootPid, ...descendants];
22517
- const deadline = Date.now() + graceMs;
22518
- while (Date.now() < deadline && members2.some(alive)) await sleep(100);
22519
- const late = alive(rootPid) ? await listDescendants(rootPid) : [];
22520
- signal(-rootPid, "SIGKILL");
22521
- for (const pid of [...members2, ...late]) if (alive(pid)) signal(pid, "SIGKILL");
22522
- }
22523
-
22524
- // src/runs/orphan-registry.ts
22525
22848
  var OrphanRegistry = class {
22526
22849
  constructor(file2) {
22527
22850
  this.file = file2;
@@ -22549,7 +22872,7 @@ var OrphanRegistry = class {
22549
22872
  async reapPrevious() {
22550
22873
  let previous = [];
22551
22874
  try {
22552
- previous = JSON.parse(await readFile5(this.file, "utf8"));
22875
+ previous = JSON.parse(await readFile6(this.file, "utf8"));
22553
22876
  } catch {
22554
22877
  return [];
22555
22878
  }
@@ -22569,18 +22892,13 @@ var OrphanRegistry = class {
22569
22892
  }
22570
22893
  };
22571
22894
  function commandOf(pid) {
22572
- if (process.platform === "win32") return Promise.resolve(void 0);
22573
- return new Promise((resolve8) => {
22574
- execFile4("ps", ["-o", "command=", "-p", String(pid)], { timeout: 2e3 }, (error62, stdout) => {
22575
- resolve8(error62 ? void 0 : stdout.trim() || void 0);
22576
- });
22577
- });
22895
+ return currentPlatform.processCommandLine(pid);
22578
22896
  }
22579
22897
 
22580
22898
  // src/runs/run-supervisor.ts
22581
22899
  import { spawn as spawn8 } from "node:child_process";
22582
- import { mkdir as mkdir5, realpath as realpath2, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
22583
- import { basename as basename3, isAbsolute as isAbsolute3, join as join9, relative as relative2, resolve as resolve3 } from "node:path";
22900
+ import { mkdir as mkdir5, realpath as realpath2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
22901
+ import { basename as basename3, isAbsolute as isAbsolute3, join as join12, relative as relative2, resolve as resolve3 } from "node:path";
22584
22902
  import { createInterface as createInterface3 } from "node:readline";
22585
22903
 
22586
22904
  // src/session/terminal-line-sanitizer.ts
@@ -22706,8 +23024,8 @@ function clipToCharacterBudget(rows, budget) {
22706
23024
  // src/runs/task-attachments.ts
22707
23025
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
22708
23026
  import { constants as constants2 } from "node:fs";
22709
- import { lstat, mkdir as mkdir4, open as open2, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
22710
- import { basename as basename2, isAbsolute as isAbsolute2, join as join8, relative } from "node:path";
23027
+ import { lstat, mkdir as mkdir4, open as open3, realpath, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
23028
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join11, relative } from "node:path";
22711
23029
  function within(root, path) {
22712
23030
  const segment = relative(root, path);
22713
23031
  return segment === "" || !segment.startsWith("..") && !isAbsolute2(segment);
@@ -22715,7 +23033,7 @@ function within(root, path) {
22715
23033
  async function attachmentDirectory(workdir, messageId) {
22716
23034
  let directory = workdir;
22717
23035
  for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
22718
- directory = join8(directory, segment);
23036
+ directory = join11(directory, segment);
22719
23037
  await mkdir4(directory, { mode: 448 }).catch((error62) => {
22720
23038
  if (error62.code !== "EEXIST") throw error62;
22721
23039
  });
@@ -22723,7 +23041,7 @@ async function attachmentDirectory(workdir, messageId) {
22723
23041
  if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
22724
23042
  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");
22725
23043
  }
22726
- if (segment === ".echo") await writeFile4(join8(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
23044
+ if (segment === ".echo") await writeFile4(join11(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
22727
23045
  if (error62.code !== "EEXIST") throw error62;
22728
23046
  });
22729
23047
  }
@@ -22732,7 +23050,7 @@ async function attachmentDirectory(workdir, messageId) {
22732
23050
  async function matches(path, size, sha256, signal2) {
22733
23051
  const metadata = await lstat(path).catch(() => void 0);
22734
23052
  if (!metadata?.isFile() || metadata.isSymbolicLink() || metadata.size !== size) return false;
22735
- const file2 = await open2(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
23053
+ const file2 = await open3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
22736
23054
  try {
22737
23055
  const hash2 = createHash2("sha256");
22738
23056
  let read = 0;
@@ -22760,9 +23078,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
22760
23078
  const characters = Array.from(basename2(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
22761
23079
  while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
22762
23080
  const name = characters.join("") || "attachment";
22763
- const path = join8(directory, `${file2.file_id}-${name}`);
23081
+ const path = join11(directory, `${file2.file_id}-${name}`);
22764
23082
  if (!await matches(path, file2.size, file2.sha256, signal2)) {
22765
- const temporary = join8(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
23083
+ const temporary = join11(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
22766
23084
  try {
22767
23085
  await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
22768
23086
  signal2.throwIfAborted();
@@ -22787,6 +23105,7 @@ ${paths.join("\n")}`;
22787
23105
 
22788
23106
  // src/runs/run-supervisor.ts
22789
23107
  var COMPLETION_EXIT_GRACE_MS = 15e3;
23108
+ var EXIT_OUTPUT_GRACE_MS = 2e3;
22790
23109
  var RECENT_RUN_TTL_MS = 10 * 6e4;
22791
23110
  var MAX_RECENT_RUNS = 100;
22792
23111
  var MAX_ERROR_ROWS = 40;
@@ -22976,15 +23295,16 @@ var RunSupervisor = class {
22976
23295
  reasoningEffort: payload.reasoning_effort,
22977
23296
  workdir
22978
23297
  });
23298
+ 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`);
22979
23299
  let child;
22980
23300
  try {
22981
23301
  child = spawn8(launch.executable, launch.args, {
22982
23302
  cwd: workdir,
22983
23303
  env: launch.env,
22984
- detached: process.platform !== "win32",
23304
+ detached: currentPlatform.runsInOwnProcessGroup,
22985
23305
  shell: false,
22986
23306
  windowsHide: true,
22987
- stdio: [provider.startInput ? "pipe" : "ignore", "pipe", "pipe"]
23307
+ stdio: [provider.startInput || launch.stdin !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
22988
23308
  });
22989
23309
  } catch (error62) {
22990
23310
  return refuse(`\u65E0\u6CD5\u542F\u52A8 ${provider.id}\uFF1A${errorMessage(error62)}`);
@@ -23003,7 +23323,6 @@ var RunSupervisor = class {
23003
23323
  agentType: provider.id,
23004
23324
  provider,
23005
23325
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
23006
- ...provider.createRunParser ? { stream: provider.createRunParser() } : {},
23007
23326
  ...sessionsBefore ? { sessionsBefore } : {},
23008
23327
  ...unverifiedResume ? { unverifiedResume: payload } : {},
23009
23328
  prompt: payload.prompt,
@@ -23026,6 +23345,16 @@ var RunSupervisor = class {
23026
23345
  lastLine: "",
23027
23346
  lastOutputAt: Date.now()
23028
23347
  };
23348
+ if (provider.createRunParser) {
23349
+ run2.stream = provider.createRunParser({
23350
+ workdir,
23351
+ sessionId,
23352
+ startedAt: run2.startedAt,
23353
+ emit: (parsed) => {
23354
+ if (this.active.has(run2.runId)) this.applyParsed(run2, parsed, "");
23355
+ }
23356
+ });
23357
+ }
23029
23358
  this.active.set(run2.runId, run2);
23030
23359
  this.preparing.delete(run2.runId);
23031
23360
  this.unreported.add(run2.runId);
@@ -23038,6 +23367,7 @@ var RunSupervisor = class {
23038
23367
  this.logger.info("run-started", { runId: run2.runId, agentType: provider.id, pid: run2.pid, resume: Boolean(sessionId) });
23039
23368
  let spawnError = "";
23040
23369
  child.stdin?.on("error", () => void 0);
23370
+ if (launch.stdin !== void 0 && !provider.startInput) child.stdin?.end(launch.stdin, "utf8");
23041
23371
  child.once("error", (error62) => {
23042
23372
  spawnError = error62.message;
23043
23373
  });
@@ -23065,7 +23395,22 @@ var RunSupervisor = class {
23065
23395
  }
23066
23396
  }
23067
23397
  });
23068
- child.once("close", (code2, signal3) => void this.onExit(run2, code2, signal3, spawnError));
23398
+ let exited = false;
23399
+ const finish = (code2, signal3) => {
23400
+ if (exited) return;
23401
+ exited = true;
23402
+ void this.onExit(run2, code2, signal3, spawnError);
23403
+ };
23404
+ child.once("exit", (code2, signal3) => {
23405
+ run2.timers.push(setTimeout(() => {
23406
+ if (exited) return;
23407
+ this.logger.warn("run-output-held", { runId: run2.runId, pid: run2.pid });
23408
+ child.stdout?.destroy();
23409
+ child.stderr?.destroy();
23410
+ finish(code2, signal3);
23411
+ }, EXIT_OUTPUT_GRACE_MS));
23412
+ });
23413
+ child.once("close", (code2, signal3) => finish(code2, signal3));
23069
23414
  if (provider.startInput) {
23070
23415
  child.once("spawn", () => {
23071
23416
  try {
@@ -23141,7 +23486,8 @@ var RunSupervisor = class {
23141
23486
  }
23142
23487
  async onExit(run2, code2, signal2, spawnError) {
23143
23488
  for (const timer of run2.timers) clearTimeout(timer);
23144
- if (run2.stream) this.applyParsed(run2, run2.stream.end(), "");
23489
+ run2.timers = [];
23490
+ if (run2.stream) this.applyParsed(run2, await run2.stream.end(), "");
23145
23491
  this.active.delete(run2.runId);
23146
23492
  this.orphans?.remove(run2.runId);
23147
23493
  if (run2.eventTimer) clearTimeout(run2.eventTimer);
@@ -23277,13 +23623,13 @@ var RunSupervisor = class {
23277
23623
  async prepareChatAttachments(payload) {
23278
23624
  if (!payload.attachments?.length) return [];
23279
23625
  if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
23280
- const directory = join9(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23626
+ const directory = join12(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
23281
23627
  await mkdir5(directory, { recursive: true, mode: 448 });
23282
23628
  const files = [];
23283
23629
  for (const attachment of payload.attachments) {
23284
23630
  const name = basename3(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
23285
- const path = join9(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23286
- const existing = await stat2(path).catch(() => void 0);
23631
+ const path = join12(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
23632
+ const existing = await stat3(path).catch(() => void 0);
23287
23633
  if (!existing?.isFile()) {
23288
23634
  const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
23289
23635
  await writeFile5(path, data, { mode: 384 });
@@ -23321,10 +23667,15 @@ var RunSupervisor = class {
23321
23667
  if (live) return live;
23322
23668
  return [...this.recent.values()].filter((run2) => run2.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
23323
23669
  };
23324
- const target = byId(query.runId) ?? byWorkstation(query.workstationId);
23325
- if (!target) {
23326
- return { status: "idle", lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23327
- }
23670
+ const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: void 0 };
23671
+ if (query.runId) {
23672
+ const run2 = byId(query.runId);
23673
+ if (!run2) return { ...empty, status: this.preparing.has(query.runId) ? "running" : "idle", run_id: query.runId };
23674
+ const read2 = run2.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23675
+ return { ...read2, status: this.active.has(run2.runId) ? "running" : "finished", run_id: run2.runId };
23676
+ }
23677
+ const target = byWorkstation(query.workstationId);
23678
+ if (!target) return { ...empty, status: "idle" };
23328
23679
  const read = target.tail.read(beforeCursor === void 0 ? { limit } : { limit, beforeCursor });
23329
23680
  return { ...read, status: this.active.has(target.runId) ? "running" : "finished", run_id: target.runId };
23330
23681
  }
@@ -23514,17 +23865,17 @@ var GatewayClient = class {
23514
23865
  };
23515
23866
 
23516
23867
  // src/workspace/directory-browser.ts
23517
- import { readdir, realpath as realpath3, stat as stat3 } from "node:fs/promises";
23518
- import { homedir as homedir7 } from "node:os";
23868
+ import { readdir as readdir2, realpath as realpath3, stat as stat4 } from "node:fs/promises";
23869
+ import { homedir as homedir8 } from "node:os";
23519
23870
  import { dirname as dirname6, parse as parse3, resolve as resolve4 } from "node:path";
23520
23871
  var MAX_ENTRIES = 1e3;
23521
23872
  async function listDirectory(requested, allowedRoots) {
23522
- const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir7()) || homedir7();
23873
+ const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir8()) || homedir8();
23523
23874
  const directory = await realpath3(resolve4(raw)).catch(() => {
23524
23875
  throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
23525
23876
  });
23526
- if (!(await stat3(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23527
- const entries = await readdir(directory, { withFileTypes: true }).catch((error62) => {
23877
+ if (!(await stat4(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
23878
+ const entries = await readdir2(directory, { withFileTypes: true }).catch((error62) => {
23528
23879
  throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
23529
23880
  });
23530
23881
  const byName = (a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base", numeric: true });
@@ -23537,8 +23888,8 @@ async function listDirectory(requested, allowedRoots) {
23537
23888
  else if (entry.isFile()) files.push(item);
23538
23889
  }
23539
23890
  const parent = dirname6(directory);
23540
- const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir7() }];
23541
- for (const root of allowedRoots) if (root !== homedir7()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23891
+ const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir8() }];
23892
+ for (const root of allowedRoots) if (root !== homedir8()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root });
23542
23893
  places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
23543
23894
  return {
23544
23895
  path: directory,
@@ -23552,9 +23903,9 @@ async function listDirectory(requested, allowedRoots) {
23552
23903
 
23553
23904
  // src/workspace/workspace-manager.ts
23554
23905
  import { spawn as spawn9 } from "node:child_process";
23555
- 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";
23556
- import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
23557
- import { isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5 } from "node:path";
23906
+ 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";
23907
+ import { homedir as homedir9, tmpdir as tmpdir2 } from "node:os";
23908
+ import { isAbsolute as isAbsolute4, join as join13, relative as relative3, resolve as resolve5 } from "node:path";
23558
23909
  var MAX_NODES = 2e3;
23559
23910
  var MAX_DIRECTORY_ENTRIES = 12e3;
23560
23911
  var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
@@ -23602,7 +23953,7 @@ var WorkspaceManager = class {
23602
23953
  };
23603
23954
  }
23604
23955
  validateRootPath(value) {
23605
- const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir8());
23956
+ const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir9());
23606
23957
  const root = resolve5(raw);
23607
23958
  if (!isAbsolute4(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
23608
23959
  if (relative3(root, resolve5(root, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
@@ -23619,7 +23970,7 @@ var WorkspaceManager = class {
23619
23970
  requestedPaths.add(relativePath);
23620
23971
  const target = this.resolveWithinRoot(rootPath, relativePath);
23621
23972
  try {
23622
- const metadata = await stat4(target).catch(() => void 0);
23973
+ const metadata = await stat5(target).catch(() => void 0);
23623
23974
  if (metadata) {
23624
23975
  if (!metadata.isDirectory()) {
23625
23976
  throw new Error("The existing workspace path is not a directory");
@@ -23677,7 +24028,7 @@ var WorkspaceManager = class {
23677
24028
  let created = false;
23678
24029
  let metadata;
23679
24030
  try {
23680
- metadata = await stat4(target);
24031
+ metadata = await stat5(target);
23681
24032
  } catch {
23682
24033
  }
23683
24034
  if (!metadata) {
@@ -23777,7 +24128,7 @@ var WorkspaceManager = class {
23777
24128
  }
23778
24129
  async scanTree(rootPath, maxDepth, scanRoots) {
23779
24130
  const resolvedRoot = await realpath4(rootPath);
23780
- const rootMetadata = await stat4(resolvedRoot);
24131
+ const rootMetadata = await stat5(resolvedRoot);
23781
24132
  if (!rootMetadata.isDirectory()) throw new Error("The workspace root is not a directory");
23782
24133
  const nodes = [];
23783
24134
  let entriesRead = 0;
@@ -23832,7 +24183,7 @@ var WorkspaceManager = class {
23832
24183
  const target = this.resolveWithinRoot(resolvedRoot, relativePath);
23833
24184
  let metadata;
23834
24185
  try {
23835
- metadata = await stat4(target);
24186
+ metadata = await stat5(target);
23836
24187
  } catch (error62) {
23837
24188
  this.logger.warn("workspace-scan-root-missing", {
23838
24189
  rootPath: target,
@@ -23929,12 +24280,12 @@ var WorkspaceManager = class {
23929
24280
  }
23930
24281
  async createGitAuthEnvironment(auth) {
23931
24282
  if (!auth) return void 0;
23932
- const directory = await mkdtemp(join10(tmpdir2(), "toc-ocra-git-auth-"));
24283
+ const directory = await mkdtemp(join13(tmpdir2(), "toc-ocra-git-auth-"));
23933
24284
  const isWindows = process.platform === "win32";
23934
- const scriptPath = join10(directory, isWindows ? "askpass.cmd" : "askpass.sh");
24285
+ const scriptPath = join13(directory, isWindows ? "askpass.cmd" : "askpass.sh");
23935
24286
  let script;
23936
24287
  if (isWindows) {
23937
- const helperPath = join10(directory, "askpass.cjs");
24288
+ const helperPath = join13(directory, "askpass.cjs");
23938
24289
  await writeFile6(
23939
24290
  helperPath,
23940
24291
  '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',
@@ -24084,7 +24435,7 @@ var AgentRuntime = class {
24084
24435
  }
24085
24436
  };
24086
24437
  this.workspaces = new WorkspaceManager(config2, this.logger);
24087
- this.orphans = new OrphanRegistry(join11(config2.dataDir, "active-runs.json"));
24438
+ this.orphans = new OrphanRegistry(join14(config2.dataDir, "active-runs.json"));
24088
24439
  this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
24089
24440
  }
24090
24441
  config;
@@ -24731,7 +25082,7 @@ function agentPackageRoot() {
24731
25082
  const packagePath = resolve6(directory, "package.json");
24732
25083
  if (existsSync5(packagePath)) {
24733
25084
  try {
24734
- const info = JSON.parse(readFileSync5(packagePath, "utf8"));
25085
+ const info = JSON.parse(readFileSync6(packagePath, "utf8"));
24735
25086
  if (info.name === PACKAGE_NAME && typeof info.version === "string") return directory;
24736
25087
  } catch {
24737
25088
  }
@@ -24743,7 +25094,7 @@ function agentPackageRoot() {
24743
25094
  }
24744
25095
  function agentVersion() {
24745
25096
  const root = agentPackageRoot();
24746
- return root ? JSON.parse(readFileSync5(resolve6(root, "package.json"), "utf8")).version : "unknown";
25097
+ return root ? JSON.parse(readFileSync6(resolve6(root, "package.json"), "utf8")).version : "unknown";
24747
25098
  }
24748
25099
  async function runService(options = {}) {
24749
25100
  const version2 = agentVersion();
@@ -24792,7 +25143,7 @@ async function runService(options = {}) {
24792
25143
  }
24793
25144
 
24794
25145
  // src/index.ts
24795
- var { currentInstallation, installShared, ensureIdle, compareVersions } = createRequire(import.meta.url)(join12(agentPackageRoot(), "scripts", "installation.cjs"));
25146
+ var { currentInstallation, installShared, ensureIdle, compareVersions } = createRequire(import.meta.url)(join15(agentPackageRoot(), "scripts", "installation.cjs"));
24796
25147
  async function run() {
24797
25148
  try {
24798
25149
  await runService();
@@ -24894,8 +25245,8 @@ async function update(args) {
24894
25245
  const customConfig = option(args, "--config");
24895
25246
  if (customConfig) process.env.TOC_OCRA_CONFIG = resolve7(customConfig);
24896
25247
  await ensureIdle();
24897
- const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
24898
- const temporary = mkdtempSync(join12(tmpdir3(), "toc-ocra-update-"));
25248
+ const npmPath = resolveCliCommand("npm");
25249
+ const temporary = mkdtempSync(join15(tmpdir3(), "toc-ocra-update-"));
24899
25250
  try {
24900
25251
  const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
24901
25252
  if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -24922,16 +25273,17 @@ async function update(args) {
24922
25273
  }
24923
25274
  const archive = Buffer.concat(chunks);
24924
25275
  if (`sha512-${createHash4("sha512").update(archive).digest("base64")}` !== dist.integrity) throw new Error("\u8BBE\u5907\u4EE3\u7406\u5B89\u88C5\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u5347\u7EA7");
24925
- const archivePath = join12(temporary, "toc-ocra.tgz");
25276
+ const archivePath = join15(temporary, "toc-ocra.tgz");
24926
25277
  writeFileSync3(archivePath, archive, { mode: 384 });
24927
- const install = spawnSync(npmCommand, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath], { stdio: "inherit", shell: false });
25278
+ const npm = directLaunch2(npmPath, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath]);
25279
+ const install = spawnSync(npm.executable, npm.args, { stdio: "inherit", shell: false, windowsHide: true });
24928
25280
  if (install.error) throw install.error;
24929
25281
  if (install.status !== 0) {
24930
25282
  process.exitCode = install.status ?? 1;
24931
25283
  return;
24932
25284
  }
24933
25285
  const previousVersion = agentVersion();
24934
- const current = await installShared(join12(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync6(defaultConfigPath()) });
25286
+ const current = await installShared(join15(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync6(defaultConfigPath()) });
24935
25287
  if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
24936
25288
  `);
24937
25289
  else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
@@ -24957,7 +25309,7 @@ async function main() {
24957
25309
  const shared = currentInstallation();
24958
25310
  if (root && root.split(/[\\/]/).includes("node_modules") && root !== shared?.root) {
24959
25311
  const selected = !shared || compareVersions(agentVersion(), shared.version) > 0 ? await installShared(root) : shared;
24960
- await import(pathToFileURL(join12(selected.root, "dist", "cli", "cli.mjs")).href);
25312
+ await import(pathToFileURL(join15(selected.root, "dist", "cli", "cli.mjs")).href);
24961
25313
  return;
24962
25314
  }
24963
25315
  const command = process.argv[2] ?? "run";