fwdloop 0.14.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 (58) hide show
  1. package/bin/fwdloop +106 -31
  2. package/package.json +2 -2
  3. package/src/authoring.js +26 -11
  4. package/src/checked.js +9 -5
  5. package/src/closers.js +5 -0
  6. package/src/config.js +66 -4
  7. package/src/declaration.js +27 -1
  8. package/src/draft-steps.js +79 -0
  9. package/src/drafter.js +54 -15
  10. package/src/flow.js +220 -5
  11. package/src/flowmodel.js +30 -0
  12. package/src/input-facts.js +12 -3
  13. package/src/keysfile.js +51 -16
  14. package/src/model-step.js +13 -11
  15. package/src/monthly.js +9 -1
  16. package/src/panel/author.js +89 -24
  17. package/src/panel/authorcard.js +80 -20
  18. package/src/panel/authorflows.js +72 -21
  19. package/src/panel/authorresume.js +11 -10
  20. package/src/panel/authorstart.js +29 -19
  21. package/src/panel/data.js +62 -21
  22. package/src/panel/index.html +662 -185
  23. package/src/panel/resume.js +3 -3
  24. package/src/panel/server.js +5 -4
  25. package/src/panel/settings.js +138 -80
  26. package/src/panel/spawn.js +15 -9
  27. package/src/provider.js +136 -178
  28. package/src/providershapes.js +7 -7
  29. package/src/runner.js +47 -23
  30. package/src/signed-diff.js +71 -0
  31. package/src/thinking.js +55 -0
  32. package/types/authoring.d.ts +20 -7
  33. package/types/checked.d.ts +6 -4
  34. package/types/closers.d.ts +2 -0
  35. package/types/config.d.ts +9 -1
  36. package/types/draft-steps.d.ts +14 -0
  37. package/types/drafter.d.ts +13 -10
  38. package/types/flow.d.ts +42 -2
  39. package/types/flowmodel.d.ts +16 -0
  40. package/types/input-facts.d.ts +6 -1
  41. package/types/keysfile.d.ts +23 -6
  42. package/types/model-step.d.ts +1 -1
  43. package/types/monthly.d.ts +1 -0
  44. package/types/panel/author.d.ts +78 -6
  45. package/types/panel/authorcard.d.ts +53 -8
  46. package/types/panel/authorflows.d.ts +68 -6
  47. package/types/panel/authorresume.d.ts +2 -1
  48. package/types/panel/authorstart.d.ts +17 -6
  49. package/types/panel/data.d.ts +10 -6
  50. package/types/panel/resume.d.ts +2 -1
  51. package/types/panel/server.d.ts +3 -1
  52. package/types/panel/settings.d.ts +3 -1
  53. package/types/panel/spawn.d.ts +13 -4
  54. package/types/provider.d.ts +94 -284
  55. package/types/providershapes.d.ts +3 -4
  56. package/types/runner.d.ts +2 -4
  57. package/types/signed-diff.d.ts +10 -0
  58. package/types/thinking.d.ts +25 -0
package/bin/fwdloop CHANGED
@@ -33,8 +33,9 @@ import { makeLiveModelStep } from '../src/model-step.js';
33
33
  import { sendViaPrimitive } from '../src/send.js';
34
34
  import { resolvePrimitives } from '../src/primitives.js';
35
35
  import {
36
- checkKeyPreflight, resolveSlot, resolvePrices, readPriceConfig, ceilingCostUsd,
36
+ checkKeyPreflight, resolveUsableModel, pickTicked, readPriceConfig, ceilingCostUsd,
37
37
  } from '../src/provider.js';
38
+ import { readModelRecord } from '../src/flowmodel.js';
38
39
  import { configDoorHome } from '../src/config.js';
39
40
  import {
40
41
  claimHold, settleHold, nameRunDir, monthlyRefusalText, ConfigError,
@@ -48,11 +49,9 @@ import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.
48
49
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
49
50
  import { userInfo } from 'node:os';
50
51
 
51
- // The baseline model (project rule, CLAUDE.md/AGENT_RULES: "deepseek-flash
52
- // ... Never Claude for fwdloop's own runs") — the ONE provider slot this CLI
53
- // drives. `PROVIDER_SLOTS.deepseek.envVar` is `DEEPSEEK_API_KEY`; this CLI
54
- // never reads a key any other way and never prints it.
55
- const MODEL_SLOT = 'deepseek';
52
+ // This CLI drives no fixed provider (M4d amendment 6). A job runs with the model recorded beside it (`model.json`, written when it was drafted:
53
+ // the provider is the name of a key, its key is read from the env under that name and never printed); `draft` takes `--model` (+ `--provider`).
54
+ // Whether that model may be used is `resolveUsableModel` (ticked in Settings > Providers with both prices): this file names no model and no price.
56
55
 
57
56
  /**
58
57
  * M4d: the ONE place a keyed command gets its env — the shell env with the keys file
@@ -60,11 +59,12 @@ const MODEL_SLOT = 'deepseek';
60
59
  * start. A file other users can read is refused here (ruling 1A), before any dir or ledger
61
60
  * write, at $0. process.env is never mutated: the merged env is handed down by hand.
62
61
  */
63
- function keyedEnv() {
62
+ function keyedLoad() {
64
63
  const loaded = keysForDoor();
65
64
  if (!loaded.ok) fail(String(loaded.refusal));
66
- return loaded.env;
65
+ return loaded;
67
66
  }
67
+ const keyedEnv = () => keyedLoad().env;
68
68
 
69
69
  /**
70
70
  * M4d piece 3: the monthly check, at the ONE seam all three money doors (`run`, `resume`, `draft`) call,
@@ -75,6 +75,8 @@ function keyedEnv() {
75
75
  * which settles it as "process gone").
76
76
  * @returns {{ addRunDir: (d: string) => void, nameRunDir: (d: string) => void }}
77
77
  */
78
+ const NO_CONFIG_HOME_REFUSAL = 'NODE_ENV=test is set without FWDLOOP_CONFIG_HOME, so the keys file, prices and monthly limit would be skipped. Nothing spent. Unset NODE_ENV, or set FWDLOOP_CONFIG_HOME.';
79
+
78
80
  function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }) {
79
81
  const door = configDoorHome();
80
82
  const home = door.home;
@@ -84,7 +86,7 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
84
86
  // a real provider call here would spend with no keys file, prices, limit or record.
85
87
  const hook = what === 'draft' ? 'FWDLOOP_TEST_DRAFT_PROVIDER' : 'FWDLOOP_TEST_MODEL_STEP';
86
88
  if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
87
- fail('NODE_ENV=test is set without FWDLOOP_CONFIG_HOME, so the keys file, prices and monthly limit would be skipped. Nothing spent. Unset NODE_ENV, or set FWDLOOP_CONFIG_HOME.');
89
+ fail(NO_CONFIG_HOME_REFUSAL);
88
90
  }
89
91
  return { addRunDir: () => {}, nameRunDir: () => {} };
90
92
  }
@@ -142,8 +144,8 @@ function today() {
142
144
  }
143
145
 
144
146
  /**
145
- * Build the run's `modelStep`. Live by default (`makeLiveModelStep` against
146
- * `MODEL_SLOT`, refusing an unset/empty/whitespace key via
147
+ * Build the run's `modelStep` and its per-round hold (`{ modelStep, ceilingUsd }`). Live by default (`makeLiveModelStep` against
148
+ * the job's recorded provider, refusing an unset/empty/whitespace key via
147
149
  * `checkKeyPreflight` BEFORE this function returns — i.e. before the caller
148
150
  * has created a run dir or written any book row).
149
151
  *
@@ -156,18 +158,57 @@ function today() {
156
158
  * be hit by a user typing `--something`. This is how the test suite drives
157
159
  * every CLI scenario at $0 with zero chance of a real network call.
158
160
  */
159
- async function resolveModelStep(spendPath, env) {
161
+ async function resolveModelStep(spendPath, env, flowDir, named = {}) {
160
162
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
161
163
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
162
164
  const mod = await import(pathToFileURL(modulePath).href);
163
165
  if (typeof mod.default !== 'function') {
164
166
  throw new Error(`FWDLOOP_TEST_MODEL_STEP module "${modulePath}" has no default export function`);
165
167
  }
166
- return mod.default({ spendPath });
168
+ // A test double has no model of its own. When Settings has one model ticked with both prices its hold applies (so a cap-halt
169
+ // is exercised the way a live run's is); with none, the double holds nothing. It is never refused here: it spends nothing.
170
+ const modelStep = await mod.default({ spendPath });
171
+ let usable = null;
172
+ try {
173
+ const rec = configDoorHome().skip ? null : readModelRecord(flowDir);
174
+ usable = rec === null ? null : resolveUsableModel(rec.slot, { config: readPriceConfig(), model: rec.model });
175
+ } catch (err) {
176
+ if (!(err instanceof ConfigError)) throw err; // a broken config is refused by name at the monthly hold, right after this
177
+ }
178
+ return { modelStep, ...(usable?.ok ? { ceilingUsd: ceilingCostUsd(usable.rates) } : {}) };
179
+ }
180
+ // A test process with no config home reads no Settings: say why, not "tick a model".
181
+ if (configDoorHome().skip) throw new Error(NO_CONFIG_HOME_REFUSAL);
182
+ // The ONE decision of which model runs and at what price (M4d amendments 5 and 6): the model recorded with the job (a job drafted before the record
183
+ // existed takes `--model`), refused by name, at $0, before a run dir or a book row exists. The per-round hold is that model's own Settings price times the token bounds.
184
+ let usable;
185
+ let slot;
186
+ try {
187
+ const config = readPriceConfig();
188
+ const rec = readModelRecord(flowDir);
189
+ if (rec !== null && named.model !== undefined && (named.model !== rec.model || (named.provider !== undefined && named.provider !== rec.slot))) {
190
+ throw new Error(`This job already has its model recorded (${rec.slot} · ${rec.model}); --model cannot change it.`);
191
+ }
192
+ let pick = rec;
193
+ if (pick === null) {
194
+ if (named.model === undefined) throw new Error('This job has no model recorded. Name one with --model <id>, a model ticked in Settings > Providers with both prices.');
195
+ const p = pickTicked(config, named);
196
+ if (!p.ok) throw new Error(p.say);
197
+ pick = p;
198
+ }
199
+ slot = pick.slot;
200
+ const keyCheck = checkKeyPreflight(slot, env);
201
+ if (!keyCheck.ok) throw new Error(keyCheck.message);
202
+ usable = resolveUsableModel(slot, { config, model: pick.model });
203
+ } catch (err) {
204
+ if (!(err instanceof ConfigError)) throw err;
205
+ throw new Error(`${err.message} — refusing to start rather than guess the price. Nothing spent.`);
167
206
  }
168
- const keyCheck = checkKeyPreflight(MODEL_SLOT, env);
169
- if (!keyCheck.ok) throw new Error(keyCheck.message);
170
- return makeLiveModelStep({ slot: MODEL_SLOT, spendPath, env });
207
+ if (!usable.ok) throw new Error(usable.say);
208
+ return {
209
+ modelStep: makeLiveModelStep({ slot, model: usable.model, spendPath, env }),
210
+ ceilingUsd: ceilingCostUsd(usable.rates),
211
+ };
171
212
  }
172
213
 
173
214
  function parseSourceFlags(list) {
@@ -249,6 +290,8 @@ async function cmdRun(rest) {
249
290
  root: { type: 'string' },
250
291
  source: { type: 'string', multiple: true, default: [] },
251
292
  'run-id': { type: 'string' },
293
+ // a job drafted before its model was recorded: the model it runs with (a ticked line); --provider only if two keys tick the same id
294
+ model: { type: 'string' }, provider: { type: 'string' },
252
295
  },
253
296
  allowPositionals: true,
254
297
  });
@@ -321,8 +364,9 @@ async function cmdRun(rest) {
321
364
  // here — before ANY directory for this run is created.
322
365
  const spendPath = join(runDir, 'spend.jsonl');
323
366
  let modelStep;
367
+ let ceilingUsd;
324
368
  try {
325
- modelStep = await resolveModelStep(spendPath, env);
369
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
326
370
  } catch (err) {
327
371
  fail(err.message);
328
372
  return;
@@ -354,6 +398,7 @@ async function cmdRun(rest) {
354
398
  sources,
355
399
  catalogue,
356
400
  modelStep,
401
+ ceilingUsd,
357
402
  askStep: makeParkingAskStep(),
358
403
  sendStep: sendViaPrimitive,
359
404
  primitives,
@@ -543,6 +588,7 @@ async function cmdResume(rest) {
543
588
  options: {
544
589
  flow: { type: 'string' },
545
590
  root: { type: 'string' },
591
+ model: { type: 'string' }, provider: { type: 'string' },
546
592
  },
547
593
  allowPositionals: true,
548
594
  });
@@ -574,8 +620,9 @@ async function cmdResume(rest) {
574
620
 
575
621
  const spendPath = join(runDir, 'spend.jsonl');
576
622
  let modelStep;
623
+ let ceilingUsd;
577
624
  try {
578
- modelStep = await resolveModelStep(spendPath, env);
625
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
579
626
  } catch (err) {
580
627
  fail(err.message);
581
628
  return;
@@ -619,6 +666,7 @@ async function cmdResume(rest) {
619
666
  runId,
620
667
  catalogue,
621
668
  modelStep,
669
+ ceilingUsd,
622
670
  sendStep: sendViaPrimitive,
623
671
  primitives,
624
672
  primitiveReds,
@@ -642,6 +690,7 @@ async function cmdContinue(rest) {
642
690
  options: {
643
691
  flow: { type: 'string' },
644
692
  root: { type: 'string' },
693
+ model: { type: 'string' }, provider: { type: 'string' },
645
694
  },
646
695
  allowPositionals: true,
647
696
  });
@@ -671,8 +720,9 @@ async function cmdContinue(rest) {
671
720
 
672
721
  const spendPath = join(runDir, 'spend.jsonl');
673
722
  let modelStep;
723
+ let ceilingUsd;
674
724
  try {
675
- modelStep = await resolveModelStep(spendPath, env);
725
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
676
726
  } catch (err) {
677
727
  fail(err.message);
678
728
  return;
@@ -706,6 +756,7 @@ async function cmdContinue(rest) {
706
756
  runId,
707
757
  catalogue,
708
758
  modelStep,
759
+ ceilingUsd,
709
760
  sendStep: sendViaPrimitive,
710
761
  primitives,
711
762
  primitiveReds,
@@ -762,10 +813,14 @@ async function cmdDraft(rest) {
762
813
  out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' }, budget: { type: 'string' },
763
814
  // M4e amendment 24 item 4: the redraft after the human's answers never asks (the panel passes this; a plain draft may ask on try 3)
764
815
  'no-questions': { type: 'boolean' },
816
+ // M4d amendment 6: the model that drafts (and then runs) the job - a line ticked in Settings > Providers; --provider only if two keys tick the same id.
817
+ // --thinking is the Chat "Thinking on" tick (drafting only; off unless given).
818
+ model: { type: 'string' }, provider: { type: 'string' }, thinking: { type: 'boolean' },
765
819
  },
766
820
  allowPositionals: true,
767
821
  });
768
- const env = keyedEnv();
822
+ const keysLoad = keyedLoad();
823
+ const { env } = keysLoad;
769
824
  const proseFile = positionals[0];
770
825
  if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>]');
771
826
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
@@ -775,19 +830,35 @@ async function cmdDraft(rest) {
775
830
  const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
776
831
  injected = await mod.default();
777
832
  }
778
- // The key preflight comes first (draftToDir repeats it), so an unset key keeps its own message ahead of the NODE_ENV refusal.
833
+ // The model is named by the caller (a ticked line): refused by name at $0 when it is not. An injected test provider carries its own.
834
+ let pick = {};
779
835
  if (injected.provider == null) {
780
- const refusal = draftKeyRefusal(MODEL_SLOT, env);
836
+ if (configDoorHome().skip) fail(NO_CONFIG_HOME_REFUSAL);
837
+ try {
838
+ const p = pickTicked(readPriceConfig(), values);
839
+ if (!p.ok) fail(`draft refused at $0 — ${p.say}`);
840
+ pick = { slot: p.slot, model: p.model };
841
+ } catch (err) {
842
+ if (!(err instanceof ConfigError)) throw err;
843
+ fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
844
+ }
845
+ // The key preflight (draftToDir repeats it).
846
+ const refusal = draftKeyRefusal(pick.slot, env);
781
847
  if (refusal !== null) fail(`draft refused at $0 — ${refusal}`);
782
- }
783
- // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced by the
784
- // ONE price lookup (an injected test provider carries its own rates).
848
+ } else if (values.model !== undefined) pick = { slot: values.provider, model: values.model };
849
+ // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced from the
850
+ // picked model's own Settings prices (an injected test provider carries its own rates). A model that is not
851
+ // ticked with both prices is refused here by name, at $0, before the monthly hold or any draft folder (M4d amendment 5).
785
852
  let ceiling;
786
853
  try {
787
- const priceConfig = readPriceConfig();
788
- const modelId = injected.modelId ?? resolveSlot('deepseek', { config: priceConfig }).model;
789
- const prices = injected.rates ? { rates: injected.rates } : resolvePrices(modelId, { slot: 'deepseek', config: priceConfig });
790
- ceiling = ceilingCostUsd(modelId, undefined, { prices });
854
+ let rates = injected.rates;
855
+ if (!rates) {
856
+ if (configDoorHome().skip) fail(NO_CONFIG_HOME_REFUSAL);
857
+ const usable = resolveUsableModel(pick.slot, { config: readPriceConfig(), model: pick.model });
858
+ if (!usable.ok) fail(`draft refused at $0 — ${usable.say}`);
859
+ rates = usable.rates;
860
+ }
861
+ ceiling = ceilingCostUsd(rates);
791
862
  } catch (err) {
792
863
  if (!(err instanceof ConfigError)) throw err;
793
864
  fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
@@ -802,7 +873,10 @@ async function cmdDraft(rest) {
802
873
  name: values.name,
803
874
  budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
804
875
  noQuestions: values['no-questions'] === true,
876
+ draftThinking: values.thinking === true ? 'on' : 'off',
805
877
  env,
878
+ keyNames: keysLoad.keyNames,
879
+ ...pick,
806
880
  ...injected,
807
881
  });
808
882
  const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
@@ -830,7 +904,8 @@ async function cmdSign(rest) {
830
904
  options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
831
905
  allowPositionals: true,
832
906
  });
833
- const env = keyedEnv(); // sign takes no key, but its leak sweep must know the file's keys too
907
+ const keysLoad = keyedLoad(); // sign takes no key, but its leak sweep must know the file's keys too
908
+ const env = keysLoad.env;
834
909
  const dir = positionals[0];
835
910
  if (!dir) fail('sign: a draft dir is required — fwdloop sign <dir> --approve <hash>');
836
911
  // M4e amendments 24/25: a plan with a question is not signed from here — the answers are taken in the panel. One check, also run again inside signDraft.
@@ -846,7 +921,7 @@ async function cmdSign(rest) {
846
921
  const typed = await confirmTypedName({ name: flowName });
847
922
  if (!typed.ok) fail(`sign refused — ${typed.red}`);
848
923
  const result = signDraft({
849
- dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env,
924
+ dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env, keyNames: keysLoad.keyNames,
850
925
  });
851
926
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
852
927
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -49,7 +49,7 @@
49
49
  "NOTICE"
50
50
  ],
51
51
  "dependencies": {
52
- "bare-agent": "^0.49.0",
52
+ "bare-agent": "^0.52.0",
53
53
  "bareguard": "^0.21.2",
54
54
  "litectx": "^0.32.0"
55
55
  },
package/src/authoring.js CHANGED
@@ -27,7 +27,9 @@ import { WIRED_VERBS } from './primitives.js';
27
27
  import { canonicalBytes } from './signature.js';
28
28
  import { writeFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
29
29
  import { checkSendDestination } from './runner.js';
30
- import { PROVIDER_SLOTS, checkKeyPreflight, appendSpendRow } from './provider.js';
30
+ import { checkKeyPreflight, appendSpendRow } from './provider.js';
31
+ import { keyValues } from './keysfile.js';
32
+ import { readModelRecord, writeModelRecord } from './flowmodel.js';
31
33
  import { writeDraftSpend } from './draftspend.js';
32
34
  import { writeSetup } from './setup.js';
33
35
 
@@ -246,7 +248,7 @@ export function draftKeyRefusal(slot, env) {
246
248
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
247
249
  */
248
250
  export async function draftToDir({
249
- proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId, noQuestions = false,
251
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId, noQuestions = false,
250
252
  }) {
251
253
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
252
254
  const nameCheck = checkFlowName(name);
@@ -267,12 +269,11 @@ export async function draftToDir({
267
269
  if (!read.ok) return refuse([String(read.red)]);
268
270
  const prose = { text: String(read.text) };
269
271
  const injected = provider != null;
270
- const secretVar = PROVIDER_SLOTS[slot]?.envVar;
271
272
  if (!injected) {
272
273
  const refusal = draftKeyRefusal(slot, env);
273
274
  if (refusal !== null) return refuse([refusal]);
274
275
  }
275
- const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
276
+ const secrets = keyValues(env, [...new Set([...(keyNames ?? []), ...(typeof slot === 'string' ? [slot] : [])])]);
276
277
  if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
277
278
  // Red messages can echo what a provider's error body echoed (a key): scrubbed like every file, before anything prints them.
278
279
  const cleanReds = (reds) => (reds ?? []).map((r) => scrub(String(r), secrets));
@@ -305,7 +306,7 @@ export async function draftToDir({
305
306
  }
306
307
  };
307
308
  const result = await draft({
308
- proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env, onBook, offerQuestions: !noQuestions,
309
+ proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env, onBook, offerQuestions: !noQuestions, draftThinking,
309
310
  });
310
311
  if (result.stop === 'pre-flight') {
311
312
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -323,6 +324,9 @@ export async function draftToDir({
323
324
  files['prose.txt'] = prose.text; // verbatim
324
325
  const targetText = dj({ root, name });
325
326
  files['target.json'] = targetText;
327
+ // M4d am6 item 6: the pick is remembered beside the draft (written below as model.json, outside the signed files) so the signed job runs with it.
328
+ const recordModel = model ?? result.modelId ?? modelId;
329
+ const pick = typeof slot === 'string' && typeof recordModel === 'string' && recordModel !== '' ? { slot, model: recordModel } : null;
326
330
  // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
327
331
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
328
332
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
@@ -330,7 +334,7 @@ export async function draftToDir({
330
334
  files['log.json'] = scrub(dj({
331
335
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
332
336
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
333
- revisions: result.revisions, log: result.log,
337
+ revisions: result.revisions, thinking: result.thinking, inputs: result.inputs, log: result.log,
334
338
  }), secrets);
335
339
  let hash = null;
336
340
  if (result.ok) {
@@ -372,6 +376,7 @@ export async function draftToDir({
372
376
  wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
373
377
  });
374
378
  for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
379
+ if (pick !== null) writeModelRecord(dir, pick);
375
380
  leaks = sweepForSecrets(dir, secrets);
376
381
  if (leaks > 0) {
377
382
  const red = `scrub: ${leaks} file(s) in the draft dir contain a key value`;
@@ -391,17 +396,20 @@ export async function draftToDir({
391
396
  * The human step, $0. Every refusal returns reds and writes NO flow.
392
397
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
393
398
  * `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.
399
+ * M6: `replaces: {flowHash}` (a draft opened from an existing signed job, carrying that job's signature hash) makes this sign REPLACE that job
400
+ * (`writeFlow` checks the hash is still the job's); without it a taken name is refused as ever.
401
+ * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, keyNames?: string[], sessionDir?: string, replaces?: {flowHash: string}}} a
394
402
  */
395
403
  export function signDraft({
396
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, sessionDir,
404
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, keyNames, sessionDir, replaces,
397
405
  }) {
398
406
  const refuse = (...reds) => ({ ok: false, reds });
399
407
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
400
408
  const openQuestion = questionsRefusal(dir);
401
409
  if (openQuestion !== null) return refuse(`sign: ${openQuestion}`);
402
- // Sign is $0 and takes no key, so it can only sweep for keys present in ITS env (any provider slot's).
410
+ // Sign is $0 and takes no key, so it can only sweep for the keys it is told of (`keyNames`, the rows set up in Settings).
403
411
  // With none set the sweep is skipped: the marker above and the missing spec.hash are then the guard.
404
- const keys = Object.values(PROVIDER_SLOTS).map((p) => env[p.envVar]).filter(Boolean);
412
+ const keys = keyValues(env, keyNames);
405
413
  if (sweepForSecrets(dir, keys) > 0) return refuse(`sign: "${dir}" contains a key value — nothing signed`);
406
414
  if (typeof approve !== 'string' || approve === '') return refuse('sign: --approve <hash> is required');
407
415
  const read = (f) => readFileInside(dir, f);
@@ -448,7 +456,7 @@ export function signDraft({
448
456
  if (reds.length) return { ok: false, reds };
449
457
 
450
458
  const written = writeFlow({
451
- root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
459
+ root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives, replaces,
452
460
  });
453
461
  if (!written.ok) return { ok: false, reds: written.reds };
454
462
  // 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
@@ -456,5 +464,12 @@ export function signDraft({
456
464
  const setup = writeSetup({
457
465
  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)),
458
466
  });
459
- return { ok: true, flowDir: written.dir, signature: written.signature, setup };
467
+ // M4d am6 item 6: the draft's model pick goes into the flow folder beside the signed files; a run reads it from there. The flow IS signed by now,
468
+ // so a failure to write it never un-signs: `modelRecord.ok:false` is returned for the caller to say (the run is then refused by name).
469
+ const pickRecord = readModelRecord(dir);
470
+ let modelRecord = { ok: true, recorded: pickRecord !== null };
471
+ if (pickRecord !== null) {
472
+ try { writeModelRecord(written.dir, pickRecord); } catch (e) { modelRecord = { ok: false, recorded: false, why: /** @type {any} */ (e)?.code ?? 'error' }; }
473
+ }
474
+ return { ok: true, flowDir: written.dir, signature: written.signature, setup, modelRecord };
460
475
  }
package/src/checked.js CHANGED
@@ -8,18 +8,21 @@
8
8
  // NOT CHECKED is the drafter's own reading (a list of short phrases it wrote in the same call). It is information only: shown with its label,
9
9
  // never signed, never in the readout, never in the spec hash. What this throws away: anything the drafter did not list; the list is not complete.
10
10
 
11
- /** The label that always sits with the "Not checked" list. */
12
- export const NOT_CHECKED_LABEL = "the drafter's own reading, not a guarantee";
11
+ /** The label that always sits with the "Not checked" list (am41 item 3: the ONE place these words live; the Job tab and the Chat card read it off their payloads). */
12
+ export const NOT_CHECKED_LABEL = "not checked (the AI's own reading)";
13
13
 
14
14
  const list = (xs) => xs.join(', ');
15
15
 
16
16
  /**
17
17
  * One entry per step, in plan order: the plain sentences for what its typed close checks.
18
- * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true)
18
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
19
+ * askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
19
20
  * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
20
21
  */
21
- export function checkedLines(declaration, { hasAsk = true } = {}) {
22
+ export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
22
23
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
24
+ if (Array.isArray(askLines)) hasAsk = askLines.length > 0;
25
+ const lastAsk = Array.isArray(askLines) ? steps.reduce((m, st, i) => (askLines.includes(st?.fromLine) ? i : m), -1) : -1;
23
26
  return steps.map((st, i) => {
24
27
  const cls = st?.close?.class;
25
28
  const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
@@ -35,7 +38,8 @@ export function checkedLines(declaration, { hasAsk = true } = {}) {
35
38
  if (Number.isInteger(shape.linesPerInvoice)) out.push(`The output comes in blocks of ${shape.linesPerInvoice} lines.`);
36
39
  if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) out.push(`Every block carries: ${list(shape.mustCarry)}.`);
37
40
  } else {
38
- out.push(hasAsk ? 'No machine check of the content: you check it at the ask.' : 'No machine check of the content; the machine checks only that the step happened.');
41
+ if (lastAsk !== -1 && i > lastAsk) out.push('No machine check of the content; you check it after you accept.');
42
+ else out.push(hasAsk ? 'No machine check of the content: you check it at the ask.' : 'No machine check of the content; the machine checks only that the step happened.');
39
43
  }
40
44
  return {
41
45
  step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
package/src/closers.js CHANGED
@@ -74,6 +74,11 @@ const FORMULAS = Object.freeze({
74
74
  sub: (vals) => vals[0] - vals[1],
75
75
  });
76
76
 
77
+ /** An input with cells (M4d amendment 8): a file whose name ends `.csv`. The one decider for "this input can be cited". */
78
+ export function isCellsPath(p) {
79
+ return typeof p === 'string' && p.toLowerCase().endsWith('.csv');
80
+ }
81
+
77
82
  const CELL_RE = /^([a-zA-Z0-9_-]+)!([A-Za-z]+)(\d+)$/;
78
83
  const FORMULA_RE = /^(sum|count|min|max|sub|daysBetween)\((.*)\)$/;
79
84
  const FIELD_REF_RE = /^#([A-Za-z0-9_]+)$/;
package/src/config.js CHANGED
@@ -4,7 +4,11 @@
4
4
  // Shape (unknown top-level fields are kept, never dropped):
5
5
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
6
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)
7
+ // "providers": { "<KEY_NAME>": { "shape": "<shape id>", "baseUrl": "http(s)://…", "legacyMaxTokens": true|false } }, // each optional; a row is a key name from the keys file (M4d amendment 6). An older file's "model" is tolerated and read by nothing.
8
+ // "models": { "<KEY_NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] } } // M4d amendment 3 C: a price per model
9
+ // A models line's price is a PAIR or nothing (`modelsProblem` is the one rule): 0 / 0 typed is a chosen price, a
10
+ // ticked line needs both, a half pair is refused. A slot with no list is migrated on READ (`effectiveModels` in
11
+ // src/provider.js); the file is only rewritten when the person saves.
8
12
  // A price is a finite number above 0; 0, a negative, NaN, Infinity or text is a ConfigError
9
13
  // naming the slot and field — on write AND on read, so a hand-edited 0 can never price a call at $0.
10
14
  // Key VALUES never live here (keys file / shell only): a secret-shaped string is refused on write.
@@ -84,7 +88,7 @@ function secretPaths(node, at, out) {
84
88
  }
85
89
  }
86
90
 
87
- export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl']);
91
+ export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl', 'legacyMaxTokens']);
88
92
 
89
93
  /** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
90
94
  export function providerFieldProblem(field, v) {
@@ -92,6 +96,8 @@ export function providerFieldProblem(field, v) {
92
96
  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
97
  } else if (field === 'shape') {
94
98
  if (!SHAPE_IDS.includes(v)) return `must be one of ${SHAPE_IDS.join(', ')}`;
99
+ } else if (field === 'legacyMaxTokens') {
100
+ if (typeof v !== 'boolean') return 'must be true or false';
95
101
  } else if (field === 'baseUrl') {
96
102
  if (typeof v !== 'string' || !(v === '' || /^https?:\/\/\S+$/.test(v))) return 'must be empty (the default) or an http(s) address';
97
103
  } else return 'is not a provider field';
@@ -103,6 +109,45 @@ export const cleanBaseUrl = (v) => v.replace(/\/+$/, '');
103
109
 
104
110
  const isPrice = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
105
111
 
112
+ /**
113
+ * THE one rule for a slot's model lines (M4d amendment 3 items 7-8), used by config validation and the Settings
114
+ * route. A price is a PAIR (`inPerM` and `outPerM`, each a finite number >= 0 — 0 / 0 typed is a chosen price,
115
+ * recorded so it is never unknown) or neither (null / absent). A ticked line (`use`) needs both. Plain words, or null.
116
+ * @param {any} list
117
+ * @returns {string|null}
118
+ */
119
+ export function modelsProblem(list) {
120
+ if (!Array.isArray(list)) return 'The model list must be a list of lines.';
121
+ const seen = new Set();
122
+ for (const line of list) {
123
+ if (line === null || typeof line !== 'object' || Array.isArray(line)) return 'Each model line must be an object.';
124
+ const bad = providerFieldProblem('model', line.model);
125
+ if (bad) return `The model name ${bad}.`;
126
+ if (seen.has(line.model)) return `The model "${line.model}" is listed twice.`;
127
+ seen.add(line.model);
128
+ if (typeof line.use !== 'boolean') return 'Use must be on or off.';
129
+ const has = (f) => line[f] !== undefined && line[f] !== null;
130
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
131
+ if (has('inPerM') !== has('outPerM')) return 'Fill both price boxes or clear both.';
132
+ if (has('inPerM') && !(isNum(line.inPerM) && isNum(line.outPerM))) return 'A price must be a number, 0 or more.';
133
+ if (line.use && !has('inPerM')) return 'Fill both prices to tick this model.';
134
+ // `thinkingOff` is an older file's field (M4d amendment 5): tolerated so the file loads, read by nothing, dropped on the next save of the list (amendment 7).
135
+ for (const k of Object.keys(line)) if (!['model', 'use', 'inPerM', 'outPerM', 'thinkingOff'].includes(k)) return `A model line has no "${k}" field.`;
136
+ }
137
+ return null;
138
+ }
139
+
140
+ /** @param {any} models */
141
+ function validateModels(models) {
142
+ if (models === undefined) return;
143
+ if (models === null || typeof models !== 'object' || Array.isArray(models)) throw new ConfigError('models must be an object of provider slots');
144
+ for (const [slot, list] of Object.entries(models)) {
145
+ if (!SLOT_RE.test(slot)) throw new ConfigError(`models: "${slot}" is not a provider slot name`);
146
+ const problem = modelsProblem(list);
147
+ if (problem) throw new ConfigError(`models.${slot}: ${problem}`);
148
+ }
149
+ }
150
+
106
151
  /** @param {any} providers */
107
152
  function validateProviders(providers) {
108
153
  if (providers === undefined) return;
@@ -129,6 +174,7 @@ function validateDoc(doc) {
129
174
  throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
130
175
  }
131
176
  validateProviders(doc.providers);
177
+ validateModels(doc.models);
132
178
  if (doc.prices === undefined) return;
133
179
  if (doc.prices === null || typeof doc.prices !== 'object' || Array.isArray(doc.prices)) {
134
180
  throw new ConfigError('prices must be an object of provider slots');
@@ -177,7 +223,7 @@ export function readConfig(opts = {}) {
177
223
 
178
224
  /**
179
225
  * 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`
226
+ * per slot, then per field; `models.<slot>` is replaced whole (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
181
227
  * clears the field). Everything is validated before anything is written; a refusal leaves the file
182
228
  * untouched.
183
229
  * @param {Record<string, any>} patch
@@ -189,7 +235,7 @@ export function updateConfig(patch, opts = {}) {
189
235
  /** @type {Record<string, any>} */
190
236
  const next = { ...cur };
191
237
  for (const [k, v] of Object.entries(patch)) {
192
- if (k === 'prices' || k === 'providers') continue;
238
+ if (k === 'prices' || k === 'providers' || k === 'models') continue;
193
239
  if (v === null) delete next[k];
194
240
  else next[k] = v;
195
241
  }
@@ -239,6 +285,22 @@ export function updateConfig(patch, opts = {}) {
239
285
  else next.providers = providers;
240
286
  }
241
287
  }
288
+ if (patch.models !== undefined) {
289
+ const p = patch.models;
290
+ if (p === null) {
291
+ delete next.models;
292
+ } else {
293
+ if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('models must be an object of provider slots');
294
+ // a slot's list is replaced whole (`null` clears the slot); other slots are kept
295
+ const models = { ...(next.models ?? {}) };
296
+ for (const [slot, list] of Object.entries(p)) {
297
+ if (list === null) delete models[slot];
298
+ else models[slot] = list;
299
+ }
300
+ if (Object.keys(models).length === 0) delete next.models;
301
+ else next.models = models;
302
+ }
303
+ }
242
304
  validateDoc(next);
243
305
  /** @type {string[]} */
244
306
  const leaks = [];