@abelxiaoxing/cadence 1.8.3 → 2.0.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 (208) hide show
  1. package/README.md +324 -111
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -26
  4. package/agents/diagnosis-worker.md +14 -25
  5. package/agents/implementation-worker.md +16 -35
  6. package/config/.env.example +2 -5
  7. package/config/workflow-task.example.json +7 -0
  8. package/docs/remote-access.md +60 -0
  9. package/docs/reuse-and-distribution.md +44 -0
  10. package/docs/service-management.md +108 -0
  11. package/licenses/bundled-web.txt +6245 -0
  12. package/licenses/pi-web-ui-MIT.txt +21 -0
  13. package/licenses/pi-web-ui-reuse.md +22 -0
  14. package/package.json +94 -21
  15. package/src/index.ts +22 -1807
  16. package/src/native-build.ts +6 -0
  17. package/src/native-client.ts +103 -0
  18. package/src/native-export.ts +58 -0
  19. package/src/native-history.ts +359 -0
  20. package/src/operator-cli.mjs +453 -1937
  21. package/src/plan-proposal.ts +87 -0
  22. package/src/sdk-worker.mjs +549 -0
  23. package/src/service/contracts/active.ts +82 -0
  24. package/src/service/contracts/budget.ts +148 -0
  25. package/src/service/contracts/build.ts +67 -0
  26. package/src/service/contracts/capture.ts +48 -0
  27. package/src/service/contracts/core.ts +33 -0
  28. package/src/service/contracts/current.ts +261 -0
  29. package/src/service/contracts/domain.ts +68 -0
  30. package/src/service/contracts/history.ts +2245 -0
  31. package/src/service/contracts/models.ts +139 -0
  32. package/src/service/coordination.ts +862 -0
  33. package/src/service/private-files.ts +204 -0
  34. package/src/service-cli.mjs +5592 -0
  35. package/src/service-client.ts +747 -0
  36. package/src/service-contract.ts +245 -0
  37. package/src/service-host.mjs +22382 -0
  38. package/src/service-http-client.ts +425 -0
  39. package/src/service-wire.ts +372 -0
  40. package/src/task-shell.ts +1045 -0
  41. package/src/task-store.ts +479 -0
  42. package/src/task-types.ts +184 -0
  43. package/src/verification-diagnostics.ts +29 -72
  44. package/src/worker-capture.mjs +1197 -0
  45. package/src/worker-public.mjs +1753 -0
  46. package/src/worker-redaction.mjs +608 -0
  47. package/src/worker-tools.mjs +202 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  50. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  56. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  62. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  65. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  68. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  71. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  74. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  77. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  80. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  89. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  92. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  95. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  98. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  101. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  104. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  107. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  108. package/web/dist/assets/cadence.css +2 -0
  109. package/web/dist/assets/cadence.js +7 -0
  110. package/web/dist/assets/markdown.js +296 -0
  111. package/web/dist/assets/react.js +9 -0
  112. package/web/dist/assets/rolldown-runtime.js +1 -0
  113. package/web/dist/assets/timeline-client.js +41 -0
  114. package/web/dist/assets/vis-timeline.css +1274 -0
  115. package/web/dist/assets/vis-timeline.js +32 -0
  116. package/web/dist/index.html +18 -0
  117. package/web/dist/manifest.json +505 -0
  118. package/config/plan-draft.example.json +0 -125
  119. package/config/plan-draft.multiple-tasks.example.json +0 -375
  120. package/config/plan-draft.quick.example.json +0 -78
  121. package/config/routes.example.json +0 -39
  122. package/prompts/abel-design.md +0 -382
  123. package/prompts/abel-diagnose.md +0 -71
  124. package/prompts/abel-implement.md +0 -284
  125. package/prompts/abel-init.md +0 -52
  126. package/src/activation.ts +0 -44
  127. package/src/activity-contracts.ts +0 -82
  128. package/src/agent-registry.ts +0 -53
  129. package/src/apply-transaction.ts +0 -1437
  130. package/src/artifact-store.ts +0 -213
  131. package/src/build-windows-job.mjs +0 -95
  132. package/src/candidate-artifact.ts +0 -143
  133. package/src/candidate-patch.ts +0 -271
  134. package/src/candidate-workspace.ts +0 -80
  135. package/src/canonical.ts +0 -16
  136. package/src/change-contract-schema.ts +0 -191
  137. package/src/change-contract.ts +0 -324
  138. package/src/change-verification.ts +0 -1617
  139. package/src/child-budget.ts +0 -58
  140. package/src/child-model.ts +0 -142
  141. package/src/child-session.ts +0 -640
  142. package/src/contracts.ts +0 -2476
  143. package/src/control-contracts.ts +0 -382
  144. package/src/delivery-compiler.ts +0 -1805
  145. package/src/delivery-revision.ts +0 -42
  146. package/src/design-control.ts +0 -1299
  147. package/src/design-diagnostics.ts +0 -181
  148. package/src/design-journal.ts +0 -1773
  149. package/src/directory-sync.ts +0 -36
  150. package/src/durable-contracts.ts +0 -231
  151. package/src/durable-workflow.ts +0 -978
  152. package/src/evidence-draft.ts +0 -122
  153. package/src/execution-profile.ts +0 -64
  154. package/src/execution-retention.ts +0 -77
  155. package/src/file-snapshot.ts +0 -163
  156. package/src/implement-continuation.ts +0 -559
  157. package/src/implement-graph.ts +0 -690
  158. package/src/implement-plan.ts +0 -72
  159. package/src/install-config.d.mts +0 -6
  160. package/src/isolation-backend.ts +0 -353
  161. package/src/model-source.ts +0 -22
  162. package/src/openspec-cli.ts +0 -494
  163. package/src/operator-cli-entry.mjs +0 -24
  164. package/src/operator-tools.ts +0 -309
  165. package/src/package-candidate.ts +0 -227
  166. package/src/package-delivery.ts +0 -486
  167. package/src/package-state.ts +0 -320
  168. package/src/package-verification.ts +0 -635
  169. package/src/package-workflow.ts +0 -342
  170. package/src/packet-runtime.ts +0 -570
  171. package/src/parent-provider.ts +0 -375
  172. package/src/phase-execution.ts +0 -2259
  173. package/src/pi-adapter.ts +0 -19
  174. package/src/plan-draft-summary.ts +0 -527
  175. package/src/plan-draft.ts +0 -502
  176. package/src/remove-path.ts +0 -32
  177. package/src/route-policy.ts +0 -545
  178. package/src/run-state.ts +0 -420
  179. package/src/run-store.ts +0 -1179
  180. package/src/safe-path.ts +0 -77
  181. package/src/scoped-grep-worker.mjs +0 -23
  182. package/src/scoped-tools.ts +0 -775
  183. package/src/single-task-draft.ts +0 -142
  184. package/src/sqlite-schema.ts +0 -171
  185. package/src/state-root.ts +0 -215
  186. package/src/storage-schema.ts +0 -360
  187. package/src/subagent-activity.ts +0 -1417
  188. package/src/submit-tool.ts +0 -950
  189. package/src/task-ledger.ts +0 -1338
  190. package/src/transport-budget.ts +0 -52
  191. package/src/verification-capability.ts +0 -1191
  192. package/src/verification-environment-io.ts +0 -389
  193. package/src/verification-environment.ts +0 -162
  194. package/src/verification-identity.ts +0 -77
  195. package/src/verification-scan.ts +0 -64
  196. package/src/windows-job-backend.ts +0 -419
  197. package/src/windows-job.c +0 -149
  198. package/src/worker-broker.ts +0 -806
  199. package/src/workflow-engine.ts +0 -28
  200. package/src/workflow-policy.ts +0 -1679
  201. package/src/workflow-recovery-policy.ts +0 -97
  202. package/src/workflow-scheduling.ts +0 -105
  203. package/src/workflow-state-machine.ts +0 -4355
  204. package/src/workflow-status.ts +0 -576
  205. package/src/workspace-io-entry.mjs +0 -76
  206. package/src/workspace-io-worker.mjs +0 -1312
  207. package/src/workspace-io.ts +0 -89
  208. package/src/workspace-store.ts +0 -634
@@ -1,775 +0,0 @@
1
- // Scoped read-only filesystem tools: read, grep, find, ls. Repository-relative
2
- // paths only, no mutation, no process execution, bounded output and scan sizes.
3
- import {
4
- constants,
5
- lstatSync,
6
- readdirSync,
7
- readFileSync,
8
- realpathSync,
9
- type Stats,
10
- statSync,
11
- } from "node:fs";
12
- import { lstat, open, opendir } from "node:fs/promises";
13
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
14
- import { Worker } from "node:worker_threads";
15
- import { observeSafePath } from "./safe-path.ts";
16
-
17
- export const TOOL_LIMITS = {
18
- maxReadBytes: 50 * 1024,
19
- maxReadLines: 2000,
20
- maxGrepPattern: 1024,
21
- maxGrepFiles: 2000,
22
- maxGrepMillis: 5000,
23
- maxGrepFileBytes: 1024 * 1024,
24
- maxGrepScanBytes: 16 * 1024 * 1024,
25
- maxGrepMatches: 1000,
26
- maxGrepResultBytes: 50 * 1024,
27
- maxEntries: 20000,
28
- } as const;
29
-
30
- function globToRegExp(pattern: string): RegExp | { error: string } {
31
- if (pattern.length === 0) return { error: "missing pattern" };
32
- if (pattern.length > TOOL_LIMITS.maxGrepPattern) {
33
- return {
34
- error: `pattern exceeds ${TOOL_LIMITS.maxGrepPattern} characters`,
35
- };
36
- }
37
- let source = "^";
38
- for (let i = 0; i < pattern.length; i++) {
39
- const ch = pattern[i];
40
- if (ch === "*" && pattern[i + 1] === "*") {
41
- const next = pattern[i + 2];
42
- if (next === "/") {
43
- source += "(?:.*/)?";
44
- i += 2;
45
- continue;
46
- }
47
- source += ".*";
48
- i += 1;
49
- continue;
50
- }
51
- if (ch === "*") {
52
- source += "[^/]*";
53
- continue;
54
- }
55
- if (ch === "?") {
56
- source += "[^/]";
57
- continue;
58
- }
59
- if (ch === "[") {
60
- let end = i + 1;
61
- if (pattern[end] === "!" || pattern[end] === "^") end++;
62
- while (end < pattern.length && pattern[end] !== "]") end++;
63
- if (end === pattern.length) {
64
- source += "\\[";
65
- continue;
66
- }
67
- const raw = pattern.slice(i + 1, end);
68
- const negated = raw.startsWith("!") || raw.startsWith("^");
69
- const body = raw.slice(negated ? 1 : 0);
70
- if (body.length === 0 || body.includes("/")) {
71
- return { error: "invalid glob character class" };
72
- }
73
- const escaped = [...body]
74
- .map((value, index) => {
75
- if (value === "\\" || value === "[" || value === "]") {
76
- return `\\${value}`;
77
- }
78
- return value === "^" && index === 0 ? "\\^" : value;
79
- })
80
- .join("");
81
- source += `[${negated ? "^" : ""}${escaped}]`;
82
- i = end;
83
- continue;
84
- }
85
- if ("\\^$+()[]{}|.".includes(ch)) source += `\\${ch}`;
86
- else source += ch;
87
- }
88
- source += "$";
89
- try {
90
- return new RegExp(source, "u");
91
- } catch {
92
- return { error: "invalid glob pattern" };
93
- }
94
- }
95
-
96
- function boundedInteger(value: unknown): number | undefined {
97
- return typeof value === "number" && Number.isInteger(value) && value > 0
98
- ? value
99
- : undefined;
100
- }
101
-
102
- function isWithinPath(path: string, parent: string): boolean {
103
- return path === parent || path.startsWith(`${parent}${sep}`);
104
- }
105
-
106
- function isAllowedContent(path: string, allowedPaths?: string[]): boolean {
107
- return (
108
- allowedPaths === undefined ||
109
- allowedPaths.some((allowed) => isWithinPath(path, allowed))
110
- );
111
- }
112
-
113
- function isRelatedToAllowedPath(
114
- path: string,
115
- allowedPaths?: string[],
116
- ): boolean {
117
- return (
118
- allowedPaths === undefined ||
119
- allowedPaths.some(
120
- (allowed) => isWithinPath(path, allowed) || isWithinPath(allowed, path),
121
- )
122
- );
123
- }
124
-
125
- function commonAncestor(paths: string[]): string {
126
- let candidate = paths[0];
127
- while (!paths.every((path) => isWithinPath(path, candidate))) {
128
- const parent = dirname(candidate);
129
- if (parent === candidate) return candidate;
130
- candidate = parent;
131
- }
132
- return candidate;
133
- }
134
-
135
- function relativePath(base: string, path: string): string {
136
- return (relative(base, path) || ".").split(sep).join("/");
137
- }
138
-
139
- export type Observation =
140
- | { kind: "file"; path: string }
141
- | { kind: "dir"; path: string };
142
-
143
- export class ScopedObservationCollector {
144
- readonly #observations = new Map<string, Observation>();
145
- readonly #limit: number;
146
- #truncated = false;
147
-
148
- constructor(limit = 512) {
149
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 4096) {
150
- throw new Error("observation-limit-invalid");
151
- }
152
- this.#limit = limit;
153
- }
154
-
155
- readonly observe = (observation: Observation): void => {
156
- const key = `${observation.kind}:${observation.path}`;
157
- if (this.#observations.has(key)) return;
158
- if (this.#observations.size >= this.#limit) {
159
- this.#truncated = true;
160
- return;
161
- }
162
- this.#observations.set(key, { ...observation });
163
- };
164
-
165
- projection(): { observations: Observation[]; truncated: boolean } {
166
- return {
167
- observations: [...this.#observations.values()]
168
- .map((entry) => ({ ...entry }))
169
- .sort(
170
- (left, right) =>
171
- left.path.localeCompare(right.path) ||
172
- left.kind.localeCompare(right.kind),
173
- ),
174
- truncated: this.#truncated,
175
- };
176
- }
177
- }
178
-
179
- export interface ScopedToolDef {
180
- name: string;
181
- description: string;
182
- execute(
183
- params: Record<string, unknown>,
184
- signal?: AbortSignal,
185
- ): Promise<Record<string, unknown>>;
186
- }
187
-
188
- interface Options {
189
- cwd?: string;
190
- roots: string[];
191
- allowedPaths?: string[];
192
- observer?: (obs: Observation) => void;
193
- }
194
-
195
- type PathResult =
196
- | { ok: true; abs: string; rel: string }
197
- | { ok: false; error: string };
198
- type ResolvedPath = Extract<PathResult, { ok: true }>;
199
-
200
- function resolveScoped(
201
- roots: string[],
202
- input: unknown,
203
- allowedPaths?: string[],
204
- allowScopedAncestor = false,
205
- workspaceRoot = commonAncestor(roots),
206
- ): PathResult {
207
- if (typeof input !== "string" || input.length === 0) {
208
- return { ok: false, error: "missing path" };
209
- }
210
- if (input.includes("\u0000"))
211
- return { ok: false, error: "NUL byte rejected" };
212
- if (input.includes("\\")) return { ok: false, error: "backslash rejected" };
213
- if (input.startsWith("/") || input.startsWith("~")) {
214
- return { ok: false, error: "absolute path rejected" };
215
- }
216
- if (input.split("/").includes("..")) {
217
- return { ok: false, error: "parent traversal rejected" };
218
- }
219
- if (input.startsWith("./") || input.includes("//") || input.endsWith("/.")) {
220
- return { ok: false, error: "noncanonical path rejected" };
221
- }
222
- if (/^[a-z]:/iu.test(input))
223
- return { ok: false, error: "absolute path rejected" };
224
- const abs = resolve(workspaceRoot, input);
225
- const root = [...roots]
226
- .sort((a, b) => b.length - a.length)
227
- .find(
228
- (candidate) =>
229
- isWithinPath(abs, candidate) ||
230
- (allowScopedAncestor && isWithinPath(candidate, abs)),
231
- );
232
- if (!root || !isWithinPath(abs, workspaceRoot)) {
233
- return { ok: false, error: "path is outside every approved root" };
234
- }
235
- if (
236
- !isAllowedContent(abs, allowedPaths) &&
237
- !(allowScopedAncestor && isRelatedToAllowedPath(abs, allowedPaths))
238
- ) {
239
- return {
240
- ok: false,
241
- error: "path is outside the declared read/write scope",
242
- };
243
- }
244
- // Check all components from the workspace, including the admitted root.
245
- const hiddenRoot =
246
- basename(root) === ".git" || basename(root) === "node_modules";
247
- if (
248
- !hiddenRoot &&
249
- input
250
- .split("/")
251
- .some((segment) => segment === ".git" || segment === "node_modules")
252
- ) {
253
- return { ok: false, error: "hidden path rejected" };
254
- }
255
- let current = workspaceRoot;
256
- for (const segment of [".", ...relative(workspaceRoot, abs).split(sep)]) {
257
- current = join(current, segment);
258
- try {
259
- if (lstatSync(current).isSymbolicLink())
260
- return { ok: false, error: "symlink rejected" };
261
- } catch {
262
- break;
263
- }
264
- }
265
- if (existsSync(current)) {
266
- const real = realpathSync(current);
267
- const realRoot = realpathSync(workspaceRoot);
268
- if (!isWithinPath(real, realRoot))
269
- return { ok: false, error: "path escapes the approved root" };
270
- }
271
- return { ok: true, abs, rel: relativePath(workspaceRoot, abs) };
272
- }
273
-
274
- function existsSync(p: string): boolean {
275
- try {
276
- statSync(p);
277
- return true;
278
- } catch {
279
- return false;
280
- }
281
- }
282
-
283
- function utf8Text(abs: string): string | null {
284
- const buf = readFileSync(abs);
285
- try {
286
- const text = new TextDecoder("utf-8", { fatal: true }).decode(buf);
287
- return text;
288
- } catch {
289
- return null;
290
- }
291
- }
292
-
293
- export function createScopedTools(opts: Options): ScopedToolDef[] {
294
- const roots = opts.roots.map((r) => resolve(r));
295
- if (roots.length === 0) throw new Error("approved roots are required");
296
- const workspaceRoot = resolve(opts.cwd ?? commonAncestor(roots));
297
- if (!roots.every((root) => isWithinPath(root, workspaceRoot)))
298
- throw new Error("approved root outside workspace");
299
- const allowedPaths = opts.allowedPaths?.map((p) => resolve(p));
300
- const observe = opts.observer ?? (() => {});
301
-
302
- function resolveScanTargets(
303
- input: unknown,
304
- ):
305
- | { ok: true; targets: ResolvedPath[]; virtual: boolean; base: string }
306
- | { ok: false; error: string } {
307
- const resolved = resolveScoped(
308
- roots,
309
- input ?? ".",
310
- allowedPaths,
311
- true,
312
- workspaceRoot,
313
- );
314
- if (!resolved.ok) return resolved;
315
- if (roots.some((root) => isWithinPath(resolved.abs, root))) {
316
- return {
317
- ok: true,
318
- targets: [resolved],
319
- virtual: false,
320
- base: resolved.abs,
321
- };
322
- }
323
- const targets: ResolvedPath[] = [];
324
- for (const root of roots) {
325
- if (!isWithinPath(root, resolved.abs)) continue;
326
- const target = resolveScoped(
327
- roots,
328
- relativePath(workspaceRoot, root),
329
- allowedPaths,
330
- true,
331
- workspaceRoot,
332
- );
333
- if (
334
- target.ok &&
335
- !targets.some((existing) => isWithinPath(target.abs, existing.abs))
336
- )
337
- targets.push(target);
338
- }
339
- return targets.length > 0
340
- ? { ok: true, targets, virtual: true, base: resolved.abs }
341
- : { ok: false, error: "path is outside the declared read/write scope" };
342
- }
343
-
344
- function rootRelativePath(path: string): string {
345
- return relativePath(workspaceRoot, path);
346
- }
347
-
348
- const readTool: ScopedToolDef = {
349
- name: "read",
350
- description:
351
- "Read a regular UTF-8 text file within the approved scope (max 2,000 lines / 50 KiB).",
352
- async execute(params) {
353
- const resolved = resolveScoped(
354
- roots,
355
- params.path,
356
- allowedPaths,
357
- false,
358
- workspaceRoot,
359
- );
360
- if (!resolved.ok) return { ok: false, error: resolved.error };
361
- let st: Stats | undefined;
362
- try {
363
- st = statSync(resolved.abs);
364
- } catch {
365
- return { ok: false, error: "file does not exist" };
366
- }
367
- if (!st.isFile()) return { ok: false, error: "not a regular file" };
368
- const text = utf8Text(resolved.abs);
369
- if (text === null) return { ok: false, error: "not valid UTF-8 text" };
370
- observe({ kind: "file", path: resolved.rel });
371
- const allLines = text.split("\n");
372
- const offset = boundedInteger(params.offset);
373
- const limit = boundedInteger(params.limit);
374
- if (offset !== undefined && offset > allLines.length) {
375
- return {
376
- ok: false,
377
- error: `offset ${offset} exceeds file length (${allLines.length} lines)`,
378
- };
379
- }
380
- const start = offset === undefined ? 0 : Math.max(0, offset - 1);
381
- const windowed =
382
- offset === undefined && limit === undefined
383
- ? allLines
384
- : allLines.slice(
385
- start,
386
- limit === undefined ? undefined : start + limit,
387
- );
388
- let content = windowed.join("\n");
389
- let truncated =
390
- Buffer.byteLength(content, "utf8") > TOOL_LIMITS.maxReadBytes ||
391
- windowed.length > TOOL_LIMITS.maxReadLines;
392
- if (Buffer.byteLength(content, "utf8") > TOOL_LIMITS.maxReadBytes) {
393
- content = Buffer.from(content, "utf8")
394
- .subarray(0, TOOL_LIMITS.maxReadBytes)
395
- .toString("utf8");
396
- truncated = true;
397
- }
398
- if (content.split("\n").length > TOOL_LIMITS.maxReadLines) {
399
- content = content
400
- .split("\n")
401
- .slice(0, TOOL_LIMITS.maxReadLines)
402
- .join("\n");
403
- truncated = true;
404
- }
405
- return { ok: true, content, truncated };
406
- },
407
- };
408
-
409
- const grepTool: ScopedToolDef = {
410
- name: "grep",
411
- description:
412
- "Search scoped UTF-8 files using a cancellable JavaScript regexp (5 seconds, 1 MiB/file, 16 MiB total, 1,000 matches / 50 KiB output); truncated results are marked.",
413
- async execute(params, signal) {
414
- if (signal?.aborted) return { ok: false, error: "search cancelled" };
415
- const pattern = params.pattern;
416
- if (typeof pattern !== "string" || pattern.length === 0) {
417
- return { ok: false, error: "missing pattern" };
418
- }
419
- if (pattern.length > TOOL_LIMITS.maxGrepPattern) {
420
- return {
421
- ok: false,
422
- error: `pattern exceeds ${TOOL_LIMITS.maxGrepPattern} characters`,
423
- };
424
- }
425
- try {
426
- new RegExp(pattern, "u");
427
- } catch {
428
- return { ok: false, error: "invalid regular expression" };
429
- }
430
- const scan = resolveScanTargets(params.path);
431
- if (!scan.ok) return { ok: false, error: scan.error };
432
- const deadline = performance.now() + TOOL_LIMITS.maxGrepMillis;
433
- const files: string[] = [];
434
- const matches: Array<{ path: string; line: number; text: string }> = [];
435
- let truncated = false;
436
- let visited = 0;
437
- let scanBytes = 0;
438
- let resultBytes = 0;
439
- let worker: Worker | undefined;
440
- const checkSearch = () => {
441
- if (signal?.aborted) throw new Error("search cancelled");
442
- if (performance.now() >= deadline) throw new Error("search timed out");
443
- };
444
- const collectSearchFiles = async (directory: string): Promise<void> => {
445
- checkSearch();
446
- const target = await lstat(directory);
447
- checkSearch();
448
- if (target.isFile()) {
449
- if (isAllowedContent(directory, allowedPaths)) files.push(directory);
450
- return;
451
- }
452
- if (!target.isDirectory()) return;
453
- const entries = await opendir(directory);
454
- for await (const entry of entries) {
455
- checkSearch();
456
- if (
457
- ++visited > TOOL_LIMITS.maxEntries ||
458
- files.length >= TOOL_LIMITS.maxGrepFiles
459
- ) {
460
- truncated = true;
461
- break;
462
- }
463
- if (isHidden(entry.name, roots)) continue;
464
- const full = join(directory, entry.name);
465
- if (entry.isDirectory() && isRelatedToAllowedPath(full, allowedPaths))
466
- await collectSearchFiles(full);
467
- else if (entry.isFile() && isAllowedContent(full, allowedPaths))
468
- files.push(full);
469
- }
470
- };
471
- try {
472
- for (const target of scan.targets) await collectSearchFiles(target.abs);
473
- const ordered = [...new Set(files)].sort((left, right) => {
474
- const a = rootRelativePath(left);
475
- const b = rootRelativePath(right);
476
- return a < b ? -1 : a > b ? 1 : 0;
477
- });
478
- if (ordered.length > TOOL_LIMITS.maxGrepFiles) truncated = true;
479
- checkSearch();
480
- worker = new Worker(
481
- new URL("./scoped-grep-worker.mjs", import.meta.url),
482
- {
483
- resourceLimits: { maxOldGenerationSizeMb: 64 },
484
- },
485
- );
486
- // Keep one rejection path installed between requests as well, so a late
487
- // worker error cannot become an uncaught EventEmitter error.
488
- let workerFailed = false;
489
- worker.on("error", () => {
490
- workerFailed = true;
491
- });
492
- for (const file of ordered.slice(0, TOOL_LIMITS.maxGrepFiles)) {
493
- checkSearch();
494
- if (scanBytes >= TOOL_LIMITS.maxGrepScanBytes) {
495
- truncated = true;
496
- break;
497
- }
498
- const limit = Math.min(
499
- TOOL_LIMITS.maxGrepFileBytes,
500
- TOOL_LIMITS.maxGrepScanBytes - scanBytes,
501
- );
502
- // Read at most the budget plus one byte, even if the file grows after
503
- // admission. Oversized files are skipped explicitly, never decoded in full.
504
- const buffer = Buffer.alloc(limit + 1);
505
- const path = rootRelativePath(file);
506
- if (observeSafePath(workspaceRoot, path).kind !== "file") {
507
- truncated = true;
508
- continue;
509
- }
510
- const fd = await open(
511
- file,
512
- constants.O_RDONLY |
513
- (constants.O_NOFOLLOW ?? 0) |
514
- (constants.O_NONBLOCK ?? 0),
515
- );
516
- let length = 0;
517
- try {
518
- if (!(await fd.stat()).isFile()) {
519
- truncated = true;
520
- continue;
521
- }
522
- while (length < buffer.length) {
523
- checkSearch();
524
- const { bytesRead: count } = await fd.read(
525
- buffer,
526
- length,
527
- buffer.length - length,
528
- null,
529
- );
530
- if (count === 0) break;
531
- length += count;
532
- }
533
- } finally {
534
- await fd.close();
535
- }
536
- checkSearch();
537
- scanBytes += Math.min(length, limit);
538
- if (length > limit) {
539
- truncated = true;
540
- continue;
541
- }
542
- let text: string;
543
- try {
544
- text = new TextDecoder("utf-8", { fatal: true }).decode(
545
- buffer.subarray(0, length),
546
- );
547
- } catch {
548
- continue;
549
- }
550
- observe({ kind: "file", path });
551
- if (workerFailed) return { ok: false, error: "search unavailable" };
552
- const currentWorker = worker;
553
- const result = await new Promise<{
554
- matches: typeof matches;
555
- bytes: number;
556
- truncated: boolean;
557
- }>((resolve, reject) => {
558
- const cleanup = () => {
559
- clearTimeout(timer);
560
- signal?.removeEventListener("abort", onAbort);
561
- currentWorker.removeListener("message", onMessage);
562
- currentWorker.removeListener("error", onError);
563
- currentWorker.removeListener("exit", onError);
564
- };
565
- const fail = (message: string) => {
566
- cleanup();
567
- reject(new Error(message));
568
- };
569
- const onAbort = () => fail("search cancelled");
570
- const onError = () => fail("search unavailable");
571
- const onMessage = (value: {
572
- matches: typeof matches;
573
- bytes: number;
574
- truncated: boolean;
575
- }) => {
576
- cleanup();
577
- resolve(value);
578
- };
579
- const timer = setTimeout(
580
- () => fail("search timed out"),
581
- Math.max(1, deadline - performance.now()),
582
- );
583
- signal?.addEventListener("abort", onAbort, { once: true });
584
- currentWorker.once("message", onMessage);
585
- currentWorker.once("error", onError);
586
- currentWorker.once("exit", onError);
587
- if (signal?.aborted) {
588
- onAbort();
589
- return;
590
- }
591
- currentWorker.postMessage({
592
- pattern,
593
- path,
594
- text,
595
- maxMatches: TOOL_LIMITS.maxGrepMatches - matches.length,
596
- maxBytes: TOOL_LIMITS.maxGrepResultBytes - resultBytes,
597
- });
598
- });
599
- matches.push(...result.matches);
600
- resultBytes += result.bytes;
601
- if (result.truncated) {
602
- truncated = true;
603
- break;
604
- }
605
- }
606
- return { ok: true, matches, truncated };
607
- } catch (error) {
608
- const message = error instanceof Error ? error.message : "";
609
- return {
610
- ok: false,
611
- error: ["search cancelled", "search timed out"].includes(message)
612
- ? message
613
- : "search unavailable",
614
- };
615
- } finally {
616
- await worker?.terminate();
617
- }
618
- },
619
- };
620
-
621
- const lsTool: ScopedToolDef = {
622
- name: "ls",
623
- description:
624
- "List a directory within the approved scope (max 20,000 entries, stable code-unit order).",
625
- async execute(params) {
626
- const scan = resolveScanTargets(params.path);
627
- if (!scan.ok) return { ok: false, error: scan.error };
628
- for (const target of scan.targets) {
629
- let st: Stats | undefined;
630
- try {
631
- st = statSync(target.abs);
632
- } catch {
633
- return { ok: false, error: "directory does not exist" };
634
- }
635
- if (!st.isDirectory()) return { ok: false, error: "not a directory" };
636
- observe({
637
- kind: "dir",
638
- path: rootRelativePath(target.abs),
639
- });
640
- }
641
- if (scan.virtual) {
642
- const names = new Set(
643
- scan.targets.map(
644
- (target) => relativePath(scan.base, target.abs).split("/")[0],
645
- ),
646
- );
647
- return {
648
- ok: true,
649
- entries: [...names]
650
- .sort()
651
- .slice(0, TOOL_LIMITS.maxEntries)
652
- .map((name) => ({ name, type: "dir" })),
653
- };
654
- }
655
- const resolved = scan.targets[0];
656
- const entries = readdirSync(resolved.abs, { withFileTypes: true })
657
- .filter((e) => !isHidden(e.name, roots))
658
- .filter((e) =>
659
- isRelatedToAllowedPath(join(resolved.abs, e.name), allowedPaths),
660
- )
661
- .slice(0, TOOL_LIMITS.maxEntries)
662
- .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
663
- return {
664
- ok: true,
665
- entries: entries.map((e) => ({
666
- name: e.name,
667
- type: e.isDirectory() ? "dir" : "file",
668
- })),
669
- };
670
- },
671
- };
672
-
673
- const findTool: ScopedToolDef = {
674
- name: "find",
675
- description:
676
- "Search for files by glob pattern within the approved scope; returned paths are workspace-relative (max 20,000 entries).",
677
- async execute(params) {
678
- const pattern = params.pattern;
679
- if (typeof pattern !== "string" || pattern.length === 0) {
680
- return { ok: false, error: "missing pattern" };
681
- }
682
- const limit =
683
- params.limit === undefined
684
- ? TOOL_LIMITS.maxEntries
685
- : boundedInteger(params.limit);
686
- if (limit === undefined) {
687
- return { ok: false, error: "limit must be a positive integer" };
688
- }
689
- const scan = resolveScanTargets(params.path);
690
- if (!scan.ok) return { ok: false, error: scan.error };
691
- for (const target of scan.targets) {
692
- let st: Stats | undefined;
693
- try {
694
- st = statSync(target.abs);
695
- } catch {
696
- return { ok: false, error: "directory does not exist" };
697
- }
698
- if (!st.isDirectory()) return { ok: false, error: "not a directory" };
699
- observe({
700
- kind: "dir",
701
- path: rootRelativePath(target.abs),
702
- });
703
- }
704
- const matcher = globToRegExp(pattern);
705
- if ("error" in matcher) {
706
- return { ok: false, error: matcher.error };
707
- }
708
- const files: string[] = [];
709
- for (const target of scan.targets) {
710
- collectFiles(target.abs, files, TOOL_LIMITS.maxEntries, allowedPaths);
711
- }
712
- const entries = [...new Set(files)]
713
- .filter((abs) => {
714
- const searched = relativePath(scan.base, abs);
715
- return matcher.test(searched) || matcher.test(basename(abs));
716
- })
717
- .map((abs) => rootRelativePath(abs));
718
- return {
719
- ok: true,
720
- entries: entries
721
- .sort()
722
- .slice(0, Math.min(limit, TOOL_LIMITS.maxEntries)),
723
- };
724
- },
725
- };
726
-
727
- function collectFiles(
728
- dir: string,
729
- out: string[],
730
- limit: number,
731
- scopedPaths?: string[],
732
- traversal = {
733
- remaining: TOOL_LIMITS.maxEntries as number,
734
- truncated: false,
735
- },
736
- ): string[] {
737
- if (out.length >= limit) return out;
738
- const target = statSync(dir);
739
- if (target.isFile()) {
740
- if (isAllowedContent(dir, scopedPaths)) out.push(dir);
741
- return out;
742
- }
743
- if (!target.isDirectory()) return out;
744
- const entries = readdirSync(dir, { withFileTypes: true });
745
- for (const e of entries) {
746
- if (out.length >= limit || traversal.remaining-- <= 0) {
747
- traversal.truncated = true;
748
- break;
749
- }
750
- if (isHidden(e.name, roots)) continue;
751
- const full = join(dir, e.name);
752
- if (e.isDirectory()) {
753
- if (isRelatedToAllowedPath(full, scopedPaths)) {
754
- collectFiles(full, out, limit, scopedPaths, traversal);
755
- }
756
- } else if (e.isFile() && isAllowedContent(full, scopedPaths)) {
757
- out.push(full);
758
- }
759
- }
760
- return out;
761
- }
762
-
763
- function isHidden(name: string, scopes: string[]): boolean {
764
- if (name !== ".git" && name !== "node_modules") return false;
765
- // Explicit scope: the approved root itself is the hidden directory.
766
- for (const scope of scopes) {
767
- if (basename(scope) === name) return false;
768
- }
769
- return true;
770
- }
771
-
772
- return [readTool, grepTool, lsTool, findTool];
773
- }
774
-
775
- export { resolveScoped };