fwdloop 0.12.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 +136 -21
- package/package.json +1 -1
- package/src/ask.js +3 -0
- package/src/authoring.js +101 -13
- package/src/books.js +23 -2
- package/src/canrun.js +36 -0
- package/src/config.js +2 -1
- package/src/declaration.js +72 -2
- package/src/drafter.js +41 -3
- package/src/draftspend.js +70 -0
- package/src/flow.js +43 -0
- package/src/liveness.js +1 -1
- package/src/model-step.js +30 -4
- package/src/monthly.js +58 -13
- 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 +1745 -127
- package/src/panel/resume.js +6 -8
- package/src/panel/server.js +119 -119
- package/src/panel/settings.js +7 -5
- package/src/panel/spawn.js +77 -0
- package/src/provider.js +12 -17
- 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 +1 -0
- package/types/declaration.d.ts +9 -1
- package/types/drafter.d.ts +15 -1
- 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 +3 -1
- package/types/monthly.d.ts +21 -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/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 +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/declaration.js
CHANGED
|
@@ -241,6 +241,73 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
|
|
|
241
241
|
return { ok: true, class: resolved.class, line };
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
+
/** The first "<n> words" in a guardrail ("3 sections, all under 600 words" -> 600), or null. */
|
|
245
|
+
function guardrailWordLimit(guardrail) {
|
|
246
|
+
const m = typeof guardrail === 'string' ? /(\d+)\s*words?\b/i.exec(guardrail) : null;
|
|
247
|
+
return m ? Number(m[1]) : null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const NUMBER_WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 };
|
|
251
|
+
/** M4e amendment 7 item 1: the first "<N> sections" in a guardrail (N digits, or the words one..ten), or null. */
|
|
252
|
+
function guardrailSectionCount(guardrail) {
|
|
253
|
+
const m = typeof guardrail === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?sections?\b/i.exec(guardrail) : null;
|
|
254
|
+
if (!m) return null;
|
|
255
|
+
return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
|
|
256
|
+
}
|
|
257
|
+
const MAX_SECTION_NAME_WORDS = 8;
|
|
258
|
+
const MAX_SECTION_SHARE_OF_LINE = 0.6;
|
|
259
|
+
const wordCount = (t) => t.trim().split(/\s+/).filter(Boolean).length;
|
|
260
|
+
|
|
261
|
+
/** M4e amendment 6 item 1 (+ amendment 7 item 1): a step's check cannot fight its own job line. Sections must be found in the line's words
|
|
262
|
+
* (case-insensitive substring of the goal, first occurrence) and in the line's order; `maxWords` must equal the line's
|
|
263
|
+
* own guardrail limit when that guardrail states one. A shape key a note may still change (mustCarry, linesPerInvoice)
|
|
264
|
+
* is untouched. Pushes reds naming the step and both orders/values. */
|
|
265
|
+
export function checkShapeFitsJobLine(step, i, lines, reds) {
|
|
266
|
+
const { shape } = step.close;
|
|
267
|
+
const label = `steps[${i}]`;
|
|
268
|
+
const line = Number.isInteger(step.fromLine) ? lines.find((l) => l.n === step.fromLine) : undefined;
|
|
269
|
+
if (Array.isArray(shape.sections) && shape.sections.every((n) => typeof n === 'string' && n.length > 0) && typeof step.goal === 'string') {
|
|
270
|
+
const goal = step.goal.toLowerCase().replace(/\s+/g, ' ');
|
|
271
|
+
const found = [];
|
|
272
|
+
for (const name of shape.sections) {
|
|
273
|
+
const at = goal.indexOf(name.toLowerCase().replace(/\s+/g, ' ').trim());
|
|
274
|
+
if (at < 0) {
|
|
275
|
+
reds.push(`declaration: ${label}.close.shape.sections names "${name}", which is not in the job line's words — change the job line on the card to change what it names`);
|
|
276
|
+
} else found.push({ name, at });
|
|
277
|
+
}
|
|
278
|
+
if (found.length === shape.sections.length) {
|
|
279
|
+
const jobOrder = [...found].sort((a, b) => a.at - b.at).map((f) => f.name);
|
|
280
|
+
if (jobOrder.some((n, k) => n !== shape.sections[k])) {
|
|
281
|
+
reds.push(`declaration: ${label} the job line says ${jobOrder.join(', then ')}; the check says ${shape.sections.join(', then ')} — change the job line on the card to change the order`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
const wantSections = guardrailSectionCount(line?.guardrail);
|
|
286
|
+
if (Array.isArray(shape.sections)) {
|
|
287
|
+
if (wantSections !== null && shape.sections.length !== wantSections) {
|
|
288
|
+
reds.push(`declaration: ${label} the guardrail says ${wantSections} sections; the check has ${shape.sections.length}`);
|
|
289
|
+
}
|
|
290
|
+
const goalWords = typeof step.goal === 'string' ? wordCount(step.goal) : 0;
|
|
291
|
+
const names = shape.sections.filter((n) => typeof n === 'string' && n.trim().length > 0);
|
|
292
|
+
for (const name of names) {
|
|
293
|
+
const n = wordCount(name);
|
|
294
|
+
if (n > MAX_SECTION_NAME_WORDS) {
|
|
295
|
+
reds.push(`declaration: ${label}.close.shape.sections names "${name}" (${n} words) — a section name is a short phrase from the job line, at most ${MAX_SECTION_NAME_WORDS} words`);
|
|
296
|
+
} else if (goalWords > 0 && n / goalWords >= MAX_SECTION_SHARE_OF_LINE) {
|
|
297
|
+
reds.push(`declaration: ${label}.close.shape.sections names "${name}", which is the job line or most of it — a section name is a short phrase from the line`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const norm = names.map((n) => n.toLowerCase().replace(/\s+/g, ' ').trim());
|
|
301
|
+
norm.forEach((a, x) => norm.forEach((b, y) => {
|
|
302
|
+
if (x !== y && a.includes(b)) reds.push(`declaration: ${label}.close.shape.sections "${names[x]}" contains "${names[y]}" — one section name may not contain another`);
|
|
303
|
+
}));
|
|
304
|
+
}
|
|
305
|
+
const limit = guardrailWordLimit(line?.guardrail);
|
|
306
|
+
if (limit !== null && shape.maxWords !== undefined && shape.maxWords !== limit) {
|
|
307
|
+
reds.push(`declaration: ${label} the job line's guardrail says ${limit} words; the check says ${shape.maxWords} — change the guardrail on the card to change the limit`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
244
311
|
/**
|
|
245
312
|
* Validate a drafter declaration against the M1 closed schema. `arbiter`
|
|
246
313
|
* and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
|
|
@@ -253,11 +320,13 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
|
|
|
253
320
|
* by name, even if the catalogue lists it. Omitted = no wired check (existing callers).
|
|
254
321
|
* `verbatimGoals` (optional boolean; M6a amendment 1): when true, a step naming a signed line must carry that line's
|
|
255
322
|
* text as its goal, exactly. Off by default so already-signed flows keep running; draft and sign turn it on.
|
|
256
|
-
*
|
|
323
|
+
* `fitJobLine` (optional boolean; M4e amendment 6): when true, a `close.shape` whose sections/maxWords fight the step's job
|
|
324
|
+
* line or its guardrail is a red. Draft, change and sign turn it on; readFlow does not (signed flows keep running).
|
|
325
|
+
* @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean }} [context]
|
|
257
326
|
* @returns {ValidateDeclarationResult}
|
|
258
327
|
*/
|
|
259
328
|
export function validateDeclaration(declaration, context = {}) {
|
|
260
|
-
const { arbiter, lines, catalogue, wired, verbatimGoals } = context;
|
|
329
|
+
const { arbiter, lines, catalogue, wired, verbatimGoals, fitJobLine } = context;
|
|
261
330
|
const reds = [];
|
|
262
331
|
|
|
263
332
|
if (!isPlainObject(declaration)) {
|
|
@@ -514,6 +583,7 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
514
583
|
reds.push(`declaration: ${label}.close.shape must be an object`);
|
|
515
584
|
} else {
|
|
516
585
|
checkShapeKeys(step.close.shape, `declaration.${label}.close.shape`, reds);
|
|
586
|
+
if (fitJobLine === true) checkShapeFitsJobLine(step, i, safeLines, reds);
|
|
517
587
|
}
|
|
518
588
|
}
|
|
519
589
|
}
|
package/src/drafter.js
CHANGED
|
@@ -166,6 +166,33 @@ function reviseMessage(reds) {
|
|
|
166
166
|
+ `${TOOL} again with the complete corrected declaration:\n${reds.map((r) => `- ${r}`).join('\n')}`;
|
|
167
167
|
}
|
|
168
168
|
|
|
169
|
+
/**
|
|
170
|
+
* M4e amendment 3 item 3 (revise the plan): the first round's user text when the human asked for a change. The model sees the
|
|
171
|
+
* current plan (its own fields only: no machine-set `goal`, no `inputFacts`) and the note; the rules above still hold, and the
|
|
172
|
+
* validator below is the ONE check that refuses a plan that touches what only the card may set.
|
|
173
|
+
*/
|
|
174
|
+
export function reviseOpening(plan, note) {
|
|
175
|
+
const own = {
|
|
176
|
+
steps: (plan.steps ?? []).map(({ goal, ...rest }) => rest), // eslint-disable-line no-unused-vars
|
|
177
|
+
guardrailClasses: plan.guardrailClasses ?? {},
|
|
178
|
+
unjudgeable: plan.unjudgeable ?? {},
|
|
179
|
+
refused: plan.refused ?? [],
|
|
180
|
+
};
|
|
181
|
+
return [
|
|
182
|
+
`The human reviewed the plan below and asks for a change to the plan. Call ${TOOL} with the complete revised plan.`,
|
|
183
|
+
'',
|
|
184
|
+
'Current plan:',
|
|
185
|
+
JSON.stringify(own),
|
|
186
|
+
'',
|
|
187
|
+
'The human\'s note:',
|
|
188
|
+
note,
|
|
189
|
+
'',
|
|
190
|
+
'The note may change HOW steps are done (their primitives, reads, close checks). It can never change the numbered job lines, '
|
|
191
|
+
+ 'the cap, the destination, the signed asks and their waits, or the inputs: those come only from the card, so keep every '
|
|
192
|
+
+ 'line served by its step and every signed ask a pure stop exactly as the rules above say.',
|
|
193
|
+
].join('\n');
|
|
194
|
+
}
|
|
195
|
+
|
|
169
196
|
function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
|
|
170
197
|
|
|
171
198
|
// F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
|
|
@@ -176,13 +203,19 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
|
|
|
176
203
|
* the batch); otherwise a live provider is built from `slot` (throws on a bad
|
|
177
204
|
* key — the batch preflights first). `budgetUsd` is this draft's hard cap.
|
|
178
205
|
* `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
|
|
206
|
+
* `onBook` (M4e piece 2a, scope 13): called right BEFORE each provider call (`inFlight: true`, the call counted in
|
|
207
|
+
* `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
|
|
208
|
+
* and a draft killed between rounds still has its paid rounds on disk. It may throw before a call (nothing is
|
|
209
|
+
* spent then and the draft stops); after a call it is the caller's to keep from throwing.
|
|
210
|
+
* `revise` (M4e amendment 3 item 3): `{ plan, note }` — the current green plan and the human's note; the first round then asks for the
|
|
211
|
+
* revised plan. Everything else (the $0 gates, the validator, the budget, the metering) is the same code path as a first draft.
|
|
179
212
|
*
|
|
180
213
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
181
214
|
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
|
|
182
215
|
*/
|
|
183
216
|
export async function draft({
|
|
184
217
|
proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
185
|
-
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
|
|
218
|
+
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, revise,
|
|
186
219
|
}) {
|
|
187
220
|
const fail = (reds, extra = {}) => ({
|
|
188
221
|
ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
|
|
@@ -228,7 +261,7 @@ export async function draft({
|
|
|
228
261
|
let revisions = 0;
|
|
229
262
|
let lastReds = [];
|
|
230
263
|
let lastDecl = null;
|
|
231
|
-
let userText = `Call ${TOOL} now.`;
|
|
264
|
+
let userText = revise ? reviseOpening(revise.plan, revise.note) : `Call ${TOOL} now.`;
|
|
232
265
|
let nextKind = 'first'; // what the round about to run actually is
|
|
233
266
|
let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
|
|
234
267
|
let stop = null;
|
|
@@ -255,6 +288,10 @@ export async function draft({
|
|
|
255
288
|
let result;
|
|
256
289
|
let threw = null;
|
|
257
290
|
calls += 1;
|
|
291
|
+
const book = (inFlight) => onBook?.({
|
|
292
|
+
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
293
|
+
});
|
|
294
|
+
book(true);
|
|
258
295
|
try {
|
|
259
296
|
result = await loop.run(
|
|
260
297
|
[{ role: 'system', content: system }, { role: 'user', content: userText }],
|
|
@@ -265,6 +302,7 @@ export async function draft({
|
|
|
265
302
|
threw = err;
|
|
266
303
|
if (roundEvents.length === 0) unmetered += 1;
|
|
267
304
|
}
|
|
305
|
+
book(false);
|
|
268
306
|
const entry = { round: log.length + 1, kind: nextKind };
|
|
269
307
|
|
|
270
308
|
if (threw) {
|
|
@@ -297,7 +335,7 @@ export async function draft({
|
|
|
297
335
|
declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
|
|
298
336
|
}
|
|
299
337
|
const verdict = validateDeclaration(declaration, {
|
|
300
|
-
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true,
|
|
338
|
+
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
301
339
|
});
|
|
302
340
|
lastDecl = declaration;
|
|
303
341
|
if (verdict.ok) {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/draftspend.js@524a244 (writeDraftSpend: one file per draft folder, rewritten atomically
|
|
2
|
+
// after EVERY metered call; the money readers count it).
|
|
3
|
+
// M4e piece 2a, item 7 (docs/wiki/the-module-ladder.md, "M4e", scope 13): drafting spend that is booked per call.
|
|
4
|
+
//
|
|
5
|
+
// Before this, `draftToDir` booked ONE `spend.jsonl` row after the whole draft returned, so a draft killed
|
|
6
|
+
// mid-way (Abandon, a SIGKILL, a panel host reboot) booked nothing for the rounds already paid for. Now the
|
|
7
|
+
// drafter reports every call (`onBook`, src/drafter.js) and `draftToDir` rewrites `<draft dir>/draft-spend.json`
|
|
8
|
+
// from it: written BEFORE each provider call as "one call in flight" (unknown cost = one ceiling, never $0),
|
|
9
|
+
// rewritten AFTER it with the metered floor.
|
|
10
|
+
//
|
|
11
|
+
// ONE rule for what a draft dir costs (`readDirSpendRows`, the only reader, called by src/monthly.js): the final
|
|
12
|
+
// `spend.jsonl` row, once the draft finished, is the whole truth and SUPERSEDES this file; before that, this file
|
|
13
|
+
// is the dir's one spend row. So a finished draft is counted once, never as both. The run that follows a sign has
|
|
14
|
+
// its own dir and its own books — it never carries this spend (counted once, as scope 13 says).
|
|
15
|
+
//
|
|
16
|
+
// The record is shaped like a spend row, so `spendRowCost` (src/provider.js, the one cost rule) prices it:
|
|
17
|
+
// { kind:'draft-live', provider, model, price, tokens, costUsd (metered floor, null when unpriced), rounds, calls,
|
|
18
|
+
// spendComplete (false while a call is in flight or any call is unmetered/unpriced), inFlight, at, startedAt, updatedAt }
|
|
19
|
+
import { renameSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
|
|
22
|
+
import { readFileInside } from './flow.js';
|
|
23
|
+
import { readSpendRows } from './provider.js';
|
|
24
|
+
|
|
25
|
+
export const DRAFT_SPEND_FILE = 'draft-spend.json';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* (Re)write `<dir>/draft-spend.json` atomically (tmp + rename), so a reader never sees a torn file.
|
|
29
|
+
* @param {string} dir the draft dir
|
|
30
|
+
* @param {Record<string, any>} rec
|
|
31
|
+
*/
|
|
32
|
+
export function writeDraftSpend(dir, rec) {
|
|
33
|
+
const file = join(dir, DRAFT_SPEND_FILE);
|
|
34
|
+
const tmp = `${file}.tmp`;
|
|
35
|
+
writeFileSync(tmp, `${JSON.stringify(rec, null, 2)}\n`, { mode: 0o600 });
|
|
36
|
+
renameSync(tmp, file);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The draft dir's live spend record as a spend row, or null when the file is not there. A file that is there but
|
|
41
|
+
* cannot be read is unknown spend: one unmetered call (priced at the ceiling), never $0 and never skipped.
|
|
42
|
+
* @param {string} dir
|
|
43
|
+
* @returns {Record<string, any>|null}
|
|
44
|
+
*/
|
|
45
|
+
export function readDraftSpend(dir) {
|
|
46
|
+
const r = readFileInside(dir, DRAFT_SPEND_FILE);
|
|
47
|
+
if (!r.ok) return r.missing ? null : unknownRow();
|
|
48
|
+
try {
|
|
49
|
+
const j = JSON.parse(r.text);
|
|
50
|
+
if (!j || typeof j !== 'object' || Array.isArray(j)) return unknownRow();
|
|
51
|
+
return j;
|
|
52
|
+
} catch { return unknownRow(); }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const unknownRow = () => ({
|
|
56
|
+
kind: 'draft-live', model: null, costUsd: null, rounds: 0, calls: 1, spendComplete: false, inFlight: false,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Every spend row of one run/draft dir: its `spend.jsonl` rows; and, only when there are none, the draft dir's
|
|
61
|
+
* `draft-spend.json` record (see the file header: a finished draft's spend.jsonl supersedes it).
|
|
62
|
+
* @param {string} dir
|
|
63
|
+
* @returns {Record<string, any>[]}
|
|
64
|
+
*/
|
|
65
|
+
export function readDirSpendRows(dir) {
|
|
66
|
+
const rows = readSpendRows(join(dir, 'spend.jsonl'));
|
|
67
|
+
if (rows.length > 0) return rows;
|
|
68
|
+
const live = readDraftSpend(dir);
|
|
69
|
+
return live ? [live] : [];
|
|
70
|
+
}
|
package/src/flow.js
CHANGED
|
@@ -36,6 +36,8 @@ import { validateDeclaration } from './declaration.js';
|
|
|
36
36
|
/** The three files a signed flow directory carries. Every place in this
|
|
37
37
|
* module that names a flow file uses this — never a literal string. */
|
|
38
38
|
export const FLOW_FILES = Object.freeze(['prose.txt', 'declaration.json', 'signature.json']);
|
|
39
|
+
/** The one folder under the flows root where the panel keeps each run start's own files (M4e piece 2b). A dot-name, so never a flow. */
|
|
40
|
+
export const PANEL_STARTS_DIR = '.starts';
|
|
39
41
|
|
|
40
42
|
const RUNS_DIR = 'runs';
|
|
41
43
|
|
|
@@ -241,6 +243,47 @@ export function listRunIds(flowDir) {
|
|
|
241
243
|
.sort();
|
|
242
244
|
}
|
|
243
245
|
|
|
246
|
+
/**
|
|
247
|
+
* M4e amendment 3 item 2: the ONE place a run gets its default name. `run-<n>`, counting up per flow (the run lives in its flow's
|
|
248
|
+
* folder, so the name only has to be unique there). `nextRunId` only LOOKS (max existing `run-<n>` + 1; the page's prefill);
|
|
249
|
+
* `claimRunId` CLAIMS: it creates the run folder exclusively (mkdir with no `recursive` on the final component, so a second
|
|
250
|
+
* starter gets EEXIST, never the same folder) and bumps n on EEXIST, a bounded number of times. Runs already made keep their ids.
|
|
251
|
+
* @param {string} flowDir
|
|
252
|
+
* @returns {string}
|
|
253
|
+
*/
|
|
254
|
+
export function nextRunId(flowDir) {
|
|
255
|
+
let max = 0;
|
|
256
|
+
for (const id of listRunIds(flowDir)) {
|
|
257
|
+
const m = /^run-([0-9]+)$/.exec(id);
|
|
258
|
+
if (m) max = Math.max(max, Number(m[1]));
|
|
259
|
+
}
|
|
260
|
+
return `run-${max + 1}`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const CLAIM_TRIES = 50;
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* @param {string} flowDir
|
|
267
|
+
* @returns {{ok:true, runId:string, runDir:string}|{ok:false, red:string}}
|
|
268
|
+
*/
|
|
269
|
+
export function claimRunId(flowDir) {
|
|
270
|
+
const runsDir = path.join(flowDir, RUNS_DIR);
|
|
271
|
+
let n = Number(nextRunId(flowDir).slice(4));
|
|
272
|
+
for (let i = 0; i < CLAIM_TRIES; i += 1, n += 1) {
|
|
273
|
+
const runId = `run-${n}`;
|
|
274
|
+
const r = resolveRunDir(flowDir, runId);
|
|
275
|
+
if (!r.ok) return r;
|
|
276
|
+
try {
|
|
277
|
+
mkdirSync(runsDir, { recursive: true });
|
|
278
|
+
mkdirSync(r.runDir); // NOT recursive: the exclusive create IS the claim
|
|
279
|
+
return { ok: true, runId, runDir: r.runDir };
|
|
280
|
+
} catch (err) {
|
|
281
|
+
if (/** @type {any} */ (err)?.code !== 'EEXIST') return { ok: false, red: `run: could not claim a run name — ${/** @type {Error} */ (err).message}` };
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { ok: false, red: `run: could not claim a run name after ${CLAIM_TRIES} tries` };
|
|
285
|
+
}
|
|
286
|
+
|
|
244
287
|
/**
|
|
245
288
|
* F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
|
|
246
289
|
* in src/ and bin/ routes through to read a file that lives inside a run
|
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
|
|
|
@@ -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
|
@@ -26,7 +26,8 @@ import { randomUUID } from 'node:crypto';
|
|
|
26
26
|
|
|
27
27
|
import { readConfig, configHome, ConfigError } from './config.js';
|
|
28
28
|
import { isFwdloopAlive, procStartOf } from './liveness.js';
|
|
29
|
-
import {
|
|
29
|
+
import { spendRowCost } from './provider.js';
|
|
30
|
+
import { readDirSpendRows } from './draftspend.js';
|
|
30
31
|
|
|
31
32
|
export { ConfigError };
|
|
32
33
|
|
|
@@ -81,9 +82,9 @@ function namedDirs(rows) {
|
|
|
81
82
|
return [...dirs];
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
/** One dir's total spend (every row, `spendRowCost
|
|
85
|
+
/** One dir's total spend (every row, `spendRowCost`; a draft dir's live record until its final row exists — src/draftspend.js). */
|
|
85
86
|
function dirSpend(dir) {
|
|
86
|
-
return
|
|
87
|
+
return readDirSpendRows(dir).reduce((n, r) => n + spendRowCost(r).usd, 0);
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
/**
|
|
@@ -107,7 +108,7 @@ export function spendSummary(opts = {}) {
|
|
|
107
108
|
else b.modelMs = (b.modelMs ?? 0) + wall;
|
|
108
109
|
};
|
|
109
110
|
for (const dir of namedDirs(readRuns(opts.home))) {
|
|
110
|
-
for (const row of
|
|
111
|
+
for (const row of readDirSpendRows(dir)) {
|
|
111
112
|
const { usd, complete } = spendRowCost(row);
|
|
112
113
|
const tokens = tokensOf(row.tokens);
|
|
113
114
|
const wall = Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null;
|
|
@@ -140,16 +141,17 @@ export function spendSummary(opts = {}) {
|
|
|
140
141
|
|
|
141
142
|
/**
|
|
142
143
|
* 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
|
+
* `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.
|
|
144
146
|
*/
|
|
145
|
-
function liveHeldBefore(rows, idx, home, nowIso) {
|
|
147
|
+
function liveHeldBefore(rows, idx, home, nowIso, settle = true) {
|
|
146
148
|
const ended = new Set(rows.filter((r) => r.kind === 'settled' || r.kind === 'released' || r.kind === 'refused').map((r) => r.holdId));
|
|
147
149
|
let heldUsd = 0;
|
|
148
150
|
let heldRuns = 0;
|
|
149
151
|
for (const r of rows.slice(0, idx)) {
|
|
150
152
|
if (r.kind !== 'hold' || ended.has(r.holdId) || !Number.isFinite(r.holdUsd)) continue;
|
|
151
153
|
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' });
|
|
154
|
+
if (settle) appendRow(home, { kind: 'settled', holdId: r.holdId, at: nowIso, why: 'process gone' });
|
|
153
155
|
continue;
|
|
154
156
|
}
|
|
155
157
|
const spentSince = Math.max(0, dirSpend(r.runDir) - (Number.isFinite(r.spentAtHold) ? r.spentAtHold : 0));
|
|
@@ -159,6 +161,53 @@ function liveHeldBefore(rows, idx, home, nowIso) {
|
|
|
159
161
|
return { heldUsd, heldRuns };
|
|
160
162
|
}
|
|
161
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
|
+
|
|
162
211
|
/**
|
|
163
212
|
* @typedef {object} Claim
|
|
164
213
|
* @property {boolean} ok the hold fits (or no limit is set)
|
|
@@ -192,12 +241,8 @@ export function claimHold({
|
|
|
192
241
|
if (limit === null) return { ok: true, holdId, room };
|
|
193
242
|
const rows = readRuns(home);
|
|
194
243
|
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 });
|
|
244
|
+
const { ok, ...found } = roomFor({ limit, holdUsd, rows, idx: idx < 0 ? rows.length : idx, home, now, nowIso });
|
|
245
|
+
Object.assign(room, found);
|
|
201
246
|
if (!ok) {
|
|
202
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 */ }
|
|
203
248
|
return { ok: false, holdId, room };
|