bare-agent 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -485,7 +485,7 @@ if (result.error?.startsWith('halt:')) {
485
485
 
486
486
  **Why four pieces (`policy` + `onLlmResult` + `onToolResult` + `filterTools`).** `policy` runs `gate.check` *before* every tool call. `onLlmResult` fires after every successful `provider.generate` — without it, `budget.maxCostUsd` never sees LLM cost and is silently undercounted for token-heavy / tool-light workloads (every chatbot). It also fires for the out-of-band `ctx.summarize` call (R-C6) tagged `kind:'summarize'`; main-loop rounds carry `kind:'turn'` — so summary-window tokens count against the budget too, and a consumer can tell the two apart. `onToolResult` fires after every `tool.execute` and carries the per-run `ctx` opaque blob into `gate.record` so per-principal accounting works. `filterTools` is a `gate.allows` pre-filter — denied tools are dropped from the catalog the LLM ever sees, no `gate.check` round-trip per call.
487
487
 
488
- `onToolResult` on a tool ERROR records `{error, durationMs}` plus an allow-listed `errorContext` copied from `error.context` — `timeout`/`denied` (boolean), `server`/`tool` (string, ≤200 chars), `timeoutMs` (finite number); wrong-typed values are dropped and `stderr`/everything else is never forwarded (the gate writes the record verbatim into the audit row). The key is absent when no allowed field is present.
488
+ `onToolResult` on a tool ERROR records `{error, durationMs}` plus an allow-listed `errorContext` copied from `error.context` — `timeout`/`denied`/`shrink` (boolean), `server`/`tool` (string, ≤200 chars), `timeoutMs`/`oldBytes`/`newBytes`/`oldLines`/`newLines` (finite number; the last four are BA-30 `shrinkGuard` refusal facts); wrong-typed values are dropped and `stderr`/everything else is never forwarded (the gate writes the record verbatim into the audit row). The key is absent when no allowed field is present.
489
489
 
490
490
  Halt-severity decisions exit the loop cleanly via a typed `HaltError` — full mechanics (sealed `msgs`, `halt:<rule>` error token, `loop:done{halted:true}` event, `throwOnError:true` interaction, `halt:unknown` coalesce) are in the **Halt decisions throw `HaltError`** paragraph below. Short version: check `result.error?.startsWith('halt:')` after the run.
491
491
 
@@ -509,6 +509,26 @@ And **`result.stopReason`** (the neutral value, or `null`) is now present on **e
509
509
 
510
510
  > Note the division of labour with **BA-6**: if the tool call was *cut off* by the output cap, you get `truncated:max_tokens` and the tool is **never executed at all** — that path is closed upstream. `stuck:` covers the residual case: a fully-formed call on an untruncated round that fails for its own reasons — the tool executes and rejects it (bad path, failed validation), or the tool name doesn't exist at all — repeated byte-identically.
511
511
 
512
+ **What the model did when a call went bad (BA-29).** `loop.run()` returns facts, never actions: `badCalls` (array, **key absent when empty**, whole-run, in order) with entries `{ kind, tool, param?, expected?, got?, argBytes?, parsed?, hasAppend, round }` (`round` is 0-based like the `loop:*` event `round`), and `cutOff: { outputTokens, reasoningTokens, maxTokensRequested }` when the run ended `truncated:max_tokens`.
513
+
514
+ ```javascript
515
+ const r = await loop.run(msgs, tools, { maxTokens: 32000 });
516
+ if (r.error === 'truncated:max_tokens') {
517
+ // r.cutOff = { outputTokens: 32000, reasoningTokens: 31400, maxTokensRequested: 32000 } (reasoningTokens null if unreported)
518
+ // r.badCalls = [{ kind: 'cut-off', tool: 'shell_write', parsed: true, argBytes: 300012, hasAppend: true, round: 3 }]
519
+ // -> a complete 300 KB write was the last thing generated and the cap hit; NOT executed. hasAppend says a
520
+ // "write it in parts" instruction is possible with this tool's schema.
521
+ }
522
+ ```
523
+
524
+ - `cut-off`: one entry per call that rode the cut round (`parsed:true`, or one `parsed:false` if its JSON was broken). Never executed (BA-4/BA-6).
525
+ - `malformed-json`: a malformed call on a round that was **not** cut (`parsed:false`); `malformedToolCall` is unchanged and still set.
526
+ - `arg-type` / `arg-missing`: only from `new Loop({ checkArgs: true })` (default off). Before `execute`, top-level only, against `tool.parameters`: `required`, and `properties[x].type` of `string`/`number`/`integer`/`boolean`/`object`/`array` (a `type` array = any-of; unknown/absent type skipped; `null` is type `"null"`; no nesting/`$ref`/coercion). A fault means the tool is **not executed** and the model gets `content must be a string, got object; to send JSON, encode it as one string` (or `content is required`) as a tool error — the same path as a tool throw, so `maxIdenticalToolErrors` still bounds it and `retry` never re-runs it. Per-call order is checkpoint prompt → policy → checkArgs → execute: with a Checkpoint and `checkArgs` both on, a human can approve a call that `checkArgs` then refuses (the gate still audits every attempt). `checkArgs: true` with a cycle-owning provider (CLIPipe `claude-mcp`) throws at construction — no tool call reaches the Loop.
527
+ - `argBytes`: raw `function.arguments` bytes for a malformed call (size only, never content), the **re-serialized** size (`Buffer.byteLength(JSON.stringify(args))`) for a parsed call. `hasAppend`: the tool's `parameters.properties` has an `append` param (unknown tool: `false`). `cutOff.maxTokensRequested` is the per-run `maxTokens` option, `null` when you passed none — never a guessed default.
528
+ - Raw arguments of a cut-round call are never in `badCalls`. Not on `onToolResult`/stream events. Shell tools do not feed it (their refusals are plain tool errors).
529
+ - `usage.reasoningTokens` (and cumulative `metrics.reasoningTokens`): reported by OpenAI-wire (`completion_tokens_details.reasoning_tokens`) and Gemini (`thoughtsTokenCount`); `null` when not reported (Anthropic, Ollama, CLIPipe) — never 0-for-absent. It is a subset of `outputTokens`; pricing is unchanged.
530
+
531
+
512
532
  **Thinking blocks are preserved and replayed (BA-7).** On `claude-sonnet-5` (and Opus 4.7+) **adaptive thinking is the default** — the API returns `thinking` blocks on a good fraction of rounds **whether or not you ask for them** (measured: ~3/10; sending `thinking:{type:'adaptive'}` explicitly changed the rate not at all). Anthropic's contract is that those blocks are echoed back **unchanged, `signature` included**, when a tool-use conversation continues. Before 0.27 bare-agent dropped every one of them, silently — and because the API returns **200** either way, nothing ever surfaced.
513
533
 
514
534
  The blocks now ride the transcript on `Message.providerBlocks` (`{provider, model, blocks}`) and the Anthropic provider replays them at the front of the assistant turn. **You get this for free — no flag.** Two things to know if you touch the transcript yourself: the blocks are **opaque** (keep the bytes; don't rebuild them from parsed fields — a `redacted_thinking` block won't survive it), and they are **tagged with the model that signed them** — a signature is model-bound, so swapping models mid-transcript drops them rather than sending a signature the new model will reject. If you persist and replay transcripts, keep `providerBlocks` intact through your serializer.
@@ -998,7 +1018,7 @@ All return `{ text, toolCalls, usage: { inputTokens, outputTokens }, model?, cos
998
1018
 
999
1019
  **Error body (v0.11.0):** on an HTTP error the OpenAI/Anthropic/Ollama providers throw a `ProviderError` whose `message` carries the upstream error string. The full parsed response is **not** attached to `err.body` by default (so an unexpected field can't leak through logs that dump the error object). Pass `{ exposeErrorBody: true }` to attach it for debugging.
1000
1020
 
1001
- **Malformed tool-call arguments (BA-27):** when an OpenAI-compatible or Ollama model emits `function.arguments` that is not valid JSON, the provider returns `toolCalls: []` plus a `malformedToolCall: { name, error }` marker (round still metered; JSON never repaired); `Loop.run()` surfaces the same marker on its result. Pass `{ exposeMalformedArgs: true }` (OpenAI/Ollama; default off, independent of `exposeErrorBody`) to also get `malformedToolCall.rawArguments` — the FULL raw arguments string, verbatim and uncapped (since 0.50.0; earlier it was the first 500 chars plus `rawTruncated`, which hid the broken tail). Model-generated and possibly large or sensitive: bare-agent only returns it to you and never logs it, but anything you forward it to (logs, audit rows) is your call. `rawTruncated` is deprecated and never set.
1021
+ **Malformed tool-call arguments (BA-27):** when an OpenAI-compatible or Ollama model emits `function.arguments` that is not valid JSON, the provider returns `toolCalls: []` plus a `malformedToolCall: { name, error, argBytes }` marker (`argBytes` = raw arguments byte length, size only, always present since BA-29; round still metered; JSON never repaired); `Loop.run()` surfaces the same marker on its result. Pass `{ exposeMalformedArgs: true }` (OpenAI/Ollama; default off, independent of `exposeErrorBody`) to also get `malformedToolCall.rawArguments` — the FULL raw arguments string, verbatim and uncapped (since 0.50.0; earlier it was the first 500 chars plus `rawTruncated`, which hid the broken tail). Model-generated and possibly large or sensitive: bare-agent only returns it to you and never logs it, but anything you forward it to (logs, audit rows) is your call. `rawTruncated` is deprecated and never set.
1002
1022
 
1003
1023
  **Request/idle timeout (BA-18, v0.34.0):** the four http(s) providers (Anthropic, OpenAI, Gemini, Ollama) accept a `timeoutMs` option — constructor default **600000 (10 min)**, overridable per call via `generate(..., { timeoutMs })`, and `0`/`Infinity` disables it. Before this they wired only `req.on('error')`, so a socket the server silently dropped — or a response that never starts — hung `generate()` until the OS TCP timeout (~2h): a hang, not an error, so retry/casualty policy above it never fired. `timeoutMs` bounds on socket **inactivity** (`req.setTimeout`), so a slow-but-streaming response is not killed — only a silent/never-answering socket trips it; the 10-min default clears any single non-streaming completion (TTFB ≈ generation time). On trip, `generate()` rejects with a retryable `TimeoutError` (`code: 'ETIMEDOUT'`, `context.bound: 'idle'`, `retryable: true`). **Retry is caller-side and already wired:** `new Loop({ provider, retry: new Retry() })` wraps `provider.generate`, and `DEFAULT_RETRY_ON` classifies `ETIMEDOUT` (and `ECONNRESET`/`ENOTFOUND`/429/5xx) as transient — so a wired `Retry` retries a timed-out request and rethrows under `retryOn: () => false`, with no extra wiring (`run-plan`'s `stepRetry` is a second consumer of the same seam). CLIPipe already bounded its child process (`timeout`, default 30000 for one-shot) and is unchanged.
1004
1024
 
@@ -1464,12 +1484,16 @@ Mobile tools follow the observe-act pattern: action tools auto-return a fresh sn
1464
1484
 
1465
1485
  > **Path canonicalization + symlink refusal, together.** bareguard >=0.19.0 already realpath-resolves the checked path and every scope root on each call, so a symlink under an allowed scope that resolves outside it is denied (`fs.<scope>.symlinkEscape`; dangling → `danglingSymlink`). bareguard 0.19.2 additionally requires the scope ROOTS themselves not be, or sit under, a symlink: `new Gate` throws otherwise, and a root swapped for a symlink later denies `fs.readScope.symlinkRoot` / `fs.writeScope.symlinkRoot` — list real paths (e.g. `fs.realpathSync(os.tmpdir())`; on macOS `/tmp` and `os.tmpdir()` are symlinks). The checked path must ALSO pass a lexical check (`within(path, scopeRoot)`) before the resolved one, so its lexical form must lie under a realpath'd scope root: with a symlinked `$HOME`, `~/x` expands (via `resolveToolPath`, which does not realpath) to `<symlink>/x` and is DENIED against a realpath'd home scope — fail-closed, a usability gap not a leak; pass the real path. bare-agent canonicalizes the path (`~` + resolve, via `resolveToolPath`) before the gate check and opens that same path — this closes a *different* gap (the gate judging a `~`/relative path in a different form than the one the tool opens), not the symlink-containment gap, which is bareguard's job. `noFollowSymlinks` refuses a symlinked final path *component* at open time. Together they narrow but do not close the check-then-open window, and neither covers hardlinks.
1466
1486
  >
1487
+ > **Wrong-typed arguments (BA-29, default ON, messages only):** `shell_write`'s `content` and `shell_edit`'s `newText`/`oldText` refusals name the received type (`object`, `array`, `number`, `boolean`, `null`); for an object/array they add `to send JSON, encode it as one string`; and the BA-4 "output was cut short, retry" sentence is kept **only** for an *absent* argument (it is the truncated-call signature, and was wrong advice for a model that sent JSON as a JSON object — it retried byte-identically into `stuck:shell_write`). Still a throw, file untouched, no coercion. For a generic pre-`execute` check on any tool, see `Loop({ checkArgs: true })`.
1488
+
1467
1489
  > **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.
1468
1490
  >
1469
1491
  > **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`.
1470
1492
  >
1471
1493
  > **`resolveToolPath(p)`** — exported alongside `createShellTools` from `bare-agent/tools`. THE canonicalizer every shell file tool applies internally before opening: expand `~`/`~/…` via `os.homedir()` (throws rather than silently degrading `~/x` to `/x` when no home directory can be determined), then `path.resolve` against `process.cwd()`. Idempotent; rejects a non-string/empty path (thrown, naming only the type/category of the bad value, never the value itself) — every file tool routes through it, so `shell_read`/`shell_grep` with `""` now error instead of silently reading/searching `process.cwd()`. Call it in your `actionTranslator` on `args.path` before returning the gated action, so the string the gate judges is the exact string the tool opens.
1472
1494
 
1495
+ > **Opt-in `shrinkGuard` (BA-30) — refuse a whole-file `shell_write` that would gut an existing file.** `createShellTools({ shrinkGuard: true })` (= `{ minOldBytes: 2048, maxShrinkRatio: 0.5 }`; an object overrides either, plus `guardPath(absPath) => boolean | Promise<boolean>` — `false` skips the guard for that file, e.g. a worker's own earlier output). `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter. Bytes decide: if the existing file is `>= minOldBytes` and the new content is `< old * maxShrinkRatio`, the write is refused (a thrown `ToolError`, so `maxIdenticalToolErrors` applies) and the file is left byte-identical. The message names the old/new bytes and lines and points at `shell_edit`, `append:true`, or `content:''`; `error.context` is `{ shrink: true, oldBytes, newBytes, oldLines, newLines }` — numbers only, no path or content — and `wireGate`'s `errorContext` forwards those five fields to the audit row. Skipped for `append:true`, `content:''`, a new file, and a non-regular target. There is deliberately no override flag the model can set. Size is measured at call time (`lstat` under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on refusal, with a bounded read (`N+ lines` when capped). A throwing or non-boolean `guardPath` rejects the write (type only); `HaltError` propagates. Unset is byte-identical; `false` is off (same as unset); any other shape throws `ValidationError` at creation. `shell_edit` is unaffected.
1496
+
1473
1497
  > **⚠️ `shell_write` requires `content` — and a gate cannot cover for it (v0.27+).** `content` used to default to `''`, so a tool call that OMITTED it silently overwrote the target with **zero bytes** and returned `"wrote 0 bytes to <path>"` as success. That is the ordinary shape of a model hitting its **output-token cap** mid-generation on a long file — observed live emptying a 1789-line source file. **No policy can catch it:** a 0-byte write is a *legal* write, and bareguard's `fs` primitive judges `{type:'write', path}` without inspecting the body (the gate correctly `allow`s it). `shell_write` now **rejects** an absent, `null`, or non-string `content` and leaves the file byte-identical; the error tells the model to retry with the full content. An explicit `content: ""` still empties the file — that one is deliberate.
1474
1498
 
1475
1499
  > **`shell_edit` — the surgical write (BA-13).** Changing one line of an 800-line file with `shell_write` forces the model to re-emit **all 800 lines** as tool-call JSON: an output-token tax ∝ file size (output is the expensive token class), paid on every revision, and the maximal broken-tree surface (a truncated rewrite mangles the lines it never meant to touch — the BA-4/BA-6 class). `shell_edit({path, oldText, newText})` emits only the anchor + replacement. Semantics worth knowing: `oldText` must match **exactly once** (a 0/2+ match is a refusal *returned as the tool result*, so the loop continues and the model widens the anchor — not a throw, so a repeated-identical miss is bounded by maxTurns/budget, not the spin guard); missing/empty `oldText` or missing/non-string `newText` **throw** (BA-4 guards; `newText:""` is a legal deletion); the write is **atomic** (sibling temp + rename, mode preserved) so an fs failure never leaves a partial file; and `newText` is a **literal splice** (a `$&`/`$1` in it lands verbatim, unlike `String.replace`). Gate it exactly like `shell_write` but as `{type:'edit'}` — **bareguard gates `edit` by the same `fs.writeScope` as `write` with zero config** (its FS primitive's `FS_TYPES` already includes `edit`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-agent",
3
- "version": "0.57.0",
3
+ "version": "0.59.0",
4
4
  "files": [
5
5
  "index.js",
6
6
  "index.d.ts",
package/primitives.json CHANGED
@@ -141,8 +141,8 @@
141
141
  "category": "tools",
142
142
  "when": "you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps",
143
143
  "import": "import { createShellTools } from 'bare-agent/tools'",
144
- "signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead}) => {tools: ToolDef[]}",
145
- "fails": "never throws at creation; 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.",
144
+ "signature": "createShellTools(options?: {noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}) => {tools: ToolDef[]}",
145
+ "fails": "throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.",
146
146
  "example": "const { tools } = createShellTools();\nconst loop = new Loop({ provider, tools, policy });\nconst { tools: safeTools } = createShellTools({ noFollowSymlinks: true });"
147
147
  },
148
148
  {
@@ -47,6 +47,8 @@ function safeStringify(value) {
47
47
  // its result verbatim to the audit log. Anything not listed here, or of the wrong type, is dropped.
48
48
  const ERROR_CONTEXT_KEYS = /** @type {const} */ ({
49
49
  timeout: 'boolean', denied: 'boolean', server: 'string', tool: 'string', timeoutMs: 'number',
50
+ // BA-30 shrinkGuard refusal facts (numbers/boolean only — never a path or content).
51
+ shrink: 'boolean', oldBytes: 'number', newBytes: 'number', oldLines: 'number', newLines: 'number',
50
52
  });
51
53
  const ERROR_CONTEXT_MAX_STR = 200;
52
54
 
@@ -0,0 +1,20 @@
1
+ export type ArgFault = {
2
+ kind: "arg-type" | "arg-missing";
3
+ param: string;
4
+ expected?: string;
5
+ got: string;
6
+ message: string;
7
+ };
8
+ /**
9
+ * @typedef {{ kind: 'arg-type'|'arg-missing', param: string, expected?: string, got: string, message: string }} ArgFault
10
+ */
11
+ /**
12
+ * @param {{ parameters?: any }} tool
13
+ * @param {any} args - the parsed arguments (anything; a non-object is read as having no params)
14
+ * @returns {ArgFault|null} the first fault, or null when the call is fine / unchecked
15
+ */
16
+ export function checkToolArgs(tool: {
17
+ parameters?: any;
18
+ }, args: any): ArgFault | null;
19
+ /** JSON type name of a parsed value. @param {any} v @returns {string} */
20
+ export function jsonType(v: any): string;
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * BA-29 — `Loop({ checkArgs: true })`: a tiny, dependency-free, TOP-LEVEL argument check against a tool's
5
+ * declared `parameters` (JSON-Schema-shaped). It exists for one failure: a model that sends the wrong
6
+ * JSON TYPE for a param (an object where a string is declared — seen live on a compat server) or drops a
7
+ * required one. The tool is not executed; the refusal goes back to the model through the same path as a
8
+ * tool throw, so `maxIdenticalToolErrors` still bounds it.
9
+ *
10
+ * Deliberately NOT a schema validator: no nested schemas, no `$ref`/`oneOf`/`enum`/`format`, no coercion.
11
+ * A `type` this file does not know (or none) is SKIPPED, never guessed. `type` may be an array = any-of.
12
+ * `integer` is `Number.isInteger`. `null` is its own type, `"null"`. Only the FIRST fault is reported
13
+ * (required-missing first, in `required` order; then type mismatches in `properties` order).
14
+ */
15
+
16
+ const KNOWN = new Set(['string', 'number', 'integer', 'boolean', 'object', 'array']);
17
+
18
+ /** JSON type name of a parsed value. @param {any} v @returns {string} */
19
+ function jsonType(v) {
20
+ if (v === null) return 'null';
21
+ if (Array.isArray(v)) return 'array';
22
+ return typeof v;
23
+ }
24
+
25
+ /** @param {any} v @param {string} type */
26
+ function matches(v, type) {
27
+ switch (type) {
28
+ case 'string': return typeof v === 'string';
29
+ case 'number': return typeof v === 'number';
30
+ case 'integer': return Number.isInteger(v);
31
+ case 'boolean': return typeof v === 'boolean';
32
+ case 'object': return v !== null && typeof v === 'object' && !Array.isArray(v);
33
+ case 'array': return Array.isArray(v);
34
+ default: return false;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * @typedef {{ kind: 'arg-type'|'arg-missing', param: string, expected?: string, got: string, message: string }} ArgFault
40
+ */
41
+
42
+ /**
43
+ * @param {{ parameters?: any }} tool
44
+ * @param {any} args - the parsed arguments (anything; a non-object is read as having no params)
45
+ * @returns {ArgFault|null} the first fault, or null when the call is fine / unchecked
46
+ */
47
+ function checkToolArgs(tool, args) {
48
+ const schema = tool && tool.parameters;
49
+ if (!schema || typeof schema !== 'object') return null;
50
+ const obj = args !== null && typeof args === 'object' && !Array.isArray(args) ? args : {};
51
+ const props = schema.properties && typeof schema.properties === 'object' ? schema.properties : {};
52
+ const own = (/** @type {any} */ o, /** @type {string} */ k) => Object.prototype.hasOwnProperty.call(o, k);
53
+ /** @param {string} p */
54
+ const declared = (p) => {
55
+ const t = own(props, p) && props[p] ? props[p].type : undefined;
56
+ const list = Array.isArray(t) ? t : typeof t === 'string' ? [t] : null;
57
+ return list && list.length > 0 && list.every((x) => typeof x === 'string' && (KNOWN.has(x) || x === 'null')) ? list : null;
58
+ };
59
+
60
+ if (Array.isArray(schema.required)) {
61
+ for (const p of schema.required) {
62
+ if (typeof p !== 'string') continue;
63
+ if (!own(obj, p) || obj[p] === undefined) {
64
+ const t = declared(p);
65
+ return { kind: 'arg-missing', param: p, ...(t && { expected: t.join(' or ') }), got: 'undefined', message: `${p} is required` };
66
+ }
67
+ }
68
+ }
69
+ for (const p of Object.keys(props)) {
70
+ if (!own(obj, p) || obj[p] === undefined) continue; // absent + optional ⇒ fine
71
+ const list = declared(p);
72
+ if (!list) continue; // unknown/absent type ⇒ skip
73
+ const v = obj[p];
74
+ if (list.some((t) => (t === 'null' ? v === null : matches(v, t)))) continue;
75
+ const got = jsonType(v);
76
+ const expected = list.join(' or ');
77
+ const encode = list.length === 1 && list[0] === 'string' && (got === 'object' || got === 'array')
78
+ ? '; to send JSON, encode it as one string' : '';
79
+ return { kind: 'arg-type', param: p, expected, got, message: `${p} must be a ${expected}, got ${got}${encode}` };
80
+ }
81
+ return null;
82
+ }
83
+
84
+ module.exports = { checkToolArgs, jsonType };
package/src/loop.d.ts CHANGED
@@ -5,6 +5,8 @@ export type ToolCall = import("../types").ToolCall;
5
5
  export type Usage = import("../types").Usage;
6
6
  export type RunMetrics = import("../types").RunMetrics;
7
7
  export type GenerateResult = import("../types").GenerateResult;
8
+ export type BadCall = import("../types").BadCall;
9
+ export type CutOff = import("../types").CutOff;
8
10
  export type Store = import("../types").Store;
9
11
  export type Checkpoint = import("./checkpoint").Checkpoint;
10
12
  export type Retry = import("./retry").Retry;
@@ -68,6 +70,10 @@ export type LoopOptions = {
68
70
  cacheWriteMult?: number;
69
71
  } | undefined;
70
72
  onToolResult?: Function | undefined;
73
+ /**
74
+ * - BA-29, opt-in. Before `execute`, check the call's args against the tool's declared `parameters` — TOP-LEVEL only: a missing `required` param, or a JSON type mismatch on a declared `string`/`number`/`integer`/`boolean`/`object`/`array` (a `type` array = any-of; an unknown/absent type is skipped; no nesting, no `$ref`/`oneOf`, no coercion). A fault means the tool is NOT executed and the refusal (`<param> must be a <type>, got <type>`, or `<param> is required`) flows through the SAME path as a tool throw — tool-result message, `loop:tool_result`, `onToolResult` error, and the `maxIdenticalToolErrors` count. Each refusal is recorded in the run return's `badCalls`. Per-call order is checkpoint prompt → policy → checkArgs → execute: with a Checkpoint and checkArgs both on, a human can approve a call that checkArgs then refuses (the gate still audits every attempt). Throws at construction with a cycle-owning (`ownsCycle`) provider — no tool call reaches the Loop, so it could never run. Default off: many caller schemas are loose.
75
+ */
76
+ checkArgs?: boolean | undefined;
71
77
  /**
72
78
  * - BA-12 safety net (default 3). Short-circuit the run when a
73
79
  * tool's `execute` throws this many times IN A ROW for a BYTE-IDENTICAL call (same tool + same args). A
@@ -126,6 +132,7 @@ export class Loop {
126
132
  policy: Function | null;
127
133
  maxConsecutiveDenials: number;
128
134
  maxIdenticalToolErrors: number;
135
+ checkArgs: boolean;
129
136
  assemble: Function | null;
130
137
  trim: Function | null;
131
138
  onLlmResult: Function | null;
@@ -167,7 +174,7 @@ export class Loop {
167
174
  * thunk is re-evaluated each round (D4/eval-assist F2) so a tool set that grows mid-run — e.g. a skill
168
175
  * unlocking its tools — is offered on the next round; a static array is resolved once at wire time.
169
176
  * @param {Record<string, any>} [options={}] - Per-run overrides (system, temperature, ctx, etc.).
170
- * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
177
+ * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], badCalls?: BadCall[], cutOff?: CutOff, temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
171
178
  * On halt the returned `error` is `halt:<rule>` (or `halt:unknown` if the
172
179
  * thrown HaltError carried no `rule`), and `msgs` is sanitized so any
173
180
  * dangling assistant `tool_calls` from the halted round are paired with
@@ -206,6 +213,8 @@ export class Loop {
206
213
  msgs: Message[];
207
214
  metrics: RunMetrics;
208
215
  malformedToolCall?: GenerateResult["malformedToolCall"];
216
+ badCalls?: BadCall[];
217
+ cutOff?: CutOff;
209
218
  temperatureDropped?: boolean;
210
219
  thinkingApplied?: boolean | null;
211
220
  thinkingStatus?: "applied" | "unsupported" | "ignored" | "unknown";
@@ -237,7 +246,7 @@ export class Loop {
237
246
  * @param {string} text - User message.
238
247
  * @param {ToolDef[]} [tools=[]] - Tool definitions.
239
248
  * @param {Record<string, any>} [options={}] - Per-run overrides.
240
- * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
249
+ * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], badCalls?: BadCall[], cutOff?: CutOff, temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
241
250
  */
242
251
  chat(text: string, tools?: ToolDef[], options?: Record<string, any>): Promise<{
243
252
  text: string;
@@ -250,6 +259,8 @@ export class Loop {
250
259
  msgs: Message[];
251
260
  metrics: RunMetrics;
252
261
  malformedToolCall?: GenerateResult["malformedToolCall"];
262
+ badCalls?: BadCall[];
263
+ cutOff?: CutOff;
253
264
  temperatureDropped?: boolean;
254
265
  thinkingApplied?: boolean | null;
255
266
  thinkingStatus?: "applied" | "unsupported" | "ignored" | "unknown";
package/src/loop.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const { ToolError, HaltError } = require('./errors');
4
4
  const { classifyStopReason } = require('./provider-stop-reason');
5
5
  const { appliedOf } = require('./thinking-mode');
6
+ const { checkToolArgs } = require('./check-args');
6
7
 
7
8
  // Worst-wins precedence for the run's `thinkingStatus`. Null-prototype so a provider-supplied
8
9
  // status string like 'constructor' cannot match an inherited key.
@@ -16,6 +17,8 @@ const THINKING_STATUS_RANK = Object.assign(Object.create(null), { applied: 0, un
16
17
  /** @typedef {import('../types').Usage} Usage */
17
18
  /** @typedef {import('../types').RunMetrics} RunMetrics */
18
19
  /** @typedef {import('../types').GenerateResult} GenerateResult */
20
+ /** @typedef {import('../types').BadCall} BadCall */
21
+ /** @typedef {import('../types').CutOff} CutOff */
19
22
  /** @typedef {import('../types').Store} Store */
20
23
  /** @typedef {import('./checkpoint').Checkpoint} Checkpoint */
21
24
  /** @typedef {import('./retry').Retry} Retry */
@@ -64,6 +67,7 @@ const THINKING_STATUS_RANK = Object.assign(Object.create(null), { applied: 0, un
64
67
  * (rateSource:'caller') instead of the built-in guesstimate. There is NO per-model rate table — bring
65
68
  * your own rate, or take a flagged guesstimate (haiku/sonnet recognized, else the Sonnet-tier default).
66
69
  * @property {Function} [onToolResult]
70
+ * @property {boolean} [checkArgs=false] - BA-29, opt-in. Before `execute`, check the call's args against the tool's declared `parameters` — TOP-LEVEL only: a missing `required` param, or a JSON type mismatch on a declared `string`/`number`/`integer`/`boolean`/`object`/`array` (a `type` array = any-of; an unknown/absent type is skipped; no nesting, no `$ref`/`oneOf`, no coercion). A fault means the tool is NOT executed and the refusal (`<param> must be a <type>, got <type>`, or `<param> is required`) flows through the SAME path as a tool throw — tool-result message, `loop:tool_result`, `onToolResult` error, and the `maxIdenticalToolErrors` count. Each refusal is recorded in the run return's `badCalls`. Per-call order is checkpoint prompt → policy → checkArgs → execute: with a Checkpoint and checkArgs both on, a human can approve a call that checkArgs then refuses (the gate still audits every attempt). Throws at construction with a cycle-owning (`ownsCycle`) provider — no tool call reaches the Loop, so it could never run. Default off: many caller schemas are loose.
67
71
  * @property {number} [maxIdenticalToolErrors] - BA-12 safety net (default 3). Short-circuit the run when a
68
72
  * tool's `execute` throws this many times IN A ROW for a BYTE-IDENTICAL call (same tool + same args). A
69
73
  * tool error is deliberately fed back to the model so it can recover — that is the point of the feedback
@@ -323,6 +327,11 @@ class Loop {
323
327
  throw new Error('[Loop] options.maxIdenticalToolErrors must be a non-negative number (0 or Infinity disables)');
324
328
  }
325
329
  this.maxIdenticalToolErrors = options.maxIdenticalToolErrors != null ? options.maxIdenticalToolErrors : 3;
330
+ // BA-29: opt-in top-level argument check (see LoopOptions.checkArgs). Strictly boolean when given.
331
+ if (options.checkArgs != null && typeof options.checkArgs !== 'boolean') {
332
+ throw new Error('[Loop] options.checkArgs must be a boolean');
333
+ }
334
+ this.checkArgs = options.checkArgs === true;
326
335
  if (options.assemble != null && typeof options.assemble !== 'function') {
327
336
  throw new Error('[Loop] options.assemble must be a function (msgs, info) => msgs');
328
337
  }
@@ -360,6 +369,14 @@ class Loop {
360
369
  + '(e.g. new CLIPipeProvider({ toolProtocol: \'claude-mcp\', policy })).',
361
370
  );
362
371
  }
372
+ // BA-29: same rule for `checkArgs` — it runs per tool call inside the Loop, and with a cycle-owning
373
+ // provider no tool call ever reaches the Loop, so it would be accepted and silently never run.
374
+ if (this.provider && this.provider.ownsCycle && this.checkArgs) {
375
+ throw new Error(
376
+ `[Loop] provider '${this.provider.name || 'unknown'}' owns its own turn cycle, so checkArgs can never run `
377
+ + '(no tool call reaches the Loop). Remove the option, or use a provider whose cycle the Loop drives.',
378
+ );
379
+ }
363
380
  if (options.onLlmResult != null && typeof options.onLlmResult !== 'function') {
364
381
  throw new Error('[Loop] options.onLlmResult must be a function');
365
382
  }
@@ -461,7 +478,7 @@ class Loop {
461
478
  * thunk is re-evaluated each round (D4/eval-assist F2) so a tool set that grows mid-run — e.g. a skill
462
479
  * unlocking its tools — is offered on the next round; a static array is resolved once at wire time.
463
480
  * @param {Record<string, any>} [options={}] - Per-run overrides (system, temperature, ctx, etc.).
464
- * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
481
+ * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], badCalls?: BadCall[], cutOff?: CutOff, temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
465
482
  * On halt the returned `error` is `halt:<rule>` (or `halt:unknown` if the
466
483
  * thrown HaltError carried no `rule`), and `msgs` is sanitized so any
467
484
  * dangling assistant `tool_calls` from the halted round are paired with
@@ -567,6 +584,27 @@ class Loop {
567
584
  // as `toolCalls: []`. Reset each completed round; a malformed round always terminates the run (no
568
585
  // usable call to continue with), so it can only be non-null on the round that returns.
569
586
  let lastMalformedToolCall = null;
587
+ // BA-29: facts about bad tool calls, accumulated over the WHOLE run and surfaced ONLY on the return
588
+ // (`badCalls`, key absent when empty; `cutOff`, only when the run ended at the output cap). Never on
589
+ // events or onToolResult. Facts, not actions: nothing here changes what executes.
590
+ /** @type {BadCall[]} */
591
+ const badCalls = [];
592
+ /** @type {CutOff|null} */
593
+ let cutOff = null;
594
+ const toolHasAppend = (/** @type {any} */ name) => {
595
+ const t = typeof name === 'string' ? toolMap.get(name) : undefined;
596
+ const props = t && t.parameters && t.parameters.properties;
597
+ return !!props && typeof props === 'object' && Object.prototype.hasOwnProperty.call(props, 'append');
598
+ };
599
+ // RE-SERIALIZED size of a parsed call's args (what the model sent, approximately — key order/escapes
600
+ // may differ from the wire bytes). Unserializable ⇒ 0.
601
+ const parsedArgBytes = (/** @type {any} */ args) => {
602
+ try { const j = JSON.stringify(args); return typeof j === 'string' ? Buffer.byteLength(j, 'utf8') : 0; } catch { return 0; }
603
+ };
604
+ const badCallFields = () => ({
605
+ ...(badCalls.length > 0 && { badCalls: badCalls.slice() }),
606
+ ...(cutOff && { cutOff: { ...cutOff } }),
607
+ });
570
608
  // BA-10: sticky across rounds — true if ANY round's `temperature` was dropped by the model (400,
571
609
  // unsupported/deprecated) and retried without it. Surfaced on the result so an upstream receipt
572
610
  // (recurse's refineLeaf) can report the EFFECTIVE temperature rather than the ignored request.
@@ -609,7 +647,7 @@ class Loop {
609
647
  sealDanglingToolCalls(msgs, `[halted:${stuckTag}]`);
610
648
  this._reportError('stuck', new Error(`tool "${tc.name}" failed ${identicalErrors} times with identical arguments`), { rule: stuckTag, attempts: identicalErrors });
611
649
  this._safeEmit({ type: 'loop:done', data: { text: lastText, stuck: true, rule: stuckTag, cost: totalCost } });
612
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: stuckTag, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
650
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: stuckTag, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
613
651
  }
614
652
  return null;
615
653
  };
@@ -633,6 +671,9 @@ class Loop {
633
671
  /** @type {Record<string, number>} */
634
672
  byTool: {},
635
673
  tokens: { input: 0, output: 0, cacheCreation: 0, cacheRead: 0 },
674
+ // BA-29: cumulative reasoning tokens = sum of rounds that REPORTED a count; null until one does.
675
+ /** @type {number|null} */
676
+ reasoningTokens: null,
636
677
  unpricedRounds: 0,
637
678
  // BA-21 — priced rounds whose rate was a built-in guesstimate (rateSource:'tier' or 'default'), i.e.
638
679
  // no provider cost and no caller `rates`. Not unpriced (they DID price and count against budget); a
@@ -664,6 +705,7 @@ class Loop {
664
705
  metrics.tokens.output += u.outputTokens || 0;
665
706
  metrics.tokens.cacheCreation += u.cacheCreationTokens || 0;
666
707
  metrics.tokens.cacheRead += u.cacheReadTokens || 0;
708
+ if (Number.isFinite(u.reasoningTokens)) metrics.reasoningTokens = (metrics.reasoningTokens || 0) + /** @type {number} */ (u.reasoningTokens);
667
709
  };
668
710
  /** Snapshot the meter for a return — finalizes the run-scoped fields. @returns {RunMetrics} */
669
711
  const finalizeMetrics = () => ({
@@ -672,6 +714,7 @@ class Loop {
672
714
  toolCalls: metrics.toolCalls,
673
715
  byTool: metrics.byTool,
674
716
  tokens: { ...metrics.tokens },
717
+ reasoningTokens: metrics.reasoningTokens, // BA-29 — sum of reported rounds, null if none reported
675
718
  costUsd: pricedAny ? totalCost : null,
676
719
  unpricedRounds: metrics.unpricedRounds,
677
720
  estimatedRounds: metrics.estimatedRounds, // BA-21 — rounds priced off the built-in guesstimate
@@ -856,7 +899,7 @@ class Loop {
856
899
  this._reportError('provider', err, { round });
857
900
  if (this.throwOnError) throw err;
858
901
  // BA-5: a mid-run provider failure must not erase the work of the rounds that succeeded.
859
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: err.message, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
902
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: err.message, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
860
903
  }
861
904
 
862
905
  lastUsage = result.usage || lastUsage;
@@ -963,7 +1006,7 @@ class Loop {
963
1006
  sealDanglingToolCalls(msgs, `[halted:${session.error}]`);
964
1007
  this._reportError('session', new Error(`provider session terminated: ${session.error}`), { rule: session.error, sessionTurns: session.turns ?? null });
965
1008
  this._safeEmit({ type: 'loop:done', data: { text: lastText, rule: session.error, sessionTurns: session.turns ?? null, cost: totalCost } });
966
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: session.error, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1009
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: session.error, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
967
1010
  }
968
1011
 
969
1012
  // BA-13: classify this round's terminal signal against the neutral stop-reason vocabulary. BA-6
@@ -1002,6 +1045,13 @@ class Loop {
1002
1045
  this._safeEmit({ type: 'loop:resume', data: { round, stopReason: lastStopReason } });
1003
1046
  continue;
1004
1047
  }
1048
+ // BA-29: a malformed call on a round that was NOT cut at the cap. (On a cut round the same call is
1049
+ // recorded once, as `cut-off` with parsed:false, below — never as two entries.) `argBytes` is the
1050
+ // raw-argument SIZE from the provider's marker; no content, no repair, nothing executes.
1051
+ if (terminal !== 'truncated' && lastMalformedToolCall) {
1052
+ const m = /** @type {any} */ (lastMalformedToolCall);
1053
+ badCalls.push({ kind: 'malformed-json', tool: typeof m.name === 'string' ? m.name : null, parsed: false, argBytes: Number.isFinite(m.argBytes) ? m.argBytes : 0, hasAppend: toolHasAppend(m.name), round });
1054
+ }
1005
1055
  if (terminal) {
1006
1056
  // terminal ∈ {'truncated','refusal','context_exceeded'} — a non-clean terminal round. Error-tag it
1007
1057
  // (NOT just surface stopReason): `recurse`'s worker path and the bareloop adopter both branch on
@@ -1015,6 +1065,24 @@ class Loop {
1015
1065
  // unpriced-round precedent). The awaited result already error-tags it (BA-13); this surfaces it
1016
1066
  // to a stream consumer and to the console without reading the return value.
1017
1067
  if (terminal === 'truncated') {
1068
+ // BA-29: facts about what the cut dropped. ONE `cut-off` entry per call riding the round (a
1069
+ // complete call that was merely last is `parsed:true`; a malformed one is ONE `parsed:false`
1070
+ // entry). Never executed (BA-4/BA-6), raw args never included. `cutOff` is the round's token
1071
+ // facts; `maxTokensRequested` is the per-run `maxTokens` option the Loop handed the provider —
1072
+ // no provider exposes an instance default, so unset ⇒ null (never a guessed default).
1073
+ for (const call of (result.toolCalls || [])) {
1074
+ badCalls.push({ kind: 'cut-off', tool: typeof call.name === 'string' ? call.name : null, parsed: true, argBytes: parsedArgBytes(call.arguments), hasAppend: toolHasAppend(call.name), round });
1075
+ }
1076
+ if (lastMalformedToolCall) {
1077
+ const m = /** @type {any} */ (lastMalformedToolCall);
1078
+ badCalls.push({ kind: 'cut-off', tool: typeof m.name === 'string' ? m.name : null, parsed: false, argBytes: Number.isFinite(m.argBytes) ? m.argBytes : 0, hasAppend: toolHasAppend(m.name), round });
1079
+ }
1080
+ const mt = options.maxTokens;
1081
+ cutOff = {
1082
+ outputTokens: result.usage && Number.isFinite(result.usage.outputTokens) ? result.usage.outputTokens : null,
1083
+ reasoningTokens: result.usage && Number.isFinite(result.usage.reasoningTokens) ? /** @type {number} */ (result.usage.reasoningTokens) : null,
1084
+ maxTokensRequested: typeof mt === 'number' && Number.isFinite(mt) && mt > 0 ? mt : null,
1085
+ };
1018
1086
  this._safeEmit({ type: 'loop:truncated', data: { round, stopReason: lastStopReason, droppedToolCalls: dropped, outputTokens: lastUsage && lastUsage.outputTokens } });
1019
1087
  if (!this._warnedTruncated) {
1020
1088
  this._warnedTruncated = true;
@@ -1028,7 +1096,7 @@ class Loop {
1028
1096
  msgs.push({ role: 'assistant', content: result.text });
1029
1097
  }
1030
1098
  this._safeEmit({ type: 'loop:done', data: { text: lastText, ...(terminal === 'truncated' && { truncated: true }), terminal, stopReason: lastStopReason, droppedToolCalls: dropped, cost: totalCost } });
1031
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: errorTag, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1099
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: errorTag, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1032
1100
  }
1033
1101
 
1034
1102
  // No tool calls — LLM gave a final text response
@@ -1048,7 +1116,7 @@ class Loop {
1048
1116
  try { await flush(msgs, ctx); }
1049
1117
  catch (err) { if (err instanceof HaltError) throw err; this._reportError('trim-flush', err, { round }); }
1050
1118
  }
1051
- return { text: result.text, toolCalls: [], usage: lastUsage, cost: totalCost, error: null, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1119
+ return { text: result.text, toolCalls: [], usage: lastUsage, cost: totalCost, error: null, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1052
1120
  }
1053
1121
 
1054
1122
  // Execute tool calls
@@ -1157,7 +1225,7 @@ class Loop {
1157
1225
  sealDanglingToolCalls(msgs, `[halted:${denyTag}]`);
1158
1226
  this._reportError('denied', new Error(`policy denied ${consecutiveDenials} consecutive tool calls (${tc.name})`), { rule: denyTag, denials: consecutiveDenials });
1159
1227
  this._safeEmit({ type: 'loop:done', data: { text: lastText, denied: true, rule: denyTag, cost: totalCost } });
1160
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: denyTag, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1228
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: denyTag, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1161
1229
  }
1162
1230
  continue;
1163
1231
  }
@@ -1171,6 +1239,17 @@ class Loop {
1171
1239
  let toolResult;
1172
1240
  let toolError;
1173
1241
  try {
1242
+ // BA-29: opt-in argument check. A fault THROWS here, inside the same try as `execute`, so the
1243
+ // refusal takes the exact tool-throw path below (tool-result message, loop:tool_result,
1244
+ // onToolResult error, recordToolFailure/maxIdenticalToolErrors). It sits OUTSIDE `retry.call`: a
1245
+ // refused call is never re-run. The tool is not executed.
1246
+ if (this.checkArgs) {
1247
+ const fault = checkToolArgs(tool, tc.arguments);
1248
+ if (fault) {
1249
+ badCalls.push({ kind: fault.kind, tool: tc.name, param: fault.param, ...(fault.expected && { expected: fault.expected }), got: fault.got, round, hasAppend: toolHasAppend(tc.name) });
1250
+ throw new Error(fault.message);
1251
+ }
1252
+ }
1174
1253
  const execute = () => tool.execute(tc.arguments);
1175
1254
  toolResult = this.retry ? await this.retry.call(execute) : await execute();
1176
1255
  const content = typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult);
@@ -1231,7 +1310,7 @@ class Loop {
1231
1310
  // BA-5: the rule tag survives on `error`; so does the work. A halt is how a bounded attempt is
1232
1311
  // SUPPOSED to end — the caller reads `error` to know it was bounded and `text` to learn from it.
1233
1312
  this._safeEmit({ type: 'loop:done', data: { text: lastText, halted: true, rule, cost: totalCost } });
1234
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: `halt:${rule}`, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1313
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: `halt:${rule}`, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1235
1314
  }
1236
1315
  throw err;
1237
1316
  }
@@ -1261,20 +1340,20 @@ class Loop {
1261
1340
  const rule = err.rule || 'unknown';
1262
1341
  this._reportError('halt', err, { rule, reason: err.decision?.reason ?? null });
1263
1342
  this._safeEmit({ type: 'loop:done', data: { text: lastText, halted: true, rule, cost: totalCost } });
1264
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: `halt:${rule}`, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1343
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: `halt:${rule}`, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1265
1344
  }
1266
1345
  this._reportError('trim-flush', err, { phase: 'stop' });
1267
1346
  }
1268
1347
  }
1269
1348
  this._safeEmit({ type: 'loop:done', data: { text: lastText, stopped: true, cost: totalCost } });
1270
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: null, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1349
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: null, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1271
1350
  }
1272
1351
 
1273
1352
  // Hard safety limit — should never fire under normal usage; bareguard's
1274
1353
  // limits.maxTurns (or the LLM's natural completion) ends the loop first.
1275
1354
  const warning = `[Loop] hit internal safety limit of ${HARD_ROUND_LIMIT} rounds. Wire bareguard for proper governance — see bare-agent/bareguard.`;
1276
1355
  this._safeEmit({ type: 'loop:done', data: { text: lastText, warning, cost: totalCost } });
1277
- return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: warning, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields() };
1356
+ return { text: lastText, toolCalls: [], usage: lastUsage, cost: totalCost, error: warning, stopReason: lastStopReason, model: lastModel, msgs, metrics: finalizeMetrics(), ...(lastMalformedToolCall && { malformedToolCall: lastMalformedToolCall }), ...(temperatureDropped && { temperatureDropped: true }), ...thinkingFields(), ...badCallFields() };
1278
1357
  }
1279
1358
 
1280
1359
  /**
@@ -1347,7 +1426,7 @@ class Loop {
1347
1426
  * @param {string} text - User message.
1348
1427
  * @param {ToolDef[]} [tools=[]] - Tool definitions.
1349
1428
  * @param {Record<string, any>} [options={}] - Per-run overrides.
1350
- * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
1429
+ * @returns {Promise<{text: string, toolCalls: ToolCall[], usage: Usage, cost: number, error: string|null, stopReason: string|null, model: string|null, msgs: Message[], metrics: RunMetrics, malformedToolCall?: GenerateResult['malformedToolCall'], badCalls?: BadCall[], cutOff?: CutOff, temperatureDropped?: boolean, thinkingApplied?: boolean|null, thinkingStatus?: 'applied'|'unsupported'|'ignored'|'unknown'}>}
1351
1430
  */
1352
1431
  async chat(text, tools = [], options = {}) {
1353
1432
  this._history.push({ role: 'user', content: text });
@@ -225,6 +225,7 @@ class AnthropicProvider {
225
225
  outputTokens: data.usage.output_tokens || 0,
226
226
  cacheReadTokens: data.usage.cache_read_input_tokens || 0,
227
227
  cacheCreationTokens: data.usage.cache_creation_input_tokens || 0,
228
+ reasoningTokens: null, // BA-29: Anthropic does not report a separate thinking count
228
229
  }
229
230
  : null,
230
231
  ...(temperatureDropped && { temperatureDropped: true }),
@@ -449,6 +449,7 @@ function createSessionStream({ onTurn, ctx, startedAt, onHalt, turnCap = null, o
449
449
  const usage = {
450
450
  inputTokens: Number(u.input_tokens) || 0,
451
451
  outputTokens: Number(u.output_tokens) || 0,
452
+ reasoningTokens: null, // BA-29: the CLI stream reports no separate reasoning count
452
453
  };
453
454
  // Omit an absent tier rather than emit a synthetic 0 (per the Usage contract).
454
455
  if (Number.isFinite(u.cache_read_input_tokens)) usage.cacheReadTokens = u.cache_read_input_tokens;
@@ -139,7 +139,7 @@ function mapClaudeMeta(outer) {
139
139
  const raw = hasUsageSignal(outer.usage, CLAUDE_USAGE_KEYS) ? outer.usage : null;
140
140
  /** @type {import('../types').Usage|null} */
141
141
  const usage = raw
142
- ? { inputTokens: Number(raw.input_tokens) || 0, outputTokens: Number(raw.output_tokens) || 0 }
142
+ ? { inputTokens: Number(raw.input_tokens) || 0, outputTokens: Number(raw.output_tokens) || 0, reasoningTokens: null } // BA-29: not reported
143
143
  : null;
144
144
  // Absent cache tiers mean the model didn't cache — omit rather than emit a synthetic 0 (per Usage docs).
145
145
  if (usage && Number.isFinite(raw.cache_read_input_tokens)) usage.cacheReadTokens = raw.cache_read_input_tokens;
@@ -101,7 +101,7 @@ function subtractUsage(total, streamed) {
101
101
  const at = (/** @type {keyof import('../types').Usage} */ k) =>
102
102
  Math.max(0, (Number(total[k]) || 0) - sum(k));
103
103
  /** @type {import('../types').Usage} */
104
- const out = { inputTokens: at('inputTokens'), outputTokens: at('outputTokens') };
104
+ const out = { inputTokens: at('inputTokens'), outputTokens: at('outputTokens'), reasoningTokens: null /* BA-29: not reported */ };
105
105
  // Only report a cache tier the session actually had — an absent tier stays absent, never a
106
106
  // synthetic 0 (the Usage contract).
107
107
  if (total.cacheReadTokens !== undefined) out.cacheReadTokens = at('cacheReadTokens');
@@ -380,7 +380,7 @@ class CLIPipeProvider {
380
380
  outputTokens: a.outputTokens + (t.outputTokens || 0),
381
381
  cacheReadTokens: a.cacheReadTokens + (t.cacheReadTokens || 0),
382
382
  cacheCreationTokens: a.cacheCreationTokens + (t.cacheCreationTokens || 0),
383
- }), { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0 })
383
+ }), { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0, reasoningTokens: null /* BA-29: not reported */ })
384
384
  : null);
385
385
 
386
386
  const { stopReason, error } = resolveSessionError({
@@ -206,6 +206,9 @@ class GeminiProvider {
206
206
  outputTokens: (u?.candidatesTokenCount || 0) + (u?.thoughtsTokenCount || 0),
207
207
  cacheReadTokens: cacheRead,
208
208
  cacheCreationTokens: 0,
209
+ // BA-29: reported thoughts (`thoughtsTokenCount`) or null — never 0-for-absent. Already FOLDED into
210
+ // `outputTokens` above (unchanged), so this is observability only and pricing is unaffected.
211
+ reasoningTokens: Number.isFinite(u?.thoughtsTokenCount) ? u.thoughtsTokenCount : null,
209
212
  };
210
213
  }
211
214
 
@@ -130,6 +130,7 @@ export class JevProvider {
130
130
  outputTokens: any;
131
131
  cacheReadTokens: number;
132
132
  cacheCreationTokens: number;
133
+ reasoningTokens: null;
133
134
  } | null;
134
135
  /**
135
136
  * @param {string} path @param {Record<string, any>} body @param {number} [timeoutMs=0] @param {number} [deadlineMs=0]
@@ -243,6 +243,7 @@ class JevProvider {
243
243
  outputTokens: u.output_tokens || 0,
244
244
  cacheReadTokens: 0,
245
245
  cacheCreationTokens: 0,
246
+ reasoningTokens: null, // BA-29: Jev reports no reasoning count
246
247
  };
247
248
  }
248
249
 
@@ -135,7 +135,7 @@ class OllamaProvider {
135
135
  // BA-24: honest null when the response carried no token counts — do NOT manufacture an all-zeros
136
136
  // object (which launders an unpriceable round into a $0 PRICED one).
137
137
  usage: hasUsageSignal(data, OLLAMA_USAGE_KEYS)
138
- ? { inputTokens: data.prompt_eval_count || 0, outputTokens: data.eval_count || 0 }
138
+ ? { inputTokens: data.prompt_eval_count || 0, outputTokens: data.eval_count || 0, reasoningTokens: null } // BA-29: not reported
139
139
  : null,
140
140
  ...(temperatureDropped && { temperatureDropped: true }),
141
141
  ...(thinkingMode && assessThinking({ kind: 'ollama', mode: thinkingMode, data, unsupported: thinkingTrack.unsupported, owner: this, label: 'OllamaProvider', model: this.model })),
@@ -252,6 +252,10 @@ class OpenAIProvider {
252
252
  outputTokens: u?.completion_tokens || 0,
253
253
  cacheReadTokens: cacheRead,
254
254
  cacheCreationTokens: 0,
255
+ // BA-29: reasoning tokens when the vendor REPORTS them (`completion_tokens_details.reasoning_tokens`),
256
+ // else null — never 0-for-absent. A SUBSET of `outputTokens` (`completion_tokens` already includes
257
+ // them), carried for observability only: pricing reads the four tiers above and is unchanged.
258
+ reasoningTokens: Number.isFinite(u?.completion_tokens_details?.reasoning_tokens) ? u.completion_tokens_details.reasoning_tokens : null,
255
259
  };
256
260
  }
257
261
 
@@ -1,5 +1,4 @@
1
1
  export type ToolCall = import("../types").ToolCall;
2
- /** @typedef {import('../types').ToolCall} ToolCall */
3
2
  /**
4
3
  * BA-27 — parse a round's raw tool calls into the neutral {@link ToolCall} shape WITHOUT throwing on
5
4
  * malformed arguments.
@@ -28,7 +27,7 @@ export type ToolCall = import("../types").ToolCall;
28
27
  * @param {any[]} rawToolCalls - provider-native tool-call entries (may be undefined/empty)
29
28
  * @param {(tc: any) => ToolCall} mapOne - maps one raw entry to a ToolCall; MAY throw on bad arguments
30
29
  * @param {{ exposeMalformedArgs?: boolean }} [opts]
31
- * @returns {{ toolCalls: ToolCall[], malformedToolCall?: { name: string|undefined, error: string, rawArguments?: string } }}
30
+ * @returns {{ toolCalls: ToolCall[], malformedToolCall?: { name: string|undefined, error: string, argBytes: number, rawArguments?: string } }}
32
31
  */
33
32
  export function parseToolCalls(rawToolCalls: any[], mapOne: (tc: any) => ToolCall, opts?: {
34
33
  exposeMalformedArgs?: boolean;
@@ -37,6 +36,7 @@ export function parseToolCalls(rawToolCalls: any[], mapOne: (tc: any) => ToolCal
37
36
  malformedToolCall?: {
38
37
  name: string | undefined;
39
38
  error: string;
39
+ argBytes: number;
40
40
  rawArguments?: string;
41
41
  };
42
42
  };
@@ -2,6 +2,20 @@
2
2
 
3
3
  /** @typedef {import('../types').ToolCall} ToolCall */
4
4
 
5
+ /**
6
+ * BA-29: byte length of a raw `function.arguments` value. A string is measured as UTF-8; a non-string
7
+ * (Ollama's already-an-object case) by its JSON form; absent/unserializable ⇒ 0. Size only, never content.
8
+ * @param {any} raw
9
+ * @returns {number}
10
+ */
11
+ function rawArgBytes(raw) {
12
+ if (typeof raw === 'string') return Buffer.byteLength(raw, 'utf8');
13
+ try {
14
+ const s = JSON.stringify(raw);
15
+ return typeof s === 'string' ? Buffer.byteLength(s, 'utf8') : 0;
16
+ } catch { return 0; }
17
+ }
18
+
5
19
  /**
6
20
  * BA-27 — parse a round's raw tool calls into the neutral {@link ToolCall} shape WITHOUT throwing on
7
21
  * malformed arguments.
@@ -30,7 +44,7 @@
30
44
  * @param {any[]} rawToolCalls - provider-native tool-call entries (may be undefined/empty)
31
45
  * @param {(tc: any) => ToolCall} mapOne - maps one raw entry to a ToolCall; MAY throw on bad arguments
32
46
  * @param {{ exposeMalformedArgs?: boolean }} [opts]
33
- * @returns {{ toolCalls: ToolCall[], malformedToolCall?: { name: string|undefined, error: string, rawArguments?: string } }}
47
+ * @returns {{ toolCalls: ToolCall[], malformedToolCall?: { name: string|undefined, error: string, argBytes: number, rawArguments?: string } }}
34
48
  */
35
49
  function parseToolCalls(rawToolCalls, mapOne, opts = {}) {
36
50
  const raw = rawToolCalls || [];
@@ -40,10 +54,13 @@ function parseToolCalls(rawToolCalls, mapOne, opts = {}) {
40
54
  try {
41
55
  toolCalls.push(mapOne(tc));
42
56
  } catch (e) {
43
- /** @type {{ name: string|undefined, error: string, rawArguments?: string }} */
57
+ /** @type {{ name: string|undefined, error: string, argBytes: number, rawArguments?: string }} */
44
58
  const malformedToolCall = {
45
59
  name: tc && tc.function ? tc.function.name : undefined,
46
60
  error: e instanceof Error ? e.message : String(e),
61
+ // BA-29: SIZE only, ALWAYS present (bytes of the raw `function.arguments` — never its content), so a
62
+ // caller can tell a 300 KB cut from a 12-byte typo without the opt-in `rawArguments`.
63
+ argBytes: rawArgBytes(tc && tc.function ? tc.function.arguments : undefined),
47
64
  };
48
65
  if (opts.exposeMalformedArgs) {
49
66
  const rawArgs = tc && tc.function ? tc.function.arguments : undefined;
package/tools/shell.d.ts CHANGED
@@ -6,6 +6,7 @@ declare namespace _exports {
6
6
  export { resolveToolPath };
7
7
  export { _grepCore };
8
8
  export { writeFile as _writeFile };
9
+ export { SHRINK_LINE_SCAN_CAP as _SHRINK_LINE_SCAN_CAP };
9
10
  export { editFile as _editFile };
10
11
  export { openFile as _openFile };
11
12
  export { assertDirStillMatchesHandle as _assertDirStillMatchesHandle };
@@ -56,7 +57,7 @@ type ToolDef = import("../types").ToolDef;
56
57
  * Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
57
58
  * caller's responsibility via `new Loop({ policy })`.
58
59
  *
59
- * @param {{noFollowSymlinks?: boolean, canRead?: CanRead}} [options] - `noFollowSymlinks` (default `false`, byte-
60
+ * @param {{noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
60
61
  * identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
61
62
  * `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
62
63
  * (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
@@ -85,9 +86,19 @@ type ToolDef = import("../types").ToolDef;
85
86
  * hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
86
87
  * time; a path swapped for a symlink between vetting and the worker's read is followed unless
87
88
  * `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
89
+ * `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
90
+ * existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
91
+ * `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
92
+ * (receives the `resolveToolPath`'d path — LEXICAL, not realpath'd, same as `canRead`: `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter; `false` skips the guard for that file; throw/non-boolean rejects, type only;
93
+ * `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
94
+ * Skipped for `append:true`, `content:''`, a new file, and a non-regular target. Size is measured at call time (`lstat`
95
+ * under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on
96
+ * refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
97
+ * (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
98
+ * creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
88
99
  * @returns {{tools: ToolDef[]}}
89
100
  * @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
90
- * @fails never throws at creation; 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.
101
+ * @fails throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.
91
102
  * @example
92
103
  * const { tools } = createShellTools();
93
104
  * const loop = new Loop({ provider, tools, policy });
@@ -96,6 +107,11 @@ type ToolDef = import("../types").ToolDef;
96
107
  declare function createShellTools(options?: {
97
108
  noFollowSymlinks?: boolean;
98
109
  canRead?: CanRead;
110
+ shrinkGuard?: true | {
111
+ minOldBytes?: number;
112
+ maxShrinkRatio?: number;
113
+ guardPath?: (absPath: string) => boolean | Promise<boolean>;
114
+ };
99
115
  }): {
100
116
  tools: ToolDef[];
101
117
  };
@@ -158,7 +174,7 @@ declare function _grepCore({ pattern, path: rawPath, recursive, maxMatches, flag
158
174
  * feeds this UNTRUSTED model-authored args (that is the boundary BA-4 was breached at, and where types buy
159
175
  * nothing).
160
176
  * @param {{path: string, content: string, append?: boolean, maxBytes?: number}} args
161
- * @param {{noFollowSymlinks?: boolean}} [options]
177
+ * @param {{noFollowSymlinks?: boolean, shrinkGuard?: ReturnType<typeof normalizeShrinkGuard>}} [options]
162
178
  * @returns {Promise<string>}
163
179
  */
164
180
  declare function writeFile({ path: rawPath, content, append, maxBytes }: {
@@ -168,7 +184,9 @@ declare function writeFile({ path: rawPath, content, append, maxBytes }: {
168
184
  maxBytes?: number;
169
185
  }, options?: {
170
186
  noFollowSymlinks?: boolean;
187
+ shrinkGuard?: ReturnType<typeof normalizeShrinkGuard>;
171
188
  }): Promise<string>;
189
+ declare const SHRINK_LINE_SCAN_CAP: number;
172
190
  /**
173
191
  * Anchored exact-string replace (BA-13) — the surgical counterpart to the whole-file `shell_write`.
174
192
  * Changing one line of an 800-line file with `shell_write` forces the model to EMIT all 800 lines as
@@ -279,4 +297,14 @@ declare function assertDirStillMatchesHandle(toolName: string, resolvedPath: str
279
297
  * @returns {string}
280
298
  */
281
299
  declare function expandHome(p: string, homedirFn?: () => string): string;
300
+ /**
301
+ * Validate + normalize `createShellTools({ shrinkGuard })`. Throws `ValidationError` naming the TYPE only.
302
+ * @param {any} sg
303
+ * @returns {{minOldBytes: number, maxShrinkRatio: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}|null}
304
+ */
305
+ declare function normalizeShrinkGuard(sg: any): {
306
+ minOldBytes: number;
307
+ maxShrinkRatio: number;
308
+ guardPath?: (absPath: string) => boolean | Promise<boolean>;
309
+ } | null;
282
310
  import fs = require("node:fs/promises");
package/tools/shell.js CHANGED
@@ -66,7 +66,7 @@ const os = require('node:os');
66
66
  const crypto = require('node:crypto');
67
67
  const { exec, execFile } = require('node:child_process');
68
68
  const { Worker } = require('node:worker_threads');
69
- const { HaltError, ValidationError } = require('../src/errors');
69
+ const { HaltError, ValidationError, ToolError } = require('../src/errors');
70
70
 
71
71
  const fsConstants = fs.constants;
72
72
 
@@ -331,6 +331,154 @@ async function readEntry(rawPath, maxBytes, options = {}) {
331
331
  }
332
332
  }
333
333
 
334
+ /**
335
+ * BA-29: the JSON type name of a model-supplied argument, for refusal messages (`array` and `null` are
336
+ * named as such — `typeof` would call both `object`).
337
+ * @param {any} v
338
+ * @returns {string}
339
+ */
340
+ function receivedType(v) {
341
+ return v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v;
342
+ }
343
+
344
+ /**
345
+ * BA-29: the fix-it sentence for a string param that arrived wrong, chosen by what actually arrived. The
346
+ * "output was cut short, retry" hint is the BA-4 signature of a truncated call and is true ONLY for an
347
+ * ABSENT (undefined) argument; for a value that is present but the wrong type it sent the model
348
+ * retrying byte-identically into the identical-error stop. Message-only: the call still throws and
349
+ * the file is untouched. Leading space included (appended to a sentence).
350
+ * @param {any} v
351
+ * @param {string} param
352
+ * @returns {string}
353
+ */
354
+ function wrongTypeHint(v, param) {
355
+ if (v === undefined) return ` If your output was cut short, retry with the full ${param}.`;
356
+ const t = receivedType(v);
357
+ if (t === 'object' || t === 'array') return ` Send ${param} as a string; to send JSON, encode it as one string.`;
358
+ return ` Send ${param} as a string.`;
359
+ }
360
+
361
+ // ---- BA-30 shrinkGuard (opt-in, per createShellTools instance) -------------------------------------------
362
+ const SHRINK_DEFAULTS = { minOldBytes: 2048, maxShrinkRatio: 0.5 };
363
+ // Upper bound on bytes read to count the OLD file's lines for the refusal message (never a full slurp).
364
+ const SHRINK_LINE_SCAN_CAP = 8 * 1024 * 1024;
365
+ const SHRINK_LINE_CHUNK = 64 * 1024;
366
+
367
+ /** @param {any} v */
368
+ function typeName(v) {
369
+ return v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v;
370
+ }
371
+
372
+ /**
373
+ * Validate + normalize `createShellTools({ shrinkGuard })`. Throws `ValidationError` naming the TYPE only.
374
+ * @param {any} sg
375
+ * @returns {{minOldBytes: number, maxShrinkRatio: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}|null}
376
+ */
377
+ function normalizeShrinkGuard(sg) {
378
+ if (sg === undefined || sg === false) return null;
379
+ if (sg === true) return { ...SHRINK_DEFAULTS };
380
+ if (sg === null || typeof sg !== 'object' || Array.isArray(sg)) {
381
+ throw new ValidationError(`createShellTools: shrinkGuard must be true or an options object (got ${typeName(sg)})`);
382
+ }
383
+ const allowed = ['minOldBytes', 'maxShrinkRatio', 'guardPath'];
384
+ if (Object.keys(sg).some((k) => !allowed.includes(k))) {
385
+ throw new ValidationError('createShellTools: shrinkGuard has an unknown option (allowed: minOldBytes, maxShrinkRatio, guardPath)');
386
+ }
387
+ const out = { ...SHRINK_DEFAULTS };
388
+ if (sg.minOldBytes !== undefined) {
389
+ if (typeof sg.minOldBytes !== 'number' || !Number.isFinite(sg.minOldBytes) || sg.minOldBytes < 0) {
390
+ throw new ValidationError(`createShellTools: shrinkGuard.minOldBytes must be a finite number >= 0 (got ${typeName(sg.minOldBytes)})`);
391
+ }
392
+ out.minOldBytes = sg.minOldBytes;
393
+ }
394
+ if (sg.maxShrinkRatio !== undefined) {
395
+ const r = sg.maxShrinkRatio;
396
+ if (typeof r !== 'number' || !Number.isFinite(r) || r <= 0 || r > 1) {
397
+ throw new ValidationError(`createShellTools: shrinkGuard.maxShrinkRatio must be a finite number in (0, 1] (got ${typeName(r)})`);
398
+ }
399
+ out.maxShrinkRatio = r;
400
+ }
401
+ /** @type {any} */
402
+ const res = out;
403
+ if (sg.guardPath !== undefined) {
404
+ if (typeof sg.guardPath !== 'function') {
405
+ throw new ValidationError(`createShellTools: shrinkGuard.guardPath must be a function (got ${typeName(sg.guardPath)})`);
406
+ }
407
+ res.guardPath = sg.guardPath;
408
+ }
409
+ return res;
410
+ }
411
+
412
+ /**
413
+ * Count the lines of an existing file with a bounded chunked read through the same no-follow open.
414
+ * @param {string} resolved
415
+ * @param {{noFollowSymlinks?: boolean}} options
416
+ * @returns {Promise<{lines: number, capped: boolean}>}
417
+ */
418
+ async function countLinesBounded(resolved, options) {
419
+ const fh = await openFile('shell_write', resolved, fsConstants.O_RDONLY, undefined, options);
420
+ try {
421
+ const buf = Buffer.alloc(SHRINK_LINE_CHUNK);
422
+ let total = 0;
423
+ let lines = 0;
424
+ let lastByte = 10;
425
+ while (total < SHRINK_LINE_SCAN_CAP) {
426
+ const { bytesRead } = await fh.read(buf, 0, Math.min(buf.length, SHRINK_LINE_SCAN_CAP - total), null);
427
+ if (bytesRead === 0) return { lines: lines + (lastByte === 10 ? 0 : 1), capped: false };
428
+ for (let i = 0; i < bytesRead; i++) if (buf[i] === 10) lines++;
429
+ lastByte = buf[bytesRead - 1];
430
+ total += bytesRead;
431
+ }
432
+ return { lines: lines + (lastByte === 10 ? 0 : 1), capped: true };
433
+ } finally {
434
+ await fh.close().catch(() => {});
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Refuse (throw ToolError, nothing written) a whole-file write that would gut an existing file.
440
+ * Bytes decide; lines are counted only here, for the message.
441
+ * @param {string} rawPath @param {string} resolved @param {string} content @param {number} newBytes
442
+ * @param {NonNullable<ReturnType<typeof normalizeShrinkGuard>>} guard
443
+ * @param {{noFollowSymlinks?: boolean}} options
444
+ */
445
+ async function checkShrink(rawPath, resolved, content, newBytes, guard, options) {
446
+ /** @type {import('node:fs').Stats} */
447
+ let st;
448
+ try {
449
+ // lstat under noFollowSymlinks: never measure through a final-component symlink (the write refuses it).
450
+ st = options.noFollowSymlinks ? await fs.lstat(resolved) : await fs.stat(resolved);
451
+ } catch (/** @type {any} */ err) {
452
+ if (err && err.code === 'ENOENT') return; // new file
453
+ throw new Error(`shell_write: shrinkGuard could not stat the target (${err && err.code ? err.code : typeof err}) — refusing to write unguarded`);
454
+ }
455
+ if (!st.isFile()) return; // symlink (noFollow) / dir / special: the normal write path handles it
456
+ const oldBytes = st.size;
457
+ if (!(oldBytes >= guard.minOldBytes && newBytes < oldBytes * guard.maxShrinkRatio)) return;
458
+ if (guard.guardPath) {
459
+ let verdict;
460
+ try {
461
+ verdict = await guard.guardPath(resolved);
462
+ } catch (/** @type {any} */ err) {
463
+ if (err instanceof HaltError) throw err;
464
+ throw new Error(`shell_write: shrinkGuard.guardPath threw for ${resolved} (${err && err.name ? err.name : typeof err})`);
465
+ }
466
+ if (verdict !== true && verdict !== false) {
467
+ throw new Error(`shell_write: shrinkGuard.guardPath returned a non-boolean (${typeName(verdict)}) for ${resolved}`);
468
+ }
469
+ if (verdict === false) return;
470
+ }
471
+ const { lines: oldLines, capped } = await countLinesBounded(resolved, options);
472
+ const newLines = content.length === 0 ? 0 : content.split('\n').length - (content.endsWith('\n') ? 1 : 0);
473
+ const n = (/** @type {number} */ x) => x.toLocaleString('en-US');
474
+ const u = (/** @type {number} */ x, /** @type {string} */ w) => `${n(x)} ${w}${x === 1 ? '' : 's'}`;
475
+ throw new ToolError(
476
+ `refusing: this would replace ${rawPath} (${u(oldBytes, 'byte')}, ${capped ? `${n(oldLines)}+ lines` : u(oldLines, 'line')}) with ${u(newBytes, 'byte')} (${u(newLines, 'line')}). ` +
477
+ 'To change part of a file use shell_edit; to rebuild it in parts use append:true; to really empty it pass content:\'\'.',
478
+ { context: { shrink: true, oldBytes, newBytes, oldLines, newLines } },
479
+ );
480
+ }
481
+
334
482
  /**
335
483
  * Write text to a file (the BA-2 first-class write primitive — a coding agent must edit files, and routing
336
484
  * writes through the shell is impractical: redirection is a shell metachar that an argv/bash allowlist denies).
@@ -348,7 +496,7 @@ async function readEntry(rawPath, maxBytes, options = {}) {
348
496
  * feeds this UNTRUSTED model-authored args (that is the boundary BA-4 was breached at, and where types buy
349
497
  * nothing).
350
498
  * @param {{path: string, content: string, append?: boolean, maxBytes?: number}} args
351
- * @param {{noFollowSymlinks?: boolean}} [options]
499
+ * @param {{noFollowSymlinks?: boolean, shrinkGuard?: ReturnType<typeof normalizeShrinkGuard>}} [options]
352
500
  * @returns {Promise<string>}
353
501
  */
354
502
  async function writeFile({ path: rawPath, content, append = false, maxBytes }, options = {}) {
@@ -358,8 +506,8 @@ async function writeFile({ path: rawPath, content, append = false, maxBytes }, o
358
506
  if (typeof content !== 'string') {
359
507
  throw new Error(
360
508
  'shell_write requires a "content" string (pass content:"" to deliberately empty the file). '
361
- + `Got ${content === undefined ? 'no content argument' : `content of type ${content === null ? 'null' : typeof content}`}`
362
- + ' — refusing to write, the file is unchanged. If your output was cut short, retry with the full content.',
509
+ + `Got ${content === undefined ? 'no content argument' : `content of type ${receivedType(content)}`}`
510
+ + ` — refusing to write, the file is unchanged.${wrongTypeHint(content, 'content')}`,
363
511
  );
364
512
  }
365
513
  const cap = maxBytes || DEFAULT_WRITE_MAX_BYTES;
@@ -368,6 +516,10 @@ async function writeFile({ path: rawPath, content, append = false, maxBytes }, o
368
516
  throw new Error(`shell_write content is ${bytes} bytes, over the ${cap}-byte cap (pass maxBytes to raise it)`);
369
517
  }
370
518
  const resolved = resolveToolPath(rawPath);
519
+ // BA-30 (opt-in): skip for append and the deliberate empty; checkShrink skips new/non-regular targets.
520
+ if (options.shrinkGuard && !append && content !== '') {
521
+ await checkShrink(rawPath, resolved, content, bytes, options.shrinkGuard, options);
522
+ }
371
523
  await fs.mkdir(path.dirname(resolved), { recursive: true });
372
524
 
373
525
  // O_TRUNC/O_APPEND + O_CREAT, mode 0o666 (subject to umask) — the same semantics `fs.writeFile`/
@@ -426,14 +578,15 @@ async function editFile({ path: rawPath, oldText, newText, maxBytes }, options =
426
578
  if (typeof oldText !== 'string' || oldText.length === 0) {
427
579
  throw new Error(
428
580
  'shell_edit requires a non-empty "oldText" string to anchor the edit — refusing to edit, the file is unchanged. '
429
- + `Got ${oldText === undefined ? 'no oldText argument' : oldText === '' ? 'an empty string' : `oldText of type ${oldText === null ? 'null' : typeof oldText}`}.`,
581
+ + `Got ${oldText === undefined ? 'no oldText argument' : oldText === '' ? 'an empty string' : `oldText of type ${receivedType(oldText)}`}.`
582
+ + (oldText === '' ? '' : wrongTypeHint(oldText, 'oldText')),
430
583
  );
431
584
  }
432
585
  if (typeof newText !== 'string') {
433
586
  throw new Error(
434
587
  'shell_edit requires a "newText" string (pass newText:"" to delete the anchored text) — refusing to edit, the file is unchanged. '
435
- + `Got ${newText === undefined ? 'no newText argument' : `newText of type ${newText === null ? 'null' : typeof newText}`}`
436
- + '. If your output was cut short, retry with the full newText.',
588
+ + `Got ${newText === undefined ? 'no newText argument' : `newText of type ${receivedType(newText)}`}.`
589
+ + wrongTypeHint(newText, 'newText'),
437
590
  );
438
591
  }
439
592
 
@@ -939,7 +1092,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
939
1092
  * Create the six shell tools. Configuration is mostly per-call via tool args; gating is the
940
1093
  * caller's responsibility via `new Loop({ policy })`.
941
1094
  *
942
- * @param {{noFollowSymlinks?: boolean, canRead?: CanRead}} [options] - `noFollowSymlinks` (default `false`, byte-
1095
+ * @param {{noFollowSymlinks?: boolean, canRead?: CanRead, shrinkGuard?: true|{minOldBytes?: number, maxShrinkRatio?: number, guardPath?: (absPath: string) => boolean|Promise<boolean>}}} [options] - `noFollowSymlinks` (default `false`, byte-
943
1096
  * identical to the pre-existing behavior when omitted): when `true`, `shell_read`, `shell_write`,
944
1097
  * `shell_edit`, and `shell_grep` refuse to open a path whose FINAL path component is a symlink
945
1098
  * (file, dir, or dangling) — THROWN, `err.code:'ELOOP'`, never a silently-followed link. Scope is
@@ -968,9 +1121,19 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
968
1121
  * hung `canRead` rejects with a distinct `canRead walk exceeded` error). TOCTOU: `canRead` vets paths at WALK
969
1122
  * time; a path swapped for a symlink between vetting and the worker's read is followed unless
970
1123
  * `noFollowSymlinks:true` — pair `canRead` with `noFollowSymlinks:true`.
1124
+ * `shrinkGuard` (BA-30, opt-in; unset => byte-identical): refuses a whole-file `shell_write` that would gut an
1125
+ * existing file — THROWN `ToolError` (so `maxIdenticalToolErrors` applies), file untouched. `true` =
1126
+ * `{minOldBytes:2048, maxShrinkRatio:0.5}`; an object may override either plus `guardPath(absPath)=>boolean|Promise<boolean>`
1127
+ * (receives the `resolveToolPath`'d path — LEXICAL, not realpath'd, same as `canRead`: `guardPath` sees the lexical path, not the realpath; realpath inside the predicate (or exempt-list rather than guard-list) if aliases matter; `false` skips the guard for that file; throw/non-boolean rejects, type only;
1128
+ * `HaltError` propagates). Bytes decide: refuse when `oldBytes >= minOldBytes && newBytes < oldBytes*maxShrinkRatio`.
1129
+ * Skipped for `append:true`, `content:''`, a new file, and a non-regular target. Size is measured at call time (`lstat`
1130
+ * under `noFollowSymlinks`, never through a symlink); a stat error other than ENOENT rejects. Lines are counted only on
1131
+ * refusal (bounded 8 MiB read, `N+` when capped). `error.context` = `{shrink:true, oldBytes, newBytes, oldLines, newLines}`
1132
+ * (numbers/boolean only, no path or content). `shrinkGuard:false` is off, same as unset. Any other `shrinkGuard` shape throws `ValidationError` at
1133
+ * creation, naming the type only. `shell_edit` is unaffected; there is deliberately no override flag.
971
1134
  * @returns {{tools: ToolDef[]}}
972
1135
  * @when you want to give an agent shell/file tools (read, grep, write, edit, run, exec) — cross-platform, pure Node, zero deps
973
- * @fails never throws at creation; 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.
1136
+ * @fails throws ValidationError at creation for a non-function canRead or a bad shrinkGuard shape; gating is the caller's via Loop({ policy }) and fs.writeScope, shell_edit refuses a non-unique anchor as a tool result (file untouched), and with noFollowSymlinks:true the four file tools throw ELOOP on a symlinked final path component.
974
1137
  * @example
975
1138
  * const { tools } = createShellTools();
976
1139
  * const loop = new Loop({ provider, tools, policy });
@@ -978,6 +1141,7 @@ function execCommand({ command, cwd, timeout, maxBuffer, env }) {
978
1141
  */
979
1142
  function createShellTools(options = {}) {
980
1143
  const { noFollowSymlinks = false, canRead } = options;
1144
+ const shrinkGuard = normalizeShrinkGuard(options.shrinkGuard);
981
1145
  if (canRead !== undefined && typeof canRead !== 'function') {
982
1146
  throw new ValidationError(`createShellTools: canRead must be a function (got ${canRead === null ? 'null' : typeof canRead})`);
983
1147
  }
@@ -1031,7 +1195,7 @@ function createShellTools(options = {}) {
1031
1195
  // The args are model-authored and UNTRUSTED — `content` may be absent (an output-token-capped
1032
1196
  // generation), so the boundary type stays loose and `writeFile` enforces the contract at runtime (BA-4).
1033
1197
  execute: async (/** @type {{path: string, content?: string, append?: boolean, maxBytes?: number}} */ args) =>
1034
- writeFile(/** @type {any} */ (args), { noFollowSymlinks }),
1198
+ writeFile(/** @type {any} */ (args), { noFollowSymlinks, shrinkGuard }),
1035
1199
  },
1036
1200
  {
1037
1201
  name: 'shell_edit',
@@ -1102,6 +1266,7 @@ module.exports = {
1102
1266
  resolveToolPath,
1103
1267
  _grepCore,
1104
1268
  _writeFile: writeFile,
1269
+ _SHRINK_LINE_SCAN_CAP: SHRINK_LINE_SCAN_CAP,
1105
1270
  _editFile: editFile,
1106
1271
  _openFile: openFile,
1107
1272
  _assertDirStillMatchesHandle: assertDirStillMatchesHandle,
package/types/index.d.ts CHANGED
@@ -22,6 +22,52 @@ export interface Usage {
22
22
  cacheReadTokens?: number;
23
23
  /** Prompt tokens written to cache — a premium tier (Anthropic ~1.25×; OpenAI/Gemini have no write surcharge → 0). */
24
24
  cacheCreationTokens?: number;
25
+ /**
26
+ * BA-29 — reasoning/thinking tokens when the vendor REPORTS them (OpenAI wire
27
+ * `completion_tokens_details.reasoning_tokens`, Gemini `thoughtsTokenCount`), else `null`: NEVER 0 for
28
+ * absent (an explicit reported 0 stays 0). Anthropic, Ollama and CLIPipe do not report it → `null`; a
29
+ * custom provider that omits the key is read as unreported. These are a SUBSET of `outputTokens`
30
+ * (already inside it), carried for observability — pricing reads the four tiers and is unchanged.
31
+ */
32
+ reasoningTokens?: number | null;
33
+ }
34
+
35
+ /**
36
+ * BA-29 — one bad tool call the model made, reported on the run RETURN as `badCalls` (key absent when
37
+ * there were none; accumulated across the whole run, in order). Facts only: nothing here is executed,
38
+ * repaired or coerced, and raw arguments are never included.
39
+ * - `arg-type` / `arg-missing`: only from the opt-in `Loop({ checkArgs: true })` (top-level `required` /
40
+ * declared primitive `type`); carry `param`, `expected`, `got`. A refused call is NOT executed.
41
+ * - `cut-off`: a call that rode a round cut at the output cap (`stopReason:'max_tokens'`); one entry per
42
+ * call, `parsed:true` when its arguments parsed, `parsed:false` for a malformed one. Never executed.
43
+ * - `malformed-json`: a call whose `function.arguments` was syntactically broken JSON on a round that was
44
+ * NOT cut (`parsed:false`).
45
+ * `argBytes`: for a malformed call, the byte length of the raw `function.arguments`; for a parsed call, the
46
+ * RE-SERIALIZED size (`Buffer.byteLength(JSON.stringify(args))`, an approximation of what was sent).
47
+ * `hasAppend`: whether the tool's `parameters.properties` declares an `append` param (unknown tool ⇒ false).
48
+ */
49
+ export interface BadCall {
50
+ kind: 'arg-type' | 'arg-missing' | 'cut-off' | 'malformed-json';
51
+ tool: string | null;
52
+ param?: string;
53
+ expected?: string;
54
+ got?: string;
55
+ argBytes?: number;
56
+ parsed?: boolean;
57
+ hasAppend: boolean;
58
+ round: number;
59
+ }
60
+
61
+ /**
62
+ * BA-29 — token facts of the round that ended a run at the output cap; on the run return as `cutOff`
63
+ * only when `error === 'truncated:max_tokens'`. `outputTokens`/`reasoningTokens` are that round's (`null`
64
+ * when the provider reported no usage / no reasoning count). `maxTokensRequested` is the per-run
65
+ * `maxTokens` option the Loop passed to the provider, else `null` — never a guessed provider default.
66
+ */
67
+ export interface CutOff {
68
+ outputTokens: number | null;
69
+ reasoningTokens: number | null;
70
+ maxTokensRequested: number | null;
25
71
  }
26
72
 
27
73
  /**
@@ -45,6 +91,8 @@ export interface RunMetrics {
45
91
  byTool: Record<string, number>;
46
92
  /** Cumulative token spend across all rounds (incl. summarize calls), by tier. */
47
93
  tokens: { input: number; output: number; cacheCreation: number; cacheRead: number };
94
+ /** BA-29 — cumulative reasoning tokens: the sum of rounds that REPORTED a count (an explicit 0 counts); `null` only if no round reported one. A subset of `tokens.output`. */
95
+ reasoningTokens: number | null;
48
96
  /** Cumulative USD over priced rounds; null ONLY if nothing could be priced (explicit-unknown, not free). */
49
97
  costUsd: number | null;
50
98
  /** Count of rounds genuinely unpriceable (no usage, or a runaway non-finite estimate) — the loud-unpriced signal. */
@@ -167,7 +215,10 @@ export interface GenerateResult {
167
215
  * raw `function.arguments` was a string: the FULL raw value verbatim, uncapped (model-generated; may be
168
216
  * large or sensitive).
169
217
  */
170
- malformedToolCall?: { name: string | undefined; error: string; rawArguments?: string;
218
+ malformedToolCall?: { name: string | undefined; error: string;
219
+ /** BA-29 — byte length of the raw `function.arguments` (size only, ALWAYS present on the marker). */
220
+ argBytes: number;
221
+ rawArguments?: string;
171
222
  /** @deprecated never set since 0.50.0 (rawArguments is now uncapped) */
172
223
  rawTruncated?: true;
173
224
  };