@carrieros/cli-staging 0.0.0-stage → 0.4.1

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 (137) hide show
  1. package/README.md +6 -2
  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 +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +26 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +78 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +160 -0
  27. package/dist/commands/update.js +285 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +229 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +364 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +132 -0
  36. package/dist/services/api.js +441 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/auto-update.js +221 -0
  39. package/dist/services/chat-stream.js +168 -0
  40. package/dist/services/checkpoints.js +278 -0
  41. package/dist/services/client-tools.js +356 -0
  42. package/dist/services/code-intel.js +243 -0
  43. package/dist/services/code-symbols.js +94 -0
  44. package/dist/services/coding-workflow.js +554 -0
  45. package/dist/services/command-coordinator.js +273 -0
  46. package/dist/services/command-policy.js +434 -0
  47. package/dist/services/config.js +384 -0
  48. package/dist/services/container-runner.js +254 -0
  49. package/dist/services/container-supervisor.js +38 -0
  50. package/dist/services/context.js +416 -0
  51. package/dist/services/device-auth.js +288 -0
  52. package/dist/services/diff.js +196 -0
  53. package/dist/services/env-policy.js +108 -0
  54. package/dist/services/execution-platform.js +30 -0
  55. package/dist/services/file-detect.js +104 -0
  56. package/dist/services/file-resolver.js +199 -0
  57. package/dist/services/file-upload.js +126 -0
  58. package/dist/services/folder-key.js +22 -0
  59. package/dist/services/git-tools.js +429 -0
  60. package/dist/services/glob-match.js +164 -0
  61. package/dist/services/helper-bin.js +85 -0
  62. package/dist/services/ignore-rules.js +189 -0
  63. package/dist/services/instruction-resolver.js +54 -0
  64. package/dist/services/job-helper.js +328 -0
  65. package/dist/services/local-files.js +639 -0
  66. package/dist/services/local-tools.js +937 -0
  67. package/dist/services/login-flow.js +156 -0
  68. package/dist/services/meta.js +42 -0
  69. package/dist/services/mutation-coordinator.js +327 -0
  70. package/dist/services/mutation-groups.js +309 -0
  71. package/dist/services/mutation-recovery.js +159 -0
  72. package/dist/services/mutations.js +679 -0
  73. package/dist/services/open-url.js +68 -0
  74. package/dist/services/output.js +62 -0
  75. package/dist/services/packaged-update.js +403 -0
  76. package/dist/services/packaged.js +39 -0
  77. package/dist/services/permission-mode.js +78 -0
  78. package/dist/services/process-runner.js +412 -0
  79. package/dist/services/project-context.js +298 -0
  80. package/dist/services/redaction.js +201 -0
  81. package/dist/services/result-reconciliation.js +49 -0
  82. package/dist/services/secure-store.js +217 -0
  83. package/dist/services/session-resolver.js +115 -0
  84. package/dist/services/sia.js +51 -0
  85. package/dist/services/spinner.js +40 -0
  86. package/dist/services/supported-runtime.js +59 -0
  87. package/dist/services/task-context.js +212 -0
  88. package/dist/services/task-snapshot.js +38 -0
  89. package/dist/services/tool-result-outbox.js +195 -0
  90. package/dist/services/update.js +730 -0
  91. package/dist/services/workspace-registry.js +310 -0
  92. package/dist/services/workspace.js +580 -0
  93. package/dist/shell/shell-chat.js +1622 -0
  94. package/dist/shell/shell-commands.js +411 -0
  95. package/dist/shell/shell-prompt.js +110 -0
  96. package/dist/shell/shell-renderer.js +51 -0
  97. package/dist/shell/shell-router.js +37 -0
  98. package/dist/shell/shell.js +414 -0
  99. package/dist/shell/task-context-view.js +40 -0
  100. package/dist/staging.js +5 -0
  101. package/dist/types/index.js +6 -0
  102. package/dist/ui/agent-cards.js +111 -0
  103. package/dist/ui/agent-presentation.js +131 -0
  104. package/dist/ui/approval.js +111 -0
  105. package/dist/ui/banner.js +56 -0
  106. package/dist/ui/btw-overlay.js +230 -0
  107. package/dist/ui/change-review.js +334 -0
  108. package/dist/ui/chat-renderer.js +463 -0
  109. package/dist/ui/code-block.js +52 -0
  110. package/dist/ui/color-picker.js +100 -0
  111. package/dist/ui/colors.js +55 -0
  112. package/dist/ui/command-details.js +11 -0
  113. package/dist/ui/command-filter.js +92 -0
  114. package/dist/ui/command-item.js +6 -0
  115. package/dist/ui/command-palette.js +383 -0
  116. package/dist/ui/command-registry.js +128 -0
  117. package/dist/ui/command-renderer.js +55 -0
  118. package/dist/ui/command-review.js +187 -0
  119. package/dist/ui/composer-layout.js +74 -0
  120. package/dist/ui/conversation.js +450 -0
  121. package/dist/ui/interrupt.js +35 -0
  122. package/dist/ui/live.js +141 -0
  123. package/dist/ui/logo.js +58 -0
  124. package/dist/ui/markdown.js +205 -0
  125. package/dist/ui/message.js +21 -0
  126. package/dist/ui/screen-prompt.js +181 -0
  127. package/dist/ui/screen.js +297 -0
  128. package/dist/ui/select.js +284 -0
  129. package/dist/ui/sia-qa.js +213 -0
  130. package/dist/ui/spinner.js +23 -0
  131. package/dist/ui/sticky-stream.js +64 -0
  132. package/dist/ui/task-context-card.js +99 -0
  133. package/dist/ui/text-prompt.js +74 -0
  134. package/dist/ui/theme.js +80 -0
  135. package/dist/ui/trust.js +88 -0
  136. package/dist/ui/ui.js +101 -0
  137. package/package.json +33 -4
@@ -0,0 +1,384 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { SealError, isSealed, seal, sealingAvailable, sealingRequired, sealingUnavailableError, unseal } from "./secure-store.js";
6
+ /**
7
+ * A URL is safe to send credentials to only over HTTPS, or over HTTP to a
8
+ * loopback host (local dev). Anything else (a plain-HTTP remote host) would send
9
+ * bearer/refresh tokens in cleartext — reject it so a mistaken or hostile
10
+ * `--url` / env override can't exfiltrate credentials.
11
+ */
12
+ export function isSafeUrl(u) {
13
+ try {
14
+ const x = new URL(u);
15
+ if (x.protocol === "https:")
16
+ return true;
17
+ const loopback = ["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"];
18
+ return x.protocol === "http:" && loopback.includes(x.hostname);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ /** Production default; override at login with `--url` or via CARRIEROS_API_URL.
25
+ * An unsafe (plain-HTTP remote) env override is ignored in favour of the
26
+ * secure default rather than silently leaking tokens. */
27
+ const ENV_API_URL = (process.env.CARRIEROS_API_URL || "").trim();
28
+ export const DEFAULT_API_URL = ENV_API_URL && isSafeUrl(ENV_API_URL) ? ENV_API_URL : "https://api.carrieros.ai/v1";
29
+ /**
30
+ * Do two API base URLs point at the same server?
31
+ *
32
+ * Compared by ORIGIN (scheme + host + port), so `https://api.carrieros.ai/v1`
33
+ * and `https://api.carrieros.ai/v2` are the same server while
34
+ * `http://localhost:5000/v1` is not. Used to decide whether a rejection came
35
+ * from the server that issued the session — the only one whose "no" means the
36
+ * session is over. An unknown value on either side is NOT a match: not knowing
37
+ * who issued a session is a reason to leave it alone, not to delete it.
38
+ */
39
+ export function sameApiOrigin(a, b) {
40
+ if (!a || !b)
41
+ return false;
42
+ try {
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;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ /**
53
+ * ConfigStore — the single owner of on-disk CLI state. Everything the CLI
54
+ * persists (credentials, active session, cached scope, recent uploads) lives in
55
+ * one JSON file so the rest of the app never touches the filesystem directly.
56
+ *
57
+ * Windows-first: `%APPDATA%/CarrierOS/config.json`; falls back to
58
+ * `~/.carrieros/config.json` on other platforms.
59
+ *
60
+ * WRITES ARE MERGES, NOT SNAPSHOTS. A `cos` process can live for hours (the
61
+ * shell) while another one signs in, and the in-memory copy it loaded at
62
+ * startup does not know about that. Writing that copy back — which is what
63
+ * saving a theme, a model, a session id or an update check used to do — served
64
+ * the whole file from a stale snapshot and silently deleted the credentials the
65
+ * other process had just written. Every write now re-reads the file, applies
66
+ * only what THIS call changes, and replaces the file atomically. A field is
67
+ * removed only when a caller asks for it to be removed, which is why logout
68
+ * still works and why nothing else can take `auth` with it.
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", "sessionSelectionToken", "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
+ }
110
+ export class ConfigStore {
111
+ dir;
112
+ file;
113
+ /** The config with credentials OPENED — what every caller reads. */
114
+ data;
115
+ options;
116
+ /**
117
+ * Why stored credentials could not be opened, when they could not: another
118
+ * Windows account, another machine, or a damaged blob. The CLI then behaves
119
+ * as signed out — it never crashes over it, and never deletes the blob, so
120
+ * `cos login` is the recovery and nothing is lost by trying.
121
+ */
122
+ credentialError = null;
123
+ constructor(options = {}) {
124
+ this.options = options;
125
+ this.dir = ConfigStore.resolveDir();
126
+ const fileName = options.fileName ?? "config.json";
127
+ if (path.basename(fileName) !== fileName || !fileName.endsWith(".json"))
128
+ throw new Error("Config filename must be a JSON file name.");
129
+ this.file = path.join(this.dir, fileName);
130
+ this.data = this.reveal(this.read());
131
+ this.protectPlaintextCredentials();
132
+ }
133
+ /**
134
+ * Credentials written before protection existed are still plaintext on disk.
135
+ * Seal them in place the first time a build that can protect them runs.
136
+ * Best-effort: a failure leaves the file exactly as it was.
137
+ */
138
+ protectPlaintextCredentials() {
139
+ const raw = this.read();
140
+ const plaintext = (typeof raw.auth?.accessToken === "string" && !isSealed(raw.auth.accessToken)) ||
141
+ (typeof raw.auth?.refreshToken === "string" && !isSealed(raw.auth.refreshToken)) ||
142
+ (typeof raw.secretKey === "string" && !isSealed(raw.secretKey));
143
+ if (!plaintext || !sealingAvailable())
144
+ return;
145
+ try {
146
+ this.commit({
147
+ ...(raw.auth ? { auth: this.data.auth } : {}),
148
+ ...(typeof raw.secretKey === "string" ? { secretKey: this.data.secretKey } : {})
149
+ });
150
+ }
151
+ catch {
152
+ /* leave the file as it was */
153
+ }
154
+ }
155
+ /**
156
+ * Seal the credential fields of a patch before it is written.
157
+ *
158
+ * Only these three are secrets; everything else in the file — the account
159
+ * email, the workspace, the issuing API — stays readable, so the prompt and
160
+ * an offline `whoami` never need to open anything. Where protection is not
161
+ * available (not Windows, or no C# compiler) the value is written as before:
162
+ * refusing to sign someone in would be worse, and the risk is documented.
163
+ */
164
+ conceal(patch) {
165
+ const canSeal = (v) => typeof v === "string" && v.length > 0 && !isSealed(v);
166
+ const carriesSecret = (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) || canSeal(patch.secretKey);
167
+ // The packaged build fails closed: a missing DPAPI helper is a damaged
168
+ // install, and writing the tokens in plaintext would silently drop the
169
+ // protection the user was promised. Nothing is written; login reports why.
170
+ if (carriesSecret && sealingRequired() && !sealingAvailable())
171
+ throw sealingUnavailableError();
172
+ const out = { ...patch };
173
+ if (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) {
174
+ if (sealingAvailable()) {
175
+ out.auth = {
176
+ ...patch.auth,
177
+ accessToken: canSeal(patch.auth.accessToken) ? seal(patch.auth.accessToken) : patch.auth.accessToken,
178
+ refreshToken: canSeal(patch.auth.refreshToken) ? seal(patch.auth.refreshToken) : patch.auth.refreshToken
179
+ };
180
+ }
181
+ }
182
+ if (canSeal(patch.secretKey) && sealingAvailable())
183
+ out.secretKey = seal(patch.secretKey);
184
+ return out;
185
+ }
186
+ /** Open the credential fields of what is on disk, for the in-memory view. */
187
+ reveal(raw) {
188
+ const out = { ...raw };
189
+ const open = (v) => {
190
+ if (typeof v !== "string")
191
+ return undefined;
192
+ if (!isSealed(v))
193
+ return v;
194
+ try {
195
+ return unseal(v);
196
+ }
197
+ catch (err) {
198
+ this.credentialError =
199
+ err instanceof SealError ? err.message : "Stored credentials could not be opened.";
200
+ return undefined;
201
+ }
202
+ };
203
+ this.credentialError = null;
204
+ if (raw.auth) {
205
+ const accessToken = open(raw.auth.accessToken);
206
+ const refreshToken = open(raw.auth.refreshToken);
207
+ // A session is both halves or neither: half a session would sign the
208
+ // user in and then fail on the first refresh.
209
+ out.auth =
210
+ accessToken && refreshToken
211
+ ? { ...raw.auth, accessToken, refreshToken }
212
+ : undefined;
213
+ }
214
+ if (raw.secretKey !== undefined) {
215
+ const key = open(raw.secretKey);
216
+ if (key)
217
+ out.secretKey = key;
218
+ else
219
+ delete out.secretKey;
220
+ }
221
+ return out;
222
+ }
223
+ static resolveDir() {
224
+ const appData = process.env.APPDATA;
225
+ const profile = process.env.CARRIEROS_CLI_PROFILE === "staging" ? "staging" : undefined;
226
+ if (appData)
227
+ return path.join(appData, "CarrierOS", ...(profile ? [profile] : []));
228
+ return path.join(os.homedir(), ".carrieros", ...(profile ? [profile] : []));
229
+ }
230
+ read() {
231
+ const defaults = {
232
+ apiUrl: this.options.fixedApiUrl ?? this.options.defaultApiUrl ?? DEFAULT_API_URL,
233
+ ...(this.options.fixedPlatformUrl || this.options.defaultPlatformUrl
234
+ ? { platformUrl: this.options.fixedPlatformUrl ?? this.options.defaultPlatformUrl }
235
+ : {})
236
+ };
237
+ let source;
238
+ try {
239
+ source = fs.readFileSync(this.file, "utf8");
240
+ }
241
+ catch (err) {
242
+ if (err.code === "ENOENT")
243
+ return defaults;
244
+ throw new ConfigReadError();
245
+ }
246
+ try {
247
+ const parsed = JSON.parse(source);
248
+ validateConfig(parsed);
249
+ return {
250
+ ...defaults,
251
+ ...parsed,
252
+ ...(this.options.fixedApiUrl ? { apiUrl: this.options.fixedApiUrl } : {}),
253
+ ...(this.options.fixedPlatformUrl ? { platformUrl: this.options.fixedPlatformUrl } : {})
254
+ };
255
+ }
256
+ catch {
257
+ // Never include the parser error: its source excerpt can contain tokens.
258
+ throw new ConfigReadError();
259
+ }
260
+ }
261
+ /**
262
+ * Apply a change on top of what is on disk NOW.
263
+ *
264
+ * `remove` is the only way a key leaves the file. Everything the caller did
265
+ * not mention survives, whoever wrote it and whenever — which is the property
266
+ * that keeps a session alive through an unrelated save from an older process.
267
+ */
268
+ commit(patch, remove = []) {
269
+ // Merge in DISK form: what is already there stays sealed, and the patch is
270
+ // sealed before it joins it. Plaintext credentials never reach the file.
271
+ const merged = {
272
+ ...this.read(),
273
+ ...this.conceal(patch),
274
+ ...(this.options.fixedApiUrl ? { apiUrl: this.options.fixedApiUrl } : {}),
275
+ ...(this.options.fixedPlatformUrl ? { platformUrl: this.options.fixedPlatformUrl } : {})
276
+ };
277
+ for (const key of remove)
278
+ delete merged[key];
279
+ validateConfig(merged);
280
+ this.write(merged);
281
+ this.data = this.reveal(merged);
282
+ }
283
+ /**
284
+ * Replace the file atomically: write a sibling temp file, then rename over
285
+ * the target. A crash or a full disk mid-write leaves the previous config
286
+ * intact instead of a truncated file that reads as "logged out".
287
+ */
288
+ write(data) {
289
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
290
+ const tmp = `${this.file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
291
+ try {
292
+ // `mode` on writeFileSync only applies when the file is CREATED — so a
293
+ // pre-existing file with looser perms would keep them. chmod after the
294
+ // write (and on the dir) to guarantee owner-only tokens. POSIX-only; a
295
+ // no-op on Windows ACLs, hence best-effort.
296
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
297
+ try {
298
+ fs.chmodSync(tmp, 0o600);
299
+ }
300
+ catch {
301
+ /* Windows / restricted FS — best effort */
302
+ }
303
+ fs.renameSync(tmp, this.file);
304
+ }
305
+ catch (err) {
306
+ try {
307
+ fs.unlinkSync(tmp);
308
+ }
309
+ catch {
310
+ /* already gone */
311
+ }
312
+ throw err;
313
+ }
314
+ try {
315
+ fs.chmodSync(this.file, 0o600);
316
+ fs.chmodSync(this.dir, 0o700);
317
+ }
318
+ catch {
319
+ /* Windows / restricted FS — best effort */
320
+ }
321
+ }
322
+ get all() {
323
+ return this.data;
324
+ }
325
+ get(key) {
326
+ return this.data[key];
327
+ }
328
+ set(key, value) {
329
+ // `undefined` is how several callers say "forget this" (e.g. sessionId);
330
+ // it is removed from the file rather than written as a null.
331
+ if (value === undefined)
332
+ this.commit({}, [key]);
333
+ else
334
+ this.commit({ [key]: value });
335
+ }
336
+ update(patch) {
337
+ this.commit(patch);
338
+ }
339
+ /**
340
+ * Re-read the file, discarding the in-memory copy.
341
+ *
342
+ * Every write already goes straight to disk, so the only thing this can pick
343
+ * up is a change made by ANOTHER `cos` process — which is exactly the case
344
+ * token refresh needs: if a second terminal rotated the session, this process
345
+ * is holding a spent refresh token, and presenting it would look to the server
346
+ * like token theft.
347
+ */
348
+ reload() {
349
+ this.data = this.reveal(this.read());
350
+ }
351
+ get isAuthenticated() {
352
+ // Device-flow session is the primary credential; a legacy key still counts.
353
+ return Boolean(this.data.auth?.accessToken || this.data.secretKey);
354
+ }
355
+ /**
356
+ * Wipe credentials + derived state on logout (keeps apiUrl).
357
+ *
358
+ * The ONE place `auth` is removed. Everything else merges, so signing out is
359
+ * something a user asks for rather than something a save can do by accident.
360
+ * Title and ordinals are CACHES OF sessionId: dropping the id without them
361
+ * left the footer naming a conversation the CLI was no longer in, and
362
+ * `/memory 2` resolving against a stale numbering from a previous account.
363
+ */
364
+ clearAuth() {
365
+ this.commit({}, [
366
+ "auth",
367
+ "secretKey",
368
+ "secretKeyApiUrl",
369
+ "sessionId",
370
+ "sessionSelectionToken",
371
+ "sessionTitle",
372
+ "sessionOrdinals",
373
+ "memoryArtifactIds",
374
+ "scope",
375
+ "attachedFileIds"
376
+ ]);
377
+ }
378
+ addUpload(record) {
379
+ // Read-modify-write against the file, so an upload recorded by another
380
+ // process is not dropped by this one.
381
+ const list = this.read().uploads ?? [];
382
+ this.commit({ uploads: [record, ...list].slice(0, 25) });
383
+ }
384
+ }
@@ -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
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Trusted PID 1 code, supplied by the CLI, never read from the repository.
3
+ * Project code runs under a different UID and cannot stop the heartbeat monitor.
4
+ * Exiting PID 1 tears down the PID namespace, including setsid/orphan descendants.
5
+ * The first input line is private control data, not inherited by project code.
6
+ */
7
+ export const CONTAINER_SUPERVISOR = String.raw `
8
+ const {spawn}=require('node:child_process');
9
+ const readline=require('node:readline');
10
+ let request, child, finished=false, last=Date.now();
11
+ function finish(result) {
12
+ if(finished)return;
13
+ finished=true;
14
+ setTimeout(()=>process.exit(0),100);
15
+ if(request) process.stderr.write('\n'+request.marker+JSON.stringify(result)+'\n',()=>process.exit(0));
16
+ else process.exit(125);
17
+ }
18
+ const watchdog=setInterval(()=>{
19
+ if(Date.now()-last>2500) finish({kind:'lease_lost',code:null,signal:null});
20
+ },100);
21
+ const input=readline.createInterface({input:process.stdin});
22
+ input.on('line',line=>{
23
+ if(request) { if(line==='heartbeat')last=Date.now(); return; }
24
+ try {
25
+ request=JSON.parse(line);
26
+ if(!Number.isInteger(request.uid)||request.uid<=0||!Number.isInteger(request.gid)||request.gid<=0)throw Error();
27
+ last=Date.now();
28
+ setTimeout(()=>finish({kind:'timeout',code:null,signal:null}),request.timeoutMs);
29
+ child=spawn(request.program,request.args,{
30
+ cwd:request.cwd,env:request.env,uid:request.uid,gid:request.gid,
31
+ stdio:['ignore','inherit','inherit']
32
+ });
33
+ child.once('error',error=>finish({kind:error&&error.code==='ENOENT'?'not_installed':'start_failed',code:null,signal:null}));
34
+ child.once('exit',(code,signal)=>finish({kind:'exit',code,signal}));
35
+ } catch { finish({kind:'start_failed',code:null,signal:null}); }
36
+ });
37
+ input.on('close',()=>finish({kind:'lease_lost',code:null,signal:null}));
38
+ `;