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/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
|
@@ -21,8 +21,9 @@ import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
|
|
|
21
21
|
import { loadCatalogue } from './catalogue.js';
|
|
22
22
|
import { WIRED_VERBS, wiredMenu } from './primitives.js';
|
|
23
23
|
import { readInputFacts } from './input-facts.js';
|
|
24
|
-
import { makeProvider, sumMeterings, ceilingCostUsd } from './provider.js';
|
|
24
|
+
import { makeProvider, sumMeterings, ceilingCostUsd, priceRecord } from './provider.js';
|
|
25
25
|
import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
|
|
26
|
+
import { ConfigError } from './config.js';
|
|
26
27
|
|
|
27
28
|
export const MAX_STRUCTURE_RETRIES = 2;
|
|
28
29
|
export const MAX_REVISIONS = 2;
|
|
@@ -165,6 +166,33 @@ function reviseMessage(reds) {
|
|
|
165
166
|
+ `${TOOL} again with the complete corrected declaration:\n${reds.map((r) => `- ${r}`).join('\n')}`;
|
|
166
167
|
}
|
|
167
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
|
+
|
|
168
196
|
function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
|
|
169
197
|
|
|
170
198
|
// F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
|
|
@@ -175,13 +203,19 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
|
|
|
175
203
|
* the batch); otherwise a live provider is built from `slot` (throws on a bad
|
|
176
204
|
* key — the batch preflights first). `budgetUsd` is this draft's hard cap.
|
|
177
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.
|
|
178
212
|
*
|
|
179
213
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
180
|
-
* costUsd:number|null, modelReturned:string|null, modelId?:string, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
|
|
214
|
+
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
|
|
181
215
|
*/
|
|
182
216
|
export async function draft({
|
|
183
|
-
proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId,
|
|
184
|
-
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
|
|
217
|
+
proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
218
|
+
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, revise,
|
|
185
219
|
}) {
|
|
186
220
|
const fail = (reds, extra = {}) => ({
|
|
187
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,
|
|
@@ -198,11 +232,14 @@ export async function draft({
|
|
|
198
232
|
if (!facts.ok) return fail(facts.reds);
|
|
199
233
|
|
|
200
234
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
235
|
+
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
201
236
|
if (provider == null) {
|
|
202
237
|
try {
|
|
203
|
-
({
|
|
238
|
+
({
|
|
239
|
+
provider, rates, modelId, prices = null,
|
|
240
|
+
} = makeProviderFn(slot, { model, env, ...DRAFT_PROVIDER_OPTIONS }));
|
|
204
241
|
} catch (err) {
|
|
205
|
-
return fail([
|
|
242
|
+
return fail([`${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
|
|
206
243
|
}
|
|
207
244
|
}
|
|
208
245
|
|
|
@@ -212,7 +249,7 @@ export async function draft({
|
|
|
212
249
|
const cat = loadCatalogue();
|
|
213
250
|
if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
|
|
214
251
|
const validationCatalogue = cat.primitives;
|
|
215
|
-
const roundCeiling = ceilingCostUsd(modelId);
|
|
252
|
+
const roundCeiling = ceilingCostUsd(modelId, undefined, prices ? { prices } : {});
|
|
216
253
|
// One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
|
|
217
254
|
if (roundCeiling > budgetUsd) {
|
|
218
255
|
return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
|
|
@@ -224,7 +261,7 @@ export async function draft({
|
|
|
224
261
|
let revisions = 0;
|
|
225
262
|
let lastReds = [];
|
|
226
263
|
let lastDecl = null;
|
|
227
|
-
let userText = `Call ${TOOL} now.`;
|
|
264
|
+
let userText = revise ? reviseOpening(revise.plan, revise.note) : `Call ${TOOL} now.`;
|
|
228
265
|
let nextKind = 'first'; // what the round about to run actually is
|
|
229
266
|
let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
|
|
230
267
|
let stop = null;
|
|
@@ -251,6 +288,10 @@ export async function draft({
|
|
|
251
288
|
let result;
|
|
252
289
|
let threw = null;
|
|
253
290
|
calls += 1;
|
|
291
|
+
const book = (inFlight) => onBook?.({
|
|
292
|
+
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
293
|
+
});
|
|
294
|
+
book(true);
|
|
254
295
|
try {
|
|
255
296
|
result = await loop.run(
|
|
256
297
|
[{ role: 'system', content: system }, { role: 'user', content: userText }],
|
|
@@ -261,6 +302,7 @@ export async function draft({
|
|
|
261
302
|
threw = err;
|
|
262
303
|
if (roundEvents.length === 0) unmetered += 1;
|
|
263
304
|
}
|
|
305
|
+
book(false);
|
|
264
306
|
const entry = { round: log.length + 1, kind: nextKind };
|
|
265
307
|
|
|
266
308
|
if (threw) {
|
|
@@ -293,7 +335,7 @@ export async function draft({
|
|
|
293
335
|
declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
|
|
294
336
|
}
|
|
295
337
|
const verdict = validateDeclaration(declaration, {
|
|
296
|
-
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true,
|
|
338
|
+
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
297
339
|
});
|
|
298
340
|
lastDecl = declaration;
|
|
299
341
|
if (verdict.ok) {
|
|
@@ -301,7 +343,7 @@ export async function draft({
|
|
|
301
343
|
log.push(entry);
|
|
302
344
|
const m = sumMeterings(meterings);
|
|
303
345
|
return {
|
|
304
|
-
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop: null, log,
|
|
346
|
+
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log,
|
|
305
347
|
};
|
|
306
348
|
}
|
|
307
349
|
lastReds = [...verdict.reds];
|
|
@@ -319,6 +361,6 @@ export async function draft({
|
|
|
319
361
|
// Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
|
|
320
362
|
// never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
|
|
321
363
|
return {
|
|
322
|
-
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop, log,
|
|
364
|
+
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log,
|
|
323
365
|
};
|
|
324
366
|
}
|
|
@@ -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/keysfile.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/keysfile.js@a42ca5f
|
|
2
|
+
// M4d scope item 1 — the keys file loader (`~/.config/fwdloop/.env`).
|
|
3
|
+
//
|
|
4
|
+
// Key VALUES live only in this file (mode 0600, outside any repo) and in the shell
|
|
5
|
+
// environment — never in config.json, the spine, runs.jsonl, a log, a page or an audit
|
|
6
|
+
// row. This is the ONE reader of that file. Plain `NAME=value` lines (an optional
|
|
7
|
+
// `export ` prefix, `#` full-line comments, one pair of matching quotes around the
|
|
8
|
+
// value); no dependency.
|
|
9
|
+
//
|
|
10
|
+
// Precedence: the SHELL wins. An exported `FOO=…` beats the file; the file only fills
|
|
11
|
+
// names the shell leaves unset (or empty). The merged env is a NEW object —
|
|
12
|
+
// `process.env` is never mutated.
|
|
13
|
+
//
|
|
14
|
+
// Adjusted from bareloop (ruling 1A, hamr 2026-10-05): a file with any group/other bit is
|
|
15
|
+
// REFUSED, not warned about. A refusal carries no env at all: nothing that needs a key runs.
|
|
16
|
+
//
|
|
17
|
+
// Values leave this module in exactly one place: the `env` of an ok `loadKeysEnv`.
|
|
18
|
+
// Everything else it returns (`names`, `path`, `exists`, `refusal`) is value-free by
|
|
19
|
+
// construction, and a parse problem never quotes the offending line.
|
|
20
|
+
import {
|
|
21
|
+
openSync, fstatSync, readFileSync, closeSync, writeFileSync, mkdirSync,
|
|
22
|
+
} from 'node:fs';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { PROVIDER_SLOTS } from './provider.js';
|
|
25
|
+
import { configHome, configDoorHome } from './config.js';
|
|
26
|
+
|
|
27
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
28
|
+
|
|
29
|
+
/** The key names fwdloop knows (one per provider slot). */
|
|
30
|
+
export const KEY_NAMES = Object.freeze(Object.values(PROVIDER_SLOTS).map((p) => p.envVar));
|
|
31
|
+
|
|
32
|
+
const DEFAULT_SHOWN = '~/.config/fwdloop/.env';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `~/.config/fwdloop`, or an injected override. The CLI/panel door honors the test-only
|
|
36
|
+
* `FWDLOOP_CONFIG_HOME` through `keysForDoor` (two gates, like the other test seams).
|
|
37
|
+
* @param {string} [home] test seam; production never passes it
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export function keysHome(home) {
|
|
41
|
+
return configHome(home); // one definition of the config home (src/config.js)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} [home]
|
|
46
|
+
* @returns {string} `<home>/.env`
|
|
47
|
+
*/
|
|
48
|
+
export function keysFilePath(home) {
|
|
49
|
+
return join(keysHome(home), '.env');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The path as a sentence shows it: `~/...` for the default home, the real path for an injected one. */
|
|
53
|
+
const shownPath = (home) => (home === undefined ? DEFAULT_SHOWN : keysFilePath(home));
|
|
54
|
+
|
|
55
|
+
/** The one wording of the 1A refusal (ruling 1A, hamr 2026-10-05). @param {string} [home] */
|
|
56
|
+
export function chmodSentence(home) {
|
|
57
|
+
return `Your keys file can be read by other users. Run: chmod 600 ${shownPath(home)}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parse the file's text. Lines that are not `NAME=value` are skipped silently
|
|
62
|
+
* (never echoed — a malformed line may hold a secret).
|
|
63
|
+
* @param {string} text
|
|
64
|
+
* @returns {Record<string,string>}
|
|
65
|
+
*/
|
|
66
|
+
export function parseKeysText(text) {
|
|
67
|
+
/** @type {Record<string,string>} */
|
|
68
|
+
const out = {};
|
|
69
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
70
|
+
const line = raw.trim();
|
|
71
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
72
|
+
const body = line.startsWith('export ') ? line.slice(7).trimStart() : line;
|
|
73
|
+
const eq = body.indexOf('=');
|
|
74
|
+
if (eq <= 0) continue;
|
|
75
|
+
const name = body.slice(0, eq).trim();
|
|
76
|
+
if (!NAME_RE.test(name)) continue;
|
|
77
|
+
let value = body.slice(eq + 1).trim();
|
|
78
|
+
if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) {
|
|
79
|
+
value = value.slice(1, -1);
|
|
80
|
+
}
|
|
81
|
+
out[name] = value;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Create the file when — and only when — it does not exist: mode 0600 (`wx`), dir 0700,
|
|
88
|
+
* the known key names as commented lines and nothing else.
|
|
89
|
+
* @param {string} [home]
|
|
90
|
+
* @returns {boolean} true if it was created
|
|
91
|
+
*/
|
|
92
|
+
function createKeysFile(home) {
|
|
93
|
+
mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
|
|
94
|
+
const body = '# fwdloop keys — type NAME=value by hand; this file is never shown or written by fwdloop.\n'
|
|
95
|
+
+ `${KEY_NAMES.map((n) => `# ${n}=`).join('\n')}\n`;
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(keysFilePath(home), body, { mode: 0o600, flag: 'wx' });
|
|
98
|
+
} catch (/** @type {any} */ e) {
|
|
99
|
+
if (e?.code === 'EEXIST') return false; // lost a race: the file is there, untouched
|
|
100
|
+
throw e;
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* @typedef {object} KeysLoad
|
|
107
|
+
* @property {boolean} ok false = refused: nothing that needs a key may run
|
|
108
|
+
* @property {string} path the keys file's path as shown to people
|
|
109
|
+
* @property {boolean} exists the file is there (true after a create)
|
|
110
|
+
* @property {string[]} names the NAMES the file defines with a value (sorted; never values)
|
|
111
|
+
* @property {string[]} shellOnly the known key names that only the shell sets (file empty/absent)
|
|
112
|
+
* @property {string|null} refusal a plain sentence when `ok` is false, else null
|
|
113
|
+
* @property {Record<string,string|undefined>} env shell env with the file filling the names the
|
|
114
|
+
* shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
|
|
115
|
+
* place file values leave this module.
|
|
116
|
+
*/
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Load the keys file over an env. A missing file is created (0600) and is not a refusal.
|
|
120
|
+
* @param {{ env?: Record<string,string|undefined>, home?: string }} [opts]
|
|
121
|
+
* @returns {KeysLoad}
|
|
122
|
+
*/
|
|
123
|
+
export function loadKeysEnv(opts = {}) {
|
|
124
|
+
const base = opts.env ?? process.env;
|
|
125
|
+
const file = keysFilePath(opts.home);
|
|
126
|
+
const path = shownPath(opts.home);
|
|
127
|
+
const knownShell = (parsed) => KEY_NAMES.filter((n) => base[n] && !parsed[n]);
|
|
128
|
+
/** @param {string} refusal @param {boolean} exists @returns {KeysLoad} */
|
|
129
|
+
const refused = (refusal, exists) => ({
|
|
130
|
+
ok: false, path, exists, names: [], shellOnly: [], refusal, env: { ...base },
|
|
131
|
+
});
|
|
132
|
+
let fd;
|
|
133
|
+
let created = false;
|
|
134
|
+
try {
|
|
135
|
+
try {
|
|
136
|
+
fd = openSync(file, 'r');
|
|
137
|
+
} catch (/** @type {any} */ e) {
|
|
138
|
+
if (e?.code !== 'ENOENT') throw e;
|
|
139
|
+
created = createKeysFile(opts.home);
|
|
140
|
+
fd = openSync(file, 'r');
|
|
141
|
+
}
|
|
142
|
+
const st = fstatSync(fd);
|
|
143
|
+
if (!st.isFile()) return refused(`Your keys file ${path} is not a regular file.`, true);
|
|
144
|
+
if ((st.mode & 0o077) !== 0) return refused(chmodSentence(opts.home), true);
|
|
145
|
+
const parsed = parseKeysText(readFileSync(fd, 'utf8'));
|
|
146
|
+
/** @type {Record<string,string|undefined>} */
|
|
147
|
+
const env = { ...base };
|
|
148
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
149
|
+
if (!env[name]) env[name] = value;
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
|
|
153
|
+
};
|
|
154
|
+
} catch (/** @type {any} */ e) {
|
|
155
|
+
return refused(`Your keys file ${path} could not be read (${e?.code ?? 'error'}).`, created || e?.code !== 'ENOENT');
|
|
156
|
+
} finally {
|
|
157
|
+
if (fd !== undefined) closeSync(fd);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The door helper the CLI and the panel call. Loads the file only when the caller is on the
|
|
163
|
+
* REAL environment, or names a home explicitly (a test), or a test process (`configDoorHome`) with
|
|
164
|
+
* `FWDLOOP_CONFIG_HOME` set — so a test that injects `env` alone, or runs under NODE_ENV=test
|
|
165
|
+
* without a home, never reads (or creates) the real `~/.config/fwdloop/.env`.
|
|
166
|
+
* @param {{ env?: Record<string,string|undefined>, keysHome?: string }} [deps]
|
|
167
|
+
* @returns {KeysLoad & { skipped: boolean }}
|
|
168
|
+
*/
|
|
169
|
+
export function keysForDoor(deps = {}) {
|
|
170
|
+
const shell = process.env;
|
|
171
|
+
const door = configDoorHome(); // the one "under test" rule (NODE_ENV=test or node --test) and its home
|
|
172
|
+
const home = deps.keysHome ?? door.home;
|
|
173
|
+
const testNoHome = door.skip && home === undefined;
|
|
174
|
+
if ((deps.env !== undefined && home === undefined) || testNoHome) {
|
|
175
|
+
return {
|
|
176
|
+
ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], refusal: null, env: { ...(deps.env ?? shell) },
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
return { ...loadKeysEnv({ env: deps.env, home }), skipped: false };
|
|
180
|
+
}
|
package/src/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) {
|