@carrieros/cli 0.2.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 (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -1,8 +1,8 @@
1
- import { spawn } from "node:child_process";
2
1
  import os from "node:os";
3
2
  import axios, { isAxiosError } from "axios";
4
3
  import { ApiError } from "./api.js";
5
4
  import { cliVersion } from "./meta.js";
5
+ import { openUrl } from "./open-url.js";
6
6
  import { sleep } from "./spinner.js";
7
7
  /**
8
8
  * device-auth — the transport for the OAuth 2.0 Device Authorization (RFC 8628)
@@ -20,21 +20,35 @@ export function platformAuthBase(apiUrl) {
20
20
  const origin = trimmed.replace(/\/v\d+$/i, ""); // drop a trailing /v1
21
21
  return `${origin}/api/platform/auth`;
22
22
  }
23
- /** Local platform default (dev convenience): when the API is on localhost, the
24
- * browser step should open the local platform (typically :3002) rather than the
25
- * production URL the API returns when PLATFORM_FRONTEND_URL isn't set. Override
26
- * the port with CARRIEROS_PLATFORM_URL. Returns undefined for non-local APIs. */
27
- export function localPlatformDefault(apiUrl) {
23
+ /** Is this URL pointing at the machine we are running on? */
24
+ function isLoopback(url) {
28
25
  try {
29
- const host = new URL(apiUrl).hostname;
30
- if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
31
- return "http://localhost:3002";
32
- }
26
+ const host = new URL(url).hostname;
27
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
33
28
  }
34
29
  catch {
35
- /* not a parseable URL — no local default */
30
+ return false;
36
31
  }
37
- return undefined;
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;
38
52
  }
39
53
  /** Swap the origin (scheme + host) of a URL, preserving its path + query. Lets
40
54
  * the CLI point the browser at a local platform during development without the
@@ -91,20 +105,14 @@ export function cliUserAgent() {
91
105
  return `CarrierOS-CLI/${cliVersion()} (${osName()}; ${clientName()})`;
92
106
  }
93
107
  /** Open a URL in the user's default browser, cross-platform, with no extra deps.
94
- * Best-effort: if it fails the caller still shows the URL to open manually. */
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. */
95
113
  export function openBrowser(url) {
96
114
  try {
97
- if (process.platform === "win32") {
98
- // `start` is a cmd builtin; the empty "" is the window title (avoids the
99
- // URL being consumed as the title when it contains spaces/&).
100
- spawn("cmd", ["/c", "start", "", url], { stdio: "ignore", detached: true }).unref();
101
- }
102
- else if (process.platform === "darwin") {
103
- spawn("open", [url], { stdio: "ignore", detached: true }).unref();
104
- }
105
- else {
106
- spawn("xdg-open", [url], { stdio: "ignore", detached: true }).unref();
107
- }
115
+ openUrl(url);
108
116
  return true;
109
117
  }
110
118
  catch {
@@ -187,16 +195,20 @@ export async function pollForToken(authBase, start, onTick) {
187
195
  }
188
196
  throw new ApiError("TIMEOUT", "Timed out waiting for approval. Run `cos login` again.");
189
197
  }
190
- /** Silently exchange a refresh token for a new session (rotation). Returns null
191
- * if the session is no longer valid (caller should clear + re-login). */
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. */
192
200
  export async function refreshCliSession(apiUrl, refreshToken) {
193
201
  const authBase = platformAuthBase(apiUrl);
194
- const { body } = await envelopePost(`${authBase}/cli/refresh`, {
202
+ const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
195
203
  refresh_token: refreshToken
196
204
  });
197
205
  if (body?.success && body.data)
198
- return body.data;
199
- return null;
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 };
200
212
  }
201
213
  /** Best-effort server-side logout (revokes the refresh token). Never throws. */
202
214
  export async function logoutCliSession(apiUrl, refreshToken) {
@@ -223,7 +235,7 @@ async function authedRequest(apiUrl, method, path, provider, body, retry = true)
223
235
  validateStatus: () => true
224
236
  });
225
237
  if (res.status === 401 && retry && provider.refresh) {
226
- const renewed = await provider.refresh();
238
+ const renewed = await provider.refresh(token);
227
239
  if (renewed)
228
240
  return authedRequest(apiUrl, method, path, provider, body, false);
229
241
  }
@@ -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
+ }