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.
Files changed (62) hide show
  1. package/bin/fwdloop +248 -27
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +103 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +256 -0
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +53 -11
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/keysfile.js +180 -0
  13. package/src/liveness.js +1 -1
  14. package/src/model-step.js +43 -8
  15. package/src/monthly.js +276 -0
  16. package/src/panel/author.js +482 -0
  17. package/src/panel/authorcard.js +297 -0
  18. package/src/panel/authorflows.js +312 -0
  19. package/src/panel/authorresume.js +149 -0
  20. package/src/panel/authorstart.js +257 -0
  21. package/src/panel/authorvalues.js +110 -0
  22. package/src/panel/data.js +228 -34
  23. package/src/panel/index.html +2073 -124
  24. package/src/panel/resume.js +14 -11
  25. package/src/panel/server.js +150 -117
  26. package/src/panel/settings.js +270 -0
  27. package/src/panel/spawn.js +77 -0
  28. package/src/provider.js +189 -43
  29. package/src/providershapes.js +19 -0
  30. package/src/runner.js +639 -85
  31. package/src/runvalues.js +178 -0
  32. package/src/send.js +10 -3
  33. package/src/setup.js +120 -0
  34. package/types/authoring.d.ts +24 -2
  35. package/types/books.d.ts +14 -2
  36. package/types/canrun.d.ts +32 -0
  37. package/types/config.d.ts +52 -0
  38. package/types/declaration.d.ts +9 -1
  39. package/types/drafter.d.ts +18 -2
  40. package/types/draftspend.d.ts +21 -0
  41. package/types/flow.d.ts +23 -0
  42. package/types/keysfile.d.ts +90 -0
  43. package/types/liveness.d.ts +2 -2
  44. package/types/model-step.d.ts +6 -2
  45. package/types/monthly.d.ts +130 -0
  46. package/types/panel/author.d.ts +335 -0
  47. package/types/panel/authorcard.d.ts +120 -0
  48. package/types/panel/authorflows.d.ts +175 -0
  49. package/types/panel/authorresume.d.ts +32 -0
  50. package/types/panel/authorstart.d.ts +115 -0
  51. package/types/panel/authorvalues.d.ts +62 -0
  52. package/types/panel/data.d.ts +103 -12
  53. package/types/panel/resume.d.ts +8 -1
  54. package/types/panel/server.d.ts +19 -33
  55. package/types/panel/settings.d.ts +23 -0
  56. package/types/panel/spawn.d.ts +30 -0
  57. package/types/provider.d.ts +123 -70
  58. package/types/providershapes.d.ts +11 -0
  59. package/types/runner.d.ts +120 -5
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +83 -0
package/src/authoring.js CHANGED
@@ -28,9 +28,13 @@ import { canonicalBytes } from './signature.js';
28
28
  import { writeFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
29
29
  import { checkSendDestination } from './runner.js';
30
30
  import { PROVIDER_SLOTS, checkKeyPreflight, appendSpendRow } from './provider.js';
31
+ import { writeDraftSpend } from './draftspend.js';
32
+ import { writeSetup } from './setup.js';
31
33
 
32
34
  export const DRAFT_BUDGET_USD = 0.10;
33
35
  export const SPEC_HASH_FILE = 'spec.hash';
36
+ /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
37
+ export const PANEL_DRAFTS_DIR = '.drafts';
34
38
  /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
35
39
  export const LEAK_MARKER_FILE = 'scrub-leak.red';
36
40
  export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
@@ -68,6 +72,15 @@ export function scrub(text, secrets) {
68
72
  return out;
69
73
  }
70
74
 
75
+ /**
76
+ * Does `text` carry any provider key VALUE in `env` (every slot, 8+ chars, literal)? The one test for a human's free text
77
+ * (the revise note) — the same literal rule `scrub` and `sweepForSecrets` use.
78
+ * @param {string} text @param {Record<string, string|undefined>} env
79
+ */
80
+ export function textHasKey(text, env) {
81
+ return Object.values(PROVIDER_SLOTS).some((p) => { const k = env[p.envVar]; return typeof k === 'string' && k.length >= 8 && text.includes(k); });
82
+ }
83
+
71
84
  /** Count files directly inside `dir` that contain a secret literally. */
72
85
  export function sweepForSecrets(dir, secrets) {
73
86
  const live = secrets.filter((s) => typeof s === 'string' && s.length >= 8);
@@ -96,6 +109,24 @@ export const costText = (n, spendComplete = true) => {
96
109
  };
97
110
  const usd = costText;
98
111
 
112
+ /** The readout's section headings: the ONE list. buildReadout writes them from here and `readoutHeadIndexes` finds them by it,
113
+ * so the panel's bold and the template cannot drift (M4e amendment 7 item 3). */
114
+ const READOUT_HEADS = {
115
+ inputs: 'INPUTS',
116
+ steps: 'STEPS',
117
+ asks: 'ASKS (human stops)',
118
+ sends: 'SEND TARGET (nothing leaves before an accepted ask)',
119
+ refused: 'REFUSED LINES',
120
+ jobLines: 'JOB LINES',
121
+ };
122
+ /** Zero-based indexes of the heading lines in a readout's text (split on "\n"): the panel renders those bold. */
123
+ export function readoutHeadIndexes(text) {
124
+ const heads = new Set(Object.values(READOUT_HEADS));
125
+ const idx = [];
126
+ String(text).split('\n').forEach((l, i) => { if (heads.has(l)) idx.push(i); });
127
+ return idx;
128
+ }
129
+
99
130
  /** Plain-text readout of what the human is about to sign. Pure. */
100
131
  export function buildReadout({
101
132
  declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
@@ -105,29 +136,33 @@ export function buildReadout({
105
136
  out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
106
137
  if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
107
138
  out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
108
- out.push('INPUTS');
139
+ out.push(READOUT_HEADS.inputs);
109
140
  for (const s of arbiter.sources) {
110
141
  const h = declaration.inputFacts?.[s.role];
111
142
  out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
112
143
  }
113
- out.push('', 'STEPS');
144
+ out.push('', READOUT_HEADS.steps);
114
145
  declaration.steps.forEach((st, i) => {
115
146
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
116
147
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
117
148
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
118
149
  });
119
- out.push('', 'ASKS (human stops)');
150
+ out.push('', READOUT_HEADS.asks);
120
151
  for (const a of arbiter.asks) out.push(` line ${a.line}: "${a.question}" (ttl ${fmtTtl(a.ttlMs)})`);
121
152
  if (arbiter.asks.length === 0) out.push(' none');
122
- out.push('', 'SEND TARGET (nothing leaves before an accepted ask)');
153
+ out.push('', READOUT_HEADS.sends);
123
154
  for (const s of arbiter.sends) out.push(` line ${s.line} -> ${s.target.kind}:${s.target.path}`);
124
155
  if (arbiter.sends.length === 0) out.push(' none');
125
156
  const refused = declaration.refused ?? [];
126
157
  if (refused.length) {
127
- out.push('', 'REFUSED LINES');
158
+ out.push('', READOUT_HEADS.refused);
128
159
  for (const r of refused) out.push(` line ${r.line}: ${r.reason}`);
129
160
  }
130
- out.push('', 'JOB LINES', ...lines.map((l) => ` ${l.n}. ${l.text}`));
161
+ out.push('', READOUT_HEADS.jobLines);
162
+ for (const l of lines) {
163
+ out.push(` ${l.n}. ${l.text}`);
164
+ if (typeof l.guardrail === 'string' && l.guardrail.trim() !== '') out.push(` ~ ${l.guardrail}`);
165
+ }
131
166
  return `${out.join('\n')}\n`;
132
167
  }
133
168
 
@@ -163,7 +198,7 @@ export function readProseFile(file) {
163
198
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
164
199
  */
165
200
  export async function draftToDir({
166
- proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId,
201
+ proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId, reviseFrom, noteFile,
167
202
  }) {
168
203
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
169
204
  const nameCheck = checkFlowName(name);
@@ -174,7 +209,10 @@ export async function draftToDir({
174
209
  const realRoot = realpathOfNew(root);
175
210
  const realDir = realpathOfNew(dir);
176
211
  const rel = path.relative(realRoot, realDir);
177
- if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
212
+ // M4e piece 2: the panel's own draft folders live at exactly `<root>/.drafts/<id>/...` (a dot-name is never a flow:
213
+ // `checkFlowName` refuses it, so `listFlowNames`/`readFlow` never list it). Nothing else under the root is allowed.
214
+ const panelDrafts = rel.startsWith(`${PANEL_DRAFTS_DIR}${path.sep}`) && !path.isAbsolute(rel);
215
+ if (!panelDrafts && (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))) {
178
216
  return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
179
217
  }
180
218
  const read = readProseFile(proseFile);
@@ -188,6 +226,28 @@ export async function draftToDir({
188
226
  }
189
227
  const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
190
228
  if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
229
+ // M4e amendment 3 item 3: a revise starts from the current green plan's dir plus the human's note, and nothing else. All $0, before the dir is claimed.
230
+ /** @type {{ plan: any, note: string }|undefined} */
231
+ let revise;
232
+ if ((reviseFrom === undefined) !== (noteFile === undefined)) return refuse(['draft: --revise-from and --note go together']);
233
+ if (reviseFrom !== undefined && noteFile !== undefined) {
234
+ const prev = {};
235
+ for (const f of ['prose.txt', 'declaration.json', SPEC_HASH_FILE]) {
236
+ const r = readFileInside(reviseFrom, f);
237
+ if (!r.ok) return refuse([`revise: "${reviseFrom}" is not a green draft — ${f} ${r.missing ? 'is missing' : `is refused (${r.red})`}`]);
238
+ prev[f] = r.text;
239
+ }
240
+ // the card's fields come only from the card: a revise carries the SAME prose, byte for byte, as the plan it revises
241
+ if (prev['prose.txt'] !== prose.text) return refuse(['revise: the prose differs from the plan being revised — a revise never changes the card']);
242
+ const noteRead = readFileInside(path.dirname(noteFile), path.basename(noteFile));
243
+ if (!noteRead.ok) return refuse([`revise: cannot read the note "${noteFile}": ${noteRead.missing ? 'missing' : noteRead.red}`]);
244
+ const note = noteRead.text;
245
+ if (note.trim() === '') return refuse(['revise: the note is empty']);
246
+ if (textHasKey(note, env)) return refuse(['note: contains an API key value — refused']);
247
+ let plan;
248
+ try { plan = JSON.parse(prev['declaration.json']); } catch { return refuse(['revise: the plan being revised is not valid JSON']); }
249
+ revise = { plan, note };
250
+ }
191
251
  // Red messages can echo what a provider's error body echoed (a key): scrubbed like every file, before anything prints them.
192
252
  const cleanReds = (reds) => (reds ?? []).map((r) => scrub(String(r), secrets));
193
253
  // Claim the dir BEFORE the paid round (exclusive mkdir: a race or an existing path refuses at $0).
@@ -200,8 +260,26 @@ export async function draftToDir({
200
260
  return e.code === 'EEXIST' ? exists() : refuse([`draft: cannot create "${dir}": ${e.code ?? e.message}`]);
201
261
  }
202
262
 
263
+ // Spend is booked per call into `<dir>/draft-spend.json` (src/draftspend.js), so a draft stopped between rounds
264
+ // keeps what it paid. The first write is the mark that a call is in flight: if that cannot be written, the call is not made.
265
+ let startedAt = null;
266
+ const onBook = ({
267
+ inFlight, calls, unmetered, metered, modelId: usedModel, price,
268
+ }) => {
269
+ const now = new Date().toISOString();
270
+ startedAt ??= now;
271
+ try {
272
+ writeDraftSpend(dir, {
273
+ kind: 'draft-live', provider: slot, model: usedModel ?? modelId ?? null, price: price ?? null, tokens: metered.tokens, costUsd: metered.costUsd, rounds: metered.rounds,
274
+ calls, spendComplete: !inFlight && unmetered === 0 && metered.costUsd !== null, inFlight, at: startedAt, startedAt, updatedAt: now,
275
+ });
276
+ } catch (e) {
277
+ if (inFlight) throw new Error(`draft: cannot book the spend before the call (${e.code ?? e.message}) — nothing was spent`);
278
+ // after a call the cost is already in the file as "one call in flight" (a ceiling): the honest direction, so no throw
279
+ }
280
+ };
203
281
  const result = await draft({
204
- proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId,
282
+ proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env, onBook, revise,
205
283
  });
206
284
  if (result.stop === 'pre-flight') {
207
285
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -219,6 +297,7 @@ export async function draftToDir({
219
297
  files['prose.txt'] = prose.text; // verbatim
220
298
  const targetText = dj({ root, name });
221
299
  files['target.json'] = targetText;
300
+ if (revise) files['note.txt'] = revise.note; // kept with the draft it made (write-once: the dir is exclusive)
222
301
  files['log.json'] = scrub(dj({
223
302
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
224
303
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
@@ -248,6 +327,8 @@ export async function draftToDir({
248
327
  try {
249
328
  appendSpendRow(path.join(dir, 'spend.jsonl'), {
250
329
  kind: 'draft',
330
+ provider: slot,
331
+ price: result.price ?? null,
251
332
  model: result.modelId ?? modelId ?? null,
252
333
  modelReturned: result.modelReturned,
253
334
  tokens: result.tokens ?? null,
@@ -257,6 +338,9 @@ export async function draftToDir({
257
338
  spendComplete: result.spendComplete,
258
339
  stop: result.stop,
259
340
  budgetUsd,
341
+ // the draft's own time (amendment 7 item 2: the Draft's total time adds up from these); null when no call was booked
342
+ startedAt,
343
+ wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
260
344
  });
261
345
  for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
262
346
  leaks = sweepForSecrets(dir, secrets);
@@ -277,9 +361,10 @@ export async function draftToDir({
277
361
  /**
278
362
  * The human step, $0. Every refusal returns reds and writes NO flow.
279
363
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
364
+ * `sessionDir` (the panel's draft folder: card, notes, every change) widens the setup record; the CLI has none, so its record is the one plan folder.
280
365
  */
281
366
  export function signDraft({
282
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env,
367
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, sessionDir,
283
368
  }) {
284
369
  const refuse = (...reds) => ({ ok: false, reds });
285
370
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
@@ -317,7 +402,7 @@ export function signDraft({
317
402
  const cat = loadCatalogue();
318
403
  if (!cat.ok) return refuse(`sign: catalogue: ${cat.reds.join('; ')}`);
319
404
  const verdict = validateDeclaration(declaration, {
320
- arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true,
405
+ arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
321
406
  });
322
407
  if (!verdict.ok) return { ok: false, reds: verdict.reds };
323
408
 
@@ -326,7 +411,7 @@ export function signDraft({
326
411
  if (s.kind === 'file' && !existsSync(s.path)) reds.push(`sign: input source "${s.role}" is missing at ${s.path}`);
327
412
  }
328
413
  for (const s of signed.arbiter.sends) {
329
- const d = checkSendDestination(`${s.target.kind}:${s.target.path}`);
414
+ const d = checkSendDestination(`${s.target.kind}:${s.target.path}`, { root: target.root });
330
415
  if (!d.ok) reds.push(`sign: ${d.red}`);
331
416
  }
332
417
  if (reds.length) return { ok: false, reds };
@@ -335,5 +420,10 @@ export function signDraft({
335
420
  root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
336
421
  });
337
422
  if (!written.ok) return { ok: false, reds: written.reds };
338
- return { ok: true, flowDir: written.dir, signature: written.signature };
423
+ // M4e amendment 6 item 4: the draft's record goes into the flow folder once, outside the three signed files. The flow IS signed by now, so a
424
+ // failure to write it never un-signs: it is returned (`setup.ok:false`) for the caller to say, and the audit reads "no setup record".
425
+ const setup = writeSetup({
426
+ flowDir: written.dir, sessionDir, planDir: dir, hash: h.hash, signedBy, signedAt, flowHash: written.signature?.flow, secrets: /** @type {string[]} */ (keys.filter((k) => typeof k === 'string' && k.length >= 8)),
427
+ });
428
+ return { ok: true, flowDir: written.dir, signature: written.signature, setup };
339
429
  }
package/src/books.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { appendFileSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
- import { readFileInside } from './flow.js';
24
+ import { readFileInside, readdirInside } from './flow.js';
25
25
 
26
26
  function appendLine(filePath, row) {
27
27
  mkdirSync(dirname(filePath), { recursive: true });
@@ -33,7 +33,7 @@ function appendLine(filePath, row) {
33
33
  * rewritten, not a book the arbiter reads. One row per process that works on
34
34
  * the run (`src/liveness.js` `recordPid` builds the row).
35
35
  * @param {string} runDir
36
- * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
36
+ * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'|'continue'}} row
37
37
  */
38
38
  export function appendPidRow(runDir, row) {
39
39
  appendLine(join(runDir, 'pids.jsonl'), row);
@@ -301,3 +301,24 @@ export function appendHistory(flowDir, row) {
301
301
  export function readHistory(flowDir) {
302
302
  return readLines(flowDir, 'history.jsonl');
303
303
  }
304
+
305
+ /** The two outcomes a run can be continued from (M4e amendment 4 item 4): the runner leaves `halt.json` for them. */
306
+ export const HALT_OUTCOMES = Object.freeze(['cap-halt', 'stopped']);
307
+
308
+ /**
309
+ * The ONE rule for "how did this run end": the LAST history row of the run (a run that was stopped or cap-halted and
310
+ * continued has one row per leg; history stays append-only). `null` when the run has no row yet, and also while a
311
+ * continue is in flight: the last row is a halt row, `halt.json` is gone (the continue consumed it by rename to
312
+ * `halt.<n>.consumed.json`) — an older halt row is then not the run's end. A run halted before halt records existed has
313
+ * no consumed file, so its halt row stays final.
314
+ * @param {any[]} historyRows `readHistory`'s rows @param {string} runDir @param {string} runId
315
+ * @returns {any|null}
316
+ */
317
+ export function endRow(historyRows, runDir, runId) {
318
+ let last = null;
319
+ for (const r of historyRows) if (r && r.runId === runId) last = r;
320
+ if (last === null || !HALT_OUTCOMES.includes(last.outcome)) return last;
321
+ const names = readdirInside(runDir, '.');
322
+ const continuing = !names.includes('halt.json') && names.some((n) => /^halt\.\d+\.consumed\.json$/.test(n));
323
+ return continuing ? null : last;
324
+ }
package/src/canrun.js ADDED
@@ -0,0 +1,36 @@
1
+ // M4e amendment 7 item 7: the ONE function that decides "can this flow run" — the panel's Signed flow list reads it, and the run's own
2
+ // preflight refusal says the same words. A flow the run would refuse at preflight (a signature that does not check out; a step granting a
3
+ // verb with no wired implementation) is not offered. Reads only; writes nothing. `WIRED_VERBS` stays the one list (src/primitives.js).
4
+ import { WIRED_VERBS } from './primitives.js';
5
+
6
+ /**
7
+ * The first step granting a verb that has no wired implementation, or null. (A verb absent from the catalogue entirely is caught earlier,
8
+ * at declaration validation inside `readFlow`.)
9
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
10
+ * @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
11
+ */
12
+ export function findUnwiredVerbStep(declaration) {
13
+ for (const step of declaration.steps) {
14
+ for (const verb of step.primitives ?? []) {
15
+ if (!WIRED_VERBS.has(verb)) return { step, verb };
16
+ }
17
+ }
18
+ return null;
19
+ }
20
+
21
+ /** The preflight refusal sentence for an unwired verb, in the words the run's own preflight uses. @param {{step: {emits: string, fromLine: number}, verb: string}} found */
22
+ export function unwiredRed(found) {
23
+ return `preflight: step "${found.step.emits}" (line ${found.step.fromLine}) grants verb "${found.verb}", which has no wired implementation`;
24
+ }
25
+
26
+ /**
27
+ * Can this flow run? `read` is `readFlow`'s result (a failed read — signature, tampering, missing files — is a refusal with its own reds).
28
+ * @param {any} read
29
+ * @returns {{ok: true} | {ok: false, red: string}}
30
+ */
31
+ export function canFlowRun(read) {
32
+ if (!read || read.ok !== true) return { ok: false, red: String(read?.reds?.[0] ?? 'the flow does not read') };
33
+ const unwired = findUnwiredVerbStep(read.declaration);
34
+ if (unwired) return { ok: false, red: unwiredRed(unwired) };
35
+ return { ok: true };
36
+ }
package/src/config.js ADDED
@@ -0,0 +1,256 @@
1
+ // borrowed-from: bareloop src/config.js@0e55685 (and the secret-shape inventory of src/validate.js@07215d6)
2
+ // M4d scope items 2-4 — the ONE reader/writer of `~/.config/fwdloop/config.json`.
3
+ //
4
+ // Shape (unknown top-level fields are kept, never dropped):
5
+ // { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
6
+ // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional; a saved "cachedInPerM" is tolerated, never read (M4d amendment 2)
7
+ // "providers": { "<slot>": { "model": "<id>", "shape": "<shape id>", "baseUrl": "" | "http(s)://…" } } } // each optional (M4d amendment 1)
8
+ // A price is a finite number above 0; 0, a negative, NaN, Infinity or text is a ConfigError
9
+ // naming the slot and field — on write AND on read, so a hand-edited 0 can never price a call at $0.
10
+ // Key VALUES never live here (keys file / shell only): a secret-shaped string is refused on write.
11
+ //
12
+ // A missing file = `{}` (nothing set). An unreadable or unparseable file THROWS `ConfigError` —
13
+ // never `{}`: a broken config must not silently mean "no limit" or "the table's price".
14
+ // Written atomically (tmp + rename), mode 0600.
15
+ import {
16
+ mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync,
17
+ } from 'node:fs';
18
+ import { join, dirname } from 'node:path';
19
+ import { homedir } from 'node:os';
20
+ import { SHAPE_IDS } from './providershapes.js';
21
+
22
+ /** A plain-words config failure (bad value, secret-shaped string, unreadable file). */
23
+ export class ConfigError extends Error {}
24
+
25
+ /**
26
+ * `~/.config/fwdloop`, or an injected override — the ONE definition of fwdloop's config home
27
+ * (the keys file lives beside config.json; `src/keysfile.js` calls this, never its own copy).
28
+ * @param {string} [home] test seam; production never passes it
29
+ * @returns {string}
30
+ */
31
+ export function configHome(home) {
32
+ return home ?? join(homedir(), '.config', 'fwdloop');
33
+ }
34
+
35
+ /**
36
+ * @param {string} [home]
37
+ * @returns {string} `<home>/config.json`
38
+ */
39
+ export function configPath(home) {
40
+ return join(configHome(home), 'config.json');
41
+ }
42
+
43
+ /**
44
+ * The home a model-call price lookup reads, resolved at the door. Under a test process
45
+ * (`NODE_ENV=test` or `node --test`) only an explicit `FWDLOOP_CONFIG_HOME` is read; with none, NO
46
+ * config is read at all — a test never touches the real `~/.config/fwdloop`. Outside tests: the real home.
47
+ * @returns {{ skip: boolean, home: string|undefined }}
48
+ */
49
+ export function configDoorHome() {
50
+ const underTest = process.env.NODE_ENV === 'test' || process.env.NODE_TEST_CONTEXT !== undefined;
51
+ if (!underTest) return { skip: false, home: undefined };
52
+ const home = process.env.FWDLOOP_CONFIG_HOME || undefined;
53
+ return { skip: home === undefined, home };
54
+ }
55
+
56
+ /** Fields a config file may hold; `cachedInPerM` stays so an older file still loads, but nothing prices from it. */
57
+ export const PRICE_FIELDS = Object.freeze(['inPerM', 'cachedInPerM', 'outPerM']);
58
+ const SLOT_RE = /^[A-Za-z0-9_-]{1,64}$/;
59
+
60
+ // The secret-shape inventory (bareloop src/validate.js SECRET_PATTERNS): known token shapes only,
61
+ // left-bounded so hyphenated words never match.
62
+ const SECRET_PATTERNS = [
63
+ /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
64
+ /(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
65
+ /(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
66
+ /(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
67
+ /(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
68
+ /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
69
+ ];
70
+ const isSecretShaped = (str) => SECRET_PATTERNS.some((re) => re.test(str));
71
+
72
+ /** Paths (never values) of every string or key in a tree that carries a secret shape. @param {any} node @param {string} at @param {string[]} out */
73
+ function secretPaths(node, at, out) {
74
+ if (typeof node === 'string') {
75
+ if (isSecretShaped(node)) out.push(at || '(root)');
76
+ } else if (Array.isArray(node)) {
77
+ node.forEach((v, i) => secretPaths(v, `${at}.${i}`, out));
78
+ } else if (node !== null && typeof node === 'object') {
79
+ for (const [k, v] of Object.entries(node)) {
80
+ const p = at ? `${at}.${k}` : k;
81
+ if (isSecretShaped(k)) out.push(p);
82
+ secretPaths(v, p, out);
83
+ }
84
+ }
85
+ }
86
+
87
+ export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl']);
88
+
89
+ /** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
90
+ export function providerFieldProblem(field, v) {
91
+ if (field === 'model') {
92
+ if (typeof v !== 'string' || v.length === 0 || v.length > 200 || /\s/.test(v)) return 'must be a model id: 1 to 200 characters, no spaces';
93
+ } else if (field === 'shape') {
94
+ if (!SHAPE_IDS.includes(v)) return `must be one of ${SHAPE_IDS.join(', ')}`;
95
+ } else if (field === 'baseUrl') {
96
+ if (typeof v !== 'string' || !(v === '' || /^https?:\/\/\S+$/.test(v))) return 'must be empty (the default) or an http(s) address';
97
+ } else return 'is not a provider field';
98
+ return null;
99
+ }
100
+
101
+ /** A Base URL as stored: trailing slashes dropped. */
102
+ export const cleanBaseUrl = (v) => v.replace(/\/+$/, '');
103
+
104
+ const isPrice = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
105
+
106
+ /** @param {any} providers */
107
+ function validateProviders(providers) {
108
+ if (providers === undefined) return;
109
+ if (providers === null || typeof providers !== 'object' || Array.isArray(providers)) {
110
+ throw new ConfigError('providers must be an object of provider slots');
111
+ }
112
+ for (const [slot, row] of Object.entries(providers)) {
113
+ if (!SLOT_RE.test(slot)) throw new ConfigError(`providers: "${slot}" is not a provider slot name`);
114
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`providers.${slot} must be an object`);
115
+ for (const [field, v] of Object.entries(row)) {
116
+ if (!PROVIDER_FIELDS.includes(field)) throw new ConfigError(`providers.${slot}.${field} is not a provider field (${PROVIDER_FIELDS.join(', ')})`);
117
+ const problem = providerFieldProblem(field, v);
118
+ if (problem) throw new ConfigError(`providers.${slot}.${field} ${problem}`);
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Validate a whole document's known fields; throws ConfigError naming the field.
125
+ * @param {Record<string, any>} doc
126
+ */
127
+ function validateDoc(doc) {
128
+ if (doc.monthlyLimitUsd !== undefined && !isPrice(doc.monthlyLimitUsd)) {
129
+ throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
130
+ }
131
+ validateProviders(doc.providers);
132
+ if (doc.prices === undefined) return;
133
+ if (doc.prices === null || typeof doc.prices !== 'object' || Array.isArray(doc.prices)) {
134
+ throw new ConfigError('prices must be an object of provider slots');
135
+ }
136
+ for (const [slot, row] of Object.entries(doc.prices)) {
137
+ if (!SLOT_RE.test(slot)) throw new ConfigError(`prices: "${slot}" is not a provider slot name`);
138
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`prices.${slot} must be an object`);
139
+ for (const [field, v] of Object.entries(row)) {
140
+ if (!PRICE_FIELDS.includes(field)) throw new ConfigError(`prices.${slot}.${field} is not a price field (${PRICE_FIELDS.join(', ')})`);
141
+ if (!isPrice(v)) throw new ConfigError(`prices.${slot}.${field} must be a number above 0 (USD per 1M tokens)`);
142
+ }
143
+ }
144
+ }
145
+
146
+ /**
147
+ * The parsed, validated document. `{}` when the file is missing. THROWS ConfigError when the file is
148
+ * there but unreadable, not a JSON object, or holds an invalid known field — never `{}` for those.
149
+ * @param {{ home?: string }} [opts]
150
+ * @returns {Record<string, any>}
151
+ */
152
+ export function readConfig(opts = {}) {
153
+ const file = configPath(opts.home);
154
+ let text;
155
+ try {
156
+ text = readFileSync(file, 'utf8');
157
+ } catch (/** @type {any} */ e) {
158
+ if (e?.code === 'ENOENT') return {};
159
+ throw new ConfigError(`${file} could not be read (${e?.code ?? 'error'}) — fix or remove it`);
160
+ }
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(text);
164
+ } catch {
165
+ throw new ConfigError(`${file} is not readable JSON — fix or remove it`);
166
+ }
167
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
168
+ throw new ConfigError(`${file} must hold a JSON object — fix or remove it`);
169
+ }
170
+ try {
171
+ validateDoc(parsed);
172
+ } catch (/** @type {any} */ e) {
173
+ throw new ConfigError(`${file}: ${e.message}`);
174
+ }
175
+ return parsed;
176
+ }
177
+
178
+ /**
179
+ * Apply a patch and write. `null` deletes a field. Top-level fields shallow-merge; `prices` merges
180
+ * per slot, then per field (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
181
+ * clears the field). Everything is validated before anything is written; a refusal leaves the file
182
+ * untouched.
183
+ * @param {Record<string, any>} patch
184
+ * @param {{ home?: string }} [opts]
185
+ * @returns {Record<string, any>} the document as written
186
+ */
187
+ export function updateConfig(patch, opts = {}) {
188
+ const cur = readConfig(opts);
189
+ /** @type {Record<string, any>} */
190
+ const next = { ...cur };
191
+ for (const [k, v] of Object.entries(patch)) {
192
+ if (k === 'prices' || k === 'providers') continue;
193
+ if (v === null) delete next[k];
194
+ else next[k] = v;
195
+ }
196
+ if (patch.prices !== undefined) {
197
+ const p = patch.prices;
198
+ if (p === null) {
199
+ delete next.prices;
200
+ } else {
201
+ if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('prices must be an object of provider slots');
202
+ /** @type {Record<string, any>} */
203
+ const prices = { ...(next.prices ?? {}) };
204
+ for (const [slot, row] of Object.entries(p)) {
205
+ if (row === null) { delete prices[slot]; continue; }
206
+ if (typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`prices.${slot} must be an object`);
207
+ const merged = { ...(prices[slot] ?? {}) };
208
+ for (const [field, v] of Object.entries(row)) {
209
+ if (v === null) delete merged[field];
210
+ else merged[field] = v;
211
+ }
212
+ if (Object.keys(merged).length === 0) delete prices[slot];
213
+ else prices[slot] = merged;
214
+ }
215
+ if (Object.keys(prices).length === 0) delete next.prices;
216
+ else next.prices = prices;
217
+ }
218
+ }
219
+ if (patch.providers !== undefined) {
220
+ const p = patch.providers;
221
+ if (p === null) {
222
+ delete next.providers;
223
+ } else {
224
+ if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('providers must be an object of provider slots');
225
+ /** @type {Record<string, any>} */
226
+ const providers = { ...(next.providers ?? {}) };
227
+ for (const [slot, row] of Object.entries(p)) {
228
+ if (row === null) { delete providers[slot]; continue; }
229
+ if (typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`providers.${slot} must be an object`);
230
+ const merged = { ...(providers[slot] ?? {}) };
231
+ for (const [field, v] of Object.entries(row)) {
232
+ if (v === null) delete merged[field];
233
+ else merged[field] = field === 'baseUrl' && typeof v === 'string' ? cleanBaseUrl(v) : v;
234
+ }
235
+ if (Object.keys(merged).length === 0) delete providers[slot];
236
+ else providers[slot] = merged;
237
+ }
238
+ if (Object.keys(providers).length === 0) delete next.providers;
239
+ else next.providers = providers;
240
+ }
241
+ }
242
+ validateDoc(next);
243
+ /** @type {string[]} */
244
+ const leaks = [];
245
+ secretPaths(next, '', leaks);
246
+ if (leaks.length) {
247
+ throw new ConfigError(`config.json never holds a key value — a secret-shaped string at ${leaks.join(', ')} was refused (keys live in the keys file)`);
248
+ }
249
+ const file = configPath(opts.home);
250
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
251
+ const tmp = `${file}.tmp-${process.pid}`;
252
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
253
+ chmodSync(tmp, 0o600);
254
+ renameSync(tmp, file);
255
+ return next;
256
+ }