fwdloop 0.11.0 → 0.13.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 +248 -27
- package/package.json +1 -1
- package/src/ask.js +3 -0
- package/src/authoring.js +103 -13
- package/src/books.js +23 -2
- package/src/canrun.js +36 -0
- package/src/config.js +256 -0
- package/src/declaration.js +72 -2
- package/src/drafter.js +53 -11
- package/src/draftspend.js +70 -0
- package/src/flow.js +43 -0
- package/src/keysfile.js +180 -0
- package/src/liveness.js +1 -1
- package/src/model-step.js +43 -8
- package/src/monthly.js +276 -0
- package/src/panel/author.js +482 -0
- package/src/panel/authorcard.js +297 -0
- package/src/panel/authorflows.js +312 -0
- package/src/panel/authorresume.js +149 -0
- package/src/panel/authorstart.js +257 -0
- package/src/panel/authorvalues.js +110 -0
- package/src/panel/data.js +228 -34
- package/src/panel/index.html +2073 -124
- package/src/panel/resume.js +14 -11
- package/src/panel/server.js +150 -117
- package/src/panel/settings.js +270 -0
- package/src/panel/spawn.js +77 -0
- package/src/provider.js +189 -43
- package/src/providershapes.js +19 -0
- package/src/runner.js +639 -85
- package/src/runvalues.js +178 -0
- package/src/send.js +10 -3
- package/src/setup.js +120 -0
- package/types/authoring.d.ts +24 -2
- package/types/books.d.ts +14 -2
- package/types/canrun.d.ts +32 -0
- package/types/config.d.ts +52 -0
- package/types/declaration.d.ts +9 -1
- package/types/drafter.d.ts +18 -2
- package/types/draftspend.d.ts +21 -0
- package/types/flow.d.ts +23 -0
- package/types/keysfile.d.ts +90 -0
- package/types/liveness.d.ts +2 -2
- package/types/model-step.d.ts +6 -2
- package/types/monthly.d.ts +130 -0
- package/types/panel/author.d.ts +335 -0
- package/types/panel/authorcard.d.ts +120 -0
- package/types/panel/authorflows.d.ts +175 -0
- package/types/panel/authorresume.d.ts +32 -0
- package/types/panel/authorstart.d.ts +115 -0
- package/types/panel/authorvalues.d.ts +62 -0
- package/types/panel/data.d.ts +103 -12
- package/types/panel/resume.d.ts +8 -1
- package/types/panel/server.d.ts +19 -33
- package/types/panel/settings.d.ts +23 -0
- package/types/panel/spawn.d.ts +30 -0
- package/types/provider.d.ts +123 -70
- package/types/providershapes.d.ts +11 -0
- package/types/runner.d.ts +120 -5
- package/types/runvalues.d.ts +97 -0
- package/types/send.d.ts +5 -1
- package/types/setup.d.ts +83 -0
package/src/model-step.js
CHANGED
|
@@ -24,11 +24,12 @@
|
|
|
24
24
|
// (green/softgreen/anything else) — never from the step's `shape` — the
|
|
25
25
|
// executor context (M2 scope item 3) carries neither.
|
|
26
26
|
|
|
27
|
-
import { Loop } from 'bare-agent';
|
|
27
|
+
import { Loop, HaltError } 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
|
|
@@ -214,6 +215,8 @@ function addToolCounts(cumulative, byTool, grantedNames) {
|
|
|
214
215
|
// clean row would just be noise).
|
|
215
216
|
function toolFields(cumulative) {
|
|
216
217
|
return {
|
|
218
|
+
// M4e amendment 7 item 8: model calls (turns) this attempt made, so a Stop can say "after turn T of try K".
|
|
219
|
+
turns: cumulative.rounds,
|
|
217
220
|
tools: cumulative.tools,
|
|
218
221
|
// Gate refusals this attempt — always present (empty array when none) so
|
|
219
222
|
// absence can never be confused with "none".
|
|
@@ -222,6 +225,15 @@ function toolFields(cumulative) {
|
|
|
222
225
|
};
|
|
223
226
|
}
|
|
224
227
|
|
|
228
|
+
const STOP_RULE = 'stop-requested';
|
|
229
|
+
|
|
230
|
+
/** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
|
|
231
|
+
function stoppedResult(cumulative, modelId, modelMatch) {
|
|
232
|
+
return {
|
|
233
|
+
ok: false, stopped: true, red: 'stopped by you', costUsd: cumulative.costUsd, tokens: cumulative.tokens, ...toolFields(cumulative), model: modelId, modelMatch,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
225
237
|
/**
|
|
226
238
|
* @param {object} opts
|
|
227
239
|
* @param {string} [opts.slot] - a `src/provider.js` PROVIDER_SLOTS name; required when `provider` isn't injected.
|
|
@@ -230,17 +242,22 @@ function toolFields(cumulative) {
|
|
|
230
242
|
* @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
|
|
231
243
|
* @param {{in:number,out:number}} [opts.rates]
|
|
232
244
|
* @param {string} [opts.modelId]
|
|
233
|
-
* @
|
|
245
|
+
* @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
|
|
246
|
+
* @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
|
|
234
247
|
*/
|
|
235
248
|
export function makeLiveModelStep({
|
|
236
|
-
slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId,
|
|
249
|
+
slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
|
|
237
250
|
}) {
|
|
238
251
|
const live = injectedProvider == null;
|
|
239
252
|
|
|
240
|
-
|
|
253
|
+
// M4e amendment 7 item 8: `seam.stopRequested` (the runner's one stop reader, never this module's) is asked before EVERY model call —
|
|
254
|
+
// each turn inside a Loop (bare-agent's `assemble`, which runs before every `provider.generate`, a thrown HaltError being a clean
|
|
255
|
+
// return) and each new Loop (a new round of this attempt). The call in flight when a Stop lands finishes and is metered; none starts after.
|
|
256
|
+
return async function liveModelStep(executorContext, grantedTools, stepMeta = {}, seam = {}) {
|
|
241
257
|
let provider = injectedProvider;
|
|
242
258
|
let rates = injectedRates;
|
|
243
259
|
let modelId = injectedModelId;
|
|
260
|
+
let prices = null;
|
|
244
261
|
if (live) {
|
|
245
262
|
// makeProvider throws synchronously on a missing/bad key, an unknown
|
|
246
263
|
// slot, or an unrated model — never let that escape as an unhandled
|
|
@@ -248,7 +265,9 @@ export function makeLiveModelStep({
|
|
|
248
265
|
// always a red, never a crash (rule 5).
|
|
249
266
|
try {
|
|
250
267
|
if (!slot) throw new Error('makeLiveModelStep: "slot" is required when no provider is injected');
|
|
251
|
-
({
|
|
268
|
+
({
|
|
269
|
+
provider, rates, modelId, prices,
|
|
270
|
+
} = makeProvider(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
|
|
252
271
|
} catch (err) {
|
|
253
272
|
// No provider was ever built, so no round could possibly have run —
|
|
254
273
|
// `model: null`, `tokens: null` and `tools: null` (M4a-3) here are the one honest
|
|
@@ -256,7 +275,7 @@ export function makeLiveModelStep({
|
|
|
256
275
|
// a call that never happened). A row that names a model must carry its
|
|
257
276
|
// tokens (appendAudit refuses it otherwise), so the model is not named.
|
|
258
277
|
return {
|
|
259
|
-
ok: false, red:
|
|
278
|
+
ok: false, red: `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
|
|
260
279
|
};
|
|
261
280
|
}
|
|
262
281
|
}
|
|
@@ -318,7 +337,11 @@ export function makeLiveModelStep({
|
|
|
318
337
|
};
|
|
319
338
|
const tools = [...primitiveTools, emitTool];
|
|
320
339
|
const roundMeterings = [];
|
|
321
|
-
const
|
|
340
|
+
const stopRequested = seam?.stopRequested;
|
|
341
|
+
const stopSeam = typeof stopRequested === 'function'
|
|
342
|
+
? { assemble: async (msgs) => { if (stopRequested()) throw new HaltError('stop requested', { rule: STOP_RULE }); return msgs; } }
|
|
343
|
+
: {};
|
|
344
|
+
const loop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundMeterings.push(ev); }, ...stopSeam });
|
|
322
345
|
|
|
323
346
|
const startedAt = Date.now();
|
|
324
347
|
let result;
|
|
@@ -330,6 +353,8 @@ export function makeLiveModelStep({
|
|
|
330
353
|
const partial = sumMeterings(roundMeterings);
|
|
331
354
|
cumulative = addMeter(cumulative, partial);
|
|
332
355
|
appendSpendRow(spendPath, {
|
|
356
|
+
provider: slot ?? null,
|
|
357
|
+
price: priceRecord(prices, rates),
|
|
333
358
|
model: modelId,
|
|
334
359
|
modelReturned: partial.model,
|
|
335
360
|
tokens: partial.tokens,
|
|
@@ -382,10 +407,16 @@ export function makeLiveModelStep({
|
|
|
382
407
|
}
|
|
383
408
|
|
|
384
409
|
const wallMs = Date.now() - startedAt;
|
|
410
|
+
const stoppedByYou = result.error === `halt:${STOP_RULE}`;
|
|
411
|
+
// A Stop read before this Loop's first call: no call ran, so there is nothing to meter or book — and an empty metering
|
|
412
|
+
// must never be added as "cost unknown" onto the calls an earlier round already made.
|
|
413
|
+
if (stoppedByYou && roundMeterings.length === 0) return stoppedResult(cumulative, modelId, null);
|
|
385
414
|
const metered = sumMeterings(roundMeterings);
|
|
386
415
|
cumulative = addMeter(cumulative, metered);
|
|
387
416
|
cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
|
|
388
417
|
appendSpendRow(spendPath, {
|
|
418
|
+
provider: slot ?? null,
|
|
419
|
+
price: priceRecord(prices, rates),
|
|
389
420
|
model: modelId,
|
|
390
421
|
modelReturned: metered.model,
|
|
391
422
|
tokens: metered.tokens,
|
|
@@ -397,6 +428,10 @@ export function makeLiveModelStep({
|
|
|
397
428
|
|
|
398
429
|
const modelMatch = classifyModelId(modelId, metered.model);
|
|
399
430
|
|
|
431
|
+
// The call in flight finished and is booked above. If it already emitted the artifact the step simply closes (the runner's
|
|
432
|
+
// after-step seam then ends the run); otherwise the step ends here, `stopped`, with its tries and spend carried.
|
|
433
|
+
if (stoppedByYou && capturedArtifact === undefined) return stoppedResult(cumulative, modelId, modelMatch);
|
|
434
|
+
|
|
400
435
|
if (result.stopReason === 'max_tokens') {
|
|
401
436
|
// Rule 4: deterministic (the step needs a smaller output or a
|
|
402
437
|
// bigger cap), never a transient fault a retry could fix.
|
package/src/monthly.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
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 { spendRowCost } from './provider.js';
|
|
30
|
+
import { readDirSpendRows } from './draftspend.js';
|
|
31
|
+
|
|
32
|
+
export { ConfigError };
|
|
33
|
+
|
|
34
|
+
export const REFUSAL_SENTENCE = 'Nothing spent. Raise the monthly limit in Settings, or wait for next month.';
|
|
35
|
+
export const NOT_RECORDED = 'not recorded';
|
|
36
|
+
|
|
37
|
+
const runsPath = (home) => join(configHome(home), 'runs.jsonl');
|
|
38
|
+
|
|
39
|
+
/** realpath of the longest existing prefix of `p`, the rest appended (a run dir does not exist yet at claim time). @param {string} p */
|
|
40
|
+
export function realpathLoose(p) {
|
|
41
|
+
const abs = resolve(p);
|
|
42
|
+
const rest = [];
|
|
43
|
+
let cur = abs;
|
|
44
|
+
for (;;) {
|
|
45
|
+
try { return join(realpathSync(cur), ...rest.reverse()); } catch { /* not there yet */ }
|
|
46
|
+
const up = dirname(cur);
|
|
47
|
+
if (up === cur) return abs;
|
|
48
|
+
rest.push(basename(cur));
|
|
49
|
+
cur = up;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function appendRow(home, row) {
|
|
54
|
+
mkdirSync(configHome(home), { recursive: true, mode: 0o700 });
|
|
55
|
+
appendFileSync(runsPath(home), `${JSON.stringify(row)}\n`, { mode: 0o600 });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @param {string} [home] @returns {any[]} every well-formed row in file order (a torn line is skipped) */
|
|
59
|
+
export function readRuns(home) {
|
|
60
|
+
let text;
|
|
61
|
+
try { text = readFileSync(runsPath(home), 'utf8'); } catch { return []; }
|
|
62
|
+
const rows = [];
|
|
63
|
+
for (const line of text.split('\n')) {
|
|
64
|
+
if (!line.trim()) continue;
|
|
65
|
+
try { const r = JSON.parse(line); if (r && typeof r === 'object') rows.push(r); } catch { /* skip */ }
|
|
66
|
+
}
|
|
67
|
+
return rows;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const tokensOf = (t) => (t && typeof t === 'object'
|
|
71
|
+
? ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheCreationTokens'].reduce((n, k) => n + (Number.isFinite(t[k]) ? t[k] : 0), 0)
|
|
72
|
+
: 0);
|
|
73
|
+
const sameMonth = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();
|
|
74
|
+
|
|
75
|
+
/** Every run/draft dir the record names (deduped by realpath), including dirs a settle note adds. */
|
|
76
|
+
function namedDirs(rows) {
|
|
77
|
+
const dirs = new Set();
|
|
78
|
+
for (const r of rows) {
|
|
79
|
+
if (r.kind === 'hold' && typeof r.runDir === 'string') dirs.add(r.runDir);
|
|
80
|
+
if (Array.isArray(r.alsoRunDirs)) for (const d of r.alsoRunDirs) if (typeof d === 'string') dirs.add(d);
|
|
81
|
+
}
|
|
82
|
+
return [...dirs];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One dir's total spend (every row, `spendRowCost`; a draft dir's live record until its final row exists — src/draftspend.js). */
|
|
86
|
+
function dirSpend(dir) {
|
|
87
|
+
return readDirSpendRows(dir).reduce((n, r) => n + spendRowCost(r).usd, 0);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The Money tab's figures (piece 4 reads this) and the check's month total.
|
|
92
|
+
* @param {{ home?: string, now?: () => number }} [opts]
|
|
93
|
+
*/
|
|
94
|
+
export function spendSummary(opts = {}) {
|
|
95
|
+
const nowDate = new Date((opts.now ?? Date.now)());
|
|
96
|
+
const newBucket = () => ({
|
|
97
|
+
usd: 0, atLeast: false, tokens: 0, modelMs: null, modelMsAtLeast: false, rows: 0,
|
|
98
|
+
});
|
|
99
|
+
const total = newBucket();
|
|
100
|
+
const month = newBucket();
|
|
101
|
+
/** @type {Record<string, {label: string, month: ReturnType<typeof newBucket>, total: ReturnType<typeof newBucket>}>} */
|
|
102
|
+
const byProvider = {};
|
|
103
|
+
let undatedRows = 0;
|
|
104
|
+
const add = (b, usd, complete, tokens, wall) => {
|
|
105
|
+
b.rows += 1; b.usd += usd; b.tokens += tokens;
|
|
106
|
+
if (!complete) b.atLeast = true;
|
|
107
|
+
if (wall === null) b.modelMsAtLeast = true;
|
|
108
|
+
else b.modelMs = (b.modelMs ?? 0) + wall;
|
|
109
|
+
};
|
|
110
|
+
for (const dir of namedDirs(readRuns(opts.home))) {
|
|
111
|
+
for (const row of readDirSpendRows(dir)) {
|
|
112
|
+
const { usd, complete } = spendRowCost(row);
|
|
113
|
+
const tokens = tokensOf(row.tokens);
|
|
114
|
+
const wall = Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null;
|
|
115
|
+
const key = typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED;
|
|
116
|
+
const p = (byProvider[key] ??= { label: key, month: newBucket(), total: newBucket() });
|
|
117
|
+
add(total, usd, complete, tokens, wall);
|
|
118
|
+
add(p.total, usd, complete, tokens, wall);
|
|
119
|
+
if (row.at === undefined || row.at === null) { undatedRows += 1; continue; }
|
|
120
|
+
const at = new Date(row.at);
|
|
121
|
+
if (Number.isNaN(at.getTime())) { month.atLeast = true; p.month.atLeast = true; continue; } // could be this month: unknown, never dropped
|
|
122
|
+
if (sameMonth(at, nowDate)) {
|
|
123
|
+
add(month, usd, complete, tokens, wall);
|
|
124
|
+
add(p.month, usd, complete, tokens, wall);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const minutes = (b) => ({ modelMinutes: b.modelMs === null ? null : b.modelMs / 60000, modelMinutesAtLeast: b.modelMs === null || b.modelMsAtLeast });
|
|
129
|
+
const fin = (b) => ({
|
|
130
|
+
usd: b.usd, atLeast: b.atLeast, tokens: b.tokens, ...minutes(b),
|
|
131
|
+
});
|
|
132
|
+
return {
|
|
133
|
+
month: fin(month),
|
|
134
|
+
total: fin(total),
|
|
135
|
+
byProvider: Object.fromEntries(Object.entries(byProvider).map(([k, v]) => [k, { label: v.label, month: fin(v.month), total: fin(v.total) }])),
|
|
136
|
+
undatedRows,
|
|
137
|
+
// Runs from before M4d were never written to runs.jsonl: their money is in no figure here.
|
|
138
|
+
preM4dRunsNotCounted: true,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Settle every unsettled hold BEFORE `idx` whose process is gone; return what the live ones still hold.
|
|
144
|
+
* `null` from the liveness check ("cannot tell") never settles: it holds. `settle: false` (the page's read-only note) counts the same
|
|
145
|
+
* but writes nothing.
|
|
146
|
+
*/
|
|
147
|
+
function liveHeldBefore(rows, idx, home, nowIso, settle = true) {
|
|
148
|
+
const ended = new Set(rows.filter((r) => r.kind === 'settled' || r.kind === 'released' || r.kind === 'refused').map((r) => r.holdId));
|
|
149
|
+
let heldUsd = 0;
|
|
150
|
+
let heldRuns = 0;
|
|
151
|
+
for (const r of rows.slice(0, idx)) {
|
|
152
|
+
if (r.kind !== 'hold' || ended.has(r.holdId) || !Number.isFinite(r.holdUsd)) continue;
|
|
153
|
+
if (isFwdloopAlive(r.pid, typeof r.procStart === 'string' ? r.procStart : null) === false) {
|
|
154
|
+
if (settle) appendRow(home, { kind: 'settled', holdId: r.holdId, at: nowIso, why: 'process gone' });
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const spentSince = Math.max(0, dirSpend(r.runDir) - (Number.isFinite(r.spentAtHold) ? r.spentAtHold : 0));
|
|
158
|
+
const extra = Math.max(0, r.holdUsd - spentSince);
|
|
159
|
+
if (extra > 0) { heldUsd += extra; heldRuns += 1; }
|
|
160
|
+
}
|
|
161
|
+
return { heldUsd, heldRuns };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The ONE computation of "does a hold of `holdUsd` fit this month": the limit minus this month's counted spend minus what live
|
|
166
|
+
* runs before `idx` still hold, in whole cents. `claimHold` (the door) and `checkMonthlyRoom` (the page's note) both call it, so the
|
|
167
|
+
* note and the refusal are never two opinions.
|
|
168
|
+
* @param {{ limit: number, holdUsd: number, rows: any[], idx: number, home?: string, now: () => number, nowIso: string, settle?: boolean }} a
|
|
169
|
+
*/
|
|
170
|
+
function roomFor({ limit, holdUsd, rows, idx, home, now, nowIso, settle = true }) {
|
|
171
|
+
const { heldUsd, heldRuns } = liveHeldBefore(rows, idx, home, nowIso, settle);
|
|
172
|
+
const month = spendSummary({ home, now }).month;
|
|
173
|
+
const leftCents = Math.max(0, Math.floor((limit - month.usd - heldUsd) * 100 + 1e-6));
|
|
174
|
+
const needCents = Math.ceil(holdUsd * 100 - 1e-6); // a non-finite hold never fits — never read as $0
|
|
175
|
+
return {
|
|
176
|
+
ok: needCents <= leftCents, leftUsd: leftCents / 100, heldUsd, heldRuns, atLeast: month.atLeast,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// borrowed-from: bareloop src/monthly.js@c1d87ce (`checkMonthlyRoom`, shape only: fwdloop's holds and rows differ)
|
|
181
|
+
/**
|
|
182
|
+
* Read-only: would a run holding `capUsd` fit this month? The same numbers `claimHold` decides on, but no hold row and no settle is
|
|
183
|
+
* written — it is what the panel's note under Cap shows. Throws ConfigError when config.json is broken.
|
|
184
|
+
* @param {{ capUsd: number, home?: string, now?: () => number }} a
|
|
185
|
+
* @returns {Claim}
|
|
186
|
+
*/
|
|
187
|
+
export function checkMonthlyRoom({ capUsd, home, now = Date.now }) {
|
|
188
|
+
const limit = readConfig({ home }).monthlyLimitUsd ?? null;
|
|
189
|
+
const room = { limitUsd: limit, leftUsd: null, heldUsd: 0, heldRuns: 0, needUsd: capUsd, atLeast: false };
|
|
190
|
+
if (limit === null) return { ok: true, holdId: '', room };
|
|
191
|
+
const rows = readRuns(home);
|
|
192
|
+
const { ok, ...found } = roomFor({ limit, holdUsd: capUsd, rows, idx: rows.length, home, now, nowIso: new Date(now()).toISOString(), settle: false });
|
|
193
|
+
Object.assign(room, found);
|
|
194
|
+
return { ok, holdId: '', room };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The short line under the Cap box (M4e amendment 4 item 1), from the same room: `needs $0.50 ($0.10 left monthly)` (red) when the
|
|
199
|
+
* cap does not fit, `$4.90 left monthly` when it does; '' when no limit is set. Money is never rounded down to look like it fits.
|
|
200
|
+
* @param {Claim} claim
|
|
201
|
+
* @returns {{ text: string, red: boolean }}
|
|
202
|
+
*/
|
|
203
|
+
export function monthlyNote(claim) {
|
|
204
|
+
const { room } = claim;
|
|
205
|
+
if (room.limitUsd === null || room.leftUsd === null) return { text: '', red: false };
|
|
206
|
+
const left = `$${room.leftUsd.toFixed(2)}`;
|
|
207
|
+
if (!claim.ok) return { text: `needs $${(Math.ceil(room.needUsd * 100 - 1e-6) / 100).toFixed(2)} (${left} left monthly)`, red: true };
|
|
208
|
+
return { text: `${room.atLeast ? 'at most ' : ''}${left} left monthly`, red: false };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @typedef {object} Claim
|
|
213
|
+
* @property {boolean} ok the hold fits (or no limit is set)
|
|
214
|
+
* @property {string} holdId the hold row's id (a $0 hold when no limit is set)
|
|
215
|
+
* @property {{limitUsd:number|null, leftUsd:number|null, heldUsd:number, heldRuns:number, needUsd:number, atLeast:boolean}} room
|
|
216
|
+
*/
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The check at a door. Appends the hold row first (always, even with no limit), then decides. Throws ConfigError when config.json is
|
|
220
|
+
* broken (nothing is appended) or the row cannot be written. A refusal appends a `refused` row.
|
|
221
|
+
* @param {{ what: 'run'|'resume'|'draft', flow: string|null, runId: string|null, runDir: string, holdUsd: number, spentAtHold?: number, home?: string, now?: () => number }} a
|
|
222
|
+
* @returns {Claim}
|
|
223
|
+
*/
|
|
224
|
+
export function claimHold({
|
|
225
|
+
what, flow, runId, runDir, holdUsd, spentAtHold = 0, home, now = Date.now,
|
|
226
|
+
}) {
|
|
227
|
+
const cfg = readConfig({ home });
|
|
228
|
+
const limit = cfg.monthlyLimitUsd ?? null;
|
|
229
|
+
const room = { limitUsd: limit, leftUsd: null, heldUsd: 0, heldRuns: 0, needUsd: holdUsd, atLeast: false };
|
|
230
|
+
const nowIso = new Date(now()).toISOString();
|
|
231
|
+
const holdId = randomUUID();
|
|
232
|
+
try {
|
|
233
|
+
appendRow(home, {
|
|
234
|
+
kind: 'hold', holdId, what, flow, runId, runDir: realpathLoose(runDir), pid: process.pid, procStart: procStartOf('self'),
|
|
235
|
+
// No limit set: $0 is held and no check runs, but the row still names the run dir so its spend is counted.
|
|
236
|
+
holdUsd: limit === null ? 0 : holdUsd, spentAtHold, at: nowIso,
|
|
237
|
+
});
|
|
238
|
+
} catch (/** @type {any} */ e) {
|
|
239
|
+
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`);
|
|
240
|
+
}
|
|
241
|
+
if (limit === null) return { ok: true, holdId, room };
|
|
242
|
+
const rows = readRuns(home);
|
|
243
|
+
const idx = rows.findIndex((r) => r.kind === 'hold' && r.holdId === holdId);
|
|
244
|
+
const { ok, ...found } = roomFor({ limit, holdUsd, rows, idx: idx < 0 ? rows.length : idx, home, now, nowIso });
|
|
245
|
+
Object.assign(room, found);
|
|
246
|
+
if (!ok) {
|
|
247
|
+
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 */ }
|
|
248
|
+
return { ok: false, holdId, room };
|
|
249
|
+
}
|
|
250
|
+
return { ok: true, holdId, room };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The run's own process ends or parks: give the hold back. Never throws (a failed settle is closed by the
|
|
255
|
+
* next check as "process gone"). `alsoRunDirs` names dirs this process also spent into (a rerun's new run).
|
|
256
|
+
* @param {{ holdId: string|null, why: string, home?: string, now?: () => number, alsoRunDirs?: string[] }} a
|
|
257
|
+
*/
|
|
258
|
+
export function settleHold({
|
|
259
|
+
holdId, why, home, now = Date.now, alsoRunDirs,
|
|
260
|
+
}) {
|
|
261
|
+
if (!holdId) return;
|
|
262
|
+
try {
|
|
263
|
+
appendRow(home, {
|
|
264
|
+
kind: 'settled', holdId, at: new Date(now()).toISOString(), why, ...(alsoRunDirs?.length ? { alsoRunDirs: alsoRunDirs.map(realpathLoose) } : {}),
|
|
265
|
+
});
|
|
266
|
+
} catch { /* see above */ }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The ONE refusal text (CLI and page): the amount line, then the signed sentence.
|
|
271
|
+
* @param {Claim['room']} room
|
|
272
|
+
*/
|
|
273
|
+
export function monthlyRefusalText(room) {
|
|
274
|
+
const held = room.heldUsd > 0 ? `, $${room.heldUsd.toFixed(2)} held by ${room.heldRuns > 1 ? 'runs' : 'a run'} in progress` : '';
|
|
275
|
+
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}`;
|
|
276
|
+
}
|