@carrieros/cli 0.3.0 → 0.4.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 (86) hide show
  1. package/README.md +34 -13
  2. package/dist/commands/chat.js +3 -3
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +27 -12
  5. package/dist/commands/logout.js +1 -0
  6. package/dist/commands/permissions.js +77 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +8 -1
  10. package/dist/commands/update.js +79 -9
  11. package/dist/commands/usage.js +5 -5
  12. package/dist/commands/whoami.js +12 -9
  13. package/dist/ide/editor-context.js +115 -12
  14. package/dist/ide/ide-session.js +274 -13
  15. package/dist/ide/tool-host.js +2 -2
  16. package/dist/main.js +0 -0
  17. package/dist/services/api.js +178 -12
  18. package/dist/services/auth-origin.js +20 -0
  19. package/dist/services/chat-stream.js +26 -3
  20. package/dist/services/checkpoints.js +176 -14
  21. package/dist/services/client-tools.js +113 -21
  22. package/dist/services/code-intel.js +243 -0
  23. package/dist/services/code-symbols.js +94 -0
  24. package/dist/services/coding-workflow.js +554 -0
  25. package/dist/services/command-coordinator.js +85 -12
  26. package/dist/services/command-policy.js +34 -4
  27. package/dist/services/config.js +67 -5
  28. package/dist/services/container-runner.js +254 -0
  29. package/dist/services/container-supervisor.js +38 -0
  30. package/dist/services/context.js +45 -17
  31. package/dist/services/device-auth.js +30 -5
  32. package/dist/services/execution-platform.js +30 -0
  33. package/dist/services/file-resolver.js +1 -1
  34. package/dist/services/folder-key.js +22 -0
  35. package/dist/services/git-tools.js +181 -0
  36. package/dist/services/helper-bin.js +56 -35
  37. package/dist/services/instruction-resolver.js +54 -0
  38. package/dist/services/job-helper.js +31 -10
  39. package/dist/services/local-files.js +148 -26
  40. package/dist/services/local-tools.js +540 -35
  41. package/dist/services/login-flow.js +43 -12
  42. package/dist/services/mutation-coordinator.js +186 -20
  43. package/dist/services/mutation-groups.js +309 -0
  44. package/dist/services/mutation-recovery.js +159 -0
  45. package/dist/services/mutations.js +264 -78
  46. package/dist/services/packaged-update.js +403 -0
  47. package/dist/services/packaged.js +15 -0
  48. package/dist/services/permission-mode.js +60 -0
  49. package/dist/services/process-runner.js +7 -1
  50. package/dist/services/project-context.js +4 -4
  51. package/dist/services/result-reconciliation.js +49 -0
  52. package/dist/services/secure-store.js +21 -1
  53. package/dist/services/session-resolver.js +5 -0
  54. package/dist/services/supported-runtime.js +59 -0
  55. package/dist/services/task-context.js +212 -0
  56. package/dist/services/task-snapshot.js +38 -0
  57. package/dist/services/tool-result-outbox.js +195 -0
  58. package/dist/services/update.js +37 -12
  59. package/dist/services/workspace-registry.js +4 -3
  60. package/dist/services/workspace.js +8 -1
  61. package/dist/shell/shell-chat.js +299 -32
  62. package/dist/shell/shell-commands.js +46 -4
  63. package/dist/shell/shell-prompt.js +21 -11
  64. package/dist/shell/shell-renderer.js +1 -1
  65. package/dist/shell/shell.js +69 -7
  66. package/dist/shell/task-context-view.js +40 -0
  67. package/dist/ui/agent-cards.js +111 -0
  68. package/dist/ui/agent-presentation.js +131 -0
  69. package/dist/ui/approval.js +46 -16
  70. package/dist/ui/banner.js +31 -87
  71. package/dist/ui/change-review.js +293 -46
  72. package/dist/ui/chat-renderer.js +6 -6
  73. package/dist/ui/colors.js +9 -9
  74. package/dist/ui/command-details.js +11 -0
  75. package/dist/ui/command-palette.js +27 -10
  76. package/dist/ui/command-registry.js +9 -2
  77. package/dist/ui/command-review.js +77 -28
  78. package/dist/ui/composer-layout.js +26 -20
  79. package/dist/ui/conversation.js +77 -25
  80. package/dist/ui/live.js +1 -1
  81. package/dist/ui/screen.js +19 -11
  82. package/dist/ui/select.js +6 -0
  83. package/dist/ui/task-context-card.js +99 -0
  84. package/dist/ui/trust.js +7 -12
  85. package/dist/ui/ui.js +23 -0
  86. package/package.json +8 -5
@@ -1,8 +1,12 @@
1
+ import { createHash } from "node:crypto";
2
+ import { APPROVAL_TIMEOUT_MS } from "./mutations.js";
1
3
  import { PolicyError, evaluateCommand } from "./command-policy.js";
2
4
  import { JobHelperError } from "./job-helper.js";
3
5
  import { RunnerError, runProcess } from "./process-runner.js";
4
6
  import { Redactor, projectEnvSecrets } from "./redaction.js";
5
7
  import { neutralizingOverrides } from "./workspace.js";
8
+ import { containerRuntime, verifyContainerRuntime } from "./container-runner.js";
9
+ import { executionAdapter, executionPlatform, executionContract } from "./execution-platform.js";
6
10
  import { RepositoryError, activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
7
11
  /**
8
12
  * One turn's proposed local commands: check → ask → run → answer.
@@ -67,17 +71,28 @@ export function createCommandCoordinator(opts) {
67
71
  const { ui } = opts;
68
72
  let chain = Promise.resolve();
69
73
  let declined = false;
70
- const fail = (call, started, code, message) => opts.submit({ tool_call_id: call.tool_call_id, ok: false, error: { code, message }, duration_ms: Date.now() - started });
74
+ // One answer per call. Transport owns retrying it; a later error must never
75
+ // send a second, contradictory result for a command that already ran.
76
+ const answered = new Set();
77
+ const submitOnce = (result) => {
78
+ if (answered.has(result.tool_call_id))
79
+ return Promise.resolve();
80
+ answered.add(result.tool_call_id);
81
+ return opts.submit(result);
82
+ };
83
+ const seen = new Set();
84
+ const fail = (call, started, code, message) => submitOnce({ tool_call_id: call.tool_call_id, ok: false, error: { code, message }, duration_ms: Date.now() - started });
71
85
  async function process(call) {
86
+ const boundCall = structuredClone(call);
72
87
  const started = Date.now();
73
88
  const args = (call.arguments ?? {});
74
89
  const reason = typeof args.reason === "string" ? args.reason.slice(0, 300) : "";
75
90
  if (declined) {
76
- await fail(call, started, "COMMAND_REJECTED", "The user already declined a command in this turn. Nothing ran; ask how to proceed.");
91
+ await fail(boundCall, started, "COMMAND_REJECTED", "The user already declined a command in this turn. Nothing ran; ask how to proceed.");
77
92
  return;
78
93
  }
79
94
  if (opts.signal.aborted) {
80
- await fail(call, started, "COMMAND_CANCELLED", "The turn was stopped. Nothing ran.");
95
+ await fail(boundCall, started, "COMMAND_CANCELLED", "The turn was stopped. Nothing ran.");
81
96
  return;
82
97
  }
83
98
  // 1. Which repository, then policy — both before anyone is asked. A command
@@ -92,18 +107,20 @@ export function createCommandCoordinator(opts) {
92
107
  catch (err) {
93
108
  const e = errorCodeOf(err);
94
109
  ui.finished({ decision: null, errorCode: e.code, message: e.message });
95
- await fail(call, started, e.code, e.message);
110
+ await fail(boundCall, started, e.code, e.message);
96
111
  return;
97
112
  }
98
113
  let decision;
114
+ let policyFingerprint;
99
115
  try {
100
116
  const { reason: _r, repository: _repo, ...proposal } = args;
101
117
  decision = evaluateCommand(proposal, root);
118
+ policyFingerprint = JSON.stringify(decision);
102
119
  }
103
120
  catch (err) {
104
121
  const e = errorCodeOf(err);
105
122
  ui.finished({ decision: null, errorCode: e.code, message: e.message });
106
- await fail(call, started, e.code, e.message);
123
+ await fail(boundCall, started, e.code, e.message);
107
124
  return;
108
125
  }
109
126
  // Git reads file content through repository-configured programs; neutralize
@@ -113,15 +130,45 @@ export function createCommandCoordinator(opts) {
113
130
  if (!overrides) {
114
131
  const message = "The repository's Git configuration could not be read safely, so the command was not run.";
115
132
  ui.finished({ decision, errorCode: "COMMAND_DENIED", message });
116
- await fail(call, started, "COMMAND_DENIED", message);
133
+ await fail(boundCall, started, "COMMAND_DENIED", message);
117
134
  return;
118
135
  }
119
136
  const sub = decision.effectiveArgs.indexOf(decision.args[0]);
120
137
  decision = { ...decision, effectiveArgs: [...decision.effectiveArgs.slice(0, sub), ...overrides, ...decision.effectiveArgs.slice(sub)] };
121
138
  }
139
+ // Capability is checked before asking for approval, and again by runProcess.
140
+ try {
141
+ if (executionAdapter(executionPlatform()) === "isolated-container") {
142
+ await verifyContainerRuntime(containerRuntime());
143
+ }
144
+ }
145
+ catch (err) {
146
+ const e = errorCodeOf(err);
147
+ ui.finished({ decision, errorCode: e.code, message: e.message });
148
+ await fail(boundCall, started, e.code, e.message);
149
+ return;
150
+ }
122
151
  // 2. Approval, then 3. run — both while holding the terminal.
123
152
  await opts.withTerminal(async () => {
124
- const answer = await ui.review(decision, reason, repository?.name);
153
+ if (opts.signal.aborted) {
154
+ await fail(boundCall, started, "COMMAND_CANCELLED", "The turn was stopped before command review. Nothing ran.");
155
+ return;
156
+ }
157
+ if (executionAdapter(executionPlatform()) === "isolated-container") {
158
+ decision = { ...decision, notes: [
159
+ ...decision.notes.filter(note => !note.includes("Windows account")),
160
+ "Runs in an isolated Linux container with only this repository mounted. Network access is disabled; host tools and credentials are not inherited."
161
+ ] };
162
+ }
163
+ const scope = opts.recoveryScope?.();
164
+ const fingerprint = () => createHash("sha256").update(JSON.stringify({ call, decision, root, repository: repository?.id, workflow: opts.approvalContext?.() })).digest("hex");
165
+ const reviewed = fingerprint();
166
+ const deadline = Date.now() + Math.min(APPROVAL_TIMEOUT_MS, call.timeout_ms ?? APPROVAL_TIMEOUT_MS);
167
+ const answer = await ui.review(decision, reason, repository?.name, boundCall.tool_call_id);
168
+ if (opts.signal.aborted) {
169
+ await fail(boundCall, started, "COMMAND_CANCELLED", "The turn was stopped during command review. Nothing ran.");
170
+ return;
171
+ }
125
172
  if (answer !== "approve") {
126
173
  declined = true;
127
174
  const code = answer === "timeout" ? "APPROVAL_TIMEOUT" : answer === "cancel" ? "COMMAND_CANCELLED" : "COMMAND_REJECTED";
@@ -131,11 +178,27 @@ export function createCommandCoordinator(opts) {
131
178
  ? "The user stopped the turn. Nothing ran."
132
179
  : "The user rejected the command. Nothing ran.";
133
180
  ui.finished({ decision, errorCode: code, message });
134
- await fail(call, started, code, message);
181
+ await fail(boundCall, started, code, message);
135
182
  if (answer === "cancel")
136
183
  ui.cancelTurn();
137
184
  return;
138
185
  }
186
+ const { reason: _reason, repository: _selector, ...currentProposal } = args;
187
+ let unchanged = false;
188
+ try {
189
+ unchanged = Date.now() < deadline && scope === opts.recoveryScope?.() && fingerprint() === reviewed &&
190
+ commandRepository(args.repository, opts.root).id === repository?.id &&
191
+ JSON.stringify(evaluateCommand(currentProposal, root)) === policyFingerprint;
192
+ }
193
+ catch {
194
+ unchanged = false;
195
+ }
196
+ if (!unchanged) {
197
+ declined = true;
198
+ ui.finished({ decision, errorCode: "APPROVAL_INVALIDATED", message: "Command, script, scope or deadline changed during review. Request fresh approval." });
199
+ await fail(boundCall, started, "APPROVAL_INVALIDATED", "Command, script, scope or deadline changed during review. Nothing ran.");
200
+ return;
201
+ }
139
202
  let result;
140
203
  try {
141
204
  const redactor = new Redactor([...projectEnvSecrets(root), ...(opts.cliSecrets ?? [])]);
@@ -145,6 +208,7 @@ export function createCommandCoordinator(opts) {
145
208
  cwd: decision.cwdAbsolute,
146
209
  root,
147
210
  timeoutMs: decision.timeoutMs,
211
+ operationId: boundCall.tool_call_id,
148
212
  signal: opts.signal,
149
213
  redactor,
150
214
  onStart: () => ui.started(decision),
@@ -154,7 +218,7 @@ export function createCommandCoordinator(opts) {
154
218
  catch (err) {
155
219
  const e = errorCodeOf(err);
156
220
  ui.finished({ decision, errorCode: e.code, message: e.message });
157
- await fail(call, started, e.code, e.message);
221
+ await fail(boundCall, started, e.code, e.message);
158
222
  return;
159
223
  }
160
224
  ui.finished({ decision, result });
@@ -176,6 +240,7 @@ export function createCommandCoordinator(opts) {
176
240
  started_at: result.started_at,
177
241
  ended_at: result.ended_at,
178
242
  duration_ms: result.duration_ms,
243
+ execution_backend: executionContract().backend,
179
244
  stdout_bytes: result.stdout_bytes,
180
245
  stderr_bytes: result.stderr_bytes,
181
246
  truncated: result.truncated,
@@ -184,16 +249,24 @@ export function createCommandCoordinator(opts) {
184
249
  ...(decision.script ? { script: { name: decision.script.name, text: decision.script.text.slice(0, 500) } } : {}),
185
250
  output: result.output
186
251
  });
187
- await opts.submit({ tool_call_id: call.tool_call_id, ok: true, result: payload, duration_ms: Date.now() - started });
252
+ await submitOnce({ tool_call_id: boundCall.tool_call_id, ok: true, result: payload, duration_ms: Date.now() - started });
188
253
  });
189
254
  }
190
255
  return {
191
256
  handle(call) {
257
+ // A repeated id is the same call: it is reviewed and run at most once.
258
+ if (seen.has(call.tool_call_id))
259
+ return Promise.resolve();
260
+ seen.add(call.tool_call_id);
261
+ const identity = structuredClone(call);
192
262
  const next = chain.then(() => process(call)).catch(async (err) => {
263
+ // Already answered (e.g. its delivery failed): surface that, never a second result.
264
+ if (answered.has(identity.tool_call_id))
265
+ throw err;
193
266
  // A bug here must still answer the call, never leave the turn waiting.
194
- await fail(call, Date.now(), "START_FAILED", err?.message ?? "The command could not be processed.").catch(() => undefined);
267
+ await fail(identity, Date.now(), "START_FAILED", err?.message ?? "The command could not be processed.").catch(() => undefined);
195
268
  });
196
- chain = next;
269
+ chain = next.catch(() => undefined);
197
270
  return next;
198
271
  }
199
272
  };
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { isInside } from "./local-files.js";
4
4
  import { MAX_TIMEOUT_MS, RunnerError, resolveCwd } from "./process-runner.js";
5
+ import { GIT_NO_HOOKS_PATH } from "./workspace.js";
5
6
  export class PolicyError extends Error {
6
7
  code;
7
8
  constructor(code, message) {
@@ -44,7 +45,6 @@ const KNOWN_DANGEROUS = {
44
45
  ruby: "an interpreter",
45
46
  perl: "an interpreter",
46
47
  deno: "an interpreter",
47
- bun: "an interpreter",
48
48
  npx: "a remote package runner",
49
49
  curl: "a network tool",
50
50
  wget: "a network tool",
@@ -128,7 +128,7 @@ function timeoutFor(tier, requested) {
128
128
  }
129
129
  // ── git ──────────────────────────────────────────────────────────────────────
130
130
  /** Global hardening, placed before the subcommand. */
131
- const GIT_GLOBAL = ["--no-pager", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=NUL", "-c", "diff.external="];
131
+ const GIT_GLOBAL = ["--no-pager", "-c", "core.fsmonitor=false", "-c", `core.hooksPath=${GIT_NO_HOOKS_PATH}`, "-c", "diff.external="];
132
132
  /** Never allowed in any git invocation: each reads or writes outside the command's intent. */
133
133
  const GIT_FORBIDDEN = /^(-c|-C|--git-dir|--work-tree|--exec-path|--namespace|--super-prefix|--config-env|--output|--ext-diff|--textconv|--no-index|--upload-pack|--receive-pack|--open-files-in-pager|-O)(=|$)/;
134
134
  const GIT_FLAGS = {
@@ -226,7 +226,8 @@ function nearestPackageJson(cwdAbs, root) {
226
226
  catch {
227
227
  /* none or unreadable here */
228
228
  }
229
- if (path.resolve(dir).toLowerCase() === path.resolve(root).toLowerCase())
229
+ // The platform's own path comparison (case-insensitive only on Windows), as isInside.
230
+ if (path.relative(path.resolve(root), path.resolve(dir)) === "")
230
231
  return null;
231
232
  const parent = path.dirname(dir);
232
233
  if (parent === dir || !isInside(root, parent))
@@ -378,6 +379,8 @@ export function evaluateCommand(proposal, root) {
378
379
  }
379
380
  throw err;
380
381
  }
382
+ // resolveCwd returns a real path; compare positional paths against the same root.
383
+ root = fs.realpathSync.native(root);
381
384
  const cwdRelative = path.relative(fs.realpathSync.native(root), cwdAbsolute).split(path.sep).join("/") || ".";
382
385
  let partial;
383
386
  switch (name) {
@@ -392,8 +395,35 @@ export function evaluateCommand(proposal, root) {
392
395
  case "yarn":
393
396
  partial = evaluatePackageManager(name, args, cwdAbsolute, root);
394
397
  break;
398
+ case "bun":
399
+ case "pytest":
400
+ case "go":
401
+ case "cargo": {
402
+ const version = args.length === 1 && args[0] === (name === "go" ? "version" : "--version");
403
+ const expected = name === "pytest" ? [] : name === "go" ? ["test", "./..."] : ["test"];
404
+ // No eval, arbitrary scripts, flags, install/publish or external paths.
405
+ if (!version && JSON.stringify(args) !== JSON.stringify(expected))
406
+ return deny(`${name} may only run its project tests or its version query.`);
407
+ const markers = name === "go" ? ["go.mod"] : name === "cargo" ? ["Cargo.toml"] : name === "bun" ? ["package.json"] : ["pyproject.toml", "pytest.ini", "setup.cfg", "setup.py"];
408
+ if (!version && !markers.some(file => {
409
+ // Same canonical form as root (realpathSync.native): 8.3, subst and mapped
410
+ // drives resolve alike, and a marker that links out still fails.
411
+ try {
412
+ const real = fs.realpathSync.native(path.join(cwdAbsolute, file));
413
+ return isInside(root, real) && fs.statSync(real).isFile();
414
+ }
415
+ catch {
416
+ return false;
417
+ }
418
+ }))
419
+ return deny(`${name} requires project configuration in the selected working directory.`);
420
+ partial = { tier: version ? "R0" : "R1", program: name, args, effectiveArgs: args,
421
+ network: version ? "none-expected" : "project-code-may-use-network",
422
+ notes: version ? [] : ["Runs project tests, including project-defined configuration and plugins."] };
423
+ break;
424
+ }
395
425
  default:
396
- return deny(`${program} is not in the allowed command set (git, node, npm, pnpm, yarn).`);
426
+ return deny(`${program} is not in the allowed command set (git, node, npm, pnpm, yarn, bun, pytest, go, cargo).`);
397
427
  }
398
428
  const notes = partial.tier === "R0" ? partial.notes : [...partial.notes, PROJECT_CODE_NOTE];
399
429
  return { ...partial, notes, cwdRelative, cwdAbsolute, timeoutMs: timeoutFor(partial.tier, proposal.timeout_ms) };
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
- import { SealError, isSealed, seal, sealingAvailable, unseal } from "./secure-store.js";
5
+ import { SealError, isSealed, seal, sealingAvailable, sealingRequired, sealingUnavailableError, unseal } from "./secure-store.js";
6
6
  /**
7
7
  * A URL is safe to send credentials to only over HTTPS, or over HTTP to a
8
8
  * loopback host (local dev). Anything else (a plain-HTTP remote host) would send
@@ -40,10 +40,13 @@ export function sameApiOrigin(a, b) {
40
40
  if (!a || !b)
41
41
  return false;
42
42
  try {
43
- return new URL(a).origin === new URL(b).origin;
43
+ const left = new URL(a);
44
+ const right = new URL(b);
45
+ return ["http:", "https:"].includes(left.protocol) &&
46
+ ["http:", "https:"].includes(right.protocol) && left.origin === right.origin;
44
47
  }
45
48
  catch {
46
- return a === b;
49
+ return false;
47
50
  }
48
51
  }
49
52
  /**
@@ -64,6 +67,46 @@ export function sameApiOrigin(a, b) {
64
67
  * removed only when a caller asks for it to be removed, which is why logout
65
68
  * still works and why nothing else can take `auth` with it.
66
69
  */
70
+ export class ConfigReadError extends Error {
71
+ code = "CONFIG_UNREADABLE";
72
+ constructor() {
73
+ super("Saved configuration is unreadable or invalid. No configuration was overwritten. Back up config.json, then repair it or explicitly move it aside before restarting.");
74
+ this.name = "ConfigReadError";
75
+ }
76
+ }
77
+ /** Reject malformed known fields; preserve unknown fields for forward compatibility. */
78
+ function validateConfig(value) {
79
+ if (!value || typeof value !== "object" || Array.isArray(value))
80
+ throw new ConfigReadError();
81
+ const data = value;
82
+ const strings = ["apiUrl", "platformUrl", "secretKey", "secretKeyApiUrl", "sessionId", "sessionTitle", "mode", "model", "latestCliVersion"];
83
+ const booleans = ["webSearch", "fast", "highPower", "localCommandsEnabled", "projectContextPending"];
84
+ const arrays = ["sessionOrdinals", "memoryArtifactIds", "attachedFileIds", "trustedFolders"];
85
+ for (const key of strings)
86
+ if (data[key] !== undefined && typeof data[key] !== "string")
87
+ throw new ConfigReadError();
88
+ for (const key of booleans)
89
+ if (data[key] !== undefined && typeof data[key] !== "boolean")
90
+ throw new ConfigReadError();
91
+ for (const key of arrays)
92
+ if (data[key] !== undefined && (!Array.isArray(data[key]) || !data[key].every(v => typeof v === "string")))
93
+ throw new ConfigReadError();
94
+ for (const key of ["updateCheckAt", "updateCheckErrorAt"])
95
+ if (data[key] !== undefined && (typeof data[key] !== "number" || !Number.isFinite(data[key])))
96
+ throw new ConfigReadError();
97
+ if (data.chatType !== undefined && !["carrier", "standard"].includes(data.chatType))
98
+ throw new ConfigReadError();
99
+ if (data.sia !== undefined && typeof data.sia !== "boolean" && !["auto", "off"].includes(data.sia))
100
+ throw new ConfigReadError();
101
+ for (const key of ["auth", "scope", "theme"])
102
+ if (data[key] !== undefined && (!data[key] || typeof data[key] !== "object" || Array.isArray(data[key])))
103
+ throw new ConfigReadError();
104
+ if (data.theme && typeof data.theme.accent !== "string")
105
+ throw new ConfigReadError();
106
+ if (data.uploads !== undefined && !Array.isArray(data.uploads))
107
+ throw new ConfigReadError();
108
+ // Credential contents and issuer policy remain the existing auth layer's job.
109
+ }
67
110
  export class ConfigStore {
68
111
  dir;
69
112
  file;
@@ -115,6 +158,12 @@ export class ConfigStore {
115
158
  */
116
159
  conceal(patch) {
117
160
  const canSeal = (v) => typeof v === "string" && v.length > 0 && !isSealed(v);
161
+ const carriesSecret = (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) || canSeal(patch.secretKey);
162
+ // The packaged build fails closed: a missing DPAPI helper is a damaged
163
+ // install, and writing the tokens in plaintext would silently drop the
164
+ // protection the user was promised. Nothing is written; login reports why.
165
+ if (carriesSecret && sealingRequired() && !sealingAvailable())
166
+ throw sealingUnavailableError();
118
167
  const out = { ...patch };
119
168
  if (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) {
120
169
  if (sealingAvailable()) {
@@ -173,12 +222,23 @@ export class ConfigStore {
173
222
  return path.join(os.homedir(), ".carrieros");
174
223
  }
175
224
  read() {
225
+ let source;
226
+ try {
227
+ source = fs.readFileSync(this.file, "utf8");
228
+ }
229
+ catch (err) {
230
+ if (err.code === "ENOENT")
231
+ return { apiUrl: DEFAULT_API_URL };
232
+ throw new ConfigReadError();
233
+ }
176
234
  try {
177
- const parsed = JSON.parse(fs.readFileSync(this.file, "utf8"));
235
+ const parsed = JSON.parse(source);
236
+ validateConfig(parsed);
178
237
  return { apiUrl: DEFAULT_API_URL, ...parsed };
179
238
  }
180
239
  catch {
181
- return { apiUrl: DEFAULT_API_URL };
240
+ // Never include the parser error: its source excerpt can contain tokens.
241
+ throw new ConfigReadError();
182
242
  }
183
243
  }
184
244
  /**
@@ -194,6 +254,7 @@ export class ConfigStore {
194
254
  const merged = { ...this.read(), ...this.conceal(patch) };
195
255
  for (const key of remove)
196
256
  delete merged[key];
257
+ validateConfig(merged);
197
258
  this.write(merged);
198
259
  this.data = this.reveal(merged);
199
260
  }
@@ -282,6 +343,7 @@ export class ConfigStore {
282
343
  this.commit({}, [
283
344
  "auth",
284
345
  "secretKey",
346
+ "secretKeyApiUrl",
285
347
  "sessionId",
286
348
  "sessionTitle",
287
349
  "sessionOrdinals",
@@ -0,0 +1,254 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import { promisify } from "node:util";
7
+ import { installedDocker } from "./supported-runtime.js";
8
+ import { executionContract } from "./execution-platform.js";
9
+ import { CONTAINER_SUPERVISOR } from "./container-supervisor.js";
10
+ import { FORCED_ENV, buildChildEnv } from "./env-policy.js";
11
+ import { isInside } from "./local-files.js";
12
+ import { HeadTailBuffer, MAX_TIMEOUT_MS, RunnerError, resolveCwd, validateArgs } from "./process-runner.js";
13
+ const exec = promisify(execFile);
14
+ const PROGRAMS = new Set(["node", "npm", "pnpm", "yarn", "git", "bun", "pytest", "go", "cargo"]);
15
+ export function runtimeHasRequiredIsolation(info) {
16
+ if (!info || typeof info !== "object")
17
+ return false;
18
+ const value = info;
19
+ return value.OSType === "linux" && Array.isArray(value.SecurityOptions) && value.SecurityOptions.some(option => typeof option === "string" && option.split(",").includes("name=seccomp") && option.split(",").includes("profile=builtin"));
20
+ }
21
+ /** Only explicit local runtime configuration. Never inherit a remote Docker context. */
22
+ export function containerRuntime(env = process.env) {
23
+ if (env.COS_COMMAND_DOCKER)
24
+ throw new RunnerError("INVALID_RUNTIME", "COS_COMMAND_DOCKER is no longer accepted. Remove it; the executor uses only a supported Docker CLI installation.");
25
+ if (env.COS_COMMAND_RUNTIME && env.COS_COMMAND_RUNTIME !== "docker-engine-v1")
26
+ throw new RunnerError("INVALID_RUNTIME", "Only docker-engine-v1 is supported.");
27
+ const socket = env.COS_COMMAND_DOCKER_SOCKET;
28
+ const image = env.COS_COMMAND_IMAGE;
29
+ if (!socket || !image) {
30
+ throw new RunnerError("ISOLATION_UNAVAILABLE", executionContract().prerequisite + " Configure COS_COMMAND_DOCKER_SOCKET and COS_COMMAND_IMAGE; nothing was run.");
31
+ }
32
+ if (!path.isAbsolute(socket) || !/^sha256:[a-f0-9]{64}$/.test(image)) {
33
+ throw new RunnerError("INVALID_RUNTIME", "The runtime requires an absolute local socket path and a local sha256 image ID.");
34
+ }
35
+ let executable;
36
+ try {
37
+ executable = installedDocker();
38
+ }
39
+ catch (error) {
40
+ throw new RunnerError("ISOLATION_UNAVAILABLE", error.message);
41
+ }
42
+ try {
43
+ if (!fs.statSync(executable).isFile() || !fs.statSync(socket).isSocket())
44
+ throw new Error();
45
+ fs.accessSync(executable, fs.constants.X_OK);
46
+ return { executable: fs.realpathSync(executable), socket: fs.realpathSync(socket), image };
47
+ }
48
+ catch {
49
+ throw new RunnerError("ISOLATION_UNAVAILABLE", "The configured local command runtime is unavailable.");
50
+ }
51
+ }
52
+ /** Pure launch plan; project data cannot add mounts, privileges, a shell or a daemon endpoint. */
53
+ export function containerArguments(runtime, name, root, operationId) {
54
+ if (root.includes(",") || /[\r\n\0]/.test(root))
55
+ throw new RunnerError("INVALID_CWD", "This repository path cannot be safely mounted.");
56
+ // Daemon-owned removal survives CLI death; normal exit still verifies removal independently.
57
+ return ["--host", `unix://${runtime.socket}`, "run", "--rm", "--name", name,
58
+ "--label", "ai.carrieros.command=true",
59
+ ...(operationId ? ["--label", `ai.carrieros.operation=${createHash("sha256").update(operationId).digest("hex")}`] : []),
60
+ "--pull=never", "--restart=no", "--init=false", "--read-only", "--network=none",
61
+ "--pids-limit=128", "--memory=1g", "--cpus=1",
62
+ "--cap-drop=ALL", "--cap-add=SETUID", "--cap-add=SETGID",
63
+ "--security-opt=no-new-privileges", "--user=0:0",
64
+ "--tmpfs=/tmp:rw,nosuid,nodev,size=128m", "--log-driver=none",
65
+ "--mount", `type=bind,source=${root},target=/workspace,bind-recursive=disabled`,
66
+ "-i", "--entrypoint=node", runtime.image, "-e", CONTAINER_SUPERVISOR];
67
+ }
68
+ /** A lost rm response is not proof of failure or success; query the daemon independently. */
69
+ export async function removeAndVerifyContainer(docker, name) {
70
+ try {
71
+ await docker(["rm", "--force", "--volumes", name]);
72
+ }
73
+ catch { /* ACK may be lost */ }
74
+ try {
75
+ return (await docker(["ps", "--all", "--quiet", "--filter", `name=^/${name}$`])).trim() === "";
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ export async function verifyContainerRuntime(runtime) {
82
+ const query = async (args) => (await exec(runtime.executable, ["--host", `unix://${runtime.socket}`, ...args], {
83
+ env: { PATH: "/usr/bin:/bin", HOME: "/nonexistent", DOCKER_CONFIG: "/nonexistent" }, timeout: 10000, maxBuffer: 64 * 1024
84
+ })).stdout;
85
+ try {
86
+ const version = JSON.parse(await query(["version", "--format", "{{json .Server}}"]));
87
+ // bind-recursive=disabled requires modern Docker Engine; compatible wrappers are not supported.
88
+ if (!Array.isArray(version.Components) || !version.Components.some((c) => c.Name === "Engine") ||
89
+ !/^\d+\./.test(version.Version) || Number(version.Version.split(".")[0]) < 25)
90
+ throw new Error();
91
+ const info = JSON.parse(await query(["info", "--format", "{{json .}}"]));
92
+ if (!runtimeHasRequiredIsolation(info))
93
+ throw new Error();
94
+ if ((await query(["image", "inspect", runtime.image, "--format", "{{.Id}}"])).trim() !== runtime.image)
95
+ throw new Error();
96
+ }
97
+ catch {
98
+ throw new RunnerError("ISOLATION_UNAVAILABLE", "Secure command execution requires Docker Engine 25+ with Linux PID isolation, builtin seccomp and the configured local image. Start the approved runtime; no native fallback was used.");
99
+ }
100
+ }
101
+ function outcomeFrom(value) {
102
+ const data = JSON.parse(value);
103
+ if (!["exit", "timeout", "lease_lost", "start_failed", "not_installed"].includes(data.kind) ||
104
+ !(data.code === null || (Number.isInteger(data.code) && data.code >= 0 && data.code <= 255)) ||
105
+ !(data.signal === null || /^SIG[A-Z0-9]+$/.test(data.signal)))
106
+ throw new Error("invalid control result");
107
+ return data;
108
+ }
109
+ export async function runContainer(req) {
110
+ const args = validateArgs(req.args);
111
+ if (!PROGRAMS.has(req.program))
112
+ throw new RunnerError("PROGRAM_DENIED", "This program is not permitted by the isolated executor.");
113
+ if (!Number.isFinite(req.timeoutMs) || req.timeoutMs < 1 || req.timeoutMs > MAX_TIMEOUT_MS)
114
+ throw new RunnerError("INVALID_TIMEOUT", "Invalid command timeout.");
115
+ const cwd = resolveCwd(req.cwd, req.root);
116
+ // The same canonical form resolveCwd and the policy use, so cwd and arguments map consistently.
117
+ const root = fs.realpathSync.native(req.root);
118
+ const runtime = containerRuntime();
119
+ if (isInside(root, runtime.executable) || isInside(root, runtime.socket))
120
+ throw new RunnerError("INVALID_RUNTIME", "The runtime must be outside the repository.");
121
+ if (req.signal?.aborted)
122
+ throw new RunnerError("CANCELLED", "Cancelled before it started.");
123
+ const name = `cos-command-${randomUUID()}`;
124
+ const marker = `COS_CONTROL_${randomUUID()}:`;
125
+ const source = req.sourceEnv ?? process.env;
126
+ const filtered = buildChildEnv(source, root);
127
+ // Host HOME, PATH, config and credentials have no place in the guest.
128
+ const env = { ...FORCED_ENV, PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/tmp", TMPDIR: "/tmp" };
129
+ for (const key of ["LANG", "TZ"])
130
+ if (filtered.env[key])
131
+ env[key] = filtered.env[key];
132
+ const dropped = Object.keys(source).filter(key => source[key] !== undefined && !["LANG", "TZ"].includes(key)).sort();
133
+ const relative = path.relative(root, cwd).split(path.sep).join("/");
134
+ const guestCwd = relative ? `/workspace/${relative}` : "/workspace";
135
+ const mappedArgs = args.map(arg => {
136
+ if (!path.isAbsolute(arg))
137
+ return arg;
138
+ const real = fs.realpathSync.native(arg);
139
+ if (!isInside(root, real))
140
+ throw new RunnerError("OUTSIDE_WORKSPACE", "An absolute argument is outside the repository.");
141
+ return `/workspace/${path.relative(root, real).split(path.sep).join("/")}`;
142
+ });
143
+ // Docker client receives no user's registry/config/plugin environment.
144
+ const clientEnv = { PATH: "/usr/bin:/bin", HOME: "/nonexistent", DOCKER_CONFIG: "/nonexistent" };
145
+ const docker = async (argv) => (await exec(runtime.executable, ["--host", `unix://${runtime.socket}`, ...argv], {
146
+ env: clientEnv, timeout: 10000, maxBuffer: 64 * 1024
147
+ })).stdout;
148
+ // Revalidate at execution even if capability was checked before approval.
149
+ await verifyContainerRuntime(runtime);
150
+ if (req.signal?.aborted)
151
+ throw new RunnerError("CANCELLED", "Cancelled before it started.");
152
+ const started = Date.now();
153
+ const buffer = new HeadTailBuffer(req.headBytes ?? 16 * 1024, req.tailBytes ?? 44 * 1024);
154
+ const counts = { stdout: 0, stderr: 0 };
155
+ let outcome;
156
+ let controlInvalid = false;
157
+ let timedOut = false;
158
+ let cancelled = false;
159
+ let startError = false;
160
+ const child = spawn(runtime.executable, containerArguments(runtime, name, root, req.operationId), {
161
+ cwd: root, env: clientEnv, stdio: ["pipe", "pipe", "pipe"], shell: false
162
+ });
163
+ child.stdin.on("error", () => { });
164
+ const redactors = Object.fromEntries(["stdout", "stderr"].map(stream => [stream, req.redactor.stream(text => {
165
+ buffer.append(text);
166
+ req.onOutput?.(stream, text);
167
+ })]));
168
+ const outDecoder = new StringDecoder("utf8");
169
+ const errDecoder = new StringDecoder("utf8");
170
+ let errPending = "";
171
+ const errorText = (text, final = false) => {
172
+ errPending += text;
173
+ let at;
174
+ while ((at = errPending.indexOf("\n")) >= 0) {
175
+ const line = errPending.slice(0, at);
176
+ errPending = errPending.slice(at + 1);
177
+ if (line.startsWith(marker)) {
178
+ counts.stderr = Math.max(0, counts.stderr - Buffer.byteLength(line + "\n") - 1);
179
+ try {
180
+ if (outcome)
181
+ throw new Error();
182
+ outcome = outcomeFrom(line.slice(marker.length));
183
+ }
184
+ catch {
185
+ controlInvalid = true;
186
+ }
187
+ }
188
+ else
189
+ redactors.stderr.write(line + "\n");
190
+ }
191
+ // Do not let a project grow an unbounded unterminated stderr line.
192
+ if (errPending.length > 8192) {
193
+ redactors.stderr.write(errPending.slice(0, -256));
194
+ errPending = errPending.slice(-256);
195
+ }
196
+ if (final) {
197
+ redactors.stderr.write(errPending);
198
+ errPending = "";
199
+ }
200
+ };
201
+ child.stdout.on("data", (chunk) => { counts.stdout += chunk.length; redactors.stdout.write(outDecoder.write(chunk)); });
202
+ child.stderr.on("data", (chunk) => { counts.stderr += chunk.length; errorText(errDecoder.write(chunk)); });
203
+ child.once("spawn", () => {
204
+ child.stdin.write(JSON.stringify({ program: req.program, args: mappedArgs, cwd: guestCwd, env,
205
+ uid: process.getuid?.() || 1000, gid: process.getgid?.() || 1000, timeoutMs: req.timeoutMs, marker }) + "\n");
206
+ req.onStart?.({ pid: child.pid, resolved: [req.program, ...args] });
207
+ });
208
+ const beat = setInterval(() => { if (!child.stdin.destroyed)
209
+ child.stdin.write("heartbeat\n"); }, 300);
210
+ const stop = () => { clearInterval(beat); child.stdin.end(); };
211
+ const abort = () => { cancelled = true; stop(); };
212
+ req.signal?.addEventListener("abort", abort, { once: true });
213
+ if (req.signal?.aborted)
214
+ abort();
215
+ const timer = setTimeout(() => { if (!cancelled) {
216
+ timedOut = true;
217
+ stop();
218
+ } }, req.timeoutMs);
219
+ // Transport cannot keep the host waiting forever. Cleanup is verified below.
220
+ const hardTimer = setTimeout(() => child.kill("SIGKILL"), req.timeoutMs + 15000);
221
+ await new Promise(resolve => {
222
+ child.once("error", () => { startError = true; resolve(); });
223
+ child.once("close", () => resolve());
224
+ });
225
+ clearInterval(beat);
226
+ clearTimeout(timer);
227
+ clearTimeout(hardTimer);
228
+ req.signal?.removeEventListener("abort", abort);
229
+ redactors.stdout.write(outDecoder.end());
230
+ errorText(errDecoder.end(), true);
231
+ redactors.stdout.end();
232
+ redactors.stderr.end();
233
+ const verified = await removeAndVerifyContainer(docker, name);
234
+ if (!verified)
235
+ throw new RunnerError("COMMAND_UNRESOLVED", "Isolated command cleanup could not be verified; the operation may remain active.");
236
+ if (!startError && outcome?.kind === "not_installed")
237
+ throw new RunnerError("PROGRAM_NOT_FOUND", `${req.program} is not installed in the command runtime image (COS_COMMAND_IMAGE). Use an image that includes it; nothing was run.`);
238
+ if (startError || outcome?.kind === "start_failed")
239
+ throw new RunnerError("START_FAILED", "The isolated project command could not be started.");
240
+ if (controlInvalid || (!outcome && !timedOut && !cancelled))
241
+ throw new RunnerError("COMMAND_UNRESOLVED", "The isolated command stopped without a verified execution result.");
242
+ timedOut ||= !cancelled && outcome?.kind === "timeout";
243
+ if (outcome?.kind === "lease_lost" && !timedOut && !cancelled)
244
+ throw new RunnerError("COMMAND_UNRESOLVED", "The isolated execution lease was lost; cleanup was verified but the command result is unknown.");
245
+ return {
246
+ exit_code: timedOut || cancelled ? null : outcome?.code ?? null,
247
+ signal: timedOut || cancelled ? "SIGKILL" : outcome?.signal ?? null,
248
+ timed_out: timedOut, cancelled: cancelled && !timedOut, tree_killed: timedOut || cancelled,
249
+ started_at: new Date(started).toISOString(), ended_at: new Date().toISOString(), duration_ms: Date.now() - started,
250
+ stdout_bytes: counts.stdout, stderr_bytes: counts.stderr, truncated: buffer.truncated,
251
+ output: buffer.text(), redaction_count: req.redactor.count, dropped_environment_names: dropped,
252
+ resolved_argv: [req.program, ...args], cwd
253
+ };
254
+ }