@carrieros/cli 0.2.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.
- package/README.md +170 -64
- package/dist/commands/attach.js +45 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +81 -15
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +63 -3
- package/dist/commands/files.js +84 -23
- package/dist/commands/help.js +1 -0
- package/dist/commands/history.js +88 -23
- package/dist/commands/login.js +31 -7
- package/dist/commands/logout.js +1 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +39 -3
- package/dist/commands/modes.js +4 -1
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +224 -65
- package/dist/commands/settings.js +94 -0
- package/dist/commands/update.js +229 -0
- package/dist/commands/upload.js +204 -31
- package/dist/commands/usage.js +213 -17
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +355 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +26 -1
- package/dist/services/api.js +315 -15
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +352 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +311 -24
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +296 -23
- package/dist/services/device-auth.js +72 -35
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +55 -17
- package/dist/services/meta.js +3 -1
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +5 -2
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +60 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +113 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +311 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1297 -59
- package/dist/shell/shell-commands.js +243 -12
- package/dist/shell/shell-prompt.js +94 -11
- package/dist/shell/shell-renderer.js +8 -20
- package/dist/shell/shell-router.js +19 -3
- package/dist/shell/shell.js +252 -22
- package/dist/shell/task-context-view.js +40 -0
- package/dist/types/index.js +3 -1
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +31 -48
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +207 -14
- package/dist/ui/colors.js +12 -8
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +26 -5
- package/dist/ui/command-palette.js +44 -14
- package/dist/ui/command-registry.js +92 -10
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +48 -1
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +4 -2
- package/dist/ui/markdown.js +63 -9
- package/dist/ui/message.js +14 -31
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +19 -11
- package/dist/ui/select.js +191 -29
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +27 -1
- package/package.json +18 -4
- package/dist/ui/activity.js +0 -77
|
@@ -0,0 +1,937 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { LocalFileError, MAX_CONTEXT_LINES, globFiles, isPathIgnored, listDirectory, readFile, resolveInside, searchFiles, sliceLines, workspaceRoot } from "./local-files.js";
|
|
5
|
+
import { RepositoryError, activeRepository, inWorkspaceMode, isWildcardSelector, listRepositories, repositoryTrust, resolveRepository } from "./workspace-registry.js";
|
|
6
|
+
import { GitToolError, MAX_BLAME_LINES, MAX_LOG_COMMITS, gitBlame, gitDiff, gitLog, gitShow, gitStatus } from "./git-tools.js";
|
|
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";
|
|
10
|
+
/**
|
|
11
|
+
* Tool descriptors, in the JSON-schema shape the engine already uses for
|
|
12
|
+
* PROJECT_TOOLS. Exported so a future protocol can advertise the client's
|
|
13
|
+
* capabilities without this list being retyped on the server, where it would
|
|
14
|
+
* immediately drift.
|
|
15
|
+
*/
|
|
16
|
+
export const LOCAL_TOOL_DEFINITIONS = [
|
|
17
|
+
{
|
|
18
|
+
type: "function",
|
|
19
|
+
function: {
|
|
20
|
+
name: "read_file",
|
|
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.",
|
|
25
|
+
parameters: {
|
|
26
|
+
type: "object",
|
|
27
|
+
properties: {
|
|
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." }
|
|
32
|
+
},
|
|
33
|
+
required: ["path"]
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
type: "function",
|
|
39
|
+
function: {
|
|
40
|
+
name: "list_files",
|
|
41
|
+
description: "List files in the user's local project, optionally under a subdirectory or matching a glob.",
|
|
42
|
+
parameters: {
|
|
43
|
+
type: "object",
|
|
44
|
+
properties: {
|
|
45
|
+
path: { type: "string", description: "Subdirectory to list, relative to the project root" },
|
|
46
|
+
glob: { type: "string", description: "Glob such as **/*.ts" },
|
|
47
|
+
depth: { type: "number", description: "How deep to descend" }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
type: "function",
|
|
54
|
+
function: {
|
|
55
|
+
name: "search_files",
|
|
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.",
|
|
58
|
+
parameters: {
|
|
59
|
+
type: "object",
|
|
60
|
+
properties: {
|
|
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)" }
|
|
69
|
+
},
|
|
70
|
+
required: ["query"]
|
|
71
|
+
}
|
|
72
|
+
}
|
|
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
|
+
},
|
|
91
|
+
{
|
|
92
|
+
type: "function",
|
|
93
|
+
function: {
|
|
94
|
+
name: "git_status",
|
|
95
|
+
description: "Read the Git status of the user's local repository: branch, upstream, ahead/behind, and which " +
|
|
96
|
+
"files are staged, unstaged, untracked, renamed or deleted. Read-only. Prefer this over running " +
|
|
97
|
+
"`git status` as a command.",
|
|
98
|
+
parameters: {
|
|
99
|
+
type: "object",
|
|
100
|
+
properties: {}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
type: "function",
|
|
106
|
+
function: {
|
|
107
|
+
name: "git_diff",
|
|
108
|
+
description: "Read the Git diff of the user's local repository, with a bounded patch and per-file line counts. " +
|
|
109
|
+
"Read-only. Prefer this over running `git diff` as a command. scope: working_tree (unstaged, the " +
|
|
110
|
+
"default), staged (index), or both (everything since HEAD).",
|
|
111
|
+
parameters: {
|
|
112
|
+
type: "object",
|
|
113
|
+
properties: {
|
|
114
|
+
scope: { type: "string", enum: ["working_tree", "staged", "both"], description: "Which changes to show." }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
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
|
+
},
|
|
216
|
+
{
|
|
217
|
+
type: "function",
|
|
218
|
+
function: {
|
|
219
|
+
name: "resolve_local_file",
|
|
220
|
+
description: "Find which trusted repository a file or directory the user referenced belongs to, WITHOUT reading it. " +
|
|
221
|
+
"Use it when the user names a file/path in natural language and you do not already know its repository " +
|
|
222
|
+
"(e.g. \"read user.js\", \"open the hooks directory\"). Returns the repository and project-relative " +
|
|
223
|
+
"path to pass to read_file/search_files/edit_file, or a list of candidates when several match — then " +
|
|
224
|
+
"ask the user which one. It reads no file contents.",
|
|
225
|
+
parameters: {
|
|
226
|
+
type: "object",
|
|
227
|
+
properties: {
|
|
228
|
+
reference: { type: "string", description: "The file or directory the user referred to." },
|
|
229
|
+
kind: { type: "string", enum: ["file", "directory", "either"], description: "Restrict the match kind." }
|
|
230
|
+
},
|
|
231
|
+
required: ["reference"]
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
];
|
|
236
|
+
export const LOCAL_TOOL_NAMES = LOCAL_TOOL_DEFINITIONS.map((t) => t.function.name);
|
|
237
|
+
/** Caps applied to whatever the caller asks for, so a request cannot set its own. */
|
|
238
|
+
const LIST_LIMIT = 500;
|
|
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
|
+
}
|
|
307
|
+
/** Most bytes of one file a tool read returns; beyond this it reports truncated. */
|
|
308
|
+
export const TOOL_READ_BYTES = 256 * 1024;
|
|
309
|
+
/**
|
|
310
|
+
* Credential-shaped filenames that are never shared with the model, whether or
|
|
311
|
+
* not the project remembered to gitignore them. Conservative on purpose: these
|
|
312
|
+
* names almost never hold anything a question about the code needs.
|
|
313
|
+
*/
|
|
314
|
+
const SENSITIVE_NAMES = [
|
|
315
|
+
/^\.env(\..+)?$/i,
|
|
316
|
+
/\.(pem|key|p12|pfx|keystore|jks)$/i,
|
|
317
|
+
/^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
|
|
318
|
+
/^\.(npmrc|pypirc|netrc|pgpass)$/i,
|
|
319
|
+
/^credentials(\.json)?$/i
|
|
320
|
+
];
|
|
321
|
+
export function isSensitiveName(name) {
|
|
322
|
+
// `.env.example` and friends are documentation, not secrets.
|
|
323
|
+
if (/^\.env\.(example|sample|template|dist)$/i.test(name))
|
|
324
|
+
return false;
|
|
325
|
+
return SENSITIVE_NAMES.some((re) => re.test(name));
|
|
326
|
+
}
|
|
327
|
+
/** Lines as an editor shows them: a trailing newline does not start a new line. */
|
|
328
|
+
export function countLines(text) {
|
|
329
|
+
if (!text)
|
|
330
|
+
return 0;
|
|
331
|
+
const breaks = text.match(/\r\n|\r|\n/g)?.length ?? 0;
|
|
332
|
+
return /(\r\n|\r|\n)$/.test(text) ? breaks : breaks + 1;
|
|
333
|
+
}
|
|
334
|
+
function str(v) {
|
|
335
|
+
return typeof v === "string" && v.trim() ? v.trim() : undefined;
|
|
336
|
+
}
|
|
337
|
+
function num(v) {
|
|
338
|
+
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
|
|
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
|
+
}
|
|
377
|
+
function fail(id, name, code, message) {
|
|
378
|
+
return { id, name, ok: false, error: { code, message } };
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Execute one tool request.
|
|
382
|
+
*
|
|
383
|
+
* Never throws: a caller on the other end of a protocol needs a result it can
|
|
384
|
+
* correlate, and an exception that unwinds past the transport would strand the
|
|
385
|
+
* request id. Every failure comes back as `ok: false` with a code.
|
|
386
|
+
*/
|
|
387
|
+
export function executeLocalTool(req, opts = {}) {
|
|
388
|
+
const id = typeof req?.id === "string" && req.id ? req.id : "unknown";
|
|
389
|
+
const name = typeof req?.name === "string" ? req.name : "";
|
|
390
|
+
const args = (req?.arguments ?? {});
|
|
391
|
+
if (!LOCAL_TOOL_NAMES.includes(name)) {
|
|
392
|
+
return fail(id, name, "UNKNOWN_TOOL", `No local tool named "${name}".`);
|
|
393
|
+
}
|
|
394
|
+
// Which repository this call is about. A NAME from the registry — never a
|
|
395
|
+
// path — so "../other-repo" cannot be smuggled in as a selector, and the
|
|
396
|
+
// path below is still resolved inside whichever root the name maps to.
|
|
397
|
+
const selector = args.repository;
|
|
398
|
+
const wildcard = isWildcardSelector(selector);
|
|
399
|
+
const wildcardOk = name === "list_files" || name === "search_files" || name === "find_files";
|
|
400
|
+
if (wildcard && !wildcardOk) {
|
|
401
|
+
return fail(id, name, "REPOSITORY_WILDCARD_NOT_ALLOWED", `${name} needs one repository; "*" is only for list_files, find_files and search_files.`);
|
|
402
|
+
}
|
|
403
|
+
let repo;
|
|
404
|
+
try {
|
|
405
|
+
repo = wildcard ? activeRepository() : resolveRepository(selector);
|
|
406
|
+
}
|
|
407
|
+
catch (err) {
|
|
408
|
+
if (err instanceof RepositoryError)
|
|
409
|
+
return fail(id, name, err.code, err.message);
|
|
410
|
+
throw err;
|
|
411
|
+
}
|
|
412
|
+
const root = repo.root;
|
|
413
|
+
// A content read of a NAMED (or active) repository must respect trust exactly
|
|
414
|
+
// as a wildcard read does. Without this, an explicit `repository` selector
|
|
415
|
+
// could reach an untrusted repository that git_status, git_diff and
|
|
416
|
+
// resolve_local_file already refuse. The wildcard branches filter with
|
|
417
|
+
// readableRepositories() themselves; here the single-target path reuses the
|
|
418
|
+
// same set. Being active (including in single-repository mode) grants no trust.
|
|
419
|
+
if (!wildcard && isContentReadTool(name) && !isReadableRepository(repo)) {
|
|
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.`);
|
|
421
|
+
}
|
|
422
|
+
try {
|
|
423
|
+
switch (name) {
|
|
424
|
+
case "read_file": {
|
|
425
|
+
const p = str(args.path);
|
|
426
|
+
if (!p)
|
|
427
|
+
return fail(id, name, "INVALID_ARGUMENTS", '"path" is required.');
|
|
428
|
+
// A file no listing or search would surface is not readable by name
|
|
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".');
|
|
436
|
+
}
|
|
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
|
+
};
|
|
474
|
+
}
|
|
475
|
+
const known = str(args.known_sha256)?.toLowerCase();
|
|
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
|
+
}
|
|
498
|
+
return {
|
|
499
|
+
id,
|
|
500
|
+
name,
|
|
501
|
+
ok: true,
|
|
502
|
+
result: {
|
|
503
|
+
...repositoryLabel(repo),
|
|
504
|
+
path: res.path,
|
|
505
|
+
content: res.text,
|
|
506
|
+
truncated: res.truncated,
|
|
507
|
+
size: res.size,
|
|
508
|
+
// Counted here, from the bytes on disk, because a model counting the
|
|
509
|
+
// lines of a long file by eye is exactly the kind of "roughly" this
|
|
510
|
+
// tool exists to replace. Omitted when the read was truncated — a
|
|
511
|
+
// count of the first N bytes would be a wrong answer, not a partial one.
|
|
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 } : {})
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
case "list_files": {
|
|
518
|
+
const glob = str(args.glob);
|
|
519
|
+
const listOne = (handle) => {
|
|
520
|
+
if (glob) {
|
|
521
|
+
const res = globFiles({ pattern: glob, limit: LIST_LIMIT, root: handle.root });
|
|
522
|
+
return { files: res.paths.map((f) => ({ path: f })), truncated: res.truncated };
|
|
523
|
+
}
|
|
524
|
+
const res = listDirectory({
|
|
525
|
+
root: handle.root,
|
|
526
|
+
path: str(args.path),
|
|
527
|
+
depth: num(args.depth) ?? 3,
|
|
528
|
+
limit: LIST_LIMIT
|
|
529
|
+
});
|
|
530
|
+
return {
|
|
531
|
+
files: res.entries.filter((e) => e.type === "file").map((e) => ({ path: e.path, size: e.size })),
|
|
532
|
+
directories: res.entries.filter((e) => e.type === "dir").map((e) => e.path),
|
|
533
|
+
truncated: res.truncated
|
|
534
|
+
};
|
|
535
|
+
};
|
|
536
|
+
if (wildcard) {
|
|
537
|
+
const perRepo = readableRepositories().map((handle) => ({ ...repositoryLabel(handle), ...listOne(handle) }));
|
|
538
|
+
return { id, name, ok: true, result: { repositories: perRepo, truncated: perRepo.some((r) => r.truncated === true) } };
|
|
539
|
+
}
|
|
540
|
+
return { id, name, ok: true, result: { ...repositoryLabel(repo), ...listOne(repo) } };
|
|
541
|
+
}
|
|
542
|
+
case "search_files": {
|
|
543
|
+
const query = typeof args.query === "string" && args.query.length ? args.query : undefined;
|
|
544
|
+
if (!query || !query.trim())
|
|
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);
|
|
555
|
+
// Each repository is searched on its own, under its own limits, and its
|
|
556
|
+
// matches are labelled — two files called src/auth.ts in two
|
|
557
|
+
// repositories must never arrive as one ambiguous list.
|
|
558
|
+
const searchOne = (handle) => {
|
|
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
|
+
});
|
|
573
|
+
return {
|
|
574
|
+
// Search already skips ignored paths; a credentials file that is NOT
|
|
575
|
+
// gitignored would still show its matching line, so drop those.
|
|
576
|
+
matches: rankMatches(res.matches, query)
|
|
577
|
+
.filter((m) => !isSensitiveName(path.basename(m.path)))
|
|
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 } : {}),
|
|
589
|
+
truncated: res.truncated
|
|
590
|
+
};
|
|
591
|
+
};
|
|
592
|
+
if (wildcard) {
|
|
593
|
+
const perRepo = readableRepositories().map((handle) => ({ ...repositoryLabel(handle), ...searchOne(handle) }));
|
|
594
|
+
return { id, name, ok: true, result: { repositories: perRepo, truncated: perRepo.some((r) => r.truncated === true) } };
|
|
595
|
+
}
|
|
596
|
+
return { id, name, ok: true, result: { ...repositoryLabel(repo), ...searchOne(repo) } };
|
|
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
|
+
}
|
|
729
|
+
case "resolve_local_file": {
|
|
730
|
+
const reference = str(args.reference);
|
|
731
|
+
if (!reference)
|
|
732
|
+
return fail(id, name, "INVALID_ARGUMENTS", '"reference" is required.');
|
|
733
|
+
const kindArg = str(args.kind);
|
|
734
|
+
const kind = kindArg === "file" || kindArg === "directory" ? kindArg : "either";
|
|
735
|
+
const res = resolveWorkspaceFile({ reference, kind });
|
|
736
|
+
if (res.status === "resolved" && res.match) {
|
|
737
|
+
return {
|
|
738
|
+
id,
|
|
739
|
+
name,
|
|
740
|
+
ok: true,
|
|
741
|
+
result: {
|
|
742
|
+
status: "resolved",
|
|
743
|
+
repository: res.match.repositoryName,
|
|
744
|
+
path: res.match.relativePath,
|
|
745
|
+
is_directory: res.match.isDirectory,
|
|
746
|
+
match_type: res.match.matchType,
|
|
747
|
+
confidence: res.match.confidence
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
if (res.status === "ambiguous" && res.candidates) {
|
|
752
|
+
return {
|
|
753
|
+
id,
|
|
754
|
+
name,
|
|
755
|
+
ok: true,
|
|
756
|
+
result: {
|
|
757
|
+
status: "ambiguous",
|
|
758
|
+
candidates: res.candidates.map((c) => ({
|
|
759
|
+
repository: c.repositoryName,
|
|
760
|
+
path: c.relativePath,
|
|
761
|
+
is_directory: c.isDirectory,
|
|
762
|
+
match_type: c.matchType
|
|
763
|
+
}))
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
if (res.status === "not_found") {
|
|
768
|
+
return { id, name, ok: true, result: { status: "not_found", message: res.error?.message ?? "No match." } };
|
|
769
|
+
}
|
|
770
|
+
return fail(id, name, res.error?.code ?? "RESOLVE_FAILED", res.error?.message ?? "Could not resolve the reference.");
|
|
771
|
+
}
|
|
772
|
+
case "git_status": {
|
|
773
|
+
// A read, but of a whole repository's state — so it honours trust the
|
|
774
|
+
// same way a wildcard read does: an untrusted repository is not
|
|
775
|
+
// inspected, even when named explicitly.
|
|
776
|
+
if (repositoryTrust(repo) !== "trusted") {
|
|
777
|
+
return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository.`);
|
|
778
|
+
}
|
|
779
|
+
const s = gitStatus(root);
|
|
780
|
+
return {
|
|
781
|
+
id,
|
|
782
|
+
name,
|
|
783
|
+
ok: true,
|
|
784
|
+
result: {
|
|
785
|
+
...repositoryLabel(repo),
|
|
786
|
+
branch: s.branch,
|
|
787
|
+
detached: s.detached,
|
|
788
|
+
head: s.head,
|
|
789
|
+
upstream: s.upstream,
|
|
790
|
+
ahead: s.ahead,
|
|
791
|
+
behind: s.behind,
|
|
792
|
+
clean: s.clean,
|
|
793
|
+
has_commits: s.hasCommits,
|
|
794
|
+
staged: s.staged,
|
|
795
|
+
unstaged: s.unstaged,
|
|
796
|
+
untracked: s.untracked,
|
|
797
|
+
renamed: s.renamed,
|
|
798
|
+
deleted: s.deleted,
|
|
799
|
+
truncated: s.truncated
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
case "git_diff": {
|
|
804
|
+
if (repositoryTrust(repo) !== "trusted") {
|
|
805
|
+
return fail(id, name, "REPOSITORY_NOT_TRUSTED", `${repo.name} is not a trusted repository.`);
|
|
806
|
+
}
|
|
807
|
+
const scopeArg = str(args.scope);
|
|
808
|
+
const scope = scopeArg === "staged" || scopeArg === "both" ? scopeArg : "working_tree";
|
|
809
|
+
const d = gitDiff(root, scope);
|
|
810
|
+
return {
|
|
811
|
+
id,
|
|
812
|
+
name,
|
|
813
|
+
ok: true,
|
|
814
|
+
result: {
|
|
815
|
+
...repositoryLabel(repo),
|
|
816
|
+
scope: d.scope,
|
|
817
|
+
files_changed: d.files_changed,
|
|
818
|
+
additions: d.additions,
|
|
819
|
+
deletions: d.deletions,
|
|
820
|
+
diff: d.diff,
|
|
821
|
+
truncated: d.truncated
|
|
822
|
+
}
|
|
823
|
+
};
|
|
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
|
+
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
catch (err) {
|
|
860
|
+
if (err instanceof ToolRefusal) {
|
|
861
|
+
return fail(id, name, err.code, err.message);
|
|
862
|
+
}
|
|
863
|
+
if (err instanceof LocalFileError) {
|
|
864
|
+
return fail(id, name, err.code, err.message);
|
|
865
|
+
}
|
|
866
|
+
if (err instanceof GitToolError) {
|
|
867
|
+
return fail(id, name, err.code, err.message);
|
|
868
|
+
}
|
|
869
|
+
return fail(id, name, "TOOL_FAILED", err.message ?? "Tool failed.");
|
|
870
|
+
}
|
|
871
|
+
return fail(id, name, "UNKNOWN_TOOL", `No local tool named "${name}".`);
|
|
872
|
+
}
|
|
873
|
+
/** What a result says about where it came from; omitted in single-repo mode. */
|
|
874
|
+
function repositoryLabel(handle) {
|
|
875
|
+
return inWorkspaceMode() ? { repository: handle.name } : {};
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* The repositories a wildcard read may touch: registered AND trusted.
|
|
879
|
+
*
|
|
880
|
+
* Registering a workspace says a repository exists. Trust says the user allowed
|
|
881
|
+
* Carrier OS to read it. A fan-out read must respect the second, or "*" would
|
|
882
|
+
* become a way to read a repository the user never opened.
|
|
883
|
+
*/
|
|
884
|
+
function readableRepositories() {
|
|
885
|
+
return listRepositories().filter((r) => repositoryTrust(r) === "trusted");
|
|
886
|
+
}
|
|
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
|
+
}
|
|
906
|
+
function isContentReadTool(name) {
|
|
907
|
+
return name === "read_file" || name === "list_files" || name === "search_files" || name === "find_files" ||
|
|
908
|
+
name === "code_outline" || name === "find_symbol" || name === "find_references";
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Whether a single, named-or-active repository may be read/searched — the same
|
|
912
|
+
* trust rule the wildcard fan-out applies (`readableRepositories`), so a named
|
|
913
|
+
* or active target can never reach a repository "*" would skip. Reused rather
|
|
914
|
+
* than re-deriving trust, including when no repositories are trusted.
|
|
915
|
+
*/
|
|
916
|
+
function isReadableRepository(handle) {
|
|
917
|
+
return readableRepositories().some((r) => r.id === handle.id);
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* A one-line, content-free record of a tool call.
|
|
921
|
+
*
|
|
922
|
+
* Deliberately not an audit system — that belongs with the phase that can
|
|
923
|
+
* change files. What it does establish now is the shape: a stable id, the tool,
|
|
924
|
+
* and enough of the arguments to be meaningful. File CONTENT never appears
|
|
925
|
+
* here, so turning this into a real audit trail later cannot accidentally start
|
|
926
|
+
* logging source code or secrets.
|
|
927
|
+
*/
|
|
928
|
+
export function describeToolCall(req) {
|
|
929
|
+
const args = (req.arguments ?? {});
|
|
930
|
+
const detail = str(args.path) ?? str(args.query) ?? str(args.pattern) ?? str(args.revision) ?? str(args.glob) ?? "";
|
|
931
|
+
const repo = str(args.repository);
|
|
932
|
+
return `${req.id} ${req.name}${repo ? ` [${repo}]` : ""}${detail ? ` ${detail}` : ""}`;
|
|
933
|
+
}
|
|
934
|
+
/** The root every tool resolves against — exported for display, not for callers. */
|
|
935
|
+
export function toolBoundary() {
|
|
936
|
+
return workspaceRoot();
|
|
937
|
+
}
|