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/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,14 +251,17 @@ 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
- ({ provider, rates, modelId } = makeProvider(slot, { model, ...LIVE_PROVIDER_OPTIONS }));
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
- // `tokens: null` (and `tools: null`, M4a-3) here is the one honest
259
+ // `model: null`, `tokens: null` and `tools: null` (M4a-3) here are the one honest
255
260
  // "no model call at all" case (never a zeroed object standing in for
256
- // a call that never happened).
261
+ // a call that never happened). A row that names a model must carry its
262
+ // tokens (appendAudit refuses it otherwise), so the model is not named.
257
263
  return {
258
- ok: false, red: `key: ${err.message}`, costUsd: null, model: model ?? null, tokens: null, tools: null,
264
+ ok: false, red: `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
259
265
  };
260
266
  }
261
267
  }
@@ -329,6 +335,8 @@ export function makeLiveModelStep({
329
335
  const partial = sumMeterings(roundMeterings);
330
336
  cumulative = addMeter(cumulative, partial);
331
337
  appendSpendRow(spendPath, {
338
+ provider: slot ?? null,
339
+ price: priceRecord(prices, rates),
332
340
  model: modelId,
333
341
  modelReturned: partial.model,
334
342
  tokens: partial.tokens,
@@ -385,6 +393,8 @@ export function makeLiveModelStep({
385
393
  cumulative = addMeter(cumulative, metered);
386
394
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
387
395
  appendSpendRow(spendPath, {
396
+ provider: slot ?? null,
397
+ price: priceRecord(prices, rates),
388
398
  model: modelId,
389
399
  modelReturned: metered.model,
390
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
+ }