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.
- package/README.md +2 -0
- package/bin/fwdloop +113 -36
- package/package.json +2 -2
- package/src/authoring.js +27 -15
- package/src/catalogue.json +9 -3
- package/src/closers.js +5 -0
- package/src/config.js +66 -4
- package/src/ctx-tools.js +245 -0
- package/src/declaration.js +25 -1
- package/src/draft-steps.js +138 -0
- package/src/drafter.js +81 -18
- package/src/draftspend.js +109 -3
- package/src/flowmodel.js +30 -0
- package/src/input-facts.js +12 -3
- package/src/keysfile.js +51 -16
- package/src/liveness.js +34 -10
- package/src/model-step.js +13 -11
- package/src/monthly.js +9 -1
- package/src/panel/author.js +170 -43
- package/src/panel/authorcard.js +32 -20
- package/src/panel/authorflows.js +34 -19
- package/src/panel/authorresume.js +11 -9
- package/src/panel/authorstart.js +11 -9
- package/src/panel/authorvalues.js +5 -3
- package/src/panel/data.js +20 -8
- package/src/panel/index.html +584 -182
- package/src/panel/resume.js +3 -3
- package/src/panel/server.js +12 -6
- package/src/panel/settings.js +138 -80
- package/src/panel/spawn.js +15 -9
- package/src/plain-checks.js +51 -0
- package/src/primitives.js +34 -3
- package/src/provider.js +148 -181
- package/src/providershapes.js +7 -7
- package/src/run-store.js +47 -0
- package/src/runner.js +40 -22
- package/src/setup.js +3 -0
- package/src/thinking.js +55 -0
- package/src/version.js +13 -0
- package/types/authoring.d.ts +11 -6
- package/types/closers.d.ts +2 -0
- package/types/config.d.ts +9 -1
- package/types/ctx-tools.d.ts +18 -0
- package/types/draft-steps.d.ts +47 -0
- package/types/drafter.d.ts +15 -12
- package/types/draftspend.d.ts +56 -0
- package/types/flowmodel.d.ts +16 -0
- package/types/input-facts.d.ts +6 -1
- package/types/keysfile.d.ts +23 -6
- package/types/liveness.d.ts +7 -1
- package/types/model-step.d.ts +1 -1
- package/types/monthly.d.ts +1 -0
- package/types/panel/author.d.ts +47 -9
- package/types/panel/authorcard.d.ts +33 -10
- package/types/panel/authorflows.d.ts +32 -9
- package/types/panel/authorresume.d.ts +2 -1
- package/types/panel/authorstart.d.ts +16 -6
- package/types/panel/authorvalues.d.ts +3 -1
- package/types/panel/data.d.ts +2 -2
- package/types/panel/resume.d.ts +2 -1
- package/types/panel/server.d.ts +6 -2
- package/types/panel/settings.d.ts +3 -1
- package/types/panel/spawn.d.ts +13 -4
- package/types/plain-checks.d.ts +22 -0
- package/types/primitives.d.ts +0 -6
- package/types/provider.d.ts +100 -284
- package/types/providershapes.d.ts +3 -4
- package/types/run-store.d.ts +11 -0
- package/types/runner.d.ts +2 -4
- package/types/setup.d.ts +8 -0
- package/types/thinking.d.ts +25 -0
- 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
|
|
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
|
|
@@ -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):
|
|
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
|
|
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
|
-
*
|
|
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.
|
|
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
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
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.
|
|
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 (!
|
|
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 ??
|
|
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:
|
|
103
|
-
|
|
104
|
-
|
|
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:
|
|
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
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
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}
|
|
179
|
-
* @param {{
|
|
148
|
+
* @param {string} slotName
|
|
149
|
+
* @param {{ config?: Record<string, any>, model?: string }} [opts]
|
|
180
150
|
* @returns {{
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* source: { in: '
|
|
184
|
-
*
|
|
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
|
|
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 };
|
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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 `
|
|
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
|
|
240
|
-
*
|
|
241
|
-
*
|
|
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(
|
|
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)
|
|
325
|
-
|
|
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
|
|
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 =
|
|
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
|
|
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
|
-
|
|
401
|
-
|
|
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
|
|
419
|
-
* unknown
|
|
420
|
-
*
|
|
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,
|
|
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
|
-
*
|
|
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,
|
|
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
|
|
446
|
-
//
|
|
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
|
-
|
|
451
|
-
// The ONE
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
const
|
|
455
|
-
const
|
|
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
|
-
|
|
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` (
|
|
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,
|
|
443
|
+
provider, rates, modelId, slot: slotName, prices,
|
|
477
444
|
};
|
|
478
445
|
}
|
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));
|
package/src/run-store.js
ADDED
|
@@ -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
|
+
}
|