bare-agent 0.56.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.
@@ -441,7 +441,7 @@ a server that breaks its stdin pipe surfaces as a failed connection, never an un
441
441
  crash; and a server whose `command` cannot start (ENOENT/EACCES, or a sync `spawn()` refusal such as an empty command or NUL byte) rejects with
442
442
  `MCP server "s" failed to start: command "<cmd>" (<code>)`, `context: { spawnError: true, server, code }`
443
443
  (`code` = Node error code if a string, else `'ESPAWN'`; command only with control chars escaped, never args/env) — `listServerTools` throws it, `allow` mode puts it in `errors` + `missing`,
444
- bulk mode in `errors` — instead of crashing the host.
444
+ bulk mode in `errors` — instead of crashing the host. If a `cwd` (bridge-level or the server's own) was in effect and cannot be entered, the message is `MCP server "s" failed to start: working folder could not be used (<code>)` with `context.cwdFailed:true` added (no folder path, no command named); absent otherwise.
445
445
 
446
446
  ## Wiring with bareguard
447
447
 
@@ -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.
@@ -597,7 +617,9 @@ Verified live against a real 0.19 Gate: `gate.check` ALLOWs `shell_run ["ls","/t
597
617
  | throws | Treated as a deny. The thrown message becomes the reason. Loop continues. |
598
618
  | omitted | Allow-all. Useful for development; never in production — that's what bareguard is for. |
599
619
 
600
- **Keep provider keys out of MCP servers (`passEnv`, F109).** By default every stdio server is spawned with your full environment, so `DEEPSEEK_API_KEY` etc. are visible to it. Pass `passEnv: ['PATH', 'HOME']` to `createMCPBridge` (or `listServerTools`) and the child gets only those vars plus the server's own `env` (own wins on a clash; its `${VAR}` refs still resolve from your full env, so you can hand one key over deliberately). `[]` = own env only. Applies to every server, every mode. Suggested starting list: PATH, HOME. Measured (fwdloop F111, Linux, tools/list only): PATH + HOME were enough for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers. Unmeasured: real tool calls (a tool that opens a window may also need DISPLAY/XDG_RUNTIME_DIR), TMPDIR/LANG, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bad shape throws `ValidationError`.
620
+ **Keep provider keys out of MCP servers (`passEnv`, F109).** By default every stdio server is spawned with your full environment, so `DEEPSEEK_API_KEY` etc. are visible to it. Pass `passEnv: ['PATH', 'HOME']` to `createMCPBridge` (or `listServerTools`) and the child gets only those vars plus the server's own `env` (own wins on a clash; its `${VAR}` refs still resolve from your full env, so you can hand one key over deliberately). `[]` = own env only. Applies to every server, every mode. Suggested starting list: PATH, HOME. Measured (fwdloop F111/F111b, Linux, passEnv ['PATH','HOME']): tools/list worked for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers, and real tool calls worked too (litectx.recall via node; a HEADLESS barebrowse browse); adding DISPLAY, XDG_RUNTIME_DIR, TMPDIR or LANG changed nothing, so PATH + HOME is the measured minimum on Linux. Unmeasured: a headed (windowed) browser, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bad shape throws `ValidationError`.
621
+
622
+ **Start folder for MCP servers (`cwd`).** `createMCPBridge({ cwd: '/abs/dir' })` (or `listServerTools`, or `cfg.mcp.cwd` in `--config`) starts every spawned server in that folder; a server's own `cwd` still wins; unset = your process cwd. It applies only at spawn: it is not saved into `.mcp-bridge.json` and does not move config discovery. It must be an absolute path to an existing directory (no `~`, no relative path) or the whole bridge throws `ValidationError` before anything spawns (the value is never echoed in the message).
601
623
 
602
624
  ### Per-caller governance with ctx (multi-user, multi-tenant)
603
625
 
@@ -996,7 +1018,7 @@ All return `{ text, toolCalls, usage: { inputTokens, outputTokens }, model?, cos
996
1018
 
997
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.
998
1020
 
999
- **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.
1000
1022
 
1001
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.
1002
1024
 
@@ -1042,6 +1064,7 @@ const mcp = liteCtxMcpBridgeConfig({ root: './child-mem' }); // own-db isolati
1042
1064
  // cfg.mcp also accepts a directory-confined { bridgePath } pointing at a .mcp-bridge.json on disk.
1043
1065
  // cfg.mcp.passEnv (optional string[], F109) limits which parent env vars reach the mounted MCP servers
1044
1066
  // (default: they inherit the child's full env incl. API keys); a bad value exits 1 via the mount error.
1067
+ // cfg.mcp.cwd (optional absolute dir) sets the mounted MCP servers' start folder; a bad value exits 1 the same way.
1045
1068
  ```
1046
1069
 
1047
1070
  Requires litectx's `litectx-mcp` binary on PATH. Isolation is **physical** (each child a distinct `--root` db) — promotion to the parent is an explicit parent-side `recall`→`remember`, never automatic. See `examples/litectx-mcp-child.mjs`. bareagent imports nothing from litectx; the helper is pure config curation.
@@ -1461,6 +1484,8 @@ Mobile tools follow the observe-act pattern: action tools auto-return a fresh sn
1461
1484
 
1462
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.
1463
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
+
1464
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.
1465
1490
  >
1466
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/bin/cli.js CHANGED
@@ -76,7 +76,7 @@ async function runConfigMode(cfgPath) {
76
76
  // `liteCtxMcpBridgeConfig`) or `{ bridgePath }` pointing at one (confined to the config directory,
77
77
  // same rule as gate.humanChannel). Mounted tools join the set BEFORE gating, so they traverse the
78
78
  // same policy as native tools. `cfg.mcp.passEnv` (string[], optional) restricts which parent env
79
- // vars reach the MCP servers (F109); invalid ⇒ the mount-failure exit below. The server `command` runs unsandboxed — same trust as `cfg.tools`.
79
+ // vars reach the MCP servers (F109); `cfg.mcp.cwd` (absolute dir) sets the servers' start folder; invalid ⇒ the mount-failure exit below. The server `command` runs unsandboxed — same trust as `cfg.tools`.
80
80
  /** @type {{ tools: ToolDef[], close: Function } | null} */
81
81
  let mcpBridge = null;
82
82
  if (cfg.mcp) {
@@ -100,20 +100,28 @@ async function runConfigMode(cfgPath) {
100
100
  process.stderr.write('[cli] cfg.mcp must be an inline bridge config ({ servers }) or { bridgePath }\n');
101
101
  process.exit(1);
102
102
  }
103
+ let mountFailed = false;
104
+ let mountMsg;
103
105
  try {
104
106
  mcpBridge = await createMCPBridge({
105
107
  bridgePath,
106
108
  servers: cfg.mcp.servers ? Object.keys(cfg.mcp.servers) : undefined,
107
109
  timeout: cfg.mcp.timeout || 15000,
108
110
  ...(cfg.mcp.passEnv !== undefined ? { passEnv: cfg.mcp.passEnv } : {}),
111
+ ...(cfg.mcp.cwd !== undefined ? { cwd: cfg.mcp.cwd } : {}),
109
112
  });
110
113
  tools.push(...mcpBridge.tools);
111
114
  } catch (err) {
112
- process.stderr.write(`[cli] failed to mount MCP (cfg.mcp): ${err.message}\n`);
113
- process.exit(1);
115
+ // Exit AFTER the finally: process.exit() inside the catch would skip it and leak the temp file.
116
+ mountFailed = true;
117
+ mountMsg = err.message;
114
118
  } finally {
115
119
  if (tmpBridge) { try { fs.unlinkSync(tmpBridge); } catch { /* best-effort */ } }
116
120
  }
121
+ if (mountFailed) {
122
+ process.stderr.write(`[cli] failed to mount MCP (cfg.mcp): ${mountMsg}\n`);
123
+ process.exit(1);
124
+ }
117
125
  }
118
126
 
119
127
  // Bareguard Gate (optional but strongly recommended for spawn children).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bare-agent",
3
- "version": "0.56.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 });
@@ -96,7 +96,8 @@ export type RpcClient = {
96
96
  * server was not found / failed / was rejected) come back in `missing`. `denied` is always `[]`, nothing is
97
97
  * written to stdout, and `mcp_invoke` on a listed-but-unsigned name throws `context.denied === true`.
98
98
  * Invalid shape throws `ValidationError` (type only, never values).
99
- * @param {string[]} [opts.passEnv] - Parent env var NAMES to hand to every spawned server. Unset (default) = the child inherits the FULL parent env (all API keys). Set = the child gets ONLY these vars (those present in process.env) plus the server's own `env` (which wins on a name clash; its `${VAR}` refs still resolve from the full process.env). `[]` = own env only. Measured (fwdloop F111, Linux, tools/list only): PATH + HOME were enough for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers. Unmeasured: real tool calls (a tool that opens a window may also need DISPLAY/XDG_RUNTIME_DIR), TMPDIR/LANG, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
99
+ * @param {string[]} [opts.passEnv] - Parent env var NAMES to hand to every spawned server. Unset (default) = the child inherits the FULL parent env (all API keys). Set = the child gets ONLY these vars (those present in process.env) plus the server's own `env` (which wins on a name clash; its `${VAR}` refs still resolve from the full process.env). `[]` = own env only. Measured (fwdloop F111/F111b, Linux, passEnv ['PATH','HOME']): tools/list worked for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers, and real tool calls worked too (litectx.recall via node; a HEADLESS barebrowse browse); adding DISPLAY, XDG_RUNTIME_DIR, TMPDIR or LANG changed nothing, so PATH + HOME is the measured minimum on Linux. Unmeasured: a headed (windowed) browser, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
100
+ * @param {string} [opts.cwd] - Start folder for every spawned server (sibling of `passEnv`, bridge-level, opt-in). Unset (default) = the child starts in `process.cwd()`, byte-identical to before. A server's own `cwd` wins. Applied ONLY at spawn: never written to `.mcp-bridge.json`, and it does not move discovery (`./.mcp.json`, the default bridge path stay on `process.cwd()`). Validated once, before anything spawns: must be a non-empty ABSOLUTE path to an existing directory (no `~` expansion, no relative path), else `ValidationError` naming the reason only, never the value; this throws for the whole bridge. A folder deleted after validation, or a bad per-server `cwd`, is not validated up front: the server fails to start / lands in `errors`, labelled `working folder could not be used` with `context.cwdFailed:true` (the folder path is never named).
100
101
  * @param {string[]} [opts.servers] - Limit to these server names (ignored when `allow` is given).
101
102
  * @param {number} [opts.timeout=15000] - Per-server handshake timeout in ms (initialize + tools/list).
102
103
  * @param {number} [opts.callTimeout=120000] - Per-invocation timeout in ms for tools/call. Bounds a
@@ -122,6 +123,7 @@ export function createMCPBridge(opts?: {
122
123
  includeProjectConfig?: boolean | undefined;
123
124
  allow?: Record<string, string[]> | undefined;
124
125
  passEnv?: string[] | undefined;
126
+ cwd?: string | undefined;
125
127
  servers?: string[] | undefined;
126
128
  timeout?: number | undefined;
127
129
  callTimeout?: number | undefined;
@@ -205,6 +207,7 @@ export function buildMetaTools(tools: ToolDef[], discoveredAt?: string, excluded
205
207
  * @param {(name: string, def: ServerDef) => boolean | Promise<boolean>} [opts.confirmServer] - Same semantics as createMCPBridge: `=== true` proceeds, a throw denies. Implies includeProjectConfig.
206
208
  * @param {boolean} [opts.includeProjectConfig=false] - Also scan `./.mcp.json` during default discovery.
207
209
  * @param {string[]} [opts.passEnv] - Same as createMCPBridge: restrict the spawned server's inherited env to these parent var names (unset = full inherit). Bad shape throws `ValidationError`.
210
+ * @param {string} [opts.cwd] - Same as createMCPBridge: start folder for the spawned server (a server's own `cwd` wins). Absolute existing directory, else `ValidationError` (reason only).
208
211
  * @param {number} [opts.timeout=15000] - Per-round-trip bound in ms (initialize and each tools/list page).
209
212
  * @returns {Promise<Array<{name: string, description: string, annotations?: Record<string, any>}>>}
210
213
  * @when you want to list one MCP server's tools and their annotation hints before deciding what to allow — no bridge, no cache file, no tools kept alive
@@ -218,6 +221,7 @@ export function listServerTools(opts: {
218
221
  confirmServer?: ((name: string, def: ServerDef) => boolean | Promise<boolean>) | undefined;
219
222
  includeProjectConfig?: boolean | undefined;
220
223
  passEnv?: string[] | undefined;
224
+ cwd?: string | undefined;
221
225
  timeout?: number | undefined;
222
226
  }): Promise<Array<{
223
227
  name: string;
package/src/mcp-bridge.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const { spawn } = require('node:child_process');
4
- const { readFileSync, writeFileSync, existsSync } = require('node:fs');
5
- const { join } = require('node:path');
4
+ const { readFileSync, writeFileSync, existsSync, statSync, accessSync, constants: fsConstants } = require('node:fs');
5
+ const { join, isAbsolute } = require('node:path');
6
6
  const { homedir } = require('node:os');
7
7
  const { ToolError, ValidationError, TimeoutError } = require('./errors');
8
8
 
@@ -234,14 +234,27 @@ function resolveEnv(env) {
234
234
  /**
235
235
  * Labelled spawn-failure error. Names the command ONLY (args/env can carry tokens); control
236
236
  * characters in the command are escaped so a NUL/newline can't corrupt logs. `code` is the Node
237
- * error code when it is a string, else 'ESPAWN'.
237
+ * error code when it is a string, else 'ESPAWN'. Node reports a bad start folder exactly like a
238
+ * missing command (ENOENT/EACCES/ENOTDIR), so when a `cwd` was in effect and it cannot be entered
239
+ * the label says the working folder is the problem instead (`context.cwdFailed:true`, key absent
240
+ * otherwise); neither the folder path nor the command is named then. The check never throws.
238
241
  * @param {string} name
239
242
  * @param {any} command
240
243
  * @param {any} err
244
+ * @param {string} [cwd] - the start folder in effect for this spawn, if any
241
245
  * @returns {ToolError}
242
246
  */
243
- function spawnFailure(name, command, err) {
247
+ function spawnFailure(name, command, err, cwd) {
244
248
  const code = typeof err?.code === 'string' ? err.code : 'ESPAWN';
249
+ if (cwd) {
250
+ let usable = false;
251
+ try { accessSync(cwd, fsConstants.X_OK); usable = statSync(cwd).isDirectory(); } catch { /* unusable */ }
252
+ if (!usable) {
253
+ return new ToolError(`MCP server "${name}" failed to start: working folder could not be used (${code})`, {
254
+ context: { spawnError: true, server: name, code, cwdFailed: true },
255
+ });
256
+ }
257
+ }
245
258
  const shown = String(command).replace(/[\u0000-\u001f\u007f]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
246
259
  return new ToolError(`MCP server "${name}" failed to start: command "${shown}" (${code})`, {
247
260
  context: { spawnError: true, server: name, code },
@@ -281,14 +294,36 @@ function validatePassEnv(passEnv, bad) {
281
294
  return passEnv;
282
295
  }
283
296
 
297
+ /**
298
+ * Validate the bridge-level `cwd` (the child's start folder). Once, up front, before anything
299
+ * spawns. Messages give the reason/type only — never echo the value. No `~` expansion: a relative
300
+ * or `~/x` path is rejected. Any stat failure is the same loud ValidationError.
301
+ * @param {any} cwd
302
+ * @param {(msg: string) => Error} bad
303
+ * @returns {string | undefined}
304
+ */
305
+ function validateBridgeCwd(cwd, bad) {
306
+ if (cwd === undefined) return undefined;
307
+ if (typeof cwd !== 'string' || cwd === '') {
308
+ throw bad(`cwd must be a non-empty absolute path string (got ${cwd === '' ? 'empty string' : typeName(cwd)})`);
309
+ }
310
+ if (!isAbsolute(cwd)) throw bad('cwd must be an absolute path (no relative path, no ~ expansion)');
311
+ let isDir;
312
+ try { isDir = statSync(cwd).isDirectory(); } catch { throw bad('cwd must be an existing directory (it could not be read)'); }
313
+ if (!isDir) throw bad('cwd must be an existing directory (it is not a directory)');
314
+ return cwd;
315
+ }
316
+
284
317
  /**
285
318
  * @param {string} name
286
319
  * @param {ServerDef} def
287
320
  * @param {string[]} [passEnv]
321
+ * @param {string} [bridgeCwd] - bridge-level start folder; the server's own `def.cwd` wins. Resolved here at spawn, never merged into `def` (which is persisted).
288
322
  * @returns {RpcClient}
289
323
  */
290
- function createRpcClient(name, def, passEnv) {
291
- const { command, args = [], env, cwd } = def;
324
+ function createRpcClient(name, def, passEnv, bridgeCwd) {
325
+ const { command, args = [], env } = def;
326
+ const cwd = def.cwd || bridgeCwd;
292
327
  const mergedEnv = buildChildEnv(passEnv, resolveEnv(env));
293
328
 
294
329
  /** @type {import('node:child_process').ChildProcessWithoutNullStreams} */
@@ -305,7 +340,7 @@ function createRpcClient(name, def, passEnv) {
305
340
  // Dead client: rpc() rejects every call; notify() is a no-op; `child` is a minimal stand-in
306
341
  // that killServer() skips (exitCode !== null) — the simplest shape that needs no null-guards
307
342
  // in connectAndListTools / killServer / close().
308
- const dead = spawnFailure(name, command, err);
343
+ const dead = spawnFailure(name, command, err, cwd);
309
344
  return {
310
345
  rpc: () => Promise.reject(dead),
311
346
  notify: () => {},
@@ -375,7 +410,7 @@ function createRpcClient(name, def, passEnv) {
375
410
  // kill() or IPC send on a LIVE child; keep the listener (so it can't crash the host) but do
376
411
  // not mark the server failed — a live server's lifecycle belongs to the 'close' handler.
377
412
  if (child.pid !== undefined || spawnErr) return;
378
- spawnErr = spawnFailure(name, command, err);
413
+ spawnErr = spawnFailure(name, command, err, cwd);
379
414
  for (const id of [...pending.keys()]) settle(id, false, spawnErr);
380
415
  });
381
416
 
@@ -551,13 +586,13 @@ const MAX_LIST_PAGES = 100;
551
586
  * @param {string} name
552
587
  * @param {ServerDef} def
553
588
  * @param {number} [timeout] - Bound on EACH round-trip (initialize, every tools/list page).
554
- * @param {{ deadlineMs?: number, passEnv?: string[] }} [o] - `passEnv`: see createMCPBridge. Optional ONE total wall-clock ceiling over the whole
589
+ * @param {{ deadlineMs?: number, passEnv?: string[], cwd?: string }} [o] - `passEnv`/`cwd`: see createMCPBridge. Optional ONE total wall-clock ceiling over the whole
555
590
  * connect+list (internal; used by listServerTools). On trip the child is killed and a labelled
556
591
  * TimeoutError rejects. The timer is always cleared.
557
592
  * @returns {Promise<{mcpTools: McpTool[], client: RpcClient}>}
558
593
  */
559
594
  async function connectAndListTools(name, def, timeout = 15000, o = {}) {
560
- const client = createRpcClient(name, def, o.passEnv);
595
+ const client = createRpcClient(name, def, o.passEnv, o.cwd);
561
596
  /** @type {NodeJS.Timeout | undefined} */
562
597
  let deadlineTimer;
563
598
 
@@ -870,6 +905,7 @@ function validateAllow(allow) {
870
905
  * @param {number} o.timeout
871
906
  * @param {number} o.callTimeout
872
907
  * @param {string[]} [o.passEnv]
908
+ * @param {string} [o.cwd]
873
909
  * @param {(name: string, def: ServerDef) => Promise<boolean>} o.vetServer
874
910
  * @param {(specs: Array<{name: string, command: string, args?: string[]}>) => void} o.warnUnvettedSpawn
875
911
  */
@@ -902,7 +938,7 @@ async function createAllowBridge(allow, o) {
902
938
  await Promise.all(toConnect.map(async ([name, def]) => {
903
939
  try {
904
940
  if (!(await o.vetServer(name, def))) return;
905
- const { mcpTools, client } = await connectAndListTools(name, def, o.timeout, { passEnv: o.passEnv });
941
+ const { mcpTools, client } = await connectAndListTools(name, def, o.timeout, { passEnv: o.passEnv, cwd: o.cwd });
906
942
  // Track the child BEFORE any processing so close() reaps it even if what follows throws.
907
943
  children.push(client.child);
908
944
  const signed = new Set(allow.get(name));
@@ -971,7 +1007,8 @@ async function createAllowBridge(allow, o) {
971
1007
  * server was not found / failed / was rejected) come back in `missing`. `denied` is always `[]`, nothing is
972
1008
  * written to stdout, and `mcp_invoke` on a listed-but-unsigned name throws `context.denied === true`.
973
1009
  * Invalid shape throws `ValidationError` (type only, never values).
974
- * @param {string[]} [opts.passEnv] - Parent env var NAMES to hand to every spawned server. Unset (default) = the child inherits the FULL parent env (all API keys). Set = the child gets ONLY these vars (those present in process.env) plus the server's own `env` (which wins on a name clash; its `${VAR}` refs still resolve from the full process.env). `[]` = own env only. Measured (fwdloop F111, Linux, tools/list only): PATH + HOME were enough for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers. Unmeasured: real tool calls (a tool that opens a window may also need DISPLAY/XDG_RUNTIME_DIR), TMPDIR/LANG, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
1010
+ * @param {string[]} [opts.passEnv] - Parent env var NAMES to hand to every spawned server. Unset (default) = the child inherits the FULL parent env (all API keys). Set = the child gets ONLY these vars (those present in process.env) plus the server's own `env` (which wins on a name clash; its `${VAR}` refs still resolve from the full process.env). `[]` = own env only. Measured (fwdloop F111/F111b, Linux, passEnv ['PATH','HOME']): tools/list worked for npx (barebrowse, baremobile), node (litectx) and sh-wrapped servers, and real tool calls worked too (litectx.recall via node; a HEADLESS barebrowse browse); adding DISPLAY, XDG_RUNTIME_DIR, TMPDIR or LANG changed nothing, so PATH + HOME is the measured minimum on Linux. Unmeasured: a headed (windowed) browser, and Windows (suggested: SYSTEMROOT, APPDATA, USERPROFILE, TEMP). Bridge-level, one list for all servers. Invalid shape throws `ValidationError` (type only).
1011
+ * @param {string} [opts.cwd] - Start folder for every spawned server (sibling of `passEnv`, bridge-level, opt-in). Unset (default) = the child starts in `process.cwd()`, byte-identical to before. A server's own `cwd` wins. Applied ONLY at spawn: never written to `.mcp-bridge.json`, and it does not move discovery (`./.mcp.json`, the default bridge path stay on `process.cwd()`). Validated once, before anything spawns: must be a non-empty ABSOLUTE path to an existing directory (no `~` expansion, no relative path), else `ValidationError` naming the reason only, never the value; this throws for the whole bridge. A folder deleted after validation, or a bad per-server `cwd`, is not validated up front: the server fails to start / lands in `errors`, labelled `working folder could not be used` with `context.cwdFailed:true` (the folder path is never named).
975
1012
  * @param {string[]} [opts.servers] - Limit to these server names (ignored when `allow` is given).
976
1013
  * @param {number} [opts.timeout=15000] - Per-server handshake timeout in ms (initialize + tools/list).
977
1014
  * @param {number} [opts.callTimeout=120000] - Per-invocation timeout in ms for tools/call. Bounds a
@@ -999,8 +1036,10 @@ async function createMCPBridge(opts = {}) {
999
1036
  'The static allow/deny filter in .mcp-bridge.json is unchanged.'
1000
1037
  );
1001
1038
  }
1002
- const passEnv = validatePassEnv(opts.passEnv, (msg) =>
1003
- new ValidationError(`[MCP Bridge] ${msg}`, { context: { lib: 'bare-agent' } }));
1039
+ const bridgeBad = (/** @type {string} */ msg) =>
1040
+ new ValidationError(`[MCP Bridge] ${msg}`, { context: { lib: 'bare-agent' } });
1041
+ const passEnv = validatePassEnv(opts.passEnv, bridgeBad);
1042
+ const cwd = validateBridgeCwd(opts.cwd, bridgeBad);
1004
1043
  const bridgePath = opts.bridgePath || DEFAULT_BRIDGE_PATH();
1005
1044
  const timeout = opts.timeout || 15000;
1006
1045
  // 0 is a valid explicit "unbounded"; only undefined falls back to the default.
@@ -1017,7 +1056,7 @@ async function createMCPBridge(opts = {}) {
1017
1056
  return createAllowBridge(allow, {
1018
1057
  configPaths: opts.configPaths,
1019
1058
  includeProjectConfig: opts.includeProjectConfig === true || !!confirmServer,
1020
- timeout, callTimeout, vetServer, warnUnvettedSpawn, passEnv,
1059
+ timeout, callTimeout, vetServer, warnUnvettedSpawn, passEnv, cwd,
1021
1060
  });
1022
1061
  }
1023
1062
 
@@ -1076,7 +1115,7 @@ async function createMCPBridge(opts = {}) {
1076
1115
  // Denied by confirmServer: skip silently — this is the caller's own
1077
1116
  // decision, not a connection failure, so it must not land in `errors`.
1078
1117
  if (!(await vetServer(name, def))) return;
1079
- const result = await connectAndListTools(name, def, timeout, { passEnv });
1118
+ const result = await connectAndListTools(name, def, timeout, { passEnv, cwd });
1080
1119
  connectResults.set(name, result.client);
1081
1120
  freshTools.set(name, result.mcpTools);
1082
1121
  } catch (err) {
@@ -1148,7 +1187,7 @@ async function createMCPBridge(opts = {}) {
1148
1187
  try {
1149
1188
  // Denied by confirmServer: skip silently (the caller's decision, not a failure).
1150
1189
  if (!(await vetServer(name, serverConf))) return;
1151
- const { mcpTools, client } = await connectAndListTools(name, serverConf, timeout, { passEnv });
1190
+ const { mcpTools, client } = await connectAndListTools(name, serverConf, timeout, { passEnv, cwd });
1152
1191
  // Track the child BEFORE any processing so close() reaps it even if what follows throws.
1153
1192
  children.push(client.child);
1154
1193
 
@@ -1221,6 +1260,7 @@ const listBad = (msg) => new ValidationError(`[MCP Bridge] listServerTools: ${ms
1221
1260
  * @param {(name: string, def: ServerDef) => boolean | Promise<boolean>} [opts.confirmServer] - Same semantics as createMCPBridge: `=== true` proceeds, a throw denies. Implies includeProjectConfig.
1222
1261
  * @param {boolean} [opts.includeProjectConfig=false] - Also scan `./.mcp.json` during default discovery.
1223
1262
  * @param {string[]} [opts.passEnv] - Same as createMCPBridge: restrict the spawned server's inherited env to these parent var names (unset = full inherit). Bad shape throws `ValidationError`.
1263
+ * @param {string} [opts.cwd] - Same as createMCPBridge: start folder for the spawned server (a server's own `cwd` wins). Absolute existing directory, else `ValidationError` (reason only).
1224
1264
  * @param {number} [opts.timeout=15000] - Per-round-trip bound in ms (initialize and each tools/list page).
1225
1265
  * @returns {Promise<Array<{name: string, description: string, annotations?: Record<string, any>}>>}
1226
1266
  * @when you want to list one MCP server's tools and their annotation hints before deciding what to allow — no bridge, no cache file, no tools kept alive
@@ -1234,6 +1274,7 @@ async function listServerTools(opts) {
1234
1274
  }
1235
1275
  const { server, configPaths, confirmServer, includeProjectConfig, timeout = 15000 } = opts;
1236
1276
  const passEnv = validatePassEnv(opts.passEnv, listBad);
1277
+ const cwd = validateBridgeCwd(opts.cwd, listBad);
1237
1278
  if (typeof server !== 'string' || server === '') {
1238
1279
  throw listBad(`server must be a non-empty string (got ${server === '' ? 'empty string' : typeName(server)})`);
1239
1280
  }
@@ -1261,7 +1302,7 @@ async function listServerTools(opts) {
1261
1302
  throw new ToolError(`MCP server "${server}" was not approved by confirmServer`, { context: { server, denied: true } });
1262
1303
  }
1263
1304
 
1264
- const { mcpTools, client } = await connectAndListTools(server, def, timeout, { deadlineMs: timeout * LIST_DEADLINE_MULTIPLIER, passEnv });
1305
+ const { mcpTools, client } = await connectAndListTools(server, def, timeout, { deadlineMs: timeout * LIST_DEADLINE_MULTIPLIER, passEnv, cwd });
1265
1306
  try {
1266
1307
  return mcpTools.map(t => {
1267
1308
  if (t === null || typeof t !== 'object' || typeof t.name !== 'string' || t.name === '') {
@@ -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
  };