fwdloop 0.15.0 → 0.16.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.
Files changed (52) hide show
  1. package/bin/fwdloop +106 -31
  2. package/package.json +2 -2
  3. package/src/authoring.js +23 -11
  4. package/src/closers.js +5 -0
  5. package/src/config.js +66 -4
  6. package/src/declaration.js +25 -1
  7. package/src/draft-steps.js +79 -0
  8. package/src/drafter.js +54 -15
  9. package/src/flowmodel.js +30 -0
  10. package/src/input-facts.js +12 -3
  11. package/src/keysfile.js +51 -16
  12. package/src/model-step.js +13 -11
  13. package/src/monthly.js +9 -1
  14. package/src/panel/author.js +81 -22
  15. package/src/panel/authorcard.js +25 -17
  16. package/src/panel/authorflows.js +33 -18
  17. package/src/panel/authorresume.js +9 -8
  18. package/src/panel/authorstart.js +11 -9
  19. package/src/panel/data.js +3 -3
  20. package/src/panel/index.html +516 -146
  21. package/src/panel/resume.js +3 -3
  22. package/src/panel/server.js +4 -3
  23. package/src/panel/settings.js +138 -80
  24. package/src/panel/spawn.js +15 -9
  25. package/src/provider.js +136 -178
  26. package/src/providershapes.js +7 -7
  27. package/src/runner.js +38 -22
  28. package/src/thinking.js +55 -0
  29. package/types/authoring.d.ts +11 -4
  30. package/types/closers.d.ts +2 -0
  31. package/types/config.d.ts +9 -1
  32. package/types/draft-steps.d.ts +14 -0
  33. package/types/drafter.d.ts +13 -10
  34. package/types/flowmodel.d.ts +16 -0
  35. package/types/input-facts.d.ts +6 -1
  36. package/types/keysfile.d.ts +23 -6
  37. package/types/model-step.d.ts +1 -1
  38. package/types/monthly.d.ts +1 -0
  39. package/types/panel/author.d.ts +44 -6
  40. package/types/panel/authorcard.d.ts +21 -8
  41. package/types/panel/authorflows.d.ts +29 -6
  42. package/types/panel/authorresume.d.ts +2 -1
  43. package/types/panel/authorstart.d.ts +16 -6
  44. package/types/panel/data.d.ts +2 -2
  45. package/types/panel/resume.d.ts +2 -1
  46. package/types/panel/server.d.ts +3 -1
  47. package/types/panel/settings.d.ts +3 -1
  48. package/types/panel/spawn.d.ts +13 -4
  49. package/types/provider.d.ts +94 -284
  50. package/types/providershapes.d.ts +3 -4
  51. package/types/runner.d.ts +2 -4
  52. package/types/thinking.d.ts +25 -0
package/src/provider.js CHANGED
@@ -1,16 +1,15 @@
1
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.
2
+ // SIGNED", scope items 7/8): provider rows, the usable-model decision, the spend
3
+ // ceiling, the key preflight, and `makeProvider`. Providers, models, prices and addresses live in Settings
4
+ // only (M4d amendments 5 and 6): a provider is a key name in the keys file, nothing is built in. Money honesty (project rule,
5
+ // CLAUDE.md): unknown cost is NEVER rendered as 0 — a row with no booked cost reads
6
+ // "at least" (`spendRowCost`); `assertUnderGlobalCap`/`appendSpendRow` never coerce a
7
+ // null cost to a number.
8
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`,
9
+ // borrowed-from: fwdloop poc/m0/provider.mjs@76a3607 (`makeProvider`, `MalformedToolCallTolerantOpenAI` —
10
+ // F28's tolerant wrapper for a provider tool-call whose `arguments` is bad
11
+ // JSON) and fwdloop poc/m0/spend.mjs@76a3607 (`ceilingCostUsd`,
12
+ // `classifyModelId`, `appendSpendRow`,
14
13
  // `assertUnderGlobalCap`) and fwdloop poc/m1/slot-batch.mjs@76a3607
15
14
  // (`checkKeyPreflight`: refuse an unset/empty/whitespace/newline key at $0,
16
15
  // before any ledger write — F26/2026-09-21's live defect). Rewritten
@@ -23,24 +22,24 @@ import { dirname, basename } from 'node:path';
23
22
  import { readFileInside } from './flow.js';
24
23
  import { readConfig, configDoorHome } from './config.js';
25
24
  import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
26
- import { SHAPES } from './providershapes.js';
27
25
 
28
26
  /**
29
- * F28 (2026-09-15) / BA-27 (bare-agent >=0.47.0): DeepSeek sometimes emits a
27
+ * F28 (2026-09-15) / BA-27 (bare-agent >=0.47.0): some providers sometimes emit a
30
28
  * tool-call whose `function.arguments` is not valid JSON. Before 0.47,
31
29
  * bare-agent's own `generate()` threw a bare `SyntaxError` AFTER the HTTP
32
30
  * round already succeeded — losing the billed round and hanging metering.
33
- * As of 0.47, `OpenAI.generate()` (bare-agent/src/provider-openai.js, via
31
+ * As of 0.47, `OpenAI.generate()` (bare-agent's OpenAI-protocol client, via
34
32
  * `provider-toolcalls.js`'s `parseToolCalls`) no longer throws: it resolves
35
33
  * normally with `toolCalls: []` and a `malformedToolCall: { name, error }`
36
34
  * field already on the result. As of 0.48 the constructor option
37
- * `exposeMalformedArgs: true` (set in `makeProvider`) adds `rawArguments`
38
- * (capped upstream at 500 chars, `rawTruncated: true` when clipped). `Loop.run()` does not forward unknown
35
+ * `exposeMalformedArgs: true` (set in `makeProvider`) adds `rawArguments`; since 0.50
36
+ * it is the FULL raw string, uncapped (`rawTruncated` is never set), so `model-step.js`
37
+ * bounds what it logs or shows. `Loop.run()` does not forward unknown
39
38
  * `generate()` fields into its own return, so this wrapper ALSO stashes the
40
39
  * marker on the instance (`this.lastMalformedToolCall`, reset at the top of
41
40
  * every `generate()` call) — the one channel `runModelStepOnPrimitives`
42
41
  * (same provider reference) can read after `loop.run()` returns. We require
43
- * bare-agent >=0.48 (package.json `^0.49.0`) and never patch around its
42
+ * bare-agent >=0.50 (package.json `^0.52.0`) and never patch around its
44
43
  * private response internals.
45
44
  */
46
45
  class MalformedToolCallTolerantOpenAI extends OpenAI {
@@ -52,112 +51,36 @@ class MalformedToolCallTolerantOpenAI extends OpenAI {
52
51
  }
53
52
  }
54
53
 
55
- /** Provider slots. Frozen — add a new slot here, never inline a baseUrl/env
56
- * var elsewhere. `deepseek` is the baseline (F12); `synthetic` is second. */
57
- export const PROVIDER_SLOTS = Object.freeze({
58
- synthetic: Object.freeze({
59
- baseUrl: 'https://api.synthetic.new/openai/v1',
60
- envVar: 'SYNTHETIC_API_KEY',
61
- defaultModel: 'hf:Qwen/Qwen3.8-27B',
62
- shape: 'openai-api',
63
- legacyMaxTokens: false,
64
- }),
65
- deepseek: Object.freeze({
66
- baseUrl: 'https://api.deepseek.com',
67
- envVar: 'DEEPSEEK_API_KEY',
68
- // F22: 'deepseek-v4-flash' is retired, routed to DeepSeek-V4.1-Flash —
69
- // request the live name so request === served.
70
- defaultModel: 'deepseek-flash',
71
- shape: 'openai-api',
72
- // F11: DeepSeek ignores `max_completion_tokens`; only the legacy
73
- // `max_tokens` key bounds output.
74
- legacyMaxTokens: true,
75
- }),
76
- });
54
+ /** The API shape a row has until one is picked in Settings: the wire protocol most providers speak (a shape is a protocol, not a provider). */
55
+ const DEFAULT_SHAPE = 'openai-api';
56
+
57
+ /** A provider row is named by its key's env name (M4d amendment 6): letters, digits, underscore; not a place, not a model. */
58
+ const KEY_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
59
+ export const isKeyName = (v) => typeof v === 'string' && KEY_NAME_RE.test(v);
77
60
 
78
61
  /**
79
- * THE one lookup of a slot's model, API shape and address (M4d amendment 1). Every model call (run,
80
- * resume, model step, drafter), Test, Balance and the spend rows read the slot through this and nothing
81
- * else: a value saved on the Settings page (`config.providers[slot]`) wins per field, else the code
82
- * default above. A blank saved Base URL means the default FOR THE EFFECTIVE SHAPE: the slot's own code
83
- * address while the shape is the slot's code shape, else that shape's vendor address ('' = bare-agent's own).
84
- * Unknown slot throws. `config` is already-read config (see `readPriceConfig`); no I/O here.
62
+ * THE one lookup of a row's API shape, address and legacy-token tick (M4d amendment 6). A row IS its key's env name, so the slot name and the
63
+ * env var are the same word. What a row holds is only what the person typed in Settings (`config.providers[slot]`): nothing is built
64
+ * in, so a row nobody typed an address for has `baseUrl: ''` and cannot run or list models. Which model a call USES is decided by
65
+ * `resolveUsableModel`. An invalid name throws. `config` is already-read config (see `readPriceConfig`); no I/O here.
85
66
  * @param {string} slotName
86
67
  * @param {{ config?: Record<string, any> }} [opts]
87
- * @returns {{ slot: string, envVar: string, legacyMaxTokens: boolean,
88
- * model: string, shape: string, baseUrl: string,
89
- * defaults: { model: string, shape: string, baseUrl: string } }}
68
+ * @returns {{ slot: string, envVar: string, legacyMaxTokens: boolean, shape: string, baseUrl: string }}
90
69
  */
91
70
  export function resolveSlot(slotName, { config = {} } = {}) {
92
- if (!Object.hasOwn(PROVIDER_SLOTS, slotName)) {
93
- throw new Error(`unknown provider slot "${slotName}" — known slots: ${Object.keys(PROVIDER_SLOTS).join(', ')}`);
94
- }
95
- const def = PROVIDER_SLOTS[slotName];
71
+ if (!isKeyName(slotName)) throw new Error(`unknown provider "${slotName}" — a provider is the name of a key in your keys file`);
96
72
  const saved = (config.providers && Object.hasOwn(config.providers, slotName)) ? config.providers[slotName] : {};
97
- const shape = saved.shape ?? def.shape;
98
- const defaultBaseUrl = shape === def.shape ? def.baseUrl : (SHAPES.find((x) => x.id === shape)?.defaultUrl ?? '');
99
- const savedUrl = typeof saved.baseUrl === 'string' ? saved.baseUrl.replace(/\/+$/, '') : '';
73
+ const shape = saved.shape ?? DEFAULT_SHAPE;
100
74
  return {
101
75
  slot: slotName,
102
- envVar: def.envVar,
103
- legacyMaxTokens: def.legacyMaxTokens === true && shape === 'openai-api',
104
- model: saved.model ?? def.defaultModel,
76
+ envVar: slotName,
77
+ // F11: some providers ignore `max_completion_tokens`; only the legacy `max_tokens` key bounds their output. A per-row tick in Settings.
78
+ legacyMaxTokens: saved.legacyMaxTokens === true && shape === 'openai-api',
105
79
  shape,
106
- baseUrl: savedUrl !== '' ? savedUrl : defaultBaseUrl,
107
- defaults: { model: def.defaultModel, shape: def.shape, baseUrl: defaultBaseUrl },
80
+ baseUrl: typeof saved.baseUrl === 'string' ? saved.baseUrl.replace(/\/+$/, '') : '',
108
81
  };
109
82
  }
110
83
 
111
- /**
112
- * List-rate ceilings (USD/1K tokens), hand-entered — see
113
- * poc/m0/spend.mjs@76a3607 for sourcing notes per row. This table is the DEFAULT
114
- * price: a price set in Settings (`~/.config/fwdloop/config.json` `prices`, per
115
- * provider slot) wins over a row here, per field, through `resolvePrices` below —
116
- * the one lookup every model call is booked and cap-checked by (M4d, signed
117
- * 2026-10-05; that REPLACES the 2026-09-21 "edit a row here, never a runtime
118
- * flag" ruling). Cached input is priced as input
119
- * (M4d amendment 2): a row has no cache rate.
120
- */
121
- export const RATES_BY_SUFFIX = {
122
- 'zai-org/GLM-5.2': { in: 0.0006, out: 0.0022, source: 'published' },
123
- 'moonshotai/Kimi-K3': { in: 0.0006, out: 0.0025, source: 'published' },
124
- 'zai-org/GLM-5.3-Flash': { in: 0.00015, out: 0.0005, source: 'published' },
125
- 'zai-org/GLM-4.7-Flash': { in: 0.00006, out: 0.0004, source: 'published' },
126
- 'Qwen/Qwen3.8-27B': { in: 0.00015, out: 0.002, source: 'published' },
127
- 'openai/gpt-oss-120b': { in: 0.00003, out: 0.00017, source: 'published' },
128
- 'nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4': { in: 0.000085, out: 0.0004, source: 'published' },
129
- 'syn:large:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
130
- 'syn:small:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
131
- 'deepseek-v4-flash': { in: 0.00044, out: 0.00132, source: 'published' }, // F22: retired name, historical rows only
132
- // DeepSeek-V4.1-Flash, peak. Source: https://api-docs.deepseek.com/quick_start/pricing/ (fetched
133
- // 2026-10-05: cache miss $0.30, output $1.20 per 1M). The cache-hit
134
- // price is deliberately not used: cached input books at `in` (M4d amendment 2, signed 2026-10-06).
135
- 'deepseek-flash': { in: 0.0003, out: 0.0012, source: 'published' },
136
- 'deepseek-v4-pro': { in: 0.00132, out: 0.00396, source: 'published' },
137
- };
138
-
139
- /**
140
- * Strip an `hf:` routing prefix and look up `suffix` with `Object.hasOwn` —
141
- * never plain truthiness/`in`, which would let a suffix like `"constructor"`
142
- * resolve to an inherited `Object.prototype` member.
143
- * @param {string|null|undefined} modelId
144
- * @param {Record<string, any>} [ratesTable]
145
- */
146
- export function lookupRate(modelId, ratesTable = RATES_BY_SUFFIX) {
147
- if (!modelId) return null;
148
- const suffix = String(modelId).replace(/^hf:/, '');
149
- if (!Object.hasOwn(ratesTable, suffix)) return null;
150
- return { suffix, rates: ratesTable[suffix] };
151
- }
152
-
153
- /** Resolve a modelId to its hand-entered rate row, or throw — a caller here
154
- * must never carry forward a 0 rate. */
155
- export function resolveModelRate(modelId, ratesTable = RATES_BY_SUFFIX) {
156
- const resolved = lookupRate(modelId, ratesTable);
157
- if (!resolved) throw new Error(`no hand-entered rate for model suffix "${String(modelId).replace(/^hf:/, '')}"`);
158
- return resolved;
159
- }
160
-
161
84
  // The two hard bounds a round is priced against when its real cost is
162
85
  // unavailable: no round in this tree ever emits more output than
163
86
  // `CEILING_OUTPUT_TOKENS`, and no prompt this project sends exceeds
@@ -168,47 +91,89 @@ export const CEILING_OUTPUT_TOKENS = 16000;
168
91
 
169
92
  const perM = (per1K) => Number((per1K * 1000).toPrecision(12));
170
93
 
94
+ const isPriced = (l) => l.use === true && typeof l.inPerM === 'number' && Number.isFinite(l.inPerM) && typeof l.outPerM === 'number' && Number.isFinite(l.outPerM);
95
+
96
+ /**
97
+ * A row's saved model lines (`config.models[slot]`) as Settings shows them; none saved = no lines. Nothing is built in
98
+ * and nothing is migrated: a line exists only because a person typed or ticked it.
99
+ * @param {string} slot
100
+ * @param {Record<string, any>} [config]
101
+ * @returns {Array<{ model: string, use: boolean, inPerM?: number, outPerM?: number }>}
102
+ */
103
+ export function effectiveModels(slot, config = {}) {
104
+ return config.models && Object.hasOwn(config.models, slot) ? config.models[slot] : [];
105
+ }
106
+
171
107
  /**
172
- * THE one price lookup (M4d scope item 6): every model call — run, resume, model step, drafter —
173
- * is booked and cap-checked from this. Per field: a Settings price (`config.prices[slot]`, USD per
174
- * 1M -> per 1K) wins, else the code table's row, else the table's HIGHEST entry for that field
175
- * (an unknown model; unknown cost is never 0). M4d amendment 2: cached input is priced AS input —
176
- * `cacheReadMult` is always 1; a saved `cachedInPerM` and a row's `cacheIn` are never read here.
108
+ * Every ticked, priced line of the given rows, in row order: what Chat's model menu offers and what a run may use (M4d amendment 6
109
+ * item 6). `rows` limits it to providers that still have a key (a model whose key is gone cannot run).
110
+ * @param {Record<string, any>} config @param {string[]} rows key names
111
+ * @returns {{ slot: string, model: string, label: string }[]}
112
+ */
113
+ export function tickedLines(config, rows) {
114
+ /** @type {{ slot: string, model: string, label: string }[]} */
115
+ const out = [];
116
+ for (const slot of rows) {
117
+ for (const l of effectiveModels(slot, config)) if (isPriced(l)) out.push({ slot, model: l.model, label: `${slot} · ${l.model}` });
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * The ticked, priced line a person names by model id (the command line): `--model <id>`, and `--provider <KEY>` when two keys tick the same id.
124
+ * Reads only the lines Settings holds. @param {Record<string, any>} config @param {{ model?: string, provider?: string }} [named]
125
+ * @returns {{ ok: true, slot: string, model: string } | { ok: false, say: string }}
126
+ */
127
+ export function pickTicked(config, { model, provider } = {}) {
128
+ const ticked = tickedLines(config, Object.keys(config.models ?? {}));
129
+ if (model === undefined || model === '') {
130
+ return { ok: false, say: ticked.length === 0 ? 'Tick a model in Settings > Providers with both prices first.' : 'Name the model with --model <id>: one ticked in Settings > Providers with both prices.' };
131
+ }
132
+ const hits = ticked.filter((l) => l.model === model && (provider === undefined || l.slot === provider));
133
+ if (hits.length === 0) return { ok: false, say: `Tick ${model} in Settings > Providers with both prices first.` };
134
+ if (hits.length > 1) return { ok: false, say: `${model} is ticked under more than one key (${hits.map((h) => h.slot).join(', ')}). Add --provider <KEY> to say which.` };
135
+ return { ok: true, slot: hits[0].slot, model };
136
+ }
137
+
138
+ /**
139
+ * THE one decision of "usable model" (M4d amendments 5 and 6): a model is usable only if it is ticked in Settings with both prices,
140
+ * under the named provider. Every model call - the drafter, a run, resume / continue, the command line, the panel - asks this and
141
+ * nothing else; no model name, price or switch lives in code. Returns the model, its provider and its prices (USD per 1M, and per 1K
142
+ * for the Loop; 0 / 0 is a chosen price), or a plain refusal in `say`.
143
+ * No model named: "Tick a model in Settings > Providers with both prices first." Pure: `config` is already-read config, no I/O.
177
144
  *
178
- * @param {string} modelId
179
- * @param {{ slot?: string, config?: Record<string, any>, ratesTable?: Record<string, any> }} [opts]
145
+ * @param {string} slotName
146
+ * @param {{ config?: Record<string, any>, model?: string }} [opts]
180
147
  * @returns {{
181
- * rates: { in: number, out: number, cacheReadMult?: number },
182
- * perM: { inPerM: number, cachedInPerM: number, outPerM: number },
183
- * source: { in: 'settings'|'table'|'ceiling', cachedIn: 'input', out: 'settings'|'table'|'ceiling' },
184
- * suffix: string|null,
185
- * }}
148
+ * ok: true, slot: string, model: string,
149
+ * rates: { in: number, out: number, cacheReadMult: number },
150
+ * prices: { perM: { inPerM: number, cachedInPerM: number, outPerM: number }, source: { in: 'model', cachedIn: 'input', out: 'model' } },
151
+ * } | { ok: false, say: string }}
186
152
  */
187
- export function resolvePrices(modelId, { slot, config = {}, ratesTable = RATES_BY_SUFFIX } = {}) {
188
- const resolved = lookupRate(modelId, ratesTable);
189
- const row = resolved ? resolved.rates : null;
190
- const set = (slot !== undefined && config.prices && Object.hasOwn(config.prices, slot)) ? config.prices[slot] : {};
191
- const ceilingOf = (field) => Math.max(...Object.values(ratesTable).map((r) => r[field]));
192
- const field = (settingsKey, rowField) => {
193
- if (set[settingsKey] !== undefined) return { v: set[settingsKey] / 1000, src: 'settings' };
194
- if (row) return { v: row[rowField], src: 'table' };
195
- return { v: ceilingOf(rowField), src: 'ceiling' };
196
- };
197
- const inF = field('inPerM', 'in');
198
- const outF = field('outPerM', 'out');
199
- /** @type {{ in: number, out: number, cacheReadMult: number }} */
200
- const rates = { in: inF.v, out: outF.v, cacheReadMult: 1 };
153
+ export function resolveUsableModel(slotName, { config = {}, model } = {}) {
154
+ if (model === undefined || model === '') return { ok: false, say: 'Tick a model in Settings > Providers with both prices first.' };
155
+ const line = effectiveModels(slotName, config).find((l) => l.model === model && isPriced(l));
156
+ if (!line) return { ok: false, say: `Tick ${model} in Settings > Providers with both prices first.` };
157
+ const inPerM = /** @type {number} */ (line.inPerM);
158
+ const outPerM = /** @type {number} */ (line.outPerM);
159
+ const inPer1K = inPerM / 1000;
160
+ const outPer1K = outPerM / 1000;
201
161
  return {
202
- rates,
203
- perM: { inPerM: perM(inF.v), cachedInPerM: perM(inF.v), outPerM: perM(outF.v) },
204
- source: { in: /** @type {any} */ (inF.src), cachedIn: 'input', out: /** @type {any} */ (outF.src) },
205
- suffix: resolved ? resolved.suffix : null,
162
+ ok: true,
163
+ slot: slotName,
164
+ model: line.model,
165
+ // cached input is priced AS input (M4d amendment 2): `cacheReadMult` is always 1
166
+ rates: { in: inPer1K, out: outPer1K, cacheReadMult: 1 },
167
+ prices: {
168
+ perM: { inPerM, cachedInPerM: inPerM, outPerM },
169
+ source: { in: 'model', cachedIn: 'input', out: 'model' },
170
+ },
206
171
  };
207
172
  }
208
173
 
209
174
  /**
210
175
  * The `price` object a spend row records: the per-1M numbers the call was booked at and where each
211
- * came from. From a `resolvePrices` result; or from INJECTED rates (tests) with source "injected".
176
+ * came from. From a `resolveUsableModel` result's `prices`; or from INJECTED rates (tests) with source "injected".
212
177
  * @param {{ perM: any, source: any }|null|undefined} prices
213
178
  * @param {{ in: number, out: number, cacheReadMult?: number }|null|undefined} [injectedRates]
214
179
  */
@@ -236,21 +201,17 @@ export function readPriceConfig(home) {
236
201
  }
237
202
 
238
203
  /**
239
- * The ceiling cost (USD) of one round of `modelId` — never 0, never null.
240
- * A known model prices at its own rate; an unknown/missing model prices at
241
- * the HIGHEST in/out rate anywhere in `ratesTable`. `opts.prices` (a
242
- * `resolvePrices` result, e.g. from `makeProvider`) makes the cap check use the
243
- * SAME price the round is booked at.
204
+ * The money hold (USD) of one round: the picked model's OWN Settings prices (`rates`, per 1K tokens, from
205
+ * `resolveUsableModel`) times the two token bounds above. Not a table, not a fallback.
206
+ * @param {{ in: number, out: number }} rates
244
207
  */
245
- export function ceilingCostUsd(modelId, ratesTable = RATES_BY_SUFFIX, opts = {}) {
246
- const { rates } = opts.prices ?? resolvePrices(modelId, { ratesTable });
208
+ export function ceilingCostUsd(rates) {
247
209
  return (CEILING_INPUT_TOKENS / 1000) * rates.in + (CEILING_OUTPUT_TOKENS / 1000) * rates.out;
248
210
  }
249
211
 
250
212
  /**
251
213
  * Compare the model asked for against the model actually served.
252
214
  * `match` identical; `prefix` identical once a routing prefix is stripped;
253
- * `alias` a declared `syn:` alias resolving to a concrete model (expected);
254
215
  * `substituted` a concrete request served by a DIFFERENT concrete model
255
216
  * (the one that matters — the signed hash records the request, not what
256
217
  * ran); `unreported` the provider told us nothing.
@@ -260,7 +221,6 @@ export function classifyModelId(requested, returned) {
260
221
  if (returned === null || returned === undefined || returned === '') return 'unreported';
261
222
  if (requested === returned) return 'match';
262
223
  if (String(requested).replace(/^[a-z]+:/, '') === returned) return 'prefix';
263
- if (/^syn:/.test(requested)) return 'alias';
264
224
  return 'substituted';
265
225
  }
266
226
 
@@ -321,13 +281,15 @@ export function appendSpendRow(path, row) {
321
281
  // "missing", never as some outside file's content folded into a cap check
322
282
  // or shown on the panel.
323
283
  // A row with no booked cost is repriced at ITS OWN booked price's ceiling when it recorded one
324
- // (M4d: forward only — today's Settings price never re-prices an old row), else at the code table's.
284
+ // (M4d: forward only — today's Settings price never re-prices an old row). A row that recorded no price at all (an
285
+ // old row; the code table that once priced it is gone, M4d amendment 5) has no ceiling to add: 0 here, and the row
286
+ // stays `complete: false`, so every total that holds it reads "at least", never as a clean figure.
325
287
  function rowCeilingUsd(row) {
326
288
  const p = row.price;
327
289
  if (p && typeof p === 'object' && Number.isFinite(p.inPerM) && p.inPerM > 0 && Number.isFinite(p.outPerM) && p.outPerM > 0) {
328
290
  return (CEILING_INPUT_TOKENS / 1e6) * p.inPerM + (CEILING_OUTPUT_TOKENS / 1e6) * p.outPerM;
329
291
  }
330
- return ceilingCostUsd(row.model);
292
+ return 0;
331
293
  }
332
294
 
333
295
  /**
@@ -387,7 +349,7 @@ export function assertUnderGlobalCap(path, capUsd) {
387
349
 
388
350
  /**
389
351
  * $0 preflight before any draft round and before any ledger write: the key
390
- * env var for `slotName` must be set, non-empty, and free of any
352
+ * env var named `slotName` must be set, non-empty, and free of any
391
353
  * whitespace/control character (F26, 2026-09-21: a two-line `pass` entry
392
354
  * exported a key with a trailing newline — still truthy, so a bare
393
355
  * `if (!apiKey)` never caught it). Never throws — `{ ok:true }` or
@@ -397,9 +359,8 @@ export function assertUnderGlobalCap(path, capUsd) {
397
359
  * @param {Record<string,string|undefined>} [env]
398
360
  */
399
361
  export function checkKeyPreflight(slotName, env = process.env) {
400
- const slotDef = Object.hasOwn(PROVIDER_SLOTS, slotName) ? PROVIDER_SLOTS[slotName] : null;
401
- if (!slotDef) return { ok: false, message: `key: unknown provider slot "${slotName}"` };
402
- const varName = slotDef.envVar;
362
+ if (!isKeyName(slotName)) return { ok: false, message: `key: unknown provider "${slotName}"` };
363
+ const varName = slotName;
403
364
  const value = env[varName];
404
365
  if (value === undefined || value === '') {
405
366
  return { ok: false, message: `key: ${varName} is not set — export it before running` };
@@ -414,10 +375,13 @@ export function checkKeyPreflight(slotName, env = process.env) {
414
375
  return { ok: true };
415
376
  }
416
377
 
378
+ /** A model that is not usable (`resolveUsableModel`): its message is the plain sentence, shown as it is (no "key:" or "config:" prefix). */
379
+ export class ModelRefusal extends Error {}
380
+
417
381
  /**
418
- * Build a provider for the given slot. Throws (never defaults) on an
419
- * unknown slot, a missing/bad env key, or a model with no hand-entered
420
- * rate. Returns `{ provider, rates, modelId, suffix, slot }`.
382
+ * Build a provider for the given row (the name of a key). Throws (never defaults) on an
383
+ * unknown name, a row with no Base URL (typed in Settings), a missing/bad env key, or a model that is not usable (`resolveUsableModel`: ticked in Settings with
384
+ * both prices - the message is its plain sentence). Returns `{ provider, rates, modelId, slot, prices }`.
421
385
  *
422
386
  * `timeoutMs`/`deadlineMs` bound a silent socket (BA-18 idle) and a
423
387
  * zombie-stream total wall clock (BA-19), respectively — see
@@ -425,42 +389,36 @@ export function checkKeyPreflight(slotName, env = process.env) {
425
389
  * values this project uses.
426
390
  *
427
391
  * @param {string} slotName
428
- * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null, env?: Record<string,string|undefined>, configHome?: string }} [options]
392
+ * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, env?: Record<string,string|undefined>, configHome?: string }} [options]
429
393
  * `configHome` (a test) is where `config.json` prices are read; default: the door's home (`readPriceConfig`).
430
394
  * `env` (M4d: the merged shell+keys-file env; default process.env) is where the key is read.
431
- * `thinking` (bare-agent >=0.49) is sent verbatim as body.thinking; unset/null leaves the body unchanged.
432
- * @returns {{ provider: any, rates: {in:number, out:number, cacheReadMult?:number}, modelId: string, suffix: string|null, slot: string, prices: ReturnType<typeof resolvePrices> }}
395
+ * @returns {{ provider: any, rates: {in:number, out:number, cacheReadMult?:number}, modelId: string, slot: string, prices: { perM: any, source: any } }}
433
396
  */
434
397
  export function makeProvider(slotName, options = {}) {
435
398
  const {
436
- model, timeoutMs, deadlineMs, thinking, env = process.env, configHome,
399
+ model, timeoutMs, deadlineMs, env = process.env, configHome,
437
400
  } = options;
438
- if (!Object.hasOwn(PROVIDER_SLOTS, slotName)) {
439
- throw new Error(`unknown provider slot "${slotName}" — known slots: ${Object.keys(PROVIDER_SLOTS).join(', ')}`);
440
- }
441
-
442
401
  const keyCheck = checkKeyPreflight(slotName, env);
443
402
  if (!keyCheck.ok) throw new Error(keyCheck.message);
444
403
 
445
- // A broken config throws by name here; it never falls back to the code defaults or the table, so a
446
- // run's model, address or charge cannot change silently.
404
+ // A broken config throws by name here; it never falls back to a default, so a run's model, address or
405
+ // charge cannot change silently.
447
406
  const config = readPriceConfig(configHome);
448
407
  const slot = resolveSlot(slotName, { config });
449
408
  const apiKey = env[slot.envVar];
450
- const modelId = model ?? slot.model;
451
- // The ONE price lookup (a Settings price wins over the table; a model the table doesn't know prices
452
- // at the table's highest rate, suffix null — unknown cost is never 0).
453
- const prices = resolvePrices(modelId, { slot: slotName, config });
454
- const { rates } = prices;
455
- const suffix = prices.suffix;
409
+ if (slot.baseUrl === '') throw new ModelRefusal(`Type a Base URL for ${slotName} in Settings.`);
410
+ // The ONE decision of which model may be used, and at what price (M4d amendment 5).
411
+ const usable = resolveUsableModel(slotName, { config, model });
412
+ if (!usable.ok) throw new ModelRefusal(usable.say);
413
+ const modelId = usable.model;
414
+ const { rates, prices } = usable;
456
415
 
457
416
  const common = {
458
417
  apiKey,
459
418
  model: modelId,
460
- ...(slot.baseUrl !== '' ? { baseUrl: slot.baseUrl } : {}),
419
+ baseUrl: slot.baseUrl,
461
420
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
462
421
  ...(deadlineMs !== undefined ? { deadlineMs } : {}),
463
- ...(thinking != null ? { thinking } : {}),
464
422
  };
465
423
  const provider = slot.shape === 'anthropic-api' ? new Anthropic(common)
466
424
  : slot.shape === 'gemini-api' ? new Gemini(common)
@@ -473,6 +431,6 @@ export function makeProvider(slotName, options = {}) {
473
431
  });
474
432
 
475
433
  return {
476
- provider, rates, modelId, suffix, slot: slotName, prices,
434
+ provider, rates, modelId, slot: slotName, prices,
477
435
  };
478
436
  }
@@ -1,19 +1,19 @@
1
1
  // borrowed-from: bareloop src/providerrows.js@5a5a811 (`SHAPES` only)
2
- // M4d amendment 1 (docs/wiki/the-module-ladder.md, "M4d" Amendment 1): the API shapes the Settings
2
+ // M4d amendments 1 and 6 (docs/wiki/the-module-ladder.md, "M4d"): the API shapes the Settings
3
3
  // Providers dropdown offers. Only a shape `makeProvider` (src/provider.js) can really build is listed:
4
4
  // bare-agent/providers exports OpenAI, Anthropic and Gemini with the same constructor options we pass
5
5
  // (`apiKey`, `model`, `baseUrl`, `timeoutMs`, `deadlineMs`). Kept in its own file so config.js can
6
6
  // validate a shape without importing provider.js (which imports config.js).
7
7
 
8
8
  /**
9
- * `id` is the value saved in config.json; `defaultUrl` is the host a blank Base URL means for a slot
10
- * that has no code default of its own on this shape ('' = bare-agent's own default for that vendor).
11
- * @type {readonly {id: string, label: string, defaultUrl: string}[]}
9
+ * `id` is the value saved in config.json. A shape is a wire protocol, never a place: no web address lives here
10
+ * (M4d amendment 6 item 2) - each row's Base URL is typed in Settings.
11
+ * @type {readonly {id: string, label: string}[]}
12
12
  */
13
13
  export const SHAPES = Object.freeze([
14
- Object.freeze({ id: 'anthropic-api', label: 'Anthropic', defaultUrl: 'https://api.anthropic.com/v1' }),
15
- Object.freeze({ id: 'openai-api', label: 'OpenAI-compatible', defaultUrl: 'https://api.openai.com/v1' }),
16
- Object.freeze({ id: 'gemini-api', label: 'Gemini', defaultUrl: '' }),
14
+ Object.freeze({ id: 'anthropic-api', label: 'Anthropic' }),
15
+ Object.freeze({ id: 'openai-api', label: 'OpenAI-compatible' }),
16
+ Object.freeze({ id: 'gemini-api', label: 'Gemini' }),
17
17
  ]);
18
18
 
19
19
  export const SHAPE_IDS = Object.freeze(SHAPES.map((s) => s.id));
package/src/runner.js CHANGED
@@ -41,8 +41,9 @@ import {
41
41
  } from 'node:fs';
42
42
  import { createHash, randomUUID } from 'node:crypto';
43
43
  import {
44
- dirname, extname, isAbsolute, join, resolve, sep,
44
+ basename, dirname, extname, isAbsolute, join, resolve, sep,
45
45
  } from 'node:path';
46
+ import { parseCsv } from './csv.js';
46
47
  import { fileURLToPath } from 'node:url';
47
48
 
48
49
  import {
@@ -55,7 +56,7 @@ import {
55
56
  findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed,
56
57
  } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
57
58
  import { configHome, configDoorHome } from './config.js';
58
- import { closeByClass } from './closers.js';
59
+ import { closeByClass, isCellsPath } from './closers.js';
59
60
  import {
60
61
  appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
61
62
  } from './books.js';
@@ -83,7 +84,7 @@ export const MAX_ATTEMPTS = 4;
83
84
  * (audit.jsonl) stay the source of truth; this tolerance only absorbs
84
85
  * summation-order noise, not a real gap. A billionth of a dollar is ~6
85
86
  * orders of magnitude below the cheapest real round (audit rows here run
86
- * $0.0006+), so nothing a real tamper produces can hide inside it. */
87
+ * a few hundredths of a cent and up), so nothing a real tamper produces can hide inside it. */
87
88
  export const SPEND_TOLERANCE_USD = 1e-9;
88
89
 
89
90
  // ---------------------------------------------------------------------------
@@ -188,23 +189,17 @@ export function readHaltRecord(runDir) {
188
189
  }
189
190
 
190
191
  // ---------------------------------------------------------------------------
191
- // Money — piece 2 wires live provider rates; this piece takes a per-attempt
192
- // ceiling as injected data, defaulting to a frozen table's highest entry for
193
- // an unknown model id (never a silent $0/unbounded assumption).
192
+ // Money - the per-attempt hold is injected data: the caller works it out from the
193
+ // picked model's own Settings prices (`ceilingCostUsd(rates)`, src/provider.js) and passes
194
+ // it as `ceilingUsd`. No model name or price lives here (M4d amendment 5 item 4).
194
195
  // ---------------------------------------------------------------------------
195
196
 
196
- const CEILING_TABLE_USD = Object.freeze({
197
- 'deepseek-flash': 0.02,
198
- 'synthetic-default': 0.05,
199
- });
200
-
201
- /** @param {string|null|undefined} modelId */
202
- export function resolveCeilingUsd(modelId) {
203
- if (typeof modelId === 'string' && Object.prototype.hasOwnProperty.call(CEILING_TABLE_USD, modelId)) {
204
- return CEILING_TABLE_USD[modelId];
205
- }
206
- return Math.max(...Object.values(CEILING_TABLE_USD));
207
- }
197
+ /**
198
+ * The hold one model round must fit under the cap. A caller with a model passes the number from Settings prices;
199
+ * a caller with no model prices (a test double) holds nothing.
200
+ * @param {number|undefined} ceilingUsd
201
+ */
202
+ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number} */ (ceilingUsd) >= 0 ? /** @type {number} */ (ceilingUsd) : 0);
208
203
 
209
204
  // ---------------------------------------------------------------------------
210
205
  // The executor — "goal in, gap back", constructed WITHOUT its close and
@@ -574,11 +569,32 @@ function readArtifactsMapChecked(runDir, ids) {
574
569
  if (!result.ok && !result.missing) {
575
570
  return { ok: false, red: `artifact "${id}" — ${result.red}` };
576
571
  }
572
+ if (!result.ok && result.missing) {
573
+ // M4d amendment 8: an id no step wrote may name a frozen CSV input; a step reads it as cells, so a green check can cite it.
574
+ const input = readInputCells(runDir, id);
575
+ if (!input.ok && !input.missing) return { ok: false, red: `input "${id}" — ${input.red}` };
576
+ if (input.ok) { map[id] = input.value; continue; }
577
+ }
577
578
  map[id] = result.ok ? result.value : undefined;
578
579
  }
579
580
  return { ok: true, map };
580
581
  }
581
582
 
583
+ /** A frozen CSV input as `{kind:'cells', header, rows}` (the shape `addressCells` gives), checked against the sha256 recorded at freeze.
584
+ * Same three outcomes as `readArtifactResult`: not an input of this run (`missing`), refused (`red`), or the cells. */
585
+ function readInputCells(runDir, id) {
586
+ const manifest = readFileInside(runDir, 'inputs.json');
587
+ if (!manifest.ok) return manifest.missing ? { ok: false, missing: true } : { ok: false, missing: false, red: manifest.red };
588
+ let entries;
589
+ try { entries = JSON.parse(manifest.text); } catch (err) { return { ok: false, missing: false, red: `inputs.json is not valid JSON — ${err.message}` }; }
590
+ const entry = Array.isArray(entries) ? entries.find((e) => e?.id === id) : undefined;
591
+ if (!entry || !isCellsPath(entry.frozen)) return { ok: false, missing: true };
592
+ const file = readFileInside(runDir, `inputs/${basename(entry.frozen)}`);
593
+ if (!file.ok) return file.missing ? { ok: false, missing: false, red: 'the frozen copy is missing' } : { ok: false, missing: false, red: file.red };
594
+ if (createHash('sha256').update(file.text).digest('hex') !== entry.sha256) return { ok: false, missing: false, red: 'the frozen copy changed since it was frozen' };
595
+ return { ok: true, value: { kind: 'cells', ...parseCsv(file.text) } };
596
+ }
597
+
582
598
  // ---------------------------------------------------------------------------
583
599
  // Item 4 (small): an `answer.json` still on disk, unconsumed, at run end —
584
600
  // a late human answer that arrived after the run already moved on. One
@@ -940,7 +956,7 @@ async function runStepRalph({
940
956
  * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
941
957
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
942
958
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
943
- * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
959
+ * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
944
960
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
945
961
  * run): a human's rerun reason, carried as the FIRST ordinary step's
946
962
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
@@ -1003,7 +1019,7 @@ export async function runFlow({
1003
1019
  const { arbiter } = applied;
1004
1020
  const capUsd = arbiter.capUsd;
1005
1021
  const redoCap = arbiter.redoCap ?? 3;
1006
- const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
1022
+ const effectiveCeilingUsd = holdOf(ceilingUsd);
1007
1023
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
1008
1024
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
1009
1025
 
@@ -2234,7 +2250,7 @@ export async function resumeRun({
2234
2250
 
2235
2251
  const capUsd = arbiter.capUsd;
2236
2252
  const redoCap = arbiter.redoCap ?? 3;
2237
- const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
2253
+ const effectiveCeilingUsd = holdOf(ceilingUsd);
2238
2254
 
2239
2255
  const step = steps[state.stepIndex];
2240
2256
  const askSlot = askLines.get(step.fromLine);
@@ -2518,7 +2534,7 @@ export async function continueRun({
2518
2534
  inputsManifest: halt.inputsManifest,
2519
2535
  capUsd,
2520
2536
  redoCap: arbiter.redoCap ?? 3,
2521
- effectiveCeilingUsd: ceilingUsd ?? resolveCeilingUsd(null),
2537
+ effectiveCeilingUsd: holdOf(ceilingUsd),
2522
2538
  primitives,
2523
2539
  businessDate,
2524
2540
  modelStep,