bare-agent 0.61.0 → 0.62.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 +2 -0
- package/package.json +1 -1
- package/primitives.json +2 -2
- package/tools/shell.d.ts +15 -4
- package/tools/shell.js +130 -17
package/bareagent.context.md
CHANGED
|
@@ -1463,6 +1463,8 @@ Mobile tools follow the observe-act pattern: action tools auto-return a fresh sn
|
|
|
1463
1463
|
|
|
1464
1464
|
> **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.
|
|
1465
1465
|
|
|
1466
|
+
> **Opt-in `decode` — read and edit Windows-1252 files.** `createShellTools({ decode: 'utf8-else-1252' })` (default `'utf8'`, byte-identical to before) makes `shell_read`, `shell_grep` and `shell_edit` decode a file as UTF-8 when its bytes are valid UTF-8 (a BOM is kept), otherwise decode the whole file as Windows-1252. A `shell_read` cut at `maxBytes` peeks up to 3 bytes past the cap (never shown; known-size files only, a pipe/procfs read never reads past the cap) to decide UTF-8 vs 1252, then drops a trailing incomplete UTF-8 sequence, so a cut mid-letter is not read as 1252 and a 1252 letter at the cut is kept. `shell_edit` writes a 1252 file back in 1252 and throws, naming only the code point (e.g. `U+2713`), if the patched text has a character 1252 cannot hold; the file stays unchanged and the size cap counts encoded bytes. `shell_write` is unchanged: rewriting a 1252 file whole with it turns the file into UTF-8. Operator-only: a model-supplied `decode` arg is ignored. Any other value throws `ValidationError` at creation.
|
|
1467
|
+
|
|
1466
1468
|
> **⚠️ `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.
|
|
1467
1469
|
|
|
1468
1470
|
> **`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, grepTimeoutMs?: number, 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
|
|
144
|
+
"signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead, grepTimeoutMs?: number, decode?: 'utf8'|'utf8-else-1252', 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, a bad shrinkGuard shape or a bad decode value; 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/tools/shell.d.ts
CHANGED
|
@@ -28,6 +28,10 @@ type GrepArgs = {
|
|
|
28
28
|
* the WHOLE call, the canRead walk included.
|
|
29
29
|
*/
|
|
30
30
|
timeout?: number | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* - INTERNAL, operator-set (`createShellTools({ decode })`); a model-supplied value is never forwarded (`grepPath` builds the worker payload from an explicit allow-list).
|
|
33
|
+
*/
|
|
34
|
+
decode?: "utf8" | "utf8-else-1252" | undefined;
|
|
31
35
|
/**
|
|
32
36
|
* - When true, refuses a symlinked ROOT path (thrown, loud)
|
|
33
37
|
* and skips (silently, like any other read error) a file that is or becomes a symlink during the
|
|
@@ -58,7 +62,7 @@ type ToolDef = import("../types").ToolDef;
|
|
|
58
62
|
* Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
|
|
59
63
|
* caller's responsibility via `new Loop({ policy })`.
|
|
60
64
|
*
|
|
61
|
-
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, grepTimeoutMs?: number, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
65
|
+
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, grepTimeoutMs?: number, decode?: 'utf8'|'utf8-else-1252', shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
62
66
|
* identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
|
|
63
67
|
* `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
|
|
64
68
|
* (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
|
|
@@ -88,6 +92,11 @@ type ToolDef = import("../types").ToolDef;
|
|
|
88
92
|
* time; a path swapped for a symlink between vetting and the worker's read is followed unless
|
|
89
93
|
* `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
|
|
90
94
|
* `grepTimeoutMs` (default 5000): the OPERATOR's wall-clock ceiling on one `shell_grep` call (canRead walk included); a finite number > 0 and <= 2^31-1, else `ValidationError` (type only). The model's own `timeout` arg can only lower it, never raise it.
|
|
95
|
+
* `decode` (opt-in, `'utf8'` default => byte-identical to before; `'utf8-else-1252'`): for `shell_read`, `shell_grep` and `shell_edit`, a file whose bytes are valid UTF-8
|
|
96
|
+
* (BOM kept) decodes as UTF-8, otherwise the WHOLE file decodes as Windows-1252 (WHATWG table), per file per call. A `shell_read` cut at the byte cap peeks up to 3 bytes past it (never shown; known-size files only, a pipe/procfs read never reads past the cap) to decide UTF-8 vs 1252, and a UTF-8 file drops the
|
|
97
|
+
* trailing incomplete sequence, so a cut mid-letter is not mistaken for 1252 and a 1252 letter at the cut is kept. `shell_edit` writes a 1252 file back in 1252 and THROWS (naming the code point only,
|
|
98
|
+
* file unchanged) on a character 1252 cannot hold; its size cap counts the encoded bytes. `shell_write` is unchanged (always UTF-8, so rewriting a 1252 file whole converts it).
|
|
99
|
+
* Operator-only: a model-supplied `decode` arg is ignored (the grep worker only ever gets the operator's mode). Any other value throws `ValidationError` at creation (type only).
|
|
91
100
|
* `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
|
|
92
101
|
* existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
|
|
93
102
|
* `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
|
|
@@ -100,7 +109,7 @@ type ToolDef = import("../types").ToolDef;
|
|
|
100
109
|
* creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
|
|
101
110
|
* @returns {{tools: ToolDef[]}}
|
|
102
111
|
* @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
|
|
103
|
-
* @fails throws ValidationError at creation for a non-function canRead or a bad
|
|
112
|
+
* @fails throws ValidationError at creation for a non-function canRead, a bad shrinkGuard shape or a bad decode value; 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.
|
|
104
113
|
* @example
|
|
105
114
|
* const { tools } = createShellTools();
|
|
106
115
|
* const loop = new Loop({ provider, tools, policy });
|
|
@@ -110,6 +119,7 @@ declare function createShellTools(options?: {
|
|
|
110
119
|
noFollowSymlinks?: boolean;
|
|
111
120
|
canRead?: CanRead;
|
|
112
121
|
grepTimeoutMs?: number;
|
|
122
|
+
decode?: "utf8" | "utf8-else-1252";
|
|
113
123
|
shrinkGuard?: true | {
|
|
114
124
|
minOldBytes?: number;
|
|
115
125
|
maxShrinkRatio?: number;
|
|
@@ -151,7 +161,7 @@ declare function resolveToolPath(p: string): string;
|
|
|
151
161
|
* @param {string[]} [providedFiles] - INTERNAL, never from tool args: the `canRead`-vetted file list
|
|
152
162
|
* (passed by grep-worker.js from its own workerData key, set only by `grepPath`).
|
|
153
163
|
*/
|
|
154
|
-
declare function _grepCore({ pattern, path: rawPath, recursive, maxMatches, flags, noFollowSymlinks }: GrepArgs, providedFiles?: string[]): Promise<{
|
|
164
|
+
declare function _grepCore({ pattern, path: rawPath, recursive, maxMatches, flags, noFollowSymlinks, decode }: GrepArgs, providedFiles?: string[]): Promise<{
|
|
155
165
|
hits: {
|
|
156
166
|
file: string;
|
|
157
167
|
line: number;
|
|
@@ -222,7 +232,7 @@ declare const SHRINK_LINE_SCAN_CAP: number;
|
|
|
222
232
|
* `newText` and would corrupt any edit whose replacement contains a `$`. We index + slice, so every byte of
|
|
223
233
|
* `newText` lands verbatim.
|
|
224
234
|
* @param {{path: string, oldText: string, newText: string, maxBytes?: number}} args
|
|
225
|
-
* @param {{noFollowSymlinks?: boolean}} [options]
|
|
235
|
+
* @param {{noFollowSymlinks?: boolean, decode?: 'utf8'|'utf8-else-1252'}} [options]
|
|
226
236
|
* @returns {Promise<string>}
|
|
227
237
|
*/
|
|
228
238
|
declare function editFile({ path: rawPath, oldText, newText, maxBytes }: {
|
|
@@ -232,6 +242,7 @@ declare function editFile({ path: rawPath, oldText, newText, maxBytes }: {
|
|
|
232
242
|
maxBytes?: number;
|
|
233
243
|
}, options?: {
|
|
234
244
|
noFollowSymlinks?: boolean;
|
|
245
|
+
decode?: "utf8" | "utf8-else-1252";
|
|
235
246
|
}): Promise<string>;
|
|
236
247
|
/**
|
|
237
248
|
* ONE shared open path for every file-open site in this module (`shell_read`, `shell_write`,
|
package/tools/shell.js
CHANGED
|
@@ -284,14 +284,106 @@ async function readBounded(fh, limit) {
|
|
|
284
284
|
return { buf: Buffer.concat(chunks, total), hitLimit: total > limit };
|
|
285
285
|
}
|
|
286
286
|
|
|
287
|
+
// ---- opt-in `decode` (UTF-8 with a Windows-1252 fallback) ------------------------------------------------
|
|
288
|
+
// WHATWG windows-1252 0x80-0x9F block, hand-written (NOT TextDecoder('windows-1252'): a Node build without
|
|
289
|
+
// full ICU throws on that label, and shell_edit needs the reverse table anyway). 00-7F and A0-FF map to the
|
|
290
|
+
// same code point; the five unused bytes (81 8D 8F 90 9D) map to the matching C1 control code points.
|
|
291
|
+
const WIN1252_HIGH = [
|
|
292
|
+
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
|
|
293
|
+
0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F,
|
|
294
|
+
0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
|
|
295
|
+
0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
|
|
296
|
+
].map((c) => String.fromCodePoint(c));
|
|
297
|
+
/** @type {Map<number, number>} code point -> byte, for the 0x80-0x9F block only (everything else is identity). */
|
|
298
|
+
const WIN1252_REVERSE = new Map(WIN1252_HIGH.map((ch, i) => [/** @type {number} */ (ch.codePointAt(0)), 0x80 + i]));
|
|
299
|
+
const UTF8_STRICT = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
300
|
+
const DECODE_MODES = ['utf8', 'utf8-else-1252'];
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Validate `createShellTools({ decode })`. Unset => `'utf8'`. Throws `ValidationError` naming the TYPE only.
|
|
304
|
+
* @param {unknown} decode
|
|
305
|
+
* @returns {'utf8'|'utf8-else-1252'}
|
|
306
|
+
*/
|
|
307
|
+
function normalizeDecode(decode) {
|
|
308
|
+
if (decode === undefined) return 'utf8';
|
|
309
|
+
if (typeof decode !== 'string' || !DECODE_MODES.includes(decode)) {
|
|
310
|
+
throw new ValidationError(`createShellTools: decode must be 'utf8' or 'utf8-else-1252' (got ${typeName(decode)})`);
|
|
311
|
+
}
|
|
312
|
+
return /** @type {'utf8'|'utf8-else-1252'} */ (decode);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Drop a trailing INCOMPLETE UTF-8 sequence (at most 3 bytes) left by a byte-cap cut. */
|
|
316
|
+
function dropPartialUtf8Tail(/** @type {Buffer} */ buf) {
|
|
317
|
+
for (let i = buf.length - 1; i >= 0 && i >= buf.length - 3; i--) {
|
|
318
|
+
const b = buf[i];
|
|
319
|
+
if ((b & 0xC0) === 0x80) continue; // continuation byte: keep looking for its lead
|
|
320
|
+
if (b < 0xC2 || b > 0xF4) return buf; // ASCII or not a lead: nothing partial
|
|
321
|
+
const need = b >= 0xF0 ? 4 : b >= 0xE0 ? 3 : 2;
|
|
322
|
+
return buf.length - i < need ? buf.subarray(0, i) : buf;
|
|
323
|
+
}
|
|
324
|
+
return buf;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Decode file bytes. `'utf8'` is exactly `buf.toString('utf8')`. `'utf8-else-1252'`: valid UTF-8 (BOM kept) wins,
|
|
329
|
+
* else the WHOLE buffer is windows-1252. `truncated` = the buffer was cut at a byte cap: `peek` (up to 3 bytes past
|
|
330
|
+
* the cap on a known-size file, 1 on a size-unknown read; decision only) decides UTF-8 vs 1252, and a UTF-8 result drops the partial trailing sequence.
|
|
331
|
+
* @param {Buffer} buf
|
|
332
|
+
* @param {'utf8'|'utf8-else-1252'} mode
|
|
333
|
+
* @param {boolean} [truncated]
|
|
334
|
+
* @param {Buffer} [peek]
|
|
335
|
+
* @returns {{text: string, enc: 'utf8'|'1252'}}
|
|
336
|
+
*/
|
|
337
|
+
function decodeBytes(buf, mode, truncated = false, peek = Buffer.alloc(0)) {
|
|
338
|
+
if (mode !== 'utf8-else-1252') return { text: buf.toString('utf8'), enc: 'utf8' };
|
|
339
|
+
if (truncated) {
|
|
340
|
+
// The byte at the cut may be a UTF-8 lead OR a 1252 letter. Decide on cap bytes + up to 3 peeked bytes
|
|
341
|
+
// (never shown): stream mode tolerates an incomplete sequence only where the input runs out.
|
|
342
|
+
let utf8 = true;
|
|
343
|
+
try { new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(Buffer.concat([buf, peek]), { stream: true }); } catch { utf8 = false; }
|
|
344
|
+
if (utf8) return { text: dropPartialUtf8Tail(buf).toString('utf8'), enc: 'utf8' };
|
|
345
|
+
return { text: buf.toString('latin1').replace(/[\x80-\x9f]/g, (c) => WIN1252_HIGH[c.charCodeAt(0) - 0x80]), enc: '1252' };
|
|
346
|
+
}
|
|
347
|
+
const head = buf;
|
|
348
|
+
try {
|
|
349
|
+
UTF8_STRICT.decode(head);
|
|
350
|
+
return { text: head.toString('utf8'), enc: 'utf8' };
|
|
351
|
+
} catch {
|
|
352
|
+
return { text: buf.toString('latin1').replace(/[\x80-\x9f]/g, (c) => WIN1252_HIGH[c.charCodeAt(0) - 0x80]), enc: '1252' };
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Encode text as windows-1252. Throws (naming the first unencodable CODE POINT only, never the text).
|
|
358
|
+
* @param {string} text
|
|
359
|
+
* @returns {Buffer}
|
|
360
|
+
*/
|
|
361
|
+
function encode1252(text) {
|
|
362
|
+
const out = Buffer.allocUnsafe(text.length);
|
|
363
|
+
let n = 0;
|
|
364
|
+
for (const ch of text) {
|
|
365
|
+
const cp = /** @type {number} */ (ch.codePointAt(0));
|
|
366
|
+
if (cp < 0x80 || (cp >= 0xA0 && cp <= 0xFF)) out[n++] = cp;
|
|
367
|
+
else {
|
|
368
|
+
const b = WIN1252_REVERSE.get(cp);
|
|
369
|
+
if (b === undefined) {
|
|
370
|
+
throw new Error(`shell_edit: the file is windows-1252 and cannot hold U+${cp.toString(16).toUpperCase().padStart(4, '0')} — refusing to edit, the file is unchanged`);
|
|
371
|
+
}
|
|
372
|
+
out[n++] = b;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return out.subarray(0, n);
|
|
376
|
+
}
|
|
377
|
+
|
|
287
378
|
/**
|
|
288
379
|
* @param {string} rawPath
|
|
289
380
|
* @param {number} [maxBytes]
|
|
290
|
-
* @param {{noFollowSymlinks?: boolean}} [options]
|
|
381
|
+
* @param {{noFollowSymlinks?: boolean, decode?: 'utf8'|'utf8-else-1252'}} [options]
|
|
291
382
|
*/
|
|
292
383
|
async function readEntry(rawPath, maxBytes, options = {}) {
|
|
293
384
|
const resolved = resolveToolPath(rawPath);
|
|
294
385
|
const cap = maxBytes || DEFAULT_READ_MAX_BYTES;
|
|
386
|
+
const mode = options.decode || 'utf8';
|
|
295
387
|
|
|
296
388
|
const fh = await openFile('shell_read', resolved, fsConstants.O_RDONLY, undefined, options);
|
|
297
389
|
try {
|
|
@@ -312,7 +404,13 @@ async function readEntry(rawPath, maxBytes, options = {}) {
|
|
|
312
404
|
// offset 0 is the fast path — no need to read the whole thing just to discard the tail.
|
|
313
405
|
const buf = Buffer.alloc(cap);
|
|
314
406
|
await fh.read(buf, 0, cap, 0);
|
|
315
|
-
|
|
407
|
+
// Peek = up to 3 bytes past the cap (decision only); a positional read on a regular file never blocks.
|
|
408
|
+
let peek = Buffer.alloc(0);
|
|
409
|
+
if (mode === 'utf8-else-1252') {
|
|
410
|
+
const p3 = Buffer.alloc(3);
|
|
411
|
+
peek = p3.subarray(0, (await fh.read(p3, 0, 3, cap)).bytesRead);
|
|
412
|
+
}
|
|
413
|
+
return decodeBytes(buf, mode, true, peek).text + `\n\n[truncated: ${stat.size - cap} more bytes not shown]`;
|
|
316
414
|
}
|
|
317
415
|
// stat.size is <= cap here, but NOT trustworthy: procfs/sysfs files (e.g. /proc/self/status,
|
|
318
416
|
// /proc/kallsyms) commonly report a size that has nothing to do with their real content, and a
|
|
@@ -323,9 +421,12 @@ async function readEntry(rawPath, maxBytes, options = {}) {
|
|
|
323
421
|
if (hitLimit) {
|
|
324
422
|
// We only know we read cap+1+ bytes, not the real total (stat.size lied) — never invent a
|
|
325
423
|
// "more bytes not shown" count for a size we don't actually know.
|
|
326
|
-
|
|
424
|
+
// Peek = the 1 byte past the cap that buf already holds. NO extra read: on a pipe/FIFO/tty/procfs a
|
|
425
|
+
// further read can block forever (FIFO with cap+1 bytes buffered and its writer still open).
|
|
426
|
+
const peek = buf.subarray(cap);
|
|
427
|
+
return decodeBytes(buf.subarray(0, cap), mode, true, peek).text + `\n\n[truncated at ${cap} bytes: file size unknown]`;
|
|
327
428
|
}
|
|
328
|
-
return buf.
|
|
429
|
+
return decodeBytes(buf, mode).text;
|
|
329
430
|
} finally {
|
|
330
431
|
await fh.close().catch(() => {});
|
|
331
432
|
}
|
|
@@ -568,7 +669,7 @@ async function writeFile({ path: rawPath, content, append = false, maxBytes }, o
|
|
|
568
669
|
* `newText` and would corrupt any edit whose replacement contains a `$`. We index + slice, so every byte of
|
|
569
670
|
* `newText` lands verbatim.
|
|
570
671
|
* @param {{path: string, oldText: string, newText: string, maxBytes?: number}} args
|
|
571
|
-
* @param {{noFollowSymlinks?: boolean}} [options]
|
|
672
|
+
* @param {{noFollowSymlinks?: boolean, decode?: 'utf8'|'utf8-else-1252'}} [options]
|
|
572
673
|
* @returns {Promise<string>}
|
|
573
674
|
*/
|
|
574
675
|
async function editFile({ path: rawPath, oldText, newText, maxBytes }, options = {}) {
|
|
@@ -598,6 +699,8 @@ async function editFile({ path: rawPath, oldText, newText, maxBytes }, options =
|
|
|
598
699
|
// or rename — a refusal must leave both the target and a would-be link's target untouched.
|
|
599
700
|
// fs-layer errors (ENOENT for a missing file, EISDIR for a directory) throw — same surface as shell_read.
|
|
600
701
|
let content;
|
|
702
|
+
/** @type {'utf8'|'1252'} */
|
|
703
|
+
let enc = 'utf8';
|
|
601
704
|
let stat;
|
|
602
705
|
const fh = await openFile('shell_edit', resolved, fsConstants.O_RDONLY, undefined, options);
|
|
603
706
|
try {
|
|
@@ -611,7 +714,7 @@ async function editFile({ path: rawPath, oldText, newText, maxBytes }, options =
|
|
|
611
714
|
if (hitLimit) {
|
|
612
715
|
throw new Error(`shell_edit: file is larger than the ${cap}-byte cap (pass maxBytes to raise it) — no change made`);
|
|
613
716
|
}
|
|
614
|
-
content = buf.
|
|
717
|
+
({ text: content, enc } = decodeBytes(buf, options.decode || 'utf8'));
|
|
615
718
|
} finally {
|
|
616
719
|
await fh.close().catch(() => {});
|
|
617
720
|
}
|
|
@@ -631,7 +734,10 @@ async function editFile({ path: rawPath, oldText, newText, maxBytes }, options =
|
|
|
631
734
|
const patched = content.slice(0, idx) + newText + content.slice(idx + oldText.length);
|
|
632
735
|
|
|
633
736
|
// `cap` was hoisted above the read (readBounded needed it); reused here unchanged.
|
|
634
|
-
|
|
737
|
+
// A windows-1252 file is written back in 1252 (a char it can't hold throws here, before any temp exists);
|
|
738
|
+
// the cap checks the ENCODED length, 1 byte per char.
|
|
739
|
+
const out1252 = enc === '1252' ? encode1252(patched) : null;
|
|
740
|
+
const bytes = out1252 ? out1252.length : Buffer.byteLength(patched, 'utf8');
|
|
635
741
|
if (bytes > cap) {
|
|
636
742
|
throw new Error(`shell_edit result is ${bytes} bytes, over the ${cap}-byte cap (pass maxBytes to raise it)`);
|
|
637
743
|
}
|
|
@@ -644,7 +750,7 @@ async function editFile({ path: rawPath, oldText, newText, maxBytes }, options =
|
|
|
644
750
|
// colliding name fails the write instead. Create owner-only (0o600) so the patched body — which may hold
|
|
645
751
|
// a secret from a sensitive source file — is never briefly world-readable in the window before chmod sets
|
|
646
752
|
// the original's real mode. (This temp pattern is new to shell_edit, so it carries its own hardening.)
|
|
647
|
-
await fs.writeFile(tmp, patched, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
|
|
753
|
+
await fs.writeFile(tmp, out1252 || patched, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
|
|
648
754
|
await fs.chmod(tmp, stat.mode & 0o777);
|
|
649
755
|
await fs.rename(tmp, resolved);
|
|
650
756
|
} catch (err) {
|
|
@@ -742,6 +848,7 @@ function looksCatastrophic(pattern) {
|
|
|
742
848
|
* worker thread; on overrun the worker is terminated and the call rejects, so a pattern that slips
|
|
743
849
|
* past `looksCatastrophic` can no longer hang the host event loop. When `canRead` is set it bounds
|
|
744
850
|
* the WHOLE call, the canRead walk included.
|
|
851
|
+
* @property {'utf8'|'utf8-else-1252'} [decode] - INTERNAL, operator-set (`createShellTools({ decode })`); a model-supplied value is never forwarded (`grepPath` builds the worker payload from an explicit allow-list).
|
|
745
852
|
* @property {boolean} [noFollowSymlinks] - When true, refuses a symlinked ROOT path (thrown, loud)
|
|
746
853
|
* and skips (silently, like any other read error) a file that is or becomes a symlink during the
|
|
747
854
|
* walk. Threaded into `workerData` so the worker thread's file reads honor it too.
|
|
@@ -836,7 +943,7 @@ async function walkChecked(dir, recursive, canRead, out, budget) {
|
|
|
836
943
|
* @param {string[]} [providedFiles] - INTERNAL, never from tool args: the `canRead`-vetted file list
|
|
837
944
|
* (passed by grep-worker.js from its own workerData key, set only by `grepPath`).
|
|
838
945
|
*/
|
|
839
|
-
async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches, flags = 'i', noFollowSymlinks = false }, providedFiles) {
|
|
946
|
+
async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches, flags = 'i', noFollowSymlinks = false, decode = 'utf8' }, providedFiles) {
|
|
840
947
|
const resolved = resolveToolPath(rawPath);
|
|
841
948
|
const cap = maxMatches || DEFAULT_GREP_MAX_MATCHES;
|
|
842
949
|
let re;
|
|
@@ -868,7 +975,7 @@ async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches,
|
|
|
868
975
|
try {
|
|
869
976
|
const fh = await openFile('shell_grep', file, fsConstants.O_RDONLY, undefined, { noFollowSymlinks });
|
|
870
977
|
try {
|
|
871
|
-
content = (await fh.readFile()).
|
|
978
|
+
content = decodeBytes(await fh.readFile(), decode).text;
|
|
872
979
|
} finally {
|
|
873
980
|
await fh.close();
|
|
874
981
|
}
|
|
@@ -901,7 +1008,7 @@ async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches,
|
|
|
901
1008
|
* on the main thread and the worker receives only the vetted file list.
|
|
902
1009
|
* @param {number} [grepTimeoutMs] - operator ceiling (validated by `createShellTools`); the model's `timeout` can only lower it.
|
|
903
1010
|
*/
|
|
904
|
-
async function grepPath(args, canRead, grepTimeoutMs = DEFAULT_GREP_TIMEOUT_MS) {
|
|
1011
|
+
async function grepPath(args, canRead, grepTimeoutMs = DEFAULT_GREP_TIMEOUT_MS, decode = 'utf8') {
|
|
905
1012
|
const { pattern, flags = 'i', timeout, path: rawPath, noFollowSymlinks = false } = args;
|
|
906
1013
|
if (looksCatastrophic(pattern)) {
|
|
907
1014
|
throw new Error(
|
|
@@ -943,7 +1050,7 @@ async function grepPath(args, canRead, grepTimeoutMs = DEFAULT_GREP_TIMEOUT_MS)
|
|
|
943
1050
|
|
|
944
1051
|
// Explicit allow-list: model-controlled tool args are NEVER spread into the worker payload.
|
|
945
1052
|
const { recursive, maxMatches } = args;
|
|
946
|
-
const workerArgs = { pattern, path: rawPath, recursive, maxMatches, flags, timeout, noFollowSymlinks };
|
|
1053
|
+
const workerArgs = { pattern, path: rawPath, recursive, maxMatches, flags, timeout, noFollowSymlinks, decode };
|
|
947
1054
|
/** @type {string[]|undefined} */
|
|
948
1055
|
let vettedFiles;
|
|
949
1056
|
// ONE budget for the WHOLE call (canRead walk + worker): the deadline starts before the walk.
|
|
@@ -1097,7 +1204,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1097
1204
|
* Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
|
|
1098
1205
|
* caller's responsibility via `new Loop({ policy })`.
|
|
1099
1206
|
*
|
|
1100
|
-
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, grepTimeoutMs?: number, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
1207
|
+
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, grepTimeoutMs?: number, decode?: 'utf8'|'utf8-else-1252', shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
|
|
1101
1208
|
* identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
|
|
1102
1209
|
* `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
|
|
1103
1210
|
* (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
|
|
@@ -1127,6 +1234,11 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1127
1234
|
* time; a path swapped for a symlink between vetting and the worker's read is followed unless
|
|
1128
1235
|
* `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
|
|
1129
1236
|
* `grepTimeoutMs` (default 5000): the OPERATOR's wall-clock ceiling on one `shell_grep` call (canRead walk included); a finite number > 0 and <= 2^31-1, else `ValidationError` (type only). The model's own `timeout` arg can only lower it, never raise it.
|
|
1237
|
+
* `decode` (opt-in, `'utf8'` default => byte-identical to before; `'utf8-else-1252'`): for `shell_read`, `shell_grep` and `shell_edit`, a file whose bytes are valid UTF-8
|
|
1238
|
+
* (BOM kept) decodes as UTF-8, otherwise the WHOLE file decodes as Windows-1252 (WHATWG table), per file per call. A `shell_read` cut at the byte cap peeks up to 3 bytes past it (never shown; known-size files only, a pipe/procfs read never reads past the cap) to decide UTF-8 vs 1252, and a UTF-8 file drops the
|
|
1239
|
+
* trailing incomplete sequence, so a cut mid-letter is not mistaken for 1252 and a 1252 letter at the cut is kept. `shell_edit` writes a 1252 file back in 1252 and THROWS (naming the code point only,
|
|
1240
|
+
* file unchanged) on a character 1252 cannot hold; its size cap counts the encoded bytes. `shell_write` is unchanged (always UTF-8, so rewriting a 1252 file whole converts it).
|
|
1241
|
+
* Operator-only: a model-supplied `decode` arg is ignored (the grep worker only ever gets the operator's mode). Any other value throws `ValidationError` at creation (type only).
|
|
1130
1242
|
* `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
|
|
1131
1243
|
* existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
|
|
1132
1244
|
* `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
|
|
@@ -1139,7 +1251,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1139
1251
|
* creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
|
|
1140
1252
|
* @returns {{tools: ToolDef[]}}
|
|
1141
1253
|
* @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
|
|
1142
|
-
* @fails throws ValidationError at creation for a non-function canRead or a bad
|
|
1254
|
+
* @fails throws ValidationError at creation for a non-function canRead, a bad shrinkGuard shape or a bad decode value; 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.
|
|
1143
1255
|
* @example
|
|
1144
1256
|
* const { tools } = createShellTools();
|
|
1145
1257
|
* const loop = new Loop({ provider, tools, policy });
|
|
@@ -1148,6 +1260,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1148
1260
|
function createShellTools(options = {}) {
|
|
1149
1261
|
const { noFollowSymlinks = false, canRead } = options;
|
|
1150
1262
|
const shrinkGuard = normalizeShrinkGuard(options.shrinkGuard);
|
|
1263
|
+
const decode = normalizeDecode(options.decode);
|
|
1151
1264
|
const grepTimeoutMs = options.grepTimeoutMs === undefined ? DEFAULT_GREP_TIMEOUT_MS : options.grepTimeoutMs;
|
|
1152
1265
|
if (typeof grepTimeoutMs !== 'number' || !Number.isFinite(grepTimeoutMs) || grepTimeoutMs <= 0 || grepTimeoutMs > MAX_TIMER_MS) {
|
|
1153
1266
|
throw new ValidationError(`createShellTools: grepTimeoutMs must be a finite number > 0 and <= ${MAX_TIMER_MS} (got ${typeName(options.grepTimeoutMs)})`);
|
|
@@ -1169,7 +1282,7 @@ function createShellTools(options = {}) {
|
|
|
1169
1282
|
required: ['path'],
|
|
1170
1283
|
},
|
|
1171
1284
|
execute: async (/** @type {{path: string, maxBytes?: number}} */ { path: p, maxBytes }) =>
|
|
1172
|
-
readEntry(p, maxBytes, { noFollowSymlinks }),
|
|
1285
|
+
readEntry(p, maxBytes, { noFollowSymlinks, decode }),
|
|
1173
1286
|
},
|
|
1174
1287
|
{
|
|
1175
1288
|
name: 'shell_grep',
|
|
@@ -1185,7 +1298,7 @@ function createShellTools(options = {}) {
|
|
|
1185
1298
|
},
|
|
1186
1299
|
required: ['pattern', 'path'],
|
|
1187
1300
|
},
|
|
1188
|
-
execute: async (/** @type {GrepArgs} */ args) => grepPath({ ...args, noFollowSymlinks }, canRead, grepTimeoutMs),
|
|
1301
|
+
execute: async (/** @type {GrepArgs} */ args) => grepPath({ ...args, noFollowSymlinks }, canRead, grepTimeoutMs, decode),
|
|
1189
1302
|
},
|
|
1190
1303
|
{
|
|
1191
1304
|
name: 'shell_write',
|
|
@@ -1229,7 +1342,7 @@ function createShellTools(options = {}) {
|
|
|
1229
1342
|
// The args are model-authored and UNTRUSTED — oldText/newText may be absent (an output-token-capped
|
|
1230
1343
|
// generation), so the boundary type stays loose and editFile enforces the BA-4 contract at runtime.
|
|
1231
1344
|
execute: async (/** @type {{path: string, oldText?: string, newText?: string, maxBytes?: number}} */ args) =>
|
|
1232
|
-
editFile(/** @type {any} */ (args), { noFollowSymlinks }),
|
|
1345
|
+
editFile(/** @type {any} */ (args), { noFollowSymlinks, decode }),
|
|
1233
1346
|
},
|
|
1234
1347
|
{
|
|
1235
1348
|
name: 'shell_run',
|