fwdloop 0.14.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.
- package/bin/fwdloop +106 -31
- package/package.json +2 -2
- package/src/authoring.js +26 -11
- package/src/checked.js +9 -5
- package/src/closers.js +5 -0
- package/src/config.js +66 -4
- package/src/declaration.js +27 -1
- package/src/draft-steps.js +79 -0
- package/src/drafter.js +54 -15
- package/src/flow.js +220 -5
- package/src/flowmodel.js +30 -0
- package/src/input-facts.js +12 -3
- package/src/keysfile.js +51 -16
- package/src/model-step.js +13 -11
- package/src/monthly.js +9 -1
- package/src/panel/author.js +89 -24
- package/src/panel/authorcard.js +80 -20
- package/src/panel/authorflows.js +72 -21
- package/src/panel/authorresume.js +11 -10
- package/src/panel/authorstart.js +29 -19
- package/src/panel/data.js +62 -21
- package/src/panel/index.html +662 -185
- package/src/panel/resume.js +3 -3
- package/src/panel/server.js +5 -4
- package/src/panel/settings.js +138 -80
- package/src/panel/spawn.js +15 -9
- package/src/provider.js +136 -178
- package/src/providershapes.js +7 -7
- package/src/runner.js +47 -23
- package/src/signed-diff.js +71 -0
- package/src/thinking.js +55 -0
- package/types/authoring.d.ts +20 -7
- package/types/checked.d.ts +6 -4
- package/types/closers.d.ts +2 -0
- package/types/config.d.ts +9 -1
- package/types/draft-steps.d.ts +14 -0
- package/types/drafter.d.ts +13 -10
- package/types/flow.d.ts +42 -2
- package/types/flowmodel.d.ts +16 -0
- package/types/input-facts.d.ts +6 -1
- package/types/keysfile.d.ts +23 -6
- package/types/model-step.d.ts +1 -1
- package/types/monthly.d.ts +1 -0
- package/types/panel/author.d.ts +78 -6
- package/types/panel/authorcard.d.ts +53 -8
- package/types/panel/authorflows.d.ts +68 -6
- package/types/panel/authorresume.d.ts +2 -1
- package/types/panel/authorstart.d.ts +17 -6
- package/types/panel/data.d.ts +10 -6
- package/types/panel/resume.d.ts +2 -1
- package/types/panel/server.d.ts +3 -1
- package/types/panel/settings.d.ts +3 -1
- package/types/panel/spawn.d.ts +13 -4
- package/types/provider.d.ts +94 -284
- package/types/providershapes.d.ts +3 -4
- package/types/runner.d.ts +2 -4
- package/types/signed-diff.d.ts +10 -0
- 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
|
|
3
|
-
// ceiling, the key preflight, and `makeProvider`.
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// `
|
|
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 (`
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
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):
|
|
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
|
|
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
|
-
*
|
|
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.
|
|
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
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
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 (!
|
|
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 ??
|
|
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:
|
|
103
|
-
|
|
104
|
-
|
|
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:
|
|
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
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
|
|
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}
|
|
179
|
-
* @param {{
|
|
145
|
+
* @param {string} slotName
|
|
146
|
+
* @param {{ config?: Record<string, any>, model?: string }} [opts]
|
|
180
147
|
* @returns {{
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* source: { in: '
|
|
184
|
-
*
|
|
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
|
|
188
|
-
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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 `
|
|
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
|
|
240
|
-
*
|
|
241
|
-
*
|
|
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(
|
|
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)
|
|
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
|
|
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
|
|
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
|
-
|
|
401
|
-
|
|
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
|
|
419
|
-
* unknown
|
|
420
|
-
*
|
|
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,
|
|
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
|
-
*
|
|
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,
|
|
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
|
|
446
|
-
//
|
|
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
|
-
|
|
451
|
-
// The ONE
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
const
|
|
455
|
-
const
|
|
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
|
-
|
|
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,
|
|
434
|
+
provider, rates, modelId, slot: slotName, prices,
|
|
477
435
|
};
|
|
478
436
|
}
|
package/src/providershapes.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// borrowed-from: bareloop src/providerrows.js@5a5a811 (`SHAPES` only)
|
|
2
|
-
// M4d
|
|
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
|
|
10
|
-
*
|
|
11
|
-
* @type {readonly {id: string, label: 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'
|
|
15
|
-
Object.freeze({ id: 'openai-api', label: 'OpenAI-compatible'
|
|
16
|
-
Object.freeze({ id: 'gemini-api', label: 'Gemini'
|
|
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));
|