@carrieros/cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,261 @@
1
+ import os from "node:os";
2
+ import axios, { isAxiosError } from "axios";
3
+ import { ApiError } from "./api.js";
4
+ import { cliVersion } 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
+ /** Is this URL pointing at the machine we are running on? */
24
+ function isLoopback(url) {
25
+ try {
26
+ const host = new URL(url).hostname;
27
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ /**
34
+ * Local authorization-site default (dev convenience).
35
+ *
36
+ * The browser step happens on the MAIN Carrier OS site now, so against a local
37
+ * API this opens the local main site (:3000) rather than the production URL the
38
+ * API returns when CLI_AUTHORIZE_URL / FRONTEND_URL aren't set.
39
+ *
40
+ * It deliberately stands down when the API already returned a loopback URL: an
41
+ * API that IS configured knows where its authorization page lives — possibly on
42
+ * a different port than this guess — and overriding it would send the browser
43
+ * somewhere with no such page. The guess only covers a local API that handed
44
+ * back a production URL.
45
+ *
46
+ * Override with CARRIEROS_PLATFORM_URL or `--platform`.
47
+ */
48
+ export function localAuthorizeDefault(apiUrl, verificationUri) {
49
+ if (verificationUri && isLoopback(verificationUri))
50
+ return undefined;
51
+ return isLoopback(apiUrl) ? "http://localhost:3000" : undefined;
52
+ }
53
+ /** Swap the origin (scheme + host) of a URL, preserving its path + query. Lets
54
+ * the CLI point the browser at a local platform during development without the
55
+ * API's PLATFORM_FRONTEND_URL being set. Returns the input unchanged on error
56
+ * or when no override is given. */
57
+ export function withPlatformOrigin(url, override) {
58
+ if (!override)
59
+ return url;
60
+ try {
61
+ const u = new URL(url);
62
+ const o = new URL(override);
63
+ u.protocol = o.protocol;
64
+ u.host = o.host;
65
+ return u.toString();
66
+ }
67
+ catch {
68
+ return url;
69
+ }
70
+ }
71
+ /** A friendly device label so the developer can recognise this machine in the
72
+ * Devices list (e.g. "cos on DESKTOP-ABC (win32)"). */
73
+ export function deviceLabel() {
74
+ const host = os.hostname?.() || "unknown-host";
75
+ return `cos on ${host} (${process.platform})`;
76
+ }
77
+ const osName = () => {
78
+ switch (process.platform) {
79
+ case "win32":
80
+ return "Windows";
81
+ case "darwin":
82
+ return "macOS";
83
+ case "linux":
84
+ return "Linux";
85
+ default:
86
+ return process.platform;
87
+ }
88
+ };
89
+ /** Best-effort terminal/host identification for the approval page. */
90
+ const clientName = () => {
91
+ if (process.env.TERM_PROGRAM === "vscode")
92
+ return "VS Code Terminal";
93
+ if (process.env.WT_SESSION)
94
+ return "Windows Terminal";
95
+ if (process.env.TERM_PROGRAM === "Apple_Terminal")
96
+ return "Apple Terminal";
97
+ if (process.env.TERM_PROGRAM)
98
+ return `${process.env.TERM_PROGRAM} Terminal`;
99
+ return "Terminal";
100
+ };
101
+ /** The User-Agent the CLI presents so the browser approval page can show a
102
+ * human "OS · client" instead of a raw HTTP library string. Parsed on the
103
+ * platform by the same `CarrierOS-CLI/<v> (<os>; <client>)` shape. */
104
+ export function cliUserAgent() {
105
+ return `CarrierOS-CLI/${cliVersion()} (${osName()}; ${clientName()})`;
106
+ }
107
+ /** Open a URL in the user's default browser, cross-platform, with no extra deps.
108
+ * Best-effort: if it fails the caller still shows the URL to open manually.
109
+ *
110
+ * Goes through the same checked, shell-free opener as every other link: the
111
+ * URL comes from the server, and a `cmd /c start` here would let a `&` in it
112
+ * run a second command. */
113
+ export function openBrowser(url) {
114
+ try {
115
+ openUrl(url);
116
+ return true;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ }
122
+ /** A bare axios call to the platform-auth base that returns the parsed envelope
123
+ * WITHOUT throwing on 4xx — so the poll loop can read RFC 8628 error codes. */
124
+ async function envelopePost(url, body, headers) {
125
+ try {
126
+ const res = await axios.post(url, body, {
127
+ headers: {
128
+ "Content-Type": "application/json",
129
+ "User-Agent": cliUserAgent(),
130
+ ...(headers ?? {})
131
+ },
132
+ timeout: 30_000,
133
+ validateStatus: () => true
134
+ });
135
+ return { status: res.status, body: res.data };
136
+ }
137
+ catch (err) {
138
+ if (isAxiosError(err) && ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "ECONNABORTED"].includes(err.code ?? "")) {
139
+ throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${url}.`, 0);
140
+ }
141
+ throw new ApiError("REQUEST_FAILED", err instanceof Error ? err.message : String(err));
142
+ }
143
+ }
144
+ /** Step 1 — ask the server to start a device authorization. */
145
+ export async function startDeviceAuthorization(authBase, label) {
146
+ const { body } = await envelopePost(`${authBase}/device/code`, { label });
147
+ if (body?.success && body.data)
148
+ return body.data;
149
+ throw new ApiError(body?.error?.code ?? "DEVICE_START_FAILED", body?.error?.message ?? "Could not start login.");
150
+ }
151
+ /** Step 2 — one poll of the token endpoint. */
152
+ async function pollOnce(authBase, deviceCode) {
153
+ const { body } = await envelopePost(`${authBase}/device/token`, {
154
+ device_code: deviceCode
155
+ });
156
+ if (body?.success && body.data)
157
+ return { kind: "approved", data: body.data };
158
+ switch (body?.error?.code) {
159
+ case "AUTHORIZATION_PENDING":
160
+ return { kind: "pending" };
161
+ case "SLOW_DOWN":
162
+ return { kind: "slow_down" };
163
+ case "ACCESS_DENIED":
164
+ return { kind: "denied" };
165
+ case "EXPIRED_TOKEN":
166
+ return { kind: "expired" };
167
+ default:
168
+ return { kind: "error", message: body?.error?.message ?? "Authorization failed." };
169
+ }
170
+ }
171
+ /** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
172
+ * `onTick` between polls so the caller can animate a spinner. */
173
+ export async function pollForToken(authBase, start, onTick) {
174
+ let intervalMs = Math.max(1, start.interval || 5) * 1000;
175
+ const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
176
+ while (Date.now() < deadline) {
177
+ onTick?.();
178
+ await sleep(intervalMs);
179
+ const outcome = await pollOnce(authBase, start.device_code);
180
+ switch (outcome.kind) {
181
+ case "approved":
182
+ return outcome.data;
183
+ case "pending":
184
+ break;
185
+ case "slow_down":
186
+ intervalMs += 5_000; // back off per RFC 8628
187
+ break;
188
+ case "denied":
189
+ throw new ApiError("ACCESS_DENIED", "Authorization was cancelled in the browser.");
190
+ case "expired":
191
+ throw new ApiError("EXPIRED_TOKEN", "The code expired before it was approved. Run `cos login` again.");
192
+ case "error":
193
+ throw new ApiError("AUTH_FAILED", outcome.message);
194
+ }
195
+ }
196
+ throw new ApiError("TIMEOUT", "Timed out waiting for approval. Run `cos login` again.");
197
+ }
198
+ /** Exchange a refresh token for a new session (rotation). Never clears anything
199
+ * itself — the caller decides, from the outcome, whether the session is over. */
200
+ export async function refreshCliSession(apiUrl, refreshToken) {
201
+ const authBase = platformAuthBase(apiUrl);
202
+ const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
203
+ refresh_token: refreshToken
204
+ });
205
+ if (body?.success && body.data)
206
+ return { kind: "ok", data: body.data };
207
+ if (status === 401)
208
+ return { kind: "dead" };
209
+ if (status === 409)
210
+ return { kind: "busy" };
211
+ return { kind: "transient", status };
212
+ }
213
+ /** Best-effort server-side logout (revokes the refresh token). Never throws. */
214
+ export async function logoutCliSession(apiUrl, refreshToken) {
215
+ try {
216
+ await envelopePost(`${platformAuthBase(apiUrl)}/cli/logout`, { refresh_token: refreshToken });
217
+ }
218
+ catch {
219
+ /* offline logout is fine — the local credentials are cleared regardless */
220
+ }
221
+ }
222
+ // ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
223
+ async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
224
+ const url = `${platformAuthBase(apiUrl)}${path}`;
225
+ const token = provider.token();
226
+ const res = await axios.request({
227
+ url,
228
+ method,
229
+ data: body,
230
+ headers: {
231
+ "Content-Type": "application/json",
232
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
233
+ },
234
+ timeout: 30_000,
235
+ validateStatus: () => true
236
+ });
237
+ if (res.status === 401 && retry && provider.refresh) {
238
+ const renewed = await provider.refresh(token);
239
+ if (renewed)
240
+ return authedRequest(apiUrl, method, path, provider, body, false);
241
+ }
242
+ const env = res.data;
243
+ if (env?.success && env.data !== undefined)
244
+ return env.data;
245
+ throw new ApiError(env?.error?.code ?? "REQUEST_FAILED", env?.error?.message ?? "Request failed.", res.status);
246
+ }
247
+ export function listCliWorkspaces(apiUrl, provider) {
248
+ return authedRequest(apiUrl, "get", "/cli/workspaces", provider);
249
+ }
250
+ export function listCliProjects(apiUrl, provider, workspaceId) {
251
+ return authedRequest(apiUrl, "get", `/cli/workspaces/${workspaceId}/projects`, provider);
252
+ }
253
+ export function setCliScope(apiUrl, provider, workspaceId, projectId) {
254
+ return authedRequest(apiUrl, "post", "/cli/scope", provider, {
255
+ workspace_id: workspaceId,
256
+ project_id: projectId
257
+ });
258
+ }
259
+ export function getCliContext(apiUrl, provider) {
260
+ return authedRequest(apiUrl, "get", "/cli/context", provider);
261
+ }
@@ -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,104 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isInside } from "./local-files.js";
4
+ import { repositoryForPath } from "./workspace-registry.js";
5
+ /** Split input into tokens, honoring double quotes so paths with spaces work. */
6
+ function tokenize(input) {
7
+ const tokens = [];
8
+ const re = /"([^"]*)"|(\S+)/g;
9
+ let m;
10
+ while ((m = re.exec(input)) !== null) {
11
+ if (m[1] !== undefined)
12
+ tokens.push({ value: m[1], quoted: true });
13
+ else
14
+ tokens.push({ value: m[2], quoted: false });
15
+ }
16
+ return tokens;
17
+ }
18
+ /** A token worth checking as a path: has a separator or a file extension. */
19
+ function looksLikePath(s) {
20
+ return /[\\/]/.test(s) || /\.[a-z0-9]{1,8}$/i.test(s);
21
+ }
22
+ /**
23
+ * Resolve a token to a file this workspace may attach.
24
+ *
25
+ * Attaching UPLOADS the file, so auto-detection has to obey the same boundary
26
+ * as every other local read. It used to accept any existing path at all — so
27
+ * `"C:\Users\me\.ssh\id_rsa" explain this`, typed from inside a project, would
28
+ * have sent that key to the server with nothing but the folder-trust prompt for
29
+ * the directory the shell started in standing in the way.
30
+ *
31
+ * Two checks, as in local-files.ts: the resolved path must be inside the
32
+ * workspace root, and so must its realpath — which is what stops a symlink or
33
+ * junction inside the project from pointing the upload somewhere else.
34
+ */
35
+ function resolveToken(token) {
36
+ try {
37
+ const abs = path.resolve(token);
38
+ if (!(fs.existsSync(abs) && fs.statSync(abs).isFile()))
39
+ return { kind: "none" };
40
+ // A workspace holds several repositories, so "inside the workspace" means
41
+ // inside ONE OF THEM — never the folder that contains them. A file in no
42
+ // registered repository is still outside, exactly as before.
43
+ const owner = repositoryForPath(abs);
44
+ if (!owner)
45
+ return { kind: "outside", abs };
46
+ const real = fs.realpathSync.native(abs);
47
+ // The realpath must belong to the SAME repository: a junction inside repo A
48
+ // pointing at repo B is not a file of A, and following it would attach one
49
+ // repository's file under another's name.
50
+ const realOwner = repositoryForPath(real);
51
+ if (!realOwner || realOwner.id !== owner.id || !isInside(owner.root, real))
52
+ return { kind: "outside", abs };
53
+ return { kind: "file", abs, repository: owner.name };
54
+ }
55
+ catch {
56
+ return { kind: "none" }; // invalid path — not a file
57
+ }
58
+ }
59
+ /**
60
+ * Detect local file path(s) at the START of the message (a leading run) or in
61
+ * any QUOTED token, and return the message with those tokens stripped. Only the
62
+ * leading run + quoted tokens are considered, so a filename mentioned mid-
63
+ * sentence (e.g. "tell me about report.pdf") is NOT uploaded.
64
+ *
65
+ * "D:\a\report.pdf summarize" → { files: [D:\a\report.pdf], prompt: "summarize" }
66
+ * "report.pdf explain this" → { files: [report.pdf], prompt: "explain this" }
67
+ * "\"./my notes.txt\" summarize"→ { files: [./my notes.txt], prompt: "summarize" }
68
+ * "just a normal question" → { files: [], prompt: "just a normal question" }
69
+ */
70
+ export function detectLocalFiles(input) {
71
+ const tokens = tokenize(input);
72
+ const files = [];
73
+ const rejected = [];
74
+ const consumed = new Set();
75
+ let inLeadingRun = true;
76
+ tokens.forEach((t, i) => {
77
+ const consider = t.quoted || inLeadingRun;
78
+ let matched = false;
79
+ if (consider && looksLikePath(t.value)) {
80
+ const r = resolveToken(t.value);
81
+ if (r.kind === "file") {
82
+ files.push(r.abs);
83
+ consumed.add(i);
84
+ matched = true;
85
+ }
86
+ else if (r.kind === "outside") {
87
+ // Not attached, and left in the prompt as the text the user typed — the
88
+ // file's CONTENT is what must not leave the machine, not their words.
89
+ rejected.push(r.abs);
90
+ }
91
+ }
92
+ // The leading run ends at the first non-quoted token that isn't a file path.
93
+ if (inLeadingRun && !matched && !t.quoted)
94
+ inLeadingRun = false;
95
+ });
96
+ if (files.length === 0)
97
+ return { files: [], prompt: input.trim(), rejected };
98
+ const prompt = tokens
99
+ .filter((_, i) => !consumed.has(i))
100
+ .map((t) => t.value)
101
+ .join(" ")
102
+ .trim();
103
+ return { files, prompt, rejected };
104
+ }