@foldrun/core 24.5.0 → 24.7.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.
@@ -22,6 +22,9 @@ type CanUseTool = (name: string, input: Json, extra: {
22
22
  interface LoopOptions {
23
23
  cwd: string;
24
24
  env: Record<string, string | undefined>;
25
+ /** What the tools (Bash) get; `env` when not given. foldrun code passes
26
+ * the person's own environment here, so the model key stays with the loop. */
27
+ shellEnv: Record<string, string | undefined>;
25
28
  model: string;
26
29
  systemPrompt: string;
27
30
  tools: EngineTool[];
@@ -75,12 +75,26 @@ function readOptions(options) {
75
75
  const model = String(options.model ?? "");
76
76
  if (!model)
77
77
  throw new Error("the foldrun engine needs a model");
78
+ // Tools the host brings, as EngineTool objects: they sit beside the
79
+ // built-in ones and go through canUseTool and the hooks like them.
80
+ // foldrun code's cloud_agents is one. A name may not shadow a built-in.
81
+ const extra = [];
82
+ for (const t of Array.isArray(options.extraTools) ? options.extraTools : []) {
83
+ const tool = t;
84
+ if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
85
+ throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
86
+ }
87
+ if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name))
88
+ throw new Error(`extraTools: ${tool.name} is already a tool`);
89
+ extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema, readOnly: tool.readOnly === true, run: tool.run });
90
+ }
78
91
  return {
79
92
  cwd: String(options.cwd ?? process.cwd()),
80
93
  env,
94
+ shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
81
95
  model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
82
96
  systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
83
- tools: names.map((n) => ENGINE_TOOLS[n]),
97
+ tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
84
98
  maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
85
99
  partial: options.includePartialMessages === true,
86
100
  pre: hookFns(options.hooks, "PreToolUse"),
@@ -345,7 +359,7 @@ async function* run(prompt, o, signal, interrupted) {
345
359
  const sessionId = crypto.randomUUID();
346
360
  const startedAt = Date.now();
347
361
  const byName = new Map(o.tools.map((t) => [t.name, t]));
348
- const ctx = { cwd: o.cwd, env: o.env, signal, reads: new Map(), groups: new Set() };
362
+ const ctx = { cwd: o.cwd, env: o.shellEnv, signal, reads: new Map(), groups: new Set() };
349
363
  // An earlier conversation comes first (foldrun code's local turns carry
350
364
  // theirs, 19 Nov 2026); the prompt is always the newest user turn.
351
365
  if (o.history.length % 2 !== 0)
@@ -28,6 +28,11 @@ export interface EngineTool {
28
28
  }
29
29
  /** The most one tool result puts into the conversation, in characters. */
30
30
  export declare const RESULT_CAP = 30000;
31
+ /** How long one Grep may match for. A pattern the model wrote can take
32
+ * exponential time on the wrong text (`(a+)+$`); the matching runs in a
33
+ * worker thread that is ended at this limit or when the step is stopped,
34
+ * so it never freezes the process that runs the loop. */
35
+ export declare const GREP_MS = 30000;
31
36
  export declare const BASH_DEFAULT_MS = 120000;
32
37
  export declare const BASH_MAX_MS = 600000;
33
38
  /** Head and tail of a long text, with the cut said in the middle. */
@@ -37,5 +42,34 @@ export declare function occurrences(hay: string, needle: string): number;
37
42
  /** A glob as a regular expression over a `/`-separated relative path:
38
43
  * `**` any folders, `*` within one name, `?` one character, `{a,b}`. */
39
44
  export declare function globToRegExp(glob: string): RegExp;
45
+ /** The most alternatives a glob's braces may expand to. */
46
+ export declare const GLOB_ALTERNATIVES = 64;
47
+ /** A glob as a test over a `/`-separated relative path — the same language
48
+ * as globToRegExp, matched in bounded time. Throws when its braces expand
49
+ * past GLOB_ALTERNATIVES. */
50
+ export declare function globMatcher(glob: string): (text: string) => boolean;
51
+ /** Why a glob is refused, or null. */
52
+ export declare function globProblem(glob: string): string | null;
53
+ type MatchJob = {
54
+ pattern: string;
55
+ flags: string;
56
+ files: string[];
57
+ mode: string;
58
+ limit: number;
59
+ maxBytes: number;
60
+ };
61
+ type MatchResult = {
62
+ out: string[];
63
+ total: number;
64
+ } | {
65
+ timedOut: true;
66
+ } | {
67
+ stopped: true;
68
+ } | {
69
+ error: string;
70
+ };
71
+ /** Run MATCH_WORKER over `job.files`; end it at `ms` or when `signal` fires. */
72
+ export declare function matchInWorker(job: MatchJob, signal: AbortSignal, ms: number): Promise<MatchResult>;
40
73
  /** The engine's built-in tools, by the name the model and core both use. */
41
74
  export declare const ENGINE_TOOLS: Readonly<Record<string, EngineTool>>;
75
+ export {};
@@ -22,6 +22,7 @@
22
22
  import fs from "node:fs";
23
23
  import path from "node:path";
24
24
  import { spawn } from "node:child_process";
25
+ import { Worker } from "node:worker_threads";
25
26
  /** End everything the session's commands started and left running. */
26
27
  export function killGroups(ctx) {
27
28
  for (const pgid of ctx.groups) {
@@ -42,6 +43,11 @@ const SEARCH_FILE_BYTES = 2 * 1024 * 1024;
42
43
  const WALK_FILES = 20_000;
43
44
  const GLOB_RESULTS = 200;
44
45
  const GREP_RESULTS = 250;
46
+ /** How long one Grep may match for. A pattern the model wrote can take
47
+ * exponential time on the wrong text (`(a+)+$`); the matching runs in a
48
+ * worker thread that is ended at this limit or when the step is stopped,
49
+ * so it never freezes the process that runs the loop. */
50
+ export const GREP_MS = 30_000;
45
51
  export const BASH_DEFAULT_MS = 120_000;
46
52
  export const BASH_MAX_MS = 600_000;
47
53
  const KILL_GRACE_MS = 2000;
@@ -304,11 +310,127 @@ export function globToRegExp(glob) {
304
310
  }
305
311
  return new RegExp(`^${re}$`);
306
312
  }
313
+ /** The most folders one walk opens: a tree of empty folders is bounded too. */
314
+ const WALK_DIRS = 20_000;
315
+ /** The most alternatives a glob's braces may expand to. */
316
+ export const GLOB_ALTERNATIVES = 64;
317
+ /** `{a,b}` expanded, as globToRegExp reads braces: no nesting, the inside literal. */
318
+ function expandBraces(glob) {
319
+ const i = glob.indexOf("{");
320
+ if (i < 0)
321
+ return [glob];
322
+ const end = glob.indexOf("}", i);
323
+ if (end < 0)
324
+ return [glob];
325
+ const rest = expandBraces(glob.slice(end + 1));
326
+ if (!rest)
327
+ return null;
328
+ const out = [];
329
+ for (const alt of glob.slice(i + 1, end).split(",")) {
330
+ for (const r of rest) {
331
+ out.push(`${glob.slice(0, i)}\u0000${alt}\u0000${r}`);
332
+ if (out.length > GLOB_ALTERNATIVES)
333
+ return null;
334
+ }
335
+ }
336
+ return out;
337
+ }
338
+ function globTokens(glob) {
339
+ const out = [];
340
+ let literal = false;
341
+ for (let i = 0; i < glob.length; i++) {
342
+ const c = glob[i];
343
+ // \u0000 brackets a brace's alternative: its characters are literal.
344
+ if (c === "\u0000") {
345
+ literal = !literal;
346
+ continue;
347
+ }
348
+ if (literal)
349
+ out.push({ t: "lit", c });
350
+ else if (c === "*") {
351
+ if (glob[i + 1] === "*") {
352
+ i++;
353
+ if (glob[i + 1] === "/") {
354
+ i++;
355
+ out.push({ t: "dirs" });
356
+ }
357
+ else
358
+ out.push({ t: "any" });
359
+ }
360
+ else
361
+ out.push({ t: "star" });
362
+ }
363
+ else if (c === "?")
364
+ out.push({ t: "one" });
365
+ else
366
+ out.push({ t: "lit", c });
367
+ }
368
+ return out;
369
+ }
370
+ /** Whether `text` matches the tokens: a table over tokens × positions, so
371
+ * the time is bounded by their product whatever the pattern (Codex: a
372
+ * backtracking regular expression is not). */
373
+ function tokensMatch(tokens, text) {
374
+ const n = text.length;
375
+ let cur = new Uint8Array(n + 1);
376
+ cur[0] = 1;
377
+ for (const tok of tokens) {
378
+ const next = new Uint8Array(n + 1);
379
+ if (tok.t === "lit") {
380
+ for (let j = 0; j < n; j++)
381
+ if (cur[j] && text[j] === tok.c)
382
+ next[j + 1] = 1;
383
+ }
384
+ else if (tok.t === "one") {
385
+ for (let j = 0; j < n; j++)
386
+ if (cur[j] && text[j] !== "/")
387
+ next[j + 1] = 1;
388
+ }
389
+ else if (tok.t === "star" || tok.t === "any") {
390
+ for (let j = 0; j <= n; j++) {
391
+ // `**` stops at a line break as the `.*` it was always read as does.
392
+ if (cur[j] || (j > 0 && next[j - 1] && (tok.t === "any" ? !/[\n\r\u2028\u2029]/.test(text[j - 1]) : text[j - 1] !== "/")))
393
+ next[j] = 1;
394
+ }
395
+ }
396
+ else {
397
+ // Zero or more whole folders: `name/` repeated, each name non-empty.
398
+ for (let j = 0; j <= n; j++) {
399
+ if (cur[j])
400
+ next[j] = 1;
401
+ if (!next[j])
402
+ continue;
403
+ const slash = text.indexOf("/", j);
404
+ if (slash > j)
405
+ next[slash + 1] = 1;
406
+ }
407
+ }
408
+ cur = next;
409
+ }
410
+ return cur[n] === 1;
411
+ }
412
+ /** A glob as a test over a `/`-separated relative path — the same language
413
+ * as globToRegExp, matched in bounded time. Throws when its braces expand
414
+ * past GLOB_ALTERNATIVES. */
415
+ export function globMatcher(glob) {
416
+ const alts = expandBraces(glob);
417
+ if (!alts)
418
+ throw new Error(`the glob's braces make more than ${GLOB_ALTERNATIVES} patterns — name fewer`);
419
+ const compiled = alts.map(globTokens);
420
+ return (text) => compiled.some((t) => tokensMatch(t, text));
421
+ }
422
+ /** Why a glob is refused, or null. */
423
+ export function globProblem(glob) {
424
+ return expandBraces(glob) ? null : `the glob's braces make more than ${GLOB_ALTERNATIVES} patterns — name fewer`;
425
+ }
307
426
  /** Every file under `root`, as paths relative to it. Bounded. */
308
427
  function walk(root) {
309
428
  const files = [];
310
429
  const stack = [""];
430
+ let dirs = 0;
311
431
  while (stack.length) {
432
+ if (++dirs > WALK_DIRS)
433
+ return { files, cut: true };
312
434
  const rel = stack.pop();
313
435
  let entries;
314
436
  try {
@@ -356,6 +478,9 @@ const glob = {
356
478
  const pattern = str(input, "pattern");
357
479
  if (!pattern)
358
480
  return fail("Glob needs pattern");
481
+ const tooWild = globProblem(pattern);
482
+ if (tooWild)
483
+ return fail(tooWild);
359
484
  const where = searchRoot(input, ctx);
360
485
  if ("text" in where)
361
486
  return where;
@@ -373,7 +498,7 @@ const glob = {
373
498
  return { text: `No files match ${pattern}` };
374
499
  where.root = fs.realpathSync(deeper);
375
500
  }
376
- const re = globToRegExp(rest);
501
+ const re = { test: globMatcher(rest) };
377
502
  // A pattern with no folder in it matches at any depth, as people expect of `*.md`.
378
503
  const anyDepth = !pattern.includes("/");
379
504
  const { files, cut } = walk(where.root);
@@ -398,6 +523,63 @@ const glob = {
398
523
  return { text: shown + more };
399
524
  },
400
525
  };
526
+ // The matching half of Grep, run in a worker thread (see GREP_MS). It reads
527
+ // each file itself and skips the large and the binary, as the tool always did.
528
+ const MATCH_WORKER = `
529
+ const { parentPort, workerData: w } = process.getBuiltinModule("node:worker_threads");
530
+ const fs = process.getBuiltinModule("node:fs");
531
+ const re = new RegExp(w.pattern, w.flags);
532
+ const out = [];
533
+ let total = 0;
534
+ for (const full of w.files) {
535
+ let buf;
536
+ try {
537
+ if (fs.statSync(full).size > w.maxBytes) continue;
538
+ buf = fs.readFileSync(full);
539
+ } catch {
540
+ continue;
541
+ }
542
+ if (buf.subarray(0, 8192).includes(0)) continue;
543
+ const lines = buf.toString("utf8").split("\\n");
544
+ let inFile = 0;
545
+ for (let i = 0; i < lines.length; i++) {
546
+ if (!re.test(lines[i])) continue;
547
+ inFile++;
548
+ if (w.mode === "content" && out.length < w.limit) {
549
+ out.push(full + ":" + (i + 1) + ":" + (lines[i].length > 500 ? lines[i].slice(0, 500) + " [… line cut]" : lines[i]));
550
+ }
551
+ }
552
+ if (!inFile) continue;
553
+ total += w.mode === "content" ? inFile : 1;
554
+ if (w.mode === "files_with_matches" && out.length < w.limit) out.push(full);
555
+ if (w.mode === "count" && out.length < w.limit) out.push(full + ":" + inFile);
556
+ }
557
+ parentPort.postMessage({ out, total });
558
+ `;
559
+ /** Run MATCH_WORKER over `job.files`; end it at `ms` or when `signal` fires. */
560
+ export function matchInWorker(job, signal, ms) {
561
+ if (signal.aborted)
562
+ return Promise.resolve({ stopped: true });
563
+ return new Promise((resolve) => {
564
+ let settled = false;
565
+ const worker = new Worker(MATCH_WORKER, { eval: true, workerData: job });
566
+ const finish = (r) => {
567
+ if (settled)
568
+ return;
569
+ settled = true;
570
+ clearTimeout(timer);
571
+ signal.removeEventListener("abort", onAbort);
572
+ void worker.terminate();
573
+ resolve(r);
574
+ };
575
+ const onAbort = () => finish({ stopped: true });
576
+ const timer = setTimeout(() => finish({ timedOut: true }), ms);
577
+ signal.addEventListener("abort", onAbort, { once: true });
578
+ worker.once("message", (m) => finish(m));
579
+ worker.once("error", (err) => finish({ error: err instanceof Error ? err.message : String(err) }));
580
+ worker.once("exit", () => finish({ error: "the search ended without an answer" }));
581
+ });
582
+ }
401
583
  const grep = {
402
584
  name: "Grep",
403
585
  description: "Search file contents with a regular expression. output_mode: `files_with_matches` (default) lists files, " +
@@ -433,47 +615,30 @@ const grep = {
433
615
  const mode = str(input, "output_mode") ?? "files_with_matches";
434
616
  const limit = Math.max(1, Math.min(GREP_RESULTS, Number.isInteger(input.head_limit) ? input.head_limit : GREP_RESULTS));
435
617
  const filter = str(input, "glob");
436
- const filterRe = filter ? globToRegExp(filter.replace(/^\.\//, "")) : null;
618
+ const tooWild = filter ? globProblem(filter) : null;
619
+ if (tooWild)
620
+ return fail(tooWild);
621
+ const filterRe = filter ? { test: globMatcher(filter.replace(/^\.\//, "")) } : null;
437
622
  const filterAnyDepth = filter ? !filter.includes("/") : false;
438
623
  const single = fs.statSync(where.root).isFile();
439
624
  const { files, cut } = single ? { files: [""], cut: false } : walk(where.root);
440
- const out = [];
441
- let total = 0;
625
+ const chosen = [];
442
626
  for (const rel of files.sort()) {
443
627
  const full = single ? where.root : path.join(where.root, rel);
444
628
  // A file named outright is tested by its own name: it has no path
445
629
  // under a search root to match against.
446
630
  if (filterRe && !filterRe.test(single || filterAnyDepth ? path.basename(full) : rel))
447
631
  continue;
448
- let buf;
449
- try {
450
- if (fs.statSync(full).size > SEARCH_FILE_BYTES)
451
- continue;
452
- buf = fs.readFileSync(full);
453
- }
454
- catch {
455
- continue;
456
- }
457
- if (looksBinary(buf))
458
- continue;
459
- const lines = buf.toString("utf8").split("\n");
460
- let inFile = 0;
461
- for (let i = 0; i < lines.length; i++) {
462
- if (!re.test(lines[i]))
463
- continue;
464
- inFile++;
465
- if (mode === "content" && out.length < limit) {
466
- out.push(`${full}:${i + 1}:${lines[i].length > 500 ? `${lines[i].slice(0, 500)} [… line cut]` : lines[i]}`);
467
- }
468
- }
469
- if (!inFile)
470
- continue;
471
- total += mode === "content" ? inFile : 1;
472
- if (mode === "files_with_matches" && out.length < limit)
473
- out.push(full);
474
- if (mode === "count" && out.length < limit)
475
- out.push(`${full}:${inFile}`);
632
+ chosen.push(full);
476
633
  }
634
+ const found = await matchInWorker({ pattern, flags: re.flags, files: chosen, mode, limit, maxBytes: SEARCH_FILE_BYTES }, ctx.signal, GREP_MS);
635
+ if ("stopped" in found)
636
+ return fail("the search was stopped");
637
+ if ("timedOut" in found)
638
+ return fail(`the search ran past ${GREP_MS / 1000} s and was ended: the pattern is too costly for this text. Use a simpler pattern or a narrower path or glob.`);
639
+ if ("error" in found)
640
+ return fail(`the search failed: ${found.error}`);
641
+ const { out, total } = found;
477
642
  if (!out.length)
478
643
  return { text: `No matches for ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
479
644
  const more = total > out.length ? `\n\n[${total - out.length} more not shown — narrow the search or raise head_limit]` : "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "24.5.0",
3
+ "version": "24.7.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -71,6 +71,9 @@ interface Usage {
71
71
  interface LoopOptions {
72
72
  cwd: string;
73
73
  env: Record<string, string | undefined>;
74
+ /** What the tools (Bash) get; `env` when not given. foldrun code passes
75
+ * the person's own environment here, so the model key stays with the loop. */
76
+ shellEnv: Record<string, string | undefined>;
74
77
  model: string;
75
78
  systemPrompt: string;
76
79
  tools: EngineTool[];
@@ -113,12 +116,25 @@ function readOptions(options: Json): LoopOptions {
113
116
  }
114
117
  const model = String(options.model ?? "");
115
118
  if (!model) throw new Error("the foldrun engine needs a model");
119
+ // Tools the host brings, as EngineTool objects: they sit beside the
120
+ // built-in ones and go through canUseTool and the hooks like them.
121
+ // foldrun code's cloud_agents is one. A name may not shadow a built-in.
122
+ const extra: EngineTool[] = [];
123
+ for (const t of Array.isArray(options.extraTools) ? (options.extraTools as unknown[]) : []) {
124
+ const tool = t as Partial<EngineTool> | null;
125
+ if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
126
+ throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
127
+ }
128
+ if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name)) throw new Error(`extraTools: ${tool.name} is already a tool`);
129
+ extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema as Record<string, unknown>, readOnly: tool.readOnly === true, run: tool.run });
130
+ }
116
131
  return {
117
132
  cwd: String(options.cwd ?? process.cwd()),
118
133
  env,
134
+ shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? (options.shellEnv as Record<string, string | undefined>) : env,
119
135
  model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
120
136
  systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
121
- tools: names.map((n) => ENGINE_TOOLS[n]),
137
+ tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
122
138
  maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
123
139
  partial: options.includePartialMessages === true,
124
140
  pre: hookFns(options.hooks, "PreToolUse"),
@@ -364,7 +380,7 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
364
380
  const sessionId = crypto.randomUUID();
365
381
  const startedAt = Date.now();
366
382
  const byName = new Map(o.tools.map((t) => [t.name, t]));
367
- const ctx: ToolContext = { cwd: o.cwd, env: o.env, signal, reads: new Map(), groups: new Set() };
383
+ const ctx: ToolContext = { cwd: o.cwd, env: o.shellEnv, signal, reads: new Map(), groups: new Set() };
368
384
  // An earlier conversation comes first (foldrun code's local turns carry
369
385
  // theirs, 19 Nov 2026); the prompt is always the newest user turn.
370
386
  if (o.history.length % 2 !== 0) throw new Error("history must end with the model's turn, so the prompt is the next user turn");
@@ -23,6 +23,7 @@
23
23
  import fs from "node:fs";
24
24
  import path from "node:path";
25
25
  import { spawn } from "node:child_process";
26
+ import { Worker } from "node:worker_threads";
26
27
 
27
28
  export interface ToolContext {
28
29
  /** Relative paths resolve here: the agent's directory. */
@@ -73,6 +74,11 @@ const SEARCH_FILE_BYTES = 2 * 1024 * 1024;
73
74
  const WALK_FILES = 20_000;
74
75
  const GLOB_RESULTS = 200;
75
76
  const GREP_RESULTS = 250;
77
+ /** How long one Grep may match for. A pattern the model wrote can take
78
+ * exponential time on the wrong text (`(a+)+$`); the matching runs in a
79
+ * worker thread that is ended at this limit or when the step is stopped,
80
+ * so it never freezes the process that runs the loop. */
81
+ export const GREP_MS = 30_000;
76
82
  export const BASH_DEFAULT_MS = 120_000;
77
83
  export const BASH_MAX_MS = 600_000;
78
84
  const KILL_GRACE_MS = 2000;
@@ -314,11 +320,110 @@ export function globToRegExp(glob: string): RegExp {
314
320
  return new RegExp(`^${re}$`);
315
321
  }
316
322
 
323
+ /** The most folders one walk opens: a tree of empty folders is bounded too. */
324
+ const WALK_DIRS = 20_000;
325
+ /** The most alternatives a glob's braces may expand to. */
326
+ export const GLOB_ALTERNATIVES = 64;
327
+
328
+ type GlobToken = { t: "lit"; c: string } | { t: "one" } | { t: "star" } | { t: "any" } | { t: "dirs" };
329
+
330
+ /** `{a,b}` expanded, as globToRegExp reads braces: no nesting, the inside literal. */
331
+ function expandBraces(glob: string): string[] | null {
332
+ const i = glob.indexOf("{");
333
+ if (i < 0) return [glob];
334
+ const end = glob.indexOf("}", i);
335
+ if (end < 0) return [glob];
336
+ const rest = expandBraces(glob.slice(end + 1));
337
+ if (!rest) return null;
338
+ const out: string[] = [];
339
+ for (const alt of glob.slice(i + 1, end).split(",")) {
340
+ for (const r of rest) {
341
+ out.push(`${glob.slice(0, i)}\u0000${alt}\u0000${r}`);
342
+ if (out.length > GLOB_ALTERNATIVES) return null;
343
+ }
344
+ }
345
+ return out;
346
+ }
347
+
348
+ function globTokens(glob: string): GlobToken[] {
349
+ const out: GlobToken[] = [];
350
+ let literal = false;
351
+ for (let i = 0; i < glob.length; i++) {
352
+ const c = glob[i]!;
353
+ // \u0000 brackets a brace's alternative: its characters are literal.
354
+ if (c === "\u0000") {
355
+ literal = !literal;
356
+ continue;
357
+ }
358
+ if (literal) out.push({ t: "lit", c });
359
+ else if (c === "*") {
360
+ if (glob[i + 1] === "*") {
361
+ i++;
362
+ if (glob[i + 1] === "/") {
363
+ i++;
364
+ out.push({ t: "dirs" });
365
+ } else out.push({ t: "any" });
366
+ } else out.push({ t: "star" });
367
+ } else if (c === "?") out.push({ t: "one" });
368
+ else out.push({ t: "lit", c });
369
+ }
370
+ return out;
371
+ }
372
+
373
+ /** Whether `text` matches the tokens: a table over tokens × positions, so
374
+ * the time is bounded by their product whatever the pattern (Codex: a
375
+ * backtracking regular expression is not). */
376
+ function tokensMatch(tokens: GlobToken[], text: string): boolean {
377
+ const n = text.length;
378
+ let cur = new Uint8Array(n + 1);
379
+ cur[0] = 1;
380
+ for (const tok of tokens) {
381
+ const next = new Uint8Array(n + 1);
382
+ if (tok.t === "lit") {
383
+ for (let j = 0; j < n; j++) if (cur[j] && text[j] === tok.c) next[j + 1] = 1;
384
+ } else if (tok.t === "one") {
385
+ for (let j = 0; j < n; j++) if (cur[j] && text[j] !== "/") next[j + 1] = 1;
386
+ } else if (tok.t === "star" || tok.t === "any") {
387
+ for (let j = 0; j <= n; j++) {
388
+ // `**` stops at a line break as the `.*` it was always read as does.
389
+ if (cur[j] || (j > 0 && next[j - 1] && (tok.t === "any" ? !/[\n\r\u2028\u2029]/.test(text[j - 1]!) : text[j - 1] !== "/"))) next[j] = 1;
390
+ }
391
+ } else {
392
+ // Zero or more whole folders: `name/` repeated, each name non-empty.
393
+ for (let j = 0; j <= n; j++) {
394
+ if (cur[j]) next[j] = 1;
395
+ if (!next[j]) continue;
396
+ const slash = text.indexOf("/", j);
397
+ if (slash > j) next[slash + 1] = 1;
398
+ }
399
+ }
400
+ cur = next;
401
+ }
402
+ return cur[n] === 1;
403
+ }
404
+
405
+ /** A glob as a test over a `/`-separated relative path — the same language
406
+ * as globToRegExp, matched in bounded time. Throws when its braces expand
407
+ * past GLOB_ALTERNATIVES. */
408
+ export function globMatcher(glob: string): (text: string) => boolean {
409
+ const alts = expandBraces(glob);
410
+ if (!alts) throw new Error(`the glob's braces make more than ${GLOB_ALTERNATIVES} patterns — name fewer`);
411
+ const compiled = alts.map(globTokens);
412
+ return (text) => compiled.some((t) => tokensMatch(t, text));
413
+ }
414
+
415
+ /** Why a glob is refused, or null. */
416
+ export function globProblem(glob: string): string | null {
417
+ return expandBraces(glob) ? null : `the glob's braces make more than ${GLOB_ALTERNATIVES} patterns — name fewer`;
418
+ }
419
+
317
420
  /** Every file under `root`, as paths relative to it. Bounded. */
318
421
  function walk(root: string): { files: string[]; cut: boolean } {
319
422
  const files: string[] = [];
320
423
  const stack = [""];
424
+ let dirs = 0;
321
425
  while (stack.length) {
426
+ if (++dirs > WALK_DIRS) return { files, cut: true };
322
427
  const rel = stack.pop()!;
323
428
  let entries: fs.Dirent[];
324
429
  try {
@@ -363,6 +468,8 @@ const glob: EngineTool = {
363
468
  async run(input, ctx) {
364
469
  const pattern = str(input, "pattern");
365
470
  if (!pattern) return fail("Glob needs pattern");
471
+ const tooWild = globProblem(pattern);
472
+ if (tooWild) return fail(tooWild);
366
473
  const where = searchRoot(input, ctx);
367
474
  if ("text" in where) return where;
368
475
  // The folders a pattern names before its first wildcard are where to
@@ -378,7 +485,7 @@ const glob: EngineTool = {
378
485
  if (!fs.existsSync(deeper)) return { text: `No files match ${pattern}` };
379
486
  where.root = fs.realpathSync(deeper);
380
487
  }
381
- const re = globToRegExp(rest);
488
+ const re = { test: globMatcher(rest) };
382
489
  // A pattern with no folder in it matches at any depth, as people expect of `*.md`.
383
490
  const anyDepth = !pattern.includes("/");
384
491
  const { files, cut } = walk(where.root);
@@ -402,6 +509,66 @@ const glob: EngineTool = {
402
509
  },
403
510
  };
404
511
 
512
+ // The matching half of Grep, run in a worker thread (see GREP_MS). It reads
513
+ // each file itself and skips the large and the binary, as the tool always did.
514
+ const MATCH_WORKER = `
515
+ const { parentPort, workerData: w } = process.getBuiltinModule("node:worker_threads");
516
+ const fs = process.getBuiltinModule("node:fs");
517
+ const re = new RegExp(w.pattern, w.flags);
518
+ const out = [];
519
+ let total = 0;
520
+ for (const full of w.files) {
521
+ let buf;
522
+ try {
523
+ if (fs.statSync(full).size > w.maxBytes) continue;
524
+ buf = fs.readFileSync(full);
525
+ } catch {
526
+ continue;
527
+ }
528
+ if (buf.subarray(0, 8192).includes(0)) continue;
529
+ const lines = buf.toString("utf8").split("\\n");
530
+ let inFile = 0;
531
+ for (let i = 0; i < lines.length; i++) {
532
+ if (!re.test(lines[i])) continue;
533
+ inFile++;
534
+ if (w.mode === "content" && out.length < w.limit) {
535
+ out.push(full + ":" + (i + 1) + ":" + (lines[i].length > 500 ? lines[i].slice(0, 500) + " [… line cut]" : lines[i]));
536
+ }
537
+ }
538
+ if (!inFile) continue;
539
+ total += w.mode === "content" ? inFile : 1;
540
+ if (w.mode === "files_with_matches" && out.length < w.limit) out.push(full);
541
+ if (w.mode === "count" && out.length < w.limit) out.push(full + ":" + inFile);
542
+ }
543
+ parentPort.postMessage({ out, total });
544
+ `;
545
+
546
+ type MatchJob = { pattern: string; flags: string; files: string[]; mode: string; limit: number; maxBytes: number };
547
+ type MatchResult = { out: string[]; total: number } | { timedOut: true } | { stopped: true } | { error: string };
548
+
549
+ /** Run MATCH_WORKER over `job.files`; end it at `ms` or when `signal` fires. */
550
+ export function matchInWorker(job: MatchJob, signal: AbortSignal, ms: number): Promise<MatchResult> {
551
+ if (signal.aborted) return Promise.resolve({ stopped: true });
552
+ return new Promise((resolve) => {
553
+ let settled = false;
554
+ const worker = new Worker(MATCH_WORKER, { eval: true, workerData: job });
555
+ const finish = (r: MatchResult) => {
556
+ if (settled) return;
557
+ settled = true;
558
+ clearTimeout(timer);
559
+ signal.removeEventListener("abort", onAbort);
560
+ void worker.terminate();
561
+ resolve(r);
562
+ };
563
+ const onAbort = () => finish({ stopped: true });
564
+ const timer = setTimeout(() => finish({ timedOut: true }), ms);
565
+ signal.addEventListener("abort", onAbort, { once: true });
566
+ worker.once("message", (m: { out: string[]; total: number }) => finish(m));
567
+ worker.once("error", (err: unknown) => finish({ error: err instanceof Error ? err.message : String(err) }));
568
+ worker.once("exit", () => finish({ error: "the search ended without an answer" }));
569
+ });
570
+ }
571
+
405
572
  const grep: EngineTool = {
406
573
  name: "Grep",
407
574
  description:
@@ -435,39 +602,30 @@ const grep: EngineTool = {
435
602
  const mode = str(input, "output_mode") ?? "files_with_matches";
436
603
  const limit = Math.max(1, Math.min(GREP_RESULTS, Number.isInteger(input.head_limit) ? (input.head_limit as number) : GREP_RESULTS));
437
604
  const filter = str(input, "glob");
438
- const filterRe = filter ? globToRegExp(filter.replace(/^\.\//, "")) : null;
605
+ const tooWild = filter ? globProblem(filter) : null;
606
+ if (tooWild) return fail(tooWild);
607
+ const filterRe = filter ? { test: globMatcher(filter.replace(/^\.\//, "")) } : null;
439
608
  const filterAnyDepth = filter ? !filter.includes("/") : false;
440
609
  const single = fs.statSync(where.root).isFile();
441
610
  const { files, cut } = single ? { files: [""], cut: false } : walk(where.root);
442
- const out: string[] = [];
443
- let total = 0;
611
+ const chosen: string[] = [];
444
612
  for (const rel of files.sort()) {
445
613
  const full = single ? where.root : path.join(where.root, rel);
446
614
  // A file named outright is tested by its own name: it has no path
447
615
  // under a search root to match against.
448
616
  if (filterRe && !filterRe.test(single || filterAnyDepth ? path.basename(full) : rel)) continue;
449
- let buf: Buffer;
450
- try {
451
- if (fs.statSync(full).size > SEARCH_FILE_BYTES) continue;
452
- buf = fs.readFileSync(full);
453
- } catch {
454
- continue;
455
- }
456
- if (looksBinary(buf)) continue;
457
- const lines = buf.toString("utf8").split("\n");
458
- let inFile = 0;
459
- for (let i = 0; i < lines.length; i++) {
460
- if (!re.test(lines[i])) continue;
461
- inFile++;
462
- if (mode === "content" && out.length < limit) {
463
- out.push(`${full}:${i + 1}:${lines[i].length > 500 ? `${lines[i].slice(0, 500)} [… line cut]` : lines[i]}`);
464
- }
465
- }
466
- if (!inFile) continue;
467
- total += mode === "content" ? inFile : 1;
468
- if (mode === "files_with_matches" && out.length < limit) out.push(full);
469
- if (mode === "count" && out.length < limit) out.push(`${full}:${inFile}`);
617
+ chosen.push(full);
470
618
  }
619
+ const found = await matchInWorker(
620
+ { pattern, flags: re.flags, files: chosen, mode, limit, maxBytes: SEARCH_FILE_BYTES },
621
+ ctx.signal,
622
+ GREP_MS,
623
+ );
624
+ if ("stopped" in found) return fail("the search was stopped");
625
+ if ("timedOut" in found)
626
+ return fail(`the search ran past ${GREP_MS / 1000} s and was ended: the pattern is too costly for this text. Use a simpler pattern or a narrower path or glob.`);
627
+ if ("error" in found) return fail(`the search failed: ${found.error}`);
628
+ const { out, total } = found;
471
629
  if (!out.length) return { text: `No matches for ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
472
630
  const more = total > out.length ? `\n\n[${total - out.length} more not shown — narrow the search or raise head_limit]` : "";
473
631
  return { text: capped(out.join("\n")) + more };