@foldrun/core 24.2.2 → 24.3.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 (64) hide show
  1. package/dist/src/account.js +2 -2
  2. package/dist/src/agent-import.js +2 -2
  3. package/dist/src/budget.js +1 -1
  4. package/dist/src/copy-back.js +2 -2
  5. package/dist/src/data-import.js +9 -9
  6. package/dist/src/deploy.js +2 -2
  7. package/dist/src/engine-loop.d.ts +45 -0
  8. package/dist/src/engine-loop.js +480 -0
  9. package/dist/src/engine-tools.d.ts +41 -0
  10. package/dist/src/engine-tools.js +579 -0
  11. package/dist/src/evals.js +1 -1
  12. package/dist/src/failure.js +1 -1
  13. package/dist/src/flow-lint.js +8 -8
  14. package/dist/src/frontmatter-fields.js +8 -8
  15. package/dist/src/mail.js +1 -1
  16. package/dist/src/manifest.js +1 -1
  17. package/dist/src/notify.js +2 -2
  18. package/dist/src/oauth-capabilities.js +1 -1
  19. package/dist/src/openapi.js +3 -3
  20. package/dist/src/package.js +2 -2
  21. package/dist/src/providers.js +2 -2
  22. package/dist/src/publish.js +2 -2
  23. package/dist/src/run-container.js +3 -3
  24. package/dist/src/scan.js +7 -7
  25. package/dist/src/secrets.js +7 -7
  26. package/dist/src/starter.js +18 -18
  27. package/dist/src/step-exec.d.ts +12 -1
  28. package/dist/src/step-exec.js +6 -2
  29. package/dist/src/storage.js +6 -6
  30. package/dist/src/store.js +16 -16
  31. package/dist/src/tool-test.js +1 -1
  32. package/dist/src/webhook.js +1 -1
  33. package/dist/src/workspace-revisions.js +2 -2
  34. package/package.json +1 -1
  35. package/src/account.ts +2 -2
  36. package/src/agent-import.ts +2 -2
  37. package/src/budget.ts +1 -1
  38. package/src/copy-back.ts +2 -2
  39. package/src/data-import.ts +9 -9
  40. package/src/deploy.ts +2 -2
  41. package/src/engine-loop.ts +495 -0
  42. package/src/engine-tools.ts +566 -0
  43. package/src/evals.ts +1 -1
  44. package/src/failure.ts +1 -1
  45. package/src/flow-lint.ts +8 -8
  46. package/src/frontmatter-fields.ts +8 -8
  47. package/src/mail.ts +1 -1
  48. package/src/manifest.ts +1 -1
  49. package/src/notify.ts +2 -2
  50. package/src/oauth-capabilities.ts +1 -1
  51. package/src/openapi.ts +3 -3
  52. package/src/package.ts +2 -2
  53. package/src/providers.ts +2 -2
  54. package/src/publish.ts +2 -2
  55. package/src/run-container.ts +3 -3
  56. package/src/scan.ts +7 -7
  57. package/src/secrets.ts +7 -7
  58. package/src/starter.ts +19 -19
  59. package/src/step-exec.ts +14 -2
  60. package/src/storage.ts +6 -6
  61. package/src/store.ts +16 -16
  62. package/src/tool-test.ts +1 -1
  63. package/src/webhook.ts +1 -1
  64. package/src/workspace-revisions.ts +2 -2
@@ -0,0 +1,566 @@
1
+ // The foldrun engine's own file and shell tools (engine-loop.ts).
2
+ //
3
+ // Six tools under the names every hook, `limits:` key, `disallowedTools:`
4
+ // entry and run record already matches on: Read, Write, Edit, Glob, Grep,
5
+ // Bash. The inputs keep the field names confine.ts checks (`file_path`,
6
+ // `path`, `pattern`, `glob`, `command`), so a call is confined by the same
7
+ // code whichever engine runs it.
8
+ //
9
+ // What these tools promise, because a model cannot see what it broke:
10
+ //
11
+ // - Edit and Write never touch a file the model has not read in this
12
+ // session, nor one that changed on disk since it read it. The refusal says
13
+ // which, and the model reads again.
14
+ // - Edit replaces exact text. No match, or more than one without
15
+ // `replace_all`, is a refusal that names the count — never a guess.
16
+ // - A write lands whole or not at all: a temporary file beside the target,
17
+ // then a rename.
18
+ // - Every result is bounded, and says so when it was cut.
19
+ //
20
+ // Nothing here decides whether a call is allowed. That is the loop's job,
21
+ // before the tool runs (the PreToolUse hook and canUseTool from step-exec).
22
+
23
+ import fs from "node:fs";
24
+ import path from "node:path";
25
+ import { spawn } from "node:child_process";
26
+
27
+ export interface ToolContext {
28
+ /** Relative paths resolve here: the agent's directory. */
29
+ cwd: string;
30
+ /** The step's environment — what a shell command runs with. */
31
+ env: Record<string, string | undefined>;
32
+ /** Fires when the step is stopped: a running command is killed. */
33
+ signal: AbortSignal;
34
+ /** Files read in this session → their mtime when read. */
35
+ reads: Map<string, number>;
36
+ /** The process groups this session's commands started. A command that
37
+ * left something in the background has returned, but what it left is
38
+ * still the step's: the loop ends every group when the step ends. */
39
+ groups: Set<number>;
40
+ }
41
+
42
+ /** End everything the session's commands started and left running. */
43
+ export function killGroups(ctx: ToolContext): void {
44
+ for (const pgid of ctx.groups) {
45
+ try {
46
+ process.kill(-pgid, "SIGKILL");
47
+ } catch {
48
+ // the group is already gone
49
+ }
50
+ }
51
+ ctx.groups.clear();
52
+ }
53
+
54
+ export interface ToolOutcome {
55
+ text: string;
56
+ isError?: boolean;
57
+ }
58
+
59
+ export interface EngineTool {
60
+ name: string;
61
+ description: string;
62
+ input_schema: Record<string, unknown>;
63
+ /** Changes nothing: several in one turn may run side by side. */
64
+ readOnly: boolean;
65
+ run: (input: Record<string, unknown>, ctx: ToolContext) => Promise<ToolOutcome>;
66
+ }
67
+
68
+ /** The most one tool result puts into the conversation, in characters. */
69
+ export const RESULT_CAP = 30_000;
70
+ const READ_LINES = 2000;
71
+ const READ_LINE_CHARS = 2000;
72
+ const SEARCH_FILE_BYTES = 2 * 1024 * 1024;
73
+ const WALK_FILES = 20_000;
74
+ const GLOB_RESULTS = 200;
75
+ const GREP_RESULTS = 250;
76
+ export const BASH_DEFAULT_MS = 120_000;
77
+ export const BASH_MAX_MS = 600_000;
78
+ const KILL_GRACE_MS = 2000;
79
+ /** Never searched: version control and installed dependencies. */
80
+ const SKIP_DIRS = new Set([".git", "node_modules"]);
81
+
82
+ const fail = (text: string): ToolOutcome => ({ text, isError: true });
83
+
84
+ /** Head and tail of a long text, with the cut said in the middle. */
85
+ export function capped(text: string, cap = RESULT_CAP): string {
86
+ if (text.length <= cap) return text;
87
+ const head = Math.floor(cap * 0.6);
88
+ const tail = cap - head;
89
+ return `${text.slice(0, head)}\n\n[… ${text.length - cap} characters cut …]\n\n${text.slice(text.length - tail)}`;
90
+ }
91
+
92
+ function str(input: Record<string, unknown>, key: string): string | null {
93
+ const v = input[key];
94
+ return typeof v === "string" ? v : null;
95
+ }
96
+
97
+ /** The file a path names, with links followed: what is read, checked for
98
+ * staleness and replaced is then one and the same file. A rename over the
99
+ * path as given would replace a link with a copy and leave its target as
100
+ * it was. For a file that does not exist yet, its folder is resolved. */
101
+ function abs(ctx: ToolContext, p: string): string {
102
+ const given = path.resolve(ctx.cwd, p);
103
+ try {
104
+ return fs.realpathSync(given);
105
+ } catch {
106
+ try {
107
+ return path.join(fs.realpathSync(path.dirname(given)), path.basename(given));
108
+ } catch {
109
+ return given;
110
+ }
111
+ }
112
+ }
113
+
114
+ function looksBinary(buf: Buffer): boolean {
115
+ return buf.subarray(0, 8192).includes(0);
116
+ }
117
+
118
+ function writeWhole(file: string, content: string): void {
119
+ fs.mkdirSync(path.dirname(file), { recursive: true });
120
+ let mode: number | undefined;
121
+ try {
122
+ mode = fs.statSync(file).mode;
123
+ } catch {
124
+ // a new file takes the default mode
125
+ }
126
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
127
+ try {
128
+ fs.writeFileSync(tmp, content, mode !== undefined ? { mode } : undefined);
129
+ fs.renameSync(tmp, file);
130
+ } catch (err) {
131
+ fs.rmSync(tmp, { force: true });
132
+ throw err;
133
+ }
134
+ }
135
+
136
+ /** Why an existing file may not be written yet, or null when it may. */
137
+ function staleReason(ctx: ToolContext, file: string): string | null {
138
+ let mtime: number;
139
+ try {
140
+ mtime = fs.statSync(file).mtimeMs;
141
+ } catch {
142
+ return null; // no such file: nothing to be stale against
143
+ }
144
+ const seen = ctx.reads.get(file);
145
+ if (seen === undefined) return `${file} exists and has not been read in this session — Read it first, then change it`;
146
+ if (seen !== mtime) return `${file} changed on disk since it was read — Read it again, then change it`;
147
+ return null;
148
+ }
149
+
150
+ const read: EngineTool = {
151
+ name: "Read",
152
+ description:
153
+ "Read a text file. Returns its lines numbered as `<line>\\t<text>`. " +
154
+ `At most ${READ_LINES} lines per call: pass offset (first line, from 1) and limit for the rest of a long file. ` +
155
+ "A file must be read before Edit or Write may change it.",
156
+ input_schema: {
157
+ type: "object",
158
+ properties: {
159
+ file_path: { type: "string", description: "The file, absolute or relative to the working directory" },
160
+ offset: { type: "integer", description: "The first line to return, from 1" },
161
+ limit: { type: "integer", description: "How many lines to return" },
162
+ },
163
+ required: ["file_path"],
164
+ },
165
+ readOnly: true,
166
+ async run(input, ctx) {
167
+ const given = str(input, "file_path");
168
+ if (!given) return fail("Read needs file_path");
169
+ const file = abs(ctx, given);
170
+ let stat: fs.Stats;
171
+ try {
172
+ stat = fs.statSync(file);
173
+ } catch {
174
+ return fail(`${file} does not exist`);
175
+ }
176
+ if (stat.isDirectory()) return fail(`${file} is a directory — use Glob to list files`);
177
+ const buf = fs.readFileSync(file);
178
+ if (looksBinary(buf)) return fail(`${file} is not a text file`);
179
+ ctx.reads.set(file, stat.mtimeMs);
180
+ const text = buf.toString("utf8");
181
+ if (!text.length) return { text: "(the file is empty)" };
182
+ const lines = text.split("\n");
183
+ if (lines[lines.length - 1] === "") lines.pop();
184
+ const offset = Math.max(1, Number.isInteger(input.offset) ? (input.offset as number) : 1);
185
+ const limit = Math.max(1, Math.min(READ_LINES, Number.isInteger(input.limit) ? (input.limit as number) : READ_LINES));
186
+ if (offset > lines.length) return fail(`${file} has ${lines.length} lines; offset ${offset} is past the end`);
187
+ const slice = lines.slice(offset - 1, offset - 1 + limit);
188
+ const body = slice
189
+ .map((l, i) => `${offset + i}\t${l.length > READ_LINE_CHARS ? `${l.slice(0, READ_LINE_CHARS)} [… line cut]` : l}`)
190
+ .join("\n");
191
+ const last = offset - 1 + slice.length;
192
+ const more = last < lines.length ? `\n\n[lines ${offset}–${last} of ${lines.length}; pass offset: ${last + 1} for more]` : "";
193
+ return { text: capped(body) + more };
194
+ },
195
+ };
196
+
197
+ const write: EngineTool = {
198
+ name: "Write",
199
+ description:
200
+ "Write a whole file, creating it and its folders if needed. Replaces what is there: an existing file must have been Read first. " +
201
+ "To change part of a file, use Edit.",
202
+ input_schema: {
203
+ type: "object",
204
+ properties: {
205
+ file_path: { type: "string", description: "The file, absolute or relative to the working directory" },
206
+ content: { type: "string", description: "The file's whole new content" },
207
+ },
208
+ required: ["file_path", "content"],
209
+ },
210
+ readOnly: false,
211
+ async run(input, ctx) {
212
+ const given = str(input, "file_path");
213
+ const content = str(input, "content");
214
+ if (!given || content === null) return fail("Write needs file_path and content");
215
+ const file = abs(ctx, given);
216
+ try {
217
+ if (fs.statSync(file).isDirectory()) return fail(`${file} is a directory`);
218
+ } catch {
219
+ // new file
220
+ }
221
+ const stale = staleReason(ctx, file);
222
+ if (stale) return fail(stale);
223
+ const existed = fs.existsSync(file);
224
+ writeWhole(file, content);
225
+ ctx.reads.set(file, fs.statSync(file).mtimeMs);
226
+ return { text: `${existed ? "Wrote" : "Created"} ${file} (${content.length} characters)` };
227
+ },
228
+ };
229
+
230
+ /** How many times `needle` occurs in `hay`, without overlap. */
231
+ export function occurrences(hay: string, needle: string): number {
232
+ if (!needle) return 0;
233
+ let n = 0;
234
+ for (let at = hay.indexOf(needle); at >= 0; at = hay.indexOf(needle, at + needle.length)) n++;
235
+ return n;
236
+ }
237
+
238
+ const edit: EngineTool = {
239
+ name: "Edit",
240
+ description:
241
+ "Replace exact text in a file that has been Read. old_string must match the file character for character, " +
242
+ "whitespace and line breaks included, and must occur exactly once — add surrounding lines to make it unique, " +
243
+ "or pass replace_all to change every occurrence. Nothing is changed when it does not match.",
244
+ input_schema: {
245
+ type: "object",
246
+ properties: {
247
+ file_path: { type: "string", description: "The file, absolute or relative to the working directory" },
248
+ old_string: { type: "string", description: "The exact text to replace" },
249
+ new_string: { type: "string", description: "What replaces it" },
250
+ replace_all: { type: "boolean", description: "Replace every occurrence (default false)" },
251
+ },
252
+ required: ["file_path", "old_string", "new_string"],
253
+ },
254
+ readOnly: false,
255
+ async run(input, ctx) {
256
+ const given = str(input, "file_path");
257
+ const from = str(input, "old_string");
258
+ const to = str(input, "new_string");
259
+ if (!given || from === null || to === null) return fail("Edit needs file_path, old_string and new_string");
260
+ const file = abs(ctx, given);
261
+ if (!fs.existsSync(file)) return fail(`${file} does not exist — use Write to create it`);
262
+ if (fs.statSync(file).isDirectory()) return fail(`${file} is a directory`);
263
+ const stale = staleReason(ctx, file);
264
+ if (stale) return fail(stale);
265
+ if (!from) return fail("old_string is empty — give the exact text to replace, or use Write for a whole file");
266
+ if (from === to) return fail("old_string and new_string are the same — nothing to change");
267
+ const buf = fs.readFileSync(file);
268
+ if (looksBinary(buf)) return fail(`${file} is not a text file`);
269
+ const before = buf.toString("utf8");
270
+ const count = occurrences(before, from);
271
+ if (count === 0) {
272
+ const hint = before.includes("\r\n") && !from.includes("\r\n") && occurrences(before.replace(/\r\n/g, "\n"), from) > 0
273
+ ? " The file uses CRLF line endings and old_string uses LF."
274
+ : "";
275
+ return fail(`old_string was not found in ${file} — nothing was changed.${hint} Read the file and copy the text exactly.`);
276
+ }
277
+ const all = input.replace_all === true;
278
+ if (count > 1 && !all) {
279
+ return fail(`old_string occurs ${count} times in ${file} — nothing was changed. Add surrounding lines so it matches once, or pass replace_all: true.`);
280
+ }
281
+ // split/join and slice, never String.replace: `$&` in new_string is text.
282
+ const at = before.indexOf(from);
283
+ const after = all ? before.split(from).join(to) : before.slice(0, at) + to + before.slice(at + from.length);
284
+ writeWhole(file, after);
285
+ ctx.reads.set(file, fs.statSync(file).mtimeMs);
286
+ return { text: `Edited ${file} (${all ? count : 1} replacement${(all ? count : 1) === 1 ? "" : "s"})` };
287
+ },
288
+ };
289
+
290
+ /** A glob as a regular expression over a `/`-separated relative path:
291
+ * `**` any folders, `*` within one name, `?` one character, `{a,b}`. */
292
+ export function globToRegExp(glob: string): RegExp {
293
+ let re = "";
294
+ for (let i = 0; i < glob.length; i++) {
295
+ const c = glob[i];
296
+ if (c === "*") {
297
+ if (glob[i + 1] === "*") {
298
+ i++;
299
+ if (glob[i + 1] === "/") {
300
+ i++;
301
+ re += "(?:[^/]+/)*";
302
+ } else re += ".*";
303
+ } else re += "[^/]*";
304
+ } else if (c === "?") re += "[^/]";
305
+ else if (c === "{") {
306
+ const end = glob.indexOf("}", i);
307
+ if (end < 0) re += "\\{";
308
+ else {
309
+ re += `(?:${glob.slice(i + 1, end).split(",").map((s) => s.replace(/[.+^$()|[\]\\*?]/g, "\\$&")).join("|")})`;
310
+ i = end;
311
+ }
312
+ } else re += /[.+^$()|[\]\\}]/.test(c) ? `\\${c}` : c;
313
+ }
314
+ return new RegExp(`^${re}$`);
315
+ }
316
+
317
+ /** Every file under `root`, as paths relative to it. Bounded. */
318
+ function walk(root: string): { files: string[]; cut: boolean } {
319
+ const files: string[] = [];
320
+ const stack = [""];
321
+ while (stack.length) {
322
+ const rel = stack.pop()!;
323
+ let entries: fs.Dirent[];
324
+ try {
325
+ entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true });
326
+ } catch {
327
+ continue;
328
+ }
329
+ for (const e of entries) {
330
+ const child = rel ? `${rel}/${e.name}` : e.name;
331
+ if (e.isDirectory()) {
332
+ if (!SKIP_DIRS.has(e.name)) stack.push(child);
333
+ } else if (e.isFile()) {
334
+ files.push(child);
335
+ if (files.length >= WALK_FILES) return { files, cut: true };
336
+ }
337
+ }
338
+ }
339
+ return { files, cut: false };
340
+ }
341
+
342
+ function searchRoot(input: Record<string, unknown>, ctx: ToolContext): { root: string } | ToolOutcome {
343
+ const given = str(input, "path");
344
+ const root = given ? abs(ctx, given) : ctx.cwd;
345
+ if (!fs.existsSync(root)) return fail(`${root} does not exist`);
346
+ return { root: fs.realpathSync(root) };
347
+ }
348
+
349
+ const glob: EngineTool = {
350
+ name: "Glob",
351
+ description:
352
+ "Find files by name pattern, such as `**/*.ts` or `src/**/*.test.js`. Returns matching paths, newest first. " +
353
+ "Skips .git and node_modules.",
354
+ input_schema: {
355
+ type: "object",
356
+ properties: {
357
+ pattern: { type: "string", description: "The glob, relative to path" },
358
+ path: { type: "string", description: "The folder to search; the working directory when absent" },
359
+ },
360
+ required: ["pattern"],
361
+ },
362
+ readOnly: true,
363
+ async run(input, ctx) {
364
+ const pattern = str(input, "pattern");
365
+ if (!pattern) return fail("Glob needs pattern");
366
+ const where = searchRoot(input, ctx);
367
+ if ("text" in where) return where;
368
+ // The folders a pattern names before its first wildcard are where to
369
+ // look, not something to match: `workspace/storage/*.md` searches
370
+ // workspace/storage. The walk follows no links, and `workspace` is one
371
+ // (confine.ts#linkWorkspace), so the root is resolved through it here.
372
+ const segs = pattern.replace(/^\.\//, "").split("/");
373
+ const wild = segs.findIndex((seg) => /[*?{]/.test(seg));
374
+ const fixed = wild < 0 ? segs.slice(0, -1) : segs.slice(0, wild);
375
+ const rest = segs.slice(fixed.length).join("/");
376
+ if (fixed.length) {
377
+ const deeper = path.join(where.root, ...fixed);
378
+ if (!fs.existsSync(deeper)) return { text: `No files match ${pattern}` };
379
+ where.root = fs.realpathSync(deeper);
380
+ }
381
+ const re = globToRegExp(rest);
382
+ // A pattern with no folder in it matches at any depth, as people expect of `*.md`.
383
+ const anyDepth = !pattern.includes("/");
384
+ const { files, cut } = walk(where.root);
385
+ const hits = files
386
+ .filter((f) => re.test(anyDepth ? path.posix.basename(f) : f))
387
+ .map((f) => {
388
+ const full = path.join(where.root, f);
389
+ let m = 0;
390
+ try {
391
+ m = fs.statSync(full).mtimeMs;
392
+ } catch {
393
+ // gone since the walk
394
+ }
395
+ return { full, m };
396
+ })
397
+ .sort((a, b) => b.m - a.m);
398
+ if (!hits.length) return { text: `No files match ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
399
+ const shown = hits.slice(0, GLOB_RESULTS).map((h) => h.full).join("\n");
400
+ const more = hits.length > GLOB_RESULTS ? `\n\n[${hits.length - GLOB_RESULTS} more not shown — narrow the pattern]` : "";
401
+ return { text: shown + more };
402
+ },
403
+ };
404
+
405
+ const grep: EngineTool = {
406
+ name: "Grep",
407
+ description:
408
+ "Search file contents with a regular expression. output_mode: `files_with_matches` (default) lists files, " +
409
+ "`content` shows matching lines as `path:line:text`, `count` gives matches per file. " +
410
+ "`glob` limits which files are searched. Skips .git, node_modules and binary files.",
411
+ input_schema: {
412
+ type: "object",
413
+ properties: {
414
+ pattern: { type: "string", description: "The regular expression (JavaScript syntax)" },
415
+ path: { type: "string", description: "The file or folder to search; the working directory when absent" },
416
+ glob: { type: "string", description: "Only files matching this glob, such as `*.ts`" },
417
+ output_mode: { type: "string", enum: ["files_with_matches", "content", "count"] },
418
+ "-i": { type: "boolean", description: "Ignore case" },
419
+ head_limit: { type: "integer", description: "The most results to return" },
420
+ },
421
+ required: ["pattern"],
422
+ },
423
+ readOnly: true,
424
+ async run(input, ctx) {
425
+ const pattern = str(input, "pattern");
426
+ if (!pattern) return fail("Grep needs pattern");
427
+ let re: RegExp;
428
+ try {
429
+ re = new RegExp(pattern, input["-i"] === true ? "i" : "");
430
+ } catch (err) {
431
+ return fail(`pattern is not a valid regular expression: ${(err as Error).message}`);
432
+ }
433
+ const where = searchRoot(input, ctx);
434
+ if ("text" in where) return where;
435
+ const mode = str(input, "output_mode") ?? "files_with_matches";
436
+ const limit = Math.max(1, Math.min(GREP_RESULTS, Number.isInteger(input.head_limit) ? (input.head_limit as number) : GREP_RESULTS));
437
+ const filter = str(input, "glob");
438
+ const filterRe = filter ? globToRegExp(filter.replace(/^\.\//, "")) : null;
439
+ const filterAnyDepth = filter ? !filter.includes("/") : false;
440
+ const single = fs.statSync(where.root).isFile();
441
+ const { files, cut } = single ? { files: [""], cut: false } : walk(where.root);
442
+ const out: string[] = [];
443
+ let total = 0;
444
+ for (const rel of files.sort()) {
445
+ const full = single ? where.root : path.join(where.root, rel);
446
+ // A file named outright is tested by its own name: it has no path
447
+ // under a search root to match against.
448
+ 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}`);
470
+ }
471
+ if (!out.length) return { text: `No matches for ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
472
+ const more = total > out.length ? `\n\n[${total - out.length} more not shown — narrow the search or raise head_limit]` : "";
473
+ return { text: capped(out.join("\n")) + more };
474
+ },
475
+ };
476
+
477
+ const bash: EngineTool = {
478
+ name: "Bash",
479
+ description:
480
+ "Run a shell command in the working directory and return its output (stdout and stderr together) and exit code. " +
481
+ `Stops after timeout milliseconds (default ${BASH_DEFAULT_MS}, at most ${BASH_MAX_MS}). ` +
482
+ "Each call is a new shell: a `cd` or a variable does not carry to the next. Use Read, Edit, Glob and Grep for files rather than cat, sed, find and grep.",
483
+ input_schema: {
484
+ type: "object",
485
+ properties: {
486
+ command: { type: "string", description: "The command line" },
487
+ timeout: { type: "integer", description: "Milliseconds before the command is stopped" },
488
+ description: { type: "string", description: "What the command does, in a few words" },
489
+ },
490
+ required: ["command"],
491
+ },
492
+ readOnly: false,
493
+ run(input, ctx) {
494
+ const command = str(input, "command");
495
+ if (!command) return Promise.resolve(fail("Bash needs command"));
496
+ const ms = Math.max(1000, Math.min(BASH_MAX_MS, Number.isInteger(input.timeout) ? (input.timeout as number) : BASH_DEFAULT_MS));
497
+ return new Promise<ToolOutcome>((resolve) => {
498
+ if (ctx.signal.aborted) return resolve(fail("the step was stopped before the command ran"));
499
+ // Its own process group, so a stop or a timeout ends what it started
500
+ // too — a test runner's children, a server it left in the background.
501
+ const child = spawn("bash", ["-c", command], {
502
+ cwd: ctx.cwd,
503
+ env: ctx.env as NodeJS.ProcessEnv,
504
+ detached: true,
505
+ stdio: ["ignore", "pipe", "pipe"],
506
+ });
507
+ if (child.pid) ctx.groups.add(child.pid);
508
+ let out = "";
509
+ let dropped = 0;
510
+ const take = (chunk: Buffer) => {
511
+ const s = chunk.toString("utf8");
512
+ // Keep a bounded window while it runs: a command that prints forever
513
+ // must not grow the step's memory.
514
+ out += s;
515
+ if (out.length > RESULT_CAP * 4) {
516
+ const keepHead = RESULT_CAP;
517
+ const keepTail = RESULT_CAP * 2;
518
+ dropped += out.length - keepHead - keepTail;
519
+ out = out.slice(0, keepHead) + out.slice(out.length - keepTail);
520
+ }
521
+ };
522
+ child.stdout!.on("data", take);
523
+ child.stderr!.on("data", take);
524
+ let why: "timeout" | "stopped" | null = null;
525
+ const killGroup = (signal: NodeJS.Signals) => {
526
+ try {
527
+ if (child.pid) process.kill(-child.pid, signal);
528
+ } catch {
529
+ // already gone
530
+ }
531
+ };
532
+ const end = (reason: "timeout" | "stopped") => {
533
+ if (why) return;
534
+ why = reason;
535
+ killGroup("SIGTERM");
536
+ setTimeout(() => killGroup("SIGKILL"), KILL_GRACE_MS).unref();
537
+ };
538
+ const timer = setTimeout(() => end("timeout"), ms);
539
+ const onAbort = () => end("stopped");
540
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
541
+ const done = (text: string, isError: boolean) => {
542
+ clearTimeout(timer);
543
+ ctx.signal.removeEventListener("abort", onAbort);
544
+ resolve({ text, ...(isError ? { isError: true } : {}) });
545
+ };
546
+ child.on("error", (err) => done(`the command could not start: ${err.message}`, true));
547
+ child.on("close", (code, signal) => {
548
+ const body = capped(out.trimEnd()) + (dropped ? `\n[${dropped} characters of output dropped while it ran]` : "");
549
+ if (why === "timeout") return done(`${body}\n[stopped after ${ms} ms — the command did not finish]`.trim(), true);
550
+ if (why === "stopped") return done(`${body}\n[stopped with the step]`.trim(), true);
551
+ if (code === 0) return done(body || "(no output)", false);
552
+ done(`${body}\n[exit code ${code ?? `none, signal ${signal}`}]`.trim(), true);
553
+ });
554
+ });
555
+ },
556
+ };
557
+
558
+ /** The engine's built-in tools, by the name the model and core both use. */
559
+ export const ENGINE_TOOLS: Readonly<Record<string, EngineTool>> = {
560
+ Read: read,
561
+ Write: write,
562
+ Edit: edit,
563
+ Glob: glob,
564
+ Grep: grep,
565
+ Bash: bash,
566
+ };
package/src/evals.ts CHANGED
@@ -631,7 +631,7 @@ export const JUDGE_TIMEOUT_MS = 120_000;
631
631
  * assistant's tool loop.
632
632
  */
633
633
  export function judgeSdkEnv(env: Record<string, string | undefined>): Record<string, string | undefined> {
634
- return { ...hostSafeEnv(), ...env };
634
+ return sdkEnv({ ...hostSafeEnv(), ...env });
635
635
  }
636
636
 
637
637
  /** One judge call: its words and what it cost (the SDK's result line). */
package/src/failure.ts CHANGED
@@ -200,7 +200,7 @@ function tooBig(reason: string): FailureExplained | null {
200
200
  const what = kind === "memory" ? "GiB of memory" : pool[2];
201
201
  const fix =
202
202
  scope === "run" ? "Ask for less with size: or resources: on the agent, or raise the flow's compute:."
203
- : scope === "workspace" ? "Ask for less with size: or resources: on the agent, or raise the workspace's compute: (its AGENTS.md)."
203
+ : scope === "workspace" ? "Ask for less with size: or resources: on the agent, or raise the project's compute: (its AGENTS.md)."
204
204
  : scope === "account" ? `Ask for less with size: or resources: on the agent, raise the account's compute: (Settings → Policies → Governance), ${UPGRADE}.`
205
205
  : "Ask for less with size: or resources: on the agent: no machine here can hold a step this big.";
206
206
  return {
package/src/flow-lint.ts CHANGED
@@ -175,7 +175,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
175
175
  message: zoneProblem,
176
176
  detail:
177
177
  "This is the zone the schedule fires in AND the calendar every step in this flow works " +
178
- "to. Unreadable, the schedule falls back to UTC and each step inherits the workspace's " +
178
+ "to. Unreadable, the schedule falls back to UTC and each step inherits the project's " +
179
179
  "zone instead of this one.",
180
180
  });
181
181
  }
@@ -237,7 +237,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
237
237
  // Trigger shapes that can never fire, said at check time rather than
238
238
  // discovered as a flow that "never runs".
239
239
  if (flow.budgetProblem) {
240
- warnings.push({ step: null, message: flow.budgetProblem, detail: "A flow's `budget:` is the most one run may spend — a number in USD, or `unlimited`. A cap over a day, week or month belongs in the workspace's or the account's AGENTS.md, where it means every run put together." });
240
+ warnings.push({ step: null, message: flow.budgetProblem, detail: "A flow's `budget:` is the most one run may spend — a number in USD, or `unlimited`. A cap over a day, week or month belongs in the project's or the account's AGENTS.md, where it means every run put together." });
241
241
  }
242
242
  if (flow.trigger === "once" && !flow.at) {
243
243
  warnings.push({ step: null, message: "trigger: once needs an `at:` instant", detail: "Write `at: 2026-09-05T09:00:00+10:00` (ISO 8601). Without a readable instant this flow never fires." });
@@ -246,7 +246,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
246
246
  warnings.push({ step: null, message: "trigger: watch needs an http(s) `url:`", detail: "The scheduler polls that URL and starts the flow when its content changes." });
247
247
  }
248
248
  if (flow.trigger === "flow") {
249
- if (!flow.after) warnings.push({ step: null, message: "trigger: flow needs `after: <flow>`", detail: "Name the flow of this workspace whose finishing starts this one." });
249
+ if (!flow.after) warnings.push({ step: null, message: "trigger: flow needs `after: <flow>`", detail: "Name the flow of this project whose finishing starts this one." });
250
250
  else if (flow.after === flow.name) warnings.push({ step: null, message: "trigger: flow — a flow cannot chain on itself", detail: "That is a loop with no bound. Chain on the flow that produces what this one needs." });
251
251
  }
252
252
  if (flow.signature && !flow.signingSecret) {
@@ -364,7 +364,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
364
364
  line: step.line,
365
365
  level: "error",
366
366
  kind: "outward",
367
- message: `[[${step.agent}]] can act outside this workspace and this step has no verify: and no gate`,
367
+ message: `[[${step.agent}]] can act outside this project and this step has no verify: and no gate`,
368
368
  detail:
369
369
  "A step that sends, posts, buys or publishes needs one of two things: a `verify:` the " +
370
370
  "runtime can fail the step on — a receipt file, a ledger row, the reply's own verdict " +
@@ -383,7 +383,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
383
383
  step: i,
384
384
  line: step.line,
385
385
  kind: "outward",
386
- message: `[[${step.agent}]] can act outside this workspace and this step has retry: ${step.retry}`,
386
+ message: `[[${step.agent}]] can act outside this project and this step has retry: ${step.retry}`,
387
387
  detail:
388
388
  "A retry runs the whole step again, sends included. The runner does not retry a failure " +
389
389
  "that came from the check after the step's tools ran, but an attempt that failed mid-way — " +
@@ -438,7 +438,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
438
438
  step: i,
439
439
  line: step.line,
440
440
  level: "error",
441
- message: `[[${step.agent}]] is not an agent in this workspace`,
441
+ message: `[[${step.agent}]] is not an agent in this project`,
442
442
  detail:
443
443
  "This step has nothing to run. Every run of this flow fails here. Check the spelling " +
444
444
  "against `agents/<name>/agent.md` — the name is the folder's, not the file's heading — " +
@@ -495,7 +495,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
495
495
  warnings.push({
496
496
  step: i,
497
497
  line: step.line,
498
- message: `delegate: "${name}" is not an agent in this workspace`,
498
+ message: `delegate: "${name}" is not an agent in this project`,
499
499
  detail:
500
500
  "The runner only accepts picks from the declared set, so this name can never be " +
501
501
  "chosen — the step silently has one fewer colleague to call on. Fix the spelling, " +
@@ -507,7 +507,7 @@ export function lintFlow(flow: FlowInfo, known?: KnownNames): FlowWarning[] {
507
507
  warnings.push({
508
508
  step: i,
509
509
  line: step.line,
510
- message: `on-fail: "${step.onFail}" is not an agent in this workspace`,
510
+ message: `on-fail: "${step.onFail}" is not an agent in this project`,
511
511
  detail:
512
512
  "The recovery path is the one you cannot test by running the flow successfully. As " +
513
513
  "written, a failure here has nowhere to go and the step just fails.",