@carrieros/cli 0.1.0 → 0.3.0

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 (104) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,68 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+ /**
4
+ * Hand a URL to the OS default browser.
5
+ *
6
+ * Detached + ignored stdio so the browser never becomes a child whose output
7
+ * bleeds into the transcript or whose lifetime is tied to the shell.
8
+ */
9
+ /**
10
+ * Only http(s) may reach the OS opener. A `file:` or `javascript:` URL must not
11
+ * launch anything just because it arrived in an API response. Callers check this
12
+ * BEFORE announcing the open, so a refusal never reads as a half-done action.
13
+ *
14
+ * @returns the normalized URL, or an error message explaining the refusal.
15
+ */
16
+ export function checkUrl(url) {
17
+ let parsed;
18
+ try {
19
+ parsed = new URL(url);
20
+ }
21
+ catch {
22
+ return { ok: false, reason: `Not a valid URL: ${url}` };
23
+ }
24
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
25
+ return { ok: false, reason: `Refusing to open a ${parsed.protocol} URL.` };
26
+ }
27
+ return { ok: true, url: parsed.toString() };
28
+ }
29
+ /**
30
+ * The program and argv that open `url`, without any shell.
31
+ *
32
+ * Windows used to go through `cmd /c start "" <url>`. cmd.exe parses its whole
33
+ * command line, and `&`, `|` and `^` are legal in a URL query — so a link like
34
+ * `https://example.com/?a=1&calc` from a search result ran `calc`. rundll32
35
+ * hands the URL to the shell's protocol handler as data; nothing parses it as a
36
+ * command. It is named by absolute path under SystemRoot so that no PATH entry
37
+ * or folder can substitute a different `rundll32`.
38
+ *
39
+ * Takes an ALREADY-CHECKED url: callers go through checkUrl first, which only
40
+ * lets http(s) through and percent-encodes spaces and quotes.
41
+ */
42
+ export function browserLaunchCommand(url, platform = process.platform) {
43
+ if (platform === "win32") {
44
+ const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
45
+ return {
46
+ program: path.win32.join(systemRoot, "System32", "rundll32.exe"),
47
+ args: ["url.dll,FileProtocolHandler", url]
48
+ };
49
+ }
50
+ if (platform === "darwin")
51
+ return { program: "open", args: [url] };
52
+ return { program: "xdg-open", args: [url] };
53
+ }
54
+ /** Launch detached with no shell and no stdio. Exported for the regression test. */
55
+ export function spawnOpener(program, args) {
56
+ const child = spawn(program, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
57
+ child.on("error", () => {
58
+ /* No browser / headless box — the caller already printed the URL. */
59
+ });
60
+ child.unref();
61
+ }
62
+ export function openUrl(url) {
63
+ const checked = checkUrl(url);
64
+ if (!checked.ok)
65
+ throw new Error(checked.reason);
66
+ const { program, args } = browserLaunchCommand(checked.url);
67
+ spawnOpener(program, args);
68
+ }
@@ -1,4 +1,5 @@
1
1
  import { c } from "../ui/colors.js";
2
+ import { screenActive, screenPrint } from "../ui/screen.js";
2
3
  import { icon } from "../ui/ui.js";
3
4
  /** Status glyphs (consistent icon set — never emojis). */
4
5
  export const glyph = {
@@ -7,6 +8,12 @@ export const glyph = {
7
8
  err: icon.err
8
9
  };
9
10
  export const line = (msg = "") => {
11
+ // In the interactive shell the screen owns the terminal: route transcript
12
+ // output through it (so it lands above the pinned composer, not over it).
13
+ if (screenActive()) {
14
+ screenPrint(msg.length ? msg.split("\n") : [""]);
15
+ return;
16
+ }
10
17
  process.stdout.write(msg + "\n");
11
18
  };
12
19
  export const success = (msg) => line(`${icon.ok} ${msg}`);
@@ -16,16 +23,17 @@ export const errorLine = (msg) => line(`${icon.err} ${msg}`);
16
23
  export const heading = (text) => line("\n" + c.title(text));
17
24
  /** Left-aligned label + value, dim label. Used across whoami / usage / doctor. */
18
25
  export function kv(label, value, width = 14) {
19
- line(` ${c.label(label.padEnd(width))}${value}`);
26
+ // A label wider than the column keeps its own separator — without this an
27
+ // over-long label runs straight into its value with no space between them.
28
+ const pad = label.length >= width ? label + " " : label.padEnd(width);
29
+ line(` ${c.label(pad)}${value}`);
20
30
  }
21
31
  /** The focused-chat header (used by `cos chat`). */
22
- export function printBanner(scope, mode, modelLabel) {
32
+ export function printBanner(_scope, mode, modelLabel) {
23
33
  line();
24
- line(c.wordmark(" Carrier OS CLI"));
34
+ line(c.brandFixed.bold(" Carrier OS CLI"));
25
35
  line(c.dim(" Ready."));
26
36
  line();
27
- kv("Workspace", scope?.workspace.name ?? c.dim("—"));
28
- kv("Project", scope?.project.name ?? c.dim("—"));
29
37
  kv("Mode", capitalize(mode));
30
38
  kv("Model", modelLabel);
31
39
  line();
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Am I running as the packaged Windows executable, or from a Node/npm checkout?
3
+ *
4
+ * A Single Executable Application reports this through `node:sea`. Several
5
+ * behaviours differ between the two: a packaged build has no npm to self-update
6
+ * through, no package.json on disk to read a version from, and ships its native
7
+ * helpers prebuilt beside the .exe. Each of those checks this rather than
8
+ * guessing from paths.
9
+ */
10
+ import { createRequire } from "node:module";
11
+ export function isPackaged() {
12
+ try {
13
+ // `node:sea` is a Node 20+ builtin; resolving it against the executable
14
+ // path works in both the ESM dev build and the bundled CJS executable.
15
+ const require = createRequire(process.execPath);
16
+ const sea = require("node:sea");
17
+ return typeof sea?.isSea === "function" ? sea.isSea() : false;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ /** Where to point someone at a new packaged build (no npm involved). */
24
+ export const PACKAGED_DOWNLOAD_URL = "https://carrieros.ai/cli";
@@ -0,0 +1,406 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { StringDecoder } from "node:string_decoder";
5
+ import { buildChildEnv } from "./env-policy.js";
6
+ import { JOB_HELPER_FAILURE_EXIT, JobHelperError, ensureJobHelper } from "./job-helper.js";
7
+ import { isInside } from "./local-files.js";
8
+ /**
9
+ * Runs ONE local program, contained, bounded and redacted.
10
+ *
11
+ * This is the only way a command proposed by a model may ever reach the
12
+ * machine, and it is deliberately unaware of models, approval or policy — the
13
+ * caller decides WHETHER to run something; this decides HOW, and refuses
14
+ * anything it cannot run safely:
15
+ *
16
+ * - no shell, ever: a command is `program` + `args[]`, started by absolute path
17
+ * through the Job Object helper. `.cmd`/`.bat`/scripts, shells and
18
+ * interpreters-as-shells are refused by name, and shell operators are refused
19
+ * even though, without a shell, they would only be text.
20
+ * - npm/pnpm/yarn run as `node <their JS entry>`, never through `npm.cmd`.
21
+ * - the working directory must resolve, by realpath, inside the project root.
22
+ * - the environment comes from an allowlist (env-policy.ts).
23
+ * - every descendant lives in a kill-on-close Job Object: timeout, abort and
24
+ * the CLI exiting all end the whole tree.
25
+ * - output is redacted line by line before anyone sees it, and only a bounded
26
+ * head and tail are kept.
27
+ */
28
+ export class RunnerError extends Error {
29
+ code;
30
+ constructor(code, message) {
31
+ super(message);
32
+ this.code = code;
33
+ this.name = "RunnerError";
34
+ }
35
+ }
36
+ /** Hard ceiling on any single command; the server holds a call for 15 minutes. */
37
+ export const MAX_TIMEOUT_MS = 14 * 60 * 1000;
38
+ export const DEFAULT_HEAD_BYTES = 16 * 1024;
39
+ export const DEFAULT_TAIL_BYTES = 44 * 1024;
40
+ /** Refused as programs regardless of policy: each is a way back to a shell. */
41
+ const DENIED_PROGRAMS = new Set([
42
+ "cmd",
43
+ "command",
44
+ "powershell",
45
+ "powershell_ise",
46
+ "pwsh",
47
+ "bash",
48
+ "sh",
49
+ "zsh",
50
+ "wsl",
51
+ "wslhost",
52
+ "wscript",
53
+ "cscript",
54
+ "mshta",
55
+ "rundll32",
56
+ "regsvr32",
57
+ "start",
58
+ "conhost",
59
+ "runas",
60
+ "npx",
61
+ "explorer"
62
+ ]);
63
+ /** Characters that only mean something to a shell. */
64
+ const SHELL_OPERATOR = /[&|;<>`\r\n\0]|\$\(/;
65
+ // ── Validation ───────────────────────────────────────────────────────────────
66
+ export function validateArgs(args) {
67
+ if (!Array.isArray(args) || args.some((a) => typeof a !== "string")) {
68
+ throw new RunnerError("INVALID_ARGUMENTS", "args must be an array of strings.");
69
+ }
70
+ if (args.length > 64)
71
+ throw new RunnerError("INVALID_ARGUMENTS", "Too many arguments.");
72
+ for (const a of args) {
73
+ if (a.length > 4096)
74
+ throw new RunnerError("INVALID_ARGUMENTS", "An argument is too long.");
75
+ if (SHELL_OPERATOR.test(a)) {
76
+ throw new RunnerError("SHELL_OPERATOR", `Shell syntax is not accepted in arguments: ${JSON.stringify(a.slice(0, 80))}`);
77
+ }
78
+ }
79
+ return args;
80
+ }
81
+ /** Realpath-contained working directory, or a RunnerError. */
82
+ export function resolveCwd(cwd, root) {
83
+ if (typeof cwd !== "string" || !cwd.trim())
84
+ throw new RunnerError("INVALID_CWD", "A working directory is required.");
85
+ const raw = cwd.trim();
86
+ if (raw.includes("\0") || raw.startsWith("\\\\") || raw.split(/[\\/]+/).includes("..")) {
87
+ throw new RunnerError("OUTSIDE_WORKSPACE", "The working directory must stay inside the project.");
88
+ }
89
+ const realRoot = fs.realpathSync.native(root);
90
+ const abs = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(realRoot, raw);
91
+ if (!isInside(realRoot, abs) && !isInside(root, abs)) {
92
+ throw new RunnerError("OUTSIDE_WORKSPACE", "The working directory must be inside the project.");
93
+ }
94
+ let real;
95
+ try {
96
+ real = fs.realpathSync.native(abs);
97
+ }
98
+ catch {
99
+ throw new RunnerError("INVALID_CWD", "The working directory does not exist.");
100
+ }
101
+ if (!isInside(realRoot, real)) {
102
+ throw new RunnerError("OUTSIDE_WORKSPACE", "The working directory links outside the project.");
103
+ }
104
+ if (!fs.statSync(real).isDirectory())
105
+ throw new RunnerError("INVALID_CWD", "The working directory is not a folder.");
106
+ return real;
107
+ }
108
+ function findOnPath(exeName, pathValue) {
109
+ for (const dir of pathValue.split(path.delimiter)) {
110
+ if (!dir || !path.isAbsolute(dir))
111
+ continue;
112
+ const candidate = path.join(dir, exeName);
113
+ try {
114
+ if (fs.statSync(candidate).isFile())
115
+ return candidate;
116
+ }
117
+ catch {
118
+ /* not here */
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ /** A package manager's JavaScript entry point, found next to its .cmd shim. */
124
+ function jsEntry(shim, pathValue, rel) {
125
+ const candidates = [path.join(path.dirname(process.execPath), "node_modules", ...rel)];
126
+ const dir = findOnPath(shim, pathValue);
127
+ if (dir)
128
+ candidates.push(path.join(path.dirname(dir), "node_modules", ...rel));
129
+ for (const c of candidates) {
130
+ try {
131
+ if (fs.statSync(c).isFile())
132
+ return c;
133
+ }
134
+ catch {
135
+ /* next */
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ /**
141
+ * The absolute argv prefix for a program name. Names only — a path, an
142
+ * extension other than .exe, or a shell/interpreter name is refused.
143
+ */
144
+ export function resolveProgram(program, pathValue) {
145
+ if (typeof program !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(program)) {
146
+ throw new RunnerError("INVALID_PROGRAM", "The program must be a bare name such as npm, node or git.");
147
+ }
148
+ const lower = program.toLowerCase();
149
+ const ext = path.extname(lower);
150
+ if (ext && ext !== ".exe") {
151
+ throw new RunnerError("PROGRAM_DENIED", `${program} cannot be run directly — only programs, not scripts or shell files.`);
152
+ }
153
+ const name = ext ? lower.slice(0, -ext.length) : lower;
154
+ if (DENIED_PROGRAMS.has(name))
155
+ throw new RunnerError("PROGRAM_DENIED", `${program} is not allowed.`);
156
+ switch (name) {
157
+ case "node":
158
+ return [process.execPath];
159
+ case "npm": {
160
+ const entry = jsEntry("npm.cmd", pathValue, ["npm", "bin", "npm-cli.js"]);
161
+ if (!entry)
162
+ throw new RunnerError("PROGRAM_NOT_FOUND", "npm was not found next to Node.");
163
+ return [process.execPath, entry];
164
+ }
165
+ case "pnpm": {
166
+ const entry = jsEntry("pnpm.cmd", pathValue, ["pnpm", "bin", "pnpm.cjs"]);
167
+ if (!entry)
168
+ throw new RunnerError("PROGRAM_NOT_FOUND", "pnpm was not found.");
169
+ return [process.execPath, entry];
170
+ }
171
+ case "yarn": {
172
+ const entry = jsEntry("yarn.cmd", pathValue, ["yarn", "bin", "yarn.js"]);
173
+ if (!entry)
174
+ throw new RunnerError("PROGRAM_NOT_FOUND", "yarn was not found.");
175
+ return [process.execPath, entry];
176
+ }
177
+ default: {
178
+ const exe = findOnPath(`${name}.exe`, pathValue);
179
+ if (!exe)
180
+ throw new RunnerError("PROGRAM_NOT_FOUND", `${program} was not found on PATH.`);
181
+ return [exe];
182
+ }
183
+ }
184
+ }
185
+ // ── Output ───────────────────────────────────────────────────────────────────
186
+ /**
187
+ * The nearest index at or after (`up`) / at or before (`down`) `i` that starts
188
+ * a UTF-8 character. `up` always returns at least 1 when i ≥ 1, so a trim
189
+ * always makes progress.
190
+ */
191
+ export function utf8Boundary(buf, i, dir) {
192
+ let at = Math.max(0, Math.min(i, buf.length));
193
+ const continuation = (n) => n < buf.length && (buf[n] & 0xc0) === 0x80;
194
+ if (dir === "up") {
195
+ while (continuation(at))
196
+ at += 1;
197
+ return at;
198
+ }
199
+ while (at > 0 && continuation(at))
200
+ at -= 1;
201
+ return at;
202
+ }
203
+ /** Keeps the first `headBytes` and the last `tailBytes` of what it is given. */
204
+ export class HeadTailBuffer {
205
+ headLimit;
206
+ tailLimit;
207
+ head = "";
208
+ headBytes = 0;
209
+ tail = [];
210
+ tailBytes = 0;
211
+ dropped = 0;
212
+ constructor(headLimit, tailLimit) {
213
+ this.headLimit = headLimit;
214
+ this.tailLimit = tailLimit;
215
+ }
216
+ append(text) {
217
+ if (!text)
218
+ return;
219
+ let rest = Buffer.from(text, "utf8");
220
+ if (this.headBytes < this.headLimit) {
221
+ if (rest.length <= this.headLimit - this.headBytes) {
222
+ this.head += text;
223
+ this.headBytes += rest.length;
224
+ return;
225
+ }
226
+ const at = utf8Boundary(rest, this.headLimit - this.headBytes, "down");
227
+ this.head += rest.subarray(0, at).toString("utf8");
228
+ this.headBytes += at;
229
+ rest = rest.subarray(at);
230
+ }
231
+ this.tail.push(rest.toString("utf8"));
232
+ this.tailBytes += rest.length;
233
+ // Every pass removes at least one byte, so this always terminates — a cut
234
+ // that lands inside a multi-byte character is moved to the next character
235
+ // boundary rather than re-encoded (re-encoding a partial `✓` can produce a
236
+ // replacement character just as long as what was cut, and loop forever).
237
+ while (this.tailBytes > this.tailLimit && this.tail.length) {
238
+ const first = Buffer.from(this.tail[0], "utf8");
239
+ const excess = this.tailBytes - this.tailLimit;
240
+ if (first.length <= excess) {
241
+ this.tail.shift();
242
+ this.tailBytes -= first.length;
243
+ this.dropped += first.length;
244
+ }
245
+ else {
246
+ const at = utf8Boundary(first, excess, "up");
247
+ this.tail[0] = first.subarray(at).toString("utf8");
248
+ this.tailBytes -= at;
249
+ this.dropped += at;
250
+ }
251
+ }
252
+ }
253
+ get truncated() {
254
+ return this.dropped > 0;
255
+ }
256
+ text() {
257
+ const tail = this.tail.join("");
258
+ return this.dropped > 0 ? `${this.head}\n… [${this.dropped} bytes of output omitted] …\n${tail}` : this.head + tail;
259
+ }
260
+ }
261
+ // ── Running ──────────────────────────────────────────────────────────────────
262
+ const active = new Set();
263
+ let exitHookInstalled = false;
264
+ /**
265
+ * Belt and braces for a clean CLI exit: the Job Object already guarantees the
266
+ * tree dies with the CLI, but ending it synchronously here means nothing is
267
+ * still running for even a moment after the prompt returns to the user.
268
+ */
269
+ function installExitHook() {
270
+ if (exitHookInstalled)
271
+ return;
272
+ exitHookInstalled = true;
273
+ process.once("exit", () => {
274
+ for (const child of active) {
275
+ try {
276
+ child.kill();
277
+ }
278
+ catch {
279
+ /* already gone */
280
+ }
281
+ }
282
+ });
283
+ }
284
+ export async function runProcess(req) {
285
+ const args = validateArgs(req.args);
286
+ if (!Number.isFinite(req.timeoutMs) || req.timeoutMs < 1 || req.timeoutMs > MAX_TIMEOUT_MS) {
287
+ throw new RunnerError("INVALID_TIMEOUT", `timeout must be between 1 ms and ${MAX_TIMEOUT_MS} ms.`);
288
+ }
289
+ const cwd = resolveCwd(req.cwd, req.root);
290
+ const { env, dropped } = buildChildEnv(req.sourceEnv ?? process.env, req.root);
291
+ const pathValue = Object.entries(env).find(([k]) => k.toUpperCase() === "PATH")?.[1] ?? "";
292
+ const prefix = resolveProgram(req.program, pathValue);
293
+ const helper = ensureJobHelper(); // throws JobHelperError — never run uncontained
294
+ if (req.signal?.aborted)
295
+ throw new RunnerError("CANCELLED", "Cancelled before it started.");
296
+ const resolved = [...prefix, ...args];
297
+ const buffer = new HeadTailBuffer(req.headBytes ?? DEFAULT_HEAD_BYTES, req.tailBytes ?? DEFAULT_TAIL_BYTES);
298
+ const counts = { stdout: 0, stderr: 0 };
299
+ let helperStderr = "";
300
+ const started = Date.now();
301
+ const child = spawn(helper, resolved, {
302
+ cwd,
303
+ env,
304
+ stdio: ["ignore", "pipe", "pipe"],
305
+ windowsHide: true,
306
+ shell: false
307
+ });
308
+ active.add(child);
309
+ installExitHook();
310
+ let timedOut = false;
311
+ let cancelled = false;
312
+ let treeKilled = false;
313
+ const killTree = () => {
314
+ if (treeKilled)
315
+ return;
316
+ treeKilled = true;
317
+ // Terminating the helper closes the only handle to its Job Object, and
318
+ // KILL_ON_JOB_CLOSE ends every process in it.
319
+ try {
320
+ child.kill();
321
+ }
322
+ catch {
323
+ /* already exited */
324
+ }
325
+ };
326
+ const wire = (stream, readable) => {
327
+ if (!readable)
328
+ return null;
329
+ const decoder = new StringDecoder("utf8");
330
+ const redact = req.redactor.stream((text) => {
331
+ buffer.append(text);
332
+ req.onOutput?.(stream, text);
333
+ });
334
+ readable.on("data", (chunk) => {
335
+ counts[stream] += chunk.length;
336
+ if (stream === "stderr" && helperStderr.length < 512)
337
+ helperStderr += chunk.toString("utf8");
338
+ redact.write(decoder.write(chunk));
339
+ });
340
+ return () => {
341
+ redact.write(decoder.end());
342
+ redact.end();
343
+ };
344
+ };
345
+ const endStdout = wire("stdout", child.stdout);
346
+ const endStderr = wire("stderr", child.stderr);
347
+ const timer = setTimeout(() => {
348
+ timedOut = true;
349
+ killTree();
350
+ }, req.timeoutMs);
351
+ const onAbort = () => {
352
+ cancelled = true;
353
+ killTree();
354
+ };
355
+ req.signal?.addEventListener("abort", onAbort, { once: true });
356
+ let spawnError = null;
357
+ child.once("spawn", () => req.onStart?.({ pid: child.pid, resolved }));
358
+ const outcome = await new Promise((resolve) => {
359
+ child.once("error", (err) => {
360
+ spawnError = err;
361
+ resolve({ code: null, signal: null });
362
+ });
363
+ child.once("close", (code, signal) => resolve({ code, signal }));
364
+ // `close` waits for every holder of the output pipes. Once the helper has
365
+ // exited its job is gone, so anything still holding them is not ours to
366
+ // wait for: stop reading after a short grace period instead of hanging.
367
+ child.once("exit", (code, signal) => {
368
+ setTimeout(() => {
369
+ child.stdout?.destroy();
370
+ child.stderr?.destroy();
371
+ resolve({ code, signal });
372
+ }, 3000).unref();
373
+ });
374
+ });
375
+ clearTimeout(timer);
376
+ req.signal?.removeEventListener("abort", onAbort);
377
+ active.delete(child);
378
+ endStdout?.();
379
+ endStderr?.();
380
+ if (spawnError) {
381
+ throw new RunnerError("START_FAILED", `The command could not be started: ${spawnError.message}`);
382
+ }
383
+ if (!treeKilled && outcome.code === JOB_HELPER_FAILURE_EXIT && helperStderr.startsWith("cos-job-runner:")) {
384
+ throw new RunnerError("START_FAILED", helperStderr.split(/\r?\n/)[0].replace(/^cos-job-runner:\s*/, ""));
385
+ }
386
+ const ended = Date.now();
387
+ return {
388
+ exit_code: treeKilled ? null : outcome.code,
389
+ signal: treeKilled ? "SIGKILL" : outcome.signal,
390
+ timed_out: timedOut,
391
+ cancelled: cancelled && !timedOut,
392
+ tree_killed: treeKilled,
393
+ started_at: new Date(started).toISOString(),
394
+ ended_at: new Date(ended).toISOString(),
395
+ duration_ms: ended - started,
396
+ stdout_bytes: counts.stdout,
397
+ stderr_bytes: counts.stderr,
398
+ truncated: buffer.truncated,
399
+ output: buffer.text(),
400
+ redaction_count: req.redactor.count,
401
+ dropped_environment_names: dropped,
402
+ resolved_argv: resolved,
403
+ cwd
404
+ };
405
+ }
406
+ export { JobHelperError };