fwdloop 0.4.0 → 0.5.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.
@@ -0,0 +1,249 @@
1
+ // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED"): the granted tools a step's live model call actually gets. Menu-
3
+ // is-inventory (M1's own rule, carried here): a verb the catalogue doesn't
4
+ // carry is a red, never a stub.
5
+ //
6
+ // borrowed-from: fwdloop poc/m0/runner.mjs@76a3607 (the `shellTool` lookup
7
+ // over `createShellTools()`, and read/write going through a real baresuite
8
+ // primitive rather than a second bespoke fs call) and fwdloop
9
+ // poc/m0/csv.mjs@76a3607 / poc/m0/docx.mjs@76a3607 (now ported at
10
+ // src/csv.js / src/docx.js — fwdloop's own citation-contract primitives,
11
+ // F13). Rewritten for M2's shape: `read`/`write`/`grep` are sandboxed here
12
+ // (M0b handed the model no tools directly and had the runner call
13
+ // `execute` itself; M2's executor hands granted tools straight to the
14
+ // model, so the sandbox check must live INSIDE each tool's own `execute`,
15
+ // not in a caller the model never reaches).
16
+ //
17
+ // Scope note (flagged, not invented quietly): only `read`, `write`, `grep`,
18
+ // `readDocx`, `addressCells` are wired here — the catalogue's litectx verbs
19
+ // (`recall`, `get`, `recent`, `compress`, `peek`, `stash`, `remember`,
20
+ // `forget`) are catalogue-present but NOT resolved by this piece; a step
21
+ // granted one of them gets every OTHER granted verb and a `reds` entry
22
+ // naming the gap, rather than a hard stop for the whole step — this is a
23
+ // signed-scope gap for hamr's ruling (job #2's step 3 declares `compress`,
24
+ // which this piece cannot yet honour).
25
+
26
+ import { readFileSync } from 'node:fs';
27
+ import path from 'node:path';
28
+ import { createShellTools } from 'bare-agent/tools';
29
+
30
+ import { primitiveFor } from './catalogue.js';
31
+ import { readDocxText } from './docx.js';
32
+ import { parseCsv } from './csv.js';
33
+
34
+ const { tools: SHELL_TOOLS } = createShellTools();
35
+
36
+ function shellTool(name) {
37
+ const found = SHELL_TOOLS.find((t) => t.name === name);
38
+ if (!found) throw new Error(`primitives: bare-agent/tools does not export a "${name}" tool`);
39
+ return found;
40
+ }
41
+
42
+ /** True when `candidate` resolves inside one of `allowedRoots` (or IS one of
43
+ * them) — lexical containment only, matching `src/runner.js`'s own
44
+ * `checkSendDestination` shape (a symlink escape is out of this check's
45
+ * scope; the run dir is created fresh by `runFlow`, never attacker-placed). */
46
+ function isPathAllowed(candidate, allowedRoots) {
47
+ const resolved = path.resolve(candidate);
48
+ return allowedRoots.some((root) => {
49
+ const r = path.resolve(root);
50
+ return resolved === r || resolved.startsWith(r + path.sep);
51
+ });
52
+ }
53
+
54
+ function sandboxError(verb, candidatePath) {
55
+ return new Error(`${verb}: "${candidatePath}" is outside the sandbox (the run dir and its frozen inputs) — refused`);
56
+ }
57
+
58
+ /** Which primitive owns a frozen input's text, by extension of its frozen path —
59
+ * `.md`/`.txt` are read/grep's own text roles, `.docx` belongs to `readDocx`,
60
+ * `.csv` belongs to `addressCells`, anything else has no text primitive.
61
+ * Pure and exported so tests can hit the four cases directly (F41 item 3). */
62
+ export function rolePrimitiveFor(frozenPath) {
63
+ const ext = path.extname(frozenPath).toLowerCase();
64
+ if (ext === '.md' || ext === '.txt') return 'read';
65
+ if (ext === '.docx') return 'readDocx';
66
+ if (ext === '.csv') return 'addressCells';
67
+ return null;
68
+ }
69
+
70
+ /** `read`/`grep` (unlike `write`) may also be granted a `role` naming one of
71
+ * the run's frozen inputs — the same `inputsByRole` map `readDocx`/
72
+ * `addressCells` use. `role` resolves to the frozen path and THEN goes
73
+ * through the same sandbox check as any path (the frozen path is always
74
+ * inside `allowedRoots`, so this can never widen what a path-only call
75
+ * could already reach) — never a shortcut around the sandbox, just a name
76
+ * for a path the model was never handed directly. `role` wins when both
77
+ * `path` and `role` are given. */
78
+ function roleDescription(real, roles) {
79
+ return `${real.description} Provide either "path" (sandboxed to the run dir and its frozen `
80
+ + `inputs) or "role" naming a frozen input by role instead of a path — at least one of `
81
+ + `path/role is required, and role wins if both are given. Available roles: ${roles.join(', ') || '(none)'}.`;
82
+ }
83
+
84
+ function roleParameters(real, roles) {
85
+ const properties = { ...real.parameters.properties };
86
+ // An empty enum is invalid JSON Schema — when there are no text roles, omit
87
+ // `role` from the schema entirely rather than advertise a role that can never
88
+ // be picked (F41 item 3: read/grep list only roles they can actually serve).
89
+ if (roles.length > 0) properties.role = { type: 'string', enum: roles };
90
+ return {
91
+ ...real.parameters,
92
+ properties,
93
+ required: (real.parameters.required ?? []).filter((f) => f !== 'path'),
94
+ };
95
+ }
96
+
97
+ /** Resolves `args.role`/`args.path` down to the one path to actually use,
98
+ * honouring "role wins if both given" and the sandbox check. Throws (never
99
+ * silently falls through) when neither is usable. `roles` is the TEXT-only
100
+ * role list (for the "no frozen input" message); the role lookup itself
101
+ * goes through the full `inputsByRole` map so a non-text role (e.g. a
102
+ * .docx) is refused BY NAME naming the primitive that owns it, even if the
103
+ * model passes a role the schema's enum never offered it (F41 item 3). */
104
+ function resolveRoleOrPath(verb, args, inputsByRole, roles, allowedRoots) {
105
+ if (args && Object.prototype.hasOwnProperty.call(args, 'role') && args.role !== undefined) {
106
+ const frozen = inputsByRole[args.role];
107
+ if (!frozen) throw new Error(`${verb}: no frozen input for role "${args.role}" (available: ${roles.join(', ')})`);
108
+ const owner = rolePrimitiveFor(frozen);
109
+ if (owner === 'readDocx') throw new Error(`${verb}: role "${args.role}" is a .docx — use readDocx`);
110
+ if (owner === 'addressCells') throw new Error(`${verb}: role "${args.role}" is a .csv — use addressCells`);
111
+ if (owner !== 'read') {
112
+ const ext = path.extname(frozen) || '(no extension)';
113
+ throw new Error(`${verb}: role "${args.role}" is a ${ext} — no text primitive serves it`);
114
+ }
115
+ return frozen;
116
+ }
117
+ if (!isPathAllowed(args?.path, allowedRoots)) throw sandboxError(verb, args?.path);
118
+ return args.path;
119
+ }
120
+
121
+ function sandboxedReadTool(allowedRoots, inputsByRole) {
122
+ const real = shellTool('shell_read');
123
+ const textRoles = Object.keys(inputsByRole).filter((r) => rolePrimitiveFor(inputsByRole[r]) === 'read');
124
+ return {
125
+ name: 'read',
126
+ description: roleDescription(real, textRoles),
127
+ parameters: roleParameters(real, textRoles),
128
+ execute: async (args) => {
129
+ const path = resolveRoleOrPath('read', args, inputsByRole, textRoles, allowedRoots);
130
+ return real.execute({ ...args, path });
131
+ },
132
+ };
133
+ }
134
+
135
+ function sandboxedGrepTool(allowedRoots, inputsByRole) {
136
+ const real = shellTool('shell_grep');
137
+ const textRoles = Object.keys(inputsByRole).filter((r) => rolePrimitiveFor(inputsByRole[r]) === 'read');
138
+ return {
139
+ name: 'grep',
140
+ description: roleDescription(real, textRoles),
141
+ parameters: roleParameters(real, textRoles),
142
+ execute: async (args) => {
143
+ const path = resolveRoleOrPath('grep', args, inputsByRole, textRoles, allowedRoots);
144
+ return real.execute({ ...args, path });
145
+ },
146
+ };
147
+ }
148
+
149
+ function sandboxedWriteTool(allowedRoots) {
150
+ const real = shellTool('shell_write');
151
+ return {
152
+ name: 'write',
153
+ description: real.description,
154
+ parameters: real.parameters,
155
+ execute: async (args) => {
156
+ if (!isPathAllowed(args?.path, allowedRoots)) throw sandboxError('write', args?.path);
157
+ return real.execute(args);
158
+ },
159
+ };
160
+ }
161
+
162
+ /** `readDocx`/`addressCells` take a `role` naming one of the run's frozen
163
+ * inputs (never a raw path — the model is never handed a filesystem path
164
+ * to type back, so there is nothing to sandbox-check on the way in). */
165
+ function readDocxPrimitiveTool(inputsByRole) {
166
+ const roles = Object.keys(inputsByRole);
167
+ return {
168
+ name: 'readDocx',
169
+ description: `Read a Word (.docx) file's text, by role. Available roles: ${roles.join(', ') || '(none)'}.`,
170
+ parameters: {
171
+ type: 'object', properties: { role: { type: 'string', enum: roles } }, required: ['role'],
172
+ },
173
+ execute: async ({ role }) => {
174
+ const frozen = inputsByRole[role];
175
+ if (!frozen) throw new Error(`readDocx: no frozen input for role "${role}" (available: ${roles.join(', ')})`);
176
+ const result = readDocxText(frozen);
177
+ if (!result.ok) throw new Error(`readDocx: ${result.red}`);
178
+ return { text: result.text, paragraphs: result.paragraphs };
179
+ },
180
+ };
181
+ }
182
+
183
+ function addressCellsPrimitiveTool(inputsByRole) {
184
+ const roles = Object.keys(inputsByRole);
185
+ return {
186
+ name: 'addressCells',
187
+ description: `Read a CSV spreadsheet as addressable cells, by role. Available roles: ${roles.join(', ') || '(none)'}.`,
188
+ parameters: {
189
+ type: 'object', properties: { role: { type: 'string', enum: roles } }, required: ['role'],
190
+ },
191
+ execute: async ({ role }) => {
192
+ const frozen = inputsByRole[role];
193
+ if (!frozen) throw new Error(`addressCells: no frozen input for role "${role}" (available: ${roles.join(', ')})`);
194
+ const text = readFileSync(frozen, 'utf8');
195
+ const { header, rows } = parseCsv(text);
196
+ return { kind: 'cells', header, rows };
197
+ },
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Resolve the granted tools for one step's model call. Never throws —
203
+ * a verb absent from the catalogue, or present but unimplemented here, is
204
+ * reported in `reds` and simply absent from `tools` (menu-is-inventory:
205
+ * absence, not a stub).
206
+ *
207
+ * @param {import('./types.js').CatalogueEntry[]} catalogue - `loadCatalogue().primitives` (or an injected test catalogue).
208
+ * @param {string[]} grantedVerbs - `step.primitives`.
209
+ * @param {{ runDir: string, inputs?: Array<{id:string, frozen:string}> }} ctx
210
+ * @returns {{ tools: Record<string, any>, reds: string[] }}
211
+ */
212
+ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
213
+ const { runDir, inputs = [] } = ctx;
214
+ const allowedRoots = [runDir, ...inputs.map((entry) => path.dirname(entry.frozen))];
215
+ const inputsByRole = Object.fromEntries(inputs.map((entry) => [entry.id, entry.frozen]));
216
+
217
+ const tools = {};
218
+ const reds = [];
219
+
220
+ for (const verb of grantedVerbs ?? []) {
221
+ const entry = primitiveFor(catalogue, verb);
222
+ if (!entry) {
223
+ reds.push(`primitives: verb "${verb}" is not in the catalogue`);
224
+ // eslint-disable-next-line no-continue
225
+ continue;
226
+ }
227
+ switch (verb) {
228
+ case 'read':
229
+ tools.read = sandboxedReadTool(allowedRoots, inputsByRole);
230
+ break;
231
+ case 'grep':
232
+ tools.grep = sandboxedGrepTool(allowedRoots, inputsByRole);
233
+ break;
234
+ case 'write':
235
+ tools.write = sandboxedWriteTool(allowedRoots);
236
+ break;
237
+ case 'readDocx':
238
+ tools.readDocx = readDocxPrimitiveTool(inputsByRole);
239
+ break;
240
+ case 'addressCells':
241
+ tools.addressCells = addressCellsPrimitiveTool(inputsByRole);
242
+ break;
243
+ default:
244
+ reds.push(`primitives: verb "${verb}" is in the catalogue but has no M2 implementation yet`);
245
+ }
246
+ }
247
+
248
+ return { tools, reds };
249
+ }
@@ -0,0 +1,306 @@
1
+ // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED", scope items 7/8): provider slots, hand-entered rates, the spend
3
+ // ceiling, the key preflight, and `makeProvider`. Money honesty (project
4
+ // rule, CLAUDE.md): unknown cost is NEVER rendered as 0 — an unknown model
5
+ // prices at the rate table's HIGHEST entry and the row is stamped
6
+ // `substituted`; `assertUnderGlobalCap`/`appendSpendRow` never coerce a null
7
+ // cost to a number.
8
+ //
9
+ // borrowed-from: fwdloop poc/m0/provider.mjs@76a3607 (`PROVIDER_SLOTS`,
10
+ // `makeProvider`, `resolveModelRate`, `MalformedToolCallTolerantOpenAI` —
11
+ // F28's tolerant wrapper for a DeepSeek tool-call whose `arguments` is bad
12
+ // JSON) and fwdloop poc/m0/spend.mjs@76a3607 (`RATES_BY_SUFFIX`,
13
+ // `lookupRate`, `ceilingCostUsd`, `classifyModelId`, `appendSpendRow`,
14
+ // `assertUnderGlobalCap`) and fwdloop poc/m1/slot-batch.mjs@76a3607
15
+ // (`checkKeyPreflight`: refuse an unset/empty/whitespace/newline key at $0,
16
+ // before any ledger write — F26/2026-09-21's live defect). Rewritten
17
+ // against src/'s ESM style; src never imports from poc/.
18
+
19
+ import {
20
+ appendFileSync, existsSync, mkdirSync, readFileSync,
21
+ } from 'node:fs';
22
+ import { dirname } from 'node:path';
23
+ import { OpenAI } from 'bare-agent/providers';
24
+
25
+ /**
26
+ * F28 (2026-09-15): DeepSeek sometimes emits a tool-call whose
27
+ * `function.arguments` is not valid JSON. bare-agent's own `generate()`
28
+ * parses it unconditionally and throws a bare `SyntaxError` AFTER the HTTP
29
+ * round already succeeded (`data.usage` is known) — the right class for
30
+ * this is "no usable tool call" (metered, retried once, then red), never a
31
+ * transport fault. This wrapper stashes the last HTTP response and, on a
32
+ * `SyntaxError` whose response DID carry a tool call, returns a normal
33
+ * `generate()`-shaped result with `toolCalls: []` and a `malformedToolCall`
34
+ * extra field instead of throwing. Any other error rethrows unchanged.
35
+ */
36
+ class MalformedToolCallTolerantOpenAI extends OpenAI {
37
+ async _request(path, body, timeoutMs, deadlineMs) {
38
+ const data = await super._request(path, body, timeoutMs, deadlineMs);
39
+ this._lastData = data;
40
+ return data;
41
+ }
42
+
43
+ async generate(messages, tools = [], options = {}) {
44
+ this.lastMalformedToolCall = null;
45
+ try {
46
+ return await super.generate(messages, tools, options);
47
+ } catch (err) {
48
+ if (!(err instanceof SyntaxError)) throw err;
49
+ const msg = this._lastData?.choices?.[0]?.message;
50
+ const toolCalls = msg?.tool_calls;
51
+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) throw err;
52
+ const tc = toolCalls[0];
53
+ const rawArguments = typeof tc?.function?.arguments === 'string'
54
+ ? tc.function.arguments.slice(0, 500)
55
+ : '';
56
+ const malformedToolCall = { name: tc?.function?.name ?? null, rawArguments, error: err.message };
57
+ this.lastMalformedToolCall = malformedToolCall;
58
+ return {
59
+ text: msg.content || '',
60
+ toolCalls: [],
61
+ model: this._lastData.model || this.model,
62
+ stopReason: 'tool_use',
63
+ usage: this._normalizeUsage(this._lastData.usage),
64
+ malformedToolCall,
65
+ };
66
+ }
67
+ }
68
+ }
69
+
70
+ /** Provider slots. Frozen — add a new slot here, never inline a baseUrl/env
71
+ * var elsewhere. `deepseek` is the baseline (F12); `synthetic` is second. */
72
+ export const PROVIDER_SLOTS = Object.freeze({
73
+ synthetic: Object.freeze({
74
+ baseUrl: 'https://api.synthetic.new/openai/v1',
75
+ envVar: 'SYNTHETIC_API_KEY',
76
+ defaultModel: 'hf:Qwen/Qwen3.8-27B',
77
+ legacyMaxTokens: false,
78
+ }),
79
+ deepseek: Object.freeze({
80
+ baseUrl: 'https://api.deepseek.com',
81
+ envVar: 'DEEPSEEK_API_KEY',
82
+ // F22: 'deepseek-v4-flash' is retired, routed to DeepSeek-V4.1-Flash —
83
+ // request the live name so request === served.
84
+ defaultModel: 'deepseek-flash',
85
+ // F11: DeepSeek ignores `max_completion_tokens`; only the legacy
86
+ // `max_tokens` key bounds output.
87
+ legacyMaxTokens: true,
88
+ }),
89
+ });
90
+
91
+ /**
92
+ * List-rate ceilings (USD/1K tokens), hand-entered — see
93
+ * poc/m0/spend.mjs@76a3607 for sourcing notes per row. A rate changes by
94
+ * editing a row here, never a second table or a runtime flag (hamr's
95
+ * ruling, 2026-09-21).
96
+ */
97
+ export const RATES_BY_SUFFIX = {
98
+ 'zai-org/GLM-5.2': { in: 0.0006, out: 0.0022, source: 'published' },
99
+ 'moonshotai/Kimi-K3': { in: 0.0006, out: 0.0025, source: 'published' },
100
+ 'zai-org/GLM-5.3-Flash': { in: 0.00015, out: 0.0005, source: 'published' },
101
+ 'zai-org/GLM-4.7-Flash': { in: 0.00006, out: 0.0004, source: 'published' },
102
+ 'Qwen/Qwen3.8-27B': { in: 0.00015, out: 0.002, source: 'published' },
103
+ 'openai/gpt-oss-120b': { in: 0.00003, out: 0.00017, source: 'published' },
104
+ 'nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4': { in: 0.000085, out: 0.0004, source: 'published' },
105
+ 'syn:large:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
106
+ 'syn:small:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
107
+ 'deepseek-v4-flash': { in: 0.00044, out: 0.00132, source: 'published' }, // F22: retired name, historical rows only
108
+ 'deepseek-flash': { in: 0.0003, out: 0.0012, source: 'published' }, // DeepSeek-V4.1-Flash, cache-miss peak
109
+ 'deepseek-v4-pro': { in: 0.00132, out: 0.00396, source: 'published' },
110
+ };
111
+
112
+ /**
113
+ * Strip an `hf:` routing prefix and look up `suffix` with `Object.hasOwn` —
114
+ * never plain truthiness/`in`, which would let a suffix like `"constructor"`
115
+ * resolve to an inherited `Object.prototype` member.
116
+ */
117
+ export function lookupRate(modelId, ratesTable = RATES_BY_SUFFIX) {
118
+ if (!modelId) return null;
119
+ const suffix = String(modelId).replace(/^hf:/, '');
120
+ if (!Object.hasOwn(ratesTable, suffix)) return null;
121
+ return { suffix, rates: ratesTable[suffix] };
122
+ }
123
+
124
+ /** Resolve a modelId to its hand-entered rate row, or throw — a caller here
125
+ * must never carry forward a 0 rate. */
126
+ export function resolveModelRate(modelId, ratesTable = RATES_BY_SUFFIX) {
127
+ const resolved = lookupRate(modelId, ratesTable);
128
+ if (!resolved) throw new Error(`no hand-entered rate for model suffix "${String(modelId).replace(/^hf:/, '')}"`);
129
+ return resolved;
130
+ }
131
+
132
+ // The two hard bounds a round is priced against when its real cost is
133
+ // unavailable: no round in this tree ever emits more output than
134
+ // `CEILING_OUTPUT_TOKENS`, and no prompt this project sends exceeds
135
+ // `CEILING_INPUT_TOKENS` (a documented, generous bound — never a measured
136
+ // number passed off as exact).
137
+ export const CEILING_INPUT_TOKENS = 32000;
138
+ export const CEILING_OUTPUT_TOKENS = 16000;
139
+
140
+ /**
141
+ * The ceiling cost (USD) of one round of `modelId` — never 0, never null.
142
+ * A known model prices at its own rate; an unknown/missing model prices at
143
+ * the HIGHEST in/out rate anywhere in `ratesTable`.
144
+ */
145
+ export function ceilingCostUsd(modelId, ratesTable = RATES_BY_SUFFIX) {
146
+ const resolved = lookupRate(modelId, ratesTable);
147
+ const rates = resolved ? resolved.rates : {
148
+ in: Math.max(...Object.values(ratesTable).map((r) => r.in)),
149
+ out: Math.max(...Object.values(ratesTable).map((r) => r.out)),
150
+ };
151
+ return (CEILING_INPUT_TOKENS / 1000) * rates.in + (CEILING_OUTPUT_TOKENS / 1000) * rates.out;
152
+ }
153
+
154
+ /**
155
+ * Compare the model asked for against the model actually served.
156
+ * `match` identical; `prefix` identical once a routing prefix is stripped;
157
+ * `alias` a declared `syn:` alias resolving to a concrete model (expected);
158
+ * `substituted` a concrete request served by a DIFFERENT concrete model
159
+ * (the one that matters — the signed hash records the request, not what
160
+ * ran); `unreported` the provider told us nothing.
161
+ */
162
+ export function classifyModelId(requested, returned) {
163
+ if (!requested) return 'unreported';
164
+ if (returned === null || returned === undefined || returned === '') return 'unreported';
165
+ if (requested === returned) return 'match';
166
+ if (String(requested).replace(/^[a-z]+:/, '') === returned) return 'prefix';
167
+ if (/^syn:/.test(requested)) return 'alias';
168
+ return 'substituted';
169
+ }
170
+
171
+ /**
172
+ * Sum every round of one model attempt into one meter. Money honesty in the
173
+ * strict direction: if ANY round has no priced cost, `costUsd` is `null` —
174
+ * never 0, never a partial sum passed off as complete. `rounds` records how
175
+ * many rounds folded in.
176
+ */
177
+ export function sumMeterings(events) {
178
+ const rounds = Array.isArray(events) ? events.filter(Boolean) : [];
179
+ if (rounds.length === 0) {
180
+ return {
181
+ rounds: 0, tokens: null, costUsd: null, model: null, rateSource: null,
182
+ };
183
+ }
184
+ const tokens = {
185
+ inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreationTokens: 0,
186
+ };
187
+ let costUsd = 0;
188
+ let costKnown = true;
189
+ for (const ev of rounds) {
190
+ for (const key of Object.keys(tokens)) tokens[key] += ev?.usage?.[key] ?? 0;
191
+ if (ev?.costUsd == null) costKnown = false;
192
+ else costUsd += ev.costUsd;
193
+ }
194
+ const last = rounds[rounds.length - 1];
195
+ return {
196
+ rounds: rounds.length,
197
+ tokens,
198
+ costUsd: costKnown ? costUsd : null,
199
+ model: last?.model ?? null,
200
+ rateSource: last?.rateSource ?? null,
201
+ };
202
+ }
203
+
204
+ /** Append one spend row, stamping `modelMatch` — the one writer for
205
+ * spend.jsonl. Warns (never throws) on a `substituted` model. */
206
+ export function appendSpendRow(path, row) {
207
+ mkdirSync(dirname(path), { recursive: true });
208
+ const modelMatch = classifyModelId(row.model, row.modelReturned);
209
+ if (modelMatch === 'substituted') {
210
+ process.emitWarning(
211
+ `spend: asked for model "${row.model}" but the provider served "${row.modelReturned}" `
212
+ + '— the signed hash records the request, not what ran',
213
+ );
214
+ }
215
+ appendFileSync(path, `${JSON.stringify({ ...row, modelMatch })}\n`);
216
+ }
217
+
218
+ function readSpendTotal(path) {
219
+ if (!existsSync(path)) return 0;
220
+ const lines = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim());
221
+ let total = 0;
222
+ for (const line of lines) {
223
+ const row = JSON.parse(line);
224
+ total += row.costUsd === null || row.costUsd === undefined ? ceilingCostUsd(row.model) : row.costUsd;
225
+ }
226
+ return total;
227
+ }
228
+
229
+ /** Throws once total spend (every null row repriced at its ceiling) is at
230
+ * or over `capUsd`. */
231
+ export function assertUnderGlobalCap(path, capUsd) {
232
+ const total = readSpendTotal(path);
233
+ if (total >= capUsd) throw new Error(`global spend cap reached: $${total.toFixed(6)} >= $${capUsd.toFixed(2)} (${path})`);
234
+ return total;
235
+ }
236
+
237
+ /**
238
+ * $0 preflight before any draft round and before any ledger write: the key
239
+ * env var for `slotName` must be set, non-empty, and free of any
240
+ * whitespace/control character (F26, 2026-09-21: a two-line `pass` entry
241
+ * exported a key with a trailing newline — still truthy, so a bare
242
+ * `if (!apiKey)` never caught it). Never throws — `{ ok:true }` or
243
+ * `{ ok:false, message }`; `message` never includes the key's value.
244
+ *
245
+ * @param {string} slotName
246
+ * @param {Record<string,string|undefined>} [env]
247
+ */
248
+ export function checkKeyPreflight(slotName, env = process.env) {
249
+ const slotDef = PROVIDER_SLOTS[slotName];
250
+ if (!slotDef) return { ok: false, message: `key: unknown provider slot "${slotName}"` };
251
+ const varName = slotDef.envVar;
252
+ const value = env[varName];
253
+ if (value === undefined || value === '') {
254
+ return { ok: false, message: `key: ${varName} is not set — export it before running` };
255
+ }
256
+ if (/[\r\n]/.test(value)) {
257
+ return { ok: false, message: `key: ${varName} contains a newline — export only the first line of the pass entry` };
258
+ }
259
+ // eslint-disable-next-line no-control-regex -- deliberately matching whitespace/control chars, never logged
260
+ if (/[\s\x00-\x1F\x7F]/.test(value)) {
261
+ return { ok: false, message: `key: ${varName} contains whitespace/control characters — export only the first line of the pass entry` };
262
+ }
263
+ return { ok: true };
264
+ }
265
+
266
+ /**
267
+ * Build a provider for the given slot. Throws (never defaults) on an
268
+ * unknown slot, a missing/bad env key, or a model with no hand-entered
269
+ * rate. Returns `{ provider, rates, modelId, suffix, slot }`.
270
+ *
271
+ * `timeoutMs`/`deadlineMs` bound a silent socket (BA-18 idle) and a
272
+ * zombie-stream total wall clock (BA-19), respectively — see
273
+ * `LIVE_PROVIDER_OPTIONS` in src/model-step.js, the one writer of the live
274
+ * values this project uses.
275
+ *
276
+ * @param {string} slotName
277
+ * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number }} [options]
278
+ * @returns {{ provider: any, rates: {in:number, out:number}, modelId: string, suffix: string, slot: string }}
279
+ */
280
+ export function makeProvider(slotName, options = {}) {
281
+ const { model, timeoutMs, deadlineMs } = options;
282
+ const slot = PROVIDER_SLOTS[slotName];
283
+ if (!slot) {
284
+ throw new Error(`unknown provider slot "${slotName}" — known slots: ${Object.keys(PROVIDER_SLOTS).join(', ')}`);
285
+ }
286
+
287
+ const keyCheck = checkKeyPreflight(slotName);
288
+ if (!keyCheck.ok) throw new Error(keyCheck.message);
289
+
290
+ const apiKey = process.env[slot.envVar];
291
+ const modelId = model ?? slot.defaultModel;
292
+ const { suffix, rates } = resolveModelRate(modelId);
293
+
294
+ const provider = new MalformedToolCallTolerantOpenAI({
295
+ apiKey,
296
+ model: modelId,
297
+ baseUrl: slot.baseUrl,
298
+ legacyMaxTokens: slot.legacyMaxTokens === true,
299
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
300
+ ...(deadlineMs !== undefined ? { deadlineMs } : {}),
301
+ });
302
+
303
+ return {
304
+ provider, rates, modelId, suffix, slot: slotName,
305
+ };
306
+ }