bare-agent 0.60.1 → 0.61.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.
@@ -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`. 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**.
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,7 +1457,7 @@ 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). A `timeout` above 2^31-1 is clamped to 2^31-1 (Node's timer max); non-finite, zero, negative or non-number values use the 5000ms default. Cost on a 5.4k-file tree: ~2.5s → ~3.7s with a real gate. See `poc/f259-grep-canread.mjs`.
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-agent",
3
- "version": "0.60.1",
3
+ "version": "0.61.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.26.0",
115
+ "litectx": "^0.43.1",
116
116
  "typescript": "^5.7.0"
117
117
  }
118
118
  }
package/primitives.json CHANGED
@@ -141,7 +141,7 @@
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[]}",
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
145
  "fails": "throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.",
146
146
  "example": "const { tools } = createShellTools();\nconst loop = new Loop({ provider, tools, policy });\nconst { tools: safeTools } = createShellTools({ noFollowSymlinks: true });"
147
147
  },
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.name || 'unknown'}' owns its own turn cycle, so ${named} can never run `
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
- if (this.provider && this.provider.ownsCycle && this.policy && !this.provider.policy) {
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.name || 'unknown'}' owns its own turn cycle, so Loop-level policy would `
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.name || 'unknown'}' owns its own turn cycle, so checkArgs can never run `
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
- /** @type {string[]} */
930
- const connected = [];
931
- /** @type {Array<{server: string, tool: string}>} */
932
- const missing = [];
933
- /** @type {Map<string, {server: string, tool: string}>} */
934
- const excluded = new Map();
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
- tools.push(...wrapTools(name, mcpTools.filter(t => signed.has(t.name)), client.rpc, o.callTimeout));
947
- for (const t of mcpTools) {
948
- if (!signed.has(t.name)) excluded.set(`${name}_${t.name}`, { server: name, tool: t.name });
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 (!listedOk.has(server)) for (const tool of list) missing.push({ server, tool });
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
- const flag = reason === 'thinking' ? '_warnedTempThinking' : '_warnedTempDropped';
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
@@ -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
@@ -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
- const flag = reason === 'thinking' ? '_warnedTempThinking' : '_warnedTempDropped';
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
  /**
@@ -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
- const flag = reason === 'thinking' ? '_warnedTempThinking' : '_warnedTempDropped';
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
  /**
@@ -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
- const flag = reason === 'thinking' ? '_warnedTempThinking' : '_warnedTempDropped';
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
  /**
@@ -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(
@@ -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 before it is offered the `spawn_child` A-tool. Flat-first
4
- * (§4.2/§8): the model fans out flat over a window-sized batch and only escalates to a nested `spawn_child`
5
- * when a single sub-task is genuinely too large to handle directly. Worked splits are deliberately small —
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." Combined with the inline `canSpawn` check (the
13
- * tool half of the scrub: `depth < maxDepth` withholds `spawn_child` at the cap) in recurse.js, this realizes
14
- * guard #5's prompt+tool-shaping half (the part bareguard's blind
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 `spawn_child` tool is withheld.
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;
@@ -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 before it is offered the `spawn_child` A-tool. Flat-first
12
- * (§4.2/§8): the model fans out flat over a window-sized batch and only escalates to a nested `spawn_child`
13
- * when a single sub-task is genuinely too large to handle directly. Worked splits are deliberately small —
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: spawn_child("Summarize the security posture of service A"), same for B, same for C,',
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 spawn_child a count for each chunk;',
37
- ' if a chunk is STILL too large, that child splits again. Sum the per-chunk counts in your final answer.',
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." Combined with the inline `canSpawn` check (the
43
- * tool half of the scrub: `depth < maxDepth` withholds `spawn_child` at the cap) in recurse.js, this realizes
44
- * guard #5's prompt+tool-shaping half (the part bareguard's blind
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 `spawn_child` tool is withheld.
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 delegate further (spawn_child) when a part of',
67
- 'it is genuinely too large to handle in one pass. Keep the recursion shallow.',
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
 
@@ -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
@@ -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,11 +20,12 @@ type GrepArgs = {
20
20
  maxMatches?: number | undefined;
21
21
  flags?: string | undefined;
22
22
  /**
23
- * - Hard wall-clock ceiling in ms (default 5000). The match runs in a
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. Values above 2^31-1 are clamped to 2^31-1 (Node's
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;
30
31
  /**
@@ -57,7 +58,7 @@ type ToolDef = import("../types").ToolDef;
57
58
  * Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
58
59
  * caller's responsibility via `new Loop({ policy })`.
59
60
  *
60
- * @param {{noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
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-
61
62
  * identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
62
63
  * `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
63
64
  * (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
@@ -86,13 +87,14 @@ type ToolDef = import("../types").ToolDef;
86
87
  * hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
87
88
  * time; a path swapped for a symlink between vetting and the worker's read is followed unless
88
89
  * `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
90
+ * `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.
89
91
  * `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
90
92
  * existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
91
93
  * `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
92
94
  * (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
95
  * `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
94
96
  * 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
97
+ * 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
98
  * refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
97
99
  * (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
98
100
  * creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
@@ -107,6 +109,7 @@ type ToolDef = import("../types").ToolDef;
107
109
  declare function createShellTools(options?: {
108
110
  noFollowSymlinks?: boolean;
109
111
  canRead?: CanRead;
112
+ grepTimeoutMs?: number;
110
113
  shrinkGuard?: true | {
111
114
  minOldBytes?: number;
112
115
  maxShrinkRatio?: number;
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; // hard ceiling on a single grep — bounds ReDoS
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
 
@@ -736,11 +736,12 @@ function looksCatastrophic(pattern) {
736
736
  * @property {boolean} [recursive]
737
737
  * @property {number} [maxMatches]
738
738
  * @property {string} [flags]
739
- * @property {number} [timeout] - Hard wall-clock ceiling in ms (default 5000). The match runs in a
739
+ * @property {number} [timeout] - Hard wall-clock ceiling in ms. The operator sets the limit via
740
+ * `createShellTools({ grepTimeoutMs })` (default 5000); this value can only LOWER it, never raise it
741
+ * (non-finite, zero, negative or absent values use the operator limit). The match runs in a
740
742
  * worker thread; on overrun the worker is terminated and the call rejects, so a pattern that slips
741
743
  * past `looksCatastrophic` can no longer hang the host event loop. When `canRead` is set it bounds
742
- * the WHOLE call, the canRead walk included. Values above 2^31-1 are clamped to 2^31-1 (Node's
743
- * timer max); non-finite, zero, negative or absent values use the default.
744
+ * the WHOLE call, the canRead walk included.
744
745
  * @property {boolean} [noFollowSymlinks] - When true, refuses a symlinked ROOT path (thrown, loud)
745
746
  * and skips (silently, like any other read error) a file that is or becomes a symlink during the
746
747
  * walk. Threaded into `workerData` so the worker thread's file reads honor it too.
@@ -773,7 +774,7 @@ async function askCanRead(canRead, abs, isDir, budget) {
773
774
  try {
774
775
  const remaining = budget.deadline - Date.now();
775
776
  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 raise timeout.`),
777
+ 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
778
  { budgetExceeded: true },
778
779
  );
779
780
  if (remaining <= 0) throw exhausted();
@@ -898,8 +899,9 @@ async function _grepCore({ pattern, path: rawPath, recursive = true, maxMatches,
898
899
  * @param {GrepArgs} args
899
900
  * @param {CanRead} [canRead] - opt-in path arbiter (see `createShellTools`); when set the walk runs here
900
901
  * on the main thread and the worker receives only the vetted file list.
902
+ * @param {number} [grepTimeoutMs] - operator ceiling (validated by `createShellTools`); the model's `timeout` can only lower it.
901
903
  */
902
- async function grepPath(args, canRead) {
904
+ async function grepPath(args, canRead, grepTimeoutMs = DEFAULT_GREP_TIMEOUT_MS) {
903
905
  const { pattern, flags = 'i', timeout, path: rawPath, noFollowSymlinks = false } = args;
904
906
  if (looksCatastrophic(pattern)) {
905
907
  throw new Error(
@@ -945,8 +947,11 @@ async function grepPath(args, canRead) {
945
947
  /** @type {string[]|undefined} */
946
948
  let vettedFiles;
947
949
  // ONE budget for the WHOLE call (canRead walk + worker): the deadline starts before the walk.
948
- // Node clamps setTimeout delays > 2^31-1 (and NaN/Infinity) to 1ms, so clamp here, at the single source.
949
- const budgetMs = typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0 ? Math.min(timeout, MAX_TIMER_MS) : DEFAULT_GREP_TIMEOUT_MS;
950
+ // The operator bound (`createShellTools({ grepTimeoutMs })`, validated to (0, 2^31-1]) is the ceiling. The
951
+ // model can pass `timeout` (the schema hides it but args are spread in): it may only TIGHTEN it —
952
+ // effective = min(model value, operator bound) — never raise it.
953
+ const budgetMs = typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0
954
+ ? Math.min(timeout, grepTimeoutMs) : grepTimeoutMs;
950
955
  const callStart = Date.now();
951
956
  const budget = { deadline: Date.now() + budgetMs, budgetMs };
952
957
  if (canRead) {
@@ -967,7 +972,7 @@ async function grepPath(args, canRead) {
967
972
  const walkMs = Date.now() - callStart;
968
973
  const workerBudgetMs = canRead ? budget.deadline - Date.now() : budgetMs;
969
974
  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 raise timeout.`);
975
+ 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
976
  }
972
977
  return new Promise((resolve, reject) => {
973
978
  const worker = new Worker(path.join(__dirname, 'grep-worker.js'), { workerData: { args: workerArgs, files: vettedFiles } });
@@ -982,7 +987,7 @@ async function grepPath(args, canRead) {
982
987
  const timer = setTimeout(() => {
983
988
  done(reject, new Error(canRead
984
989
  ? `shell_grep: exceeded ${budgetMs}ms time budget (shared with the canRead walk, which used ${walkMs}ms) — ` +
985
- `a slow canRead or a catastrophic regex; raise timeout or simplify the regex.`
990
+ `a slow canRead or a catastrophic regex; narrow the root or simplify the regex; the time limit is set by the operator (grepTimeoutMs).`
986
991
  : `shell_grep: pattern exceeded ${budgetMs}ms time budget — likely catastrophic backtracking. ` +
987
992
  `Simplify the regex.`,
988
993
  ));
@@ -1092,7 +1097,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
1092
1097
  * Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
1093
1098
  * caller's responsibility via `new Loop({ policy })`.
1094
1099
  *
1095
- * @param {{noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
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-
1096
1101
  * identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
1097
1102
  * `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
1098
1103
  * (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
@@ -1121,13 +1126,14 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
1121
1126
  * hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
1122
1127
  * time; a path swapped for a symlink between vetting and the worker's read is followed unless
1123
1128
  * `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
1129
+ * `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.
1124
1130
  * `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
1125
1131
  * existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
1126
1132
  * `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
1127
1133
  * (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
1134
  * `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
1129
1135
  * 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
1136
+ * 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
1137
  * refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
1132
1138
  * (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
1133
1139
  * creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
@@ -1142,6 +1148,10 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
1142
1148
  function createShellTools(options = {}) {
1143
1149
  const { noFollowSymlinks = false, canRead } = options;
1144
1150
  const shrinkGuard = normalizeShrinkGuard(options.shrinkGuard);
1151
+ const grepTimeoutMs = options.grepTimeoutMs === undefined ? DEFAULT_GREP_TIMEOUT_MS : options.grepTimeoutMs;
1152
+ if (typeof grepTimeoutMs !== 'number' || !Number.isFinite(grepTimeoutMs) || grepTimeoutMs <= 0 || grepTimeoutMs > MAX_TIMER_MS) {
1153
+ throw new ValidationError(`createShellTools: grepTimeoutMs must be a finite number > 0 and <= ${MAX_TIMER_MS} (got ${typeName(options.grepTimeoutMs)})`);
1154
+ }
1145
1155
  if (canRead !== undefined && typeof canRead !== 'function') {
1146
1156
  throw new ValidationError(`createShellTools: canRead must be a function (got ${canRead === null ? 'null' : typeof canRead})`);
1147
1157
  }
@@ -1175,7 +1185,7 @@ function createShellTools(options = {}) {
1175
1185
  },
1176
1186
  required: ['pattern', 'path'],
1177
1187
  },
1178
- execute: async (/** @type {GrepArgs} */ args) => grepPath({ ...args, noFollowSymlinks }, canRead),
1188
+ execute: async (/** @type {GrepArgs} */ args) => grepPath({ ...args, noFollowSymlinks }, canRead, grepTimeoutMs),
1179
1189
  },
1180
1190
  {
1181
1191
  name: 'shell_write',
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(