bare-agent 0.57.0 → 0.58.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.
@@ -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,6 +1484,8 @@ 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`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-agent",
3
- "version": "0.57.0",
3
+ "version": "0.58.0",
4
4
  "files": [
5
5
  "index.js",
6
6
  "index.d.ts",
@@ -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.js CHANGED
@@ -331,6 +331,33 @@ 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
+
334
361
  /**
335
362
  * Write text to a file (the BA-2 first-class write primitive — a coding agent must edit files, and routing
336
363
  * writes through the shell is impractical: redirection is a shell metachar that an argv/bash allowlist denies).
@@ -358,8 +385,8 @@ async function writeFile({ path: rawPath, content, append = false, maxBytes }, o
358
385
  if (typeof content !== 'string') {
359
386
  throw new Error(
360
387
  '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.',
388
+ + `Got ${content === undefined ? 'no content argument' : `content of type ${receivedType(content)}`}`
389
+ + ` — refusing to write, the file is unchanged.${wrongTypeHint(content, 'content')}`,
363
390
  );
364
391
  }
365
392
  const cap = maxBytes || DEFAULT_WRITE_MAX_BYTES;
@@ -426,14 +453,15 @@ async function editFile({ path: rawPath, oldText, newText, maxBytes }, options =
426
453
  if (typeof oldText !== 'string' || oldText.length === 0) {
427
454
  throw new Error(
428
455
  '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}`}.`,
456
+ + `Got ${oldText === undefined ? 'no oldText argument' : oldText === '' ? 'an empty string' : `oldText of type ${receivedType(oldText)}`}.`
457
+ + (oldText === '' ? '' : wrongTypeHint(oldText, 'oldText')),
430
458
  );
431
459
  }
432
460
  if (typeof newText !== 'string') {
433
461
  throw new Error(
434
462
  '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.',
463
+ + `Got ${newText === undefined ? 'no newText argument' : `newText of type ${receivedType(newText)}`}.`
464
+ + wrongTypeHint(newText, 'newText'),
437
465
  );
438
466
  }
439
467
 
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
  };