fwdloop 0.15.0 → 0.16.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 (52) hide show
  1. package/bin/fwdloop +106 -31
  2. package/package.json +2 -2
  3. package/src/authoring.js +23 -11
  4. package/src/closers.js +5 -0
  5. package/src/config.js +66 -4
  6. package/src/declaration.js +25 -1
  7. package/src/draft-steps.js +79 -0
  8. package/src/drafter.js +54 -15
  9. package/src/flowmodel.js +30 -0
  10. package/src/input-facts.js +12 -3
  11. package/src/keysfile.js +51 -16
  12. package/src/model-step.js +13 -11
  13. package/src/monthly.js +9 -1
  14. package/src/panel/author.js +81 -22
  15. package/src/panel/authorcard.js +25 -17
  16. package/src/panel/authorflows.js +33 -18
  17. package/src/panel/authorresume.js +9 -8
  18. package/src/panel/authorstart.js +11 -9
  19. package/src/panel/data.js +3 -3
  20. package/src/panel/index.html +516 -146
  21. package/src/panel/resume.js +3 -3
  22. package/src/panel/server.js +4 -3
  23. package/src/panel/settings.js +138 -80
  24. package/src/panel/spawn.js +15 -9
  25. package/src/provider.js +136 -178
  26. package/src/providershapes.js +7 -7
  27. package/src/runner.js +38 -22
  28. package/src/thinking.js +55 -0
  29. package/types/authoring.d.ts +11 -4
  30. package/types/closers.d.ts +2 -0
  31. package/types/config.d.ts +9 -1
  32. package/types/draft-steps.d.ts +14 -0
  33. package/types/drafter.d.ts +13 -10
  34. package/types/flowmodel.d.ts +16 -0
  35. package/types/input-facts.d.ts +6 -1
  36. package/types/keysfile.d.ts +23 -6
  37. package/types/model-step.d.ts +1 -1
  38. package/types/monthly.d.ts +1 -0
  39. package/types/panel/author.d.ts +44 -6
  40. package/types/panel/authorcard.d.ts +21 -8
  41. package/types/panel/authorflows.d.ts +29 -6
  42. package/types/panel/authorresume.d.ts +2 -1
  43. package/types/panel/authorstart.d.ts +16 -6
  44. package/types/panel/data.d.ts +2 -2
  45. package/types/panel/resume.d.ts +2 -1
  46. package/types/panel/server.d.ts +3 -1
  47. package/types/panel/settings.d.ts +3 -1
  48. package/types/panel/spawn.d.ts +13 -4
  49. package/types/provider.d.ts +94 -284
  50. package/types/providershapes.d.ts +3 -4
  51. package/types/runner.d.ts +2 -4
  52. package/types/thinking.d.ts +25 -0
@@ -0,0 +1,79 @@
1
+ // M4d amendment 10: the Chat card's list of what a draft really did. ONE function builds it (here), from the draft's own log.json and its
2
+ // declaration; the page only renders it. It sits outside the readout (never signed, never hashed).
3
+ //
4
+ // Each entry: { id, label, status: 'done' | 'failed', details: string[], reds?: string[] }. `reds` (plan checks and try lines) are the checker's raw
5
+ // refusals: the page turns each into its plain sentence (one function there). A step that didn't happen is not in the list.
6
+ // Throws away: the log's per-round tokens, the model's replies and the questions; only the facts named in the amendment are kept.
7
+ // Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
8
+
9
+ const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
10
+ const TRIES = 3;
11
+
12
+ function money(log) {
13
+ if (typeof log.costUsd !== 'number') return 'cost unknown';
14
+ return `${log.spendComplete === false ? 'at least ' : ''}$${log.costUsd.toFixed(4)}`;
15
+ }
16
+
17
+ /** Why a round did not give a plan: its validator reds (raw, as `reds`: the page's one translator makes them plain), else its outcome as a detail line. */
18
+ function reasonOf(entry) {
19
+ if (Array.isArray(entry?.reds) && entry.reds.length > 0) return { details: [], reds: entry.reds.map(String) };
20
+ const o = typeof entry?.outcome === 'string' ? entry.outcome : '';
21
+ return { details: o === '' ? [] : [o.replace(/^structure: /, '')] };
22
+ }
23
+
24
+ /**
25
+ * @param {{ log: any, declaration: any }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
26
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }> | null}
27
+ */
28
+ export function draftStepList({ log, declaration }) {
29
+ if (log === null || typeof log !== 'object') return null;
30
+ const rounds = Array.isArray(log.log) ? log.log : [];
31
+ /** @type {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }>} */
32
+ const out = [];
33
+
34
+ const t = log.thinking;
35
+ if (t && (t.asked === 'on' || t.asked === 'off') && typeof t.status === 'string') {
36
+ if (t.status === 'applied') out.push({ id: 'thinking', label: `thinking ${t.asked}`, status: 'done', details: [] });
37
+ else if (typeof t.say === 'string' && t.say !== '') out.push({ id: 'thinking', label: t.say, status: 'failed', details: [] });
38
+ }
39
+
40
+ if (Array.isArray(log.inputs) && log.inputs.length > 0) {
41
+ out.push({ id: 'inputs', label: 'inputs', status: 'done', details: log.inputs.map((i) => `${i.role}: ${i.detail}`) });
42
+ }
43
+
44
+ // a plan came back (valid or refused by the checker) vs. a round that never gave one (provider red, cut off, budget)
45
+ const gotPlan = rounds.some((e) => e.outcome === 'valid' || String(e.outcome).startsWith('validator'));
46
+ const n = typeof log.rounds === 'number' ? log.rounds : 0;
47
+ const who = typeof log.modelId === 'string' && log.modelId !== '' ? log.modelId : 'the drafter';
48
+ const drafted = { id: 'drafted', label: `drafted with ${who}`, status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [`${n} round${n === 1 ? '' : 's'} · ${money(log)}`] };
49
+ if (!gotPlan) drafted.details.push(...(Array.isArray(log.reds) ? log.reds.map(String) : []));
50
+ out.push(drafted);
51
+
52
+ const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
53
+ const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
54
+ const rubricReds = [];
55
+ const checkReds = [];
56
+ for (const r of reds) {
57
+ const m = REBUILD_RE.exec(r);
58
+ if (m) rubricReds.push(`line ${steps[Number(m[1])]?.fromLine ?? '?'}: ${m[2]}`); else checkReds.push(r);
59
+ }
60
+ if (gotPlan) {
61
+ out.push(log.ok === true
62
+ ? { id: 'checks', label: 'plan checks', status: 'done', details: [] }
63
+ : { id: 'checks', label: 'plan checks', status: 'failed', details: [], reds: checkReds });
64
+ }
65
+
66
+ if (log.ok === true) {
67
+ const soft = steps.filter((s) => s?.close?.class === 'softgreen');
68
+ if (soft.length > 0) out.push({ id: 'rubrics', label: 'rubrics', status: 'done', details: soft.map((s) => `line ${s.fromLine}: built`) });
69
+ } else if (rubricReds.length > 0) {
70
+ out.push({ id: 'rubrics', label: 'rubrics', status: 'failed', details: rubricReds });
71
+ }
72
+
73
+ rounds.forEach((e, i) => {
74
+ if (i === 0) return;
75
+ const no = i + 1;
76
+ out.push({ id: `try-${no}`, label: no <= TRIES ? `try ${no} of ${TRIES}` : `try ${no}`, status: e.outcome === 'valid' ? 'done' : 'failed', ...reasonOf(rounds[i - 1]) });
77
+ });
78
+ return out;
79
+ }
package/src/drafter.js CHANGED
@@ -21,9 +21,13 @@ import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerS
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, priceRecord } from './provider.js';
24
+ import { isCellsPath } from './closers.js';
25
+ import {
26
+ makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
27
+ } from './provider.js';
25
28
  import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
26
29
  import { ConfigError } from './config.js';
30
+ import { thinkingSay, worstThinkingStatus } from './thinking.js';
27
31
 
28
32
  export const MAX_STRUCTURE_RETRIES = 2;
29
33
  export const MAX_REVISIONS = 2;
@@ -63,7 +67,7 @@ export function buildDeclarationSchema(menu) {
63
67
  items: { type: 'string', enum: menu.map((e) => e.verb) },
64
68
  description: 'verbs this step is granted, from the menu only; [] for a pure stop',
65
69
  },
66
- reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only' },
70
+ reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
67
71
  emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
68
72
  fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
69
73
  picks: {
@@ -214,6 +218,15 @@ function jobLinesText(lines, asks) {
214
218
  .join('\n');
215
219
  }
216
220
 
221
+ /** M4d amendment 8: the green step must read an input with cells, so the drafter is told the rule and which inputs have cells. */
222
+ function greenReadRule(sources) {
223
+ const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
224
+ const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be cited; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
225
+ return [csvRoles.length
226
+ ? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}.`
227
+ : `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl".`];
228
+ }
229
+
217
230
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
218
231
  const askLines = arbiter.asks.map((a) => a.line);
219
232
  const sendLines = arbiter.sends.map((s) => s.line);
@@ -224,14 +237,16 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
224
237
  ...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
225
238
  '',
226
239
  'Rules:',
227
- '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step only), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
240
+ '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
228
241
  '- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
229
242
  '- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must cite its source cell), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
230
243
  '- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
244
+ ...greenReadRule(arbiter.sources),
231
245
  '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
232
246
  '- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
233
247
  `- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
234
248
  `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
249
+ '- An ask step must read the output of an earlier step, the thing you are asked to check: its FIRST read is what the human sees at the ask (for example reads: ["bucket_assignment"], the nearest earlier step\'s emits). An ask that reads nothing, or reads something no earlier step makes, is refused. Reading is not a grant: the ask still grants no primitive.',
235
250
  '- Nothing hitl may come after the last signed ask except the send step.',
236
251
  '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
237
252
  '',
@@ -260,9 +275,6 @@ function reviseMessage(reds) {
260
275
 
261
276
  function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
262
277
 
263
- // F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
264
- export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS, thinking: Object.freeze({ type: 'disabled' }) });
265
-
266
278
  /**
267
279
  * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
268
280
  * the batch); otherwise a live provider is built from `slot` (throws on a bad
@@ -275,17 +287,24 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
275
287
  *
276
288
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
277
289
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
278
- * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[]}>}
290
+ * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[]}>}
279
291
  */
280
292
  export async function draft({
281
- proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
282
- budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true,
293
+ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
294
+ budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
283
295
  }) {
296
+ // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
297
+ const thinkingOf = () => {
298
+ const status = worstThinkingStatus(log.map((e) => e.thinkingStatus));
299
+ return { asked: draftThinking, status, say: thinkingSay(status) };
300
+ };
284
301
  const fail = (reds, extra = {}) => ({
285
302
  ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
286
303
  });
287
304
 
288
305
  // ---- $0 gates, before any provider is built -------------------------------
306
+ // `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
307
+ if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
289
308
  const parsed = parseSignedText(proseText);
290
309
  if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
291
310
  const { lines, arbiter } = parsed;
@@ -304,9 +323,9 @@ export async function draft({
304
323
  try {
305
324
  ({
306
325
  provider, rates, modelId, prices = null,
307
- } = makeProviderFn(slot, { model, env, ...DRAFT_PROVIDER_OPTIONS }));
326
+ } = makeProviderFn(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
308
327
  } catch (err) {
309
- return fail([`${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
328
+ return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
310
329
  }
311
330
  }
312
331
 
@@ -318,7 +337,9 @@ export async function draft({
318
337
  const cat = loadCatalogue();
319
338
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
320
339
  const validationCatalogue = cat.primitives;
321
- const roundCeiling = ceilingCostUsd(modelId, undefined, prices ? { prices } : {});
340
+ // The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
341
+ if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
342
+ const roundCeiling = ceilingCostUsd(rates);
322
343
  // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
323
344
  if (roundCeiling > budgetUsd) {
324
345
  return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
@@ -374,7 +395,9 @@ export async function draft({
374
395
  result = await loop.run(
375
396
  [{ role: 'system', content: system }, { role: 'user', content: userText }],
376
397
  [tool],
377
- { maxTokens: DRAFT_MAX_TOKENS, toolChoice: { name: TOOL } },
398
+ // M4d am4: thinking 'on' forces no tool (provider default 'auto'; a text reply goes to the structure retry); 'off' forces it.
399
+ // M4d am7 item 3: `thinkingMode` is bareagent's switch ('on' | 'off'); we send no raw `thinking` field anywhere.
400
+ { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: draftThinking, ...(draftThinking === 'on' ? {} : { toolChoice: { name: TOOL } }) },
378
401
  );
379
402
  } catch (err) {
380
403
  threw = err;
@@ -383,6 +406,9 @@ export async function draft({
383
406
  book(false);
384
407
  const entry = { round: log.length + 1, kind: nextKind };
385
408
 
409
+ if (result?.thinkingApplied !== undefined) entry.thinkingApplied = result.thinkingApplied; // bareagent's verdict on this round: true | false | null
410
+ if (result?.thinkingStatus !== undefined) entry.thinkingStatus = result.thinkingStatus; // 'applied' | 'unsupported' | 'ignored' | 'unknown' (bare-agent >= 0.52)
411
+
386
412
  if (threw) {
387
413
  entry.outcome = `provider-red: ${threw.message}`;
388
414
  log.push(entry);
@@ -399,6 +425,19 @@ export async function draft({
399
425
  entry.outcome = `structure: ${why}`;
400
426
  log.push(entry);
401
427
  lastReds = [why];
428
+ // M4d am3 A3: a round cut off at the output cap before tries 1 and 2 are spent is a FAILED TRY, advancing the same counter a
429
+ // validator red does, so the try-3 question can open. A cut-off names no line, so then every job line may be asked about.
430
+ if (result?.stopReason === 'max_tokens' && revisions < MAX_REVISIONS) {
431
+ revisions += 1;
432
+ nextKind = 'revision';
433
+ userText = `Your last reply was cut off at the output limit before a complete tool call. Call ${TOOL} now with a complete, valid JSON declaration.`;
434
+ if (validatorReds.length) userText += `\n\nThe last declaration you emitted was still refused by the validator; keep fixing these too:\n${validatorReds.map((r) => `- ${r}`).join('\n')}`;
435
+ if (offerQuestions && revisions === MAX_REVISIONS) {
436
+ failedLines = lineNums;
437
+ userText += `\n\n${QUESTIONS_PROMPT}`;
438
+ }
439
+ continue;
440
+ }
402
441
  if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; break; }
403
442
  structureRetries += 1;
404
443
  nextKind = 'structure-retry';
@@ -439,7 +478,7 @@ export async function draft({
439
478
  log.push(entry);
440
479
  const m = sumMeterings(meterings);
441
480
  return {
442
- 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, ...extras,
481
+ 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, thinking: thinkingOf(), inputs: facts.list, ...extras,
443
482
  };
444
483
  }
445
484
  lastReds = [...verdict.reds];
@@ -461,6 +500,6 @@ export async function draft({
461
500
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
462
501
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
463
502
  return {
464
- 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, ...extras,
503
+ 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, thinking: thinkingOf(), inputs: facts.list, ...extras,
465
504
  };
466
505
  }
@@ -0,0 +1,30 @@
1
+ // M4d amendment 6 item 6: the model a job was drafted with is the model it runs with. The pick - a provider (the name of a key)
2
+ // and a model id - is recorded in `model.json`, beside the draft and then beside the signed flow. It is NOT one of the signed files: which model
3
+ // runs, and at what price, is Settings' to say (a line that is no longer ticked is refused by name at run time), so the record only remembers the choice.
4
+ // One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
5
+ import { writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { readFileInside } from './flow.js';
8
+ import { isKeyName } from './provider.js';
9
+
10
+ export const MODEL_FILE = 'model.json';
11
+
12
+ /**
13
+ * @param {string} dir a draft folder or a flow folder
14
+ * @returns {{ slot: string, model: string }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
15
+ */
16
+ export function readModelRecord(dir) {
17
+ const r = readFileInside(dir, MODEL_FILE);
18
+ if (!r.ok) return null;
19
+ try {
20
+ const j = JSON.parse(r.text);
21
+ return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
22
+ } catch { return null; }
23
+ }
24
+
25
+ /**
26
+ * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
27
+ */
28
+ export function writeModelRecord(dir, { slot, model }) {
29
+ writeFileSync(join(dir, MODEL_FILE), `${JSON.stringify({ slot, model }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
30
+ }
@@ -12,15 +12,20 @@
12
12
 
13
13
  import { readFileSync } from 'node:fs';
14
14
  import { readDocxText, readDocxHeadings } from './docx.js';
15
+ import { isCellsPath } from './closers.js';
16
+ import { parseCsv } from './csv.js';
15
17
 
16
18
  /**
17
19
  * @param {Array<{kind?:string, role:string, path:string}>} sources arbiter.sources
18
- * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], reds:string[]}}
20
+ * `list` (M4d am10) is one `{role, detail}` per readable input for the Chat card's list (a CSV: its columns; text: its headings); never hashed.
21
+ * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], list:Array<{role:string, detail:string}>, reds:string[]}}
19
22
  */
20
23
  export function readInputFacts(sources) {
21
24
  /** @type {Record<string,string[]>} */
22
25
  const inputFacts = {};
23
26
  const info = [];
27
+ const list = [];
28
+ const headingsDetail = (n) => `${n} heading${n === 1 ? '' : 's'}`;
24
29
  const reds = [];
25
30
  for (const s of sources ?? []) {
26
31
  if (s.kind !== 'file') continue;
@@ -31,6 +36,7 @@ export function readInputFacts(sources) {
31
36
  if (!h.ok) { reds.push(`input "${s.role}": ${h.red}`); continue; }
32
37
  const words = r.text.trim() === '' ? 0 : r.text.trim().split(/\s+/).length;
33
38
  inputFacts[s.role] = h.headings;
39
+ list.push({ role: s.role, detail: headingsDetail(h.headings.length) });
34
40
  info.push(`- ${s.role}: a .docx file, ${r.paragraphs} paragraphs, ~${words} words, headings: ${h.headings.join(', ') || '(none)'} (read it with "readDocx")`);
35
41
  } else {
36
42
  let raw;
@@ -38,8 +44,11 @@ export function readInputFacts(sources) {
38
44
  if (raw.trim() === '') { reds.push(`input "${s.role}": "${s.path}" is empty`); continue; }
39
45
  const headings = raw.split(/\r?\n/).filter((l) => /^#{1,6}\s+\S/.test(l)).map((l) => l.replace(/^#{1,6}\s*/, '').trim());
40
46
  inputFacts[s.role] = headings;
41
- info.push(`- ${s.role}: a text/markdown file, ~${raw.trim().split(/\s+/).length} words, headings: ${headings.join(', ') || '(none)'} (read it with "read")`);
47
+ list.push({ role: s.role, detail: isCellsPath(s.path) ? `${parseCsv(raw).header.length} columns` : headingsDetail(headings.length) });
48
+ info.push(isCellsPath(s.path)
49
+ ? `- ${s.role}: a CSV file with cells (a step reads it by listing "${s.role}" in its reads; or with "read")`
50
+ : `- ${s.role}: a text/markdown file, ~${raw.trim().split(/\s+/).length} words, headings: ${headings.join(', ') || '(none)'} (read it with "read")`);
42
51
  }
43
52
  }
44
- return { ok: reds.length === 0, inputFacts, info, reds };
53
+ return { ok: reds.length === 0, inputFacts, info, list, reds };
45
54
  }
package/src/keysfile.js CHANGED
@@ -7,6 +7,10 @@
7
7
  // `export ` prefix, `#` full-line comments, one pair of matching quotes around the
8
8
  // value); no dependency.
9
9
  //
10
+ // Every key-looking name (`isKeyName`: …_KEY) with a value is a Settings row (M4d amendment 6): fwdloop knows no key name of its own.
11
+ // A name reaches the env (and so a child) only once its row is set up in Settings (`configured`): a `NODE_OPTIONS` line is not a key
12
+ // name, so it is neither listed nor passed on, even if config.json names it.
13
+ //
10
14
  // Precedence: the SHELL wins. An exported `FOO=…` beats the file; the file only fills
11
15
  // names the shell leaves unset (or empty). The merged env is a NEW object —
12
16
  // `process.env` is never mutated.
@@ -21,13 +25,19 @@ import {
21
25
  openSync, fstatSync, readFileSync, closeSync, writeFileSync, mkdirSync,
22
26
  } from 'node:fs';
23
27
  import { join } from 'node:path';
24
- import { PROVIDER_SLOTS } from './provider.js';
25
- import { configHome, configDoorHome } from './config.js';
28
+ import { configHome, configDoorHome, readConfig } from './config.js';
26
29
 
27
30
  const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
31
+ const KEY_NAME_RE = /^[A-Z][A-Z0-9_]*_KEY$/;
28
32
 
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));
33
+ /**
34
+ * THE rule for what may be a key name (hamr's ruling, branch-review): it looks like an API key, `…_KEY` in capitals. Used at every gate:
35
+ * the `names` Settings lists, the env pass-through, and the routes that take a slot name. A `NODE_OPTIONS` line is not a key.
36
+ * @param {unknown} name @returns {name is string}
37
+ */
38
+ export function isKeyName(name) {
39
+ return typeof name === 'string' && KEY_NAME_RE.test(name);
40
+ }
31
41
 
32
42
  const DEFAULT_SHOWN = '~/.config/fwdloop/.env';
33
43
 
@@ -92,7 +102,7 @@ export function parseKeysText(text) {
92
102
  function createKeysFile(home) {
93
103
  mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
94
104
  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`;
105
+ + '# One line per provider key, e.g. MY_PROVIDER_API_KEY=... ; each key becomes a row in Settings > Providers.\n';
96
106
  try {
97
107
  writeFileSync(keysFilePath(home), body, { mode: 0o600, flag: 'wx' });
98
108
  } catch (/** @type {any} */ e) {
@@ -108,7 +118,8 @@ function createKeysFile(home) {
108
118
  * @property {string} path the keys file's path as shown to people
109
119
  * @property {boolean} exists the file is there (true after a create)
110
120
  * @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)
121
+ * @property {string[]} shellOnly the configured key names that only the shell sets (file empty/absent)
122
+ * @property {string[]} keyNames the NAMES of the keys that are set up in Settings and hold a value in `env` (the scrub list's names; never values)
112
123
  * @property {string|null} refusal a plain sentence when `ok` is false, else null
113
124
  * @property {Record<string,string|undefined>} env shell env with the file filling the names the
114
125
  * shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
@@ -116,18 +127,32 @@ function createKeysFile(home) {
116
127
  */
117
128
 
118
129
  /**
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]
130
+ * The key VALUES of the named keys in an env: the scrub list. The names come from a load's `keyNames`.
131
+ * @param {Record<string,string|undefined>} env @param {readonly string[]|undefined} names
132
+ * @returns {string[]}
133
+ */
134
+ export function keyValues(env, names) {
135
+ /** @type {string[]} */
136
+ const out = [];
137
+ for (const n of names ?? []) { const v = env[n]; if (typeof v === 'string' && v !== '') out.push(v); }
138
+ return out;
139
+ }
140
+
141
+ /**
142
+ * Load the keys file over an env. A missing file is created (0600) and is not a refusal. `configured` = the key names that have a row
143
+ * set up in Settings (`config.providers`): only those file values reach `env`.
144
+ * @param {{ env?: Record<string,string|undefined>, home?: string, configured?: string[] }} [opts]
121
145
  * @returns {KeysLoad}
122
146
  */
123
147
  export function loadKeysEnv(opts = {}) {
124
148
  const base = opts.env ?? process.env;
125
149
  const file = keysFilePath(opts.home);
126
150
  const path = shownPath(opts.home);
127
- const knownShell = (parsed) => KEY_NAMES.filter((n) => base[n] && !parsed[n]);
151
+ const configured = (opts.configured ?? []).filter(isKeyName); // defence in depth: a non-key name in config.json never reaches env
152
+ const knownShell = (parsed) => configured.filter((n) => base[n] && !parsed[n]);
128
153
  /** @param {string} refusal @param {boolean} exists @returns {KeysLoad} */
129
154
  const refused = (refusal, exists) => ({
130
- ok: false, path, exists, names: [], shellOnly: [], refusal, env: { ...base },
155
+ ok: false, path, exists, names: [], shellOnly: [], keyNames: [], refusal, env: { ...base },
131
156
  });
132
157
  let fd;
133
158
  let created = false;
@@ -145,13 +170,13 @@ export function loadKeysEnv(opts = {}) {
145
170
  const parsed = parseKeysText(readFileSync(fd, 'utf8'));
146
171
  /** @type {Record<string,string|undefined>} */
147
172
  const env = { ...base };
148
- // C4 (amendment 16): only the known key names reach the env (and so a child). Any other name in the file is listed in `names`
149
- // for Settings but its value stays here — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
150
- for (const name of KEY_NAMES) {
173
+ // C4 (amendment 16), M4d amendment 6: only a name whose row is set up in Settings reaches the env (and so a child). Any other name in the
174
+ // file stays here (a non-key name is not even listed) — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
175
+ for (const name of configured) {
151
176
  if (!env[name] && Object.hasOwn(parsed, name)) env[name] = parsed[name];
152
177
  }
153
178
  return {
154
- ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
179
+ ok: true, path, exists: true, names: Object.entries(parsed).filter(([n, v]) => v !== '' && isKeyName(n)).map(([n]) => n).sort(), shellOnly: knownShell(parsed), keyNames: [...new Set(configured)].filter((n) => env[n]).sort(), refusal: null, env,
155
180
  };
156
181
  } catch (/** @type {any} */ e) {
157
182
  return refused(`Your keys file ${path} could not be read (${e?.code ?? 'error'}).`, created || e?.code !== 'ENOENT');
@@ -160,6 +185,16 @@ export function loadKeysEnv(opts = {}) {
160
185
  }
161
186
  }
162
187
 
188
+ /**
189
+ * The key names that have a row set up in Settings (a `config.providers` entry). A broken config reads as none here: the file is
190
+ * still listed, and whoever reads the config refuses it by name.
191
+ * @param {string|undefined} home
192
+ * @returns {string[]}
193
+ */
194
+ function configuredNames(home) {
195
+ try { return Object.keys(readConfig({ home }).providers ?? {}); } catch { return []; }
196
+ }
197
+
163
198
  /**
164
199
  * The door helper the CLI and the panel call. Loads the file only when the caller is on the
165
200
  * REAL environment, or names a home explicitly (a test), or a test process (`configDoorHome`) with
@@ -175,8 +210,8 @@ export function keysForDoor(deps = {}) {
175
210
  const testNoHome = door.skip && home === undefined;
176
211
  if ((deps.env !== undefined && home === undefined) || testNoHome) {
177
212
  return {
178
- ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], refusal: null, env: { ...(deps.env ?? shell) },
213
+ ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], keyNames: [], refusal: null, env: { ...(deps.env ?? shell) },
179
214
  };
180
215
  }
181
- return { ...loadKeysEnv({ env: deps.env, home }), skipped: false };
216
+ return { ...loadKeysEnv({ env: deps.env, home, configured: configuredNames(home) }), skipped: false };
182
217
  }
package/src/model-step.js CHANGED
@@ -29,15 +29,20 @@ import { GateRefusal } from './primitives.js';
29
29
  import { ConfigError } from './config.js';
30
30
 
31
31
  import {
32
- makeProvider, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
32
+ makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
33
33
  } from './provider.js';
34
34
 
35
- // F27: DeepSeek's `chat/completions` can send HTTP 200 + headers + one byte
35
+ // F27: a provider's `chat/completions` can send HTTP 200 + headers + one byte
36
36
  // then nothing — a "zombie stream" that `timeoutMs`'s idle bound never
37
37
  // trips on. `deadlineMs` is bare-agent's TOTAL wall-clock ceiling
38
38
  // (`code: 'EDEADLINE'`, `retryable: false`) — deliberately shorter than
39
39
  // `timeoutMs` so a hung request reds well inside the idle bound. Frozen +
40
40
  // exported so a test can assert on the live call's actual config.
41
+ /** How much of a malformed tool call's raw arguments is logged/shown (bare-agent hands over all of it). */
42
+ const RAW_ARGS_BOUND = 2000;
43
+ /** The raw text cut at `RAW_ARGS_BOUND` chars with the cut said out loud, never silently. @param {string} raw */
44
+ const boundRaw = (raw) => (raw.length > RAW_ARGS_BOUND ? `${raw.slice(0, RAW_ARGS_BOUND)}… (${raw.length - RAW_ARGS_BOUND} more chars)` : raw);
45
+
41
46
  export const LIVE_PROVIDER_OPTIONS = Object.freeze({ timeoutMs: 300_000, deadlineMs: 240_000 });
42
47
 
43
48
  const TRANSPORT_CODES = Object.freeze([
@@ -236,7 +241,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
236
241
 
237
242
  /**
238
243
  * @param {object} opts
239
- * @param {string} [opts.slot] - a `src/provider.js` PROVIDER_SLOTS name; required when `provider` isn't injected.
244
+ * @param {string} [opts.slot] - a provider row (the name of a key in the keys file); required when `provider` isn't injected.
240
245
  * @param {string} [opts.model] - overrides the slot's default model.
241
246
  * @param {string} opts.spendPath - the run's spend.jsonl (never a second ledger).
242
247
  * @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
@@ -260,7 +265,7 @@ export function makeLiveModelStep({
260
265
  let prices = null;
261
266
  if (live) {
262
267
  // makeProvider throws synchronously on a missing/bad key, an unknown
263
- // slot, or an unrated model — never let that escape as an unhandled
268
+ // slot, or a model that is not ticked in Settings with both prices — never let that escape as an unhandled
264
269
  // rejection out of the ralph loop; a step's own model failure is
265
270
  // always a red, never a crash (rule 5).
266
271
  try {
@@ -275,7 +280,7 @@ export function makeLiveModelStep({
275
280
  // a call that never happened). A row that names a model must carry its
276
281
  // tokens (appendAudit refuses it otherwise), so the model is not named.
277
282
  return {
278
- ok: false, red: `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
283
+ ok: false, red: err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
279
284
  };
280
285
  }
281
286
  }
@@ -451,12 +456,9 @@ export function makeLiveModelStep({
451
456
  if (noToolCallStreak >= 2) {
452
457
  const malformed = provider?.lastMalformedToolCall ?? null;
453
458
  if (malformed) {
454
- // bare-agent >=0.48 delivers `rawArguments` only when the provider
455
- // was built with `exposeMalformedArgs: true`; upstream caps it and
456
- // sets `rawTruncated` when clipped. Absent -> no "; raw:" suffix.
457
- const rawSuffix = malformed.rawArguments !== undefined
458
- ? `; raw: ${malformed.rawArguments}${malformed.rawTruncated === true ? ' (truncated)' : ''}`
459
- : '';
459
+ // bare-agent >=0.50 delivers the FULL `rawArguments` (verbatim, uncapped; `rawTruncated` is never set), and only when the provider was
460
+ // built with `exposeMalformedArgs: true`. We bound what is logged and shown, with the cut said out loud. Absent -> no "; raw:" suffix.
461
+ const rawSuffix = malformed.rawArguments !== undefined ? `; raw: ${boundRaw(malformed.rawArguments)}` : '';
460
462
  return {
461
463
  ok: false,
462
464
  red: `the tool call's arguments were not valid JSON twice in a row (${malformed.error})${rawSuffix}`,
package/src/monthly.js CHANGED
@@ -100,6 +100,7 @@ function reduceRow(row) {
100
100
  t: tokensOf(row.tokens),
101
101
  w: Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null,
102
102
  p: typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED,
103
+ ...(typeof row.model === 'string' && row.model !== '' ? { m: row.model } : {}),
103
104
  ...(row.at === undefined ? {} : { a: row.at }),
104
105
  };
105
106
  }
@@ -171,6 +172,8 @@ export function spendSummary(opts = {}) {
171
172
  const month = newBucket();
172
173
  /** @type {Record<string, {label: string, month: ReturnType<typeof newBucket>, total: ReturnType<typeof newBucket>}>} */
173
174
  const byProvider = {};
175
+ /** Tokens per provider key per model, from the rows that name their model (a row that names none, or a rolled row from before this, counts in no model). @type {Record<string, Record<string, number>>} */
176
+ const byModel = {};
174
177
  let undatedRows = 0;
175
178
  const add = (b, usd, complete, tokens, wall) => {
176
179
  b.rows += 1; b.usd += usd; b.tokens += tokens;
@@ -183,8 +186,12 @@ export function spendSummary(opts = {}) {
183
186
  for (const dir of namedDirs(record)) {
184
187
  for (const row of rolled.get(dir) ?? diskRows(dir)) {
185
188
  const {
186
- u: usd, c: complete, t: tokens, w: wall, p: key,
189
+ u: usd, c: complete, t: tokens, w: wall, p: key, m: model,
187
190
  } = row;
191
+ if (model !== undefined) {
192
+ const per = (byModel[key] ??= {});
193
+ per[model] = (per[model] ?? 0) + tokens;
194
+ }
188
195
  const p = (byProvider[key] ??= { label: key, month: newBucket(), total: newBucket() });
189
196
  add(total, usd, complete, tokens, wall);
190
197
  add(p.total, usd, complete, tokens, wall);
@@ -205,6 +212,7 @@ export function spendSummary(opts = {}) {
205
212
  month: fin(month),
206
213
  total: fin(total),
207
214
  byProvider: Object.fromEntries(Object.entries(byProvider).map(([k, v]) => [k, { label: v.label, month: fin(v.month), total: fin(v.total) }])),
215
+ byModel,
208
216
  undatedRows,
209
217
  // Runs from before M4d were never written to runs.jsonl: their money is in no figure here.
210
218
  preM4dRunsNotCounted: true,