bare-agent 0.58.0 → 0.59.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/bareagent.context.md +3 -1
- package/package.json +1 -1
- package/primitives.json +2 -2
- package/src/bareguard-adapter.js +2 -0
- package/tools/shell.d.ts +31 -3
- package/tools/shell.js +142 -5
package/bareagent.context.md
CHANGED
|
@@ -485,7 +485,7 @@ if (result.error?.startsWith('halt:')) {
|
|
|
485
485
|
|
|
486
486
|
**Why four pieces (`policy` + `onLlmResult` + `onToolResult` + `filterTools`).** `policy` runs `gate.check` *before* every tool call. `onLlmResult` fires after every successful `provider.generate` — without it, `budget.maxCostUsd` never sees LLM cost and is silently undercounted for token-heavy / tool-light workloads (every chatbot). It also fires for the out-of-band `ctx.summarize` call (R-C6) tagged `kind:'summarize'`; main-loop rounds carry `kind:'turn'` — so summary-window tokens count against the budget too, and a consumer can tell the two apart. `onToolResult` fires after every `tool.execute` and carries the per-run `ctx` opaque blob into `gate.record` so per-principal accounting works. `filterTools` is a `gate.allows` pre-filter — denied tools are dropped from the catalog the LLM ever sees, no `gate.check` round-trip per call.
|
|
487
487
|
|
|
488
|
-
`onToolResult` on a tool ERROR records `{error, durationMs}` plus an allow-listed `errorContext` copied from `error.context` — `timeout`/`denied` (boolean), `server`/`tool` (string, ≤200 chars), `timeoutMs` (finite number); wrong-typed values are dropped and `stderr`/everything else is never forwarded (the gate writes the record verbatim into the audit row). The key is absent when no allowed field is present.
|
|
488
|
+
`onToolResult` on a tool ERROR records `{error, durationMs}` plus an allow-listed `errorContext` copied from `error.context` — `timeout`/`denied`/`shrink` (boolean), `server`/`tool` (string, ≤200 chars), `timeoutMs`/`oldBytes`/`newBytes`/`oldLines`/`newLines` (finite number; the last four are BA-30 `shrinkGuard` refusal facts); wrong-typed values are dropped and `stderr`/everything else is never forwarded (the gate writes the record verbatim into the audit row). The key is absent when no allowed field is present.
|
|
489
489
|
|
|
490
490
|
Halt-severity decisions exit the loop cleanly via a typed `HaltError` — full mechanics (sealed `msgs`, `halt:<rule>` error token, `loop:done{halted:true}` event, `throwOnError:true` interaction, `halt:unknown` coalesce) are in the **Halt decisions throw `HaltError`** paragraph below. Short version: check `result.error?.startsWith('halt:')` after the run.
|
|
491
491
|
|
|
@@ -1492,6 +1492,8 @@ Mobile tools follow the observe-act pattern: action tools auto-return a fresh sn
|
|
|
1492
1492
|
>
|
|
1493
1493
|
> **`resolveToolPath(p)`** — exported alongside `createShellTools` from `bare-agent/tools`. THE canonicalizer every shell file tool applies internally before opening: expand `~`/`~/…` via `os.homedir()` (throws rather than silently degrading `~/x` to `/x` when no home directory can be determined), then `path.resolve` against `process.cwd()`. Idempotent; rejects a non-string/empty path (thrown, naming only the type/category of the bad value, never the value itself) — every file tool routes through it, so `shell_read`/`shell_grep` with `""` now error instead of silently reading/searching `process.cwd()`. Call it in your `actionTranslator` on `args.path` before returning the gated action, so the string the gate judges is the exact string the tool opens.
|
|
1494
1494
|
|
|
1495
|
+
> **Opt-in `shrinkGuard` (BA-30) — refuse a whole-file `shell_write` that would gut an existing file.** `createShellTools({ shrinkGuard: true })` (= `{ minOldBytes: 2048, maxShrinkRatio: 0.5 }`; an object overrides either, plus `guardPath(absPath) => boolean | Promise<boolean>` — `false` skips the guard for that file, e.g. a worker's own earlier output). `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter. Bytes decide: if the existing file is `>= minOldBytes` and the new content is `< old * maxShrinkRatio`, the write is refused (a thrown `ToolError`, so `maxIdenticalToolErrors` applies) and the file is left byte-identical. The message names the old/new bytes and lines and points at `shell_edit`, `append:true`, or `content:''`; `error.context` is `{ shrink: true, oldBytes, newBytes, oldLines, newLines }` — numbers only, no path or content — and `wireGate`'s `errorContext` forwards those five fields to the audit row. Skipped for `append:true`, `content:''`, a new file, and a non-regular target. There is deliberately no override flag the model can set. Size is measured at call time (`lstat` under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on refusal, with a bounded read (`N+ lines` when capped). A throwing or non-boolean `guardPath` rejects the write (type only); `HaltError` propagates. Unset is byte-identical; `false` is off (same as unset); any other shape throws `ValidationError` at creation. `shell_edit` is unaffected.
|
|
1496
|
+
|
|
1495
1497
|
> **⚠️ `shell_write` requires `content` — and a gate cannot cover for it (v0.27+).** `content` used to default to `''`, so a tool call that OMITTED it silently overwrote the target with **zero bytes** and returned `"wrote 0 bytes to <path>"` as success. That is the ordinary shape of a model hitting its **output-token cap** mid-generation on a long file — observed live emptying a 1789-line source file. **No policy can catch it:** a 0-byte write is a *legal* write, and bareguard's `fs` primitive judges `{type:'write', path}` without inspecting the body (the gate correctly `allow`s it). `shell_write` now **rejects** an absent, `null`, or non-string `content` and leaves the file byte-identical; the error tells the model to retry with the full content. An explicit `content: ""` still empties the file — that one is deliberate.
|
|
1496
1498
|
|
|
1497
1499
|
> **`shell_edit` — the surgical write (BA-13).** Changing one line of an 800-line file with `shell_write` forces the model to re-emit **all 800 lines** as tool-call JSON: an output-token tax ∝ file size (output is the expensive token class), paid on every revision, and the maximal broken-tree surface (a truncated rewrite mangles the lines it never meant to touch — the BA-4/BA-6 class). `shell_edit({path, oldText, newText})` emits only the anchor + replacement. Semantics worth knowing: `oldText` must match **exactly once** (a 0/2+ match is a refusal *returned as the tool result*, so the loop continues and the model widens the anchor — not a throw, so a repeated-identical miss is bounded by maxTurns/budget, not the spin guard); missing/empty `oldText` or missing/non-string `newText` **throw** (BA-4 guards; `newText:""` is a legal deletion); the write is **atomic** (sibling temp + rename, mode preserved) so an fs failure never leaves a partial file; and `newText` is a **literal splice** (a `$&`/`$1` in it lands verbatim, unlike `String.replace`). Gate it exactly like `shell_write` but as `{type:'edit'}` — **bareguard gates `edit` by the same `fs.writeScope` as `write` with zero config** (its FS primitive's `FS_TYPES` already includes `edit`).
|
package/package.json
CHANGED
package/primitives.json
CHANGED
|
@@ -141,8 +141,8 @@
|
|
|
141
141
|
"category": "tools",
|
|
142
142
|
"when": "you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps",
|
|
143
143
|
"import": "import { createShellTools } from 'bare-agent/tools'",
|
|
144
|
-
"signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead}) => {tools: ToolDef[]}",
|
|
145
|
-
"fails": "
|
|
144
|
+
"signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}) => {tools: ToolDef[]}",
|
|
145
|
+
"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.",
|
|
146
146
|
"example": "const { tools } = createShellTools();\nconst loop = new Loop({ provider, tools, policy });\nconst { tools: safeTools } = createShellTools({ noFollowSymlinks: true });"
|
|
147
147
|
},
|
|
148
148
|
{
|
package/src/bareguard-adapter.js
CHANGED
|
@@ -47,6 +47,8 @@ function safeStringify(value) {
|
|
|
47
47
|
// its result verbatim to the audit log. Anything not listed here, or of the wrong type, is dropped.
|
|
48
48
|
const ERROR_CONTEXT_KEYS = /** @type {const} */ ({
|
|
49
49
|
timeout: 'boolean', denied: 'boolean', server: 'string', tool: 'string', timeoutMs: 'number',
|
|
50
|
+
// BA-30 shrinkGuard refusal facts (numbers/boolean only — never a path or content).
|
|
51
|
+
shrink: 'boolean', oldBytes: 'number', newBytes: 'number', oldLines: 'number', newLines: 'number',
|
|
50
52
|
});
|
|
51
53
|
const ERROR_CONTEXT_MAX_STR = 200;
|
|
52
54
|
|
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,
|