fwdloop 0.11.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 +115 -9
- package/package.json +1 -1
- package/src/authoring.js +3 -1
- package/src/config.js +255 -0
- package/src/drafter.js +12 -8
- package/src/keysfile.js +180 -0
- package/src/model-step.js +13 -4
- package/src/monthly.js +231 -0
- package/src/panel/index.html +331 -0
- package/src/panel/resume.js +9 -4
- package/src/panel/server.js +38 -5
- package/src/panel/settings.js +268 -0
- package/src/provider.js +194 -43
- package/src/providershapes.js +19 -0
- package/types/config.d.ts +51 -0
- package/types/drafter.d.ts +4 -2
- package/types/keysfile.d.ts +90 -0
- package/types/model-step.d.ts +3 -1
- package/types/monthly.d.ts +109 -0
- package/types/panel/resume.d.ts +8 -1
- package/types/panel/server.d.ts +10 -2
- package/types/panel/settings.d.ts +23 -0
- package/types/provider.d.ts +126 -70
- package/types/providershapes.d.ts +11 -0
package/src/keysfile.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/keysfile.js@a42ca5f
|
|
2
|
+
// M4d scope item 1 — the keys file loader (`~/.config/fwdloop/.env`).
|
|
3
|
+
//
|
|
4
|
+
// Key VALUES live only in this file (mode 0600, outside any repo) and in the shell
|
|
5
|
+
// environment — never in config.json, the spine, runs.jsonl, a log, a page or an audit
|
|
6
|
+
// row. This is the ONE reader of that file. Plain `NAME=value` lines (an optional
|
|
7
|
+
// `export ` prefix, `#` full-line comments, one pair of matching quotes around the
|
|
8
|
+
// value); no dependency.
|
|
9
|
+
//
|
|
10
|
+
// Precedence: the SHELL wins. An exported `FOO=…` beats the file; the file only fills
|
|
11
|
+
// names the shell leaves unset (or empty). The merged env is a NEW object —
|
|
12
|
+
// `process.env` is never mutated.
|
|
13
|
+
//
|
|
14
|
+
// Adjusted from bareloop (ruling 1A, hamr 2026-10-05): a file with any group/other bit is
|
|
15
|
+
// REFUSED, not warned about. A refusal carries no env at all: nothing that needs a key runs.
|
|
16
|
+
//
|
|
17
|
+
// Values leave this module in exactly one place: the `env` of an ok `loadKeysEnv`.
|
|
18
|
+
// Everything else it returns (`names`, `path`, `exists`, `refusal`) is value-free by
|
|
19
|
+
// construction, and a parse problem never quotes the offending line.
|
|
20
|
+
import {
|
|
21
|
+
openSync, fstatSync, readFileSync, closeSync, writeFileSync, mkdirSync,
|
|
22
|
+
} from 'node:fs';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { PROVIDER_SLOTS } from './provider.js';
|
|
25
|
+
import { configHome, configDoorHome } from './config.js';
|
|
26
|
+
|
|
27
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
28
|
+
|
|
29
|
+
/** The key names fwdloop knows (one per provider slot). */
|
|
30
|
+
export const KEY_NAMES = Object.freeze(Object.values(PROVIDER_SLOTS).map((p) => p.envVar));
|
|
31
|
+
|
|
32
|
+
const DEFAULT_SHOWN = '~/.config/fwdloop/.env';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `~/.config/fwdloop`, or an injected override. The CLI/panel door honors the test-only
|
|
36
|
+
* `FWDLOOP_CONFIG_HOME` through `keysForDoor` (two gates, like the other test seams).
|
|
37
|
+
* @param {string} [home] test seam; production never passes it
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export function keysHome(home) {
|
|
41
|
+
return configHome(home); // one definition of the config home (src/config.js)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} [home]
|
|
46
|
+
* @returns {string} `<home>/.env`
|
|
47
|
+
*/
|
|
48
|
+
export function keysFilePath(home) {
|
|
49
|
+
return join(keysHome(home), '.env');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The path as a sentence shows it: `~/...` for the default home, the real path for an injected one. */
|
|
53
|
+
const shownPath = (home) => (home === undefined ? DEFAULT_SHOWN : keysFilePath(home));
|
|
54
|
+
|
|
55
|
+
/** The one wording of the 1A refusal (ruling 1A, hamr 2026-10-05). @param {string} [home] */
|
|
56
|
+
export function chmodSentence(home) {
|
|
57
|
+
return `Your keys file can be read by other users. Run: chmod 600 ${shownPath(home)}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parse the file's text. Lines that are not `NAME=value` are skipped silently
|
|
62
|
+
* (never echoed — a malformed line may hold a secret).
|
|
63
|
+
* @param {string} text
|
|
64
|
+
* @returns {Record<string,string>}
|
|
65
|
+
*/
|
|
66
|
+
export function parseKeysText(text) {
|
|
67
|
+
/** @type {Record<string,string>} */
|
|
68
|
+
const out = {};
|
|
69
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
70
|
+
const line = raw.trim();
|
|
71
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
72
|
+
const body = line.startsWith('export ') ? line.slice(7).trimStart() : line;
|
|
73
|
+
const eq = body.indexOf('=');
|
|
74
|
+
if (eq <= 0) continue;
|
|
75
|
+
const name = body.slice(0, eq).trim();
|
|
76
|
+
if (!NAME_RE.test(name)) continue;
|
|
77
|
+
let value = body.slice(eq + 1).trim();
|
|
78
|
+
if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) {
|
|
79
|
+
value = value.slice(1, -1);
|
|
80
|
+
}
|
|
81
|
+
out[name] = value;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Create the file when — and only when — it does not exist: mode 0600 (`wx`), dir 0700,
|
|
88
|
+
* the known key names as commented lines and nothing else.
|
|
89
|
+
* @param {string} [home]
|
|
90
|
+
* @returns {boolean} true if it was created
|
|
91
|
+
*/
|
|
92
|
+
function createKeysFile(home) {
|
|
93
|
+
mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
|
|
94
|
+
const body = '# fwdloop keys — type NAME=value by hand; this file is never shown or written by fwdloop.\n'
|
|
95
|
+
+ `${KEY_NAMES.map((n) => `# ${n}=`).join('\n')}\n`;
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(keysFilePath(home), body, { mode: 0o600, flag: 'wx' });
|
|
98
|
+
} catch (/** @type {any} */ e) {
|
|
99
|
+
if (e?.code === 'EEXIST') return false; // lost a race: the file is there, untouched
|
|
100
|
+
throw e;
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* @typedef {object} KeysLoad
|
|
107
|
+
* @property {boolean} ok false = refused: nothing that needs a key may run
|
|
108
|
+
* @property {string} path the keys file's path as shown to people
|
|
109
|
+
* @property {boolean} exists the file is there (true after a create)
|
|
110
|
+
* @property {string[]} names the NAMES the file defines with a value (sorted; never values)
|
|
111
|
+
* @property {string[]} shellOnly the known key names that only the shell sets (file empty/absent)
|
|
112
|
+
* @property {string|null} refusal a plain sentence when `ok` is false, else null
|
|
113
|
+
* @property {Record<string,string|undefined>} env shell env with the file filling the names the
|
|
114
|
+
* shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
|
|
115
|
+
* place file values leave this module.
|
|
116
|
+
*/
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Load the keys file over an env. A missing file is created (0600) and is not a refusal.
|
|
120
|
+
* @param {{ env?: Record<string,string|undefined>, home?: string }} [opts]
|
|
121
|
+
* @returns {KeysLoad}
|
|
122
|
+
*/
|
|
123
|
+
export function loadKeysEnv(opts = {}) {
|
|
124
|
+
const base = opts.env ?? process.env;
|
|
125
|
+
const file = keysFilePath(opts.home);
|
|
126
|
+
const path = shownPath(opts.home);
|
|
127
|
+
const knownShell = (parsed) => KEY_NAMES.filter((n) => base[n] && !parsed[n]);
|
|
128
|
+
/** @param {string} refusal @param {boolean} exists @returns {KeysLoad} */
|
|
129
|
+
const refused = (refusal, exists) => ({
|
|
130
|
+
ok: false, path, exists, names: [], shellOnly: [], refusal, env: { ...base },
|
|
131
|
+
});
|
|
132
|
+
let fd;
|
|
133
|
+
let created = false;
|
|
134
|
+
try {
|
|
135
|
+
try {
|
|
136
|
+
fd = openSync(file, 'r');
|
|
137
|
+
} catch (/** @type {any} */ e) {
|
|
138
|
+
if (e?.code !== 'ENOENT') throw e;
|
|
139
|
+
created = createKeysFile(opts.home);
|
|
140
|
+
fd = openSync(file, 'r');
|
|
141
|
+
}
|
|
142
|
+
const st = fstatSync(fd);
|
|
143
|
+
if (!st.isFile()) return refused(`Your keys file ${path} is not a regular file.`, true);
|
|
144
|
+
if ((st.mode & 0o077) !== 0) return refused(chmodSentence(opts.home), true);
|
|
145
|
+
const parsed = parseKeysText(readFileSync(fd, 'utf8'));
|
|
146
|
+
/** @type {Record<string,string|undefined>} */
|
|
147
|
+
const env = { ...base };
|
|
148
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
149
|
+
if (!env[name]) env[name] = value;
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
|
|
153
|
+
};
|
|
154
|
+
} catch (/** @type {any} */ e) {
|
|
155
|
+
return refused(`Your keys file ${path} could not be read (${e?.code ?? 'error'}).`, created || e?.code !== 'ENOENT');
|
|
156
|
+
} finally {
|
|
157
|
+
if (fd !== undefined) closeSync(fd);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The door helper the CLI and the panel call. Loads the file only when the caller is on the
|
|
163
|
+
* REAL environment, or names a home explicitly (a test), or a test process (`configDoorHome`) with
|
|
164
|
+
* `FWDLOOP_CONFIG_HOME` set — so a test that injects `env` alone, or runs under NODE_ENV=test
|
|
165
|
+
* without a home, never reads (or creates) the real `~/.config/fwdloop/.env`.
|
|
166
|
+
* @param {{ env?: Record<string,string|undefined>, keysHome?: string }} [deps]
|
|
167
|
+
* @returns {KeysLoad & { skipped: boolean }}
|
|
168
|
+
*/
|
|
169
|
+
export function keysForDoor(deps = {}) {
|
|
170
|
+
const shell = process.env;
|
|
171
|
+
const door = configDoorHome(); // the one "under test" rule (NODE_ENV=test or node --test) and its home
|
|
172
|
+
const home = deps.keysHome ?? door.home;
|
|
173
|
+
const testNoHome = door.skip && home === undefined;
|
|
174
|
+
if ((deps.env !== undefined && home === undefined) || testNoHome) {
|
|
175
|
+
return {
|
|
176
|
+
ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], refusal: null, env: { ...(deps.env ?? shell) },
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
return { ...loadKeysEnv({ env: deps.env, home }), skipped: false };
|
|
180
|
+
}
|
package/src/model-step.js
CHANGED
|
@@ -26,9 +26,10 @@
|
|
|
26
26
|
|
|
27
27
|
import { Loop } from 'bare-agent';
|
|
28
28
|
import { GateRefusal } from './primitives.js';
|
|
29
|
+
import { ConfigError } from './config.js';
|
|
29
30
|
|
|
30
31
|
import {
|
|
31
|
-
makeProvider, sumMeterings, appendSpendRow, classifyModelId,
|
|
32
|
+
makeProvider, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
|
|
32
33
|
} from './provider.js';
|
|
33
34
|
|
|
34
35
|
// F27: DeepSeek's `chat/completions` can send HTTP 200 + headers + one byte
|
|
@@ -230,10 +231,11 @@ function toolFields(cumulative) {
|
|
|
230
231
|
* @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
|
|
231
232
|
* @param {{in:number,out:number}} [opts.rates]
|
|
232
233
|
* @param {string} [opts.modelId]
|
|
234
|
+
* @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
|
|
233
235
|
* @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}) => Promise<any>}
|
|
234
236
|
*/
|
|
235
237
|
export function makeLiveModelStep({
|
|
236
|
-
slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId,
|
|
238
|
+
slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
|
|
237
239
|
}) {
|
|
238
240
|
const live = injectedProvider == null;
|
|
239
241
|
|
|
@@ -241,6 +243,7 @@ export function makeLiveModelStep({
|
|
|
241
243
|
let provider = injectedProvider;
|
|
242
244
|
let rates = injectedRates;
|
|
243
245
|
let modelId = injectedModelId;
|
|
246
|
+
let prices = null;
|
|
244
247
|
if (live) {
|
|
245
248
|
// makeProvider throws synchronously on a missing/bad key, an unknown
|
|
246
249
|
// slot, or an unrated model — never let that escape as an unhandled
|
|
@@ -248,7 +251,9 @@ export function makeLiveModelStep({
|
|
|
248
251
|
// always a red, never a crash (rule 5).
|
|
249
252
|
try {
|
|
250
253
|
if (!slot) throw new Error('makeLiveModelStep: "slot" is required when no provider is injected');
|
|
251
|
-
({
|
|
254
|
+
({
|
|
255
|
+
provider, rates, modelId, prices,
|
|
256
|
+
} = makeProvider(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
|
|
252
257
|
} catch (err) {
|
|
253
258
|
// No provider was ever built, so no round could possibly have run —
|
|
254
259
|
// `model: null`, `tokens: null` and `tools: null` (M4a-3) here are the one honest
|
|
@@ -256,7 +261,7 @@ export function makeLiveModelStep({
|
|
|
256
261
|
// a call that never happened). A row that names a model must carry its
|
|
257
262
|
// tokens (appendAudit refuses it otherwise), so the model is not named.
|
|
258
263
|
return {
|
|
259
|
-
ok: false, red:
|
|
264
|
+
ok: false, red: `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
|
|
260
265
|
};
|
|
261
266
|
}
|
|
262
267
|
}
|
|
@@ -330,6 +335,8 @@ export function makeLiveModelStep({
|
|
|
330
335
|
const partial = sumMeterings(roundMeterings);
|
|
331
336
|
cumulative = addMeter(cumulative, partial);
|
|
332
337
|
appendSpendRow(spendPath, {
|
|
338
|
+
provider: slot ?? null,
|
|
339
|
+
price: priceRecord(prices, rates),
|
|
333
340
|
model: modelId,
|
|
334
341
|
modelReturned: partial.model,
|
|
335
342
|
tokens: partial.tokens,
|
|
@@ -386,6 +393,8 @@ export function makeLiveModelStep({
|
|
|
386
393
|
cumulative = addMeter(cumulative, metered);
|
|
387
394
|
cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
|
|
388
395
|
appendSpendRow(spendPath, {
|
|
396
|
+
provider: slot ?? null,
|
|
397
|
+
price: priceRecord(prices, rates),
|
|
389
398
|
model: modelId,
|
|
390
399
|
modelReturned: metered.model,
|
|
391
400
|
tokens: metered.tokens,
|
package/src/monthly.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/monthly.js@0e55685 (the claim protocol, the refusal text shape, the spend summary's honesty rules)
|
|
2
|
+
// M4d piece 3 (docs/wiki/the-module-ladder.md, "M4d", scope items 4-5): the monthly limit.
|
|
3
|
+
//
|
|
4
|
+
// ONE record: `<configHome>/runs.jsonl`, append-only, mode 0600, one row per hold and per terminal note.
|
|
5
|
+
// hold: { kind:'hold', holdId, what:'run'|'resume'|'draft', flow, runId, runDir, pid, procStart, holdUsd, spentAtHold, at }
|
|
6
|
+
// terminal: { kind:'settled'|'released'|'refused', holdId, at, why [, alsoRunDirs] }
|
|
7
|
+
// Rows are only ever appended. Month spend is read from each named run/draft dir's OWN `spend.jsonl`
|
|
8
|
+
// (so the total is the same whichever `--root` a run used) — this file carries no money of its own.
|
|
9
|
+
//
|
|
10
|
+
// The claim (bareloop `claimRun`): the door APPENDS its hold FIRST, then reads the file; only live,
|
|
11
|
+
// unsettled holds that come BEFORE its own row count against it, so whoever is first holds. A hold whose
|
|
12
|
+
// process is gone (src/liveness.js `isFwdloopAlive`, M4c's one rule) is settled by the checker.
|
|
13
|
+
// No limit set = a hold row of $0 and no check (the row is what names the run dir, so its spend is counted
|
|
14
|
+
// once a limit is set). An unreadable/invalid config.json THROWS ConfigError: the gate refuses
|
|
15
|
+
// by name, it never reads as "no limit".
|
|
16
|
+
//
|
|
17
|
+
// Honesty: a row whose cost is unknown counts as `spendRowCost` says (floor + ceiling at its own price) and
|
|
18
|
+
// makes its figure "at least". A row with no `at` (written before M4d, reachable only when an old run is
|
|
19
|
+
// resumed) counts in "to date" only and is counted in `undatedRows`. Model time is the sum of rows' `wallMs`;
|
|
20
|
+
// a row without one (a draft row) adds nothing and marks that figure "at least"; none at all = null.
|
|
21
|
+
import {
|
|
22
|
+
appendFileSync, mkdirSync, readFileSync, realpathSync,
|
|
23
|
+
} from 'node:fs';
|
|
24
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
25
|
+
import { randomUUID } from 'node:crypto';
|
|
26
|
+
|
|
27
|
+
import { readConfig, configHome, ConfigError } from './config.js';
|
|
28
|
+
import { isFwdloopAlive, procStartOf } from './liveness.js';
|
|
29
|
+
import { readSpendRows, spendRowCost } from './provider.js';
|
|
30
|
+
|
|
31
|
+
export { ConfigError };
|
|
32
|
+
|
|
33
|
+
export const REFUSAL_SENTENCE = 'Nothing spent. Raise the monthly limit in Settings, or wait for next month.';
|
|
34
|
+
export const NOT_RECORDED = 'not recorded';
|
|
35
|
+
|
|
36
|
+
const runsPath = (home) => join(configHome(home), 'runs.jsonl');
|
|
37
|
+
|
|
38
|
+
/** realpath of the longest existing prefix of `p`, the rest appended (a run dir does not exist yet at claim time). @param {string} p */
|
|
39
|
+
export function realpathLoose(p) {
|
|
40
|
+
const abs = resolve(p);
|
|
41
|
+
const rest = [];
|
|
42
|
+
let cur = abs;
|
|
43
|
+
for (;;) {
|
|
44
|
+
try { return join(realpathSync(cur), ...rest.reverse()); } catch { /* not there yet */ }
|
|
45
|
+
const up = dirname(cur);
|
|
46
|
+
if (up === cur) return abs;
|
|
47
|
+
rest.push(basename(cur));
|
|
48
|
+
cur = up;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function appendRow(home, row) {
|
|
53
|
+
mkdirSync(configHome(home), { recursive: true, mode: 0o700 });
|
|
54
|
+
appendFileSync(runsPath(home), `${JSON.stringify(row)}\n`, { mode: 0o600 });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @param {string} [home] @returns {any[]} every well-formed row in file order (a torn line is skipped) */
|
|
58
|
+
export function readRuns(home) {
|
|
59
|
+
let text;
|
|
60
|
+
try { text = readFileSync(runsPath(home), 'utf8'); } catch { return []; }
|
|
61
|
+
const rows = [];
|
|
62
|
+
for (const line of text.split('\n')) {
|
|
63
|
+
if (!line.trim()) continue;
|
|
64
|
+
try { const r = JSON.parse(line); if (r && typeof r === 'object') rows.push(r); } catch { /* skip */ }
|
|
65
|
+
}
|
|
66
|
+
return rows;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const tokensOf = (t) => (t && typeof t === 'object'
|
|
70
|
+
? ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheCreationTokens'].reduce((n, k) => n + (Number.isFinite(t[k]) ? t[k] : 0), 0)
|
|
71
|
+
: 0);
|
|
72
|
+
const sameMonth = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();
|
|
73
|
+
|
|
74
|
+
/** Every run/draft dir the record names (deduped by realpath), including dirs a settle note adds. */
|
|
75
|
+
function namedDirs(rows) {
|
|
76
|
+
const dirs = new Set();
|
|
77
|
+
for (const r of rows) {
|
|
78
|
+
if (r.kind === 'hold' && typeof r.runDir === 'string') dirs.add(r.runDir);
|
|
79
|
+
if (Array.isArray(r.alsoRunDirs)) for (const d of r.alsoRunDirs) if (typeof d === 'string') dirs.add(d);
|
|
80
|
+
}
|
|
81
|
+
return [...dirs];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** One dir's total spend (every row, `spendRowCost`). */
|
|
85
|
+
function dirSpend(dir) {
|
|
86
|
+
return readSpendRows(join(dir, 'spend.jsonl')).reduce((n, r) => n + spendRowCost(r).usd, 0);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The Money tab's figures (piece 4 reads this) and the check's month total.
|
|
91
|
+
* @param {{ home?: string, now?: () => number }} [opts]
|
|
92
|
+
*/
|
|
93
|
+
export function spendSummary(opts = {}) {
|
|
94
|
+
const nowDate = new Date((opts.now ?? Date.now)());
|
|
95
|
+
const newBucket = () => ({
|
|
96
|
+
usd: 0, atLeast: false, tokens: 0, modelMs: null, modelMsAtLeast: false, rows: 0,
|
|
97
|
+
});
|
|
98
|
+
const total = newBucket();
|
|
99
|
+
const month = newBucket();
|
|
100
|
+
/** @type {Record<string, {label: string, month: ReturnType<typeof newBucket>, total: ReturnType<typeof newBucket>}>} */
|
|
101
|
+
const byProvider = {};
|
|
102
|
+
let undatedRows = 0;
|
|
103
|
+
const add = (b, usd, complete, tokens, wall) => {
|
|
104
|
+
b.rows += 1; b.usd += usd; b.tokens += tokens;
|
|
105
|
+
if (!complete) b.atLeast = true;
|
|
106
|
+
if (wall === null) b.modelMsAtLeast = true;
|
|
107
|
+
else b.modelMs = (b.modelMs ?? 0) + wall;
|
|
108
|
+
};
|
|
109
|
+
for (const dir of namedDirs(readRuns(opts.home))) {
|
|
110
|
+
for (const row of readSpendRows(join(dir, 'spend.jsonl'))) {
|
|
111
|
+
const { usd, complete } = spendRowCost(row);
|
|
112
|
+
const tokens = tokensOf(row.tokens);
|
|
113
|
+
const wall = Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null;
|
|
114
|
+
const key = typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED;
|
|
115
|
+
const p = (byProvider[key] ??= { label: key, month: newBucket(), total: newBucket() });
|
|
116
|
+
add(total, usd, complete, tokens, wall);
|
|
117
|
+
add(p.total, usd, complete, tokens, wall);
|
|
118
|
+
if (row.at === undefined || row.at === null) { undatedRows += 1; continue; }
|
|
119
|
+
const at = new Date(row.at);
|
|
120
|
+
if (Number.isNaN(at.getTime())) { month.atLeast = true; p.month.atLeast = true; continue; } // could be this month: unknown, never dropped
|
|
121
|
+
if (sameMonth(at, nowDate)) {
|
|
122
|
+
add(month, usd, complete, tokens, wall);
|
|
123
|
+
add(p.month, usd, complete, tokens, wall);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const minutes = (b) => ({ modelMinutes: b.modelMs === null ? null : b.modelMs / 60000, modelMinutesAtLeast: b.modelMs === null || b.modelMsAtLeast });
|
|
128
|
+
const fin = (b) => ({
|
|
129
|
+
usd: b.usd, atLeast: b.atLeast, tokens: b.tokens, ...minutes(b),
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
month: fin(month),
|
|
133
|
+
total: fin(total),
|
|
134
|
+
byProvider: Object.fromEntries(Object.entries(byProvider).map(([k, v]) => [k, { label: v.label, month: fin(v.month), total: fin(v.total) }])),
|
|
135
|
+
undatedRows,
|
|
136
|
+
// Runs from before M4d were never written to runs.jsonl: their money is in no figure here.
|
|
137
|
+
preM4dRunsNotCounted: true,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Settle every unsettled hold BEFORE `idx` whose process is gone; return what the live ones still hold.
|
|
143
|
+
* `null` from the liveness check ("cannot tell") never settles: it holds.
|
|
144
|
+
*/
|
|
145
|
+
function liveHeldBefore(rows, idx, home, nowIso) {
|
|
146
|
+
const ended = new Set(rows.filter((r) => r.kind === 'settled' || r.kind === 'released' || r.kind === 'refused').map((r) => r.holdId));
|
|
147
|
+
let heldUsd = 0;
|
|
148
|
+
let heldRuns = 0;
|
|
149
|
+
for (const r of rows.slice(0, idx)) {
|
|
150
|
+
if (r.kind !== 'hold' || ended.has(r.holdId) || !Number.isFinite(r.holdUsd)) continue;
|
|
151
|
+
if (isFwdloopAlive(r.pid, typeof r.procStart === 'string' ? r.procStart : null) === false) {
|
|
152
|
+
appendRow(home, { kind: 'settled', holdId: r.holdId, at: nowIso, why: 'process gone' });
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const spentSince = Math.max(0, dirSpend(r.runDir) - (Number.isFinite(r.spentAtHold) ? r.spentAtHold : 0));
|
|
156
|
+
const extra = Math.max(0, r.holdUsd - spentSince);
|
|
157
|
+
if (extra > 0) { heldUsd += extra; heldRuns += 1; }
|
|
158
|
+
}
|
|
159
|
+
return { heldUsd, heldRuns };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* @typedef {object} Claim
|
|
164
|
+
* @property {boolean} ok the hold fits (or no limit is set)
|
|
165
|
+
* @property {string} holdId the hold row's id (a $0 hold when no limit is set)
|
|
166
|
+
* @property {{limitUsd:number|null, leftUsd:number|null, heldUsd:number, heldRuns:number, needUsd:number, atLeast:boolean}} room
|
|
167
|
+
*/
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The check at a door. Appends the hold row first (always, even with no limit), then decides. Throws ConfigError when config.json is
|
|
171
|
+
* broken (nothing is appended) or the row cannot be written. A refusal appends a `refused` row.
|
|
172
|
+
* @param {{ what: 'run'|'resume'|'draft', flow: string|null, runId: string|null, runDir: string, holdUsd: number, spentAtHold?: number, home?: string, now?: () => number }} a
|
|
173
|
+
* @returns {Claim}
|
|
174
|
+
*/
|
|
175
|
+
export function claimHold({
|
|
176
|
+
what, flow, runId, runDir, holdUsd, spentAtHold = 0, home, now = Date.now,
|
|
177
|
+
}) {
|
|
178
|
+
const cfg = readConfig({ home });
|
|
179
|
+
const limit = cfg.monthlyLimitUsd ?? null;
|
|
180
|
+
const room = { limitUsd: limit, leftUsd: null, heldUsd: 0, heldRuns: 0, needUsd: holdUsd, atLeast: false };
|
|
181
|
+
const nowIso = new Date(now()).toISOString();
|
|
182
|
+
const holdId = randomUUID();
|
|
183
|
+
try {
|
|
184
|
+
appendRow(home, {
|
|
185
|
+
kind: 'hold', holdId, what, flow, runId, runDir: realpathLoose(runDir), pid: process.pid, procStart: procStartOf('self'),
|
|
186
|
+
// No limit set: $0 is held and no check runs, but the row still names the run dir so its spend is counted.
|
|
187
|
+
holdUsd: limit === null ? 0 : holdUsd, spentAtHold, at: nowIso,
|
|
188
|
+
});
|
|
189
|
+
} catch (/** @type {any} */ e) {
|
|
190
|
+
throw new ConfigError(`cannot write this hold to ${runsPath(home)} (${e?.code ?? 'error'}) — refusing rather than run with its spend unrecorded or past the monthly limit unchecked`);
|
|
191
|
+
}
|
|
192
|
+
if (limit === null) return { ok: true, holdId, room };
|
|
193
|
+
const rows = readRuns(home);
|
|
194
|
+
const idx = rows.findIndex((r) => r.kind === 'hold' && r.holdId === holdId);
|
|
195
|
+
const { heldUsd, heldRuns } = liveHeldBefore(rows, idx < 0 ? rows.length : idx, home, nowIso);
|
|
196
|
+
const month = spendSummary({ home, now }).month;
|
|
197
|
+
const leftCents = Math.max(0, Math.floor((limit - month.usd - heldUsd) * 100 + 1e-6));
|
|
198
|
+
const needCents = Math.ceil(holdUsd * 100 - 1e-6); // a non-finite hold never fits — never read as $0
|
|
199
|
+
const ok = needCents <= leftCents;
|
|
200
|
+
Object.assign(room, { leftUsd: leftCents / 100, heldUsd, heldRuns, atLeast: month.atLeast });
|
|
201
|
+
if (!ok) {
|
|
202
|
+
try { appendRow(home, { kind: 'refused', holdId, at: nowIso, why: 'over the monthly limit' }); } catch { /* the refusal stands; a dead process's hold is settled by the next check */ }
|
|
203
|
+
return { ok: false, holdId, room };
|
|
204
|
+
}
|
|
205
|
+
return { ok: true, holdId, room };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The run's own process ends or parks: give the hold back. Never throws (a failed settle is closed by the
|
|
210
|
+
* next check as "process gone"). `alsoRunDirs` names dirs this process also spent into (a rerun's new run).
|
|
211
|
+
* @param {{ holdId: string|null, why: string, home?: string, now?: () => number, alsoRunDirs?: string[] }} a
|
|
212
|
+
*/
|
|
213
|
+
export function settleHold({
|
|
214
|
+
holdId, why, home, now = Date.now, alsoRunDirs,
|
|
215
|
+
}) {
|
|
216
|
+
if (!holdId) return;
|
|
217
|
+
try {
|
|
218
|
+
appendRow(home, {
|
|
219
|
+
kind: 'settled', holdId, at: new Date(now()).toISOString(), why, ...(alsoRunDirs?.length ? { alsoRunDirs: alsoRunDirs.map(realpathLoose) } : {}),
|
|
220
|
+
});
|
|
221
|
+
} catch { /* see above */ }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* The ONE refusal text (CLI and page): the amount line, then the signed sentence.
|
|
226
|
+
* @param {Claim['room']} room
|
|
227
|
+
*/
|
|
228
|
+
export function monthlyRefusalText(room) {
|
|
229
|
+
const held = room.heldUsd > 0 ? `, $${room.heldUsd.toFixed(2)} held by ${room.heldRuns > 1 ? 'runs' : 'a run'} in progress` : '';
|
|
230
|
+
return `Max $${(room.leftUsd ?? 0).toFixed(2)} left this month (monthly limit $${(room.limitUsd ?? 0).toFixed(2)}${held}); this needs $${room.needUsd.toFixed(2)}.\n${REFUSAL_SENTENCE}`;
|
|
231
|
+
}
|