@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,288 @@
1
+ import os from "node:os";
2
+ import axios, { isAxiosError } from "axios";
3
+ import { ApiError } from "./api.js";
4
+ import { cliVersion, clientHeaders } from "./meta.js";
5
+ import { openUrl } from "./open-url.js";
6
+ import { sleep } from "./spinner.js";
7
+ /**
8
+ * device-auth — the transport for the OAuth 2.0 Device Authorization (RFC 8628)
9
+ * flow that backs the browser-based `cos login`. These are low-level primitives
10
+ * (start / poll / refresh / logout / manage scope); the user-facing orchestration
11
+ * and printing live in login-flow.ts.
12
+ *
13
+ * The device + CLI endpoints live under `/api/platform/auth`, NOT under `/v1`,
14
+ * so we derive that base from the configured API URL.
15
+ */
16
+ /** Derive `<origin>/api/platform/auth` from an API base like
17
+ * `https://api.carrieros.ai/v1` or `http://localhost:5000/v1`. */
18
+ export function platformAuthBase(apiUrl) {
19
+ const trimmed = apiUrl.replace(/\/+$/, "");
20
+ const origin = trimmed.replace(/\/v\d+$/i, ""); // drop a trailing /v1
21
+ return `${origin}/api/platform/auth`;
22
+ }
23
+ /** Dedicated user-owned CLI auth endpoints; existing sessions retain their issuer. */
24
+ export function userCliAuthBase(apiUrl) {
25
+ return platformAuthBase(apiUrl).replace(/\/platform\/auth$/, "/cli/auth");
26
+ }
27
+ /** Unverified claims select an endpoint only; the server authenticates the token.
28
+ * Both choices stay on the configured, origin-validated API. */
29
+ export function cliSessionAuthBase(apiUrl, token) {
30
+ try {
31
+ const claims = JSON.parse(Buffer.from((token ?? "").split(".")[1], "base64url").toString("utf8"));
32
+ if (claims.realm === "carrier-cli")
33
+ return userCliAuthBase(apiUrl);
34
+ }
35
+ catch { /* legacy and opaque credentials retain their original endpoint */ }
36
+ return platformAuthBase(apiUrl);
37
+ }
38
+ /** Is this URL pointing at the machine we are running on? */
39
+ function isLoopback(url) {
40
+ try {
41
+ const host = new URL(url).hostname;
42
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ /**
49
+ * Local authorization-site default (dev convenience).
50
+ *
51
+ * The browser step happens on the MAIN Carrier OS site now, so against a local
52
+ * API this opens the local main site (:3000) rather than the production URL the
53
+ * API returns when CLI_AUTHORIZE_URL / FRONTEND_URL aren't set.
54
+ *
55
+ * It deliberately stands down when the API already returned a loopback URL: an
56
+ * API that IS configured knows where its authorization page lives — possibly on
57
+ * a different port than this guess — and overriding it would send the browser
58
+ * somewhere with no such page. The guess only covers a local API that handed
59
+ * back a production URL.
60
+ *
61
+ * Override with CARRIEROS_PLATFORM_URL or `--platform`.
62
+ */
63
+ export function localAuthorizeDefault(apiUrl, verificationUri) {
64
+ if (verificationUri && isLoopback(verificationUri))
65
+ return undefined;
66
+ return isLoopback(apiUrl) ? "http://localhost:3000" : undefined;
67
+ }
68
+ /** Swap the origin (scheme + host) of a URL, preserving its path + query. Lets
69
+ * the CLI point the browser at a local platform during development without the
70
+ * API's PLATFORM_FRONTEND_URL being set. Returns the input unchanged on error
71
+ * or when no override is given. */
72
+ export function withPlatformOrigin(url, override) {
73
+ if (!override)
74
+ return url;
75
+ try {
76
+ const u = new URL(url);
77
+ const o = new URL(override);
78
+ u.protocol = o.protocol;
79
+ u.host = o.host;
80
+ return u.toString();
81
+ }
82
+ catch {
83
+ return url;
84
+ }
85
+ }
86
+ /** A friendly device label so the developer can recognise this machine in the
87
+ * Devices list (e.g. "cos on DESKTOP-ABC (win32)"). */
88
+ export function deviceLabel() {
89
+ const host = os.hostname?.() || "unknown-host";
90
+ return `cos on ${host} (${process.platform})`;
91
+ }
92
+ const osName = () => {
93
+ switch (process.platform) {
94
+ case "win32":
95
+ return "Windows";
96
+ case "darwin":
97
+ return "macOS";
98
+ case "linux":
99
+ return "Linux";
100
+ default:
101
+ return process.platform;
102
+ }
103
+ };
104
+ /** Best-effort terminal/host identification for the approval page. */
105
+ const clientName = () => {
106
+ if (process.env.TERM_PROGRAM === "vscode")
107
+ return "VS Code Terminal";
108
+ if (process.env.WT_SESSION)
109
+ return "Windows Terminal";
110
+ if (process.env.TERM_PROGRAM === "Apple_Terminal")
111
+ return "Apple Terminal";
112
+ if (process.env.TERM_PROGRAM)
113
+ return `${process.env.TERM_PROGRAM} Terminal`;
114
+ return "Terminal";
115
+ };
116
+ /** The User-Agent the CLI presents so the browser approval page can show a
117
+ * human "OS · client" instead of a raw HTTP library string. Parsed on the
118
+ * platform by the same `CarrierOS-CLI/<v> (<os>; <client>)` shape. */
119
+ export function cliUserAgent() {
120
+ return `CarrierOS-CLI/${cliVersion()} (${osName()}; ${clientName()})`;
121
+ }
122
+ /** Open a URL in the user's default browser, cross-platform, with no extra deps.
123
+ * Best-effort: if it fails the caller still shows the URL to open manually.
124
+ *
125
+ * Goes through the same checked, shell-free opener as every other link: the
126
+ * URL comes from the server, and a `cmd /c start` here would let a `&` in it
127
+ * run a second command. */
128
+ export function openBrowser(url) {
129
+ try {
130
+ openUrl(url);
131
+ return true;
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
137
+ /** A bare axios call to the platform-auth base that returns the parsed envelope
138
+ * WITHOUT throwing on 4xx — so the poll loop can read RFC 8628 error codes. */
139
+ async function envelopePost(url, body, headers) {
140
+ try {
141
+ const res = await axios.post(url, body, {
142
+ headers: {
143
+ "Content-Type": "application/json",
144
+ "User-Agent": cliUserAgent(),
145
+ ...clientHeaders(),
146
+ ...(headers ?? {})
147
+ },
148
+ timeout: 30_000,
149
+ maxRedirects: 0,
150
+ validateStatus: () => true
151
+ });
152
+ return { status: res.status, body: res.data };
153
+ }
154
+ catch (err) {
155
+ if (isAxiosError(err) && ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "ECONNABORTED"].includes(err.code ?? "")) {
156
+ throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${url}.`, 0);
157
+ }
158
+ throw new ApiError("REQUEST_FAILED", err instanceof Error ? err.message : String(err));
159
+ }
160
+ }
161
+ /** Step 1 — ask the server to start a device authorization. */
162
+ export async function startDeviceAuthorization(authBase, label) {
163
+ const { body } = await envelopePost(`${authBase}/device/code`, { label });
164
+ if (body?.success && body.data)
165
+ return body.data;
166
+ throw new ApiError(body?.error?.code ?? "DEVICE_START_FAILED", body?.error?.message ?? "Could not start login.");
167
+ }
168
+ /** Step 2 — one poll of the token endpoint. */
169
+ async function pollOnce(authBase, deviceCode) {
170
+ const { body } = await envelopePost(`${authBase}/device/token`, {
171
+ device_code: deviceCode
172
+ });
173
+ if (body?.success && body.data)
174
+ return { kind: "approved", data: body.data };
175
+ switch (body?.error?.code) {
176
+ case "AUTHORIZATION_PENDING":
177
+ return { kind: "pending" };
178
+ case "SLOW_DOWN":
179
+ return { kind: "slow_down" };
180
+ case "ACCESS_DENIED":
181
+ return { kind: "denied" };
182
+ case "EXPIRED_TOKEN":
183
+ return { kind: "expired" };
184
+ default:
185
+ return { kind: "error", message: body?.error?.message ?? "Authorization failed." };
186
+ }
187
+ }
188
+ /** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
189
+ * `onTick` between polls so the caller can animate a spinner. */
190
+ export async function pollForToken(authBase, start, onTick,
191
+ /** Stops polling: an approval that arrives after it is never used. */
192
+ signal) {
193
+ let intervalMs = Math.max(1, start.interval || 5) * 1000;
194
+ const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
195
+ while (Date.now() < deadline) {
196
+ onTick?.();
197
+ await sleep(intervalMs);
198
+ if (signal?.aborted)
199
+ throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
200
+ const outcome = await pollOnce(authBase, start.device_code);
201
+ if (signal?.aborted)
202
+ throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
203
+ switch (outcome.kind) {
204
+ case "approved":
205
+ return outcome.data;
206
+ case "pending":
207
+ break;
208
+ case "slow_down":
209
+ intervalMs += 5_000; // back off per RFC 8628
210
+ break;
211
+ case "denied":
212
+ throw new ApiError("ACCESS_DENIED", "Authorization was cancelled in the browser.");
213
+ case "expired":
214
+ throw new ApiError("EXPIRED_TOKEN", "The code expired before it was approved. Run `cos login` again.");
215
+ case "error":
216
+ throw new ApiError("AUTH_FAILED", outcome.message);
217
+ }
218
+ }
219
+ throw new ApiError("TIMEOUT", "Timed out waiting for approval. Run `cos login` again.");
220
+ }
221
+ /** Exchange a refresh token for a new session (rotation). Never clears anything
222
+ * itself — the caller decides, from the outcome, whether the session is over. */
223
+ export async function refreshCliSession(apiUrl, refreshToken) {
224
+ const authBase = cliSessionAuthBase(apiUrl, refreshToken);
225
+ const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
226
+ refresh_token: refreshToken
227
+ });
228
+ if (body?.success && body.data)
229
+ return { kind: "ok", data: body.data };
230
+ if (status === 401)
231
+ return { kind: "dead" };
232
+ if (status === 409)
233
+ return { kind: "busy" };
234
+ if (status === 404)
235
+ return { kind: "unsupported" };
236
+ return { kind: "transient", status };
237
+ }
238
+ /** Best-effort server-side logout (revokes the refresh token). Never throws. */
239
+ export async function logoutCliSession(apiUrl, refreshToken) {
240
+ try {
241
+ await envelopePost(`${cliSessionAuthBase(apiUrl, refreshToken)}/cli/logout`, { refresh_token: refreshToken });
242
+ }
243
+ catch {
244
+ /* offline logout is fine — the local credentials are cleared regardless */
245
+ }
246
+ }
247
+ // ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
248
+ async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
249
+ const token = provider.token(apiUrl);
250
+ const url = `${cliSessionAuthBase(apiUrl, token)}${path}`;
251
+ const res = await axios.request({
252
+ url,
253
+ method,
254
+ data: body,
255
+ headers: {
256
+ "Content-Type": "application/json",
257
+ ...clientHeaders(),
258
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
259
+ },
260
+ timeout: 30_000,
261
+ maxRedirects: 0,
262
+ validateStatus: () => true
263
+ });
264
+ if (res.status === 401 && retry && provider.refresh) {
265
+ const renewed = await provider.refresh(token);
266
+ if (renewed)
267
+ return authedRequest(apiUrl, method, path, provider, body, false);
268
+ }
269
+ const env = res.data;
270
+ if (env?.success && env.data !== undefined)
271
+ return env.data;
272
+ throw new ApiError(env?.error?.code ?? "REQUEST_FAILED", env?.error?.message ?? "Request failed.", res.status);
273
+ }
274
+ export function listCliWorkspaces(apiUrl, provider) {
275
+ return authedRequest(apiUrl, "get", "/cli/workspaces", provider);
276
+ }
277
+ export function listCliProjects(apiUrl, provider, workspaceId) {
278
+ return authedRequest(apiUrl, "get", `/cli/workspaces/${workspaceId}/projects`, provider);
279
+ }
280
+ export function setCliScope(apiUrl, provider, workspaceId, projectId) {
281
+ return authedRequest(apiUrl, "post", "/cli/scope", provider, {
282
+ workspace_id: workspaceId,
283
+ project_id: projectId
284
+ });
285
+ }
286
+ export function getCliContext(apiUrl, provider) {
287
+ return authedRequest(apiUrl, "get", "/cli/context", provider);
288
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Line-based unified diffs, for showing a person exactly what a proposed change
3
+ * does before they approve it.
4
+ *
5
+ * Myers' algorithm on the lines that actually differ: the common prefix and
6
+ * suffix are trimmed first, which is what keeps the typical case — a few lines
7
+ * changed in a long file — cheap. When what is left is still huge (a whole-file
8
+ * rewrite), it is shown as a replacement rather than spending seconds finding a
9
+ * minimal edit script nobody will read line by line.
10
+ *
11
+ * Deterministic: the same before/after always yields the same diff, so the
12
+ * text a user approved can be reproduced exactly for the audit and for tests.
13
+ */
14
+ const CONTEXT = 3;
15
+ /** Beyond this many differing lines per side, show a replacement, not an edit script. */
16
+ const MAX_MYERS_LINES = 4000;
17
+ /** Split into lines without their terminators; a trailing newline adds no empty line. */
18
+ export function toLines(text) {
19
+ if (text === "")
20
+ return [];
21
+ const lines = text.split(/\r?\n/);
22
+ if (lines[lines.length - 1] === "")
23
+ lines.pop();
24
+ return lines;
25
+ }
26
+ /** Shortest edit script for a and b, as a list of ops in order. */
27
+ function myers(a, b) {
28
+ const n = a.length;
29
+ const m = b.length;
30
+ const max = n + m;
31
+ const offset = max;
32
+ const v = new Int32Array(2 * max + 2);
33
+ const trace = [];
34
+ let found = -1;
35
+ for (let d = 0; d <= max; d += 1) {
36
+ trace.push(v.slice());
37
+ for (let k = -d; k <= d; k += 2) {
38
+ let x;
39
+ if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) {
40
+ x = v[offset + k + 1]; // down: insertion
41
+ }
42
+ else {
43
+ x = v[offset + k - 1] + 1; // right: deletion
44
+ }
45
+ let y = x - k;
46
+ while (x < n && y < m && a[x] === b[y]) {
47
+ x += 1;
48
+ y += 1;
49
+ }
50
+ v[offset + k] = x;
51
+ if (x >= n && y >= m) {
52
+ found = d;
53
+ break;
54
+ }
55
+ }
56
+ if (found >= 0)
57
+ break;
58
+ }
59
+ // Walk the trace backwards to recover the path.
60
+ const out = [];
61
+ let x = n;
62
+ let y = m;
63
+ for (let d = found; d > 0; d -= 1) {
64
+ const vd = trace[d];
65
+ const k = x - y;
66
+ const down = k === -d || (k !== d && vd[offset + k - 1] < vd[offset + k + 1]);
67
+ const prevK = down ? k + 1 : k - 1;
68
+ const prevX = vd[offset + prevK];
69
+ const prevY = prevX - prevK;
70
+ while (x > prevX && y > prevY) {
71
+ out.push({ op: " ", text: a[x - 1] });
72
+ x -= 1;
73
+ y -= 1;
74
+ }
75
+ if (down)
76
+ out.push({ op: "+", text: b[y - 1] });
77
+ else
78
+ out.push({ op: "-", text: a[x - 1] });
79
+ x = prevX;
80
+ y = prevY;
81
+ }
82
+ while (x > 0 && y > 0) {
83
+ out.push({ op: " ", text: a[x - 1] });
84
+ x -= 1;
85
+ y -= 1;
86
+ }
87
+ return out.reverse();
88
+ }
89
+ /** Full op list for before → after. */
90
+ function editScript(a, b) {
91
+ let start = 0;
92
+ while (start < a.length && start < b.length && a[start] === b[start])
93
+ start += 1;
94
+ let endA = a.length;
95
+ let endB = b.length;
96
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
97
+ endA -= 1;
98
+ endB -= 1;
99
+ }
100
+ const head = a.slice(0, start).map((text) => ({ op: " ", text }));
101
+ const tail = a.slice(endA).map((text) => ({ op: " ", text }));
102
+ const midA = a.slice(start, endA);
103
+ const midB = b.slice(start, endB);
104
+ let middle;
105
+ if (midA.length > MAX_MYERS_LINES || midB.length > MAX_MYERS_LINES) {
106
+ middle = [
107
+ ...midA.map((text) => ({ op: "-", text })),
108
+ ...midB.map((text) => ({ op: "+", text }))
109
+ ];
110
+ }
111
+ else {
112
+ middle = myers(midA, midB);
113
+ }
114
+ return [...head, ...middle, ...tail];
115
+ }
116
+ /** Group an op list into unified-diff hunks with surrounding context. */
117
+ export function diffLines(before, after) {
118
+ const ops = editScript(toLines(before), toLines(after));
119
+ const added = ops.filter((o) => o.op === "+").length;
120
+ const removed = ops.filter((o) => o.op === "-").length;
121
+ const hunks = [];
122
+ let oldLine = 1;
123
+ let newLine = 1;
124
+ let i = 0;
125
+ while (i < ops.length) {
126
+ if (ops[i].op === " ") {
127
+ oldLine += 1;
128
+ newLine += 1;
129
+ i += 1;
130
+ continue;
131
+ }
132
+ // A change starts here: back up for context, then run forward until the
133
+ // changes are separated by more than 2 × CONTEXT unchanged lines.
134
+ const ctxStart = Math.max(0, i - CONTEXT);
135
+ const lead = i - ctxStart;
136
+ const hunk = { oldStart: oldLine - lead, newStart: newLine - lead, oldLines: 0, newLines: 0, lines: [] };
137
+ for (let j = ctxStart; j < i; j += 1) {
138
+ hunk.lines.push(ops[j]);
139
+ hunk.oldLines += 1;
140
+ hunk.newLines += 1;
141
+ }
142
+ let j = i;
143
+ let quiet = 0;
144
+ while (j < ops.length) {
145
+ const op = ops[j];
146
+ if (op.op === " ") {
147
+ quiet += 1;
148
+ if (quiet > CONTEXT * 2)
149
+ break;
150
+ }
151
+ else {
152
+ quiet = 0;
153
+ }
154
+ hunk.lines.push(op);
155
+ if (op.op !== "+")
156
+ hunk.oldLines += 1;
157
+ if (op.op !== "-")
158
+ hunk.newLines += 1;
159
+ if (op.op !== "+")
160
+ oldLine += 1;
161
+ if (op.op !== "-")
162
+ newLine += 1;
163
+ j += 1;
164
+ }
165
+ // Trim trailing context beyond CONTEXT.
166
+ let trailing = 0;
167
+ for (let t = hunk.lines.length - 1; t >= 0 && hunk.lines[t].op === " "; t -= 1)
168
+ trailing += 1;
169
+ const excess = Math.max(0, trailing - CONTEXT);
170
+ if (excess > 0) {
171
+ hunk.lines.splice(hunk.lines.length - excess, excess);
172
+ hunk.oldLines -= excess;
173
+ hunk.newLines -= excess;
174
+ oldLine -= excess;
175
+ newLine -= excess;
176
+ j -= excess;
177
+ }
178
+ hunks.push(hunk);
179
+ i = j;
180
+ }
181
+ return { hunks, added, removed };
182
+ }
183
+ /** Standard unified diff text (`--- a/…`, `+++ b/…`, `@@ … @@`). */
184
+ export function formatUnified(path, result, opts = {}) {
185
+ const lines = [];
186
+ lines.push(opts.oldExists === false ? "--- /dev/null" : `--- a/${path}`);
187
+ lines.push(opts.newExists === false ? "+++ /dev/null" : `+++ b/${path}`);
188
+ for (const h of result.hunks) {
189
+ const oldRange = h.oldLines === 0 ? `${Math.max(0, h.oldStart - 1)},0` : `${h.oldStart},${h.oldLines}`;
190
+ const newRange = h.newLines === 0 ? `${Math.max(0, h.newStart - 1)},0` : `${h.newStart},${h.newLines}`;
191
+ lines.push(`@@ -${oldRange} +${newRange} @@`);
192
+ for (const l of h.lines)
193
+ lines.push(`${l.op}${l.text}`);
194
+ }
195
+ return lines.join("\n");
196
+ }
@@ -0,0 +1,108 @@
1
+ import path from "node:path";
2
+ /**
3
+ * The environment a local command gets: built from an allowlist, never
4
+ * inherited wholesale.
5
+ *
6
+ * A developer's shell environment is where credentials live — cloud keys,
7
+ * registry tokens, CI secrets, other tools' session tokens. A project command
8
+ * is project code the user approved to RUN; it was never approved to read those.
9
+ *
10
+ * Values are never logged or returned — only the NAMES that were dropped, so a
11
+ * prompt or an audit row can say what a command did not get.
12
+ */
13
+ /** Exact names (compared case-insensitively — Windows env names are). */
14
+ const ALLOWED = new Set([
15
+ "PATH",
16
+ "PATHEXT",
17
+ "SystemRoot",
18
+ "SystemDrive",
19
+ "windir",
20
+ "ComSpec",
21
+ "TEMP",
22
+ "TMP",
23
+ "USERPROFILE",
24
+ "APPDATA",
25
+ "LOCALAPPDATA",
26
+ "HOMEDRIVE",
27
+ "HOMEPATH",
28
+ "OS",
29
+ "NUMBER_OF_PROCESSORS",
30
+ "ProgramFiles",
31
+ "ProgramFiles(x86)",
32
+ "ProgramW6432",
33
+ "CommonProgramFiles",
34
+ "CommonProgramFiles(x86)",
35
+ "CommonProgramW6432",
36
+ "ProgramData",
37
+ "USERNAME",
38
+ "COMPUTERNAME",
39
+ "LANG",
40
+ "TZ"
41
+ ].map((n) => n.toUpperCase()));
42
+ /** Prefixes allowed when nothing else rules the name out. */
43
+ const ALLOWED_PREFIXES = ["PROCESSOR_", "NPM_CONFIG_"];
44
+ /** Any of these in a name means it is dropped, even if otherwise allowed. */
45
+ const SENSITIVE_NAME = /(TOKEN|SECRET|PASS|KEY|CRED|AUTH|SESSION|COOKIE|CERT|PRIVATE)/i;
46
+ /** Whole families that are dropped regardless. */
47
+ const DENIED_PREFIX = /^(AWS_|AZURE_|GOOGLE_|GCP_|GCLOUD_|GH_|GITHUB_|GITLAB_|OPENAI_|ANTHROPIC_|CLAUDE_CODE_|HF_|HUGGING|STRIPE_|SLACK_|TWILIO_|SENDGRID_|VAULT_|DOCKER_|KUBE)/i;
48
+ /** Database and connection URLs, by name. */
49
+ const DATABASE_NAME = /(DATABASE|_DB_|^DB_|_URI$|_URL$|DSN|CONNECTION|REDIS|MONGO|POSTGRES|PG[A-Z]*$|MYSQL)/i;
50
+ /** A value that embeds credentials in a URL (`scheme://user:pass@host`). */
51
+ const URL_WITH_USERINFO = /^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/i;
52
+ /** Always set, overriding anything inherited. */
53
+ export const FORCED_ENV = {
54
+ CI: "1",
55
+ GIT_TERMINAL_PROMPT: "0",
56
+ GIT_OPTIONAL_LOCKS: "0",
57
+ NO_COLOR: "1",
58
+ npm_config_update_notifier: "false",
59
+ npm_config_fund: "false"
60
+ };
61
+ function allowedName(name) {
62
+ const upper = name.toUpperCase();
63
+ if (SENSITIVE_NAME.test(upper) || DENIED_PREFIX.test(upper))
64
+ return false;
65
+ if (upper.startsWith("NPM_CONFIG_")) {
66
+ // npm config can carry registry auth (`_auth`, `_authToken`, `//host/:_password`).
67
+ return !/(_AUTH|TOKEN|PASSWORD|USERNAME|EMAIL|CERT|KEY|CAFILE)/.test(upper);
68
+ }
69
+ if (DATABASE_NAME.test(upper))
70
+ return false;
71
+ return ALLOWED.has(upper) || ALLOWED_PREFIXES.some((p) => upper.startsWith(p));
72
+ }
73
+ /**
74
+ * PATH without relative, empty or project-local entries: a `.` or a folder
75
+ * inside the repository would let the project substitute its own `git.exe`.
76
+ */
77
+ export function sanitizePath(value, projectRoot) {
78
+ const root = path.resolve(projectRoot).toLowerCase();
79
+ return value
80
+ .split(path.delimiter)
81
+ .map((p) => p.trim().replace(/^"(.*)"$/, "$1"))
82
+ .filter((p) => p && path.isAbsolute(p))
83
+ .filter((p) => {
84
+ const abs = path.resolve(p).toLowerCase();
85
+ return abs !== root && !abs.startsWith(root + path.sep);
86
+ })
87
+ .join(path.delimiter);
88
+ }
89
+ export function buildChildEnv(source, projectRoot) {
90
+ const env = {};
91
+ const dropped = [];
92
+ for (const [name, value] of Object.entries(source)) {
93
+ if (value === undefined)
94
+ continue;
95
+ if (!allowedName(name) || URL_WITH_USERINFO.test(value)) {
96
+ dropped.push(name);
97
+ continue;
98
+ }
99
+ env[name] = name.toUpperCase() === "PATH" ? sanitizePath(value, projectRoot) : value;
100
+ }
101
+ // Forced values replace any inherited spelling of the same name.
102
+ for (const name of Object.keys(env)) {
103
+ if (Object.keys(FORCED_ENV).some((f) => f.toUpperCase() === name.toUpperCase()))
104
+ delete env[name];
105
+ }
106
+ Object.assign(env, FORCED_ENV);
107
+ return { env, dropped: dropped.sort() };
108
+ }
@@ -0,0 +1,30 @@
1
+ export function executionContract(value = process.platform) {
2
+ const windows = value === "win32";
3
+ const isolated = value === "darwin" || value === "linux";
4
+ const supported = windows || isolated;
5
+ return {
6
+ capability: windows ? "NATIVE_SECURE" : isolated ? "ISOLATED_RUNTIME_REQUIRED" : "UNSUPPORTED",
7
+ backend: windows ? "windows-job" : isolated ? "docker-engine-v1" : null,
8
+ guarantees: {
9
+ descendantTracking: windows ? "job-membership" : isolated ? "pid-namespace" : "unavailable",
10
+ descendantTermination: supported, orphanCleanup: supported, timeout: supported,
11
+ cancellation: supported, workingDirectoryContainment: supported,
12
+ environment: windows ? "filtered-host" : isolated ? "isolated-guest" : "unavailable",
13
+ commandRestrictions: supported
14
+ },
15
+ prerequisite: windows ? "Verified Windows Job Object helper; no breakaway. Native OS acceptance must be verified separately."
16
+ : isolated ? "Secure command execution requires the approved Docker Engine runtime because native process lifecycle guarantees are insufficient."
17
+ : `Secure command execution is unsupported on ${value}.`
18
+ };
19
+ }
20
+ export function executionPlatform(value = process.platform) {
21
+ if (executionContract(value).capability !== "UNSUPPORTED")
22
+ return value;
23
+ throw Object.assign(new Error(executionContract(value).prerequisite), { code: "UNSUPPORTED_PLATFORM" });
24
+ }
25
+ export function executionAdapter(platform) {
26
+ const contract = executionContract(platform);
27
+ if (contract.capability === "UNSUPPORTED")
28
+ executionPlatform(platform);
29
+ return contract.backend === "windows-job" ? "windows-job" : "isolated-container";
30
+ }