@picassohq/cli 1.0.3 → 1.0.5

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 (64) hide show
  1. package/dist/build-info.json +2 -1
  2. package/dist/index.js +1860 -1316
  3. package/package.json +1 -1
  4. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +4 -7
  5. package/runtime/dsh/picasso-sdk.patch.yml +47 -0
  6. package/runtime/engine-manifest.json +37 -16
  7. package/runtime/packages/picasso-compaction/cordis.patch.yml +4 -0
  8. package/runtime/packages/picasso-compaction/index.js +875 -0
  9. package/runtime/packages/picasso-compaction/package.json +27 -0
  10. package/runtime/packages/picasso-hooks/cordis.patch.yml +4 -0
  11. package/runtime/packages/picasso-hooks/index.js +302 -0
  12. package/runtime/packages/picasso-hooks/lifecycle-events.js +651 -0
  13. package/runtime/packages/picasso-hooks/package.json +29 -0
  14. package/runtime/packages/picasso-lean-context/argument-repair.js +422 -0
  15. package/runtime/packages/picasso-lean-context/glob-walk.js +518 -0
  16. package/runtime/packages/picasso-lean-context/index.js +159 -11
  17. package/runtime/packages/picasso-memory/index.js +66 -24
  18. package/runtime/packages/picasso-model-router/connections.js +213 -10
  19. package/runtime/packages/picasso-model-router/index.js +128 -1
  20. package/runtime/packages/picasso-model-router/package.json +3 -1
  21. package/runtime/packages/picasso-model-router/thinking-default.js +236 -0
  22. package/runtime/packages/picasso-progress-reports/index.js +128 -18
  23. package/runtime/packages/picasso-sdk-server/command-runs.js +37 -0
  24. package/runtime/packages/picasso-sdk-server/ignore-file.js +5 -1
  25. package/runtime/packages/picasso-sdk-server/index.js +11 -3
  26. package/runtime/packages/picasso-sdk-server/package.json +1 -0
  27. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +26 -6
  28. package/runtime/packages/picasso-web-search/backends.js +245 -195
  29. package/runtime/packages/picasso-web-search/config.js +75 -27
  30. package/runtime/packages/picasso-web-search/cordis.patch.yml +2 -1
  31. package/runtime/packages/picasso-web-search/failure.js +7 -1
  32. package/runtime/packages/picasso-web-search/index.js +7 -5
  33. package/runtime/packages/picasso-web-search/package.json +6 -0
  34. package/runtime/packages/picasso-web-search/requests.js +339 -0
  35. package/runtime/packages/picasso-web-search/router.js +17 -12
  36. package/runtime/packages/picasso-x-reader/settings.js +4 -1
  37. package/runtime/plugins/picasso-auto-approve/index.js +21 -8
  38. package/runtime/plugins/picasso-compaction/index.js +875 -0
  39. package/runtime/plugins/picasso-compaction/package.json +27 -0
  40. package/runtime/plugins/picasso-hooks/index.js +302 -0
  41. package/runtime/plugins/picasso-hooks/lifecycle-events.js +651 -0
  42. package/runtime/plugins/picasso-hooks/package.json +29 -0
  43. package/runtime/plugins/picasso-lean-context/argument-repair.js +422 -0
  44. package/runtime/plugins/picasso-lean-context/glob-walk.js +518 -0
  45. package/runtime/plugins/picasso-lean-context/index.js +159 -11
  46. package/runtime/plugins/picasso-memory/index.js +66 -24
  47. package/runtime/plugins/picasso-model-router/connections.js +213 -10
  48. package/runtime/plugins/picasso-model-router/index.js +128 -1
  49. package/runtime/plugins/picasso-model-router/package.json +3 -1
  50. package/runtime/plugins/picasso-model-router/thinking-default.js +236 -0
  51. package/runtime/plugins/picasso-progress-reports/index.js +128 -18
  52. package/runtime/plugins/picasso-provider-models/index.js +236 -4
  53. package/runtime/plugins/picasso-trackers/index.js +12 -2
  54. package/runtime/plugins/picasso-web-search/backends.js +245 -195
  55. package/runtime/plugins/picasso-web-search/config.js +75 -27
  56. package/runtime/plugins/picasso-web-search/failure.js +7 -1
  57. package/runtime/plugins/picasso-web-search/index.js +7 -5
  58. package/runtime/plugins/picasso-web-search/package.json +6 -0
  59. package/runtime/plugins/picasso-web-search/requests.js +339 -0
  60. package/runtime/plugins/picasso-web-search/router.js +17 -12
  61. package/runtime/plugins/picasso-x-reader/settings.js +4 -1
  62. package/runtime/relay/main.mjs +3877 -1989
  63. package/runtime/relay/model-listing.mjs +337 -26
  64. package/runtime/relay/versions-routes.mjs +86 -20
@@ -0,0 +1,518 @@
1
+ // Fast, complete `glob` for large workspaces (both surfaces).
2
+ //
3
+ // The engine's `glob` (`@deepseek-ai/dsh-tool-fs-search`) runs `rg --files --glob=<pattern> --sort=modified
4
+ // --no-ignore --hidden`. `--no-ignore` walks every dependency, build and cache tree, and `--sort=modified` makes
5
+ // ripgrep walk on one thread and stat every match before printing anything. In a large monorepo (4.1 million files,
6
+ // most of them under node_modules, .next and other ignored trees) that is ~50 s, and the engine's 30 s per-call limit
7
+ // (`tool-call-timeout-policy`) turns a pattern like `apps/**/trace-intel/*.ts` into `tool call timed out after 30000ms`.
8
+ //
9
+ // This module answers the same call differently:
10
+ // - ripgrep only LISTS files (`--files`, all cores, no `--sort`), honouring .gitignore / .ignore / .rgignore
11
+ // (`--no-require-git`, so a checkout without .git honours them too), and skipping VCS metadata (the engine's list)
12
+ // and dependency / build-cache directories by name. The pattern is NOT given to ripgrep: a `--glob` that matches a
13
+ // directory name (`*`, `**/*`, `apps/**`) whitelists that directory past .gitignore and the walk is huge again.
14
+ // - The pattern is matched here, with ripgrep's own glob rules (`compileGlob`): no "/" matches the basename at any
15
+ // depth, a "/" anchors it to the workspace, `*` and `?` stop at "/", `**`, `[...]`, `{a,b}`, `\` escapes. With
16
+ // `path`, a pattern also matches relative to that directory.
17
+ // - A pattern without `path` that starts with literal directories (`apps/web/**/*.ts`) walks only that directory.
18
+ // - When the pattern or path names a skipped directory (`node_modules/react/**`), or starts inside a directory
19
+ // .gitignore excludes (`tmp/**/*.json` with `tmp/` ignored), the walk uses `--no-ignore` and keeps it.
20
+ // - Matches are sorted by modification time here, oldest first (what `--sort=modified` printed), ties by path.
21
+ // It always returns the COMPLETE match set: no cap, no partial result. The engine's own renderer, card projection and
22
+ // spill path (`tools/post-execute`: over 100 paths the full sorted list is saved and the result names the file) see
23
+ // exactly the value the engine body produces, `{ root, paths }`.
24
+ //
25
+ // How it is wired (`tools/execute` is a waterfall, `{ global: true }` so CLI root and Mac preset scopes alike):
26
+ // 1. an OUTER listener (prepended, so it runs before the engine's 30 s timeout wrapper arms) does the walk with the
27
+ // caller's own signal — Esc / Ctrl+C still stops it — under a generous ceiling (`GLOB_WALK_MAX_MS`), stashes the
28
+ // result for this exact call, then calls `next()` so every other wrapper (checkpoint flush, failure policy, user
29
+ // hooks) still runs;
30
+ // 2. an INNER listener returns the stashed result in place of the engine body (no second walk).
31
+ // Anything unexpected (no ripgrep binary, a spawn failure, a `!` or directory-only pattern, unusual arguments) stashes
32
+ // nothing, so the call runs the engine body exactly as before. Nothing here touches the tool list or prompt text:
33
+ // Tier 1 is byte-identical.
34
+
35
+ import { spawn } from "node:child_process";
36
+ import { existsSync, realpathSync } from "node:fs";
37
+ import { stat } from "node:fs/promises";
38
+ import { createRequire } from "node:module";
39
+ import { delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";
40
+
41
+ export const GLOB_TOOL = "glob";
42
+
43
+ /** VCS metadata directories: the engine's `GLOB_VCS_EXCLUDES`, never listed. */
44
+ export const VCS_DIRS = Object.freeze([".git", ".svn", ".hg", ".bzr", ".jj", ".sl"]);
45
+
46
+ /**
47
+ * Dependency and build-cache directories skipped by name unless the pattern or path names them. Only names that are
48
+ * never hand-written source: `dist`, `build`, `target`, `out` and `coverage` are left to .gitignore, because some
49
+ * repositories commit them.
50
+ */
51
+ export const SKIPPED_DIRS = Object.freeze([
52
+ "node_modules",
53
+ "bower_components",
54
+ "jspm_packages",
55
+ ".pnpm-store",
56
+ ".venv",
57
+ "venv",
58
+ "__pycache__",
59
+ ".tox",
60
+ ".nox",
61
+ ".mypy_cache",
62
+ ".pytest_cache",
63
+ ".ruff_cache",
64
+ ".gradle",
65
+ "DerivedData",
66
+ ".next",
67
+ ".nuxt",
68
+ ".svelte-kit",
69
+ ".turbo",
70
+ ".parcel-cache",
71
+ ".cache",
72
+ ]);
73
+
74
+ /** Ceiling for one walk (replaces the engine's 30 s for this tool). The caller's Esc / Ctrl+C stops it sooner. */
75
+ export const GLOB_WALK_MAX_MS = 10 * 60_000;
76
+
77
+ /** Concurrent `stat` calls while sorting by modification time. */
78
+ const STAT_CONCURRENCY = 64;
79
+ const GIT_CHECK_IGNORE_MS = 3_000;
80
+ const STDERR_MAX_BYTES = 64 * 1024;
81
+ const GLOB_META = /[*?[\]{}!]/;
82
+
83
+ /** The `{ pattern, path? }` a stock `glob` call carries, or undefined for anything else (the engine then answers). */
84
+ export function globArgsOf(args) {
85
+ if (args === null || typeof args !== "object" || Array.isArray(args)) return undefined;
86
+ for (const key of Object.keys(args)) if (key !== "pattern" && key !== "path") return undefined;
87
+ const { pattern, path } = args;
88
+ if (typeof pattern !== "string" || pattern.trim().length === 0) return undefined;
89
+ if (path !== undefined && (typeof path !== "string" || path.trim().length === 0)) return undefined;
90
+ return path === undefined ? { pattern } : { pattern, path };
91
+ }
92
+
93
+ /**
94
+ * Compile one glob with ripgrep's `--glob` rules (gitignore-style overrides, literal separator) into a RegExp tested
95
+ * against a "/"-separated relative path. Undefined for what ripgrep reads differently from a plain positive file glob
96
+ * (a leading `!` is an exclusion, a trailing `/` matches directories only); the engine answers those.
97
+ */
98
+ export function compileGlob(pattern) {
99
+ let glob = pattern;
100
+ if (glob.startsWith("!") || glob.endsWith("/")) return undefined;
101
+ if (glob.startsWith("\\!") || glob.startsWith("\\#")) glob = glob.slice(1);
102
+ let anchored = false;
103
+ if (glob.startsWith("/")) {
104
+ anchored = true;
105
+ glob = glob.slice(1);
106
+ }
107
+ if (glob.length === 0) return undefined;
108
+ if (!anchored && !glob.includes("/") && !glob.startsWith("**")) glob = `**/${glob}`;
109
+ if (glob.endsWith("/**")) glob = `${glob}/*`;
110
+ const tokens = [];
111
+ const chars = [...glob];
112
+ let braceDepth = 0;
113
+ for (let i = 0; i < chars.length; i += 1) {
114
+ const c = chars[i];
115
+ if (c === "\\") {
116
+ i += 1;
117
+ tokens.push(escapeRegExp(chars[i] ?? "\\"));
118
+ } else if (c === "*") {
119
+ let j = i;
120
+ while (chars[j + 1] === "*") j += 1;
121
+ const recursive = j > i;
122
+ const atStart = i === 0 || chars[i - 1] === "/";
123
+ const atEnd = j === chars.length - 1 || chars[j + 1] === "/";
124
+ if (recursive && atStart && atEnd) {
125
+ if (j === chars.length - 1) tokens.push(i === 0 ? ".*" : ".*");
126
+ else {
127
+ // `**/`: zero or more whole directories
128
+ tokens.push("(?:[^/]*/)*");
129
+ j += 1; // consume the "/"
130
+ }
131
+ } else tokens.push("[^/]*");
132
+ i = j;
133
+ } else if (c === "?") tokens.push("[^/]");
134
+ else if (c === "[") {
135
+ let j = i + 1;
136
+ let negate = false;
137
+ if (chars[j] === "!" || chars[j] === "^") {
138
+ negate = true;
139
+ j += 1;
140
+ }
141
+ let body = "";
142
+ if (chars[j] === "]") {
143
+ body += "\\]";
144
+ j += 1;
145
+ }
146
+ while (j < chars.length && chars[j] !== "]") {
147
+ const d = chars[j];
148
+ body += d === "\\" || d === "^" || d === "[" ? `\\${d}` : d;
149
+ j += 1;
150
+ }
151
+ if (j >= chars.length) tokens.push("\\[");
152
+ else {
153
+ tokens.push(negate ? `[^/${body}]` : `[${body}]`);
154
+ i = j;
155
+ }
156
+ } else if (c === "{") {
157
+ braceDepth += 1;
158
+ tokens.push("(?:");
159
+ } else if (c === "}" && braceDepth > 0) {
160
+ braceDepth -= 1;
161
+ tokens.push(")");
162
+ } else if (c === "," && braceDepth > 0) tokens.push("|");
163
+ else tokens.push(escapeRegExp(c));
164
+ }
165
+ if (braceDepth > 0) return undefined;
166
+ try {
167
+ return new RegExp(`^${tokens.join("")}$`, "u");
168
+ } catch {
169
+ return undefined;
170
+ }
171
+ }
172
+
173
+ function escapeRegExp(text) {
174
+ return text.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
175
+ }
176
+
177
+ /** Names from `SKIPPED_DIRS` the pattern or path mentions: those directories are searched, not skipped. */
178
+ export function targetedSkippedDirs(input) {
179
+ const text = `${input.pattern}\n${input.path ?? ""}`;
180
+ return SKIPPED_DIRS.filter((name) => text.includes(name));
181
+ }
182
+
183
+ /** The pattern's leading directory segments that hold no glob syntax: `apps/web/**` → `apps/web`, `**` → "". */
184
+ export function literalPrefix(pattern) {
185
+ const body = pattern.startsWith("/") ? pattern.slice(1) : pattern;
186
+ const segments = body.split("/").slice(0, -1);
187
+ const literal = [];
188
+ for (const segment of segments) {
189
+ if (segment.length === 0 || segment === "." || segment === ".." || GLOB_META.test(segment)) break;
190
+ literal.push(segment);
191
+ }
192
+ return literal.join("/");
193
+ }
194
+
195
+ /**
196
+ * Where ripgrep starts: `path` when given (as the engine does), else the pattern's literal directory prefix when the
197
+ * pattern is anchored (has a "/"), else the workspace (undefined).
198
+ */
199
+ export function searchRoot(input) {
200
+ if (input.path !== undefined) return input.path;
201
+ const prefix = literalPrefix(input.pattern);
202
+ return prefix === "" ? undefined : prefix;
203
+ }
204
+
205
+ /**
206
+ * The ripgrep argv (without the binary): list files only, NUL-separated, hidden files included, ignore files honoured
207
+ * unless `noIgnore`, VCS and skipped directories pruned, the root behind `--`.
208
+ * @param {{pattern: string, path?: string}} input
209
+ * @param {{ noIgnore?: boolean }} [options] - `noIgnore`: the search starts inside an ignored directory.
210
+ */
211
+ export function buildGlobArgv(input, options = {}) {
212
+ const targeted = new Set(targetedSkippedDirs(input));
213
+ const noIgnore = options.noIgnore === true || targeted.size > 0;
214
+ const skipped = SKIPPED_DIRS.filter((name) => !targeted.has(name));
215
+ const argv = [
216
+ "--files",
217
+ "--null",
218
+ "--hidden",
219
+ noIgnore ? "--no-ignore" : "--no-require-git",
220
+ ...VCS_DIRS.flatMap((name) => [`--glob=!**/${name}`, `--glob=!**/${name}/**`]),
221
+ ...skipped.flatMap((name) => [`--glob=!**/${name}`, `--glob=!**/${name}/**`]),
222
+ ];
223
+ const root = searchRoot(input);
224
+ if (root !== undefined) argv.push("--", root);
225
+ return argv;
226
+ }
227
+
228
+ /**
229
+ * The path predicate for one call: ripgrep's rule (the pattern against the path relative to the workspace), plus,
230
+ * with `path`, the pattern against the path relative to that directory. Undefined when the pattern cannot compile.
231
+ */
232
+ export function globMatcher(input, workdir) {
233
+ const regex = compileGlob(input.pattern);
234
+ if (regex === undefined) return undefined;
235
+ const base = input.path === undefined ? undefined : resolve(workdir, input.path);
236
+ const slash = (text) => (sep === "/" ? text : text.split(sep).join("/"));
237
+ return (printed) => {
238
+ const absolute = resolve(workdir, printed);
239
+ const fromWorkdir = relative(workdir, absolute);
240
+ if (!fromWorkdir.startsWith("..") && !isAbsolute(fromWorkdir) && regex.test(slash(fromWorkdir))) return true;
241
+ if (base !== undefined) {
242
+ const fromBase = relative(base, absolute);
243
+ if (!fromBase.startsWith("..") && !isAbsolute(fromBase) && regex.test(slash(fromBase))) return true;
244
+ }
245
+ return false;
246
+ };
247
+ }
248
+
249
+ /** The engine's display rule: absolute paths inside the workdir become workdir-relative, everything else unchanged. */
250
+ export function toWorkdirRelative(path, workdir) {
251
+ if (!isAbsolute(path)) return path;
252
+ const rel = relative(workdir, path);
253
+ if (rel.length === 0) return ".";
254
+ if (rel === ".." || rel.startsWith(`..${sep}`)) return path;
255
+ return rel;
256
+ }
257
+
258
+ /**
259
+ * The packaged ripgrep the engine itself uses (resolved from the launched engine, the same anchor trick as the schema
260
+ * library), then a sidecar next to a single-file runtime, then `rg` on PATH. Undefined when none exists.
261
+ */
262
+ export function resolveRipgrep(env = process.env) {
263
+ const platformPkg = `@vscode/ripgrep-${process.platform}-${process.arch}`;
264
+ const binary = process.platform === "win32" ? "rg.exe" : "rg";
265
+ const anchors = [];
266
+ if (typeof process.argv?.[1] === "string" && process.argv[1]) anchors.push(process.argv[1]);
267
+ for (const dir of (env.PATH ?? "").split(delimiter).filter(Boolean)) anchors.push(join(dir, "dsh"));
268
+ for (const anchor of anchors) {
269
+ let require;
270
+ try {
271
+ require = createRequire(realpathSync(anchor));
272
+ } catch {
273
+ continue;
274
+ }
275
+ try {
276
+ return require.resolve(`${platformPkg}/bin/${binary}`);
277
+ } catch {
278
+ // ripgrep may sit under the engine's ripgrep util package instead
279
+ }
280
+ try {
281
+ return createRequire(require.resolve("@deepseek-ai/dsh-util-ripgrep")).resolve(`${platformPkg}/bin/${binary}`);
282
+ } catch {
283
+ // try the next anchor
284
+ }
285
+ }
286
+ const sidecar = process.platform === "win32" ? process.execPath.replace(/\.exe$/i, "-rg.exe") : `${process.execPath}-rg`;
287
+ if ("pkg" in process && existsSync(sidecar)) return sidecar;
288
+ for (const dir of [...(env.PATH ?? "").split(delimiter).filter(Boolean), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"]) {
289
+ const candidate = join(dir, binary);
290
+ if (existsSync(candidate)) return candidate;
291
+ }
292
+ return undefined;
293
+ }
294
+
295
+ /** Whether `target` (relative to `cwd`) is ignored by git. False when git is missing, errors, or is slow. */
296
+ export function gitIgnores(cwd, target, signal) {
297
+ return new Promise((done) => {
298
+ let child;
299
+ try {
300
+ child = spawn("git", ["-C", cwd, "check-ignore", "-q", "--", target], { stdio: "ignore", signal });
301
+ } catch {
302
+ done(false);
303
+ return;
304
+ }
305
+ const timer = setTimeout(() => child.kill("SIGKILL"), GIT_CHECK_IGNORE_MS);
306
+ child.on("error", () => {
307
+ clearTimeout(timer);
308
+ done(false);
309
+ });
310
+ child.on("close", (code) => {
311
+ clearTimeout(timer);
312
+ done(code === 0);
313
+ });
314
+ });
315
+ }
316
+
317
+ /**
318
+ * Run ripgrep and keep every NUL-separated path `keep` accepts (filtered as it streams, so a multi-million-file walk
319
+ * never holds every path). Resolves `{ paths, listed, exitCode, killSignal, stderr }`; rejects with the abort reason
320
+ * when `signal` fires (the process is killed first).
321
+ */
322
+ export function runRipgrepFiles(rgPath, argv, cwd, signal, keep = () => true) {
323
+ return new Promise((done, fail) => {
324
+ if (signal?.aborted) {
325
+ fail(signal.reason ?? new Error("aborted"));
326
+ return;
327
+ }
328
+ const env = { ...process.env };
329
+ delete env.RIPGREP_CONFIG_PATH;
330
+ const child = spawn(rgPath, ["--no-config", ...argv], { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
331
+ const paths = [];
332
+ let listed = 0;
333
+ let pending = "";
334
+ let stderr = "";
335
+ let settled = false;
336
+ const take = (line) => {
337
+ if (line.length === 0) return;
338
+ listed += 1;
339
+ if (keep(line)) paths.push(line);
340
+ };
341
+ const onAbort = () => {
342
+ child.kill("SIGKILL");
343
+ if (!settled) {
344
+ settled = true;
345
+ fail(signal.reason ?? new Error("aborted"));
346
+ }
347
+ };
348
+ signal?.addEventListener("abort", onAbort, { once: true });
349
+ child.stdout.setEncoding("utf8");
350
+ child.stdout.on("data", (chunk) => {
351
+ pending += chunk;
352
+ let start = 0;
353
+ let end;
354
+ while ((end = pending.indexOf("\0", start)) !== -1) {
355
+ take(pending.slice(start, end));
356
+ start = end + 1;
357
+ }
358
+ pending = pending.slice(start);
359
+ });
360
+ child.stderr.setEncoding("utf8");
361
+ child.stderr.on("data", (chunk) => {
362
+ if (stderr.length < STDERR_MAX_BYTES) stderr += chunk;
363
+ });
364
+ child.on("error", (error) => {
365
+ signal?.removeEventListener("abort", onAbort);
366
+ if (!settled) {
367
+ settled = true;
368
+ fail(error);
369
+ }
370
+ });
371
+ child.on("close", (code, killSignal) => {
372
+ signal?.removeEventListener("abort", onAbort);
373
+ if (settled) return;
374
+ settled = true;
375
+ take(pending);
376
+ done({ paths, listed, exitCode: code, killSignal, stderr: stderr.trim() });
377
+ });
378
+ });
379
+ }
380
+
381
+ /** Sort `paths` by modification time, oldest first (ripgrep's `--sort=modified`), ties by path. */
382
+ export async function sortByModified(paths, cwd, signal) {
383
+ const times = new Array(paths.length);
384
+ let next = 0;
385
+ const worker = async () => {
386
+ while (next < paths.length) {
387
+ if (signal?.aborted) throw signal.reason ?? new Error("aborted");
388
+ const index = next++;
389
+ try {
390
+ times[index] = (await stat(resolve(cwd, paths[index]))).mtimeMs;
391
+ } catch {
392
+ times[index] = 0; // gone since the walk: keep it, first
393
+ }
394
+ }
395
+ };
396
+ await Promise.all(Array.from({ length: Math.min(STAT_CONCURRENCY, paths.length) }, worker));
397
+ const order = paths.map((_, index) => index);
398
+ order.sort((a, b) => times[a] - times[b] || (paths[a] < paths[b] ? -1 : paths[a] > paths[b] ? 1 : 0));
399
+ return order.map((index) => paths[index]);
400
+ }
401
+
402
+ /** The engine's error envelope for a failed search (`SearchError` with a `SEARCH_*` code). */
403
+ function searchError(message, code) {
404
+ return { content: [{ type: "text", text: `Error: ${message}` }], isError: true, error: { message, info: { name: "SearchError", code } } };
405
+ }
406
+
407
+ /**
408
+ * One complete walk. Returns the tool result to serve (`{ isError: false, value: { root, paths } }` or the engine's
409
+ * error envelope), or undefined when the engine body should answer instead.
410
+ * @param {{pattern: string, path?: string}} input
411
+ * @param {string} workdir - the absolute directory the engine would run ripgrep in.
412
+ * @param {AbortSignal | undefined} signal
413
+ * @param {{ rgPath?: string, gitIgnores?: Function }} [options]
414
+ */
415
+ export async function walkGlob(input, workdir, signal, options = {}) {
416
+ const matches = globMatcher(input, workdir);
417
+ if (matches === undefined) return undefined;
418
+ const rgPath = options.rgPath ?? resolveRipgrep();
419
+ if (rgPath === undefined) return undefined;
420
+ const display = input.path === undefined ? "." : toWorkdirRelative(input.path, workdir);
421
+ const start = searchRoot(input);
422
+ if (start !== undefined && input.path === undefined && !existsSync(resolve(workdir, start))) {
423
+ // The pattern's literal directory does not exist: nothing can match (ripgrep would only report the missing root).
424
+ return { isError: false, value: { root: display, paths: [] } };
425
+ }
426
+ const checkIgnore = options.gitIgnores ?? gitIgnores;
427
+ const noIgnore = start !== undefined && targetedSkippedDirs(input).length === 0 ? await checkIgnore(workdir, start, signal) : false;
428
+ const run = await runRipgrepFiles(rgPath, buildGlobArgv(input, { noIgnore }), workdir, signal, matches);
429
+ if (run.killSignal !== null && run.killSignal !== undefined) return undefined;
430
+ if (run.exitCode !== 0 && run.exitCode !== 1 && run.listed === 0) {
431
+ // Nothing listed at all (a missing or unreadable path): the engine's own failure class. Exit 2 after listing files
432
+ // only means some entries were unreadable; every readable match is still returned.
433
+ return searchError(`glob search failed (exit ${run.exitCode})${run.stderr ? `: ${run.stderr}` : ""}`, "SEARCH_FAILED");
434
+ }
435
+ const sorted = await sortByModified(run.paths, workdir, signal);
436
+ return { isError: false, value: { root: display, paths: sorted.map((path) => toWorkdirRelative(path, workdir)) } };
437
+ }
438
+
439
+ function serviceOf(ctx, name) {
440
+ try {
441
+ return typeof ctx?.get === "function" ? ctx.get(name) : undefined;
442
+ } catch {
443
+ return undefined;
444
+ }
445
+ }
446
+
447
+ /** The workdir the engine's `glob` would use: the agent's session directory, else the process cwd. */
448
+ async function workdirFor(ctx, exec, signal) {
449
+ if (exec?.agent === undefined) return process.cwd();
450
+ const workingDirectory = serviceOf(ctx, "workingDirectory");
451
+ if (typeof workingDirectory?.ensure !== "function") return undefined;
452
+ return workingDirectory.ensure(exec.agent, signal);
453
+ }
454
+
455
+ /**
456
+ * The two `tools/execute` listeners. `outer` walks and stashes; `inner` serves the stash in place of the engine body.
457
+ * @param {object} ctx - the plugin context (`ctx.get('tools' | 'workingDirectory')`, read at call time).
458
+ * @param {{ rgPath?: string, maxMs?: number, gitIgnores?: Function, now?: () => number }} [options]
459
+ */
460
+ export function createGlobWalk(ctx, options = {}) {
461
+ const stash = new WeakMap();
462
+ const maxMs = options.maxMs ?? GLOB_WALK_MAX_MS;
463
+
464
+ async function outer(exec, next) {
465
+ if (exec?.name !== GLOB_TOOL) return next();
466
+ const input = globArgsOf(exec.arguments);
467
+ const tools = serviceOf(ctx, "tools");
468
+ if (input === undefined || (tools !== undefined && typeof tools.get === "function" && !tools.get(GLOB_TOOL, exec.agent, exec.toolSet))) {
469
+ return next();
470
+ }
471
+ const caller = exec.signal;
472
+ if (caller?.aborted) return next();
473
+ const limit = AbortSignal.timeout(maxMs);
474
+ const signal = caller === undefined ? limit : AbortSignal.any([caller, limit]);
475
+ let served;
476
+ try {
477
+ const workdir = await workdirFor(ctx, exec, signal);
478
+ if (workdir !== undefined) served = await walkGlob(input, workdir, signal, options);
479
+ } catch {
480
+ if (limit.aborted && !caller?.aborted) {
481
+ served = searchError(
482
+ `glob was still walking after ${maxMs >= 60_000 ? `${Math.round(maxMs / 60_000)} min` : `${Math.max(1, Math.round(maxMs / 1000))} s`}; narrow pattern or path and retry`,
483
+ "SEARCH_ABORTED",
484
+ );
485
+ }
486
+ // A caller abort or any other failure: the engine pipeline answers (cancelled, or its own body).
487
+ }
488
+ if (served === undefined) return next();
489
+ stash.set(exec, served);
490
+ try {
491
+ return await next();
492
+ } finally {
493
+ stash.delete(exec);
494
+ }
495
+ }
496
+
497
+ async function inner(exec, next) {
498
+ const served = exec?.name === GLOB_TOOL ? stash.get(exec) : undefined;
499
+ return served === undefined ? next() : served;
500
+ }
501
+
502
+ return { outer, inner, stash };
503
+ }
504
+
505
+ /** Mount both listeners on every scope. Returns the disposers (empty when the context has no event API). */
506
+ export function installGlobWalk(ctx, options = {}) {
507
+ if (typeof ctx?.on !== "function") return [];
508
+ const { outer, inner } = createGlobWalk(ctx, options);
509
+ const disposers = [];
510
+ try {
511
+ // The server first: an outer walk with nothing to serve it would make the engine walk a second time.
512
+ disposers.push(ctx.on("tools/execute", inner, { global: true }));
513
+ disposers.push(ctx.on("tools/execute", outer, { global: true, prepend: true }));
514
+ } catch {
515
+ // an event API without these options: leave the engine's glob as it is
516
+ }
517
+ return disposers;
518
+ }