@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,639 @@
1
+ import { enclosingSymbol } from "./code-symbols.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { compileGlob, toPosix } from "./glob-match.js";
5
+ import { IgnoreMatcher, isLowSignalFile } from "./ignore-rules.js";
6
+ import { activeRepository } from "./workspace-registry.js";
7
+ import { getWorkspace } from "./workspace.js";
8
+ /**
9
+ * Reading the machine the CLI is standing on.
10
+ *
11
+ * This is the thick half of "thick client for the filesystem, thin client for
12
+ * reasoning": listing, reading, globbing and searching all happen here, and
13
+ * none of it goes near a model. Nothing in this module uploads, and nothing
14
+ * writes — every operation is read-only, by construction rather than by
15
+ * convention, because the same containment boundary will be load-bearing when
16
+ * writes eventually arrive.
17
+ *
18
+ * The shapes are deliberately structured rather than string-in/string-out
19
+ * (`readFile({ path })`, not `readFile(path)`): a later phase turns these into
20
+ * the executors behind backend tool calls, and the argument objects are already
21
+ * the tool payloads.
22
+ *
23
+ * Relative paths are POSIX-separated everywhere they leave this module, which
24
+ * matches the backend's `codebase_map` and means a local tree and an uploaded
25
+ * ZIP of the same project describe files the same way.
26
+ */
27
+ // ── Budgets ──────────────────────────────────────────────────────────────────
28
+ // A monorepo will happily hand you a million files. Everything here is bounded
29
+ // so a mistyped search cannot pin the terminal, and every limit reports when it
30
+ // bites rather than silently truncating.
31
+ /** Directory entries examined in one traversal. */
32
+ const MAX_VISITED = 20_000;
33
+ /** Read into memory for display. Beyond this the read truncates and says so. */
34
+ const MAX_READ_BYTES = 1024 * 1024;
35
+ /** Files larger than this are skipped by search — cost without much signal. */
36
+ const MAX_SEARCH_FILE_BYTES = 2 * 1024 * 1024;
37
+ /** Bytes sampled to decide whether a file is text. */
38
+ const SNIFF_BYTES = 8192;
39
+ /** Default depth for the tree view. */
40
+ const DEFAULT_TREE_DEPTH = 3;
41
+ export class LocalFileError extends Error {
42
+ code;
43
+ constructor(code, message) {
44
+ super(message);
45
+ this.code = code;
46
+ this.name = "LocalFileError";
47
+ }
48
+ }
49
+ // ── Root and containment ─────────────────────────────────────────────────────
50
+ /**
51
+ * The root every local operation is relative to.
52
+ *
53
+ * The repository root when there is one, so `/files` from `src/components`
54
+ * describes the project rather than the corner of it you happen to be standing
55
+ * in. Otherwise the working directory — Git is not a requirement for reading
56
+ * your own files.
57
+ */
58
+ export function workspaceRoot() {
59
+ // One repository is always the root of everything this module does. In a
60
+ // multi-repository workspace that is the ACTIVE repository — never the
61
+ // folder holding them, which would widen containment to every sibling.
62
+ try {
63
+ return activeRepository().root;
64
+ }
65
+ catch {
66
+ const ws = getWorkspace();
67
+ return ws.repository.root ?? ws.cwd;
68
+ }
69
+ }
70
+ /** Windows compares paths case-insensitively; matches the rule in ui/trust.ts. */
71
+ function normalizeForCompare(p) {
72
+ const resolved = path.resolve(p);
73
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
74
+ }
75
+ /**
76
+ * Is `candidate` the root itself, or beneath it?
77
+ *
78
+ * The separator check is the part that matters: a plain `startsWith` would
79
+ * accept `D:\project-secrets` as inside `D:\project`.
80
+ */
81
+ export function isInside(root, candidate) {
82
+ const r = normalizeForCompare(root);
83
+ const c = normalizeForCompare(candidate);
84
+ return c === r || c.startsWith(r.endsWith(path.sep) ? r : r + path.sep);
85
+ }
86
+ /**
87
+ * Resolve a user-supplied path against the workspace root and refuse anything
88
+ * that leaves it.
89
+ *
90
+ * Checked twice on purpose. The first check catches `..` and absolute paths.
91
+ * The second re-checks after `realpathSync`, which is what catches a symlink or
92
+ * a Windows junction whose own path looks innocent but whose target is not —
93
+ * the check that would otherwise be a hole the moment someone clones a
94
+ * repository containing a link to `C:\Users`.
95
+ */
96
+ export function resolveInside(input, root = workspaceRoot()) {
97
+ // A foreign Windows drive must not become a relative POSIX filename.
98
+ // Native absolute Windows paths still pass through the normal root checks.
99
+ if ((/^[A-Za-z]:/.test(input) || input.startsWith("\\\\")) && !path.isAbsolute(input)) {
100
+ throw new LocalFileError("OUTSIDE_WORKSPACE", `Outside the workspace: ${input}`);
101
+ }
102
+ const abs = path.resolve(root, input);
103
+ if (!isInside(root, abs)) {
104
+ throw new LocalFileError("OUTSIDE_WORKSPACE", `Outside the workspace: ${input}`);
105
+ }
106
+ try {
107
+ const real = fs.realpathSync.native(abs);
108
+ if (!isInside(fs.realpathSync.native(root), real)) {
109
+ throw new LocalFileError("OUTSIDE_WORKSPACE", `${input} links outside the workspace.`);
110
+ }
111
+ return real;
112
+ }
113
+ catch (err) {
114
+ if (err instanceof LocalFileError)
115
+ throw err;
116
+ // realpath fails on a path that does not exist yet; the lexical check above
117
+ // already established it would be inside, so let the caller's stat report it.
118
+ return abs;
119
+ }
120
+ }
121
+ /**
122
+ * Walk the workspace, honouring the ignore policy.
123
+ *
124
+ * Recursive rather than an explicit stack because the .gitignore rules nest the
125
+ * same way the directories do: a rule set is pushed on the way into a directory
126
+ * and truncated on the way out, so a file is judged by every .gitignore at or
127
+ * above it. Depth is bounded, so the recursion is too.
128
+ *
129
+ * Symlinked directories are never descended into. On Windows that also covers
130
+ * junctions and reparse points, which Node reports as symbolic links — the
131
+ * usual way a naive walker ends up looping forever or wandering onto C:.
132
+ */
133
+ export function walkRepository(opts = {}) {
134
+ const root = opts.root ?? workspaceRoot();
135
+ const maxDepth = opts.maxDepth ?? Infinity;
136
+ const maxEntries = opts.maxEntries ?? MAX_VISITED;
137
+ const entries = [];
138
+ const ignore = new IgnoreMatcher();
139
+ const state = { visited: 0, skipped: 0, truncated: false, stop: false };
140
+ const startRel = opts.start ? toPosix(path.normalize(opts.start)).replace(/^\.\/?$/, "").replace(/\/+$/, "") : "";
141
+ const startAbs = startRel ? resolveInside(startRel, root) : root;
142
+ // Starting below the root must not shed the rules above it: a root
143
+ // .gitignore that says `src/generated/` still governs a walk from `src`.
144
+ // Push every ancestor's .gitignore first, and refuse a start that those
145
+ // rules (or the hard excludes) already exclude — the same answer a direct
146
+ // read of that path gets from isPathIgnored.
147
+ if (startRel) {
148
+ const parts = startRel.split("/").filter(Boolean);
149
+ let absDir = root;
150
+ let relDir = "";
151
+ for (let i = 0; i < parts.length; i += 1) {
152
+ try {
153
+ ignore.push(fs.readFileSync(path.join(absDir, ".gitignore"), "utf8"), relDir);
154
+ }
155
+ catch {
156
+ /* no .gitignore at this level */
157
+ }
158
+ absDir = path.join(absDir, parts[i]);
159
+ relDir = relDir ? `${relDir}/${parts[i]}` : parts[i];
160
+ // Every component of a start is a directory, so directory-only rules
161
+ // such as `generated/` apply to it.
162
+ if (ignore.shouldIgnore(relDir, { isDirectory: true })) {
163
+ return { entries: [], truncated: false, visited: 0, skipped: 0 };
164
+ }
165
+ }
166
+ }
167
+ const descend = (absDir, relDir, depth) => {
168
+ if (state.stop)
169
+ return;
170
+ if (opts.signal?.aborted) {
171
+ state.stop = true;
172
+ state.truncated = true;
173
+ return;
174
+ }
175
+ let dirents;
176
+ try {
177
+ dirents = fs.readdirSync(absDir, { withFileTypes: true });
178
+ }
179
+ catch {
180
+ state.skipped += 1;
181
+ return;
182
+ }
183
+ // A .gitignore here governs this directory and everything under it. Free to
184
+ // notice — the listing already named it.
185
+ const restore = ignore.depth;
186
+ if (dirents.some((d) => d.isFile() && d.name === ".gitignore")) {
187
+ try {
188
+ ignore.push(fs.readFileSync(path.join(absDir, ".gitignore"), "utf8"), relDir);
189
+ }
190
+ catch {
191
+ /* unreadable .gitignore — carry on with the hard excludes */
192
+ }
193
+ }
194
+ // Directories first, then files, each alphabetical: a stable, readable tree.
195
+ dirents.sort((a, b) => {
196
+ const ad = a.isDirectory() ? 0 : 1;
197
+ const bd = b.isDirectory() ? 0 : 1;
198
+ return ad !== bd ? ad - bd : a.name.localeCompare(b.name);
199
+ });
200
+ for (const d of dirents) {
201
+ if (state.stop)
202
+ break;
203
+ if (opts.signal?.aborted) {
204
+ state.stop = true;
205
+ state.truncated = true;
206
+ break;
207
+ }
208
+ state.visited += 1;
209
+ if (state.visited > maxEntries) {
210
+ state.truncated = true;
211
+ state.stop = true;
212
+ break;
213
+ }
214
+ const rel = relDir ? `${relDir}/${d.name}` : d.name;
215
+ const abs = path.join(absDir, d.name);
216
+ const isDir = d.isDirectory();
217
+ if (ignore.shouldIgnore(rel, { isDirectory: isDir }))
218
+ continue;
219
+ // Never follow a link out of the tree, and never risk a cycle.
220
+ if (d.isSymbolicLink())
221
+ continue;
222
+ if (isDir) {
223
+ if (opts.includeDirectories !== false) {
224
+ const entry = { path: rel, size: 0, type: "dir", depth };
225
+ entries.push(entry);
226
+ if (opts.onEntry?.(entry) === false) {
227
+ state.stop = true;
228
+ break;
229
+ }
230
+ }
231
+ if (depth < maxDepth)
232
+ descend(abs, rel, depth + 1);
233
+ continue;
234
+ }
235
+ if (!d.isFile())
236
+ continue; // sockets, FIFOs, devices
237
+ let size = 0;
238
+ let modified;
239
+ try {
240
+ const st = fs.statSync(abs);
241
+ size = st.size;
242
+ modified = st.mtimeMs;
243
+ }
244
+ catch {
245
+ state.skipped += 1;
246
+ continue;
247
+ }
248
+ const entry = { path: rel, size, type: "file", depth, modified };
249
+ entries.push(entry);
250
+ if (opts.onEntry?.(entry) === false) {
251
+ state.stop = true;
252
+ break;
253
+ }
254
+ }
255
+ ignore.truncate(restore);
256
+ };
257
+ descend(startAbs, startRel, 1);
258
+ return { entries, truncated: state.truncated, visited: state.visited, skipped: state.skipped };
259
+ }
260
+ /** A bounded tree of the workspace, shaped for display. */
261
+ export function listDirectory(opts = {}) {
262
+ const limit = opts.limit ?? 200;
263
+ const collected = [];
264
+ const res = walkRepository({
265
+ root: opts.root,
266
+ start: opts.path,
267
+ maxDepth: opts.depth ?? DEFAULT_TREE_DEPTH,
268
+ includeDirectories: true,
269
+ signal: opts.signal,
270
+ onEntry: (e) => {
271
+ collected.push(e);
272
+ return collected.length < limit;
273
+ }
274
+ });
275
+ return {
276
+ ...res,
277
+ entries: collected,
278
+ truncated: res.truncated || collected.length >= limit
279
+ };
280
+ }
281
+ // ── Metadata ─────────────────────────────────────────────────────────────────
282
+ const CATEGORY = {
283
+ ".ts": "TypeScript",
284
+ ".tsx": "TypeScript (React)",
285
+ ".js": "JavaScript",
286
+ ".jsx": "JavaScript (React)",
287
+ ".mjs": "JavaScript",
288
+ ".cjs": "JavaScript",
289
+ ".json": "JSON",
290
+ ".md": "Markdown",
291
+ ".py": "Python",
292
+ ".rs": "Rust",
293
+ ".go": "Go",
294
+ ".java": "Java",
295
+ ".rb": "Ruby",
296
+ ".php": "PHP",
297
+ ".cs": "C#",
298
+ ".c": "C",
299
+ ".h": "C header",
300
+ ".cpp": "C++",
301
+ ".css": "CSS",
302
+ ".scss": "Sass",
303
+ ".html": "HTML",
304
+ ".yml": "YAML",
305
+ ".yaml": "YAML",
306
+ ".toml": "TOML",
307
+ ".sql": "SQL",
308
+ ".sh": "Shell",
309
+ ".ps1": "PowerShell",
310
+ ".txt": "Text",
311
+ ".png": "Image",
312
+ ".jpg": "Image",
313
+ ".jpeg": "Image",
314
+ ".gif": "Image",
315
+ ".svg": "Image",
316
+ ".ico": "Image",
317
+ ".pdf": "PDF",
318
+ ".zip": "Archive",
319
+ ".exe": "Executable",
320
+ ".dll": "Library"
321
+ };
322
+ export function categorize(name) {
323
+ const ext = path.extname(name).toLowerCase();
324
+ return CATEGORY[ext] ?? (ext ? ext.slice(1).toUpperCase() : "Unknown");
325
+ }
326
+ export function getFileMetadata(input) {
327
+ const root = input.root ?? workspaceRoot();
328
+ const abs = resolveInside(input.path, root);
329
+ let st;
330
+ try {
331
+ st = fs.statSync(abs);
332
+ }
333
+ catch {
334
+ throw new LocalFileError("NOT_FOUND", `No such file: ${input.path}`);
335
+ }
336
+ const rel = toPosix(path.relative(fs.realpathSync.native(root), abs)) || toPosix(path.basename(abs));
337
+ return {
338
+ path: rel,
339
+ size: st.isDirectory() ? 0 : st.size,
340
+ type: st.isDirectory() ? "dir" : "file",
341
+ depth: rel.split("/").length,
342
+ modified: st.mtimeMs,
343
+ extension: path.extname(abs).toLowerCase(),
344
+ category: st.isDirectory() ? "Directory" : categorize(abs)
345
+ };
346
+ }
347
+ // ── Reading ──────────────────────────────────────────────────────────────────
348
+ /**
349
+ * Does this look like binary?
350
+ *
351
+ * A NUL byte in the first few KB, which is the same heuristic Git uses. Cheap,
352
+ * and wrong only for exotic encodings the CLI would not render usefully anyway.
353
+ */
354
+ export function looksBinary(buf) {
355
+ const end = Math.min(buf.length, SNIFF_BYTES);
356
+ for (let i = 0; i < end; i += 1)
357
+ if (buf[i] === 0)
358
+ return true;
359
+ return false;
360
+ }
361
+ /**
362
+ * Slice whole lines out of `text` without normalizing them.
363
+ *
364
+ * Line endings are kept byte-for-byte, so a range covering the whole file is
365
+ * the whole file — which is what lets the coding workflow keep treating only a
366
+ * byte-identical read as a complete one.
367
+ */
368
+ export function sliceLines(text, startLine, endLine) {
369
+ const starts = [0];
370
+ for (let i = 0; i < text.length; i += 1) {
371
+ const ch = text.charCodeAt(i);
372
+ if (ch === 10 || (ch === 13 && text.charCodeAt(i + 1) !== 10))
373
+ starts.push(i + 1);
374
+ }
375
+ // A trailing newline ends the last line; it does not open another.
376
+ const totalLines = text.length === 0 ? 0 : starts[starts.length - 1] === text.length ? starts.length - 1 : starts.length;
377
+ const start = Math.max(1, Math.floor(startLine));
378
+ const end = Math.min(totalLines, Math.max(start, Math.floor(endLine)));
379
+ if (start > totalLines)
380
+ return { startLine: start, endLine: start - 1, totalLines, text: "" };
381
+ const from = starts[start - 1];
382
+ const to = end < totalLines ? starts[end] : text.length;
383
+ return { startLine: start, endLine: end, totalLines, text: text.slice(from, to) };
384
+ }
385
+ /**
386
+ * Read a text file from inside the workspace.
387
+ *
388
+ * Size is checked with `stat` BEFORE opening, so an enormous file is never
389
+ * pulled into memory just to discover it was enormous. Beyond the cap the read
390
+ * takes the first slice and says it did — silently returning a partial file
391
+ * would be worse than refusing.
392
+ */
393
+ export function readFile(input) {
394
+ const root = input.root ?? workspaceRoot();
395
+ const abs = resolveInside(input.path, root);
396
+ const cap = input.maxBytes ?? MAX_READ_BYTES;
397
+ let st;
398
+ try {
399
+ st = fs.statSync(abs);
400
+ }
401
+ catch {
402
+ throw new LocalFileError("NOT_FOUND", `No such file: ${input.path}`);
403
+ }
404
+ if (st.isDirectory()) {
405
+ throw new LocalFileError("NOT_A_FILE", `${input.path} is a directory.`);
406
+ }
407
+ const wanted = Math.min(st.size, cap);
408
+ let buf;
409
+ try {
410
+ const fd = fs.openSync(abs, "r");
411
+ try {
412
+ buf = Buffer.alloc(wanted);
413
+ fs.readSync(fd, buf, 0, wanted, 0);
414
+ }
415
+ finally {
416
+ fs.closeSync(fd);
417
+ }
418
+ }
419
+ catch {
420
+ throw new LocalFileError("UNREADABLE", `Could not read ${input.path}.`);
421
+ }
422
+ if (looksBinary(buf)) {
423
+ throw new LocalFileError("BINARY", `${input.path} is not a text file.`);
424
+ }
425
+ return {
426
+ path: toPosix(path.relative(fs.realpathSync.native(root), abs)),
427
+ text: buf.toString("utf8"),
428
+ size: st.size,
429
+ truncated: st.size > wanted
430
+ };
431
+ }
432
+ // ── Glob ─────────────────────────────────────────────────────────────────────
433
+ /**
434
+ * Would a walk of the workspace skip this path?
435
+ *
436
+ * The walker answers that implicitly by never descending; a direct read has no
437
+ * walk, so it asks here instead. Same matcher, same rules: every .gitignore from
438
+ * the root down to the file's own directory, plus the hard excludes. Without
439
+ * this a read addressed straight at `node_modules/…` or a gitignored `.env`
440
+ * would succeed even though no listing or search would ever have surfaced it.
441
+ */
442
+ export function isPathIgnored(relPath, root = workspaceRoot()) {
443
+ const parts = toPosix(relPath).split("/").filter((p) => p && p !== ".");
444
+ const ignore = new IgnoreMatcher();
445
+ const pushGitignore = (absDir, relDir) => {
446
+ try {
447
+ ignore.push(fs.readFileSync(path.join(absDir, ".gitignore"), "utf8"), relDir);
448
+ }
449
+ catch {
450
+ /* no .gitignore at this level */
451
+ }
452
+ };
453
+ pushGitignore(root, "");
454
+ let absDir = root;
455
+ for (let i = 0; i < parts.length; i += 1) {
456
+ const rel = parts.slice(0, i + 1).join("/");
457
+ const isLast = i === parts.length - 1;
458
+ if (ignore.shouldIgnore(rel, { isDirectory: !isLast }))
459
+ return true;
460
+ if (!isLast) {
461
+ absDir = path.join(absDir, parts[i]);
462
+ pushGitignore(absDir, rel);
463
+ }
464
+ }
465
+ return false;
466
+ }
467
+ /**
468
+ * Files matching a glob, rooted at the workspace.
469
+ *
470
+ * The pattern is matched against the relative path, so it cannot address
471
+ * anything outside the root no matter what it contains — there is no path
472
+ * resolution here for `..` to act on.
473
+ */
474
+ export function globFiles(opts) {
475
+ const re = compileGlob(toPosix(opts.pattern));
476
+ const limit = opts.limit ?? 500;
477
+ const entries = [];
478
+ const res = walkRepository({
479
+ root: opts.root,
480
+ start: opts.path,
481
+ includeDirectories: false,
482
+ signal: opts.signal,
483
+ onEntry: (e) => {
484
+ if (e.type === "file" && re.test(e.path))
485
+ entries.push(e);
486
+ return entries.length < limit;
487
+ }
488
+ });
489
+ return { paths: entries.map((e) => e.path), entries, truncated: res.truncated || entries.length >= limit };
490
+ }
491
+ /** Longest regular expression accepted. Real searches are nowhere near this. */
492
+ export const MAX_REGEX_CHARS = 512;
493
+ /** Lines longer than this are not tested against a regex (minified bundles, data). */
494
+ const MAX_REGEX_LINE_CHARS = 4000;
495
+ /** Longest context line returned; context is orientation, not content. */
496
+ const MAX_CONTEXT_LINE_CHARS = 400;
497
+ export const MAX_CONTEXT_LINES = 5;
498
+ /**
499
+ * Compile a model-supplied pattern, refusing the shapes that backtrack
500
+ * catastrophically.
501
+ *
502
+ * JavaScript has no regex timeout, so the defence is structural: a bounded
503
+ * pattern length, a bounded line length, and no quantified group that itself
504
+ * contains a quantifier (`(a+)+`, `(\w*)*`, `(x|y+){2,}`) — the classic ReDoS
505
+ * shape. Backreferences are refused for the same reason. A refused pattern is
506
+ * an error the model can rewrite, never a silent literal fallback.
507
+ */
508
+ export function compileSearchRegex(pattern, caseSensitive) {
509
+ if (pattern.length > MAX_REGEX_CHARS)
510
+ throw new LocalFileError("INVALID_PATTERN", "The regular expression is too long.");
511
+ if (/\\[1-9]|\\k</.test(pattern)) {
512
+ throw new LocalFileError("INVALID_PATTERN", "Backreferences are not supported in search patterns.");
513
+ }
514
+ if (/\((?:[^()\\]|\\.)*(?:[+*]|\{\d+,?\d*\})(?:[^()\\]|\\.)*\)\s*(?:[+*]|\{\d+,?\d*\})/.test(pattern)) {
515
+ throw new LocalFileError("INVALID_PATTERN", "Nested quantifiers such as (a+)+ are not supported; simplify the pattern.");
516
+ }
517
+ try {
518
+ return new RegExp(pattern, caseSensitive ? "" : "i");
519
+ }
520
+ catch (err) {
521
+ throw new LocalFileError("INVALID_PATTERN", `Invalid regular expression: ${err.message}`);
522
+ }
523
+ }
524
+ const clip = (line) => line.length > MAX_CONTEXT_LINE_CHARS ? `${line.slice(0, MAX_CONTEXT_LINE_CHARS)}…` : line;
525
+ /**
526
+ * Text search across the workspace.
527
+ *
528
+ * Literal substring matching by default; a JavaScript regular expression when
529
+ * `regex` is set. Never semantic search — a query is what it says it is. Binary
530
+ * files are sniffed and skipped rather than scanned as text, large files are
531
+ * skipped by size, and low-signal files (lockfiles, minified assets, images)
532
+ * never make it here at all because the ignore vocabulary already removed them.
533
+ * The walk is the same contained, ignore-aware walk listing uses, optionally
534
+ * started from a subdirectory that is resolved inside the root.
535
+ */
536
+ export function searchFiles(opts) {
537
+ const limit = opts.limit ?? 50;
538
+ const perFile = opts.maxPerFile ?? 3;
539
+ const context = Math.min(MAX_CONTEXT_LINES, Math.max(0, Math.floor(opts.contextLines ?? 0)));
540
+ const needle = opts.caseSensitive ? opts.query : opts.query.toLowerCase();
541
+ const pattern = opts.regex ? compileSearchRegex(opts.query, Boolean(opts.caseSensitive)) : null;
542
+ const globRe = opts.glob ? compileGlob(toPosix(opts.glob)) : null;
543
+ const matches = [];
544
+ let filesScanned = 0;
545
+ let filesMatched = 0;
546
+ let longLinesSkipped = 0;
547
+ // Hoisted: this is per-search, not per-file.
548
+ const root = opts.root ?? workspaceRoot();
549
+ const lineMatches = (line) => {
550
+ if (!pattern)
551
+ return (opts.caseSensitive ? line : line.toLowerCase()).includes(needle);
552
+ if (line.length > MAX_REGEX_LINE_CHARS) {
553
+ longLinesSkipped += 1;
554
+ return false;
555
+ }
556
+ return pattern.test(line);
557
+ };
558
+ const res = walkRepository({
559
+ // The walk MUST cover the same repository the reads below resolve against —
560
+ // hoisted `root` and an unrooted walk would list one repository's files and
561
+ // read another's.
562
+ root,
563
+ start: opts.path,
564
+ includeDirectories: false,
565
+ signal: opts.signal,
566
+ onEntry: (e) => {
567
+ if (e.type !== "file")
568
+ return true;
569
+ if (globRe && !globRe.test(e.path))
570
+ return true;
571
+ if (opts.include && !opts.include(e.path))
572
+ return true;
573
+ if (isLowSignalFile(e.path.slice(e.path.lastIndexOf("/") + 1)))
574
+ return true;
575
+ if (e.size > MAX_SEARCH_FILE_BYTES)
576
+ return true;
577
+ let buf;
578
+ try {
579
+ buf = fs.readFileSync(path.join(root, e.path));
580
+ }
581
+ catch {
582
+ return true; // unreadable — skip, never fail the whole search
583
+ }
584
+ if (looksBinary(buf))
585
+ return true;
586
+ filesScanned += 1;
587
+ const text = buf.toString("utf8");
588
+ // Reject the whole file before splitting it. Most files do not contain
589
+ // the term at all, and lowercasing them line by line to discover that
590
+ // was the entire cost of a search: 2.5s on a 1000-file repository, spent
591
+ // almost entirely on allocating strings nobody ever looked at. (Literal
592
+ // mode only: a regex cannot be prefiltered this way.)
593
+ if (!pattern) {
594
+ const whole = opts.caseSensitive ? text : text.toLowerCase();
595
+ if (!whole.includes(needle))
596
+ return true;
597
+ }
598
+ const lines = text.split(/\r\n|\r|\n/);
599
+ let hits = 0;
600
+ for (let i = 0; i < lines.length; i += 1) {
601
+ if (!lineMatches(lines[i]))
602
+ continue;
603
+ if (hits === 0)
604
+ filesMatched += 1;
605
+ hits += 1;
606
+ if (hits > perFile)
607
+ break;
608
+ const match = { path: e.path, line: i + 1, text: lines[i].trim() };
609
+ const symbol = enclosingSymbol(lines, i);
610
+ if (symbol)
611
+ match.symbol = symbol;
612
+ if (context > 0) {
613
+ match.before = lines.slice(Math.max(0, i - context), i).map(clip);
614
+ match.after = lines.slice(i + 1, i + 1 + context).map(clip);
615
+ }
616
+ matches.push(match);
617
+ if (matches.length >= limit)
618
+ return false;
619
+ }
620
+ return true;
621
+ }
622
+ });
623
+ return {
624
+ matches,
625
+ filesScanned,
626
+ filesMatched,
627
+ truncated: res.truncated || matches.length >= limit,
628
+ aborted: Boolean(opts.signal?.aborted),
629
+ ...(pattern ? { longLinesSkipped } : {})
630
+ };
631
+ }
632
+ /** "14.2 KB" — sizes read in the terminal, not in bytes. */
633
+ export function formatSize(bytes) {
634
+ if (bytes < 1024)
635
+ return `${bytes} B`;
636
+ if (bytes < 1024 * 1024)
637
+ return `${(bytes / 1024).toFixed(1)} KB`;
638
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
639
+ }