bare-agent 0.60.1 → 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 +4 -2
- package/package.json +2 -2
- package/primitives.json +2 -2
- package/src/loop.js +14 -4
- package/src/mcp-bridge.js +26 -13
- package/src/provider-anthropic.js +2 -7
- package/src/provider-fallback.d.ts +15 -0
- package/src/provider-fallback.js +21 -0
- package/src/provider-gemini.js +2 -7
- package/src/provider-ollama.js +2 -7
- package/src/provider-openai.js +2 -7
- package/src/recurse-env.js +3 -1
- package/src/recurse-prompts.d.ts +7 -8
- package/src/recurse-prompts.js +13 -16
- package/src/thinking-mode.d.ts +14 -0
- package/src/thinking-mode.js +18 -0
- package/tools/shell.d.ts +22 -8
- package/tools/shell.js +150 -27
- package/types/index.d.ts +5 -0
package/bareagent.context.md
CHANGED
|
@@ -841,7 +841,7 @@ if (out.incomplete) console.warn(out.blocker, out.missingSlices, out.best); //
|
|
|
841
841
|
else console.log(out.result.count, out.result.ids); // count DERIVED by code from the ids var
|
|
842
842
|
```
|
|
843
843
|
|
|
844
|
-
**Fixed tools (no model-written code):** `info`, `peek`, `find` (literal AND-terms, no regex), `chunk`, `ask` (one sub-call on a piece), `map` (code-driven fan-out over a list var, every slot required), `classify` (scan every item with an LLM judge, window 8 x 2 passes, **code-counts** the union of returned ids — the verbatim, measured wording; RC-2 drops ids the judge was not shown), `join`/`count` (code reductions), `final(var)` / `final_text(text)` / `final_parts
|
|
844
|
+
**Fixed tools (no model-written code):** `info`, `peek`, `find` (literal AND-terms, no regex), `chunk`, `ask` (one sub-call on a piece), `map` (code-driven fan-out over a list var, every slot required), `classify` (scan every item with an LLM judge, window 8 x 2 passes, **code-counts** the union of returned ids — the verbatim, measured wording; RC-2 drops ids the judge was not shown), `join`/`count` (code reductions), `final(var)` / `final_text(text)` / `final_parts` (its needle must occur literally in the input, else refused like a blank one). Every tool returns a truncated preview and stores the full value under a var name; your `opts.tools` are appended. `classify`/`map`/`ask` are withheld at the depth cap (and the prompt says so). Repeating `classify`/`map`/`find` with the same args over the same data is a **memo hit: zero calls**.
|
|
845
845
|
|
|
846
846
|
**Typed final — "AI points, code decides".** For `count`/`ids` the model must cite a classify var with `final("<var>")`; code derives `{count, ids}` (the model never types a number, and no number is parsed from prose). A wrong-kind final (or a `final(var)` on a blank/whitespace-only text var, same as a blank `final_text`) gets ONE nudge, then `{ incomplete, blocker:'wrong-final' }`; no final at all is `blocker:'no-final'`. (A `text` task may also end with a plain reply.) A dead window/slot is **never a zero or a survivor-sum**: it surfaces as `{ incomplete, missingSlices, best:<floor> }`.
|
|
847
847
|
|
|
@@ -1457,12 +1457,14 @@ Mobile tools follow the observe-act pattern: action tools auto-return a fresh sn
|
|
|
1457
1457
|
|
|
1458
1458
|
> **Opt-in symlink refusal:** `createShellTools({ noFollowSymlinks: true })` makes `shell_read`, `shell_write`, `shell_edit`, and `shell_grep` refuse to open a path whose **final** path component is a symlink — a file, a dir, or dangling — instead of silently following it. Refusal is a **thrown** error with `err.code === 'ELOOP'` (feeds the Loop's `maxIdenticalToolErrors` guard like any other tool error), and for `shell_write` the link's target is never created or touched. Scope is the final component **only** — a symlinked *parent* directory is not covered (per the canonicalization note above), and neither is the `cwd` option of `shell_run`/`shell_exec` — it only gets `~` expansion, never this flag or `resolveToolPath`'s full canonicalization, so a symlinked `cwd` is always followed. `shell_grep` refuses only a symlinked **root** path loudly, via the same atomic open every other tool uses (open-then-fstat, not a look-then-open `lstat`); a file that turns into a symlink partway through the walk is skipped silently, the same as any other read error. The check is atomic (`O_NOFOLLOW`) on linux/macOS; on Windows, which has no `O_NOFOLLOW`-equivalent open flag, it falls back to a non-atomic `lstat`-then-open check — a symlink planted in that gap slips through. A directory listing (`shell_read` on a dir, `shell_grep`'s root when it's a dir) additionally rechecks the path's `dev`+`ino` against the open handle right after listing — Node has no `fdopendir`, so the listing itself still goes by path, and this narrows (does not close) the window where a directory swapped in between the open and the listing would report a different directory's names; a swap-and-swap-back inside that narrow window still passes undetected. Default `false` — omitting the option is byte-identical to the pre-existing behavior.
|
|
1459
1459
|
>
|
|
1460
|
-
> **Opt-in `canRead` (F259) — closes the root-grep bypass of `fs.deny`.** The Loop `policy` gates `shell_grep` as ONE action on the ROOT path, so `shell_grep` on a repo root walks into paths a gate `fs.deny`s (a direct `shell_read` of them is denied). `createShellTools({ canRead: async (absPath, { isDir, tool }) => boolean })` makes `shell_grep` ask before every directory (`false` prunes the whole subtree, never listed) and every file (`false` skips silently); the root is not passed. Wire bareguard as `canRead: (p, { tool }) => gate.allows({ type: 'read', tool, path: p })`. Unset ⇒ byte-identical; when set the walk runs on the main thread and the worker reads only the allowed list. A throw or non-boolean return rejects the grep (type only in the message), `HaltError` propagates, a non-function `canRead` throws `ValidationError` at creation. `shell_read` on a dir is unaffected (names of one dir, gated on its own path). The grep `timeout` bounds the WHOLE call including the canRead walk (a slow/hung `canRead` rejects with a `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at walk time; a path swapped for a symlink between vetting and the worker's read is followed unless `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`. `shell_grep` builds its worker payload from an explicit allow-list: a model-supplied `files` arg is ignored (only the `canRead`-vetted list, set by `grepPath` itself, reaches the worker).
|
|
1460
|
+
> **Opt-in `canRead` (F259) — closes the root-grep bypass of `fs.deny`.** The Loop `policy` gates `shell_grep` as ONE action on the ROOT path, so `shell_grep` on a repo root walks into paths a gate `fs.deny`s (a direct `shell_read` of them is denied). `createShellTools({ canRead: async (absPath, { isDir, tool }) => boolean })` makes `shell_grep` ask before every directory (`false` prunes the whole subtree, never listed) and every file (`false` skips silently); the root is not passed. Wire bareguard as `canRead: (p, { tool }) => gate.allows({ type: 'read', tool, path: p })`. Unset ⇒ byte-identical; when set the walk runs on the main thread and the worker reads only the allowed list. A throw or non-boolean return rejects the grep (type only in the message), `HaltError` propagates, a non-function `canRead` throws `ValidationError` at creation. `shell_read` on a dir is unaffected (names of one dir, gated on its own path). The grep `timeout` bounds the WHOLE call including the canRead walk (a slow/hung `canRead` rejects with a `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at walk time; a path swapped for a symlink between vetting and the worker's read is followed unless `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`. `shell_grep` builds its worker payload from an explicit allow-list: a model-supplied `files` arg is ignored (only the `canRead`-vetted list, set by `grepPath` itself, reaches the worker). The time limit is the OPERATOR's: `createShellTools({ grepTimeoutMs })` (default 5000; a finite number > 0 and <= 2^31-1, else `ValidationError`). A model-supplied `timeout` can only LOWER it (effective = min(value, grepTimeoutMs)); non-finite, zero, negative or non-number values use the operator limit, and the model can never raise it. Cost on a 5.4k-file tree: ~2.5s → ~3.7s with a real gate. See `poc/f259-grep-canread.mjs`.
|
|
1461
1461
|
>
|
|
1462
1462
|
> **`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.
|
|
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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bare-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.62.0",
|
|
4
4
|
"files": [
|
|
5
5
|
"index.js",
|
|
6
6
|
"index.d.ts",
|
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
"devDependencies": {
|
|
113
113
|
"@types/node": "^22.19.19",
|
|
114
114
|
"bareguard": ">=0.19.2 <1.0.0",
|
|
115
|
-
"litectx": "^0.
|
|
115
|
+
"litectx": "^0.43.1",
|
|
116
116
|
"typescript": "^5.7.0"
|
|
117
117
|
}
|
|
118
118
|
}
|
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, 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/src/loop.js
CHANGED
|
@@ -274,6 +274,12 @@ function renderForSummary(excerpt) {
|
|
|
274
274
|
return parts.join('\n\n');
|
|
275
275
|
}
|
|
276
276
|
|
|
277
|
+
/** Provider label for construction-time error text only (never metering): `name`, else a non-generic class name, else 'unknown'. */
|
|
278
|
+
function providerLabel(p) {
|
|
279
|
+
const c = p.constructor?.name;
|
|
280
|
+
return p.name || (c && c !== 'Object' ? c : 'unknown');
|
|
281
|
+
}
|
|
282
|
+
|
|
277
283
|
class Loop {
|
|
278
284
|
/**
|
|
279
285
|
* `policy` is async `(toolName, args, ctx) => true | string`. Recommended wiring: a closure
|
|
@@ -354,7 +360,7 @@ class Loop {
|
|
|
354
360
|
if (this.provider && this.provider.ownsCycle && (this.assemble || this.trim)) {
|
|
355
361
|
const named = [this.assemble && 'assemble', this.trim && 'trim'].filter(Boolean).join(' and ');
|
|
356
362
|
throw new Error(
|
|
357
|
-
`[Loop] provider '${this.provider
|
|
363
|
+
`[Loop] provider '${providerLabel(this.provider)}' owns its own turn cycle, so ${named} can never run `
|
|
358
364
|
+ '(the provider owns the transcript, not the Loop). Remove the option, or use a provider whose cycle the Loop drives.',
|
|
359
365
|
);
|
|
360
366
|
}
|
|
@@ -362,9 +368,13 @@ class Loop {
|
|
|
362
368
|
// provider no tool call ever reaches the Loop, so a `Loop({policy})` is a fence that is simply
|
|
363
369
|
// not there — the run looks governed and is not. Refuse it: the gate must be wired on the
|
|
364
370
|
// provider, where every tool call actually crosses.
|
|
365
|
-
|
|
371
|
+
// A chain (FallbackProvider) answers via `ungatedCycleOwner`: Loop policy gates its non-native members and
|
|
372
|
+
// each native member's own policy gates it, so only a native member WITHOUT a policy leaves the fence absent.
|
|
373
|
+
const ungatedOwner = this.provider
|
|
374
|
+
&& (this.provider.ungatedCycleOwner ?? (!!this.provider.ownsCycle && !this.provider.policy));
|
|
375
|
+
if (this.policy && ungatedOwner) {
|
|
366
376
|
throw new Error(
|
|
367
|
-
`[Loop] provider '${this.provider
|
|
377
|
+
`[Loop] provider '${providerLabel(this.provider)}' owns its own turn cycle, so Loop-level policy would `
|
|
368
378
|
+ 'NEVER run — no tool call reaches the Loop. Wire the gate on the provider instead '
|
|
369
379
|
+ '(e.g. new CLIPipeProvider({ toolProtocol: \'claude-mcp\', policy })).',
|
|
370
380
|
);
|
|
@@ -373,7 +383,7 @@ class Loop {
|
|
|
373
383
|
// provider no tool call ever reaches the Loop, so it would be accepted and silently never run.
|
|
374
384
|
if (this.provider && this.provider.ownsCycle && this.checkArgs) {
|
|
375
385
|
throw new Error(
|
|
376
|
-
`[Loop] provider '${this.provider
|
|
386
|
+
`[Loop] provider '${providerLabel(this.provider)}' owns its own turn cycle, so checkArgs can never run `
|
|
377
387
|
+ '(no tool call reaches the Loop). Remove the option, or use a provider whose cycle the Loop drives.',
|
|
378
388
|
);
|
|
379
389
|
}
|
package/src/mcp-bridge.js
CHANGED
|
@@ -926,12 +926,15 @@ async function createAllowBridge(allow, o) {
|
|
|
926
926
|
const tools = [];
|
|
927
927
|
/** @type {import('node:child_process').ChildProcess[]} */
|
|
928
928
|
const children = [];
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
929
|
+
// Per-server results are filled in async completion order; EVERY output (`tools`, `servers`, `excluded`,
|
|
930
|
+
// `missing`, `errors`, and so `systemContext` + the metaTools catalog) is re-assembled below in the
|
|
931
|
+
// caller's `allow` key order so the output is deterministic across runs.
|
|
932
|
+
/** @type {Map<string, Array<{server: string, tool: string}>>} */
|
|
933
|
+
const missingBy = new Map();
|
|
934
|
+
/** @type {Map<string, ToolDef[]>} */
|
|
935
|
+
const toolsBy = new Map();
|
|
936
|
+
/** @type {Map<string, Array<[string, {server: string, tool: string}]>>} */
|
|
937
|
+
const excludedBy = new Map();
|
|
935
938
|
/** @type {Set<string>} */
|
|
936
939
|
const listedOk = new Set();
|
|
937
940
|
|
|
@@ -943,12 +946,9 @@ async function createAllowBridge(allow, o) {
|
|
|
943
946
|
children.push(client.child);
|
|
944
947
|
const signed = new Set(allow.get(name));
|
|
945
948
|
const listed = new Set(mcpTools.map(t => t.name));
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
}
|
|
950
|
-
for (const t of signed) if (!listed.has(t)) missing.push({ server: name, tool: t });
|
|
951
|
-
connected.push(name);
|
|
949
|
+
toolsBy.set(name, wrapTools(name, mcpTools.filter(t => signed.has(t.name)), client.rpc, o.callTimeout));
|
|
950
|
+
excludedBy.set(name, mcpTools.filter(t => !signed.has(t.name)).map(t => [`${name}_${t.name}`, { server: name, tool: t.name }]));
|
|
951
|
+
missingBy.set(name, [...signed].filter(t => !listed.has(t)).map(t => ({ server: name, tool: t })));
|
|
952
952
|
listedOk.add(name);
|
|
953
953
|
} catch (err) {
|
|
954
954
|
errors.push({ server: name, error: err.message });
|
|
@@ -956,9 +956,22 @@ async function createAllowBridge(allow, o) {
|
|
|
956
956
|
}));
|
|
957
957
|
|
|
958
958
|
// Every signed tool of a server that was not found / failed / was rejected by confirmServer is missing.
|
|
959
|
+
/** @type {Array<{server: string, tool: string}>} */
|
|
960
|
+
const missing = [];
|
|
959
961
|
for (const [server, list] of allow) {
|
|
960
|
-
if (
|
|
962
|
+
if (listedOk.has(server)) missing.push(...(missingBy.get(server) || []));
|
|
963
|
+
else for (const tool of list) missing.push({ server, tool });
|
|
964
|
+
}
|
|
965
|
+
const keyOrder = [...allow.keys()];
|
|
966
|
+
/** @type {string[]} */
|
|
967
|
+
const connected = keyOrder.filter(n => listedOk.has(n));
|
|
968
|
+
/** @type {Map<string, {server: string, tool: string}>} */
|
|
969
|
+
const excluded = new Map();
|
|
970
|
+
for (const n of connected) {
|
|
971
|
+
tools.push(...(toolsBy.get(n) || []));
|
|
972
|
+
for (const [k, v] of excludedBy.get(n) || []) excluded.set(k, v);
|
|
961
973
|
}
|
|
974
|
+
errors.sort((x, y) => keyOrder.indexOf(x.server) - keyOrder.indexOf(y.server));
|
|
962
975
|
|
|
963
976
|
if (errors.length > 0) console.warn('[MCP Bridge] Some servers failed to connect:', errors);
|
|
964
977
|
|
|
@@ -7,7 +7,7 @@ const { requestWithTemperatureFallback } = require('./provider-temperature');
|
|
|
7
7
|
const { normalizeStopReason } = require('./provider-stop-reason');
|
|
8
8
|
const { resolveTimeoutMs, applyRequestBounds, guardResponseSettles } = require('./provider-http');
|
|
9
9
|
const { hasUsageSignal } = require('./provider-usage');
|
|
10
|
-
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking } = require('./thinking-mode');
|
|
10
|
+
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking, warnTemperatureDropped } = require('./thinking-mode');
|
|
11
11
|
|
|
12
12
|
// BA-24: the raw Anthropic usage field names. Presence of any (even value 0) means the API reported a
|
|
13
13
|
// usage signal → build the object; absence of all means no signal → surface null (unpriceable).
|
|
@@ -235,12 +235,7 @@ class AnthropicProvider {
|
|
|
235
235
|
|
|
236
236
|
/** One-time warning (per reason) that this model rejected `temperature` and the request was retried without it (BA-10). */
|
|
237
237
|
_warnTemperatureDropped(reason = 'unsupported') {
|
|
238
|
-
|
|
239
|
-
if (this[flag]) return;
|
|
240
|
-
this[flag] = true;
|
|
241
|
-
console.warn(reason === 'thinking'
|
|
242
|
-
? `[AnthropicProvider] '${this.model}': 'temperature' must be 1 while thinking is on — retrying without it. Further drops from this provider instance are silent.`
|
|
243
|
-
: `[AnthropicProvider] '${this.model}' rejected a non-default 'temperature' (unsupported/deprecated) — retrying without it. Further drops from this provider instance are silent.`);
|
|
238
|
+
warnTemperatureDropped({ owner: this, label: 'AnthropicProvider', model: this.model, reason });
|
|
244
239
|
}
|
|
245
240
|
|
|
246
241
|
/**
|
|
@@ -44,6 +44,21 @@ export class FallbackProvider {
|
|
|
44
44
|
providers: import("../types").Provider[];
|
|
45
45
|
shouldFallback: (error: any, index: number) => boolean;
|
|
46
46
|
onFallback: ((error: any, fromIndex: number, toIndex: number) => void) | null;
|
|
47
|
+
/**
|
|
48
|
+
* True when ANY member owns its own turn cycle (e.g. CLIPipe native tool mode), so the Loop's
|
|
49
|
+
* construction-time guards for options a native member would leave silently dead (assemble/trim,
|
|
50
|
+
* checkArgs) fire through the chain — the chain may fall through to that member at any call.
|
|
51
|
+
* @type {boolean}
|
|
52
|
+
*/
|
|
53
|
+
get ownsCycle(): boolean;
|
|
54
|
+
/**
|
|
55
|
+
* True when some cycle-owning member carries NO policy of its own. A Loop-level `policy` never reaches a
|
|
56
|
+
* native member's tool calls, so it is only safe when every such member is gated itself; the Loop's
|
|
57
|
+
* policy guard reads this (mirrors its direct-provider rule `ownsCycle && !provider.policy`). A nested
|
|
58
|
+
* chain member answers through its own `ungatedCycleOwner`.
|
|
59
|
+
* @type {boolean}
|
|
60
|
+
*/
|
|
61
|
+
get ungatedCycleOwner(): boolean;
|
|
47
62
|
/**
|
|
48
63
|
* Generate using first available provider.
|
|
49
64
|
* @param {Message[]} messages
|
package/src/provider-fallback.js
CHANGED
|
@@ -39,6 +39,27 @@ class FallbackProvider {
|
|
|
39
39
|
this.onFallback = options.onFallback || null;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* True when ANY member owns its own turn cycle (e.g. CLIPipe native tool mode), so the Loop's
|
|
44
|
+
* construction-time guards for options a native member would leave silently dead (assemble/trim,
|
|
45
|
+
* checkArgs) fire through the chain — the chain may fall through to that member at any call.
|
|
46
|
+
* @type {boolean}
|
|
47
|
+
*/
|
|
48
|
+
get ownsCycle() {
|
|
49
|
+
return this.providers.some((p) => !!p.ownsCycle);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* True when some cycle-owning member carries NO policy of its own. A Loop-level `policy` never reaches a
|
|
54
|
+
* native member's tool calls, so it is only safe when every such member is gated itself; the Loop's
|
|
55
|
+
* policy guard reads this (mirrors its direct-provider rule `ownsCycle && !provider.policy`). A nested
|
|
56
|
+
* chain member answers through its own `ungatedCycleOwner`.
|
|
57
|
+
* @type {boolean}
|
|
58
|
+
*/
|
|
59
|
+
get ungatedCycleOwner() {
|
|
60
|
+
return this.providers.some((p) => p.ungatedCycleOwner ?? (!!p.ownsCycle && !p.policy));
|
|
61
|
+
}
|
|
62
|
+
|
|
42
63
|
/**
|
|
43
64
|
* Generate using first available provider.
|
|
44
65
|
* @param {Message[]} messages
|
package/src/provider-gemini.js
CHANGED
|
@@ -7,7 +7,7 @@ const { requestWithTemperatureFallback } = require('./provider-temperature');
|
|
|
7
7
|
const { normalizeStopReason } = require('./provider-stop-reason');
|
|
8
8
|
const { resolveTimeoutMs, applyRequestBounds, guardResponseSettles } = require('./provider-http');
|
|
9
9
|
const { hasUsageSignal } = require('./provider-usage');
|
|
10
|
-
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking } = require('./thinking-mode');
|
|
10
|
+
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking, warnTemperatureDropped } = require('./thinking-mode');
|
|
11
11
|
|
|
12
12
|
// BA-24: raw Gemini usageMetadata fields. Any present (even 0) ⇒ a usage signal; none ⇒ null.
|
|
13
13
|
const GEMINI_USAGE_KEYS = ['promptTokenCount', 'candidatesTokenCount', 'thoughtsTokenCount', 'cachedContentTokenCount'];
|
|
@@ -179,12 +179,7 @@ class GeminiProvider {
|
|
|
179
179
|
|
|
180
180
|
/** One-time warning (per reason) that this model rejected `temperature` and the request was retried without it (BA-10). */
|
|
181
181
|
_warnTemperatureDropped(reason = 'unsupported') {
|
|
182
|
-
|
|
183
|
-
if (this[flag]) return;
|
|
184
|
-
this[flag] = true;
|
|
185
|
-
console.warn(reason === 'thinking'
|
|
186
|
-
? `[GeminiProvider] '${this.model}': 'temperature' must be 1 while thinking is on — retrying without it. Further drops from this provider instance are silent.`
|
|
187
|
-
: `[GeminiProvider] '${this.model}' rejected a non-default 'temperature' (unsupported/deprecated) — retrying without it. Further drops from this provider instance are silent.`);
|
|
182
|
+
warnTemperatureDropped({ owner: this, label: 'GeminiProvider', model: this.model, reason });
|
|
188
183
|
}
|
|
189
184
|
|
|
190
185
|
/**
|
package/src/provider-ollama.js
CHANGED
|
@@ -7,7 +7,7 @@ const { normalizeStopReason } = require('./provider-stop-reason');
|
|
|
7
7
|
const { resolveTimeoutMs, applyRequestBounds, guardResponseSettles } = require('./provider-http');
|
|
8
8
|
const { hasUsageSignal } = require('./provider-usage');
|
|
9
9
|
const { parseToolCalls } = require('./provider-toolcalls');
|
|
10
|
-
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking } = require('./thinking-mode');
|
|
10
|
+
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking, warnTemperatureDropped } = require('./thinking-mode');
|
|
11
11
|
|
|
12
12
|
// BA-24: raw Ollama usage fields. Any present (even 0) ⇒ a usage signal; none ⇒ null (unpriceable).
|
|
13
13
|
const OLLAMA_USAGE_KEYS = ['prompt_eval_count', 'eval_count'];
|
|
@@ -144,12 +144,7 @@ class OllamaProvider {
|
|
|
144
144
|
|
|
145
145
|
/** One-time warning (per reason) that this model rejected `temperature` and the request was retried without it (BA-10). */
|
|
146
146
|
_warnTemperatureDropped(reason = 'unsupported') {
|
|
147
|
-
|
|
148
|
-
if (this[flag]) return;
|
|
149
|
-
this[flag] = true;
|
|
150
|
-
console.warn(reason === 'thinking'
|
|
151
|
-
? `[OllamaProvider] '${this.model}': 'temperature' must be 1 while thinking is on — retrying without it. Further drops from this provider instance are silent.`
|
|
152
|
-
: `[OllamaProvider] '${this.model}' rejected a non-default 'temperature' (unsupported/deprecated) — retrying without it. Further drops from this provider instance are silent.`);
|
|
147
|
+
warnTemperatureDropped({ owner: this, label: 'OllamaProvider', model: this.model, reason });
|
|
153
148
|
}
|
|
154
149
|
|
|
155
150
|
/**
|
package/src/provider-openai.js
CHANGED
|
@@ -8,7 +8,7 @@ const { normalizeStopReason } = require('./provider-stop-reason');
|
|
|
8
8
|
const { resolveTimeoutMs, applyRequestBounds, guardResponseSettles } = require('./provider-http');
|
|
9
9
|
const { hasUsageSignal } = require('./provider-usage');
|
|
10
10
|
const { parseToolCalls } = require('./provider-toolcalls');
|
|
11
|
-
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking, deepseekDisabledBody, isDeepSeek } = require('./thinking-mode');
|
|
11
|
+
const { normalizeThinkingMode, resolveThinkingMode, requestWithThinkingMode, assessThinking, warnTemperatureDropped, deepseekDisabledBody, isDeepSeek } = require('./thinking-mode');
|
|
12
12
|
|
|
13
13
|
// BA-24: raw OpenAI usage fields. Any present (even 0) ⇒ a usage signal; none ⇒ null (unpriceable).
|
|
14
14
|
const OPENAI_USAGE_KEYS = ['prompt_tokens', 'completion_tokens', 'prompt_tokens_details'];
|
|
@@ -225,12 +225,7 @@ class OpenAIProvider {
|
|
|
225
225
|
|
|
226
226
|
/** One-time warning (per reason) that this model rejected `temperature` and the request was retried without it (BA-10). */
|
|
227
227
|
_warnTemperatureDropped(reason = 'unsupported') {
|
|
228
|
-
|
|
229
|
-
if (this[flag]) return;
|
|
230
|
-
this[flag] = true;
|
|
231
|
-
console.warn(reason === 'thinking'
|
|
232
|
-
? `[OpenAIProvider] '${this.model}': 'temperature' must be 1 while thinking is on — retrying without it. Further drops from this provider instance are silent.`
|
|
233
|
-
: `[OpenAIProvider] '${this.model}' rejected a non-default 'temperature' (unsupported/deprecated) — retrying without it. Further drops from this provider instance are silent.`);
|
|
228
|
+
warnTemperatureDropped({ owner: this, label: 'OpenAIProvider', model: this.model, reason });
|
|
234
229
|
}
|
|
235
230
|
|
|
236
231
|
/**
|
package/src/recurse-env.js
CHANGED
|
@@ -78,7 +78,6 @@ function describeInput(/** @type {string|any[]|null} */ input) {
|
|
|
78
78
|
function makeEnv({ input, kind, node, counter, depth, ctx, opts, provider, child }) {
|
|
79
79
|
const vars = new Map(); const kinds = new Map(); const memo = new Map(); const missingOf = new Map();
|
|
80
80
|
const conc = Number.isInteger(opts.concurrency) && opts.concurrency > 0 ? opts.concurrency : DEFAULT_CONCURRENCY;
|
|
81
|
-
const known = new Set(Array.isArray(input) ? input.map((r) => r.id) : []);
|
|
82
81
|
const canSub = counter.canSpawn(depth);
|
|
83
82
|
const state = { final: /** @type {any} */ (null), wrong: /** @type {string|null} */ (null) };
|
|
84
83
|
let n = 0; let last = ''; let loop = /** @type {any} */ (null); let nudged = false;
|
|
@@ -209,6 +208,9 @@ function makeEnv({ input, kind, node, counter, depth, ctx, opts, provider, child
|
|
|
209
208
|
execute: ({ needle, count }) => {
|
|
210
209
|
if (typeof needle !== 'string' || !needle.trim()) return reject('needle text is empty');
|
|
211
210
|
if (!vars.has(count) || kinds.get(count) !== 'ids') return reject(`count var "${count}" is not a count/ids var`);
|
|
211
|
+
// CODE checks the needle: it must occur literally (case-sensitive substring) in the input text — never model-asserted.
|
|
212
|
+
const inp = vars.get('input'); const pieces = Array.isArray(inp) ? inp.map((/** @type {any} */ x) => x.text) : [inp];
|
|
213
|
+
if (!pieces.some((t) => typeof t === 'string' && t.includes(needle))) return reject('needle text does not occur literally in the input');
|
|
212
214
|
return accept({ needle, count: idsPayload(count) }, missingOf.get(count)); } });
|
|
213
215
|
} else {
|
|
214
216
|
tools.push(
|
package/src/recurse-prompts.d.ts
CHANGED
|
@@ -1,22 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* NB-5 — the decomposition-policy system blurb + few-shot. Prepended to a Family-A worker's system prompt so
|
|
3
|
-
* the model has an in-context example of HOW to split
|
|
4
|
-
* (§4.2/§8):
|
|
5
|
-
*
|
|
3
|
+
* the model has an in-context example of HOW to split. The worker (refineWorker) is offered no delegation tool, so
|
|
4
|
+
* it does the split itself, part by part. Flat-first (§4.2/§8): split flat over a window-sized batch and only split
|
|
5
|
+
* a part again when it is genuinely too large to handle directly. Worked splits are deliberately small —
|
|
6
6
|
* the lift is from showing the SHAPE of a good split, not from volume.
|
|
7
7
|
* @type {string}
|
|
8
8
|
*/
|
|
9
9
|
export const DECOMPOSITION_POLICY: string;
|
|
10
10
|
/**
|
|
11
11
|
* NB-4 / RC-12 — the depth-aware capability-scrub suffix. Deeper workers get a more conservative prompt:
|
|
12
|
-
* "prefer direct action, only delegate if truly necessary."
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* `policy` cap cannot express). At depth 0 there is no suffix (the top-level worker decomposes freely);
|
|
12
|
+
* "prefer direct action, only delegate if truly necessary." The prompt half of the depth
|
|
13
|
+
* scrub (guard #5: the part bareguard's blind `policy` cap cannot express); refineWorker offers no
|
|
14
|
+
* delegation tool, so nothing here names one. At depth 0 there is no suffix (the top-level worker decomposes freely);
|
|
16
15
|
* from depth 1 on, each level nudges harder toward answering directly so recursion contracts toward its base
|
|
17
16
|
* case rather than fanning out without bound.
|
|
18
17
|
* @param {number} depth - The worker's depth (0 = top level).
|
|
19
|
-
* @param {number} maxDepth - The topology ceiling; at `depth >= maxDepth` the
|
|
18
|
+
* @param {number} maxDepth - The topology ceiling; at `depth >= maxDepth` the deepest-level wording is used.
|
|
20
19
|
* @returns {string} A suffix to append to the worker system prompt ('' at depth 0).
|
|
21
20
|
*/
|
|
22
21
|
export function capabilityScrub(depth: number, maxDepth: number): string;
|
package/src/recurse-prompts.js
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* NB-5 — the decomposition-policy system blurb + few-shot. Prepended to a Family-A worker's system prompt so
|
|
11
|
-
* the model has an in-context example of HOW to split
|
|
12
|
-
* (§4.2/§8):
|
|
13
|
-
*
|
|
11
|
+
* the model has an in-context example of HOW to split. The worker (refineWorker) is offered no delegation tool, so
|
|
12
|
+
* it does the split itself, part by part. Flat-first (§4.2/§8): split flat over a window-sized batch and only split
|
|
13
|
+
* a part again when it is genuinely too large to handle directly. Worked splits are deliberately small —
|
|
14
14
|
* the lift is from showing the SHAPE of a good split, not from volume.
|
|
15
15
|
* @type {string}
|
|
16
16
|
*/
|
|
@@ -21,32 +21,29 @@ const DECOMPOSITION_POLICY = [
|
|
|
21
21
|
'- Break the task into independent sub-tasks, each small enough to handle in one focused pass.',
|
|
22
22
|
'- Prefer a FLAT split (several sibling sub-tasks) over a deep one. Only nest — split a sub-task again —',
|
|
23
23
|
' when that single sub-task is itself too large to handle directly.',
|
|
24
|
-
'- When you have a sub-task that is large or independent, delegate it with the `spawn_child` tool: it runs',
|
|
25
|
-
' in a FRESH context window and returns only its result. Do the small/glue parts yourself.',
|
|
26
24
|
'- After the sub-results come back, COMBINE them into one final answer for the original task.',
|
|
27
25
|
'- If you can answer directly without splitting, just do so — decomposition is for tasks too big for one pass.',
|
|
28
26
|
'',
|
|
29
27
|
'Worked example 1 (flat split):',
|
|
30
28
|
' Task: "Summarize the security posture of services A, B, and C."',
|
|
31
|
-
' Good split:
|
|
32
|
-
' then combine the three summaries into one posture report.',
|
|
29
|
+
' Good split: summarize the security posture of service A, then do the same for B, then for C,',
|
|
30
|
+
' one part at a time, then combine the three summaries into one posture report.',
|
|
33
31
|
'',
|
|
34
32
|
'Worked example 2 (nest only on overflow):',
|
|
35
33
|
' Task: "Count matching records across a 10,000-line log."',
|
|
36
|
-
' The log is too large for one pass, so split it into chunks and
|
|
37
|
-
' if a chunk is STILL too large,
|
|
34
|
+
' The log is too large for one pass, so split it into chunks and count the matches in each chunk in turn;',
|
|
35
|
+
' if a chunk is STILL too large, split it again. Sum the per-chunk counts in your final answer.',
|
|
38
36
|
].join('\n');
|
|
39
37
|
|
|
40
38
|
/**
|
|
41
39
|
* NB-4 / RC-12 — the depth-aware capability-scrub suffix. Deeper workers get a more conservative prompt:
|
|
42
|
-
* "prefer direct action, only delegate if truly necessary."
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* `policy` cap cannot express). At depth 0 there is no suffix (the top-level worker decomposes freely);
|
|
40
|
+
* "prefer direct action, only delegate if truly necessary." The prompt half of the depth
|
|
41
|
+
* scrub (guard #5: the part bareguard's blind `policy` cap cannot express); refineWorker offers no
|
|
42
|
+
* delegation tool, so nothing here names one. At depth 0 there is no suffix (the top-level worker decomposes freely);
|
|
46
43
|
* from depth 1 on, each level nudges harder toward answering directly so recursion contracts toward its base
|
|
47
44
|
* case rather than fanning out without bound.
|
|
48
45
|
* @param {number} depth - The worker's depth (0 = top level).
|
|
49
|
-
* @param {number} maxDepth - The topology ceiling; at `depth >= maxDepth` the
|
|
46
|
+
* @param {number} maxDepth - The topology ceiling; at `depth >= maxDepth` the deepest-level wording is used.
|
|
50
47
|
* @returns {string} A suffix to append to the worker system prompt ('' at depth 0).
|
|
51
48
|
*/
|
|
52
49
|
function capabilityScrub(depth, maxDepth) {
|
|
@@ -63,8 +60,8 @@ function capabilityScrub(depth, maxDepth) {
|
|
|
63
60
|
return [
|
|
64
61
|
'',
|
|
65
62
|
`DEPTH ${depth} of ${maxDepth} — you are already inside a delegated sub-task. PREFER DIRECT ACTION:`,
|
|
66
|
-
'answer this sub-task yourself if you reasonably can. Only
|
|
67
|
-
'it is genuinely too large to handle in one pass. Keep the
|
|
63
|
+
'answer this sub-task yourself if you reasonably can. Only split it further when a part of',
|
|
64
|
+
'it is genuinely too large to handle in one pass. Keep the splitting shallow.',
|
|
68
65
|
].join('\n');
|
|
69
66
|
}
|
|
70
67
|
|
package/src/thinking-mode.d.ts
CHANGED
|
@@ -154,6 +154,20 @@ export function warnThinkingStatus({ owner, label, model, mode, status, reason }
|
|
|
154
154
|
status: ThinkingStatus;
|
|
155
155
|
reason?: string | undefined;
|
|
156
156
|
}): void;
|
|
157
|
+
/**
|
|
158
|
+
* Warn ONCE per provider instance (per reason) that a non-default `temperature` was stripped and the call retried.
|
|
159
|
+
* @param {object} p
|
|
160
|
+
* @param {any} p.owner - provider instance (holds the warn-once flags)
|
|
161
|
+
* @param {string} p.label
|
|
162
|
+
* @param {string} p.model
|
|
163
|
+
* @param {string} [p.reason] - 'thinking' ("must be 1 while thinking is on"), else unsupported/deprecated
|
|
164
|
+
*/
|
|
165
|
+
export function warnTemperatureDropped({ owner, label, model, reason }: {
|
|
166
|
+
owner: any;
|
|
167
|
+
label: string;
|
|
168
|
+
model: string;
|
|
169
|
+
reason?: string | undefined;
|
|
170
|
+
}): void;
|
|
157
171
|
/**
|
|
158
172
|
* The DeepSeek body for thinking-ON + a forced tool choice: thinking-on is impossible there (the API
|
|
159
173
|
* 400s), so the request goes out with `thinking:{type:'disabled'}` — the only shape that works with a
|
package/src/thinking-mode.js
CHANGED
|
@@ -345,6 +345,23 @@ function warnThinkingStatus({ owner, label, model, mode, status, reason }) {
|
|
|
345
345
|
console.warn(`[${label}] thinkingMode '${mode}' for ${model}: thinkingStatus '${status}' — ${why}. The result is kept. Further '${status}' occurrences from this provider instance are silent.`);
|
|
346
346
|
}
|
|
347
347
|
|
|
348
|
+
/**
|
|
349
|
+
* Warn ONCE per provider instance (per reason) that a non-default `temperature` was stripped and the call retried.
|
|
350
|
+
* @param {object} p
|
|
351
|
+
* @param {any} p.owner - provider instance (holds the warn-once flags)
|
|
352
|
+
* @param {string} p.label
|
|
353
|
+
* @param {string} p.model
|
|
354
|
+
* @param {string} [p.reason] - 'thinking' ("must be 1 while thinking is on"), else unsupported/deprecated
|
|
355
|
+
*/
|
|
356
|
+
function warnTemperatureDropped({ owner, label, model, reason = 'unsupported' }) {
|
|
357
|
+
const flag = reason === 'thinking' ? '_warnedTempThinking' : '_warnedTempDropped';
|
|
358
|
+
if (owner[flag]) return;
|
|
359
|
+
owner[flag] = true;
|
|
360
|
+
console.warn(reason === 'thinking'
|
|
361
|
+
? `[${label}] '${model}': 'temperature' must be 1 while thinking is on — retrying without it. Further drops from this provider instance are silent.`
|
|
362
|
+
: `[${label}] '${model}' rejected a non-default 'temperature' (unsupported/deprecated) — retrying without it. Further drops from this provider instance are silent.`);
|
|
363
|
+
}
|
|
364
|
+
|
|
348
365
|
/**
|
|
349
366
|
* The outcome of a thinkingMode call: `{thinkingStatus, thinkingApplied}` ready to spread onto a
|
|
350
367
|
* GenerateResult. `unsupported` ⇒ the call ran without our field. Otherwise 'on' ⇒ 'applied' (an
|
|
@@ -436,6 +453,7 @@ module.exports = {
|
|
|
436
453
|
assessThinking,
|
|
437
454
|
appliedOf,
|
|
438
455
|
warnThinkingStatus,
|
|
456
|
+
warnTemperatureDropped,
|
|
439
457
|
deepseekDisabledBody,
|
|
440
458
|
readThinkingSignal,
|
|
441
459
|
isDeepSeek,
|
package/tools/shell.d.ts
CHANGED
|
@@ -20,13 +20,18 @@ type GrepArgs = {
|
|
|
20
20
|
maxMatches?: number | undefined;
|
|
21
21
|
flags?: string | undefined;
|
|
22
22
|
/**
|
|
23
|
-
* - Hard wall-clock ceiling in ms
|
|
23
|
+
* - Hard wall-clock ceiling in ms. The operator sets the limit via
|
|
24
|
+
* `createShellTools({ grepTimeoutMs })` (default 5000); this value can only LOWER it, never raise it
|
|
25
|
+
* (non-finite, zero, negative or absent values use the operator limit). The match runs in a
|
|
24
26
|
* worker thread; on overrun the worker is terminated and the call rejects, so a pattern that slips
|
|
25
27
|
* past `looksCatastrophic` can no longer hang the host event loop. When `canRead` is set it bounds
|
|
26
|
-
* the WHOLE call, the canRead walk included.
|
|
27
|
-
* timer max); non-finite, zero, negative or absent values use the default.
|
|
28
|
+
* the WHOLE call, the canRead walk included.
|
|
28
29
|
*/
|
|
29
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;
|
|
30
35
|
/**
|
|
31
36
|
* - When true, refuses a symlinked ROOT path (thrown, loud)
|
|
32
37
|
* and skips (silently, like any other read error) a file that is or becomes a symlink during the
|
|
@@ -57,7 +62,7 @@ type ToolDef = import("../types").ToolDef;
|
|
|
57
62
|
* Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
|
|
58
63
|
* caller's responsibility via `new Loop({ policy })`.
|
|
59
64
|
*
|
|
60
|
-
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, 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-
|
|
61
66
|
* identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
|
|
62
67
|
* `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
|
|
63
68
|
* (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
|
|
@@ -86,19 +91,25 @@ type ToolDef = import("../types").ToolDef;
|
|
|
86
91
|
* hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
|
|
87
92
|
* time; a path swapped for a symlink between vetting and the worker's read is followed unless
|
|
88
93
|
* `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
|
|
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).
|
|
89
100
|
* `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
|
|
90
101
|
* existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
|
|
91
102
|
* `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
|
|
92
103
|
* (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
104
|
* `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
|
|
94
105
|
* 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
|
|
106
|
+
* under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. The size check and the truncating open are separate steps, so a concurrent writer that grows the file in between is truncated unguarded (a stat-then-open race; the guard is best-effort against a model's own write, not a lock). Lines are counted only on
|
|
96
107
|
* refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
|
|
97
108
|
* (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
|
|
98
109
|
* creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
|
|
99
110
|
* @returns {{tools: ToolDef[]}}
|
|
100
111
|
* @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
|
|
101
|
-
* @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.
|
|
102
113
|
* @example
|
|
103
114
|
* const { tools } = createShellTools();
|
|
104
115
|
* const loop = new Loop({ provider, tools, policy });
|
|
@@ -107,6 +118,8 @@ type ToolDef = import("../types").ToolDef;
|
|
|
107
118
|
declare function createShellTools(options?: {
|
|
108
119
|
noFollowSymlinks?: boolean;
|
|
109
120
|
canRead?: CanRead;
|
|
121
|
+
grepTimeoutMs?: number;
|
|
122
|
+
decode?: "utf8" | "utf8-else-1252";
|
|
110
123
|
shrinkGuard?: true | {
|
|
111
124
|
minOldBytes?: number;
|
|
112
125
|
maxShrinkRatio?: number;
|
|
@@ -148,7 +161,7 @@ declare function resolveToolPath(p: string): string;
|
|
|
148
161
|
* @param {string[]} [providedFiles] - INTERNAL, never from tool args: the `canRead`-vetted file list
|
|
149
162
|
* (passed by grep-worker.js from its own workerData key, set only by `grepPath`).
|
|
150
163
|
*/
|
|
151
|
-
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<{
|
|
152
165
|
hits: {
|
|
153
166
|
file: string;
|
|
154
167
|
line: number;
|
|
@@ -219,7 +232,7 @@ declare const SHRINK_LINE_SCAN_CAP: number;
|
|
|
219
232
|
* `newText` and would corrupt any edit whose replacement contains a `$`. We index + slice, so every byte of
|
|
220
233
|
* `newText` lands verbatim.
|
|
221
234
|
* @param {{path: string, oldText: string, newText: string, maxBytes?: number}} args
|
|
222
|
-
* @param {{noFollowSymlinks?: boolean}} [options]
|
|
235
|
+
* @param {{noFollowSymlinks?: boolean, decode?: 'utf8'|'utf8-else-1252'}} [options]
|
|
223
236
|
* @returns {Promise<string>}
|
|
224
237
|
*/
|
|
225
238
|
declare function editFile({ path: rawPath, oldText, newText, maxBytes }: {
|
|
@@ -229,6 +242,7 @@ declare function editFile({ path: rawPath, oldText, newText, maxBytes }: {
|
|
|
229
242
|
maxBytes?: number;
|
|
230
243
|
}, options?: {
|
|
231
244
|
noFollowSymlinks?: boolean;
|
|
245
|
+
decode?: "utf8" | "utf8-else-1252";
|
|
232
246
|
}): Promise<string>;
|
|
233
247
|
/**
|
|
234
248
|
* ONE shared open path for every file-open site in this module (`shell_read`, `shell_write`,
|
package/tools/shell.js
CHANGED
|
@@ -74,7 +74,7 @@ const DEFAULT_READ_MAX_BYTES = 256 * 1024; // 256 KB
|
|
|
74
74
|
const DEFAULT_WRITE_MAX_BYTES = 5 * 1024 * 1024; // 5 MB — a sanity ceiling on a single write (LLM-authored)
|
|
75
75
|
const DEFAULT_GREP_MAX_MATCHES = 200;
|
|
76
76
|
const MAX_TIMER_MS = 2_147_483_647; // setTimeout's max delay; larger overflows to 1ms
|
|
77
|
-
const DEFAULT_GREP_TIMEOUT_MS = 5_000; //
|
|
77
|
+
const DEFAULT_GREP_TIMEOUT_MS = 5_000; // default operator ceiling on a single grep (createShellTools grepTimeoutMs) — bounds ReDoS
|
|
78
78
|
const DEFAULT_EXEC_TIMEOUT_MS = 30_000;
|
|
79
79
|
const DEFAULT_EXEC_MAX_BUFFER = 1024 * 1024; // 1 MB
|
|
80
80
|
|
|
@@ -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) {
|
|
@@ -736,11 +842,13 @@ function looksCatastrophic(pattern) {
|
|
|
736
842
|
* @property {boolean} [recursive]
|
|
737
843
|
* @property {number} [maxMatches]
|
|
738
844
|
* @property {string} [flags]
|
|
739
|
-
* @property {number} [timeout] - Hard wall-clock ceiling in ms
|
|
845
|
+
* @property {number} [timeout] - Hard wall-clock ceiling in ms. The operator sets the limit via
|
|
846
|
+
* `createShellTools({ grepTimeoutMs })` (default 5000); this value can only LOWER it, never raise it
|
|
847
|
+
* (non-finite, zero, negative or absent values use the operator limit). The match runs in a
|
|
740
848
|
* worker thread; on overrun the worker is terminated and the call rejects, so a pattern that slips
|
|
741
849
|
* past `looksCatastrophic` can no longer hang the host event loop. When `canRead` is set it bounds
|
|
742
|
-
* the WHOLE call, the canRead walk included.
|
|
743
|
-
*
|
|
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).
|
|
744
852
|
* @property {boolean} [noFollowSymlinks] - When true, refuses a symlinked ROOT path (thrown, loud)
|
|
745
853
|
* and skips (silently, like any other read error) a file that is or becomes a symlink during the
|
|
746
854
|
* walk. Threaded into `workerData` so the worker thread's file reads honor it too.
|
|
@@ -773,7 +881,7 @@ async function askCanRead(canRead, abs, isDir, budget) {
|
|
|
773
881
|
try {
|
|
774
882
|
const remaining = budget.deadline - Date.now();
|
|
775
883
|
const exhausted = () => Object.assign(
|
|
776
|
-
new Error(`shell_grep: canRead walk exceeded ${budget.budgetMs}ms time budget — slow or hung canRead. Narrow the root or
|
|
884
|
+
new Error(`shell_grep: canRead walk exceeded ${budget.budgetMs}ms time budget — slow or hung canRead. Narrow the root or simplify the regex; the time limit is set by the operator (grepTimeoutMs).`),
|
|
777
885
|
{ budgetExceeded: true },
|
|
778
886
|
);
|
|
779
887
|
if (remaining <= 0) throw exhausted();
|
|
@@ -835,7 +943,7 @@ async function walkChecked(dir, recursive, canRead, out, budget) {
|
|
|
835
943
|
* @param {string[]} [providedFiles] - INTERNAL, never from tool args: the `canRead`-vetted file list
|
|
836
944
|
* (passed by grep-worker.js from its own workerData key, set only by `grepPath`).
|
|
837
945
|
*/
|
|
838
|
-
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) {
|
|
839
947
|
const resolved = resolveToolPath(rawPath);
|
|
840
948
|
const cap = maxMatches || DEFAULT_GREP_MAX_MATCHES;
|
|
841
949
|
let re;
|
|
@@ -867,7 +975,7 @@ async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches,
|
|
|
867
975
|
try {
|
|
868
976
|
const fh = await openFile('shell_grep', file, fsConstants.O_RDONLY, undefined, { noFollowSymlinks });
|
|
869
977
|
try {
|
|
870
|
-
content = (await fh.readFile()).
|
|
978
|
+
content = decodeBytes(await fh.readFile(), decode).text;
|
|
871
979
|
} finally {
|
|
872
980
|
await fh.close();
|
|
873
981
|
}
|
|
@@ -898,8 +1006,9 @@ async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches,
|
|
|
898
1006
|
* @param {GrepArgs} args
|
|
899
1007
|
* @param {CanRead} [canRead] - opt-in path arbiter (see `createShellTools`); when set the walk runs here
|
|
900
1008
|
* on the main thread and the worker receives only the vetted file list.
|
|
1009
|
+
* @param {number} [grepTimeoutMs] - operator ceiling (validated by `createShellTools`); the model's `timeout` can only lower it.
|
|
901
1010
|
*/
|
|
902
|
-
async function grepPath(args, canRead) {
|
|
1011
|
+
async function grepPath(args, canRead, grepTimeoutMs = DEFAULT_GREP_TIMEOUT_MS, decode = 'utf8') {
|
|
903
1012
|
const { pattern, flags = 'i', timeout, path: rawPath, noFollowSymlinks = false } = args;
|
|
904
1013
|
if (looksCatastrophic(pattern)) {
|
|
905
1014
|
throw new Error(
|
|
@@ -941,12 +1050,15 @@ async function grepPath(args, canRead) {
|
|
|
941
1050
|
|
|
942
1051
|
// Explicit allow-list: model-controlled tool args are NEVER spread into the worker payload.
|
|
943
1052
|
const { recursive, maxMatches } = args;
|
|
944
|
-
const workerArgs = { pattern, path: rawPath, recursive, maxMatches, flags, timeout, noFollowSymlinks };
|
|
1053
|
+
const workerArgs = { pattern, path: rawPath, recursive, maxMatches, flags, timeout, noFollowSymlinks, decode };
|
|
945
1054
|
/** @type {string[]|undefined} */
|
|
946
1055
|
let vettedFiles;
|
|
947
1056
|
// ONE budget for the WHOLE call (canRead walk + worker): the deadline starts before the walk.
|
|
948
|
-
//
|
|
949
|
-
|
|
1057
|
+
// The operator bound (`createShellTools({ grepTimeoutMs })`, validated to (0, 2^31-1]) is the ceiling. The
|
|
1058
|
+
// model can pass `timeout` (the schema hides it but args are spread in): it may only TIGHTEN it —
|
|
1059
|
+
// effective = min(model value, operator bound) — never raise it.
|
|
1060
|
+
const budgetMs = typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0
|
|
1061
|
+
? Math.min(timeout, grepTimeoutMs) : grepTimeoutMs;
|
|
950
1062
|
const callStart = Date.now();
|
|
951
1063
|
const budget = { deadline: Date.now() + budgetMs, budgetMs };
|
|
952
1064
|
if (canRead) {
|
|
@@ -967,7 +1079,7 @@ async function grepPath(args, canRead) {
|
|
|
967
1079
|
const walkMs = Date.now() - callStart;
|
|
968
1080
|
const workerBudgetMs = canRead ? budget.deadline - Date.now() : budgetMs;
|
|
969
1081
|
if (workerBudgetMs <= 0) {
|
|
970
|
-
throw new Error(`shell_grep: canRead walk exceeded ${budgetMs}ms time budget — no time left to search. Narrow the root or
|
|
1082
|
+
throw new Error(`shell_grep: canRead walk exceeded ${budgetMs}ms time budget — no time left to search. Narrow the root or simplify the regex; the time limit is set by the operator (grepTimeoutMs).`);
|
|
971
1083
|
}
|
|
972
1084
|
return new Promise((resolve, reject) => {
|
|
973
1085
|
const worker = new Worker(path.join(__dirname, 'grep-worker.js'), { workerData: { args: workerArgs, files: vettedFiles } });
|
|
@@ -982,7 +1094,7 @@ async function grepPath(args, canRead) {
|
|
|
982
1094
|
const timer = setTimeout(() => {
|
|
983
1095
|
done(reject, new Error(canRead
|
|
984
1096
|
? `shell_grep: exceeded ${budgetMs}ms time budget (shared with the canRead walk, which used ${walkMs}ms) — ` +
|
|
985
|
-
`a slow canRead or a catastrophic regex;
|
|
1097
|
+
`a slow canRead or a catastrophic regex; narrow the root or simplify the regex; the time limit is set by the operator (grepTimeoutMs).`
|
|
986
1098
|
: `shell_grep: pattern exceeded ${budgetMs}ms time budget — likely catastrophic backtracking. ` +
|
|
987
1099
|
`Simplify the regex.`,
|
|
988
1100
|
));
|
|
@@ -1092,7 +1204,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1092
1204
|
* Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
|
|
1093
1205
|
* caller's responsibility via `new Loop({ policy })`.
|
|
1094
1206
|
*
|
|
1095
|
-
* @param {{noFollowSymlinks?: boolean, canRead?: CanRead, 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-
|
|
1096
1208
|
* identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
|
|
1097
1209
|
* `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
|
|
1098
1210
|
* (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
|
|
@@ -1121,19 +1233,25 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1121
1233
|
* hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
|
|
1122
1234
|
* time; a path swapped for a symlink between vetting and the worker's read is followed unless
|
|
1123
1235
|
* `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
|
|
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).
|
|
1124
1242
|
* `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
|
|
1125
1243
|
* existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
|
|
1126
1244
|
* `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
|
|
1127
1245
|
* (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
1246
|
* `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
|
|
1129
1247
|
* 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
|
|
1248
|
+
* under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. The size check and the truncating open are separate steps, so a concurrent writer that grows the file in between is truncated unguarded (a stat-then-open race; the guard is best-effort against a model's own write, not a lock). Lines are counted only on
|
|
1131
1249
|
* refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
|
|
1132
1250
|
* (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
|
|
1133
1251
|
* creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
|
|
1134
1252
|
* @returns {{tools: ToolDef[]}}
|
|
1135
1253
|
* @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
|
|
1136
|
-
* @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.
|
|
1137
1255
|
* @example
|
|
1138
1256
|
* const { tools } = createShellTools();
|
|
1139
1257
|
* const loop = new Loop({ provider, tools, policy });
|
|
@@ -1142,6 +1260,11 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
|
|
|
1142
1260
|
function createShellTools(options = {}) {
|
|
1143
1261
|
const { noFollowSymlinks = false, canRead } = options;
|
|
1144
1262
|
const shrinkGuard = normalizeShrinkGuard(options.shrinkGuard);
|
|
1263
|
+
const decode = normalizeDecode(options.decode);
|
|
1264
|
+
const grepTimeoutMs = options.grepTimeoutMs === undefined ? DEFAULT_GREP_TIMEOUT_MS : options.grepTimeoutMs;
|
|
1265
|
+
if (typeof grepTimeoutMs !== 'number' || !Number.isFinite(grepTimeoutMs) || grepTimeoutMs <= 0 || grepTimeoutMs > MAX_TIMER_MS) {
|
|
1266
|
+
throw new ValidationError(`createShellTools: grepTimeoutMs must be a finite number > 0 and <= ${MAX_TIMER_MS} (got ${typeName(options.grepTimeoutMs)})`);
|
|
1267
|
+
}
|
|
1145
1268
|
if (canRead !== undefined && typeof canRead !== 'function') {
|
|
1146
1269
|
throw new ValidationError(`createShellTools: canRead must be a function (got ${canRead === null ? 'null' : typeof canRead})`);
|
|
1147
1270
|
}
|
|
@@ -1159,7 +1282,7 @@ function createShellTools(options = {}) {
|
|
|
1159
1282
|
required: ['path'],
|
|
1160
1283
|
},
|
|
1161
1284
|
execute: async (/** @type {{path: string, maxBytes?: number}} */ { path: p, maxBytes }) =>
|
|
1162
|
-
readEntry(p, maxBytes, { noFollowSymlinks }),
|
|
1285
|
+
readEntry(p, maxBytes, { noFollowSymlinks, decode }),
|
|
1163
1286
|
},
|
|
1164
1287
|
{
|
|
1165
1288
|
name: 'shell_grep',
|
|
@@ -1175,7 +1298,7 @@ function createShellTools(options = {}) {
|
|
|
1175
1298
|
},
|
|
1176
1299
|
required: ['pattern', 'path'],
|
|
1177
1300
|
},
|
|
1178
|
-
execute: async (/** @type {GrepArgs} */ args) => grepPath({ ...args, noFollowSymlinks }, canRead),
|
|
1301
|
+
execute: async (/** @type {GrepArgs} */ args) => grepPath({ ...args, noFollowSymlinks }, canRead, grepTimeoutMs, decode),
|
|
1179
1302
|
},
|
|
1180
1303
|
{
|
|
1181
1304
|
name: 'shell_write',
|
|
@@ -1219,7 +1342,7 @@ function createShellTools(options = {}) {
|
|
|
1219
1342
|
// The args are model-authored and UNTRUSTED — oldText/newText may be absent (an output-token-capped
|
|
1220
1343
|
// generation), so the boundary type stays loose and editFile enforces the BA-4 contract at runtime.
|
|
1221
1344
|
execute: async (/** @type {{path: string, oldText?: string, newText?: string, maxBytes?: number}} */ args) =>
|
|
1222
|
-
editFile(/** @type {any} */ (args), { noFollowSymlinks }),
|
|
1345
|
+
editFile(/** @type {any} */ (args), { noFollowSymlinks, decode }),
|
|
1223
1346
|
},
|
|
1224
1347
|
{
|
|
1225
1348
|
name: 'shell_run',
|
package/types/index.d.ts
CHANGED
|
@@ -297,6 +297,11 @@ export interface Provider {
|
|
|
297
297
|
* while the run still looked governed. Such a provider must carry its own `policy`.
|
|
298
298
|
*/
|
|
299
299
|
ownsCycle?: boolean;
|
|
300
|
+
/**
|
|
301
|
+
* Set by a composite provider (`FallbackProvider`): true when some cycle-owning member has no `policy` of
|
|
302
|
+
* its own. When present the Loop's policy guard reads it instead of `ownsCycle && !policy`.
|
|
303
|
+
*/
|
|
304
|
+
readonly ungatedCycleOwner?: boolean;
|
|
300
305
|
/** Gate chokepoint for a cycle-owning provider — same contract as `Loop({policy})`. */
|
|
301
306
|
policy?: ((tool: string, args: any, ctx?: any) => any) | null;
|
|
302
307
|
generate(
|