fwdloop 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/fwdloop CHANGED
@@ -25,12 +25,19 @@ import {
25
25
  } from '../src/flow.js';
26
26
  import { loadCatalogue } from '../src/catalogue.js';
27
27
  import {
28
- runFlow, resumeRun, makeParkingAskStep, readAsk,
28
+ runFlow, resumeRun, makeParkingAskStep, readAsk, readRunState,
29
29
  } from '../src/runner.js';
30
30
  import { makeLiveModelStep } from '../src/model-step.js';
31
31
  import { sendViaPrimitive } from '../src/send.js';
32
32
  import { resolvePrimitives } from '../src/primitives.js';
33
- import { checkKeyPreflight } from '../src/provider.js';
33
+ import {
34
+ checkKeyPreflight, resolveSlot, resolvePrices, readPriceConfig, ceilingCostUsd,
35
+ } from '../src/provider.js';
36
+ import { configDoorHome } from '../src/config.js';
37
+ import {
38
+ claimHold, settleHold, monthlyRefusalText, ConfigError,
39
+ } from '../src/monthly.js';
40
+ import { keysForDoor } from '../src/keysfile.js';
34
41
  import {
35
42
  answerAsk, readAskEvidence, normalizeDecision, stripControl, withReopen,
36
43
  } from '../src/ask.js';
@@ -45,6 +52,65 @@ import { userInfo } from 'node:os';
45
52
  // never reads a key any other way and never prints it.
46
53
  const MODEL_SLOT = 'deepseek';
47
54
 
55
+ /**
56
+ * M4d: the ONE place a keyed command gets its env — the shell env with the keys file
57
+ * (`~/.config/fwdloop/.env`) filling what the shell leaves unset, loaded once at command
58
+ * start. A file other users can read is refused here (ruling 1A), before any dir or ledger
59
+ * write, at $0. process.env is never mutated: the merged env is handed down by hand.
60
+ */
61
+ function keyedEnv() {
62
+ const loaded = keysForDoor();
63
+ if (!loaded.ok) fail(String(loaded.refusal));
64
+ return loaded.env;
65
+ }
66
+
67
+ /**
68
+ * M4d piece 3: the monthly check, at the ONE seam all three money doors (`run`, `resume`, `draft`) call,
69
+ * before any spend and before any ledger write. No limit set = a $0 hold row (so the run's spend is counted once a limit is set), no check;
70
+ * a test process with no config home = no row at all. A broken config.json or an unwritable record refuses by name, never "no limit". A hold
71
+ * that does not fit refuses at $0 with the one refusal text. A hold that fits is given back when this
72
+ * process ends or parks (the `exit` hook runs on every exit path; a SIGKILL leaves it for the next check,
73
+ * which settles it as "process gone").
74
+ * @returns {{ addRunDir: (d: string) => void }}
75
+ */
76
+ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }) {
77
+ const door = configDoorHome();
78
+ const home = door.home;
79
+ const also = [];
80
+ if (door.skip) {
81
+ // A test process with no config home skips the money checks. Only an injected test hook may do that;
82
+ // a real provider call here would spend with no keys file, prices, limit or record.
83
+ const hook = what === 'draft' ? 'FWDLOOP_TEST_DRAFT_PROVIDER' : 'FWDLOOP_TEST_MODEL_STEP';
84
+ if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
85
+ 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.');
86
+ }
87
+ return { addRunDir: () => {} };
88
+ }
89
+ let claim;
90
+ try {
91
+ claim = claimHold({
92
+ what, flow, runId, runDir, holdUsd, spentAtHold, home,
93
+ });
94
+ } catch (err) {
95
+ if (!(err instanceof ConfigError)) throw err;
96
+ fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
97
+ }
98
+ if (!claim.ok) fail(monthlyRefusalText(claim.room));
99
+ if (claim.holdId !== null) {
100
+ process.on('exit', () => settleHold({
101
+ holdId: claim.holdId, why: process.exitCode ? 'ended (red)' : 'ended or parked', home, alsoRunDirs: also,
102
+ }));
103
+ }
104
+ return { addRunDir: (d) => also.push(d) };
105
+ }
106
+
107
+ /** The new runs a `rerun` chain started in this process — their spend belongs to this hold's month too. */
108
+ function rerunDirs(result, flowDir) {
109
+ const dirs = [];
110
+ for (let r = result; r && r.outcome === 'rerun'; r = r.newRun) dirs.push(join(flowDir, r.newRunId));
111
+ return dirs;
112
+ }
113
+
48
114
  function fail(message) {
49
115
  process.stderr.write(`fwdloop: ${message}\n`);
50
116
  process.exit(1);
@@ -84,7 +150,7 @@ function today() {
84
150
  * be hit by a user typing `--something`. This is how the test suite drives
85
151
  * every CLI scenario at $0 with zero chance of a real network call.
86
152
  */
87
- async function resolveModelStep(spendPath) {
153
+ async function resolveModelStep(spendPath, env) {
88
154
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
89
155
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
90
156
  const mod = await import(pathToFileURL(modulePath).href);
@@ -93,9 +159,9 @@ async function resolveModelStep(spendPath) {
93
159
  }
94
160
  return mod.default({ spendPath });
95
161
  }
96
- const keyCheck = checkKeyPreflight(MODEL_SLOT);
162
+ const keyCheck = checkKeyPreflight(MODEL_SLOT, env);
97
163
  if (!keyCheck.ok) throw new Error(keyCheck.message);
98
- return makeLiveModelStep({ slot: MODEL_SLOT, spendPath });
164
+ return makeLiveModelStep({ slot: MODEL_SLOT, spendPath, env });
99
165
  }
100
166
 
101
167
  function parseSourceFlags(list) {
@@ -176,6 +242,7 @@ async function cmdRun(rest) {
176
242
  },
177
243
  allowPositionals: true,
178
244
  });
245
+ const env = keyedEnv();
179
246
 
180
247
  const flowName = positionals[0];
181
248
  if (!flowName) fail('run: a flow name is required — fwdloop run <flow> --root <dir> --source <role>=<path> ...');
@@ -227,12 +294,18 @@ async function cmdRun(rest) {
227
294
  const spendPath = join(runDir, 'spend.jsonl');
228
295
  let modelStep;
229
296
  try {
230
- modelStep = await resolveModelStep(spendPath);
297
+ modelStep = await resolveModelStep(spendPath, env);
231
298
  } catch (err) {
232
299
  fail(err.message);
233
300
  return;
234
301
  }
235
302
 
303
+ // M4d piece 3: the monthly check — the hold is the flow's signed per-run cap. Before the run dir exists
304
+ // (runFlow makes it), so a refusal leaves only the refused rows in runs.jsonl.
305
+ const hold = takeMonthlyHold({
306
+ what: 'run', flow: flowName, runId, runDir, holdUsd: arbiter.capUsd,
307
+ });
308
+
236
309
  // Predict the frozen input paths `runFlow`'s own `freezeInputs` will use
237
310
  // (deterministic: `<runDir>/inputs/<id><ext>`) so the primitives map can
238
311
  // be built once, before `runFlow` itself freezes anything. Pure path
@@ -260,6 +333,7 @@ async function cmdRun(rest) {
260
333
  businessDate: today(),
261
334
  });
262
335
 
336
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
263
337
  reportRunResult(result, { rootArg: values.root });
264
338
  }
265
339
 
@@ -444,6 +518,7 @@ async function cmdResume(rest) {
444
518
  },
445
519
  allowPositionals: true,
446
520
  });
521
+ const env = keyedEnv();
447
522
  const runId = positionals[0];
448
523
  if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> --root <dir>');
449
524
  if (!values.flow) fail('resume: --flow <name> is required');
@@ -458,7 +533,7 @@ async function cmdResume(rest) {
458
533
 
459
534
  const read = readFlow({ root, name: flowName, catalogue });
460
535
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
461
- const { declaration } = read;
536
+ const { declaration, arbiter } = read;
462
537
 
463
538
  const runIdCheck = resolveRunDir(join(root, flowName), runId);
464
539
  if (!runIdCheck.ok) fail(runIdCheck.red);
@@ -468,12 +543,19 @@ async function cmdResume(rest) {
468
543
  const spendPath = join(runDir, 'spend.jsonl');
469
544
  let modelStep;
470
545
  try {
471
- modelStep = await resolveModelStep(spendPath);
546
+ modelStep = await resolveModelStep(spendPath, env);
472
547
  } catch (err) {
473
548
  fail(err.message);
474
549
  return;
475
550
  }
476
551
 
552
+ // M4d piece 3: the monthly check — the hold is the signed cap minus what this run already spent (its own
553
+ // state.json; no readable figure = the whole cap, never less).
554
+ const priorSpent = Number.isFinite(readRunState(runDir)?.spent) ? readRunState(runDir).spent : 0;
555
+ const hold = takeMonthlyHold({
556
+ what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, arbiter.capUsd - priorSpent), spentAtHold: priorSpent,
557
+ });
558
+
477
559
  // Resume never re-freezes inputs — the run's own `inputs.json` (written at
478
560
  // park by `freezeInputs`) is the one source of the already-frozen paths a
479
561
  // sandboxed primitive may read.
@@ -511,6 +593,7 @@ async function cmdResume(rest) {
511
593
  businessDate: today(),
512
594
  });
513
595
 
596
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
514
597
  reportRunResult(result, { rootArg: values.root });
515
598
  }
516
599
 
@@ -563,6 +646,7 @@ async function cmdDraft(rest) {
563
646
  },
564
647
  allowPositionals: true,
565
648
  });
649
+ const env = keyedEnv();
566
650
  const proseFile = positionals[0];
567
651
  if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>]');
568
652
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
@@ -572,12 +656,33 @@ async function cmdDraft(rest) {
572
656
  const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
573
657
  injected = await mod.default();
574
658
  }
659
+ // The key preflight comes first (draftToDir repeats it), so an unset key keeps its own message ahead of the NODE_ENV refusal.
660
+ if (injected.provider == null) {
661
+ const keyCheck = checkKeyPreflight('deepseek', env);
662
+ if (!keyCheck.ok) fail(`draft refused at $0 — ${keyCheck.message}`);
663
+ }
664
+ // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced by the
665
+ // ONE price lookup (an injected test provider carries its own rates).
666
+ let ceiling;
667
+ try {
668
+ const priceConfig = readPriceConfig();
669
+ const modelId = injected.modelId ?? resolveSlot('deepseek', { config: priceConfig }).model;
670
+ const prices = injected.rates ? { rates: injected.rates } : resolvePrices(modelId, { slot: 'deepseek', config: priceConfig });
671
+ ceiling = ceilingCostUsd(modelId, undefined, { prices });
672
+ } catch (err) {
673
+ if (!(err instanceof ConfigError)) throw err;
674
+ fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
675
+ }
676
+ takeMonthlyHold({
677
+ what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: ceiling,
678
+ });
575
679
  const result = await draftToDir({
576
680
  proseFile: resolve(proseFile),
577
681
  dir: resolve(values.out),
578
682
  root: resolve(values.root),
579
683
  name: values.name,
580
684
  budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
685
+ env,
581
686
  ...injected,
582
687
  });
583
688
  const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
@@ -601,6 +706,7 @@ async function cmdSign(rest) {
601
706
  options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
602
707
  allowPositionals: true,
603
708
  });
709
+ const env = keyedEnv(); // sign takes no key, but its leak sweep must know the file's keys too
604
710
  const dir = positionals[0];
605
711
  if (!dir) fail('sign: a draft dir is required — fwdloop sign <dir> --approve <hash>');
606
712
  // Amendment 2: a person at a keyboard. TTY check first (cheapest), then the typed flow name; only then
@@ -613,7 +719,7 @@ async function cmdSign(rest) {
613
719
  const typed = await confirmTypedName({ name: flowName });
614
720
  if (!typed.ok) fail(`sign refused — ${typed.red}`);
615
721
  const result = signDraft({
616
- dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username,
722
+ dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env,
617
723
  });
618
724
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
619
725
  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.11.0",
3
+ "version": "0.12.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",
package/src/authoring.js CHANGED
@@ -201,7 +201,7 @@ export async function draftToDir({
201
201
  }
202
202
 
203
203
  const result = await draft({
204
- proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId,
204
+ proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env,
205
205
  });
206
206
  if (result.stop === 'pre-flight') {
207
207
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -248,6 +248,8 @@ export async function draftToDir({
248
248
  try {
249
249
  appendSpendRow(path.join(dir, 'spend.jsonl'), {
250
250
  kind: 'draft',
251
+ provider: slot,
252
+ price: result.price ?? null,
251
253
  model: result.modelId ?? modelId ?? null,
252
254
  modelReturned: result.modelReturned,
253
255
  tokens: result.tokens ?? null,
package/src/config.js ADDED
@@ -0,0 +1,255 @@
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
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
+ export const PRICE_FIELDS = Object.freeze(['inPerM', 'cachedInPerM', 'outPerM']);
57
+ const SLOT_RE = /^[A-Za-z0-9_-]{1,64}$/;
58
+
59
+ // The secret-shape inventory (bareloop src/validate.js SECRET_PATTERNS): known token shapes only,
60
+ // left-bounded so hyphenated words never match.
61
+ const SECRET_PATTERNS = [
62
+ /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
63
+ /(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
64
+ /(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
65
+ /(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
66
+ /(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
67
+ /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
68
+ ];
69
+ const isSecretShaped = (str) => SECRET_PATTERNS.some((re) => re.test(str));
70
+
71
+ /** 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 */
72
+ function secretPaths(node, at, out) {
73
+ if (typeof node === 'string') {
74
+ if (isSecretShaped(node)) out.push(at || '(root)');
75
+ } else if (Array.isArray(node)) {
76
+ node.forEach((v, i) => secretPaths(v, `${at}.${i}`, out));
77
+ } else if (node !== null && typeof node === 'object') {
78
+ for (const [k, v] of Object.entries(node)) {
79
+ const p = at ? `${at}.${k}` : k;
80
+ if (isSecretShaped(k)) out.push(p);
81
+ secretPaths(v, p, out);
82
+ }
83
+ }
84
+ }
85
+
86
+ export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl']);
87
+
88
+ /** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
89
+ export function providerFieldProblem(field, v) {
90
+ if (field === 'model') {
91
+ 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';
92
+ } else if (field === 'shape') {
93
+ if (!SHAPE_IDS.includes(v)) return `must be one of ${SHAPE_IDS.join(', ')}`;
94
+ } else if (field === 'baseUrl') {
95
+ if (typeof v !== 'string' || !(v === '' || /^https?:\/\/\S+$/.test(v))) return 'must be empty (the default) or an http(s) address';
96
+ } else return 'is not a provider field';
97
+ return null;
98
+ }
99
+
100
+ /** A Base URL as stored: trailing slashes dropped. */
101
+ export const cleanBaseUrl = (v) => v.replace(/\/+$/, '');
102
+
103
+ const isPrice = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
104
+
105
+ /** @param {any} providers */
106
+ function validateProviders(providers) {
107
+ if (providers === undefined) return;
108
+ if (providers === null || typeof providers !== 'object' || Array.isArray(providers)) {
109
+ throw new ConfigError('providers must be an object of provider slots');
110
+ }
111
+ for (const [slot, row] of Object.entries(providers)) {
112
+ if (!SLOT_RE.test(slot)) throw new ConfigError(`providers: "${slot}" is not a provider slot name`);
113
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`providers.${slot} must be an object`);
114
+ for (const [field, v] of Object.entries(row)) {
115
+ if (!PROVIDER_FIELDS.includes(field)) throw new ConfigError(`providers.${slot}.${field} is not a provider field (${PROVIDER_FIELDS.join(', ')})`);
116
+ const problem = providerFieldProblem(field, v);
117
+ if (problem) throw new ConfigError(`providers.${slot}.${field} ${problem}`);
118
+ }
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Validate a whole document's known fields; throws ConfigError naming the field.
124
+ * @param {Record<string, any>} doc
125
+ */
126
+ function validateDoc(doc) {
127
+ if (doc.monthlyLimitUsd !== undefined && !isPrice(doc.monthlyLimitUsd)) {
128
+ throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
129
+ }
130
+ validateProviders(doc.providers);
131
+ if (doc.prices === undefined) return;
132
+ if (doc.prices === null || typeof doc.prices !== 'object' || Array.isArray(doc.prices)) {
133
+ throw new ConfigError('prices must be an object of provider slots');
134
+ }
135
+ for (const [slot, row] of Object.entries(doc.prices)) {
136
+ if (!SLOT_RE.test(slot)) throw new ConfigError(`prices: "${slot}" is not a provider slot name`);
137
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`prices.${slot} must be an object`);
138
+ for (const [field, v] of Object.entries(row)) {
139
+ if (!PRICE_FIELDS.includes(field)) throw new ConfigError(`prices.${slot}.${field} is not a price field (${PRICE_FIELDS.join(', ')})`);
140
+ if (!isPrice(v)) throw new ConfigError(`prices.${slot}.${field} must be a number above 0 (USD per 1M tokens)`);
141
+ }
142
+ }
143
+ }
144
+
145
+ /**
146
+ * The parsed, validated document. `{}` when the file is missing. THROWS ConfigError when the file is
147
+ * there but unreadable, not a JSON object, or holds an invalid known field — never `{}` for those.
148
+ * @param {{ home?: string }} [opts]
149
+ * @returns {Record<string, any>}
150
+ */
151
+ export function readConfig(opts = {}) {
152
+ const file = configPath(opts.home);
153
+ let text;
154
+ try {
155
+ text = readFileSync(file, 'utf8');
156
+ } catch (/** @type {any} */ e) {
157
+ if (e?.code === 'ENOENT') return {};
158
+ throw new ConfigError(`${file} could not be read (${e?.code ?? 'error'}) — fix or remove it`);
159
+ }
160
+ let parsed;
161
+ try {
162
+ parsed = JSON.parse(text);
163
+ } catch {
164
+ throw new ConfigError(`${file} is not readable JSON — fix or remove it`);
165
+ }
166
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
167
+ throw new ConfigError(`${file} must hold a JSON object — fix or remove it`);
168
+ }
169
+ try {
170
+ validateDoc(parsed);
171
+ } catch (/** @type {any} */ e) {
172
+ throw new ConfigError(`${file}: ${e.message}`);
173
+ }
174
+ return parsed;
175
+ }
176
+
177
+ /**
178
+ * Apply a patch and write. `null` deletes a field. Top-level fields shallow-merge; `prices` merges
179
+ * per slot, then per field (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
180
+ * clears the field). Everything is validated before anything is written; a refusal leaves the file
181
+ * untouched.
182
+ * @param {Record<string, any>} patch
183
+ * @param {{ home?: string }} [opts]
184
+ * @returns {Record<string, any>} the document as written
185
+ */
186
+ export function updateConfig(patch, opts = {}) {
187
+ const cur = readConfig(opts);
188
+ /** @type {Record<string, any>} */
189
+ const next = { ...cur };
190
+ for (const [k, v] of Object.entries(patch)) {
191
+ if (k === 'prices' || k === 'providers') continue;
192
+ if (v === null) delete next[k];
193
+ else next[k] = v;
194
+ }
195
+ if (patch.prices !== undefined) {
196
+ const p = patch.prices;
197
+ if (p === null) {
198
+ delete next.prices;
199
+ } else {
200
+ if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('prices must be an object of provider slots');
201
+ /** @type {Record<string, any>} */
202
+ const prices = { ...(next.prices ?? {}) };
203
+ for (const [slot, row] of Object.entries(p)) {
204
+ if (row === null) { delete prices[slot]; continue; }
205
+ if (typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`prices.${slot} must be an object`);
206
+ const merged = { ...(prices[slot] ?? {}) };
207
+ for (const [field, v] of Object.entries(row)) {
208
+ if (v === null) delete merged[field];
209
+ else merged[field] = v;
210
+ }
211
+ if (Object.keys(merged).length === 0) delete prices[slot];
212
+ else prices[slot] = merged;
213
+ }
214
+ if (Object.keys(prices).length === 0) delete next.prices;
215
+ else next.prices = prices;
216
+ }
217
+ }
218
+ if (patch.providers !== undefined) {
219
+ const p = patch.providers;
220
+ if (p === null) {
221
+ delete next.providers;
222
+ } else {
223
+ if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('providers must be an object of provider slots');
224
+ /** @type {Record<string, any>} */
225
+ const providers = { ...(next.providers ?? {}) };
226
+ for (const [slot, row] of Object.entries(p)) {
227
+ if (row === null) { delete providers[slot]; continue; }
228
+ if (typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`providers.${slot} must be an object`);
229
+ const merged = { ...(providers[slot] ?? {}) };
230
+ for (const [field, v] of Object.entries(row)) {
231
+ if (v === null) delete merged[field];
232
+ else merged[field] = field === 'baseUrl' && typeof v === 'string' ? cleanBaseUrl(v) : v;
233
+ }
234
+ if (Object.keys(merged).length === 0) delete providers[slot];
235
+ else providers[slot] = merged;
236
+ }
237
+ if (Object.keys(providers).length === 0) delete next.providers;
238
+ else next.providers = providers;
239
+ }
240
+ }
241
+ validateDoc(next);
242
+ /** @type {string[]} */
243
+ const leaks = [];
244
+ secretPaths(next, '', leaks);
245
+ if (leaks.length) {
246
+ 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)`);
247
+ }
248
+ const file = configPath(opts.home);
249
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
250
+ const tmp = `${file}.tmp-${process.pid}`;
251
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
252
+ chmodSync(tmp, 0o600);
253
+ renameSync(tmp, file);
254
+ return next;
255
+ }
package/src/drafter.js CHANGED
@@ -21,8 +21,9 @@ import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
21
21
  import { loadCatalogue } from './catalogue.js';
22
22
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
23
23
  import { readInputFacts } from './input-facts.js';
24
- import { makeProvider, sumMeterings, ceilingCostUsd } from './provider.js';
24
+ import { makeProvider, sumMeterings, ceilingCostUsd, priceRecord } from './provider.js';
25
25
  import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
26
+ import { ConfigError } from './config.js';
26
27
 
27
28
  export const MAX_STRUCTURE_RETRIES = 2;
28
29
  export const MAX_REVISIONS = 2;
@@ -177,10 +178,10 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
177
178
  * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
178
179
  *
179
180
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
180
- * costUsd:number|null, modelReturned:string|null, modelId?:string, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
181
+ * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
181
182
  */
182
183
  export async function draft({
183
- proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId,
184
+ proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
184
185
  budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
185
186
  }) {
186
187
  const fail = (reds, extra = {}) => ({
@@ -198,11 +199,14 @@ export async function draft({
198
199
  if (!facts.ok) return fail(facts.reds);
199
200
 
200
201
  let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
202
+ let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
201
203
  if (provider == null) {
202
204
  try {
203
- ({ provider, rates, modelId } = makeProviderFn(slot, { model, ...DRAFT_PROVIDER_OPTIONS }));
205
+ ({
206
+ provider, rates, modelId, prices = null,
207
+ } = makeProviderFn(slot, { model, env, ...DRAFT_PROVIDER_OPTIONS }));
204
208
  } catch (err) {
205
- return fail([`key: ${err.message}`]);
209
+ return fail([`${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
206
210
  }
207
211
  }
208
212
 
@@ -212,7 +216,7 @@ export async function draft({
212
216
  const cat = loadCatalogue();
213
217
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
214
218
  const validationCatalogue = cat.primitives;
215
- const roundCeiling = ceilingCostUsd(modelId);
219
+ const roundCeiling = ceilingCostUsd(modelId, undefined, prices ? { prices } : {});
216
220
  // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
217
221
  if (roundCeiling > budgetUsd) {
218
222
  return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
@@ -301,7 +305,7 @@ export async function draft({
301
305
  log.push(entry);
302
306
  const m = sumMeterings(meterings);
303
307
  return {
304
- ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop: null, log,
308
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log,
305
309
  };
306
310
  }
307
311
  lastReds = [...verdict.reds];
@@ -319,6 +323,6 @@ export async function draft({
319
323
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
320
324
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
321
325
  return {
322
- ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop, log,
326
+ ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log,
323
327
  };
324
328
  }