fwdloop 0.15.0 → 0.17.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 (72) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +113 -36
  3. package/package.json +2 -2
  4. package/src/authoring.js +27 -15
  5. package/src/catalogue.json +9 -3
  6. package/src/closers.js +5 -0
  7. package/src/config.js +66 -4
  8. package/src/ctx-tools.js +245 -0
  9. package/src/declaration.js +25 -1
  10. package/src/draft-steps.js +138 -0
  11. package/src/drafter.js +81 -18
  12. package/src/draftspend.js +109 -3
  13. package/src/flowmodel.js +30 -0
  14. package/src/input-facts.js +12 -3
  15. package/src/keysfile.js +51 -16
  16. package/src/liveness.js +34 -10
  17. package/src/model-step.js +13 -11
  18. package/src/monthly.js +9 -1
  19. package/src/panel/author.js +170 -43
  20. package/src/panel/authorcard.js +32 -20
  21. package/src/panel/authorflows.js +34 -19
  22. package/src/panel/authorresume.js +11 -9
  23. package/src/panel/authorstart.js +11 -9
  24. package/src/panel/authorvalues.js +5 -3
  25. package/src/panel/data.js +20 -8
  26. package/src/panel/index.html +584 -182
  27. package/src/panel/resume.js +3 -3
  28. package/src/panel/server.js +12 -6
  29. package/src/panel/settings.js +138 -80
  30. package/src/panel/spawn.js +15 -9
  31. package/src/plain-checks.js +51 -0
  32. package/src/primitives.js +34 -3
  33. package/src/provider.js +148 -181
  34. package/src/providershapes.js +7 -7
  35. package/src/run-store.js +47 -0
  36. package/src/runner.js +40 -22
  37. package/src/setup.js +3 -0
  38. package/src/thinking.js +55 -0
  39. package/src/version.js +13 -0
  40. package/types/authoring.d.ts +11 -6
  41. package/types/closers.d.ts +2 -0
  42. package/types/config.d.ts +9 -1
  43. package/types/ctx-tools.d.ts +18 -0
  44. package/types/draft-steps.d.ts +47 -0
  45. package/types/drafter.d.ts +15 -12
  46. package/types/draftspend.d.ts +56 -0
  47. package/types/flowmodel.d.ts +16 -0
  48. package/types/input-facts.d.ts +6 -1
  49. package/types/keysfile.d.ts +23 -6
  50. package/types/liveness.d.ts +7 -1
  51. package/types/model-step.d.ts +1 -1
  52. package/types/monthly.d.ts +1 -0
  53. package/types/panel/author.d.ts +47 -9
  54. package/types/panel/authorcard.d.ts +33 -10
  55. package/types/panel/authorflows.d.ts +32 -9
  56. package/types/panel/authorresume.d.ts +2 -1
  57. package/types/panel/authorstart.d.ts +16 -6
  58. package/types/panel/authorvalues.d.ts +3 -1
  59. package/types/panel/data.d.ts +2 -2
  60. package/types/panel/resume.d.ts +2 -1
  61. package/types/panel/server.d.ts +6 -2
  62. package/types/panel/settings.d.ts +3 -1
  63. package/types/panel/spawn.d.ts +13 -4
  64. package/types/plain-checks.d.ts +22 -0
  65. package/types/primitives.d.ts +0 -6
  66. package/types/provider.d.ts +100 -284
  67. package/types/providershapes.d.ts +3 -4
  68. package/types/run-store.d.ts +11 -0
  69. package/types/runner.d.ts +2 -4
  70. package/types/setup.d.ts +8 -0
  71. package/types/thinking.d.ts +25 -0
  72. package/types/version.d.ts +2 -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
@@ -22,25 +21,26 @@ import {
22
21
  import { dirname, basename } from 'node:path';
23
22
  import { readFileInside } from './flow.js';
24
23
  import { readConfig, configDoorHome } from './config.js';
24
+ import { isKeyName } from './keysfile.js';
25
25
  import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
26
- import { SHAPES } from './providershapes.js';
27
26
 
28
27
  /**
29
- * F28 (2026-09-15) / BA-27 (bare-agent >=0.47.0): DeepSeek sometimes emits a
28
+ * F28 (2026-09-15) / BA-27 (bare-agent >=0.47.0): some providers sometimes emit a
30
29
  * tool-call whose `function.arguments` is not valid JSON. Before 0.47,
31
30
  * bare-agent's own `generate()` threw a bare `SyntaxError` AFTER the HTTP
32
31
  * round already succeeded — losing the billed round and hanging metering.
33
- * As of 0.47, `OpenAI.generate()` (bare-agent/src/provider-openai.js, via
32
+ * As of 0.47, `OpenAI.generate()` (bare-agent's OpenAI-protocol client, via
34
33
  * `provider-toolcalls.js`'s `parseToolCalls`) no longer throws: it resolves
35
34
  * normally with `toolCalls: []` and a `malformedToolCall: { name, error }`
36
35
  * 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
36
+ * `exposeMalformedArgs: true` (set in `makeProvider`) adds `rawArguments`; since 0.50
37
+ * it is the FULL raw string, uncapped (`rawTruncated` is never set), so `model-step.js`
38
+ * bounds what it logs or shows. `Loop.run()` does not forward unknown
39
39
  * `generate()` fields into its own return, so this wrapper ALSO stashes the
40
40
  * marker on the instance (`this.lastMalformedToolCall`, reset at the top of
41
41
  * every `generate()` call) — the one channel `runModelStepOnPrimitives`
42
42
  * (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
43
+ * bare-agent >=0.50 (package.json `^0.52.0`) and never patch around its
44
44
  * private response internals.
45
45
  */
46
46
  class MalformedToolCallTolerantOpenAI extends OpenAI {
@@ -52,112 +52,38 @@ class MalformedToolCallTolerantOpenAI extends OpenAI {
52
52
  }
53
53
  }
54
54
 
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
- });
55
+ /** 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). */
56
+ const DEFAULT_SHAPE = 'openai-api';
57
+
58
+ /** A provider row is named by its key's env name (M4d amendment 6). M4d am21 item 4: ONE rule for what that name may be, `isKeyName` in src/keysfile.js (`…_KEY` in
59
+ * capitals): the same gate the keys file, the env pass-through and the log scrubber use, so a key a run can use is always one the scrubber knows. */
60
+ export { isKeyName };
61
+ /** The sentence part every refusal of a non-key name carries, so the rule is named wherever it is refused. */
62
+ export const KEY_NAME_RULE_SAY = 'a key name is written in capitals and ends in _KEY';
77
63
 
78
64
  /**
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.
65
+ * 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
66
+ * env var are the same word. What a row holds is only what the person typed in Settings (`config.providers[slot]`): nothing is built
67
+ * 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
68
+ * `resolveUsableModel`. An invalid name throws. `config` is already-read config (see `readPriceConfig`); no I/O here.
85
69
  * @param {string} slotName
86
70
  * @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 } }}
71
+ * @returns {{ slot: string, envVar: string, legacyMaxTokens: boolean, shape: string, baseUrl: string }}
90
72
  */
91
73
  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];
74
+ if (!isKeyName(slotName)) throw new Error(`unknown provider "${slotName}" — a provider is the name of a key in your keys file; ${KEY_NAME_RULE_SAY}`);
96
75
  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(/\/+$/, '') : '';
76
+ const shape = saved.shape ?? DEFAULT_SHAPE;
100
77
  return {
101
78
  slot: slotName,
102
- envVar: def.envVar,
103
- legacyMaxTokens: def.legacyMaxTokens === true && shape === 'openai-api',
104
- model: saved.model ?? def.defaultModel,
79
+ envVar: slotName,
80
+ // F11: some providers ignore `max_completion_tokens`; only the legacy `max_tokens` key bounds their output. A per-row tick in Settings.
81
+ legacyMaxTokens: saved.legacyMaxTokens === true && shape === 'openai-api',
105
82
  shape,
106
- baseUrl: savedUrl !== '' ? savedUrl : defaultBaseUrl,
107
- defaults: { model: def.defaultModel, shape: def.shape, baseUrl: defaultBaseUrl },
83
+ baseUrl: typeof saved.baseUrl === 'string' ? saved.baseUrl.replace(/\/+$/, '') : '',
108
84
  };
109
85
  }
110
86
 
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
87
  // The two hard bounds a round is priced against when its real cost is
162
88
  // unavailable: no round in this tree ever emits more output than
163
89
  // `CEILING_OUTPUT_TOKENS`, and no prompt this project sends exceeds
@@ -168,47 +94,89 @@ export const CEILING_OUTPUT_TOKENS = 16000;
168
94
 
169
95
  const perM = (per1K) => Number((per1K * 1000).toPrecision(12));
170
96
 
97
+ const isPriced = (l) => l.use === true && typeof l.inPerM === 'number' && Number.isFinite(l.inPerM) && typeof l.outPerM === 'number' && Number.isFinite(l.outPerM);
98
+
99
+ /**
100
+ * A row's saved model lines (`config.models[slot]`) as Settings shows them; none saved = no lines. Nothing is built in
101
+ * and nothing is migrated: a line exists only because a person typed or ticked it.
102
+ * @param {string} slot
103
+ * @param {Record<string, any>} [config]
104
+ * @returns {Array<{ model: string, use: boolean, inPerM?: number, outPerM?: number }>}
105
+ */
106
+ export function effectiveModels(slot, config = {}) {
107
+ return config.models && Object.hasOwn(config.models, slot) ? config.models[slot] : [];
108
+ }
109
+
110
+ /**
111
+ * 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
112
+ * item 6). `rows` limits it to providers that still have a key (a model whose key is gone cannot run).
113
+ * @param {Record<string, any>} config @param {string[]} rows key names
114
+ * @returns {{ slot: string, model: string, label: string }[]}
115
+ */
116
+ export function tickedLines(config, rows) {
117
+ /** @type {{ slot: string, model: string, label: string }[]} */
118
+ const out = [];
119
+ for (const slot of rows) {
120
+ for (const l of effectiveModels(slot, config)) if (isPriced(l)) out.push({ slot, model: l.model, label: `${slot} · ${l.model}` });
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * 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.
127
+ * Reads only the lines Settings holds. @param {Record<string, any>} config @param {{ model?: string, provider?: string }} [named]
128
+ * @returns {{ ok: true, slot: string, model: string } | { ok: false, say: string }}
129
+ */
130
+ export function pickTicked(config, { model, provider } = {}) {
131
+ const ticked = tickedLines(config, Object.keys(config.models ?? {}));
132
+ if (model === undefined || model === '') {
133
+ 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.' };
134
+ }
135
+ const hits = ticked.filter((l) => l.model === model && (provider === undefined || l.slot === provider));
136
+ if (hits.length === 0) return { ok: false, say: `Tick ${model} in Settings > Providers with both prices first.` };
137
+ 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.` };
138
+ return { ok: true, slot: hits[0].slot, model };
139
+ }
140
+
171
141
  /**
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.
142
+ * 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,
143
+ * under the named provider. Every model call - the drafter, a run, resume / continue, the command line, the panel - asks this and
144
+ * 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
145
+ * for the Loop; 0 / 0 is a chosen price), or a plain refusal in `say`.
146
+ * No model named: "Tick a model in Settings > Providers with both prices first." Pure: `config` is already-read config, no I/O.
177
147
  *
178
- * @param {string} modelId
179
- * @param {{ slot?: string, config?: Record<string, any>, ratesTable?: Record<string, any> }} [opts]
148
+ * @param {string} slotName
149
+ * @param {{ config?: Record<string, any>, model?: string }} [opts]
180
150
  * @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
- * }}
151
+ * ok: true, slot: string, model: string,
152
+ * rates: { in: number, out: number, cacheReadMult: number },
153
+ * prices: { perM: { inPerM: number, cachedInPerM: number, outPerM: number }, source: { in: 'model', cachedIn: 'input', out: 'model' } },
154
+ * } | { ok: false, say: string }}
186
155
  */
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 };
156
+ export function resolveUsableModel(slotName, { config = {}, model } = {}) {
157
+ if (model === undefined || model === '') return { ok: false, say: 'Tick a model in Settings > Providers with both prices first.' };
158
+ const line = effectiveModels(slotName, config).find((l) => l.model === model && isPriced(l));
159
+ if (!line) return { ok: false, say: `Tick ${model} in Settings > Providers with both prices first.` };
160
+ const inPerM = /** @type {number} */ (line.inPerM);
161
+ const outPerM = /** @type {number} */ (line.outPerM);
162
+ const inPer1K = inPerM / 1000;
163
+ const outPer1K = outPerM / 1000;
201
164
  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,
165
+ ok: true,
166
+ slot: slotName,
167
+ model: line.model,
168
+ // cached input is priced AS input (M4d amendment 2): `cacheReadMult` is always 1
169
+ rates: { in: inPer1K, out: outPer1K, cacheReadMult: 1 },
170
+ prices: {
171
+ perM: { inPerM, cachedInPerM: inPerM, outPerM },
172
+ source: { in: 'model', cachedIn: 'input', out: 'model' },
173
+ },
206
174
  };
207
175
  }
208
176
 
209
177
  /**
210
178
  * 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".
179
+ * came from. From a `resolveUsableModel` result's `prices`; or from INJECTED rates (tests) with source "injected".
212
180
  * @param {{ perM: any, source: any }|null|undefined} prices
213
181
  * @param {{ in: number, out: number, cacheReadMult?: number }|null|undefined} [injectedRates]
214
182
  */
@@ -236,21 +204,17 @@ export function readPriceConfig(home) {
236
204
  }
237
205
 
238
206
  /**
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.
207
+ * The money hold (USD) of one round: the picked model's OWN Settings prices (`rates`, per 1K tokens, from
208
+ * `resolveUsableModel`) times the two token bounds above. Not a table, not a fallback.
209
+ * @param {{ in: number, out: number }} rates
244
210
  */
245
- export function ceilingCostUsd(modelId, ratesTable = RATES_BY_SUFFIX, opts = {}) {
246
- const { rates } = opts.prices ?? resolvePrices(modelId, { ratesTable });
211
+ export function ceilingCostUsd(rates) {
247
212
  return (CEILING_INPUT_TOKENS / 1000) * rates.in + (CEILING_OUTPUT_TOKENS / 1000) * rates.out;
248
213
  }
249
214
 
250
215
  /**
251
216
  * Compare the model asked for against the model actually served.
252
217
  * `match` identical; `prefix` identical once a routing prefix is stripped;
253
- * `alias` a declared `syn:` alias resolving to a concrete model (expected);
254
218
  * `substituted` a concrete request served by a DIFFERENT concrete model
255
219
  * (the one that matters — the signed hash records the request, not what
256
220
  * ran); `unreported` the provider told us nothing.
@@ -260,7 +224,6 @@ export function classifyModelId(requested, returned) {
260
224
  if (returned === null || returned === undefined || returned === '') return 'unreported';
261
225
  if (requested === returned) return 'match';
262
226
  if (String(requested).replace(/^[a-z]+:/, '') === returned) return 'prefix';
263
- if (/^syn:/.test(requested)) return 'alias';
264
227
  return 'substituted';
265
228
  }
266
229
 
@@ -321,13 +284,20 @@ export function appendSpendRow(path, row) {
321
284
  // "missing", never as some outside file's content folded into a cap check
322
285
  // or shown on the panel.
323
286
  // 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.
325
- function rowCeilingUsd(row) {
287
+ // (M4d: forward only — today's Settings price never re-prices an old row). A row that recorded no price at all (an
288
+ // old row; the code table that once priced it is gone, M4d amendment 5) has no ceiling to add: 0 here, and the row
289
+ // stays `complete: false`, so every total that holds it reads "at least", never as a clean figure.
290
+ export function rowCeilingUsd(row) {
326
291
  const p = row.price;
327
292
  if (p && typeof p === 'object' && Number.isFinite(p.inPerM) && p.inPerM > 0 && Number.isFinite(p.outPerM) && p.outPerM > 0) {
328
293
  return (CEILING_INPUT_TOKENS / 1e6) * p.inPerM + (CEILING_OUTPUT_TOKENS / 1e6) * p.outPerM;
329
294
  }
330
- return ceilingCostUsd(row.model);
295
+ return 0;
296
+ }
297
+
298
+ /** How many calls of an incomplete row were never metered (at least one). @param {any} row */
299
+ export function unmeteredCalls(row) {
300
+ return Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
331
301
  }
332
302
 
333
303
  /**
@@ -339,7 +309,7 @@ function rowCeilingUsd(row) {
339
309
  */
340
310
  export function spendRowCost(row) {
341
311
  if (row.spendComplete === false) {
342
- const unmetered = Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
312
+ const unmetered = unmeteredCalls(row);
343
313
  return { usd: (row.costUsd ?? 0) + unmetered * rowCeilingUsd(row), complete: false };
344
314
  }
345
315
  if (row.costUsd === null || row.costUsd === undefined) return { usd: rowCeilingUsd(row), complete: false };
@@ -387,7 +357,7 @@ export function assertUnderGlobalCap(path, capUsd) {
387
357
 
388
358
  /**
389
359
  * $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
360
+ * env var named `slotName` must be set, non-empty, and free of any
391
361
  * whitespace/control character (F26, 2026-09-21: a two-line `pass` entry
392
362
  * exported a key with a trailing newline — still truthy, so a bare
393
363
  * `if (!apiKey)` never caught it). Never throws — `{ ok:true }` or
@@ -397,9 +367,8 @@ export function assertUnderGlobalCap(path, capUsd) {
397
367
  * @param {Record<string,string|undefined>} [env]
398
368
  */
399
369
  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;
370
+ if (!isKeyName(slotName)) return { ok: false, message: `key: unknown provider "${slotName}" — ${KEY_NAME_RULE_SAY}` };
371
+ const varName = slotName;
403
372
  const value = env[varName];
404
373
  if (value === undefined || value === '') {
405
374
  return { ok: false, message: `key: ${varName} is not set — export it before running` };
@@ -414,10 +383,13 @@ export function checkKeyPreflight(slotName, env = process.env) {
414
383
  return { ok: true };
415
384
  }
416
385
 
386
+ /** A model that is not usable (`resolveUsableModel`): its message is the plain sentence, shown as it is (no "key:" or "config:" prefix). */
387
+ export class ModelRefusal extends Error {}
388
+
417
389
  /**
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 }`.
390
+ * Build a provider for the given row (the name of a key). Throws (never defaults) on an
391
+ * 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
392
+ * both prices - the message is its plain sentence). Returns `{ provider, rates, modelId, slot, prices }`.
421
393
  *
422
394
  * `timeoutMs`/`deadlineMs` bound a silent socket (BA-18 idle) and a
423
395
  * zombie-stream total wall clock (BA-19), respectively — see
@@ -425,42 +397,36 @@ export function checkKeyPreflight(slotName, env = process.env) {
425
397
  * values this project uses.
426
398
  *
427
399
  * @param {string} slotName
428
- * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null, env?: Record<string,string|undefined>, configHome?: string }} [options]
400
+ * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, env?: Record<string,string|undefined>, configHome?: string }} [options]
429
401
  * `configHome` (a test) is where `config.json` prices are read; default: the door's home (`readPriceConfig`).
430
402
  * `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> }}
403
+ * @returns {{ provider: any, rates: {in:number, out:number, cacheReadMult?:number}, modelId: string, slot: string, prices: { perM: any, source: any } }}
433
404
  */
434
405
  export function makeProvider(slotName, options = {}) {
435
406
  const {
436
- model, timeoutMs, deadlineMs, thinking, env = process.env, configHome,
407
+ model, timeoutMs, deadlineMs, env = process.env, configHome,
437
408
  } = 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
409
  const keyCheck = checkKeyPreflight(slotName, env);
443
410
  if (!keyCheck.ok) throw new Error(keyCheck.message);
444
411
 
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.
412
+ // A broken config throws by name here; it never falls back to a default, so a run's model, address or
413
+ // charge cannot change silently.
447
414
  const config = readPriceConfig(configHome);
448
415
  const slot = resolveSlot(slotName, { config });
449
416
  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;
417
+ if (slot.baseUrl === '') throw new ModelRefusal(`Type a Base URL for ${slotName} in Settings.`);
418
+ // The ONE decision of which model may be used, and at what price (M4d amendment 5).
419
+ const usable = resolveUsableModel(slotName, { config, model });
420
+ if (!usable.ok) throw new ModelRefusal(usable.say);
421
+ const modelId = usable.model;
422
+ const { rates, prices } = usable;
456
423
 
457
424
  const common = {
458
425
  apiKey,
459
426
  model: modelId,
460
- ...(slot.baseUrl !== '' ? { baseUrl: slot.baseUrl } : {}),
427
+ baseUrl: slot.baseUrl,
461
428
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
462
429
  ...(deadlineMs !== undefined ? { deadlineMs } : {}),
463
- ...(thinking != null ? { thinking } : {}),
464
430
  };
465
431
  const provider = slot.shape === 'anthropic-api' ? new Anthropic(common)
466
432
  : slot.shape === 'gemini-api' ? new Gemini(common)
@@ -468,11 +434,12 @@ export function makeProvider(slotName, options = {}) {
468
434
  ...common,
469
435
  legacyMaxTokens: slot.legacyMaxTokens,
470
436
  // bare-agent >=0.48: opt in to the raw broken tool-call arguments on
471
- // `malformedToolCall` (capped upstream at 500 chars). Not exposeErrorBody.
437
+ // `malformedToolCall` (bare-agent >=0.50 hands over the full uncapped string; model-step.js
438
+ // bounds it, RAW_ARGS_BOUND). Not exposeErrorBody.
472
439
  exposeMalformedArgs: true,
473
440
  });
474
441
 
475
442
  return {
476
- provider, rates, modelId, suffix, slot: slotName, prices,
443
+ provider, rates, modelId, slot: slotName, prices,
477
444
  };
478
445
  }
@@ -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));
@@ -0,0 +1,47 @@
1
+ // M7 piece 2 (docs/wiki/the-module-ladder.md, "M7 scope — SIGNED", item 2): memory
2
+ // lasts one run only. Each run gets its own fresh litectx store and nothing carries
3
+ // into the next run.
4
+ //
5
+ // One function decides where a run's store lives (`runStoreDir`); everything else
6
+ // asks it. The store is a sibling of the run folder, under `<runs>/.stores/<runId>/`,
7
+ // so it is OUTSIDE the run dir and therefore outside every `readScope` the gate hands
8
+ // a step (read reaches the run dir and its frozen inputs' dirs, nothing above). A
9
+ // granted `read` cannot open the store's sqlite file as raw bytes. `.stores` is not a
10
+ // valid run id (a run id must start with a letter or digit), so run listings skip it.
11
+ //
12
+ // The store is opened per call and closed in `finally`: no handle outlives a tool
13
+ // call, so a restarted process (resume) finds the same run's store on disk and a
14
+ // different run never shares one.
15
+
16
+ import { rmSync } from 'node:fs';
17
+ import path from 'node:path';
18
+ import { createRequire } from 'node:module';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const { LiteCtx } = require('litectx');
22
+
23
+ /** The folder holding THIS run's store. A different run dir is a different folder.
24
+ * @param {string} runDir */
25
+ export function runStoreDir(runDir) {
26
+ const resolved = path.resolve(runDir);
27
+ return path.join(path.dirname(resolved), '.stores', path.basename(resolved));
28
+ }
29
+
30
+ /** Open this run's store, run `fn(lc)`, close it. `root` is the run dir: litectx indexes
31
+ * only its own extensions (.md .js .py ...) there, never the run's json/jsonl records.
32
+ * @template T @param {string} runDir @param {(lc: any) => Promise<T>|T} fn @returns {Promise<T>} */
33
+ export async function withRunStore(runDir, fn) {
34
+ const lc = new LiteCtx({ root: path.resolve(runDir), dbPath: path.join(runStoreDir(runDir), 'index.db') });
35
+ try {
36
+ return await fn(lc);
37
+ } finally {
38
+ lc.close();
39
+ }
40
+ }
41
+
42
+ /** A run STARTS with an empty store, never an inherited one: a run id can be reused (the next id is max+1, so deleting the last run
43
+ * folder hands its id to the next run) and the store sits beside the run folder, not in it. Called by the one place a fresh run
44
+ * begins (`runFlow`); resume and continue keep the run's own store. @param {string} runDir */
45
+ export function resetRunStore(runDir) {
46
+ rmSync(runStoreDir(runDir), { recursive: true, force: true });
47
+ }