@foldrun/core 24.2.3 → 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.
- package/dist/src/engine-loop.d.ts +45 -0
- package/dist/src/engine-loop.js +480 -0
- package/dist/src/engine-tools.d.ts +41 -0
- package/dist/src/engine-tools.js +579 -0
- package/dist/src/evals.js +1 -1
- package/dist/src/step-exec.d.ts +12 -1
- package/dist/src/step-exec.js +6 -2
- package/package.json +1 -1
- package/src/engine-loop.ts +495 -0
- package/src/engine-tools.ts +566 -0
- package/src/evals.ts +1 -1
- package/src/step-exec.ts +14 -2
|
@@ -0,0 +1,579 @@
|
|
|
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
|
+
import fs from "node:fs";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import { spawn } from "node:child_process";
|
|
25
|
+
/** End everything the session's commands started and left running. */
|
|
26
|
+
export function killGroups(ctx) {
|
|
27
|
+
for (const pgid of ctx.groups) {
|
|
28
|
+
try {
|
|
29
|
+
process.kill(-pgid, "SIGKILL");
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// the group is already gone
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
ctx.groups.clear();
|
|
36
|
+
}
|
|
37
|
+
/** The most one tool result puts into the conversation, in characters. */
|
|
38
|
+
export const RESULT_CAP = 30_000;
|
|
39
|
+
const READ_LINES = 2000;
|
|
40
|
+
const READ_LINE_CHARS = 2000;
|
|
41
|
+
const SEARCH_FILE_BYTES = 2 * 1024 * 1024;
|
|
42
|
+
const WALK_FILES = 20_000;
|
|
43
|
+
const GLOB_RESULTS = 200;
|
|
44
|
+
const GREP_RESULTS = 250;
|
|
45
|
+
export const BASH_DEFAULT_MS = 120_000;
|
|
46
|
+
export const BASH_MAX_MS = 600_000;
|
|
47
|
+
const KILL_GRACE_MS = 2000;
|
|
48
|
+
/** Never searched: version control and installed dependencies. */
|
|
49
|
+
const SKIP_DIRS = new Set([".git", "node_modules"]);
|
|
50
|
+
const fail = (text) => ({ text, isError: true });
|
|
51
|
+
/** Head and tail of a long text, with the cut said in the middle. */
|
|
52
|
+
export function capped(text, cap = RESULT_CAP) {
|
|
53
|
+
if (text.length <= cap)
|
|
54
|
+
return text;
|
|
55
|
+
const head = Math.floor(cap * 0.6);
|
|
56
|
+
const tail = cap - head;
|
|
57
|
+
return `${text.slice(0, head)}\n\n[… ${text.length - cap} characters cut …]\n\n${text.slice(text.length - tail)}`;
|
|
58
|
+
}
|
|
59
|
+
function str(input, key) {
|
|
60
|
+
const v = input[key];
|
|
61
|
+
return typeof v === "string" ? v : null;
|
|
62
|
+
}
|
|
63
|
+
/** The file a path names, with links followed: what is read, checked for
|
|
64
|
+
* staleness and replaced is then one and the same file. A rename over the
|
|
65
|
+
* path as given would replace a link with a copy and leave its target as
|
|
66
|
+
* it was. For a file that does not exist yet, its folder is resolved. */
|
|
67
|
+
function abs(ctx, p) {
|
|
68
|
+
const given = path.resolve(ctx.cwd, p);
|
|
69
|
+
try {
|
|
70
|
+
return fs.realpathSync(given);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
try {
|
|
74
|
+
return path.join(fs.realpathSync(path.dirname(given)), path.basename(given));
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return given;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function looksBinary(buf) {
|
|
82
|
+
return buf.subarray(0, 8192).includes(0);
|
|
83
|
+
}
|
|
84
|
+
function writeWhole(file, content) {
|
|
85
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
86
|
+
let mode;
|
|
87
|
+
try {
|
|
88
|
+
mode = fs.statSync(file).mode;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// a new file takes the default mode
|
|
92
|
+
}
|
|
93
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
|
|
94
|
+
try {
|
|
95
|
+
fs.writeFileSync(tmp, content, mode !== undefined ? { mode } : undefined);
|
|
96
|
+
fs.renameSync(tmp, file);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
fs.rmSync(tmp, { force: true });
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Why an existing file may not be written yet, or null when it may. */
|
|
104
|
+
function staleReason(ctx, file) {
|
|
105
|
+
let mtime;
|
|
106
|
+
try {
|
|
107
|
+
mtime = fs.statSync(file).mtimeMs;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return null; // no such file: nothing to be stale against
|
|
111
|
+
}
|
|
112
|
+
const seen = ctx.reads.get(file);
|
|
113
|
+
if (seen === undefined)
|
|
114
|
+
return `${file} exists and has not been read in this session — Read it first, then change it`;
|
|
115
|
+
if (seen !== mtime)
|
|
116
|
+
return `${file} changed on disk since it was read — Read it again, then change it`;
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
const read = {
|
|
120
|
+
name: "Read",
|
|
121
|
+
description: "Read a text file. Returns its lines numbered as `<line>\\t<text>`. " +
|
|
122
|
+
`At most ${READ_LINES} lines per call: pass offset (first line, from 1) and limit for the rest of a long file. ` +
|
|
123
|
+
"A file must be read before Edit or Write may change it.",
|
|
124
|
+
input_schema: {
|
|
125
|
+
type: "object",
|
|
126
|
+
properties: {
|
|
127
|
+
file_path: { type: "string", description: "The file, absolute or relative to the working directory" },
|
|
128
|
+
offset: { type: "integer", description: "The first line to return, from 1" },
|
|
129
|
+
limit: { type: "integer", description: "How many lines to return" },
|
|
130
|
+
},
|
|
131
|
+
required: ["file_path"],
|
|
132
|
+
},
|
|
133
|
+
readOnly: true,
|
|
134
|
+
async run(input, ctx) {
|
|
135
|
+
const given = str(input, "file_path");
|
|
136
|
+
if (!given)
|
|
137
|
+
return fail("Read needs file_path");
|
|
138
|
+
const file = abs(ctx, given);
|
|
139
|
+
let stat;
|
|
140
|
+
try {
|
|
141
|
+
stat = fs.statSync(file);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return fail(`${file} does not exist`);
|
|
145
|
+
}
|
|
146
|
+
if (stat.isDirectory())
|
|
147
|
+
return fail(`${file} is a directory — use Glob to list files`);
|
|
148
|
+
const buf = fs.readFileSync(file);
|
|
149
|
+
if (looksBinary(buf))
|
|
150
|
+
return fail(`${file} is not a text file`);
|
|
151
|
+
ctx.reads.set(file, stat.mtimeMs);
|
|
152
|
+
const text = buf.toString("utf8");
|
|
153
|
+
if (!text.length)
|
|
154
|
+
return { text: "(the file is empty)" };
|
|
155
|
+
const lines = text.split("\n");
|
|
156
|
+
if (lines[lines.length - 1] === "")
|
|
157
|
+
lines.pop();
|
|
158
|
+
const offset = Math.max(1, Number.isInteger(input.offset) ? input.offset : 1);
|
|
159
|
+
const limit = Math.max(1, Math.min(READ_LINES, Number.isInteger(input.limit) ? input.limit : READ_LINES));
|
|
160
|
+
if (offset > lines.length)
|
|
161
|
+
return fail(`${file} has ${lines.length} lines; offset ${offset} is past the end`);
|
|
162
|
+
const slice = lines.slice(offset - 1, offset - 1 + limit);
|
|
163
|
+
const body = slice
|
|
164
|
+
.map((l, i) => `${offset + i}\t${l.length > READ_LINE_CHARS ? `${l.slice(0, READ_LINE_CHARS)} [… line cut]` : l}`)
|
|
165
|
+
.join("\n");
|
|
166
|
+
const last = offset - 1 + slice.length;
|
|
167
|
+
const more = last < lines.length ? `\n\n[lines ${offset}–${last} of ${lines.length}; pass offset: ${last + 1} for more]` : "";
|
|
168
|
+
return { text: capped(body) + more };
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
const write = {
|
|
172
|
+
name: "Write",
|
|
173
|
+
description: "Write a whole file, creating it and its folders if needed. Replaces what is there: an existing file must have been Read first. " +
|
|
174
|
+
"To change part of a file, use Edit.",
|
|
175
|
+
input_schema: {
|
|
176
|
+
type: "object",
|
|
177
|
+
properties: {
|
|
178
|
+
file_path: { type: "string", description: "The file, absolute or relative to the working directory" },
|
|
179
|
+
content: { type: "string", description: "The file's whole new content" },
|
|
180
|
+
},
|
|
181
|
+
required: ["file_path", "content"],
|
|
182
|
+
},
|
|
183
|
+
readOnly: false,
|
|
184
|
+
async run(input, ctx) {
|
|
185
|
+
const given = str(input, "file_path");
|
|
186
|
+
const content = str(input, "content");
|
|
187
|
+
if (!given || content === null)
|
|
188
|
+
return fail("Write needs file_path and content");
|
|
189
|
+
const file = abs(ctx, given);
|
|
190
|
+
try {
|
|
191
|
+
if (fs.statSync(file).isDirectory())
|
|
192
|
+
return fail(`${file} is a directory`);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
// new file
|
|
196
|
+
}
|
|
197
|
+
const stale = staleReason(ctx, file);
|
|
198
|
+
if (stale)
|
|
199
|
+
return fail(stale);
|
|
200
|
+
const existed = fs.existsSync(file);
|
|
201
|
+
writeWhole(file, content);
|
|
202
|
+
ctx.reads.set(file, fs.statSync(file).mtimeMs);
|
|
203
|
+
return { text: `${existed ? "Wrote" : "Created"} ${file} (${content.length} characters)` };
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
/** How many times `needle` occurs in `hay`, without overlap. */
|
|
207
|
+
export function occurrences(hay, needle) {
|
|
208
|
+
if (!needle)
|
|
209
|
+
return 0;
|
|
210
|
+
let n = 0;
|
|
211
|
+
for (let at = hay.indexOf(needle); at >= 0; at = hay.indexOf(needle, at + needle.length))
|
|
212
|
+
n++;
|
|
213
|
+
return n;
|
|
214
|
+
}
|
|
215
|
+
const edit = {
|
|
216
|
+
name: "Edit",
|
|
217
|
+
description: "Replace exact text in a file that has been Read. old_string must match the file character for character, " +
|
|
218
|
+
"whitespace and line breaks included, and must occur exactly once — add surrounding lines to make it unique, " +
|
|
219
|
+
"or pass replace_all to change every occurrence. Nothing is changed when it does not match.",
|
|
220
|
+
input_schema: {
|
|
221
|
+
type: "object",
|
|
222
|
+
properties: {
|
|
223
|
+
file_path: { type: "string", description: "The file, absolute or relative to the working directory" },
|
|
224
|
+
old_string: { type: "string", description: "The exact text to replace" },
|
|
225
|
+
new_string: { type: "string", description: "What replaces it" },
|
|
226
|
+
replace_all: { type: "boolean", description: "Replace every occurrence (default false)" },
|
|
227
|
+
},
|
|
228
|
+
required: ["file_path", "old_string", "new_string"],
|
|
229
|
+
},
|
|
230
|
+
readOnly: false,
|
|
231
|
+
async run(input, ctx) {
|
|
232
|
+
const given = str(input, "file_path");
|
|
233
|
+
const from = str(input, "old_string");
|
|
234
|
+
const to = str(input, "new_string");
|
|
235
|
+
if (!given || from === null || to === null)
|
|
236
|
+
return fail("Edit needs file_path, old_string and new_string");
|
|
237
|
+
const file = abs(ctx, given);
|
|
238
|
+
if (!fs.existsSync(file))
|
|
239
|
+
return fail(`${file} does not exist — use Write to create it`);
|
|
240
|
+
if (fs.statSync(file).isDirectory())
|
|
241
|
+
return fail(`${file} is a directory`);
|
|
242
|
+
const stale = staleReason(ctx, file);
|
|
243
|
+
if (stale)
|
|
244
|
+
return fail(stale);
|
|
245
|
+
if (!from)
|
|
246
|
+
return fail("old_string is empty — give the exact text to replace, or use Write for a whole file");
|
|
247
|
+
if (from === to)
|
|
248
|
+
return fail("old_string and new_string are the same — nothing to change");
|
|
249
|
+
const buf = fs.readFileSync(file);
|
|
250
|
+
if (looksBinary(buf))
|
|
251
|
+
return fail(`${file} is not a text file`);
|
|
252
|
+
const before = buf.toString("utf8");
|
|
253
|
+
const count = occurrences(before, from);
|
|
254
|
+
if (count === 0) {
|
|
255
|
+
const hint = before.includes("\r\n") && !from.includes("\r\n") && occurrences(before.replace(/\r\n/g, "\n"), from) > 0
|
|
256
|
+
? " The file uses CRLF line endings and old_string uses LF."
|
|
257
|
+
: "";
|
|
258
|
+
return fail(`old_string was not found in ${file} — nothing was changed.${hint} Read the file and copy the text exactly.`);
|
|
259
|
+
}
|
|
260
|
+
const all = input.replace_all === true;
|
|
261
|
+
if (count > 1 && !all) {
|
|
262
|
+
return fail(`old_string occurs ${count} times in ${file} — nothing was changed. Add surrounding lines so it matches once, or pass replace_all: true.`);
|
|
263
|
+
}
|
|
264
|
+
// split/join and slice, never String.replace: `$&` in new_string is text.
|
|
265
|
+
const at = before.indexOf(from);
|
|
266
|
+
const after = all ? before.split(from).join(to) : before.slice(0, at) + to + before.slice(at + from.length);
|
|
267
|
+
writeWhole(file, after);
|
|
268
|
+
ctx.reads.set(file, fs.statSync(file).mtimeMs);
|
|
269
|
+
return { text: `Edited ${file} (${all ? count : 1} replacement${(all ? count : 1) === 1 ? "" : "s"})` };
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
/** A glob as a regular expression over a `/`-separated relative path:
|
|
273
|
+
* `**` any folders, `*` within one name, `?` one character, `{a,b}`. */
|
|
274
|
+
export function globToRegExp(glob) {
|
|
275
|
+
let re = "";
|
|
276
|
+
for (let i = 0; i < glob.length; i++) {
|
|
277
|
+
const c = glob[i];
|
|
278
|
+
if (c === "*") {
|
|
279
|
+
if (glob[i + 1] === "*") {
|
|
280
|
+
i++;
|
|
281
|
+
if (glob[i + 1] === "/") {
|
|
282
|
+
i++;
|
|
283
|
+
re += "(?:[^/]+/)*";
|
|
284
|
+
}
|
|
285
|
+
else
|
|
286
|
+
re += ".*";
|
|
287
|
+
}
|
|
288
|
+
else
|
|
289
|
+
re += "[^/]*";
|
|
290
|
+
}
|
|
291
|
+
else if (c === "?")
|
|
292
|
+
re += "[^/]";
|
|
293
|
+
else if (c === "{") {
|
|
294
|
+
const end = glob.indexOf("}", i);
|
|
295
|
+
if (end < 0)
|
|
296
|
+
re += "\\{";
|
|
297
|
+
else {
|
|
298
|
+
re += `(?:${glob.slice(i + 1, end).split(",").map((s) => s.replace(/[.+^$()|[\]\\*?]/g, "\\$&")).join("|")})`;
|
|
299
|
+
i = end;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
else
|
|
303
|
+
re += /[.+^$()|[\]\\}]/.test(c) ? `\\${c}` : c;
|
|
304
|
+
}
|
|
305
|
+
return new RegExp(`^${re}$`);
|
|
306
|
+
}
|
|
307
|
+
/** Every file under `root`, as paths relative to it. Bounded. */
|
|
308
|
+
function walk(root) {
|
|
309
|
+
const files = [];
|
|
310
|
+
const stack = [""];
|
|
311
|
+
while (stack.length) {
|
|
312
|
+
const rel = stack.pop();
|
|
313
|
+
let entries;
|
|
314
|
+
try {
|
|
315
|
+
entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true });
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
for (const e of entries) {
|
|
321
|
+
const child = rel ? `${rel}/${e.name}` : e.name;
|
|
322
|
+
if (e.isDirectory()) {
|
|
323
|
+
if (!SKIP_DIRS.has(e.name))
|
|
324
|
+
stack.push(child);
|
|
325
|
+
}
|
|
326
|
+
else if (e.isFile()) {
|
|
327
|
+
files.push(child);
|
|
328
|
+
if (files.length >= WALK_FILES)
|
|
329
|
+
return { files, cut: true };
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return { files, cut: false };
|
|
334
|
+
}
|
|
335
|
+
function searchRoot(input, ctx) {
|
|
336
|
+
const given = str(input, "path");
|
|
337
|
+
const root = given ? abs(ctx, given) : ctx.cwd;
|
|
338
|
+
if (!fs.existsSync(root))
|
|
339
|
+
return fail(`${root} does not exist`);
|
|
340
|
+
return { root: fs.realpathSync(root) };
|
|
341
|
+
}
|
|
342
|
+
const glob = {
|
|
343
|
+
name: "Glob",
|
|
344
|
+
description: "Find files by name pattern, such as `**/*.ts` or `src/**/*.test.js`. Returns matching paths, newest first. " +
|
|
345
|
+
"Skips .git and node_modules.",
|
|
346
|
+
input_schema: {
|
|
347
|
+
type: "object",
|
|
348
|
+
properties: {
|
|
349
|
+
pattern: { type: "string", description: "The glob, relative to path" },
|
|
350
|
+
path: { type: "string", description: "The folder to search; the working directory when absent" },
|
|
351
|
+
},
|
|
352
|
+
required: ["pattern"],
|
|
353
|
+
},
|
|
354
|
+
readOnly: true,
|
|
355
|
+
async run(input, ctx) {
|
|
356
|
+
const pattern = str(input, "pattern");
|
|
357
|
+
if (!pattern)
|
|
358
|
+
return fail("Glob needs pattern");
|
|
359
|
+
const where = searchRoot(input, ctx);
|
|
360
|
+
if ("text" in where)
|
|
361
|
+
return where;
|
|
362
|
+
// The folders a pattern names before its first wildcard are where to
|
|
363
|
+
// look, not something to match: `workspace/storage/*.md` searches
|
|
364
|
+
// workspace/storage. The walk follows no links, and `workspace` is one
|
|
365
|
+
// (confine.ts#linkWorkspace), so the root is resolved through it here.
|
|
366
|
+
const segs = pattern.replace(/^\.\//, "").split("/");
|
|
367
|
+
const wild = segs.findIndex((seg) => /[*?{]/.test(seg));
|
|
368
|
+
const fixed = wild < 0 ? segs.slice(0, -1) : segs.slice(0, wild);
|
|
369
|
+
const rest = segs.slice(fixed.length).join("/");
|
|
370
|
+
if (fixed.length) {
|
|
371
|
+
const deeper = path.join(where.root, ...fixed);
|
|
372
|
+
if (!fs.existsSync(deeper))
|
|
373
|
+
return { text: `No files match ${pattern}` };
|
|
374
|
+
where.root = fs.realpathSync(deeper);
|
|
375
|
+
}
|
|
376
|
+
const re = globToRegExp(rest);
|
|
377
|
+
// A pattern with no folder in it matches at any depth, as people expect of `*.md`.
|
|
378
|
+
const anyDepth = !pattern.includes("/");
|
|
379
|
+
const { files, cut } = walk(where.root);
|
|
380
|
+
const hits = files
|
|
381
|
+
.filter((f) => re.test(anyDepth ? path.posix.basename(f) : f))
|
|
382
|
+
.map((f) => {
|
|
383
|
+
const full = path.join(where.root, f);
|
|
384
|
+
let m = 0;
|
|
385
|
+
try {
|
|
386
|
+
m = fs.statSync(full).mtimeMs;
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
// gone since the walk
|
|
390
|
+
}
|
|
391
|
+
return { full, m };
|
|
392
|
+
})
|
|
393
|
+
.sort((a, b) => b.m - a.m);
|
|
394
|
+
if (!hits.length)
|
|
395
|
+
return { text: `No files match ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
|
|
396
|
+
const shown = hits.slice(0, GLOB_RESULTS).map((h) => h.full).join("\n");
|
|
397
|
+
const more = hits.length > GLOB_RESULTS ? `\n\n[${hits.length - GLOB_RESULTS} more not shown — narrow the pattern]` : "";
|
|
398
|
+
return { text: shown + more };
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
const grep = {
|
|
402
|
+
name: "Grep",
|
|
403
|
+
description: "Search file contents with a regular expression. output_mode: `files_with_matches` (default) lists files, " +
|
|
404
|
+
"`content` shows matching lines as `path:line:text`, `count` gives matches per file. " +
|
|
405
|
+
"`glob` limits which files are searched. Skips .git, node_modules and binary files.",
|
|
406
|
+
input_schema: {
|
|
407
|
+
type: "object",
|
|
408
|
+
properties: {
|
|
409
|
+
pattern: { type: "string", description: "The regular expression (JavaScript syntax)" },
|
|
410
|
+
path: { type: "string", description: "The file or folder to search; the working directory when absent" },
|
|
411
|
+
glob: { type: "string", description: "Only files matching this glob, such as `*.ts`" },
|
|
412
|
+
output_mode: { type: "string", enum: ["files_with_matches", "content", "count"] },
|
|
413
|
+
"-i": { type: "boolean", description: "Ignore case" },
|
|
414
|
+
head_limit: { type: "integer", description: "The most results to return" },
|
|
415
|
+
},
|
|
416
|
+
required: ["pattern"],
|
|
417
|
+
},
|
|
418
|
+
readOnly: true,
|
|
419
|
+
async run(input, ctx) {
|
|
420
|
+
const pattern = str(input, "pattern");
|
|
421
|
+
if (!pattern)
|
|
422
|
+
return fail("Grep needs pattern");
|
|
423
|
+
let re;
|
|
424
|
+
try {
|
|
425
|
+
re = new RegExp(pattern, input["-i"] === true ? "i" : "");
|
|
426
|
+
}
|
|
427
|
+
catch (err) {
|
|
428
|
+
return fail(`pattern is not a valid regular expression: ${err.message}`);
|
|
429
|
+
}
|
|
430
|
+
const where = searchRoot(input, ctx);
|
|
431
|
+
if ("text" in where)
|
|
432
|
+
return where;
|
|
433
|
+
const mode = str(input, "output_mode") ?? "files_with_matches";
|
|
434
|
+
const limit = Math.max(1, Math.min(GREP_RESULTS, Number.isInteger(input.head_limit) ? input.head_limit : GREP_RESULTS));
|
|
435
|
+
const filter = str(input, "glob");
|
|
436
|
+
const filterRe = filter ? globToRegExp(filter.replace(/^\.\//, "")) : null;
|
|
437
|
+
const filterAnyDepth = filter ? !filter.includes("/") : false;
|
|
438
|
+
const single = fs.statSync(where.root).isFile();
|
|
439
|
+
const { files, cut } = single ? { files: [""], cut: false } : walk(where.root);
|
|
440
|
+
const out = [];
|
|
441
|
+
let total = 0;
|
|
442
|
+
for (const rel of files.sort()) {
|
|
443
|
+
const full = single ? where.root : path.join(where.root, rel);
|
|
444
|
+
// A file named outright is tested by its own name: it has no path
|
|
445
|
+
// under a search root to match against.
|
|
446
|
+
if (filterRe && !filterRe.test(single || filterAnyDepth ? path.basename(full) : rel))
|
|
447
|
+
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}`);
|
|
476
|
+
}
|
|
477
|
+
if (!out.length)
|
|
478
|
+
return { text: `No matches for ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
|
|
479
|
+
const more = total > out.length ? `\n\n[${total - out.length} more not shown — narrow the search or raise head_limit]` : "";
|
|
480
|
+
return { text: capped(out.join("\n")) + more };
|
|
481
|
+
},
|
|
482
|
+
};
|
|
483
|
+
const bash = {
|
|
484
|
+
name: "Bash",
|
|
485
|
+
description: "Run a shell command in the working directory and return its output (stdout and stderr together) and exit code. " +
|
|
486
|
+
`Stops after timeout milliseconds (default ${BASH_DEFAULT_MS}, at most ${BASH_MAX_MS}). ` +
|
|
487
|
+
"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.",
|
|
488
|
+
input_schema: {
|
|
489
|
+
type: "object",
|
|
490
|
+
properties: {
|
|
491
|
+
command: { type: "string", description: "The command line" },
|
|
492
|
+
timeout: { type: "integer", description: "Milliseconds before the command is stopped" },
|
|
493
|
+
description: { type: "string", description: "What the command does, in a few words" },
|
|
494
|
+
},
|
|
495
|
+
required: ["command"],
|
|
496
|
+
},
|
|
497
|
+
readOnly: false,
|
|
498
|
+
run(input, ctx) {
|
|
499
|
+
const command = str(input, "command");
|
|
500
|
+
if (!command)
|
|
501
|
+
return Promise.resolve(fail("Bash needs command"));
|
|
502
|
+
const ms = Math.max(1000, Math.min(BASH_MAX_MS, Number.isInteger(input.timeout) ? input.timeout : BASH_DEFAULT_MS));
|
|
503
|
+
return new Promise((resolve) => {
|
|
504
|
+
if (ctx.signal.aborted)
|
|
505
|
+
return resolve(fail("the step was stopped before the command ran"));
|
|
506
|
+
// Its own process group, so a stop or a timeout ends what it started
|
|
507
|
+
// too — a test runner's children, a server it left in the background.
|
|
508
|
+
const child = spawn("bash", ["-c", command], {
|
|
509
|
+
cwd: ctx.cwd,
|
|
510
|
+
env: ctx.env,
|
|
511
|
+
detached: true,
|
|
512
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
513
|
+
});
|
|
514
|
+
if (child.pid)
|
|
515
|
+
ctx.groups.add(child.pid);
|
|
516
|
+
let out = "";
|
|
517
|
+
let dropped = 0;
|
|
518
|
+
const take = (chunk) => {
|
|
519
|
+
const s = chunk.toString("utf8");
|
|
520
|
+
// Keep a bounded window while it runs: a command that prints forever
|
|
521
|
+
// must not grow the step's memory.
|
|
522
|
+
out += s;
|
|
523
|
+
if (out.length > RESULT_CAP * 4) {
|
|
524
|
+
const keepHead = RESULT_CAP;
|
|
525
|
+
const keepTail = RESULT_CAP * 2;
|
|
526
|
+
dropped += out.length - keepHead - keepTail;
|
|
527
|
+
out = out.slice(0, keepHead) + out.slice(out.length - keepTail);
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
child.stdout.on("data", take);
|
|
531
|
+
child.stderr.on("data", take);
|
|
532
|
+
let why = null;
|
|
533
|
+
const killGroup = (signal) => {
|
|
534
|
+
try {
|
|
535
|
+
if (child.pid)
|
|
536
|
+
process.kill(-child.pid, signal);
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
// already gone
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
const end = (reason) => {
|
|
543
|
+
if (why)
|
|
544
|
+
return;
|
|
545
|
+
why = reason;
|
|
546
|
+
killGroup("SIGTERM");
|
|
547
|
+
setTimeout(() => killGroup("SIGKILL"), KILL_GRACE_MS).unref();
|
|
548
|
+
};
|
|
549
|
+
const timer = setTimeout(() => end("timeout"), ms);
|
|
550
|
+
const onAbort = () => end("stopped");
|
|
551
|
+
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
552
|
+
const done = (text, isError) => {
|
|
553
|
+
clearTimeout(timer);
|
|
554
|
+
ctx.signal.removeEventListener("abort", onAbort);
|
|
555
|
+
resolve({ text, ...(isError ? { isError: true } : {}) });
|
|
556
|
+
};
|
|
557
|
+
child.on("error", (err) => done(`the command could not start: ${err.message}`, true));
|
|
558
|
+
child.on("close", (code, signal) => {
|
|
559
|
+
const body = capped(out.trimEnd()) + (dropped ? `\n[${dropped} characters of output dropped while it ran]` : "");
|
|
560
|
+
if (why === "timeout")
|
|
561
|
+
return done(`${body}\n[stopped after ${ms} ms — the command did not finish]`.trim(), true);
|
|
562
|
+
if (why === "stopped")
|
|
563
|
+
return done(`${body}\n[stopped with the step]`.trim(), true);
|
|
564
|
+
if (code === 0)
|
|
565
|
+
return done(body || "(no output)", false);
|
|
566
|
+
done(`${body}\n[exit code ${code ?? `none, signal ${signal}`}]`.trim(), true);
|
|
567
|
+
});
|
|
568
|
+
});
|
|
569
|
+
},
|
|
570
|
+
};
|
|
571
|
+
/** The engine's built-in tools, by the name the model and core both use. */
|
|
572
|
+
export const ENGINE_TOOLS = {
|
|
573
|
+
Read: read,
|
|
574
|
+
Write: write,
|
|
575
|
+
Edit: edit,
|
|
576
|
+
Glob: glob,
|
|
577
|
+
Grep: grep,
|
|
578
|
+
Bash: bash,
|
|
579
|
+
};
|
package/dist/src/evals.js
CHANGED
|
@@ -477,7 +477,7 @@ export const JUDGE_TIMEOUT_MS = 120_000;
|
|
|
477
477
|
* assistant's tool loop.
|
|
478
478
|
*/
|
|
479
479
|
export function judgeSdkEnv(env) {
|
|
480
|
-
return { ...hostSafeEnv(), ...env };
|
|
480
|
+
return sdkEnv({ ...hostSafeEnv(), ...env });
|
|
481
481
|
}
|
|
482
482
|
/** One judge call: its words and what it cost (the SDK's result line). */
|
|
483
483
|
export async function judgeCall(rubric, output, model, effort, env,
|
package/dist/src/step-exec.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type HookDef, type HookRecord } from "./hooks.ts";
|
|
2
|
+
import { type Engine } from "./engine-loop.ts";
|
|
2
3
|
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
|
|
3
4
|
import { type Effort, type ModelCall } from "./store.ts";
|
|
4
5
|
import { type TokenPrice } from "./catalog.ts";
|
|
@@ -73,6 +74,14 @@ export interface ExecOptions {
|
|
|
73
74
|
* host's paths. A name that resolves to nothing refuses the step. */
|
|
74
75
|
hookNames?: string[];
|
|
75
76
|
hookBase?: Record<string, unknown>;
|
|
77
|
+
/** Which loop runs the turns: the SDK (the default) or foldrun's own
|
|
78
|
+
* (engine-loop.ts). The caller's choice, from configuration it trusts —
|
|
79
|
+
* never read from `env`, which carries the tenant's secrets by name. */
|
|
80
|
+
engine?: Engine;
|
|
81
|
+
/** With foldrun's engine on a host: run the shell with no OS sandbox.
|
|
82
|
+
* Only for a person's own machine, on their word; a run container is
|
|
83
|
+
* its own boundary and needs nothing said (`sandboxBash: false`). */
|
|
84
|
+
engineHostShell?: boolean;
|
|
76
85
|
agentDir: string;
|
|
77
86
|
workspaceRoot: string;
|
|
78
87
|
libraryRoot: string;
|
|
@@ -266,7 +275,9 @@ export declare function stepCeilingFor(flowShareUsd: number | null, agentBudgetU
|
|
|
266
275
|
};
|
|
267
276
|
export declare function executeStep(opts: ExecOptions,
|
|
268
277
|
/** The model loop. Injected so the clock and the stop can be tested
|
|
269
|
-
* without a model; production passes nothing and gets the SDK
|
|
278
|
+
* without a model; production passes nothing and gets the SDK — or
|
|
279
|
+
* foldrun's own loop when the caller asked for it (`opts.engine`,
|
|
280
|
+
* engine-loop.ts). */
|
|
270
281
|
runQuery?: QueryFn): Promise<ExecOutcome>;
|
|
271
282
|
/**
|
|
272
283
|
* The one JSON value a reply carries. A ```json fence wins — it is what the
|
package/dist/src/step-exec.js
CHANGED
|
@@ -14,6 +14,7 @@ import fs from "node:fs";
|
|
|
14
14
|
import os from "node:os";
|
|
15
15
|
import path from "node:path";
|
|
16
16
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
17
|
+
import { foldrunQuery } from "./engine-loop.js";
|
|
17
18
|
import { CAPTURE_CAP } from "./store.js";
|
|
18
19
|
import { costOf } from "./catalog.js";
|
|
19
20
|
import { spawn } from "node:child_process";
|
|
@@ -141,8 +142,10 @@ export function stepCeilingFor(flowShareUsd, agentBudgetUsd, agentSpentUsd, agen
|
|
|
141
142
|
}
|
|
142
143
|
export async function executeStep(opts,
|
|
143
144
|
/** The model loop. Injected so the clock and the stop can be tested
|
|
144
|
-
* without a model; production passes nothing and gets the SDK
|
|
145
|
-
|
|
145
|
+
* without a model; production passes nothing and gets the SDK — or
|
|
146
|
+
* foldrun's own loop when the caller asked for it (`opts.engine`,
|
|
147
|
+
* engine-loop.ts). */
|
|
148
|
+
runQuery = opts.engine === "foldrun" ? foldrunQuery : query) {
|
|
146
149
|
// `workspace/…` for the shell, the scripts and a shell `verify:` — the
|
|
147
150
|
// file tools expand the prefix themselves. Held for the step, verify
|
|
148
151
|
// included, and gone before anyone reads the step's files back
|
|
@@ -270,6 +273,7 @@ async function executeStepInner(opts, runQuery) {
|
|
|
270
273
|
// false) and the container's walls do the containing; the in-process
|
|
271
274
|
// path (the CLI on someone's laptop, and the host executor) keeps it,
|
|
272
275
|
// because there a shell escape reaches the real machine.
|
|
276
|
+
...(opts.engineHostShell ? { engineHostShell: true } : {}),
|
|
273
277
|
sandbox: {
|
|
274
278
|
enabled: opts.sandboxBash !== false,
|
|
275
279
|
// Must stay false. Auto-allowing bash because it's sandboxed skips
|