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
@@ -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,
@@ -38,7 +38,8 @@ import { fileURLToPath } from 'node:url';
38
38
  import {
39
39
  ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, readQuestions, readoutHeadIndexes, scrub, signDraft,
40
40
  } from '../authoring.js';
41
- import { nextRunId, readFileInside, readdirInside } from '../flow.js';
41
+ import { checkFlowName, nextRunId, readFileInside, readdirInside } from '../flow.js';
42
+ import { readModelRecord } from '../flowmodel.js';
42
43
  import { isFwdloopAlive } from '../liveness.js';
43
44
  import {
44
45
  checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
@@ -47,7 +48,12 @@ import {
47
48
  appendAnswersToJob, capFloorText, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
48
49
  } from './authorcard.js';
49
50
  import { checkedLines, notCheckedBlock } from '../checked.js';
51
+ import {
52
+ readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
53
+ } from '../provider.js';
54
+ import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
50
55
  import { parseSignedText } from '../signed-text.js';
56
+ import { draftStepList } from '../draft-steps.js';
51
57
  import { leastResumeCapUsd } from './authorvalues.js';
52
58
  import { createFlowsDoor } from './authorflows.js';
53
59
  import { createResumeDoor } from './authorresume.js';
@@ -84,23 +90,23 @@ const KILL_HARD_WAIT_MS = 2000;
84
90
  const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
85
91
 
86
92
  /**
87
- * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, childRunning?: (dir: string) => boolean }} opts
93
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, childRunning?: (dir: string) => boolean, thinkingSupport?: typeof bareagentThinkingSupport }} opts
88
94
  * `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
89
95
  * the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
90
96
  */
91
97
  export function createAuthor(opts) {
92
98
  const {
93
- root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow,
99
+ root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow, thinkingSupport = bareagentThinkingSupport,
94
100
  } = opts;
95
101
  // the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
96
102
  const starter = createStarter({ root, bin });
97
103
  const flowsDoor = createFlowsDoor({
98
- root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd),
104
+ root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd), modelRefusal: (card, loaded) => modelRefusal(card, loaded),
99
105
  });
100
106
 
101
107
  /** The ONE monthly check, defined below (a function declaration, so the doors above may take it now). */
102
108
  const resumeDoor = createResumeDoor({
103
- root, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
109
+ root, home, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
104
110
  });
105
111
 
106
112
  /** The drafts folder's real path, or null when the flows root does not exist. */
@@ -152,6 +158,19 @@ export function createAuthor(opts) {
152
158
  return logText.ok ? scrub(logText.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
153
159
  }
154
160
 
161
+ /**
162
+ * M4d am10: the Chat list of what this plan's draft really did, READ from its log.json and declaration (never from the readout, which is signed text),
163
+ * built by the ONE function `draftStepList`; every string scrubbed. `null` when the draft left no log (the page then lists what it always did).
164
+ * @param {string} dir @param {string} rel @param {string[]} keys
165
+ */
166
+ function stepListOf(dir, rel, keys) {
167
+ const declaration = readJson(dir, `${rel}/declaration.json`) ?? readJson(dir, `${rel}/declaration.rejected.json`);
168
+ const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration });
169
+ if (list === null) return null;
170
+ const sc = (x) => scrub(String(x), keys);
171
+ return list.map((st) => ({ ...st, label: sc(st.label), details: st.details.map(sc), ...(st.reds ? { reds: st.reds.map(sc) } : {}) }));
172
+ }
173
+
155
174
  /**
156
175
  * One plan folder's result, READ from its files: green (spec.hash), red (a log that says not ok, or a leak marker), or null (no result yet).
157
176
  * @param {string} dir the draft folder @param {string} rel `draft` or `draft-<n>` @param {string[]} keys
@@ -162,14 +181,14 @@ export function createAuthor(opts) {
162
181
  if (hashFile.ok && hashFile.text.trim() !== '') {
163
182
  const readout = readFileInside(dir, `${rel}/readout.txt`);
164
183
  const text = readout.ok ? scrub(readout.text, keys) : '';
165
- return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text) };
184
+ return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text), stepList: stepListOf(dir, rel, keys) };
166
185
  }
167
186
  const leak = readFileInside(dir, `${rel}/scrub-leak.red`);
168
187
  const log = readJson(dir, `${rel}/log.json`);
169
188
  if (leak.ok || (log && log.ok === false)) {
170
189
  const reds = Array.isArray(log?.reds) ? log.reds.map((r) => scrub(String(r), keys)) : [];
171
190
  if (leak.ok) reds.push(scrub(leak.text.trim(), keys));
172
- return { phase: 'red', reds, say: RED_SAY };
191
+ return { phase: 'red', reds, say: RED_SAY, stepList: stepListOf(dir, rel, keys) };
173
192
  }
174
193
  return null;
175
194
  }
@@ -201,7 +220,7 @@ export function createAuthor(opts) {
201
220
  return { n, kind, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
202
221
  });
203
222
  const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
204
- const shared = { ...base, card, revises, revisesLeft };
223
+ const shared = { ...base, card, revises, revisesLeft, stepList: first.stepList ?? null };
205
224
  const rel = newest > 0 ? `draft-${newest}` : 'draft';
206
225
  if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
207
226
  if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
@@ -229,8 +248,8 @@ export function createAuthor(opts) {
229
248
  const decl = readJson(dir, `${rel}/declaration.json`);
230
249
  const prose = readFileInside(dir, `${rel}/prose.txt`);
231
250
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
232
- const hasAsk = parsed?.ok === true ? parsed.arbiter.asks.length > 0 : true;
233
- return { checked: checkedLines(decl, { hasAsk }), notChecked: notCheckedBlock(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked) };
251
+ const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line) } : { hasAsk: true };
252
+ return { checked: checkedLines(decl, opts), notChecked: notCheckedBlock(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked) };
234
253
  }
235
254
 
236
255
  /** The answers an answer-redraft was drafted with, as the marker recorded them: `[{ line, lineText, question, answer }]` (scrubbed). @param {string} dir @param {number} n @param {string[]} keys */
@@ -257,7 +276,7 @@ export function createAuthor(opts) {
257
276
  /** The one request-time read of the keys door: the merged env (scrub list + child env) or null on its refusal. */
258
277
  const keysNow = () => {
259
278
  const loaded = loadEnv();
260
- return { loaded, keys: providerKeys(loaded.env) };
279
+ return { loaded, keys: providerKeys(loaded) };
261
280
  };
262
281
 
263
282
  /**
@@ -282,16 +301,38 @@ export function createAuthor(opts) {
282
301
  };
283
302
  }
284
303
 
304
+ /**
305
+ * M4d amendment 6 item 6: the model the card picked must still be a ticked, priced line of a provider that has its key set up; nothing ticked says
306
+ * what to do. `[]` = fine. Reads Settings now, at the click: a line unticked since Chat drew its menu is refused by name, at $0.
307
+ * @param {any} card @param {{ keyNames?: string[] }} loaded @returns {{ field: string, say: string }[]}
308
+ */
309
+ function modelRefusal(card, loaded) {
310
+ const no = (say) => [{ field: 'model', say }];
311
+ let config;
312
+ try { config = readPriceConfig(home); } catch { return no('Your settings file (config.json) cannot be read. Fix or remove it, then look again. Nothing was spent.'); }
313
+ const rows = loaded.keyNames ?? [];
314
+ if (typeof card.provider !== 'string' || card.provider === '' || typeof card.model !== 'string' || card.model === '') {
315
+ return no(tickedLines(config, rows).length === 0 ? 'Tick a model in Settings > Providers. Nothing was spent.' : 'Pick a model. Nothing was spent.');
316
+ }
317
+ if (!rows.includes(card.provider)) return no(`${card.provider} is not set up: put its key in your keys file and type its Base URL in Settings > Providers. Nothing was spent.`);
318
+ const u = resolveUsableModel(card.provider, { config, model: card.model });
319
+ return u.ok ? [] : no(`${u.say} Nothing was spent.`);
320
+ }
321
+
322
+ /** The flags that make a draft child use the card's model and thinking choice. @param {any} card */
323
+ const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : [])];
324
+
285
325
  /**
286
326
  * The $0 checks both a first draft and a revise run on the card as submitted: the card's own checks (a key value, the flow name,
287
327
  * every field), then the monthly room for its cap. `{ ok: true, card, prose }` or `{ ok: false, reply }`. Writes nothing.
288
- * @param {any} body @param {{ ok: boolean, env: Record<string, string|undefined> }} loaded
328
+ * @param {any} body @param {{ ok: boolean, env: Record<string, string|undefined>, keyNames?: string[] }} loaded
289
329
  * @returns {{ ok: true, card: any, prose: string }|{ ok: false, reply: { status: number, body: any } }}
290
330
  */
291
331
  function vetCard(body, loaded) {
292
332
  const card = cardFields(body);
293
- const checked = checkCard(card, { root: realpathSync(root), env: loaded.env });
294
- if (!checked.ok) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: checked.refusals } } };
333
+ const checked = checkCard(card, { root: realpathSync(root), keys: providerKeys(loaded), home });
334
+ const modelSays = modelRefusal(card, loaded);
335
+ if (!checked.ok || modelSays.length > 0) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [...(checked.ok ? [] : checked.refusals), ...modelSays] } } };
295
336
  // amendment 4 item 1: a cap that does not fit this month refuses here too, at $0, with the one refusal text (the page's red note is only a courtesy)
296
337
  const claim = monthlyClaim(Number(card.capUsd));
297
338
  if (claim && 'problem' in claim) return { ok: false, reply: { status: 409, body: { ok: false, refused: 'monthly', say: `${claim.problem} — refusing rather than guess the monthly limit. Nothing spent.` } } };
@@ -312,11 +353,13 @@ export function createAuthor(opts) {
312
353
  * `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
313
354
  * the cap does not fit this month); `floorUsd` is the smallest cap that funds one round of a model step, for the page's
314
355
  * `needs at least $X per run` line. A cap that is not a number above 0 gets no note. Never spends, never writes.
315
- * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4)
356
+ * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Resume) the flow whose recorded model it is: its own prices are the floor (M4d am6)
316
357
  */
317
- monthlyCheck(cap, spent = null) {
358
+ monthlyCheck(cap, spent = null, pick = null) {
318
359
  const n = Number(cap);
319
- const floorUsd = capFloorUsd('x');
360
+ // a Resume names its flow: the model recorded beside the signed job is the one whose prices are the floor
361
+ const recorded = pick?.flow !== undefined && checkFlowName(pick.flow).ok ? readModelRecord(join(root, pick.flow)) : null;
362
+ const floorUsd = capFloorUsd('x', home, recorded ?? pick);
320
363
  if (typeof cap !== 'string' || cap.trim() === '' || !Number.isFinite(n) || n <= 0) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
321
364
  // a Resume (amendment 4 item 1): only what the run still has to spend is held, so the note asks for `cap - spent`; a cap not above
322
365
  // what is spent says so in the door's own words (red)
@@ -329,6 +372,22 @@ export function createAuthor(opts) {
329
372
  return { status: 200, body: { ok: true, ...monthlyNote(claim), floorUsd, floorText: capFloorText(floorUsd) } };
330
373
  },
331
374
 
375
+ /**
376
+ * `GET /api/author/models` (M4d amendment 6 item 6): what Chat's Model menu offers - every ticked, priced line of a provider whose key is set up, as
377
+ * "provider · model" - and, per line, whether "Thinking on" can change (`canChange`; bareagent's answer through `src/thinking.js`, am7). Read-only.
378
+ */
379
+ models() {
380
+ const { loaded } = keysNow();
381
+ let config;
382
+ try { config = readPriceConfig(home); } catch { return { status: 200, body: { ok: true, lines: [], say: 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.' } }; }
383
+ const lines = tickedLines(config, loaded.keyNames ?? []).map((l) => {
384
+ const row = resolveSlot(l.slot, { config });
385
+ const support = thinkingSupport(row.shape, l.model, { baseUrl: row.baseUrl }); // the Base URL lets bareagent resolve the row by its host, as its request path does
386
+ return { ...l, thinking: { support, canChange: support !== false, say: support === false ? THINKING_FIXED_SAY : (support === 'unverified' ? THINKING_UNVERIFIED_SAY : '') } };
387
+ });
388
+ return { status: 200, body: { ok: true, lines, say: lines.length === 0 ? 'Tick a model in Settings > Providers.' : '' } };
389
+ },
390
+
332
391
  /** `GET /api/author/start/:startId`: the start's phase, read from its files. @param {string} id */
333
392
  startGet(id) { return starter.get(id, keysNow().keys); },
334
393
 
@@ -370,7 +429,7 @@ export function createAuthor(opts) {
370
429
  let child;
371
430
  try {
372
431
  child = spawnDetached({
373
- bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName], env: loaded.env, logPath: join(dir, 'child.log'),
432
+ bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...modelArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
374
433
  });
375
434
  } catch (e) {
376
435
  return { status: 500, body: { ok: false, refused: 'spawn', say: `The draft could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
@@ -412,7 +471,7 @@ export function createAuthor(opts) {
412
471
  const { v, name, dir } = seen;
413
472
  const b = body && typeof body === 'object' ? body : {};
414
473
  // amendment 4 item 2: a cap that cannot fund one round of the first model step is never signed (it would cap-halt at $0 spent)
415
- const floor = capFloorUsd(typeof v.card.job === 'string' ? v.card.job : '');
474
+ const floor = capFloorUsd(typeof v.card.job === 'string' ? v.card.job : '', home, v.card);
416
475
  if (Number(v.card.capUsd) < floor) return { status: 400, body: { ok: false, refused: 'cap-too-small', say: capFloorText(floor) } };
417
476
  if (typeof b.hash !== 'string' || b.hash !== v.hash) {
418
477
  return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'The plan on disk is not the one you were shown (its hash differs). Nothing was signed. Reload and read the plan again.' } };
@@ -428,11 +487,17 @@ export function createAuthor(opts) {
428
487
  if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
429
488
  }
430
489
  const signedBy = userInfo().username;
490
+ // M6: a card that edits a signed job signs as a REPLACEMENT of that job, only at the signature hash it was opened at (the writer re-checks it)
491
+ const editOf = v.card.editOf && typeof v.card.editOf === 'object' ? v.card.editOf : null;
492
+ if (editOf !== null && editOf.flow !== name) return { status: 409, body: { ok: false, refused: 'edit-name', say: 'This draft edits another job than the name it was drafted under. Nothing was signed.' } };
493
+ // M6 amendments 1 and 3: a replacing sign is refused while a run of the job is running, waiting at its ask or starting (a stale page cannot get round the greyed button)
494
+ const editBlock = editOf !== null ? flowsDoor.editBlock(name) : null;
495
+ if (editBlock !== null) return { status: 409, body: { ok: false, refused: 'run-live', say: editBlock } };
431
496
  const result = signDraft({
432
- dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir,
497
+ dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, keyNames: loaded.keyNames, sessionDir: dir, replaces: editOf !== null ? { flowHash: String(editOf.flowHash) } : undefined,
433
498
  });
434
499
  if (!result.ok) {
435
- const keys = providerKeys(loaded.env);
500
+ const keys = providerKeys(loaded);
436
501
  return { status: 409, body: { ok: false, refused: 'sign-refused', say: 'The draft did not pass the signing checks. Nothing was signed.', reds: result.reds.map((r) => scrub(String(r), keys)) } };
437
502
  }
438
503
  writeFileSync(join(dir, 'signed.json'), `${JSON.stringify({
@@ -440,7 +505,7 @@ export function createAuthor(opts) {
440
505
  })}\n`, { mode: 0o600 });
441
506
  const started = starter.start({
442
507
  kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })),
443
- }, loaded.env);
508
+ }, loaded);
444
509
  if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, flow: name, say: `${started.body.say ?? 'The run did not start.'} The flow is signed; start it from "Run a signed flow".` } };
445
510
  return { status: 202, body: { ...started.body, signed: true } };
446
511
  },
@@ -487,7 +552,7 @@ export function createAuthor(opts) {
487
552
  try {
488
553
  child = spawnDetached({
489
554
  bin,
490
- argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName],
555
+ argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName, ...modelArgv(vet.card)],
491
556
  env: loaded.env,
492
557
  logPath: join(dir, `revise-${n}.log`),
493
558
  });
@@ -559,7 +624,7 @@ export function createAuthor(opts) {
559
624
  writeFileSync(files[2], `${JSON.stringify({ fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })) })}\n`, { mode: 0o600, flag: 'wx' });
560
625
  child = spawnDetached({
561
626
  bin,
562
- argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions'],
627
+ argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions', ...modelArgv(redraft.vet.card)],
563
628
  env: loaded.env,
564
629
  logPath: join(dir, `redraft-${n}.log`),
565
630
  });