bare-agent 0.58.0 → 0.60.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/README.md +2 -2
- package/bareagent.context.md +32 -61
- package/index.d.ts +2 -5
- package/index.js +2 -5
- package/package.json +5 -1
- package/primitives.json +23 -14
- package/src/bareguard-adapter.js +2 -0
- package/src/{recurse-retrieval.d.ts → recurse-adapters.d.ts} +71 -89
- package/src/{recurse-retrieval.js → recurse-adapters.js} +10 -60
- package/src/recurse-brakes.d.ts +111 -0
- package/src/recurse-brakes.js +154 -0
- package/src/recurse-env.d.ts +43 -0
- package/src/recurse-env.js +233 -0
- package/src/recurse-finish.d.ts +46 -0
- package/src/recurse-finish.js +123 -0
- package/src/recurse-prompts.d.ts +38 -0
- package/src/recurse-prompts.js +69 -1
- package/src/recurse.d.ts +114 -503
- package/src/recurse.js +176 -1513
- package/src/refine-worker.d.ts +155 -0
- package/src/refine-worker.js +598 -0
- package/tools/shell.d.ts +31 -3
- package/tools/shell.js +142 -5
- package/src/recurse-synthesize.d.ts +0 -53
- package/src/recurse-synthesize.js +0 -106
package/tools/shell.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ declare namespace _exports {
|
|
|
6
6
|
export { resolveToolPath };
|
|
7
7
|
export { _grepCore };
|
|
8
8
|
export { writeFile as _writeFile };
|
|
9
|
+
export { SHRINK_LINE_SCAN_CAP as _SHRINK_LINE_SCAN_CAP };
|
|
9
10
|
export { editFile as _editFile };
|
|
10
11
|
export { openFile as _openFile };
|
|
11
12
|
export { assertDirStillMatchesHandle as _assertDirStillMatchesHandle };
|
|
@@ -56,7 +57,7 @@ type ToolDef = import("../types").ToolDef;
|
|
|
56
57
|
* Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
|
|
57
58
|
* caller's responsibility via `new Loop({ policy })`.
|
|
58
59
|
*
|
|
59
|
-
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
60
|
+
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
60
61
|
* identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
|
|
61
62
|
* `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
|
|
62
63
|
* (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
|
|
@@ -85,9 +86,19 @@ type ToolDef = import("../types").ToolDef;
|
|
|
85
86
|
* hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
|
|
86
87
|
* time; a path swapped for a symlink between vetting and the worker's read is followed unless
|
|
87
88
|
* `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
|
|
89
|
+
* `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
|
|
90
|
+
* existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
|
|
91
|
+
* `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
|
|
92
|
+
* (receives the `resolveToolPath`'d path — LEXICAL, not realpath'd, same as `canRead`: `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter; `false` skips the guard for that file; throw/non-boolean rejects, type only;
|
|
93
|
+
* `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
|
|
94
|
+
* Skipped for `append:true`, `content:''`, a new file, and a non-regular target. Size is measured at call time (`lstat`
|
|
95
|
+
* under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on
|
|
96
|
+
* refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
|
|
97
|
+
* (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
|
|
98
|
+
* creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
|
|
88
99
|
* @returns {{tools: ToolDef[]}}
|
|
89
100
|
* @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
|
|
90
|
-
* @fails
|
|
101
|
+
* @fails throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.
|
|
91
102
|
* @example
|
|
92
103
|
* const { tools } = createShellTools();
|
|
93
104
|
* const loop = new Loop({ provider, tools, policy });
|
|
@@ -96,6 +107,11 @@ type ToolDef = import("../types").ToolDef;
|
|
|
96
107
|
declare function createShellTools(options?: {
|
|
97
108
|
noFollowSymlinks?: boolean;
|
|
98
109
|
canRead?: CanRead;
|
|
110
|
+
shrinkGuard?: true | {
|
|
111
|
+
minOldBytes?: number;
|
|
112
|
+
maxShrinkRatio?: number;
|
|
113
|
+
guardPath?: (absPath: string) => boolean | Promise<boolean>;
|
|
114
|
+
};
|
|
99
115
|
}): {
|
|
100
116
|
tools: ToolDef[];
|
|
101
117
|
};
|
|
@@ -158,7 +174,7 @@ declare function _grepCore({ pattern, path: rawPath, recursive, maxMatches, flag
|
|
|
158
174
|
* feeds this UNTRUSTED model-authored args (that is the boundary BA-4 was breached at, and where types buy
|
|
159
175
|
* nothing).
|
|
160
176
|
* @param {{path: string, content: string, append?: boolean, maxBytes?: number}} args
|
|
161
|
-
* @param {{noFollowSymlinks?: boolean}} [options]
|
|
177
|
+
* @param {{noFollowSymlinks?: boolean, shrinkGuard?: ReturnType<typeof normalizeShrinkGuard>}} [options]
|
|
162
178
|
* @returns {Promise<string>}
|
|
163
179
|
*/
|
|
164
180
|
declare function writeFile({ path: rawPath, content, append, maxBytes }: {
|
|
@@ -168,7 +184,9 @@ declare function writeFile({ path: rawPath, content, append, maxBytes }: {
|
|
|
168
184
|
maxBytes?: number;
|
|
169
185
|
}, options?: {
|
|
170
186
|
noFollowSymlinks?: boolean;
|
|
187
|
+
shrinkGuard?: ReturnType<typeof normalizeShrinkGuard>;
|
|
171
188
|
}): Promise<string>;
|
|
189
|
+
declare const SHRINK_LINE_SCAN_CAP: number;
|
|
172
190
|
/**
|
|
173
191
|
* Anchored exact-string replace (BA-13) — the surgical counterpart to the whole-file `shell_write`.
|
|
174
192
|
* Changing one line of an 800-line file with `shell_write` forces the model to EMIT all 800 lines as
|
|
@@ -279,4 +297,14 @@ declare function assertDirStillMatchesHandle(toolName: string, resolvedPath: str
|
|
|
279
297
|
* @returns {string}
|
|
280
298
|
*/
|
|
281
299
|
declare function expandHome(p: string, homedirFn?: () => string): string;
|
|
300
|
+
/**
|
|
301
|
+
* Validate + normalize `createShellTools({ shrinkGuard })`. Throws `ValidationError` naming the TYPE only.
|
|
302
|
+
* @param {any} sg
|
|
303
|
+
* @returns {{minOldBytes: number, maxShrinkRatio: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}|null}
|
|
304
|
+
*/
|
|
305
|
+
declare function normalizeShrinkGuard(sg: any): {
|
|
306
|
+
minOldBytes: number;
|
|
307
|
+
maxShrinkRatio: number;
|
|
308
|
+
guardPath?: (absPath: string) => boolean | Promise<boolean>;
|
|
309
|
+
} | null;
|
|
282
310
|
import fs = require("node:fs/promises");
|
package/tools/shell.js
CHANGED
|
@@ -66,7 +66,7 @@ const os = require('node:os');
|
|
|
66
66
|
const crypto = require('node:crypto');
|
|
67
67
|
const { exec, execFile } = require('node:child_process');
|
|
68
68
|
const { Worker } = require('node:worker_threads');
|
|
69
|
-
const { HaltError, ValidationError } = require('../src/errors');
|
|
69
|
+
const { HaltError, ValidationError, ToolError } = require('../src/errors');
|
|
70
70
|
|
|
71
71
|
const fsConstants = fs.constants;
|
|
72
72
|
|
|
@@ -358,6 +358,127 @@ function wrongTypeHint(v, param) {
|
|
|
358
358
|
return ` Send ${param} as a string.`;
|
|
359
359
|
}
|
|
360
360
|
|
|
361
|
+
// ---- BA-30 shrinkGuard (opt-in, per createShellTools instance) -------------------------------------------
|
|
362
|
+
const SHRINK_DEFAULTS = { minOldBytes: 2048, maxShrinkRatio: 0.5 };
|
|
363
|
+
// Upper bound on bytes read to count the OLD file's lines for the refusal message (never a full slurp).
|
|
364
|
+
const SHRINK_LINE_SCAN_CAP = 8 * 1024 * 1024;
|
|
365
|
+
const SHRINK_LINE_CHUNK = 64 * 1024;
|
|
366
|
+
|
|
367
|
+
/** @param {any} v */
|
|
368
|
+
function typeName(v) {
|
|
369
|
+
return v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Validate + normalize `createShellTools({ shrinkGuard })`. Throws `ValidationError` naming the TYPE only.
|
|
374
|
+
* @param {any} sg
|
|
375
|
+
* @returns {{minOldBytes: number, maxShrinkRatio: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}|null}
|
|
376
|
+
*/
|
|
377
|
+
function normalizeShrinkGuard(sg) {
|
|
378
|
+
if (sg === undefined || sg === false) return null;
|
|
379
|
+
if (sg === true) return { ...SHRINK_DEFAULTS };
|
|
380
|
+
if (sg === null || typeof sg !== 'object' || Array.isArray(sg)) {
|
|
381
|
+
throw new ValidationError(`createShellTools: shrinkGuard must be true or an options object (got ${typeName(sg)})`);
|
|
382
|
+
}
|
|
383
|
+
const allowed = ['minOldBytes', 'maxShrinkRatio', 'guardPath'];
|
|
384
|
+
if (Object.keys(sg).some((k) => !allowed.includes(k))) {
|
|
385
|
+
throw new ValidationError('createShellTools: shrinkGuard has an unknown option (allowed: minOldBytes, maxShrinkRatio, guardPath)');
|
|
386
|
+
}
|
|
387
|
+
const out = { ...SHRINK_DEFAULTS };
|
|
388
|
+
if (sg.minOldBytes !== undefined) {
|
|
389
|
+
if (typeof sg.minOldBytes !== 'number' || !Number.isFinite(sg.minOldBytes) || sg.minOldBytes < 0) {
|
|
390
|
+
throw new ValidationError(`createShellTools: shrinkGuard.minOldBytes must be a finite number >= 0 (got ${typeName(sg.minOldBytes)})`);
|
|
391
|
+
}
|
|
392
|
+
out.minOldBytes = sg.minOldBytes;
|
|
393
|
+
}
|
|
394
|
+
if (sg.maxShrinkRatio !== undefined) {
|
|
395
|
+
const r = sg.maxShrinkRatio;
|
|
396
|
+
if (typeof r !== 'number' || !Number.isFinite(r) || r <= 0 || r > 1) {
|
|
397
|
+
throw new ValidationError(`createShellTools: shrinkGuard.maxShrinkRatio must be a finite number in (0, 1] (got ${typeName(r)})`);
|
|
398
|
+
}
|
|
399
|
+
out.maxShrinkRatio = r;
|
|
400
|
+
}
|
|
401
|
+
/** @type {any} */
|
|
402
|
+
const res = out;
|
|
403
|
+
if (sg.guardPath !== undefined) {
|
|
404
|
+
if (typeof sg.guardPath !== 'function') {
|
|
405
|
+
throw new ValidationError(`createShellTools: shrinkGuard.guardPath must be a function (got ${typeName(sg.guardPath)})`);
|
|
406
|
+
}
|
|
407
|
+
res.guardPath = sg.guardPath;
|
|
408
|
+
}
|
|
409
|
+
return res;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Count the lines of an existing file with a bounded chunked read through the same no-follow open.
|
|
414
|
+
* @param {string} resolved
|
|
415
|
+
* @param {{noFollowSymlinks?: boolean}} options
|
|
416
|
+
* @returns {Promise<{lines: number, capped: boolean}>}
|
|
417
|
+
*/
|
|
418
|
+
async function countLinesBounded(resolved, options) {
|
|
419
|
+
const fh = await openFile('shell_write', resolved, fsConstants.O_RDONLY, undefined, options);
|
|
420
|
+
try {
|
|
421
|
+
const buf = Buffer.alloc(SHRINK_LINE_CHUNK);
|
|
422
|
+
let total = 0;
|
|
423
|
+
let lines = 0;
|
|
424
|
+
let lastByte = 10;
|
|
425
|
+
while (total < SHRINK_LINE_SCAN_CAP) {
|
|
426
|
+
const { bytesRead } = await fh.read(buf, 0, Math.min(buf.length, SHRINK_LINE_SCAN_CAP - total), null);
|
|
427
|
+
if (bytesRead === 0) return { lines: lines + (lastByte === 10 ? 0 : 1), capped: false };
|
|
428
|
+
for (let i = 0; i < bytesRead; i++) if (buf[i] === 10) lines++;
|
|
429
|
+
lastByte = buf[bytesRead - 1];
|
|
430
|
+
total += bytesRead;
|
|
431
|
+
}
|
|
432
|
+
return { lines: lines + (lastByte === 10 ? 0 : 1), capped: true };
|
|
433
|
+
} finally {
|
|
434
|
+
await fh.close().catch(() => {});
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Refuse (throw ToolError, nothing written) a whole-file write that would gut an existing file.
|
|
440
|
+
* Bytes decide; lines are counted only here, for the message.
|
|
441
|
+
* @param {string} rawPath @param {string} resolved @param {string} content @param {number} newBytes
|
|
442
|
+
* @param {NonNullable<ReturnType<typeof normalizeShrinkGuard>>} guard
|
|
443
|
+
* @param {{noFollowSymlinks?: boolean}} options
|
|
444
|
+
*/
|
|
445
|
+
async function checkShrink(rawPath, resolved, content, newBytes, guard, options) {
|
|
446
|
+
/** @type {import('node:fs').Stats} */
|
|
447
|
+
let st;
|
|
448
|
+
try {
|
|
449
|
+
// lstat under noFollowSymlinks: never measure through a final-component symlink (the write refuses it).
|
|
450
|
+
st = options.noFollowSymlinks ? await fs.lstat(resolved) : await fs.stat(resolved);
|
|
451
|
+
} catch (/** @type {any} */ err) {
|
|
452
|
+
if (err && err.code === 'ENOENT') return; // new file
|
|
453
|
+
throw new Error(`shell_write: shrinkGuard could not stat the target (${err && err.code ? err.code : typeof err}) — refusing to write unguarded`);
|
|
454
|
+
}
|
|
455
|
+
if (!st.isFile()) return; // symlink (noFollow) / dir / special: the normal write path handles it
|
|
456
|
+
const oldBytes = st.size;
|
|
457
|
+
if (!(oldBytes >= guard.minOldBytes && newBytes < oldBytes * guard.maxShrinkRatio)) return;
|
|
458
|
+
if (guard.guardPath) {
|
|
459
|
+
let verdict;
|
|
460
|
+
try {
|
|
461
|
+
verdict = await guard.guardPath(resolved);
|
|
462
|
+
} catch (/** @type {any} */ err) {
|
|
463
|
+
if (err instanceof HaltError) throw err;
|
|
464
|
+
throw new Error(`shell_write: shrinkGuard.guardPath threw for ${resolved} (${err && err.name ? err.name : typeof err})`);
|
|
465
|
+
}
|
|
466
|
+
if (verdict !== true && verdict !== false) {
|
|
467
|
+
throw new Error(`shell_write: shrinkGuard.guardPath returned a non-boolean (${typeName(verdict)}) for ${resolved}`);
|
|
468
|
+
}
|
|
469
|
+
if (verdict === false) return;
|
|
470
|
+
}
|
|
471
|
+
const { lines: oldLines, capped } = await countLinesBounded(resolved, options);
|
|
472
|
+
const newLines = content.length === 0 ? 0 : content.split('\n').length - (content.endsWith('\n') ? 1 : 0);
|
|
473
|
+
const n = (/** @type {number} */ x) => x.toLocaleString('en-US');
|
|
474
|
+
const u = (/** @type {number} */ x, /** @type {string} */ w) => `${n(x)} ${w}${x === 1 ? '' : 's'}`;
|
|
475
|
+
throw new ToolError(
|
|
476
|
+
`refusing: this would replace ${rawPath} (${u(oldBytes, 'byte')}, ${capped ? `${n(oldLines)}+ lines` : u(oldLines, 'line')}) with ${u(newBytes, 'byte')} (${u(newLines, 'line')}). ` +
|
|
477
|
+
'To change part of a file use shell_edit; to rebuild it in parts use append:true; to really empty it pass content:\'\'.',
|
|
478
|
+
{ context: { shrink: true, oldBytes, newBytes, oldLines, newLines } },
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
|
|
361
482
|
/**
|
|
362
483
|
* Write text to a file (the BA-2 first-class write primitive — a coding agent must edit files, and routing
|
|
363
484
|
* writes through the shell is impractical: redirection is a shell metachar that an argv/bash allowlist denies).
|
|
@@ -375,7 +496,7 @@ function wrongTypeHint(v, param) {
|
|
|
375
496
|
* feeds this UNTRUSTED model-authored args (that is the boundary BA-4 was breached at, and where types buy
|
|
376
497
|
* nothing).
|
|
377
498
|
* @param {{path: string, content: string, append?: boolean, maxBytes?: number}} args
|
|
378
|
-
* @param {{noFollowSymlinks?: boolean}} [options]
|
|
499
|
+
* @param {{noFollowSymlinks?: boolean, shrinkGuard?: ReturnType<typeof normalizeShrinkGuard>}} [options]
|
|
379
500
|
* @returns {Promise<string>}
|
|
380
501
|
*/
|
|
381
502
|
async function writeFile({ path: rawPath, content, append = false, maxBytes }, options = {}) {
|
|
@@ -395,6 +516,10 @@ async function writeFile({ path: rawPath, content, append = false, maxBytes }, o
|
|
|
395
516
|
throw new Error(`shell_write content is ${bytes} bytes, over the ${cap}-byte cap (pass maxBytes to raise it)`);
|
|
396
517
|
}
|
|
397
518
|
const resolved = resolveToolPath(rawPath);
|
|
519
|
+
// BA-30 (opt-in): skip for append and the deliberate empty; checkShrink skips new/non-regular targets.
|
|
520
|
+
if (options.shrinkGuard && !append && content !== '') {
|
|
521
|
+
await checkShrink(rawPath, resolved, content, bytes, options.shrinkGuard, options);
|
|
522
|
+
}
|
|
398
523
|
await fs.mkdir(path.dirname(resolved), { recursive: true });
|
|
399
524
|
|
|
400
525
|
// O_TRUNC/O_APPEND + O_CREAT, mode 0o666 (subject to umask) — the same semantics `fs.writeFile`/
|
|
@@ -967,7 +1092,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
967
1092
|
* Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
|
|
968
1093
|
* caller's responsibility via `new Loop({ policy })`.
|
|
969
1094
|
*
|
|
970
|
-
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
1095
|
+
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
971
1096
|
* identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
|
|
972
1097
|
* `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
|
|
973
1098
|
* (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
|
|
@@ -996,9 +1121,19 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
996
1121
|
* hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
|
|
997
1122
|
* time; a path swapped for a symlink between vetting and the worker's read is followed unless
|
|
998
1123
|
* `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
|
|
1124
|
+
* `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
|
|
1125
|
+
* existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
|
|
1126
|
+
* `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
|
|
1127
|
+
* (receives the `resolveToolPath`'d path — LEXICAL, not realpath'd, same as `canRead`: `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter; `false` skips the guard for that file; throw/non-boolean rejects, type only;
|
|
1128
|
+
* `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
|
|
1129
|
+
* Skipped for `append:true`, `content:''`, a new file, and a non-regular target. Size is measured at call time (`lstat`
|
|
1130
|
+
* under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on
|
|
1131
|
+
* refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
|
|
1132
|
+
* (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
|
|
1133
|
+
* creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
|
|
999
1134
|
* @returns {{tools: ToolDef[]}}
|
|
1000
1135
|
* @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
|
|
1001
|
-
* @fails
|
|
1136
|
+
* @fails throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.
|
|
1002
1137
|
* @example
|
|
1003
1138
|
* const { tools } = createShellTools();
|
|
1004
1139
|
* const loop = new Loop({ provider, tools, policy });
|
|
@@ -1006,6 +1141,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1006
1141
|
*/
|
|
1007
1142
|
function createShellTools(options = {}) {
|
|
1008
1143
|
const { noFollowSymlinks = false, canRead } = options;
|
|
1144
|
+
const shrinkGuard = normalizeShrinkGuard(options.shrinkGuard);
|
|
1009
1145
|
if (canRead !== undefined && typeof canRead !== 'function') {
|
|
1010
1146
|
throw new ValidationError(`createShellTools: canRead must be a function (got ${canRead === null ? 'null' : typeof canRead})`);
|
|
1011
1147
|
}
|
|
@@ -1059,7 +1195,7 @@ function createShellTools(options = {}) {
|
|
|
1059
1195
|
// The args are model-authored and UNTRUSTED — `content` may be absent (an output-token-capped
|
|
1060
1196
|
// generation), so the boundary type stays loose and `writeFile` enforces the contract at runtime (BA-4).
|
|
1061
1197
|
execute: async (/** @type {{path: string, content?: string, append?: boolean, maxBytes?: number}} */ args) =>
|
|
1062
|
-
writeFile(/** @type {any} */ (args), { noFollowSymlinks }),
|
|
1198
|
+
writeFile(/** @type {any} */ (args), { noFollowSymlinks, shrinkGuard }),
|
|
1063
1199
|
},
|
|
1064
1200
|
{
|
|
1065
1201
|
name: 'shell_edit',
|
|
@@ -1130,6 +1266,7 @@ module.exports = {
|
|
|
1130
1266
|
resolveToolPath,
|
|
1131
1267
|
_grepCore,
|
|
1132
1268
|
_writeFile: writeFile,
|
|
1269
|
+
_SHRINK_LINE_SCAN_CAP: SHRINK_LINE_SCAN_CAP,
|
|
1133
1270
|
_editFile: editFile,
|
|
1134
1271
|
_openFile: openFile,
|
|
1135
1272
|
_assertDirStillMatchesHandle: assertDirStillMatchesHandle,
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
export type Provider = import("../types").Provider;
|
|
2
|
-
/**
|
|
3
|
-
* The reducer dispatcher used by `recurse` (and, at build step 5, Family B over `runPlan` results[]).
|
|
4
|
-
* @param {string} task
|
|
5
|
-
* @param {any[]} results - The worker/child result values (NOT transcripts — copy-on-return holds upstream).
|
|
6
|
-
* @param {object} [opts]
|
|
7
|
-
* @param {Function} [opts.reduce] - A deterministic code-reduce: `({ task, results }) => any`. The §9.1
|
|
8
|
-
* aggregation path; takes precedence over `strategy`.
|
|
9
|
-
* @param {'concat'|'merge'} [opts.strategy='concat'] - Built-in strategy when no `reduce` fn is given.
|
|
10
|
-
* @param {Provider} [opts.provider] - Required for `merge`.
|
|
11
|
-
* @param {string|null} [opts.contract]
|
|
12
|
-
* @param {Function} [opts.onLlmResult]
|
|
13
|
-
* @param {Function} [opts.policy]
|
|
14
|
-
* @param {any} [opts.text] - The worker's own synthesized text (Family A), available to a `reduce` fn.
|
|
15
|
-
* @param {any[]} [opts.children] - The receipts nodes, available to a `reduce` fn.
|
|
16
|
-
* @param {any} [opts.ctx]
|
|
17
|
-
* @returns {Promise<any>}
|
|
18
|
-
*/
|
|
19
|
-
export function synthesize(task: string, results: any[], opts?: {
|
|
20
|
-
reduce?: Function | undefined;
|
|
21
|
-
strategy?: "concat" | "merge" | undefined;
|
|
22
|
-
provider?: import("../types").Provider | undefined;
|
|
23
|
-
contract?: string | null | undefined;
|
|
24
|
-
onLlmResult?: Function | undefined;
|
|
25
|
-
policy?: Function | undefined;
|
|
26
|
-
text?: any;
|
|
27
|
-
children?: any[] | undefined;
|
|
28
|
-
ctx?: any;
|
|
29
|
-
}): Promise<any>;
|
|
30
|
-
/**
|
|
31
|
-
* Deterministic lossless join — no LLM. The safe default when partials are independent and order-able.
|
|
32
|
-
* @param {any[]} results
|
|
33
|
-
* @returns {string}
|
|
34
|
-
*/
|
|
35
|
-
export function concatReduce(results: any[]): string;
|
|
36
|
-
/**
|
|
37
|
-
* Subjective merge — an ISOLATED Loop (fresh context window, a harsh synthesis persona) combines the partials
|
|
38
|
-
* into one answer. Use for prose / overlapping-findings synthesis; NEVER for arithmetic (§9.1 → use a
|
|
39
|
-
* `reduce` fn). Budget visibility: forwards usage to `onLlmResult`. A governance HaltError propagates clean
|
|
40
|
-
* (the caller decides), mirroring the Evaluator's agentic path.
|
|
41
|
-
* @param {string} task
|
|
42
|
-
* @param {any[]} results
|
|
43
|
-
* @param {{provider: Provider, contract?: string|null, onLlmResult?: Function, policy?: Function}} opts
|
|
44
|
-
* @returns {Promise<string>}
|
|
45
|
-
* @throws {HaltError} a governance cap halted the synthesis Loop.
|
|
46
|
-
*/
|
|
47
|
-
export function mergeReduce(task: string, results: any[], opts: {
|
|
48
|
-
provider: Provider;
|
|
49
|
-
contract?: string | null;
|
|
50
|
-
onLlmResult?: Function;
|
|
51
|
-
policy?: Function;
|
|
52
|
-
}): Promise<string>;
|
|
53
|
-
export const MERGE_PROMPT: string;
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
// NB-3 — the synthesis/reduce step (RLM_PRD §4.3 / §10 step 4). A Family-A worker synthesizes in its own
|
|
4
|
-
// closing turn; Family B's `runPlan` returns results[] with nothing to combine them — this is that reducer,
|
|
5
|
-
// AND the seam a Family-A caller uses to OVERRIDE the model's synthesis when it shouldn't be trusted.
|
|
6
|
-
//
|
|
7
|
-
// §9.1 RESOLVED: numeric/AGGREGATION reduces must be DETERMINISTIC CODE — LLM arithmetic over found partials
|
|
8
|
-
// carried ~10–15% error even at FULL retrieval (spikes 1 & 2). So the `reduce` FUNCTION form is the
|
|
9
|
-
// aggregation path (the caller sums / maxes / dedups in JS); the Loop-driven `merge` strategy is reserved for
|
|
10
|
-
// genuinely SUBJECTIVE synthesis (combine prose, reconcile overlapping findings) where there is no exact
|
|
11
|
-
// answer to compute. `concat` is the lossless no-LLM default. The merge path is low-risk Loop reuse (the Loop
|
|
12
|
-
// is already live-proven) — the riskiest NB-3 assumption was "trust-code-over-LLM-arithmetic," already
|
|
13
|
-
// validated; this file does not re-POC it.
|
|
14
|
-
|
|
15
|
-
/** @typedef {import('../types').Provider} Provider */
|
|
16
|
-
|
|
17
|
-
const { Loop } = require('./loop');
|
|
18
|
-
const { HaltError } = require('./errors');
|
|
19
|
-
|
|
20
|
-
const MERGE_PROMPT =
|
|
21
|
-
'You are a synthesis engine. You are given a TASK and several PARTIAL RESULTS, each produced by a separate ' +
|
|
22
|
-
'worker over its own slice of the problem. Combine them into ONE coherent, de-duplicated answer to the ' +
|
|
23
|
-
'task. Preserve every distinct fact; drop exact duplicates; reconcile overlaps; do NOT invent anything not ' +
|
|
24
|
-
'present in the partials. Output only the combined answer.';
|
|
25
|
-
|
|
26
|
-
const asText = (/** @type {any} */ r) => (typeof r === 'string' ? r : JSON.stringify(r));
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Deterministic lossless join — no LLM. The safe default when partials are independent and order-able.
|
|
30
|
-
* @param {any[]} results
|
|
31
|
-
* @returns {string}
|
|
32
|
-
*/
|
|
33
|
-
function concatReduce(results) {
|
|
34
|
-
return results.map((r, i) => `### Part ${i + 1}\n${asText(r)}`).join('\n\n');
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Subjective merge — an ISOLATED Loop (fresh context window, a harsh synthesis persona) combines the partials
|
|
39
|
-
* into one answer. Use for prose / overlapping-findings synthesis; NEVER for arithmetic (§9.1 → use a
|
|
40
|
-
* `reduce` fn). Budget visibility: forwards usage to `onLlmResult`. A governance HaltError propagates clean
|
|
41
|
-
* (the caller decides), mirroring the Evaluator's agentic path.
|
|
42
|
-
* @param {string} task
|
|
43
|
-
* @param {any[]} results
|
|
44
|
-
* @param {{provider: Provider, contract?: string|null, onLlmResult?: Function, policy?: Function}} opts
|
|
45
|
-
* @returns {Promise<string>}
|
|
46
|
-
* @throws {HaltError} a governance cap halted the synthesis Loop.
|
|
47
|
-
*/
|
|
48
|
-
async function mergeReduce(task, results, opts) {
|
|
49
|
-
if (!opts || !opts.provider) throw new Error('[synthesize] strategy "merge" requires a provider');
|
|
50
|
-
const loop = new Loop({
|
|
51
|
-
provider: opts.provider,
|
|
52
|
-
system: MERGE_PROMPT,
|
|
53
|
-
policy: opts.policy || undefined,
|
|
54
|
-
onLlmResult: opts.onLlmResult || undefined,
|
|
55
|
-
throwOnError: false, // a synthesis fault surfaces below; a halt is re-thrown as a clean HaltError
|
|
56
|
-
});
|
|
57
|
-
const dod = opts.contract ? `\n\nDEFINITION OF DONE:\n${opts.contract}` : '';
|
|
58
|
-
const body =
|
|
59
|
-
`TASK:\n${task}${dod}\n\nPARTIAL RESULTS:\n` +
|
|
60
|
-
results.map((r, i) => `[${i + 1}] ${asText(r)}`).join('\n\n');
|
|
61
|
-
const out = await loop.run([{ role: 'user', content: body }]);
|
|
62
|
-
if (typeof out.error === 'string' && out.error.startsWith('halt:')) {
|
|
63
|
-
throw new HaltError('[synthesize] merge halted by governance', { rule: out.error.slice('halt:'.length) });
|
|
64
|
-
}
|
|
65
|
-
// A non-halt fault (e.g. provider error, deny short-circuit, the hard round limit) is non-fatal here — fall
|
|
66
|
-
// back to the LOSSLESS concat rather than losing the partials entirely. recurse still reports honest
|
|
67
|
-
// completeness via its own paths.
|
|
68
|
-
//
|
|
69
|
-
// Branch on `out.error`, NOT on the falsiness of `out.text` (BA-5). Since the Loop now preserves the text a
|
|
70
|
-
// bounded run produced, a faulted merge returns its PARTIAL, aborted prose — so `out.text || concat` would
|
|
71
|
-
// silently ship that fragment as the synthesized answer and every child result would be lost. Proven
|
|
72
|
-
// reachable: the merge Loop registers no tools, so a hallucinated tool call is fed back as
|
|
73
|
-
// `[Loop] Unknown tool` and the round loop CONTINUES — round 1 emits prose, round 2 dies, and the fallback
|
|
74
|
-
// never fires. `error` is the sole success signal; text-falsiness never was one.
|
|
75
|
-
if (out.error) return concatReduce(results);
|
|
76
|
-
return out.text || concatReduce(results);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* The reducer dispatcher used by `recurse` (and, at build step 5, Family B over `runPlan` results[]).
|
|
81
|
-
* @param {string} task
|
|
82
|
-
* @param {any[]} results - The worker/child result values (NOT transcripts — copy-on-return holds upstream).
|
|
83
|
-
* @param {object} [opts]
|
|
84
|
-
* @param {Function} [opts.reduce] - A deterministic code-reduce: `({ task, results }) => any`. The §9.1
|
|
85
|
-
* aggregation path; takes precedence over `strategy`.
|
|
86
|
-
* @param {'concat'|'merge'} [opts.strategy='concat'] - Built-in strategy when no `reduce` fn is given.
|
|
87
|
-
* @param {Provider} [opts.provider] - Required for `merge`.
|
|
88
|
-
* @param {string|null} [opts.contract]
|
|
89
|
-
* @param {Function} [opts.onLlmResult]
|
|
90
|
-
* @param {Function} [opts.policy]
|
|
91
|
-
* @param {any} [opts.text] - The worker's own synthesized text (Family A), available to a `reduce` fn.
|
|
92
|
-
* @param {any[]} [opts.children] - The receipts nodes, available to a `reduce` fn.
|
|
93
|
-
* @param {any} [opts.ctx]
|
|
94
|
-
* @returns {Promise<any>}
|
|
95
|
-
*/
|
|
96
|
-
async function synthesize(task, results, opts = {}) {
|
|
97
|
-
if (typeof opts.reduce === 'function') {
|
|
98
|
-
return opts.reduce({ task, results, text: opts.text, children: opts.children, ctx: opts.ctx });
|
|
99
|
-
}
|
|
100
|
-
const strategy = opts.strategy || 'concat';
|
|
101
|
-
if (strategy === 'merge') return mergeReduce(task, results, /** @type {any} */ (opts));
|
|
102
|
-
if (strategy === 'concat') return concatReduce(results);
|
|
103
|
-
throw new Error(`[synthesize] unknown strategy: ${strategy} (expected 'concat' | 'merge', or a reduce function)`);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
module.exports = { synthesize, concatReduce, mergeReduce, MERGE_PROMPT };
|