fwdloop 0.10.0 → 0.12.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 +130 -20
- package/package.json +1 -1
- package/src/ask.js +200 -8
- package/src/authoring.js +34 -6
- package/src/config.js +255 -0
- package/src/drafter.js +12 -8
- package/src/keysfile.js +180 -0
- package/src/liveness.js +7 -7
- package/src/model-step.js +16 -6
- package/src/monthly.js +231 -0
- package/src/panel/data.js +200 -73
- package/src/panel/index.html +750 -120
- package/src/panel/lock.js +42 -0
- package/src/panel/resume.js +43 -7
- package/src/panel/server.js +295 -47
- package/src/panel/settings.js +268 -0
- package/src/provider.js +194 -35
- package/src/providershapes.js +19 -0
- package/src/runner.js +47 -10
- package/types/ask.d.ts +70 -1
- package/types/authoring.d.ts +3 -2
- package/types/config.d.ts +51 -0
- package/types/drafter.d.ts +4 -2
- package/types/keysfile.d.ts +90 -0
- package/types/liveness.d.ts +2 -1
- package/types/model-step.d.ts +3 -1
- package/types/monthly.d.ts +109 -0
- package/types/panel/data.d.ts +108 -29
- package/types/panel/lock.d.ts +21 -0
- package/types/panel/resume.d.ts +12 -1
- package/types/panel/server.d.ts +39 -3
- package/types/panel/settings.d.ts +23 -0
- package/types/provider.d.ts +126 -70
- package/types/providershapes.d.ts +11 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/panel/settingsroutes.js@2b101d5 — ADAPTED for fwdloop.
|
|
2
|
+
// M4d piece 4 (docs/wiki/the-module-ladder.md, "M4d", scope items 2-3): the Settings routes under
|
|
3
|
+
// `/api/settings/`, dispatched by `src/panel/server.js` AFTER the same gates as every other route
|
|
4
|
+
// (Host, cookie, and for a POST: Origin + the 8 KiB body cap). This file only decides what a settings
|
|
5
|
+
// request means.
|
|
6
|
+
//
|
|
7
|
+
// What it never does (negatives (i) (ii) (ix) (xiv)):
|
|
8
|
+
// - no route WRITES the keys file, and no response carries a key value: a key is read from the merged
|
|
9
|
+
// env only to put in an `Authorization` header, then forgotten;
|
|
10
|
+
// - Test and Balance are one GET each (`<baseUrl>/models`, DeepSeek's `/user/balance`), never a
|
|
11
|
+
// completion, and write no spend row;
|
|
12
|
+
// - no route reads or writes a flow or its cap. The only files touched are config.json (via
|
|
13
|
+
// `updateConfig`) and the keys file (read through `keysForDoor`), both under the one config home.
|
|
14
|
+
// Every refusal is a plain sentence in `say`; nothing here puts an HTTP code, an id or a path on the page.
|
|
15
|
+
import { PROVIDER_SLOTS, resolvePrices, resolveSlot, checkKeyPreflight } from '../provider.js';
|
|
16
|
+
import {
|
|
17
|
+
readConfig, updateConfig, ConfigError, PRICE_FIELDS, providerFieldProblem, cleanBaseUrl,
|
|
18
|
+
} from '../config.js';
|
|
19
|
+
import { SHAPES } from '../providershapes.js';
|
|
20
|
+
import { keysForDoor } from '../keysfile.js';
|
|
21
|
+
import { spendSummary } from '../monthly.js';
|
|
22
|
+
|
|
23
|
+
const DEEPSEEK_BALANCE_URL = 'https://api.deepseek.com/user/balance';
|
|
24
|
+
const TIMEOUT_MS = 4000;
|
|
25
|
+
|
|
26
|
+
/** Plain words for each price field (the page's three boxes). */
|
|
27
|
+
const FIELD_LABEL = Object.freeze({ inPerM: 'Input', cachedInPerM: 'Cached input', outPerM: 'Output' });
|
|
28
|
+
|
|
29
|
+
const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
|
|
30
|
+
|
|
31
|
+
const isNumberAbove0 = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }} cfg
|
|
35
|
+
* `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
|
|
36
|
+
* with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
|
|
37
|
+
* `fetch` and `now` are test seams.
|
|
38
|
+
*/
|
|
39
|
+
export function createSettings(cfg) {
|
|
40
|
+
const doFetch = cfg.fetch ?? globalThis.fetch;
|
|
41
|
+
const keys = () => keysForDoor({ env: cfg.env, keysHome: cfg.home });
|
|
42
|
+
|
|
43
|
+
/** @param {number} status @param {any} body */
|
|
44
|
+
const reply = (status, body) => ({ status, body });
|
|
45
|
+
/** @param {string} refused @param {string} say @param {number} [status] */
|
|
46
|
+
const refuse = (refused, say, status = 400) => reply(status, { ok: false, refused, say });
|
|
47
|
+
|
|
48
|
+
/** The slot named by a request, or null. @param {unknown} slot */
|
|
49
|
+
const slotOf = (slot) => (typeof slot === 'string' && Object.hasOwn(PROVIDER_SLOTS, slot) ? slot : null);
|
|
50
|
+
|
|
51
|
+
/** Balance is offered only on an OpenAI-compatible slot whose host is api.deepseek.com (bareloop's rule). @param {{ shape: string, baseUrl: string }} eff */
|
|
52
|
+
function canBalance(eff) {
|
|
53
|
+
if (eff.shape !== 'openai-api') return false;
|
|
54
|
+
try { return new URL(eff.baseUrl).host === 'api.deepseek.com'; } catch { return false; }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
|
|
58
|
+
function config() {
|
|
59
|
+
try { return { config: readConfig({ home: cfg.home }), problem: null }; } catch (e) {
|
|
60
|
+
if (!(e instanceof ConfigError)) throw e;
|
|
61
|
+
return { config: {}, problem: BROKEN_CONFIG };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function providers() {
|
|
66
|
+
const k = keys();
|
|
67
|
+
const c = config();
|
|
68
|
+
const spend = spendSummary({ home: cfg.home, now: cfg.now });
|
|
69
|
+
const rows = Object.entries(PROVIDER_SLOTS).map(([slot, def]) => {
|
|
70
|
+
const eff = resolveSlot(slot, { config: c.config });
|
|
71
|
+
const p = resolvePrices(eff.model, { slot, config: c.config });
|
|
72
|
+
const one = (value, source) => ({ value, source });
|
|
73
|
+
let keyStatus = 'not set';
|
|
74
|
+
if (!k.ok) keyStatus = 'refused';
|
|
75
|
+
else if (k.names.includes(def.envVar)) keyStatus = 'set in file';
|
|
76
|
+
else if (k.shellOnly.includes(def.envVar)) keyStatus = 'found in shell';
|
|
77
|
+
return {
|
|
78
|
+
slot,
|
|
79
|
+
label: slot,
|
|
80
|
+
envVar: def.envVar,
|
|
81
|
+
keyStatus,
|
|
82
|
+
model: eff.model,
|
|
83
|
+
shape: eff.shape,
|
|
84
|
+
baseUrl: eff.baseUrl,
|
|
85
|
+
savedBaseUrl: /** @type {Record<string, any>} */ (c.config).providers?.[slot]?.baseUrl ?? '',
|
|
86
|
+
defaults: eff.defaults,
|
|
87
|
+
tokens: spend.byProvider[slot]?.total.tokens ?? 0,
|
|
88
|
+
price: {
|
|
89
|
+
inPerM: one(p.perM.inPerM, p.source.in),
|
|
90
|
+
cachedInPerM: one(p.perM.cachedInPerM, p.source.cachedIn),
|
|
91
|
+
outPerM: one(p.perM.outPerM, p.source.out),
|
|
92
|
+
},
|
|
93
|
+
canBalance: canBalance(eff),
|
|
94
|
+
};
|
|
95
|
+
});
|
|
96
|
+
return reply(200, {
|
|
97
|
+
ok: true,
|
|
98
|
+
keysFile: { path: k.path, exists: k.exists, refusal: k.refusal },
|
|
99
|
+
configProblem: c.problem,
|
|
100
|
+
shapes: SHAPES.map(({ id, label }) => ({ id, label })),
|
|
101
|
+
rows,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The key for a slot, for a header only; or `{why}` in plain words. @param {string} slot @returns {{ key?: string, why?: string }} */
|
|
106
|
+
function keyFor(slot) {
|
|
107
|
+
const k = keys();
|
|
108
|
+
if (!k.ok) return { why: String(k.refusal) };
|
|
109
|
+
const def = PROVIDER_SLOTS[slot];
|
|
110
|
+
const value = k.env[def.envVar];
|
|
111
|
+
if (value === undefined || value === '') return { why: 'No key set for this provider.' };
|
|
112
|
+
if (!checkKeyPreflight(slot, k.env).ok) return { why: 'The key has a space or a line break in it. Fix it in your keys file, then reload keys.' };
|
|
113
|
+
return { key: value };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The key goes only in a header, in the form each shape expects. @param {string} shape @param {string} key @returns {Record<string, string>} */
|
|
117
|
+
function authHeaders(shape, key) {
|
|
118
|
+
if (shape === 'anthropic-api') return { 'x-api-key': key, 'anthropic-version': '2023-06-01' };
|
|
119
|
+
if (shape === 'gemini-api') return { 'x-goog-api-key': key };
|
|
120
|
+
return { Authorization: `Bearer ${key}` };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** One $0 GET with a 4 s deadline and the key only in the header. @param {string} url @param {string} key @returns {Promise<{ body?: any, why?: string }>} */
|
|
124
|
+
async function getWithKey(url, key, shape = 'openai-api') {
|
|
125
|
+
const ctl = new AbortController();
|
|
126
|
+
const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
|
|
127
|
+
try {
|
|
128
|
+
const res = await doFetch(url, { method: 'GET', headers: authHeaders(shape, key), signal: ctl.signal, redirect: 'manual' });
|
|
129
|
+
if (res.status >= 300 && res.status < 400) return { why: 'The provider answered with a redirect; the key was not sent on. Check the Base URL.' };
|
|
130
|
+
if (res.status === 401 || res.status === 403) return { why: 'The provider refused the key.' };
|
|
131
|
+
if (!res.ok) return { why: 'The provider answered with an error.' };
|
|
132
|
+
let body = null;
|
|
133
|
+
try { body = await res.json(); } catch { body = null; }
|
|
134
|
+
return { body };
|
|
135
|
+
} catch (/** @type {any} */ e) {
|
|
136
|
+
if (e?.name === 'AbortError') return { why: 'The provider did not answer in 4 seconds.' };
|
|
137
|
+
return { why: 'Could not reach the provider.' };
|
|
138
|
+
} finally {
|
|
139
|
+
clearTimeout(timer);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function test(body) {
|
|
144
|
+
const slot = slotOf(body?.slot);
|
|
145
|
+
if (!slot) return refuse('unknown-provider', 'That provider is not known.');
|
|
146
|
+
const k = keyFor(slot);
|
|
147
|
+
if (k.why) return reply(200, { ok: false, why: k.why });
|
|
148
|
+
const started = Date.now();
|
|
149
|
+
const c = config();
|
|
150
|
+
if (c.problem) return reply(200, { ok: false, why: c.problem });
|
|
151
|
+
const eff = resolveSlot(slot, { config: c.config });
|
|
152
|
+
const base = eff.baseUrl !== '' ? eff.baseUrl : 'https://generativelanguage.googleapis.com/v1beta'; // bare-agent's own Gemini address
|
|
153
|
+
const r = await getWithKey(`${base}/models`, String(k.key), eff.shape);
|
|
154
|
+
if (r.why) return reply(200, { ok: false, why: r.why });
|
|
155
|
+
return reply(200, { ok: true, ms: Date.now() - started });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function balance(query) {
|
|
159
|
+
const slot = slotOf(query.get('slot'));
|
|
160
|
+
if (!slot) return refuse('unknown-provider', 'That provider is not known.');
|
|
161
|
+
const c = config();
|
|
162
|
+
if (c.problem) return reply(200, { ok: false, why: c.problem });
|
|
163
|
+
if (!canBalance(resolveSlot(slot, { config: c.config }))) return reply(200, { ok: false, why: 'Not offered by this provider.' });
|
|
164
|
+
const k = keyFor(slot);
|
|
165
|
+
if (k.why) return reply(200, { ok: false, why: k.why });
|
|
166
|
+
const r = await getWithKey(DEEPSEEK_BALANCE_URL, String(k.key));
|
|
167
|
+
if (r.why) return reply(200, { ok: false, why: r.why });
|
|
168
|
+
const infos = Array.isArray(r.body?.balance_infos) ? r.body.balance_infos : [];
|
|
169
|
+
const balances = infos
|
|
170
|
+
.filter((b) => b && typeof b.currency === 'string' && b.total_balance !== undefined)
|
|
171
|
+
.map((b) => ({ currency: b.currency, total: String(b.total_balance) }));
|
|
172
|
+
if (balances.length === 0) return reply(200, { ok: false, why: 'The provider did not report a balance.' });
|
|
173
|
+
return reply(200, { ok: true, balances });
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Validate EVERY field first; write only if all pass. */
|
|
177
|
+
function price(body) {
|
|
178
|
+
const slot = slotOf(body?.slot);
|
|
179
|
+
if (!slot) return refuse('unknown-provider', 'That provider is not known.');
|
|
180
|
+
/** @type {Record<string, number|null>} */
|
|
181
|
+
const patch = {};
|
|
182
|
+
for (const f of PRICE_FIELDS) {
|
|
183
|
+
if (!Object.hasOwn(body, f)) continue;
|
|
184
|
+
const v = body[f];
|
|
185
|
+
if (v !== null && !isNumberAbove0(v)) {
|
|
186
|
+
return refuse('bad-price', `${FIELD_LABEL[f]} price must be a number above 0, or empty to use the default. Nothing was saved.`);
|
|
187
|
+
}
|
|
188
|
+
patch[f] = v;
|
|
189
|
+
}
|
|
190
|
+
if (Object.keys(patch).length === 0) return refuse('bad-price', 'Nothing to save.');
|
|
191
|
+
try {
|
|
192
|
+
updateConfig({ prices: { [slot]: patch } }, { home: cfg.home });
|
|
193
|
+
} catch (e) {
|
|
194
|
+
if (!(e instanceof ConfigError)) throw e;
|
|
195
|
+
return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
196
|
+
}
|
|
197
|
+
return reply(200, { ok: true, slot });
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Save a provider slot's name (model id), shape and Base URL. Validate EVERY field first; write only if all pass. */
|
|
201
|
+
function provider(body) {
|
|
202
|
+
const slot = slotOf(body?.slot);
|
|
203
|
+
if (!slot) return refuse('unknown-provider', 'That provider is not known.');
|
|
204
|
+
const fields = { name: 'model', shape: 'shape', baseUrl: 'baseUrl' };
|
|
205
|
+
const say = { name: 'The name must be a model id: 1 to 200 characters, no spaces.', shape: 'Pick an API shape from the list.', baseUrl: 'The Base URL must be empty (use the default) or start with http:// or https://.' };
|
|
206
|
+
/** @type {Record<string, string|null>} */
|
|
207
|
+
const patch = {};
|
|
208
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
209
|
+
if (!Object.hasOwn(body, key)) continue;
|
|
210
|
+
const v = body[key];
|
|
211
|
+
const clearUrl = key === 'baseUrl' && v === '';
|
|
212
|
+
if (!clearUrl && providerFieldProblem(field, v) !== null) return refuse('bad-provider', `${say[key]} Nothing was saved.`);
|
|
213
|
+
patch[field] = clearUrl ? null : (key === 'baseUrl' ? cleanBaseUrl(v) : v);
|
|
214
|
+
}
|
|
215
|
+
if (Object.keys(patch).length === 0) return refuse('bad-provider', 'Nothing to save.');
|
|
216
|
+
try {
|
|
217
|
+
updateConfig({ providers: { [slot]: patch } }, { home: cfg.home });
|
|
218
|
+
} catch (e) {
|
|
219
|
+
if (!(e instanceof ConfigError)) throw e;
|
|
220
|
+
return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
221
|
+
}
|
|
222
|
+
return reply(200, { ok: true, slot });
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function moneyGet() {
|
|
226
|
+
const c = config();
|
|
227
|
+
const summary = spendSummary({ home: cfg.home, now: cfg.now });
|
|
228
|
+
const limit = c.problem === null && isNumberAbove0(c.config.monthlyLimitUsd) ? c.config.monthlyLimitUsd : null;
|
|
229
|
+
return reply(200, { ok: true, ...summary, monthlyLimitUsd: limit, configProblem: c.problem });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function moneyPost(body) {
|
|
233
|
+
if (body === null || typeof body !== 'object' || !Object.hasOwn(body, 'monthlyLimitUsd')) {
|
|
234
|
+
return refuse('bad-limit', 'Send a number above 0, or leave it empty for no limit. Nothing was saved.');
|
|
235
|
+
}
|
|
236
|
+
const raw = body.monthlyLimitUsd;
|
|
237
|
+
const clear = raw === null || raw === '';
|
|
238
|
+
if (!clear && !isNumberAbove0(raw)) return refuse('bad-limit', 'The monthly limit must be a number above 0, or empty for no limit. Nothing was saved.');
|
|
239
|
+
try {
|
|
240
|
+
updateConfig({ monthlyLimitUsd: clear ? null : raw }, { home: cfg.home });
|
|
241
|
+
} catch (e) {
|
|
242
|
+
if (!(e instanceof ConfigError)) throw e;
|
|
243
|
+
return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
244
|
+
}
|
|
245
|
+
return reply(200, { ok: true, monthlyLimitUsd: clear ? null : raw });
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* @param {{ method: string, pathname: string, query: URLSearchParams, body: any }} r
|
|
250
|
+
* @returns {Promise<{ status: number, body: any }>}
|
|
251
|
+
*/
|
|
252
|
+
async function handle({ method, pathname, query, body }) {
|
|
253
|
+
if (cfg.skip) return refuse('settings-unavailable', 'Settings is not available here.', 404);
|
|
254
|
+
const known = { GET: ['/api/settings/providers', '/api/settings/balance', '/api/settings/money'], POST: ['/api/settings/test', '/api/settings/price', '/api/settings/provider', '/api/settings/money'] };
|
|
255
|
+
if (!(known[method] ?? []).includes(pathname)) return refuse('no-such-settings-route', 'Settings cannot do that. Keys are typed into your keys file by hand.', 404);
|
|
256
|
+
if (method === 'GET') {
|
|
257
|
+
if (pathname === '/api/settings/providers') return providers();
|
|
258
|
+
if (pathname === '/api/settings/balance') return balance(query);
|
|
259
|
+
return moneyGet();
|
|
260
|
+
}
|
|
261
|
+
if (pathname === '/api/settings/test') return test(body);
|
|
262
|
+
if (pathname === '/api/settings/price') return price(body);
|
|
263
|
+
if (pathname === '/api/settings/provider') return provider(body);
|
|
264
|
+
return moneyPost(body);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return { handle };
|
|
268
|
+
}
|
package/src/provider.js
CHANGED
|
@@ -21,7 +21,9 @@ import {
|
|
|
21
21
|
} from 'node:fs';
|
|
22
22
|
import { dirname, basename } from 'node:path';
|
|
23
23
|
import { readFileInside } from './flow.js';
|
|
24
|
-
import {
|
|
24
|
+
import { readConfig, configDoorHome } from './config.js';
|
|
25
|
+
import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
|
|
26
|
+
import { SHAPES } from './providershapes.js';
|
|
25
27
|
|
|
26
28
|
/**
|
|
27
29
|
* F28 (2026-09-15) / BA-27 (bare-agent >=0.47.0): DeepSeek sometimes emits a
|
|
@@ -57,6 +59,7 @@ export const PROVIDER_SLOTS = Object.freeze({
|
|
|
57
59
|
baseUrl: 'https://api.synthetic.new/openai/v1',
|
|
58
60
|
envVar: 'SYNTHETIC_API_KEY',
|
|
59
61
|
defaultModel: 'hf:Qwen/Qwen3.8-27B',
|
|
62
|
+
shape: 'openai-api',
|
|
60
63
|
legacyMaxTokens: false,
|
|
61
64
|
}),
|
|
62
65
|
deepseek: Object.freeze({
|
|
@@ -65,17 +68,55 @@ export const PROVIDER_SLOTS = Object.freeze({
|
|
|
65
68
|
// F22: 'deepseek-v4-flash' is retired, routed to DeepSeek-V4.1-Flash —
|
|
66
69
|
// request the live name so request === served.
|
|
67
70
|
defaultModel: 'deepseek-flash',
|
|
71
|
+
shape: 'openai-api',
|
|
68
72
|
// F11: DeepSeek ignores `max_completion_tokens`; only the legacy
|
|
69
73
|
// `max_tokens` key bounds output.
|
|
70
74
|
legacyMaxTokens: true,
|
|
71
75
|
}),
|
|
72
76
|
});
|
|
73
77
|
|
|
78
|
+
/**
|
|
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.
|
|
85
|
+
* @param {string} slotName
|
|
86
|
+
* @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 } }}
|
|
90
|
+
*/
|
|
91
|
+
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];
|
|
96
|
+
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(/\/+$/, '') : '';
|
|
100
|
+
return {
|
|
101
|
+
slot: slotName,
|
|
102
|
+
envVar: def.envVar,
|
|
103
|
+
legacyMaxTokens: def.legacyMaxTokens === true && shape === 'openai-api',
|
|
104
|
+
model: saved.model ?? def.defaultModel,
|
|
105
|
+
shape,
|
|
106
|
+
baseUrl: savedUrl !== '' ? savedUrl : defaultBaseUrl,
|
|
107
|
+
defaults: { model: def.defaultModel, shape: def.shape, baseUrl: defaultBaseUrl },
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
74
111
|
/**
|
|
75
112
|
* List-rate ceilings (USD/1K tokens), hand-entered — see
|
|
76
|
-
* poc/m0/spend.mjs@76a3607 for sourcing notes per row.
|
|
77
|
-
*
|
|
78
|
-
*
|
|
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). `cacheIn` (optional) is the cache-READ price per 1K; a row
|
|
119
|
+
* without it books cache reads at bare-agent's default 0.1x of `in`.
|
|
79
120
|
*/
|
|
80
121
|
export const RATES_BY_SUFFIX = {
|
|
81
122
|
'zai-org/GLM-5.2': { in: 0.0006, out: 0.0022, source: 'published' },
|
|
@@ -88,7 +129,10 @@ export const RATES_BY_SUFFIX = {
|
|
|
88
129
|
'syn:large:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
|
|
89
130
|
'syn:small:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
|
|
90
131
|
'deepseek-v4-flash': { in: 0.00044, out: 0.00132, source: 'published' }, // F22: retired name, historical rows only
|
|
91
|
-
|
|
132
|
+
// DeepSeek-V4.1-Flash, peak. Source: https://api-docs.deepseek.com/quick_start/pricing/ (fetched
|
|
133
|
+
// 2026-10-05: cache hit $0.006, cache miss $0.30, output $1.20 per 1M). `cacheIn` = the hit price
|
|
134
|
+
// (hamr ruling "A", 2026-10-05, poc/m4d/RESULTS.md (b): bare-agent's 0.1x default booked hits 5x real).
|
|
135
|
+
'deepseek-flash': { in: 0.0003, cacheIn: 0.000006, out: 0.0012, source: 'published' },
|
|
92
136
|
'deepseek-v4-pro': { in: 0.00132, out: 0.00396, source: 'published' },
|
|
93
137
|
};
|
|
94
138
|
|
|
@@ -96,6 +140,8 @@ export const RATES_BY_SUFFIX = {
|
|
|
96
140
|
* Strip an `hf:` routing prefix and look up `suffix` with `Object.hasOwn` —
|
|
97
141
|
* never plain truthiness/`in`, which would let a suffix like `"constructor"`
|
|
98
142
|
* resolve to an inherited `Object.prototype` member.
|
|
143
|
+
* @param {string|null|undefined} modelId
|
|
144
|
+
* @param {Record<string, any>} [ratesTable]
|
|
99
145
|
*/
|
|
100
146
|
export function lookupRate(modelId, ratesTable = RATES_BY_SUFFIX) {
|
|
101
147
|
if (!modelId) return null;
|
|
@@ -120,17 +166,89 @@ export function resolveModelRate(modelId, ratesTable = RATES_BY_SUFFIX) {
|
|
|
120
166
|
export const CEILING_INPUT_TOKENS = 32000;
|
|
121
167
|
export const CEILING_OUTPUT_TOKENS = 16000;
|
|
122
168
|
|
|
169
|
+
const perM = (per1K) => Number((per1K * 1000).toPrecision(12));
|
|
170
|
+
|
|
123
171
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
* the HIGHEST
|
|
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). A cache-read price is known only from Settings or a
|
|
176
|
+
* row's `cacheIn`; otherwise it is left out (`cacheReadMult` omitted -> bare-agent's 0.1x of `in`).
|
|
177
|
+
*
|
|
178
|
+
* @param {string} modelId
|
|
179
|
+
* @param {{ slot?: string, config?: Record<string, any>, ratesTable?: Record<string, any> }} [opts]
|
|
180
|
+
* @returns {{
|
|
181
|
+
* rates: { in: number, out: number, cacheReadMult?: number },
|
|
182
|
+
* perM: { inPerM: number, cachedInPerM: number, outPerM: number },
|
|
183
|
+
* source: { in: 'settings'|'table'|'ceiling', cachedIn: 'settings'|'table'|'default-multiplier', out: 'settings'|'table'|'ceiling' },
|
|
184
|
+
* suffix: string|null,
|
|
185
|
+
* }}
|
|
127
186
|
*/
|
|
128
|
-
export function
|
|
187
|
+
export function resolvePrices(modelId, { slot, config = {}, ratesTable = RATES_BY_SUFFIX } = {}) {
|
|
129
188
|
const resolved = lookupRate(modelId, ratesTable);
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
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
|
+
let cachedIn = null;
|
|
200
|
+
let cachedSrc = 'default-multiplier';
|
|
201
|
+
if (set.cachedInPerM !== undefined) { cachedIn = set.cachedInPerM / 1000; cachedSrc = 'settings'; }
|
|
202
|
+
else if (row && row.cacheIn !== undefined) { cachedIn = row.cacheIn; cachedSrc = 'table'; }
|
|
203
|
+
/** @type {{ in: number, out: number, cacheReadMult?: number }} */
|
|
204
|
+
const rates = { in: inF.v, out: outF.v };
|
|
205
|
+
if (cachedIn !== null) rates.cacheReadMult = cachedIn / inF.v;
|
|
206
|
+
return {
|
|
207
|
+
rates,
|
|
208
|
+
perM: { inPerM: perM(inF.v), cachedInPerM: perM(cachedIn ?? inF.v * 0.1), outPerM: perM(outF.v) },
|
|
209
|
+
source: { in: /** @type {any} */ (inF.src), cachedIn: /** @type {any} */ (cachedSrc), out: /** @type {any} */ (outF.src) },
|
|
210
|
+
suffix: resolved ? resolved.suffix : null,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The `price` object a spend row records: the per-1M numbers the call was booked at and where each
|
|
216
|
+
* came from. From a `resolvePrices` result; or from INJECTED rates (tests) with source "injected".
|
|
217
|
+
* @param {{ perM: any, source: any }|null|undefined} prices
|
|
218
|
+
* @param {{ in: number, out: number, cacheReadMult?: number }|null|undefined} [injectedRates]
|
|
219
|
+
*/
|
|
220
|
+
export function priceRecord(prices, injectedRates) {
|
|
221
|
+
if (prices) return { ...prices.perM, source: prices.source };
|
|
222
|
+
if (!injectedRates) return null;
|
|
223
|
+
return {
|
|
224
|
+
inPerM: perM(injectedRates.in),
|
|
225
|
+
cachedInPerM: perM(injectedRates.in * (injectedRates.cacheReadMult ?? 0.1)),
|
|
226
|
+
outPerM: perM(injectedRates.out),
|
|
227
|
+
source: 'injected',
|
|
133
228
|
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The config a model call is priced against, read at the door: `{}` when no config applies
|
|
233
|
+
* (a test process with no `FWDLOOP_CONFIG_HOME`), else the validated `config.json`. A broken
|
|
234
|
+
* config THROWS (ConfigError) — a run's charge never changes silently.
|
|
235
|
+
* @param {string} [home] explicit config home (a test); default: the door's home
|
|
236
|
+
*/
|
|
237
|
+
export function readPriceConfig(home) {
|
|
238
|
+
if (home !== undefined) return readConfig({ home });
|
|
239
|
+
const door = configDoorHome();
|
|
240
|
+
return door.skip ? {} : readConfig({ home: door.home });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* The ceiling cost (USD) of one round of `modelId` — never 0, never null.
|
|
245
|
+
* A known model prices at its own rate; an unknown/missing model prices at
|
|
246
|
+
* the HIGHEST in/out rate anywhere in `ratesTable`. `opts.prices` (a
|
|
247
|
+
* `resolvePrices` result, e.g. from `makeProvider`) makes the cap check use the
|
|
248
|
+
* SAME price the round is booked at.
|
|
249
|
+
*/
|
|
250
|
+
export function ceilingCostUsd(modelId, ratesTable = RATES_BY_SUFFIX, opts = {}) {
|
|
251
|
+
const { rates } = opts.prices ?? resolvePrices(modelId, { ratesTable });
|
|
134
252
|
return (CEILING_INPUT_TOKENS / 1000) * rates.in + (CEILING_OUTPUT_TOKENS / 1000) * rates.out;
|
|
135
253
|
}
|
|
136
254
|
|
|
@@ -195,7 +313,9 @@ export function appendSpendRow(path, row) {
|
|
|
195
313
|
+ '— the signed hash records the request, not what ran',
|
|
196
314
|
);
|
|
197
315
|
}
|
|
198
|
-
|
|
316
|
+
// M4d piece 3: the writer stamps `at` (after the spread: a caller can never set it) so month spend can be read
|
|
317
|
+
// off each run's own books. Rows written before M4d carry none.
|
|
318
|
+
appendFileSync(path, `${JSON.stringify({ ...row, at: new Date().toISOString(), modelMatch })}\n`);
|
|
199
319
|
}
|
|
200
320
|
|
|
201
321
|
// F48 round 3: both readers below take a full path (`<runDir>/spend.jsonl`,
|
|
@@ -205,15 +325,38 @@ export function appendSpendRow(path, row) {
|
|
|
205
325
|
// a symlinked `spend.jsonl` (or a symlinked run-dir ancestor) reads as
|
|
206
326
|
// "missing", never as some outside file's content folded into a cap check
|
|
207
327
|
// or shown on the panel.
|
|
328
|
+
// A row with no booked cost is repriced at ITS OWN booked price's ceiling when it recorded one
|
|
329
|
+
// (M4d: forward only — today's Settings price never re-prices an old row), else at the code table's.
|
|
330
|
+
function rowCeilingUsd(row) {
|
|
331
|
+
const p = row.price;
|
|
332
|
+
if (p && typeof p === 'object' && Number.isFinite(p.inPerM) && p.inPerM > 0 && Number.isFinite(p.outPerM) && p.outPerM > 0) {
|
|
333
|
+
return (CEILING_INPUT_TOKENS / 1e6) * p.inPerM + (CEILING_OUTPUT_TOKENS / 1e6) * p.outPerM;
|
|
334
|
+
}
|
|
335
|
+
return ceilingCostUsd(row.model);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* The one rule for what a spend row costs: `usd` and whether it is `complete`. An incomplete row (a call
|
|
340
|
+
* died unmetered, or a round was left unpriced) counts its priced floor PLUS one ceiling per unmetered call
|
|
341
|
+
* (unknown cost is never 0). Same shape as poc/m6a/batch.mjs rowCostUsd.
|
|
342
|
+
* @param {any} row
|
|
343
|
+
* @returns {{usd: number, complete: boolean}}
|
|
344
|
+
*/
|
|
345
|
+
export function spendRowCost(row) {
|
|
346
|
+
if (row.spendComplete === false) {
|
|
347
|
+
const unmetered = Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
|
|
348
|
+
return { usd: (row.costUsd ?? 0) + unmetered * rowCeilingUsd(row), complete: false };
|
|
349
|
+
}
|
|
350
|
+
if (row.costUsd === null || row.costUsd === undefined) return { usd: rowCeilingUsd(row), complete: false };
|
|
351
|
+
return { usd: row.costUsd, complete: true };
|
|
352
|
+
}
|
|
353
|
+
|
|
208
354
|
function readSpendTotal(path) {
|
|
209
355
|
const result = readFileInside(dirname(path), basename(path));
|
|
210
356
|
if (!result.ok) return 0;
|
|
211
357
|
const lines = result.text.split('\n').filter((l) => l.trim());
|
|
212
358
|
let total = 0;
|
|
213
|
-
for (const line of lines)
|
|
214
|
-
const row = JSON.parse(line);
|
|
215
|
-
total += row.costUsd === null || row.costUsd === undefined ? ceilingCostUsd(row.model) : row.costUsd;
|
|
216
|
-
}
|
|
359
|
+
for (const line of lines) total += spendRowCost(JSON.parse(line)).usd;
|
|
217
360
|
return total;
|
|
218
361
|
}
|
|
219
362
|
|
|
@@ -259,7 +402,7 @@ export function assertUnderGlobalCap(path, capUsd) {
|
|
|
259
402
|
* @param {Record<string,string|undefined>} [env]
|
|
260
403
|
*/
|
|
261
404
|
export function checkKeyPreflight(slotName, env = process.env) {
|
|
262
|
-
const slotDef = PROVIDER_SLOTS[slotName];
|
|
405
|
+
const slotDef = Object.hasOwn(PROVIDER_SLOTS, slotName) ? PROVIDER_SLOTS[slotName] : null;
|
|
263
406
|
if (!slotDef) return { ok: false, message: `key: unknown provider slot "${slotName}"` };
|
|
264
407
|
const varName = slotDef.envVar;
|
|
265
408
|
const value = env[varName];
|
|
@@ -287,38 +430,54 @@ export function checkKeyPreflight(slotName, env = process.env) {
|
|
|
287
430
|
* values this project uses.
|
|
288
431
|
*
|
|
289
432
|
* @param {string} slotName
|
|
290
|
-
* @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null }} [options]
|
|
433
|
+
* @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null, env?: Record<string,string|undefined>, configHome?: string }} [options]
|
|
434
|
+
* `configHome` (a test) is where `config.json` prices are read; default: the door's home (`readPriceConfig`).
|
|
435
|
+
* `env` (M4d: the merged shell+keys-file env; default process.env) is where the key is read.
|
|
291
436
|
* `thinking` (bare-agent >=0.49) is sent verbatim as body.thinking; unset/null leaves the body unchanged.
|
|
292
|
-
* @returns {{ provider: any, rates: {in:number, out:number}, modelId: string, suffix: string, slot: string }}
|
|
437
|
+
* @returns {{ provider: any, rates: {in:number, out:number, cacheReadMult?:number}, modelId: string, suffix: string|null, slot: string, prices: ReturnType<typeof resolvePrices> }}
|
|
293
438
|
*/
|
|
294
439
|
export function makeProvider(slotName, options = {}) {
|
|
295
|
-
const {
|
|
296
|
-
|
|
297
|
-
|
|
440
|
+
const {
|
|
441
|
+
model, timeoutMs, deadlineMs, thinking, env = process.env, configHome,
|
|
442
|
+
} = options;
|
|
443
|
+
if (!Object.hasOwn(PROVIDER_SLOTS, slotName)) {
|
|
298
444
|
throw new Error(`unknown provider slot "${slotName}" — known slots: ${Object.keys(PROVIDER_SLOTS).join(', ')}`);
|
|
299
445
|
}
|
|
300
446
|
|
|
301
|
-
const keyCheck = checkKeyPreflight(slotName);
|
|
447
|
+
const keyCheck = checkKeyPreflight(slotName, env);
|
|
302
448
|
if (!keyCheck.ok) throw new Error(keyCheck.message);
|
|
303
449
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
const
|
|
450
|
+
// A broken config throws by name here; it never falls back to the code defaults or the table, so a
|
|
451
|
+
// run's model, address or charge cannot change silently.
|
|
452
|
+
const config = readPriceConfig(configHome);
|
|
453
|
+
const slot = resolveSlot(slotName, { config });
|
|
454
|
+
const apiKey = env[slot.envVar];
|
|
455
|
+
const modelId = model ?? slot.model;
|
|
456
|
+
// The ONE price lookup (a Settings price wins over the table; a model the table doesn't know prices
|
|
457
|
+
// at the table's highest rate, suffix null — unknown cost is never 0).
|
|
458
|
+
const prices = resolvePrices(modelId, { slot: slotName, config });
|
|
459
|
+
const { rates } = prices;
|
|
460
|
+
const suffix = prices.suffix;
|
|
307
461
|
|
|
308
|
-
const
|
|
462
|
+
const common = {
|
|
309
463
|
apiKey,
|
|
310
464
|
model: modelId,
|
|
311
|
-
baseUrl: slot.baseUrl,
|
|
312
|
-
legacyMaxTokens: slot.legacyMaxTokens === true,
|
|
313
|
-
// bare-agent >=0.48: opt in to the raw broken tool-call arguments on
|
|
314
|
-
// `malformedToolCall` (capped upstream at 500 chars). Not exposeErrorBody.
|
|
315
|
-
exposeMalformedArgs: true,
|
|
465
|
+
...(slot.baseUrl !== '' ? { baseUrl: slot.baseUrl } : {}),
|
|
316
466
|
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
317
467
|
...(deadlineMs !== undefined ? { deadlineMs } : {}),
|
|
318
468
|
...(thinking != null ? { thinking } : {}),
|
|
319
|
-
}
|
|
469
|
+
};
|
|
470
|
+
const provider = slot.shape === 'anthropic-api' ? new Anthropic(common)
|
|
471
|
+
: slot.shape === 'gemini-api' ? new Gemini(common)
|
|
472
|
+
: new MalformedToolCallTolerantOpenAI({
|
|
473
|
+
...common,
|
|
474
|
+
legacyMaxTokens: slot.legacyMaxTokens,
|
|
475
|
+
// bare-agent >=0.48: opt in to the raw broken tool-call arguments on
|
|
476
|
+
// `malformedToolCall` (capped upstream at 500 chars). Not exposeErrorBody.
|
|
477
|
+
exposeMalformedArgs: true,
|
|
478
|
+
});
|
|
320
479
|
|
|
321
480
|
return {
|
|
322
|
-
provider, rates, modelId, suffix, slot: slotName,
|
|
481
|
+
provider, rates, modelId, suffix, slot: slotName, prices,
|
|
323
482
|
};
|
|
324
483
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
|
3
|
+
// Providers dropdown offers. Only a shape `makeProvider` (src/provider.js) can really build is listed:
|
|
4
|
+
// bare-agent/providers exports OpenAI, Anthropic and Gemini with the same constructor options we pass
|
|
5
|
+
// (`apiKey`, `model`, `baseUrl`, `timeoutMs`, `deadlineMs`). Kept in its own file so config.js can
|
|
6
|
+
// validate a shape without importing provider.js (which imports config.js).
|
|
7
|
+
|
|
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}[]}
|
|
12
|
+
*/
|
|
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: '' }),
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
export const SHAPE_IDS = Object.freeze(SHAPES.map((s) => s.id));
|