fwdloop 0.12.0 → 0.14.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 +155 -27
- package/package.json +2 -2
- package/src/ask.js +3 -0
- package/src/authoring.js +135 -16
- package/src/books.js +23 -2
- package/src/canrun.js +106 -0
- package/src/catalogue.json +2 -2
- package/src/checked.js +50 -0
- package/src/closers.js +112 -91
- package/src/config.js +2 -1
- package/src/declaration.js +175 -3
- package/src/drafter.js +148 -10
- package/src/draftspend.js +70 -0
- package/src/flow.js +43 -0
- package/src/keysfile.js +4 -2
- package/src/liveness.js +1 -1
- package/src/model-step.js +31 -5
- package/src/monthly.js +195 -28
- package/src/panel/author.js +638 -0
- package/src/panel/authorcard.js +340 -0
- package/src/panel/authorflows.js +317 -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 +318 -99
- package/src/panel/index.html +2000 -330
- package/src/panel/resume.js +6 -8
- package/src/panel/server.js +122 -119
- package/src/panel/settings.js +8 -6
- package/src/panel/spawn.js +77 -0
- package/src/provider.js +12 -17
- package/src/runner.js +707 -104
- package/src/runvalues.js +178 -0
- package/src/send.js +10 -3
- package/src/setup.js +127 -0
- package/types/authoring.d.ts +56 -2
- package/types/books.d.ts +14 -2
- package/types/canrun.d.ts +64 -0
- package/types/checked.d.ts +23 -0
- package/types/closers.d.ts +47 -28
- package/types/config.d.ts +1 -0
- package/types/declaration.d.ts +23 -1
- package/types/drafter.d.ts +151 -2
- package/types/draftspend.d.ts +21 -0
- package/types/flow.d.ts +23 -0
- package/types/liveness.d.ts +2 -2
- package/types/model-step.d.ts +4 -7
- package/types/monthly.d.ts +46 -1
- package/types/panel/author.d.ts +316 -0
- package/types/panel/authorcard.d.ts +142 -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 +105 -63
- package/types/panel/server.d.ts +11 -33
- package/types/panel/spawn.d.ts +30 -0
- package/types/provider.d.ts +6 -9
- package/types/runner.d.ts +129 -6
- package/types/runvalues.d.ts +97 -0
- package/types/send.d.ts +5 -1
- package/types/setup.d.ts +77 -0
package/src/keysfile.js
CHANGED
|
@@ -145,8 +145,10 @@ export function loadKeysEnv(opts = {}) {
|
|
|
145
145
|
const parsed = parseKeysText(readFileSync(fd, 'utf8'));
|
|
146
146
|
/** @type {Record<string,string|undefined>} */
|
|
147
147
|
const env = { ...base };
|
|
148
|
-
|
|
149
|
-
|
|
148
|
+
// C4 (amendment 16): only the known key names reach the env (and so a child). Any other name in the file is listed in `names`
|
|
149
|
+
// for Settings but its value stays here — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
|
|
150
|
+
for (const name of KEY_NAMES) {
|
|
151
|
+
if (!env[name] && Object.hasOwn(parsed, name)) env[name] = parsed[name];
|
|
150
152
|
}
|
|
151
153
|
return {
|
|
152
154
|
ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
|
package/src/liveness.js
CHANGED
|
@@ -75,7 +75,7 @@ function hasProc() {
|
|
|
75
75
|
* The one writer call: this process records itself in the run dir's
|
|
76
76
|
* `pids.jsonl`, before its first step.
|
|
77
77
|
* @param {string} runDir
|
|
78
|
-
* @param {'run'|'resume'} leg
|
|
78
|
+
* @param {'run'|'resume'|'continue'} leg
|
|
79
79
|
* @param {string} at ISO timestamp from the run's own clock
|
|
80
80
|
*/
|
|
81
81
|
export function recordPid(runDir, leg, at) {
|
package/src/model-step.js
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
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
29
|
import { ConfigError } from './config.js';
|
|
30
30
|
|
|
@@ -103,10 +103,10 @@ const SOFTGREEN_SCHEMA = Object.freeze({
|
|
|
103
103
|
type: 'object',
|
|
104
104
|
properties: {
|
|
105
105
|
text: { type: 'string' },
|
|
106
|
-
lines: { type: 'array', items: { type: 'string' } },
|
|
107
106
|
...DONE_PROPS,
|
|
108
107
|
},
|
|
109
108
|
required: ['text', 'done'],
|
|
109
|
+
additionalProperties: false,
|
|
110
110
|
});
|
|
111
111
|
|
|
112
112
|
// hitl/read-style steps: the documented common shapes are {text} or
|
|
@@ -215,6 +215,8 @@ function addToolCounts(cumulative, byTool, grantedNames) {
|
|
|
215
215
|
// clean row would just be noise).
|
|
216
216
|
function toolFields(cumulative) {
|
|
217
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,
|
|
218
220
|
tools: cumulative.tools,
|
|
219
221
|
// Gate refusals this attempt — always present (empty array when none) so
|
|
220
222
|
// absence can never be confused with "none".
|
|
@@ -223,6 +225,15 @@ function toolFields(cumulative) {
|
|
|
223
225
|
};
|
|
224
226
|
}
|
|
225
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
|
+
|
|
226
237
|
/**
|
|
227
238
|
* @param {object} opts
|
|
228
239
|
* @param {string} [opts.slot] - a `src/provider.js` PROVIDER_SLOTS name; required when `provider` isn't injected.
|
|
@@ -232,14 +243,17 @@ function toolFields(cumulative) {
|
|
|
232
243
|
* @param {{in:number,out:number}} [opts.rates]
|
|
233
244
|
* @param {string} [opts.modelId]
|
|
234
245
|
* @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
|
|
235
|
-
* @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}) => Promise<any>}
|
|
246
|
+
* @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
|
|
236
247
|
*/
|
|
237
248
|
export function makeLiveModelStep({
|
|
238
249
|
slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
|
|
239
250
|
}) {
|
|
240
251
|
const live = injectedProvider == null;
|
|
241
252
|
|
|
242
|
-
|
|
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 = {}) {
|
|
243
257
|
let provider = injectedProvider;
|
|
244
258
|
let rates = injectedRates;
|
|
245
259
|
let modelId = injectedModelId;
|
|
@@ -323,7 +337,11 @@ export function makeLiveModelStep({
|
|
|
323
337
|
};
|
|
324
338
|
const tools = [...primitiveTools, emitTool];
|
|
325
339
|
const roundMeterings = [];
|
|
326
|
-
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 });
|
|
327
345
|
|
|
328
346
|
const startedAt = Date.now();
|
|
329
347
|
let result;
|
|
@@ -389,6 +407,10 @@ export function makeLiveModelStep({
|
|
|
389
407
|
}
|
|
390
408
|
|
|
391
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);
|
|
392
414
|
const metered = sumMeterings(roundMeterings);
|
|
393
415
|
cumulative = addMeter(cumulative, metered);
|
|
394
416
|
cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
|
|
@@ -406,6 +428,10 @@ export function makeLiveModelStep({
|
|
|
406
428
|
|
|
407
429
|
const modelMatch = classifyModelId(modelId, metered.model);
|
|
408
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
|
+
|
|
409
435
|
if (result.stopReason === 'max_tokens') {
|
|
410
436
|
// Rule 4: deterministic (the step needs a smaller output or a
|
|
411
437
|
// bigger cap), never a transient fault a retry could fix.
|
package/src/monthly.js
CHANGED
|
@@ -4,8 +4,12 @@
|
|
|
4
4
|
// ONE record: `<configHome>/runs.jsonl`, append-only, mode 0600, one row per hold and per terminal note.
|
|
5
5
|
// hold: { kind:'hold', holdId, what:'run'|'resume'|'draft', flow, runId, runDir, pid, procStart, holdUsd, spentAtHold, at }
|
|
6
6
|
// terminal: { kind:'settled'|'released'|'refused', holdId, at, why [, alsoRunDirs] }
|
|
7
|
-
//
|
|
8
|
-
//
|
|
7
|
+
// named: { kind:'named', holdId, at, alsoRunDirs } — a hold's process starts spending into one more run dir (a rerun's new run)
|
|
8
|
+
// rolled: { kind:'rolled', at, seen, dirs } — the reduced spend rows of dirs whose holds all ended on their own (never "process
|
|
9
|
+
// gone"), so a read opens one record, not one file per run; `seen` = how many rows the record had when it was read
|
|
10
|
+
// Rows are only ever appended. Month spend is read from each named run/draft dir's OWN `spend.jsonl` (so the total is the same
|
|
11
|
+
// whichever `--root` a run used); only a `rolled` row stands in for a dir's file (its copy of that dir's spend, kept if the dir is
|
|
12
|
+
// deleted). hold, terminal and named rows carry no money.
|
|
9
13
|
//
|
|
10
14
|
// The claim (bareloop `claimRun`): the door APPENDS its hold FIRST, then reads the file; only live,
|
|
11
15
|
// unsettled holds that come BEFORE its own row count against it, so whoever is first holds. A hold whose
|
|
@@ -26,7 +30,8 @@ import { randomUUID } from 'node:crypto';
|
|
|
26
30
|
|
|
27
31
|
import { readConfig, configHome, ConfigError } from './config.js';
|
|
28
32
|
import { isFwdloopAlive, procStartOf } from './liveness.js';
|
|
29
|
-
import {
|
|
33
|
+
import { spendRowCost } from './provider.js';
|
|
34
|
+
import { readDirSpendRows } from './draftspend.js';
|
|
30
35
|
|
|
31
36
|
export { ConfigError };
|
|
32
37
|
|
|
@@ -60,7 +65,7 @@ export function readRuns(home) {
|
|
|
60
65
|
try { text = readFileSync(runsPath(home), 'utf8'); } catch { return []; }
|
|
61
66
|
const rows = [];
|
|
62
67
|
for (const line of text.split('\n')) {
|
|
63
|
-
if (
|
|
68
|
+
if (line === '') continue; // a blank or torn line is skipped by the parse below
|
|
64
69
|
try { const r = JSON.parse(line); if (r && typeof r === 'object') rows.push(r); } catch { /* skip */ }
|
|
65
70
|
}
|
|
66
71
|
return rows;
|
|
@@ -74,21 +79,88 @@ const sameMonth = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth()
|
|
|
74
79
|
/** Every run/draft dir the record names (deduped by realpath), including dirs a settle note adds. */
|
|
75
80
|
function namedDirs(rows) {
|
|
76
81
|
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
|
-
}
|
|
82
|
+
for (const r of rows) for (const d of dirsNamedBy(r)) dirs.add(d);
|
|
81
83
|
return [...dirs];
|
|
82
84
|
}
|
|
83
85
|
|
|
84
|
-
/** One dir's total spend (every row, `spendRowCost
|
|
86
|
+
/** One dir's total spend (every row, `spendRowCost`; a draft dir's live record until its final row exists — src/draftspend.js). */
|
|
85
87
|
function dirSpend(dir) {
|
|
86
|
-
return
|
|
88
|
+
return readDirSpendRows(dir).reduce((n, r) => n + spendRowCost(r).usd, 0);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One spend row reduced to exactly what `spendSummary` reads of it (I1, amendment 16): `u` cost (spendRowCost), `c` complete, `t` tokens,
|
|
93
|
+
* `w` wall ms or null, `p` the provider key, `a` the row's `at` as written (absent when it had none). Nothing else of a row is used.
|
|
94
|
+
*/
|
|
95
|
+
function reduceRow(row) {
|
|
96
|
+
const { usd, complete } = spendRowCost(row);
|
|
97
|
+
return {
|
|
98
|
+
u: usd,
|
|
99
|
+
c: complete,
|
|
100
|
+
t: tokensOf(row.tokens),
|
|
101
|
+
w: Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null,
|
|
102
|
+
p: typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED,
|
|
103
|
+
...(row.at === undefined ? {} : { a: row.at }),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const diskRows = (dir) => readDirSpendRows(dir).map(reduceRow);
|
|
108
|
+
|
|
109
|
+
/** The run dirs a row names: a hold's `runDir`, and any `alsoRunDirs` (a settle or named note). */
|
|
110
|
+
function dirsNamedBy(r) {
|
|
111
|
+
const out = [];
|
|
112
|
+
if (r.kind === 'hold' && typeof r.runDir === 'string') out.push(r.runDir);
|
|
113
|
+
if (Array.isArray(r.alsoRunDirs)) for (const d of r.alsoRunDirs) if (typeof d === 'string') out.push(d);
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The dirs of every hold the checker settled as "process gone" (amendment 17 3A): that run may have been misjudged and still spend,
|
|
119
|
+
* so such a dir is never rolled (rollSettled) and an older rolled row for it is never used (rolledEntries, amendment 19 1).
|
|
120
|
+
* @param {any[]} rows
|
|
121
|
+
* @returns {Set<string>}
|
|
122
|
+
*/
|
|
123
|
+
function goneDirs(rows) {
|
|
124
|
+
const goneHolds = new Set(rows.filter((r) => r.kind === 'settled' && r.why === 'process gone').map((r) => r.holdId));
|
|
125
|
+
const out = new Set();
|
|
126
|
+
for (const r of rows) {
|
|
127
|
+
if (r.kind !== 'rolled' && typeof r.holdId === 'string' && goneHolds.has(r.holdId)) for (const d of dirsNamedBy(r)) out.add(d);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The rolled spend of settled dirs (I1, amendment 16). A `rolled` row in runs.jsonl carries, for dirs whose every hold had ended,
|
|
134
|
+
* their reduced spend rows, and `seen` = how many rows the record had when the snapshot was read. An entry is used only if NO row
|
|
135
|
+
* at index >= `seen` names that dir (a resume or a rerun names it again, so its live spend is read from the dir instead). Anything
|
|
136
|
+
* else — no entry, a newer naming row — reads the dir as before, so a total can never differ from reading every dir.
|
|
137
|
+
* @param {any[]} rows
|
|
138
|
+
* @returns {Map<string, ReturnType<typeof reduceRow>[]>}
|
|
139
|
+
*/
|
|
140
|
+
function rolledEntries(rows) {
|
|
141
|
+
/** @type {Map<string, {seen: number, rows: any[]}>} */
|
|
142
|
+
const best = new Map();
|
|
143
|
+
/** @type {Map<string, number>} */
|
|
144
|
+
const lastNamed = new Map();
|
|
145
|
+
rows.forEach((r, i) => {
|
|
146
|
+
for (const d of dirsNamedBy(r)) lastNamed.set(d, i);
|
|
147
|
+
if (r.kind === 'rolled' && Number.isInteger(r.seen) && r.dirs && typeof r.dirs === 'object') {
|
|
148
|
+
for (const [d, rs] of Object.entries(r.dirs)) {
|
|
149
|
+
const prev = best.get(d);
|
|
150
|
+
if (Array.isArray(rs) && !(prev && prev.seen > r.seen)) best.set(d, { seen: r.seen, rows: rs });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
const gone = goneDirs(rows);
|
|
155
|
+
const out = new Map();
|
|
156
|
+
for (const [d, e] of best) if (!gone.has(d) && (lastNamed.get(d) ?? -1) < e.seen) out.set(d, e.rows);
|
|
157
|
+
return out;
|
|
87
158
|
}
|
|
88
159
|
|
|
89
160
|
/**
|
|
90
161
|
* The Money tab's figures (piece 4 reads this) and the check's month total.
|
|
91
|
-
*
|
|
162
|
+
* `rows` (a caller that has just read the record, like the claim) saves a second parse of the same file.
|
|
163
|
+
* @param {{ home?: string, now?: () => number, rows?: any[] }} [opts]
|
|
92
164
|
*/
|
|
93
165
|
export function spendSummary(opts = {}) {
|
|
94
166
|
const nowDate = new Date((opts.now ?? Date.now)());
|
|
@@ -106,17 +178,18 @@ export function spendSummary(opts = {}) {
|
|
|
106
178
|
if (wall === null) b.modelMsAtLeast = true;
|
|
107
179
|
else b.modelMs = (b.modelMs ?? 0) + wall;
|
|
108
180
|
};
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const
|
|
114
|
-
|
|
181
|
+
const record = opts.rows ?? readRuns(opts.home);
|
|
182
|
+
const rolled = rolledEntries(record);
|
|
183
|
+
for (const dir of namedDirs(record)) {
|
|
184
|
+
for (const row of rolled.get(dir) ?? diskRows(dir)) {
|
|
185
|
+
const {
|
|
186
|
+
u: usd, c: complete, t: tokens, w: wall, p: key,
|
|
187
|
+
} = row;
|
|
115
188
|
const p = (byProvider[key] ??= { label: key, month: newBucket(), total: newBucket() });
|
|
116
189
|
add(total, usd, complete, tokens, wall);
|
|
117
190
|
add(p.total, usd, complete, tokens, wall);
|
|
118
|
-
if (row.
|
|
119
|
-
const at = new Date(row.
|
|
191
|
+
if (row.a === undefined || row.a === null) { undatedRows += 1; continue; }
|
|
192
|
+
const at = new Date(row.a);
|
|
120
193
|
if (Number.isNaN(at.getTime())) { month.atLeast = true; p.month.atLeast = true; continue; } // could be this month: unknown, never dropped
|
|
121
194
|
if (sameMonth(at, nowDate)) {
|
|
122
195
|
add(month, usd, complete, tokens, wall);
|
|
@@ -140,16 +213,17 @@ export function spendSummary(opts = {}) {
|
|
|
140
213
|
|
|
141
214
|
/**
|
|
142
215
|
* 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.
|
|
216
|
+
* `null` from the liveness check ("cannot tell") never settles: it holds. `settle: false` (the page's read-only note) counts the same
|
|
217
|
+
* but writes nothing.
|
|
144
218
|
*/
|
|
145
|
-
function liveHeldBefore(rows, idx, home, nowIso) {
|
|
219
|
+
function liveHeldBefore(rows, idx, home, nowIso, settle = true) {
|
|
146
220
|
const ended = new Set(rows.filter((r) => r.kind === 'settled' || r.kind === 'released' || r.kind === 'refused').map((r) => r.holdId));
|
|
147
221
|
let heldUsd = 0;
|
|
148
222
|
let heldRuns = 0;
|
|
149
223
|
for (const r of rows.slice(0, idx)) {
|
|
150
224
|
if (r.kind !== 'hold' || ended.has(r.holdId) || !Number.isFinite(r.holdUsd)) continue;
|
|
151
225
|
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' });
|
|
226
|
+
if (settle) appendRow(home, { kind: 'settled', holdId: r.holdId, at: nowIso, why: 'process gone' });
|
|
153
227
|
continue;
|
|
154
228
|
}
|
|
155
229
|
const spentSince = Math.max(0, dirSpend(r.runDir) - (Number.isFinite(r.spentAtHold) ? r.spentAtHold : 0));
|
|
@@ -159,6 +233,53 @@ function liveHeldBefore(rows, idx, home, nowIso) {
|
|
|
159
233
|
return { heldUsd, heldRuns };
|
|
160
234
|
}
|
|
161
235
|
|
|
236
|
+
/**
|
|
237
|
+
* The ONE computation of "does a hold of `holdUsd` fit this month": the limit minus this month's counted spend minus what live
|
|
238
|
+
* runs before `idx` still hold, in whole cents. `claimHold` (the door) and `checkMonthlyRoom` (the page's note) both call it, so the
|
|
239
|
+
* note and the refusal are never two opinions.
|
|
240
|
+
* @param {{ limit: number, holdUsd: number, rows: any[], idx: number, home?: string, now: () => number, nowIso: string, settle?: boolean }} a
|
|
241
|
+
*/
|
|
242
|
+
function roomFor({ limit, holdUsd, rows, idx, home, now, nowIso, settle = true }) {
|
|
243
|
+
const { heldUsd, heldRuns } = liveHeldBefore(rows, idx, home, nowIso, settle);
|
|
244
|
+
const month = spendSummary({ home, now, rows }).month;
|
|
245
|
+
const leftCents = Math.max(0, Math.floor((limit - month.usd - heldUsd) * 100 + 1e-6));
|
|
246
|
+
const needCents = Math.ceil(holdUsd * 100 - 1e-6); // a non-finite hold never fits — never read as $0
|
|
247
|
+
return {
|
|
248
|
+
ok: needCents <= leftCents, leftUsd: leftCents / 100, heldUsd, heldRuns, atLeast: month.atLeast,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// borrowed-from: bareloop src/monthly.js@c1d87ce (`checkMonthlyRoom`, shape only: fwdloop's holds and rows differ)
|
|
253
|
+
/**
|
|
254
|
+
* Read-only: would a run holding `capUsd` fit this month? The same numbers `claimHold` decides on, but no hold row and no settle is
|
|
255
|
+
* written — it is what the panel's note under Cap shows. Throws ConfigError when config.json is broken.
|
|
256
|
+
* @param {{ capUsd: number, home?: string, now?: () => number }} a
|
|
257
|
+
* @returns {Claim}
|
|
258
|
+
*/
|
|
259
|
+
export function checkMonthlyRoom({ capUsd, home, now = Date.now }) {
|
|
260
|
+
const limit = readConfig({ home }).monthlyLimitUsd ?? null;
|
|
261
|
+
const room = { limitUsd: limit, leftUsd: null, heldUsd: 0, heldRuns: 0, needUsd: capUsd, atLeast: false };
|
|
262
|
+
if (limit === null) return { ok: true, holdId: '', room };
|
|
263
|
+
const rows = readRuns(home);
|
|
264
|
+
const { ok, ...found } = roomFor({ limit, holdUsd: capUsd, rows, idx: rows.length, home, now, nowIso: new Date(now()).toISOString(), settle: false });
|
|
265
|
+
Object.assign(room, found);
|
|
266
|
+
return { ok, holdId: '', room };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* 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
|
|
271
|
+
* 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.
|
|
272
|
+
* @param {Claim} claim
|
|
273
|
+
* @returns {{ text: string, red: boolean }}
|
|
274
|
+
*/
|
|
275
|
+
export function monthlyNote(claim) {
|
|
276
|
+
const { room } = claim;
|
|
277
|
+
if (room.limitUsd === null || room.leftUsd === null) return { text: '', red: false };
|
|
278
|
+
const left = `$${room.leftUsd.toFixed(2)}`;
|
|
279
|
+
if (!claim.ok) return { text: `needs $${(Math.ceil(room.needUsd * 100 - 1e-6) / 100).toFixed(2)} (${left} left monthly)`, red: true };
|
|
280
|
+
return { text: `${room.atLeast ? 'at most ' : ''}${left} left monthly`, red: false };
|
|
281
|
+
}
|
|
282
|
+
|
|
162
283
|
/**
|
|
163
284
|
* @typedef {object} Claim
|
|
164
285
|
* @property {boolean} ok the hold fits (or no limit is set)
|
|
@@ -192,12 +313,8 @@ export function claimHold({
|
|
|
192
313
|
if (limit === null) return { ok: true, holdId, room };
|
|
193
314
|
const rows = readRuns(home);
|
|
194
315
|
const idx = rows.findIndex((r) => r.kind === 'hold' && r.holdId === holdId);
|
|
195
|
-
const {
|
|
196
|
-
|
|
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 });
|
|
316
|
+
const { ok, ...found } = roomFor({ limit, holdUsd, rows, idx: idx < 0 ? rows.length : idx, home, now, nowIso });
|
|
317
|
+
Object.assign(room, found);
|
|
201
318
|
if (!ok) {
|
|
202
319
|
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
320
|
return { ok: false, holdId, room };
|
|
@@ -205,6 +322,55 @@ export function claimHold({
|
|
|
205
322
|
return { ok: true, holdId, room };
|
|
206
323
|
}
|
|
207
324
|
|
|
325
|
+
/**
|
|
326
|
+
* Amendment 16 C2: a hold's process starts spending into one more run dir (a rerun's new run): name it NOW, so a process killed hard
|
|
327
|
+
* still has that dir's spend counted. Append-only; `namedDirs` dedupes, so the settle note naming it again never counts it twice.
|
|
328
|
+
* Never throws (a failed note is closed by the settle note's `alsoRunDirs` on a normal exit).
|
|
329
|
+
* @param {{ holdId: string|null, runDir: string, home?: string, now?: () => number }} a
|
|
330
|
+
*/
|
|
331
|
+
export function nameRunDir({
|
|
332
|
+
holdId, runDir, home, now = Date.now,
|
|
333
|
+
}) {
|
|
334
|
+
if (!holdId) return;
|
|
335
|
+
try {
|
|
336
|
+
appendRow(home, {
|
|
337
|
+
kind: 'named', holdId, at: new Date(now()).toISOString(), alsoRunDirs: [realpathLoose(runDir)],
|
|
338
|
+
});
|
|
339
|
+
} catch { /* see above */ }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** How many dirs one `rolled` row carries (keeps each appended line small enough to be one whole write). */
|
|
343
|
+
const ROLL_CHUNK = 200;
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* I1 (amendment 16): fold the spend of every run/draft dir whose holds have ALL ended (settled, released or refused) into `rolled`
|
|
347
|
+
* rows, so the next month figure or Money load reads one record instead of one file per run. Append-only; a dir already rolled and not
|
|
348
|
+
* named since is left alone. Reads the dirs it folds exactly as `spendSummary` would, so no total changes. Never throws.
|
|
349
|
+
* @param {{ home?: string, now?: () => number }} [a]
|
|
350
|
+
*/
|
|
351
|
+
export function rollSettled({ home, now = Date.now } = {}) {
|
|
352
|
+
try {
|
|
353
|
+
const rows = readRuns(home);
|
|
354
|
+
const seen = rows.length;
|
|
355
|
+
const ended = new Set(rows.filter((r) => r.kind === 'settled' || r.kind === 'released' || r.kind === 'refused').map((r) => r.holdId));
|
|
356
|
+
/** @type {Set<string>} */
|
|
357
|
+
const open = new Set();
|
|
358
|
+
for (const r of rows) {
|
|
359
|
+
if (r.kind === 'rolled') continue;
|
|
360
|
+
const named = dirsNamedBy(r);
|
|
361
|
+
const unended = typeof r.holdId !== 'string' || !ended.has(r.holdId);
|
|
362
|
+
if (unended) for (const d of named) open.add(d);
|
|
363
|
+
}
|
|
364
|
+
for (const d of goneDirs(rows)) open.add(d);
|
|
365
|
+
const have = rolledEntries(rows);
|
|
366
|
+
const todo = namedDirs(rows).filter((d) => !open.has(d) && !have.has(d));
|
|
367
|
+
for (let i = 0; i < todo.length; i += ROLL_CHUNK) {
|
|
368
|
+
const dirs = Object.fromEntries(todo.slice(i, i + ROLL_CHUNK).map((d) => [d, diskRows(d)]));
|
|
369
|
+
appendRow(home, { kind: 'rolled', at: new Date(now()).toISOString(), seen, dirs });
|
|
370
|
+
}
|
|
371
|
+
} catch { /* a failed roll only means the next read opens the dirs, as before */ }
|
|
372
|
+
}
|
|
373
|
+
|
|
208
374
|
/**
|
|
209
375
|
* The run's own process ends or parks: give the hold back. Never throws (a failed settle is closed by the
|
|
210
376
|
* next check as "process gone"). `alsoRunDirs` names dirs this process also spent into (a rerun's new run).
|
|
@@ -219,6 +385,7 @@ export function settleHold({
|
|
|
219
385
|
kind: 'settled', holdId, at: new Date(now()).toISOString(), why, ...(alsoRunDirs?.length ? { alsoRunDirs: alsoRunDirs.map(realpathLoose) } : {}),
|
|
220
386
|
});
|
|
221
387
|
} catch { /* see above */ }
|
|
388
|
+
rollSettled({ home, now });
|
|
222
389
|
}
|
|
223
390
|
|
|
224
391
|
/**
|