@carrieros/cli 0.3.0 → 0.4.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 (86) hide show
  1. package/README.md +34 -13
  2. package/dist/commands/chat.js +3 -3
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +27 -12
  5. package/dist/commands/logout.js +1 -0
  6. package/dist/commands/permissions.js +77 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +8 -1
  10. package/dist/commands/update.js +79 -9
  11. package/dist/commands/usage.js +5 -5
  12. package/dist/commands/whoami.js +12 -9
  13. package/dist/ide/editor-context.js +115 -12
  14. package/dist/ide/ide-session.js +274 -13
  15. package/dist/ide/tool-host.js +2 -2
  16. package/dist/main.js +0 -0
  17. package/dist/services/api.js +178 -12
  18. package/dist/services/auth-origin.js +20 -0
  19. package/dist/services/chat-stream.js +26 -3
  20. package/dist/services/checkpoints.js +176 -14
  21. package/dist/services/client-tools.js +113 -21
  22. package/dist/services/code-intel.js +243 -0
  23. package/dist/services/code-symbols.js +94 -0
  24. package/dist/services/coding-workflow.js +554 -0
  25. package/dist/services/command-coordinator.js +85 -12
  26. package/dist/services/command-policy.js +34 -4
  27. package/dist/services/config.js +67 -5
  28. package/dist/services/container-runner.js +254 -0
  29. package/dist/services/container-supervisor.js +38 -0
  30. package/dist/services/context.js +45 -17
  31. package/dist/services/device-auth.js +30 -5
  32. package/dist/services/execution-platform.js +30 -0
  33. package/dist/services/file-resolver.js +1 -1
  34. package/dist/services/folder-key.js +22 -0
  35. package/dist/services/git-tools.js +181 -0
  36. package/dist/services/helper-bin.js +56 -35
  37. package/dist/services/instruction-resolver.js +54 -0
  38. package/dist/services/job-helper.js +31 -10
  39. package/dist/services/local-files.js +148 -26
  40. package/dist/services/local-tools.js +540 -35
  41. package/dist/services/login-flow.js +43 -12
  42. package/dist/services/mutation-coordinator.js +186 -20
  43. package/dist/services/mutation-groups.js +309 -0
  44. package/dist/services/mutation-recovery.js +159 -0
  45. package/dist/services/mutations.js +264 -78
  46. package/dist/services/packaged-update.js +403 -0
  47. package/dist/services/packaged.js +15 -0
  48. package/dist/services/permission-mode.js +60 -0
  49. package/dist/services/process-runner.js +7 -1
  50. package/dist/services/project-context.js +4 -4
  51. package/dist/services/result-reconciliation.js +49 -0
  52. package/dist/services/secure-store.js +21 -1
  53. package/dist/services/session-resolver.js +5 -0
  54. package/dist/services/supported-runtime.js +59 -0
  55. package/dist/services/task-context.js +212 -0
  56. package/dist/services/task-snapshot.js +38 -0
  57. package/dist/services/tool-result-outbox.js +195 -0
  58. package/dist/services/update.js +37 -12
  59. package/dist/services/workspace-registry.js +4 -3
  60. package/dist/services/workspace.js +8 -1
  61. package/dist/shell/shell-chat.js +299 -32
  62. package/dist/shell/shell-commands.js +46 -4
  63. package/dist/shell/shell-prompt.js +21 -11
  64. package/dist/shell/shell-renderer.js +1 -1
  65. package/dist/shell/shell.js +69 -7
  66. package/dist/shell/task-context-view.js +40 -0
  67. package/dist/ui/agent-cards.js +111 -0
  68. package/dist/ui/agent-presentation.js +131 -0
  69. package/dist/ui/approval.js +46 -16
  70. package/dist/ui/banner.js +31 -87
  71. package/dist/ui/change-review.js +293 -46
  72. package/dist/ui/chat-renderer.js +6 -6
  73. package/dist/ui/colors.js +9 -9
  74. package/dist/ui/command-details.js +11 -0
  75. package/dist/ui/command-palette.js +27 -10
  76. package/dist/ui/command-registry.js +9 -2
  77. package/dist/ui/command-review.js +77 -28
  78. package/dist/ui/composer-layout.js +26 -20
  79. package/dist/ui/conversation.js +77 -25
  80. package/dist/ui/live.js +1 -1
  81. package/dist/ui/screen.js +19 -11
  82. package/dist/ui/select.js +6 -0
  83. package/dist/ui/task-context-card.js +99 -0
  84. package/dist/ui/trust.js +7 -12
  85. package/dist/ui/ui.js +23 -0
  86. package/package.json +8 -5
@@ -1,8 +1,12 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
- import { LocalFileError, globFiles, isPathIgnored, listDirectory, readFile, resolveInside, searchFiles, workspaceRoot } from "./local-files.js";
3
+ import { createHash } from "node:crypto";
4
+ import { LocalFileError, MAX_CONTEXT_LINES, globFiles, isPathIgnored, listDirectory, readFile, resolveInside, searchFiles, sliceLines, workspaceRoot } from "./local-files.js";
3
5
  import { RepositoryError, activeRepository, inWorkspaceMode, isWildcardSelector, listRepositories, repositoryTrust, resolveRepository } from "./workspace-registry.js";
4
- import { GitToolError, gitDiff, gitStatus } from "./git-tools.js";
6
+ import { GitToolError, MAX_BLAME_LINES, MAX_LOG_COMMITS, gitBlame, gitDiff, gitLog, gitShow, gitStatus } from "./git-tools.js";
5
7
  import { resolveWorkspaceFile } from "./file-resolver.js";
8
+ import { languageOf, outline, referenceKind, relevance, resolveImport, urlUse } from "./code-intel.js";
9
+ import { declaration } from "./code-symbols.js";
6
10
  /**
7
11
  * Tool descriptors, in the JSON-schema shape the engine already uses for
8
12
  * PROJECT_TOOLS. Exported so a future protocol can advertise the client's
@@ -14,11 +18,17 @@ export const LOCAL_TOOL_DEFINITIONS = [
14
18
  type: "function",
15
19
  function: {
16
20
  name: "read_file",
17
- description: "Read one text file from the user's local project. Paths are relative to the project root.",
21
+ description: "Read one text file from the user's local project. Paths are relative to the project root. " +
22
+ "Pass start_line/end_line to read only those lines (e.g. the function a search located); omit them " +
23
+ "for the complete file. Pass known_sha256 from an earlier complete read in this turn to skip " +
24
+ "re-sending unchanged content.",
18
25
  parameters: {
19
26
  type: "object",
20
27
  properties: {
21
- path: { type: "string", description: "Project-relative path, e.g. src/auth.ts" }
28
+ path: { type: "string", description: "Project-relative path, e.g. src/auth.ts" },
29
+ start_line: { type: "number", description: "First line to read, 1-based." },
30
+ end_line: { type: "number", description: "Last line to read, inclusive." },
31
+ known_sha256: { type: "string", description: "sha256 from an earlier complete read of this file in this turn." }
22
32
  },
23
33
  required: ["path"]
24
34
  }
@@ -43,17 +53,41 @@ export const LOCAL_TOOL_DEFINITIONS = [
43
53
  type: "function",
44
54
  function: {
45
55
  name: "search_files",
46
- description: "Search the user's local project for literal text. Not semantic search.",
56
+ description: "Search the user's local project for literal text, or a regular expression with regex: true. " +
57
+ "Returns path, line number, the matching line and optional surrounding context. Not semantic search.",
47
58
  parameters: {
48
59
  type: "object",
49
60
  properties: {
50
- query: { type: "string", description: "Text to find" },
51
- glob: { type: "string", description: "Restrict to files matching this glob" }
61
+ query: { type: "string", description: "Text (or regex) to find" },
62
+ regex: { type: "boolean", description: "Treat query as a JavaScript regular expression." },
63
+ glob: { type: "string", description: "Restrict to files matching this glob" },
64
+ path: { type: "string", description: "Restrict to this subdirectory" },
65
+ type: { type: "string", description: "Restrict to a file type such as ts, js, py, go" },
66
+ context_lines: { type: "number", description: "Lines of context around each match (0-5)" },
67
+ case_sensitive: { type: "boolean", description: "Match case exactly" },
68
+ max_per_file: { type: "number", description: "Matches reported per file (1-20, default 3)" }
52
69
  },
53
70
  required: ["query"]
54
71
  }
55
72
  }
56
73
  },
74
+ {
75
+ type: "function",
76
+ function: {
77
+ name: "find_files",
78
+ description: "Find files in the user's local project whose path matches a glob such as **/*auth*.js or " +
79
+ "src/**/*.test.ts. Names, sizes and modification times only — no contents.",
80
+ parameters: {
81
+ type: "object",
82
+ properties: {
83
+ pattern: { type: "string", description: "Glob relative to the project root" },
84
+ path: { type: "string", description: "Only look under this subdirectory" },
85
+ limit: { type: "number", description: "Most files to return (1-500)" }
86
+ },
87
+ required: ["pattern"]
88
+ }
89
+ }
90
+ },
57
91
  {
58
92
  type: "function",
59
93
  function: {
@@ -82,6 +116,103 @@ export const LOCAL_TOOL_DEFINITIONS = [
82
116
  }
83
117
  }
84
118
  },
119
+ {
120
+ type: "function",
121
+ function: {
122
+ name: "git_log",
123
+ description: "Read recent commits of the user's local repository, optionally only those touching one file: hash, " +
124
+ "author, date, subject and changed paths. Read-only; never patches.",
125
+ parameters: {
126
+ type: "object",
127
+ properties: {
128
+ path: { type: "string", description: "Only commits touching this project-relative file" },
129
+ limit: { type: "number", description: `Most commits to return (1-${MAX_LOG_COMMITS}, default 10)` }
130
+ }
131
+ }
132
+ }
133
+ },
134
+ {
135
+ type: "function",
136
+ function: {
137
+ name: "git_blame",
138
+ description: `Read which commit last changed each line in a range of one file (at most ${MAX_BLAME_LINES} lines). Read-only.`,
139
+ parameters: {
140
+ type: "object",
141
+ properties: {
142
+ path: { type: "string", description: "Project-relative file path" },
143
+ start_line: { type: "number", description: "First line, 1-based" },
144
+ end_line: { type: "number", description: "Last line, inclusive" }
145
+ },
146
+ required: ["path", "start_line"]
147
+ }
148
+ }
149
+ },
150
+ {
151
+ type: "function",
152
+ function: {
153
+ name: "git_show",
154
+ description: "Read one commit: message, author, date and per-file line counts. Pass path to also get that one " +
155
+ "file's bounded patch. revision is HEAD, HEAD~n, HEAD^ or a commit hash. Read-only.",
156
+ parameters: {
157
+ type: "object",
158
+ properties: {
159
+ revision: { type: "string", description: "HEAD, HEAD~n, HEAD^ or a commit hash" },
160
+ path: { type: "string", description: "Project-relative file whose patch to include" }
161
+ },
162
+ required: ["revision"]
163
+ }
164
+ }
165
+ },
166
+ {
167
+ type: "function",
168
+ function: {
169
+ name: "code_outline",
170
+ description: "Outline one source file without reading all of it: its functions, classes, methods, components and " +
171
+ "types with exact line ranges and whether each is exported, plus its imports (relative ones resolved to " +
172
+ "repository files), HTTP route definitions with their handlers, and client HTTP requests. Heuristic " +
173
+ "(JS/TS, Python, Go): confirm with read_file before relying on it.",
174
+ parameters: {
175
+ type: "object",
176
+ properties: { path: { type: "string", description: "Project-relative file path." } },
177
+ required: ["path"]
178
+ }
179
+ }
180
+ },
181
+ {
182
+ type: "function",
183
+ function: {
184
+ name: "find_symbol",
185
+ description: "Find where a function, class, method, component or type is DEFINED, ranked by relevance (exact exported " +
186
+ "definitions first, tests last). Returns each definition's file, kind and line range — then read_file " +
187
+ "those lines. Use it to follow a call to its implementation.",
188
+ parameters: {
189
+ type: "object",
190
+ properties: {
191
+ name: { type: "string", description: "Identifier, e.g. handleLogin or SessionStore.setSession." },
192
+ path: { type: "string", description: "Only look under this subdirectory." }
193
+ },
194
+ required: ["name"]
195
+ }
196
+ }
197
+ },
198
+ {
199
+ type: "function",
200
+ function: {
201
+ name: "find_references",
202
+ description: "Find where an identifier is USED — calls, imports, JSX usage, other references (definitions excluded) — " +
203
+ "each with its enclosing function; with path (the defining file), also the files that import it. " +
204
+ "Pass a URL path such as /api/login instead to find the server routes that handle it and the client " +
205
+ "code that requests it. Bounded; follow one hop at a time.",
206
+ parameters: {
207
+ type: "object",
208
+ properties: {
209
+ name: { type: "string", description: "Identifier, or a URL path starting with /." },
210
+ path: { type: "string", description: "The file that defines it (adds its importers)." }
211
+ },
212
+ required: ["name"]
213
+ }
214
+ }
215
+ },
85
216
  {
86
217
  type: "function",
87
218
  function: {
@@ -106,6 +237,73 @@ export const LOCAL_TOOL_NAMES = LOCAL_TOOL_DEFINITIONS.map((t) => t.function.nam
106
237
  /** Caps applied to whatever the caller asks for, so a request cannot set its own. */
107
238
  const LIST_LIMIT = 500;
108
239
  const SEARCH_LIMIT = 50;
240
+ /** Repository-intelligence bounds: matches scanned, and files outlined, per call. */
241
+ const INTEL_MATCH_LIMIT = 400;
242
+ const INTEL_FILE_LIMIT = 15;
243
+ /** Most lines one ranged read returns; a function, not a file. */
244
+ export const MAX_RANGE_LINES = 2000;
245
+ /** Ranged reads may address files larger than a complete read can return. */
246
+ const RANGE_SOURCE_BYTES = 1024 * 1024;
247
+ /**
248
+ * File types a search can be restricted to, by extension. Deliberately a
249
+ * closed table: an unknown type is an error the model can correct, never a
250
+ * silently unfiltered search.
251
+ */
252
+ const FILE_TYPES = {
253
+ js: [".js", ".jsx", ".mjs", ".cjs"],
254
+ ts: [".ts", ".tsx", ".mts", ".cts"],
255
+ py: [".py", ".pyi"],
256
+ go: [".go"],
257
+ rs: [".rs"],
258
+ java: [".java", ".kt", ".kts"],
259
+ rb: [".rb"],
260
+ php: [".php"],
261
+ cs: [".cs"],
262
+ c: [".c", ".h", ".cc", ".cpp", ".hpp", ".cxx"],
263
+ swift: [".swift"],
264
+ css: [".css", ".scss", ".sass", ".less"],
265
+ html: [".html", ".htm", ".vue", ".svelte"],
266
+ md: [".md", ".mdx"],
267
+ json: [".json", ".jsonc"],
268
+ yaml: [".yml", ".yaml"],
269
+ sql: [".sql"],
270
+ sh: [".sh", ".bash", ".zsh", ".ps1"]
271
+ };
272
+ export const SEARCH_FILE_TYPES = Object.freeze(Object.keys(FILE_TYPES));
273
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
274
+ /**
275
+ * Complete reads already delivered to the model during ONE turn.
276
+ *
277
+ * Tool results are not replayed into later turns, so this lives exactly as long
278
+ * as a turn and no longer. It lets a repeat read of an unchanged file say
279
+ * "unchanged since your read at X" instead of re-sending the bytes — but only
280
+ * when the model presents the sha256 it was given AND this CLI really did
281
+ * deliver those exact bytes this turn AND they still match disk. The coding
282
+ * workflow invalidates it whenever it requires fresh reads (failure analysis),
283
+ * so a corrective plan always receives complete current content again.
284
+ */
285
+ export class TurnReadCache {
286
+ delivered = new Map();
287
+ static key(repoId, rel) {
288
+ return `${repoId}\0${rel}`;
289
+ }
290
+ record(repoId, rel, sha, toolCallId) {
291
+ if (this.delivered.size >= 200 && !this.delivered.has(TurnReadCache.key(repoId, rel)))
292
+ return;
293
+ this.delivered.set(TurnReadCache.key(repoId, rel), { sha, toolCallId });
294
+ }
295
+ /** The tool call that delivered exactly these bytes this turn, if any. */
296
+ deliveredAs(repoId, rel, sha) {
297
+ const hit = this.delivered.get(TurnReadCache.key(repoId, rel));
298
+ return hit && hit.sha === sha ? hit.toolCallId : undefined;
299
+ }
300
+ invalidate() {
301
+ this.delivered.clear();
302
+ }
303
+ get size() {
304
+ return this.delivered.size;
305
+ }
306
+ }
109
307
  /** Most bytes of one file a tool read returns; beyond this it reports truncated. */
110
308
  export const TOOL_READ_BYTES = 256 * 1024;
111
309
  /**
@@ -139,6 +337,43 @@ function str(v) {
139
337
  function num(v) {
140
338
  return typeof v === "number" && Number.isFinite(v) ? v : undefined;
141
339
  }
340
+ /** An argument or policy refusal with its own public code. */
341
+ class ToolRefusal extends Error {
342
+ code;
343
+ constructor(code, message) {
344
+ super(message);
345
+ this.code = code;
346
+ }
347
+ }
348
+ function bool(v) {
349
+ return v === true;
350
+ }
351
+ /** A positive whole line number, or undefined when absent. Throws on nonsense. */
352
+ function lineArg(v, field) {
353
+ if (v === undefined || v === null)
354
+ return undefined;
355
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1) {
356
+ throw new ToolRefusal("INVALID_ARGUMENTS", `"${field}" must be a positive whole line number.`);
357
+ }
358
+ return v;
359
+ }
360
+ /**
361
+ * Resolve a path for a CONTENT read — read_file, blame, a history patch — and
362
+ * apply every rule a direct read must honour: containment with realpath, the
363
+ * project's ignore rules, and credential-shaped names. One function, so a new
364
+ * content-reading tool cannot forget one of them.
365
+ */
366
+ function contentPath(input, root) {
367
+ const abs = resolveInside(input, root);
368
+ const rel = path.relative(fs.realpathSync.native(root), abs).split(path.sep).join("/");
369
+ if (isPathIgnored(rel, root)) {
370
+ throw new ToolRefusal("IGNORED_PATH", `${input} is excluded by the project's ignore rules.`);
371
+ }
372
+ if (isSensitiveName(path.basename(abs))) {
373
+ throw new ToolRefusal("SENSITIVE_FILE", `${input} looks like a credentials file and is not shared.`);
374
+ }
375
+ return { abs, rel };
376
+ }
142
377
  function fail(id, name, code, message) {
143
378
  return { id, name, ok: false, error: { code, message } };
144
379
  }
@@ -149,7 +384,7 @@ function fail(id, name, code, message) {
149
384
  * correlate, and an exception that unwinds past the transport would strand the
150
385
  * request id. Every failure comes back as `ok: false` with a code.
151
386
  */
152
- export function executeLocalTool(req) {
387
+ export function executeLocalTool(req, opts = {}) {
153
388
  const id = typeof req?.id === "string" && req.id ? req.id : "unknown";
154
389
  const name = typeof req?.name === "string" ? req.name : "";
155
390
  const args = (req?.arguments ?? {});
@@ -161,9 +396,9 @@ export function executeLocalTool(req) {
161
396
  // path below is still resolved inside whichever root the name maps to.
162
397
  const selector = args.repository;
163
398
  const wildcard = isWildcardSelector(selector);
164
- const wildcardOk = name === "list_files" || name === "search_files";
399
+ const wildcardOk = name === "list_files" || name === "search_files" || name === "find_files";
165
400
  if (wildcard && !wildcardOk) {
166
- return fail(id, name, "REPOSITORY_WILDCARD_NOT_ALLOWED", `${name} needs one repository; "*" is only for list_files and search_files.`);
401
+ return fail(id, name, "REPOSITORY_WILDCARD_NOT_ALLOWED", `${name} needs one repository; "*" is only for list_files, find_files and search_files.`);
167
402
  }
168
403
  let repo;
169
404
  try {
@@ -180,8 +415,7 @@ export function executeLocalTool(req) {
180
415
  // could reach an untrusted repository that git_status, git_diff and
181
416
  // resolve_local_file already refuse. The wildcard branches filter with
182
417
  // readableRepositories() themselves; here the single-target path reuses the
183
- // same set, so the single-repository fallback (no repository trusted → the
184
- // active one is still readable) is preserved and trust logic is not duplicated.
418
+ // same set. Being active (including in single-repository mode) grants no trust.
185
419
  if (!wildcard && isContentReadTool(name) && !isReadableRepository(repo)) {
186
420
  return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository. Ask the user to run /repo use ${repo.name} and confirm the trust prompt first.`);
187
421
  }
@@ -191,22 +425,76 @@ export function executeLocalTool(req) {
191
425
  const p = str(args.path);
192
426
  if (!p)
193
427
  return fail(id, name, "INVALID_ARGUMENTS", '"path" is required.');
194
- // readFile does the containment and realpath checks; this layer does not
195
- // re-implement them, it just refuses to bypass them. Capped lower than
196
- // the display read: the result travels back to the server inside a JSON
197
- // body, and a model gets nothing from a megabyte it cannot hold.
198
428
  // A file no listing or search would surface is not readable by name
199
- // either. This is what keeps a gitignored `.env` on the machine when the
200
- // model — or a prompt in some README — asks for it directly.
201
- const resolved = resolveInside(p, root);
202
- const rel = path.relative(root, resolved);
203
- if (isPathIgnored(rel, root)) {
204
- return fail(id, name, "IGNORED_PATH", `${p} is excluded by the project's ignore rules.`);
429
+ // either (contentPath). This is what keeps a gitignored `.env` on the
430
+ // machine when the model — or a prompt in some README — asks for it.
431
+ const { rel } = contentPath(p, root);
432
+ const startLine = lineArg(args.start_line, "start_line");
433
+ const endLine = lineArg(args.end_line, "end_line");
434
+ if (startLine !== undefined && endLine !== undefined && endLine < startLine) {
435
+ return fail(id, name, "INVALID_ARGUMENTS", '"end_line" must not be before "start_line".');
205
436
  }
206
- if (isSensitiveName(path.basename(resolved))) {
207
- return fail(id, name, "SENSITIVE_FILE", `${p} looks like a credentials file and is not shared.`);
437
+ if (startLine !== undefined || endLine !== undefined) {
438
+ // A ranged read: the lines a search pointed at, not the whole file.
439
+ // It may address a file larger than a complete read returns, and it
440
+ // never counts as a complete read unless it really is every byte.
441
+ const res = readFile({ path: p, maxBytes: RANGE_SOURCE_BYTES, root });
442
+ const from = startLine ?? 1;
443
+ const requestedEnd = endLine ?? from + MAX_RANGE_LINES - 1;
444
+ const to = Math.min(requestedEnd, from + MAX_RANGE_LINES - 1);
445
+ const slice = sliceLines(res.text, from, to);
446
+ let content = slice.text;
447
+ let cut = to < requestedEnd;
448
+ if (Buffer.byteLength(content, "utf8") > TOOL_READ_BYTES) {
449
+ content = content.slice(0, TOOL_READ_BYTES);
450
+ content = content.slice(0, Math.max(0, content.lastIndexOf("\n") + 1));
451
+ cut = true;
452
+ }
453
+ const returnedEnd = cut ? slice.startLine + countLines(content) - 1 : slice.endLine;
454
+ const complete = !res.truncated && !cut && content === res.text;
455
+ return {
456
+ id,
457
+ name,
458
+ ok: true,
459
+ result: {
460
+ ...repositoryLabel(repo),
461
+ path: res.path,
462
+ content,
463
+ range: true,
464
+ start_line: slice.startLine,
465
+ end_line: returnedEnd,
466
+ // Unknown when the source itself was longer than the ranged-read cap.
467
+ ...(res.truncated ? { source_truncated: true } : { total_lines: slice.totalLines, sha256: sha256(res.text) }),
468
+ ...(cut ? { range_truncated: true } : {}),
469
+ complete,
470
+ truncated: !complete,
471
+ size: res.size
472
+ }
473
+ };
208
474
  }
475
+ const known = str(args.known_sha256)?.toLowerCase();
209
476
  const res = readFile({ path: p, maxBytes: TOOL_READ_BYTES, root });
477
+ const digest = res.truncated ? undefined : sha256(res.text);
478
+ if (known && digest === known && opts.readCache) {
479
+ const previous = opts.readCache.deliveredAs(repo.id, rel, digest);
480
+ if (previous) {
481
+ return {
482
+ id,
483
+ name,
484
+ ok: true,
485
+ result: {
486
+ ...repositoryLabel(repo),
487
+ path: res.path,
488
+ unchanged: true,
489
+ previous_tool_call_id: previous,
490
+ sha256: digest,
491
+ size: res.size,
492
+ line_count: countLines(res.text),
493
+ note: "Unchanged since the complete read returned earlier in this turn; content omitted."
494
+ }
495
+ };
496
+ }
497
+ }
210
498
  return {
211
499
  id,
212
500
  name,
@@ -221,7 +509,8 @@ export function executeLocalTool(req) {
221
509
  // lines of a long file by eye is exactly the kind of "roughly" this
222
510
  // tool exists to replace. Omitted when the read was truncated — a
223
511
  // count of the first N bytes would be a wrong answer, not a partial one.
224
- ...(res.truncated ? {} : { line_count: countLines(res.text) })
512
+ ...(res.truncated ? {} : { line_count: countLines(res.text), start_line: 1, end_line: countLines(res.text), sha256: digest }),
513
+ ...(known && known !== digest ? { known_sha256_matched: false } : {})
225
514
  }
226
515
  };
227
516
  }
@@ -251,20 +540,52 @@ export function executeLocalTool(req) {
251
540
  return { id, name, ok: true, result: { ...repositoryLabel(repo), ...listOne(repo) } };
252
541
  }
253
542
  case "search_files": {
254
- const query = str(args.query);
255
- if (!query)
543
+ const query = typeof args.query === "string" && args.query.length ? args.query : undefined;
544
+ if (!query || !query.trim())
256
545
  return fail(id, name, "INVALID_ARGUMENTS", '"query" is required.');
546
+ const typeArg = str(args.type)?.toLowerCase();
547
+ const exts = typeArg ? FILE_TYPES[typeArg] : undefined;
548
+ if (typeArg && !exts) {
549
+ return fail(id, name, "INVALID_ARGUMENTS", `Unknown file type "${typeArg}". Supported: ${SEARCH_FILE_TYPES.join(", ")}.`);
550
+ }
551
+ const include = exts ? (rel) => exts.includes(path.extname(rel).toLowerCase()) : undefined;
552
+ const contextLines = Math.min(MAX_CONTEXT_LINES, Math.max(0, Math.floor(num(args.context_lines) ?? 0)));
553
+ const maxPerFile = Math.min(20, Math.max(1, Math.floor(num(args.max_per_file) ?? 3)));
554
+ const sub = str(args.path);
257
555
  // Each repository is searched on its own, under its own limits, and its
258
556
  // matches are labelled — two files called src/auth.ts in two
259
557
  // repositories must never arrive as one ambiguous list.
260
558
  const searchOne = (handle) => {
261
- const res = searchFiles({ query, glob: str(args.glob), limit: SEARCH_LIMIT, root: handle.root });
559
+ if (sub)
560
+ resolveInside(sub, handle.root); // containment first, before any walk
561
+ const res = searchFiles({
562
+ query,
563
+ regex: bool(args.regex),
564
+ caseSensitive: bool(args.case_sensitive),
565
+ glob: str(args.glob),
566
+ path: sub,
567
+ include,
568
+ contextLines,
569
+ maxPerFile,
570
+ limit: SEARCH_LIMIT,
571
+ root: handle.root
572
+ });
262
573
  return {
263
574
  // Search already skips ignored paths; a credentials file that is NOT
264
575
  // gitignored would still show its matching line, so drop those.
265
- matches: res.matches
576
+ matches: rankMatches(res.matches, query)
266
577
  .filter((m) => !isSensitiveName(path.basename(m.path)))
267
- .map((m) => ({ path: m.path, line: m.line, snippet: m.text })),
578
+ .map((m) => ({
579
+ path: m.path,
580
+ line: m.line,
581
+ snippet: m.text,
582
+ // The enclosing function/class, so the next step can be "who calls it?"
583
+ ...(m.symbol ? { symbol: m.symbol } : {}),
584
+ ...(m.before ? { before: m.before, after: m.after } : {})
585
+ })),
586
+ files_scanned: res.filesScanned,
587
+ files_matched: res.filesMatched,
588
+ ...(res.longLinesSkipped ? { long_lines_skipped: res.longLinesSkipped } : {}),
268
589
  truncated: res.truncated
269
590
  };
270
591
  };
@@ -274,6 +595,137 @@ export function executeLocalTool(req) {
274
595
  }
275
596
  return { id, name, ok: true, result: { ...repositoryLabel(repo), ...searchOne(repo) } };
276
597
  }
598
+ case "code_outline": {
599
+ const p = str(args.path);
600
+ if (!p)
601
+ return fail(id, name, "INVALID_ARGUMENTS", '"path" is required.');
602
+ const { rel } = contentPath(p, root); // the read policy, as read_file
603
+ const res = readFile({ path: p, maxBytes: RANGE_SOURCE_BYTES, root });
604
+ const o = outline(res.text, rel);
605
+ const exists = (r) => { try {
606
+ contentPath(r, root);
607
+ return fs.statSync(path.join(root, r)).isFile();
608
+ }
609
+ catch {
610
+ return false;
611
+ } };
612
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), path: rel, sha256: createHash("sha256").update(res.text).digest("hex"),
613
+ language: o.language, symbols: o.symbols, imports: o.imports.map((i) => ({ ...i, resolved: resolveImport(i.specifier, rel, exists) })),
614
+ routes: o.routes, requests: o.requests, truncated: o.truncated || res.truncated, heuristic: true } };
615
+ }
616
+ case "find_symbol":
617
+ case "find_references": {
618
+ const wanted = str(args.name)?.trim();
619
+ if (!wanted || wanted.length > 200)
620
+ return fail(id, name, "INVALID_ARGUMENTS", '"name" is required (at most 200 characters).');
621
+ const sub = str(args.path);
622
+ const isUrl = name === "find_references" && wanted.startsWith("/");
623
+ if (!isUrl && !/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)?$/.test(wanted))
624
+ return fail(id, name, "INVALID_ARGUMENTS", '"name" must be an identifier (Class.method allowed) or, for find_references, a URL path.');
625
+ const ident = wanted.split(".").pop();
626
+ const escaped = (isUrl ? wanted : ident).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
627
+ const search = searchFiles({ query: isUrl ? `['"\`]${escaped}['"\`?]` : `\\b${escaped}\\b`, regex: true, caseSensitive: true,
628
+ path: name === "find_symbol" ? sub : undefined, include: (r) => languageOf(r) !== "text", maxPerFile: 20, limit: INTEL_MATCH_LIMIT, root });
629
+ const hits = search.matches.filter((m) => !isSensitiveName(path.basename(m.path)));
630
+ if (name === "find_symbol") {
631
+ // Candidate files from the search, outlined through the read policy; definitions only.
632
+ const byFile = new Map();
633
+ for (const m of hits)
634
+ byFile.set(m.path, (byFile.get(m.path) ?? 0) + 1);
635
+ const defs = [];
636
+ for (const rel of [...byFile.keys()].slice(0, INTEL_FILE_LIMIT)) {
637
+ let text;
638
+ try {
639
+ contentPath(rel, root);
640
+ text = readFile({ path: rel, maxBytes: RANGE_SOURCE_BYTES, root }).text;
641
+ }
642
+ catch {
643
+ continue;
644
+ }
645
+ const container = wanted.includes(".") ? wanted.split(".")[0] : undefined;
646
+ for (const sym of outline(text, rel).symbols) {
647
+ if (sym.name !== ident || (container && sym.container !== container))
648
+ continue;
649
+ const score = relevance(rel, ident, { definition: true, count: byFile.get(rel) ?? 0 }) + (sym.exported ? 5 : 0) + (sym.container ? 0 : 2);
650
+ defs.push({ path: rel, symbol: sym.container ? `${sym.container}.${sym.name}` : sym.name, kind: sym.kind, start_line: sym.start_line, end_line: sym.end_line, exported: sym.exported, score });
651
+ }
652
+ }
653
+ defs.sort((a, b) => b.score - a.score || String(a.path).localeCompare(String(b.path)));
654
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), name: wanted, definitions: defs.slice(0, 10).map(({ score: _s, ...d }) => d),
655
+ files_searched: search.filesScanned, truncated: search.truncated || defs.length > 10, heuristic: true } };
656
+ }
657
+ if (isUrl) {
658
+ const routes = [], requests = [], other = [];
659
+ for (const m of hits) {
660
+ const use = urlUse(m.text, wanted);
661
+ const entry = { path: m.path, line: m.line, snippet: m.text, ...(m.symbol ? { symbol: m.symbol } : {}) };
662
+ (use === "route" ? routes : use === "request" ? requests : other).push(entry);
663
+ }
664
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), url: wanted, routes: routes.slice(0, 20), requests: requests.slice(0, 20), other: other.slice(0, 10),
665
+ files_searched: search.filesScanned, truncated: search.truncated, heuristic: true } };
666
+ }
667
+ const references = hits.map((m) => ({ path: m.path, line: m.line, kind: referenceKind(m.text, ident), snippet: m.text, ...(m.symbol ? { in: m.symbol } : {}) }))
668
+ .filter((r) => r.kind !== "definition");
669
+ // Importers of the defining file: imports in candidate files that resolve to it.
670
+ let importers;
671
+ if (sub) {
672
+ const target = contentPath(sub, root).rel;
673
+ const exists = (r) => { try {
674
+ contentPath(r, root);
675
+ return fs.statSync(path.join(root, r)).isFile();
676
+ }
677
+ catch {
678
+ return false;
679
+ } };
680
+ const stem = path.posix.basename(target).replace(/\.[^.]+$/, "");
681
+ const near = searchFiles({ query: stem, caseSensitive: true, include: (r) => languageOf(r) !== "text" && r !== target, maxPerFile: 5, limit: INTEL_MATCH_LIMIT, root });
682
+ importers = [];
683
+ for (const rel of [...new Set(near.matches.map((m) => m.path))].slice(0, INTEL_FILE_LIMIT)) {
684
+ let text;
685
+ try {
686
+ contentPath(rel, root);
687
+ text = readFile({ path: rel, maxBytes: RANGE_SOURCE_BYTES, root }).text;
688
+ }
689
+ catch {
690
+ continue;
691
+ }
692
+ for (const i of outline(text, rel).imports)
693
+ if (resolveImport(i.specifier, rel, exists) === target)
694
+ importers.push({ path: rel, line: i.line, names: i.names });
695
+ }
696
+ }
697
+ const counts = new Map();
698
+ for (const r of references)
699
+ counts.set(r.path, (counts.get(r.path) ?? 0) + 1);
700
+ references.sort((a, b) => relevance(b.path, ident, { definition: false, count: counts.get(b.path) ?? 0 }) - relevance(a.path, ident, { definition: false, count: counts.get(a.path) ?? 0 }) || a.path.localeCompare(b.path) || a.line - b.line);
701
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), name: wanted, references: references.slice(0, 50), ...(importers ? { importers: importers.slice(0, 20) } : {}),
702
+ files_searched: search.filesScanned, truncated: search.truncated || references.length > 50, heuristic: true } };
703
+ }
704
+ case "find_files": {
705
+ const pattern = str(args.pattern);
706
+ if (!pattern)
707
+ return fail(id, name, "INVALID_ARGUMENTS", '"pattern" is required.');
708
+ const sub = str(args.path);
709
+ const limit = Math.min(LIST_LIMIT, Math.max(1, Math.floor(num(args.limit) ?? 200)));
710
+ const findOne = (handle) => {
711
+ if (sub)
712
+ resolveInside(sub, handle.root);
713
+ const res = globFiles({ pattern, path: sub, limit, root: handle.root });
714
+ return {
715
+ files: res.entries.map((e) => ({
716
+ path: e.path,
717
+ size: e.size,
718
+ ...(e.modified ? { modified: new Date(e.modified).toISOString() } : {})
719
+ })),
720
+ truncated: res.truncated
721
+ };
722
+ };
723
+ if (wildcard) {
724
+ const perRepo = readableRepositories().map((handle) => ({ ...repositoryLabel(handle), ...findOne(handle) }));
725
+ return { id, name, ok: true, result: { repositories: perRepo, truncated: perRepo.some((r) => r.truncated === true) } };
726
+ }
727
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), pattern, ...findOne(repo) } };
728
+ }
277
729
  case "resolve_local_file": {
278
730
  const reference = str(args.reference);
279
731
  if (!reference)
@@ -370,9 +822,44 @@ export function executeLocalTool(req) {
370
822
  }
371
823
  };
372
824
  }
825
+ case "git_log":
826
+ case "git_blame":
827
+ case "git_show": {
828
+ // History is a whole-repository read, so it honours trust exactly as
829
+ // git_status does, and any path goes through the content-read rules.
830
+ if (repositoryTrust(repo) !== "trusted") {
831
+ return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository.`);
832
+ }
833
+ const p = str(args.path);
834
+ const target = p ? contentPath(p, root) : undefined;
835
+ if (name === "git_log") {
836
+ const res = gitLog(root, { path: target?.rel, limit: num(args.limit) });
837
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), ...(target ? { path: target.rel } : {}), ...res } };
838
+ }
839
+ if (name === "git_blame") {
840
+ if (!target)
841
+ return fail(id, name, "INVALID_ARGUMENTS", '"path" is required.');
842
+ const start = lineArg(args.start_line, "start_line");
843
+ if (start === undefined)
844
+ return fail(id, name, "INVALID_ARGUMENTS", '"start_line" is required.');
845
+ const end = lineArg(args.end_line, "end_line") ?? start + 49;
846
+ if (end < start)
847
+ return fail(id, name, "INVALID_ARGUMENTS", '"end_line" must not be before "start_line".');
848
+ const res = gitBlame(root, target.rel, start, end);
849
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), path: target.rel, start_line: start, end_line: end, ...res } };
850
+ }
851
+ const revision = str(args.revision);
852
+ if (!revision)
853
+ return fail(id, name, "INVALID_ARGUMENTS", '"revision" is required.');
854
+ const res = gitShow(root, revision, target?.rel);
855
+ return { id, name, ok: true, result: { ...repositoryLabel(repo), ...res } };
856
+ }
373
857
  }
374
858
  }
375
859
  catch (err) {
860
+ if (err instanceof ToolRefusal) {
861
+ return fail(id, name, err.code, err.message);
862
+ }
376
863
  if (err instanceof LocalFileError) {
377
864
  return fail(id, name, err.code, err.message);
378
865
  }
@@ -395,18 +882,36 @@ function repositoryLabel(handle) {
395
882
  * become a way to read a repository the user never opened.
396
883
  */
397
884
  function readableRepositories() {
398
- const all = listRepositories().filter((r) => repositoryTrust(r) === "trusted");
399
- return all.length ? all : [activeRepository()];
885
+ return listRepositories().filter((r) => repositoryTrust(r) === "trusted");
400
886
  }
401
887
  /** The tools that read or search file CONTENT, and so must respect trust. */
888
+ /**
889
+ * Search results, most relevant FILE first — a file defining the term, then one
890
+ * named after it, then by how often it matches; tests last. Lines keep their
891
+ * order within a file, and no match is added or dropped.
892
+ */
893
+ function rankMatches(matches, query) {
894
+ const term = query.replace(/\\[bBwWsSdD]|[^A-Za-z0-9_$]+/g, " ").trim().split(/\s+/).sort((a, b) => b.length - a.length)[0] ?? "";
895
+ const files = new Map();
896
+ matches.forEach((m, i) => {
897
+ const f = files.get(m.path) ?? { first: i, count: 0, definition: false };
898
+ f.count++;
899
+ if (term && declaration(m.text)?.name.toLowerCase() === term.toLowerCase())
900
+ f.definition = true;
901
+ files.set(m.path, f);
902
+ });
903
+ const score = new Map([...files].map(([p, f]) => [p, relevance(p, term, f)]));
904
+ return [...matches].sort((a, b) => (score.get(b.path) - score.get(a.path)) || (files.get(a.path).first - files.get(b.path).first) || a.line - b.line);
905
+ }
402
906
  function isContentReadTool(name) {
403
- return name === "read_file" || name === "list_files" || name === "search_files";
907
+ return name === "read_file" || name === "list_files" || name === "search_files" || name === "find_files" ||
908
+ name === "code_outline" || name === "find_symbol" || name === "find_references";
404
909
  }
405
910
  /**
406
911
  * Whether a single, named-or-active repository may be read/searched — the same
407
912
  * trust rule the wildcard fan-out applies (`readableRepositories`), so a named
408
913
  * or active target can never reach a repository "*" would skip. Reused rather
409
- * than re-deriving trust, and it inherits the single-repository fallback.
914
+ * than re-deriving trust, including when no repositories are trusted.
410
915
  */
411
916
  function isReadableRepository(handle) {
412
917
  return readableRepositories().some((r) => r.id === handle.id);
@@ -422,7 +927,7 @@ function isReadableRepository(handle) {
422
927
  */
423
928
  export function describeToolCall(req) {
424
929
  const args = (req.arguments ?? {});
425
- const detail = str(args.path) ?? str(args.query) ?? str(args.glob) ?? "";
930
+ const detail = str(args.path) ?? str(args.query) ?? str(args.pattern) ?? str(args.revision) ?? str(args.glob) ?? "";
426
931
  const repo = str(args.repository);
427
932
  return `${req.id} ${req.name}${repo ? ` [${repo}]` : ""}${detail ? ` ${detail}` : ""}`;
428
933
  }