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
@@ -14,10 +14,10 @@ import {
14
14
  } from 'node:fs';
15
15
  import { isAbsolute, join } from 'node:path';
16
16
 
17
- import { checkFlowName } from '../flow.js';
18
- import { checkSendDestination, resolveCeilingUsd } from '../runner.js';
17
+ import { checkFlowName, signedHashOf } from '../flow.js';
18
+ import { checkSendDestination } from '../runner.js';
19
19
  import { parseSignedText } from '../signed-text.js';
20
- import { PROVIDER_SLOTS } from '../provider.js';
20
+ import { readPriceConfig, resolveUsableModel, ceilingCostUsd } from '../provider.js';
21
21
 
22
22
  /** The heading line the prose files use (flows/job2-m6a-3/prose.txt); the parser matches `/^arbiter guardrails\b/i`. */
23
23
  export const ARBITER_HEADING = 'Arbiter guardrails (belong to no line; human-signed, tighten-only — never authored or claimed by the drafter):';
@@ -170,6 +170,11 @@ export function cardFields(body) {
170
170
  inputs: str(b.inputs).replace(/\r\n?/g, '\n'),
171
171
  capUsd: typeof b.capUsd === 'string' && b.capUsd.trim() !== '' ? Number(b.capUsd) : b.capUsd,
172
172
  askWait: str(b.askWait).trim(),
173
+ // M4d amendment 6: the picked model (a key name and a model id from Chat's menu) and the per-job "Thinking on" tick; present only when sent
174
+ ...(str(b.provider).trim() !== '' || str(b.model).trim() !== '' ? { provider: str(b.provider).trim(), model: str(b.model).trim() } : {}),
175
+ ...(b.thinking === true ? { thinking: true } : {}),
176
+ // M6: present only when this card EDITS a signed job: which job, and the signature hash it was opened at
177
+ ...(typeof b.editOf?.flow === 'string' && typeof b.editOf?.flowHash === 'string' && b.editOf.flowHash !== '' ? { editOf: { flow: b.editOf.flow, flowHash: b.editOf.flowHash } } : {}),
173
178
  };
174
179
  }
175
180
 
@@ -193,6 +198,51 @@ export function cardToProse(card) {
193
198
  return `${out.join('\n')}\n`;
194
199
  }
195
200
 
201
+ /** An ask wait in ms as the card spells it (`30m`, `2h`), or null when it is not a whole number of minutes. @param {number} ms */
202
+ function waitText(ms) {
203
+ if (!Number.isInteger(ms) || ms <= 0 || ms % 60000 !== 0) return null;
204
+ return ms % 3600000 === 0 ? `${ms / 3600000}h` : `${ms / 60000}m`;
205
+ }
206
+
207
+ /**
208
+ * M6: a signed job turned back into the card's fields (the job box, inputs box, destination, cap, ask wait), from `parseSignedText`'s `lines` and
209
+ * `arbiter`. The ONE rule of fidelity is mechanical: the card is offered only if writing it again (`cardToProse` -> `parseSignedText`) gives back the
210
+ * SAME lines and the SAME arbiter (an old unsigned `ask:` wait is the one thing allowed to differ: it comes back signed at its 30m). A setting the
211
+ * card has no box for (a redo cap, a second send, a send off the last line, a wait in seconds) makes the answer `{ok:false, say}`; nothing is dropped.
212
+ * @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed
213
+ * @returns {{ ok: true, card: { job: string, inputs: string, destination: string, capUsd: string, askWait: string } } | { ok: false, say: string }}
214
+ */
215
+ export function cardFromSigned({ lines, arbiter }) {
216
+ const no = () => ({ ok: /** @type {false} */ (false), say: 'This job has a setting the card has no box for, so it cannot be opened for editing here.' });
217
+ const asks = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
218
+ const jobLines = [];
219
+ let firstWait = null;
220
+ for (const l of lines) {
221
+ const ak = asks.get(l.n);
222
+ if (ak) {
223
+ const w = waitText(ak.ttlMs);
224
+ if (w === null) return no();
225
+ firstWait ??= w;
226
+ jobLines.push(`Ask ${w}: ${l.text}`);
227
+ } else jobLines.push(l.text);
228
+ if (typeof l.guardrail === 'string' && l.guardrail !== '') jobLines.push(`~ ${l.guardrail}`);
229
+ }
230
+ const sends = arbiter.sends ?? [];
231
+ if (sends.length > 1 || (sends.length === 1 && sends[0].target?.kind !== 'file')) return no();
232
+ const card = {
233
+ job: jobLines.join('\n'),
234
+ inputs: (arbiter.sources ?? []).map((x) => `${x.role}: ${x.path}`).join('\n'),
235
+ destination: sends.length === 1 ? sends[0].target.path : '',
236
+ capUsd: capText(Number(arbiter.capUsd)),
237
+ askWait: firstWait ?? '1h',
238
+ };
239
+ const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
240
+ const norm = (a) => JSON.stringify({ ...a, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
241
+ const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
242
+ if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
243
+ return { ok: true, card };
244
+ }
245
+
196
246
  /** The refusal for a path that does not name a readable regular file (realpath at the click). @param {string} p */
197
247
  function fileProblem(p) {
198
248
  let real;
@@ -239,17 +289,24 @@ export function checkInputRows(rows) {
239
289
  /**
240
290
  * M4e amendment 4 item 2: the smallest per-run cap that funds ONE round of the first model step. The runner halts a step when
241
291
  * `spent + ceiling > cap` (`runStepRalph`), and every ordinary (non-ask) step is a model step, so the floor is the runner's own
242
- * per-round ceiling (`resolveCeilingUsd`) as soon as the job has one such line; a job of only asks spends nothing before its stop.
292
+ * per-round hold (the picked model's own Settings prices times the token bounds) as soon as the job has one such line; a job of only asks spends nothing before its stop.
243
293
  * ONE function: the card's Draft check, Sign, and the page's note all read it. Returns 0 when no step needs a round.
244
- * @param {string} jobText
294
+ * @param {string} jobText @param {string} [home] the config home the panel reads Settings from (default: the process door)
295
+ * @param {{ slot?: string, provider?: string, model?: string }|null} [pick] the job's picked model (M4d amendment 6): its own Settings prices are the hold (a card names its key as `provider`)
245
296
  */
246
- export function capFloorUsd(jobText) {
247
- return capFloorFor(parseJobBox(jobText).steps.some((s) => s.ask === null));
297
+ export function capFloorUsd(jobText, home, pick) {
298
+ return capFloorFor(parseJobBox(jobText).steps.some((s) => s.ask === null), home, pick);
248
299
  }
249
300
 
250
- /** The floor itself, for a caller that already knows whether the job has a step that is not an ask (a signed flow: any step off an ask line). @param {boolean} hasRoundStep */
251
- export function capFloorFor(hasRoundStep) {
252
- return hasRoundStep ? resolveCeilingUsd(null) : 0;
301
+ /** The floor itself, for a caller that already knows whether the job has a step that is not an ask (a signed flow: any step off an ask line). @param {boolean} hasRoundStep @param {string} [home] @param {{ slot?: string, provider?: string, model?: string }|null} [pick] */
302
+ export function capFloorFor(hasRoundStep, home, pick) {
303
+ const slot = pick?.slot ?? pick?.provider;
304
+ if (!hasRoundStep || !slot) return 0;
305
+ // No usable model (nothing picked or ticked, a broken config): nothing is held here, and the run itself is refused by name (`resolveUsableModel`).
306
+ try {
307
+ const u = resolveUsableModel(slot, { config: readPriceConfig(home), model: pick?.model });
308
+ return u.ok ? ceilingCostUsd(u.rates) : 0;
309
+ } catch { return 0; }
253
310
  }
254
311
 
255
312
  /** The one sentence for a cap under the floor (red under Cap, and the Draft / sign refusal). @param {number} floorUsd */
@@ -273,18 +330,23 @@ export function destinationRefusal(dest, root) {
273
330
  /**
274
331
  * Every $0 check on the card, before any spawn (scope 6). Collects all refusals so the page can name every box.
275
332
  * @param {ReturnType<typeof cardFields>} card
276
- * @param {{ root: string, env?: Record<string, string|undefined> }} ctx `env` = the merged keys env: a key value typed into any box is refused
333
+ * @param {{ root: string, keys?: string[], home?: string }} ctx `keys` = the provider key values (the keys load's scrub list): a key value typed into any box is refused; `home` = the config home Settings is read from (the cap floor)
277
334
  * @returns {{ ok: true, prose: string }|{ ok: false, refusals: {field: string, say: string}[] }}
278
335
  */
279
- export function checkCard(card, { root, env = {} }) {
336
+ export function checkCard(card, { root, keys = [], home }) {
280
337
  /** @type {{field: string, say: string}[]} */
281
338
  const refusals = [];
282
339
  const no = (field, say) => refusals.push({ field, say });
283
340
 
284
- // flow name: the CLI's own check, and not an existing flow
341
+ // flow name: the CLI's own check, and not an existing flow (M6: unless this card edits that very job, still at the hash it was opened at)
285
342
  const name = checkFlowName(card.flowName);
286
343
  if (!name.ok) no('flowName', `${name.red}. Use lowercase letters, digits, "-" or "_".`);
287
- else {
344
+ else if (card.editOf) {
345
+ const was = signedHashOf(join(root, card.editOf.flow));
346
+ if (card.flowName !== card.editOf.flow) no('flowName', `The name of a job being edited cannot change. It stays "${card.editOf.flow}".`);
347
+ else if (was === null) no('flowName', `The job "${card.editOf.flow}" is no longer here, so it cannot be edited. Clear the card and start a new job.`);
348
+ else if (was !== card.editOf.flowHash) no('flowName', `"${card.editOf.flow}" was signed again since you opened it for editing. Open it again to edit the new version. Nothing was changed.`);
349
+ } else {
288
350
  let there = true;
289
351
  try { lstatSync(join(root, card.flowName)); } catch { there = false; }
290
352
  if (there) no('flowName', `There is already a flow named "${card.flowName}" here. Pick a name that is not used yet.`);
@@ -302,7 +364,7 @@ export function checkCard(card, { root, env = {} }) {
302
364
  // cap
303
365
  if (typeof card.capUsd === 'string' || typeof card.capUsd === 'number') {
304
366
  if (!(Number.isFinite(Number(card.capUsd)) && Number(card.capUsd) > 0)) no('capUsd', 'The cap must be a number above 0 (dollars per run).');
305
- else if (Number(card.capUsd) < capFloorUsd(card.job)) no('capUsd', capFloorText(capFloorUsd(card.job)));
367
+ else if (Number(card.capUsd) < capFloorUsd(card.job, home, card)) no('capUsd', capFloorText(capFloorUsd(card.job, home, card)));
306
368
  } else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
307
369
 
308
370
  // destination: one folder, or empty for no send (it is sent at the last step)
@@ -316,12 +378,10 @@ export function checkCard(card, { root, env = {} }) {
316
378
  refusals.push(...checkInputRows(parseInputLines(card.inputs)));
317
379
 
318
380
  // a provider key typed into any box never reaches a file
319
- /** @type {string[]} */
320
- const keys = [];
321
- for (const p of Object.values(PROVIDER_SLOTS)) { const k = env[p.envVar]; if (typeof k === 'string' && k.length >= 8) keys.push(k); }
322
- if (keys.length > 0) {
381
+ const longKeys = keys.filter((k) => k.length >= 8);
382
+ if (longKeys.length > 0) {
323
383
  const boxes = [['job', card.job], ['flowName', card.flowName], ['destination', dest], ['inputs', card.inputs]];
324
- for (const [field, text] of boxes) if (keys.some((k) => String(text).includes(k))) no(String(field), 'This box contains an API key. Keys go in Settings only. Nothing was saved.');
384
+ for (const [field, text] of boxes) if (longKeys.some((k) => String(text).includes(k))) no(String(field), 'This box contains an API key. Keys go in Settings only. Nothing was saved.');
325
385
  }
326
386
 
327
387
  if (refusals.length > 0) return { ok: false, refusals };
@@ -19,7 +19,7 @@ import { canFlowRun, willNotRunSay } from '../canrun.js';
19
19
  import { loadCatalogue } from '../catalogue.js';
20
20
  import { ConfigError, readConfig } from '../config.js';
21
21
  import {
22
- checkFlowName, listFlowNames, listRunIds, nextRunId, readFileInside, readFlow, resolveRunDir,
22
+ changeSentence, checkFlowName, listFlowNames, listRunIds, nextRunId, readFileInside, readFlow, resolveRunDir,
23
23
  } from '../flow.js';
24
24
  import { spendSummary } from '../monthly.js';
25
25
  import { userInfo } from 'node:os';
@@ -27,38 +27,48 @@ import {
27
27
  applyRunValues, flowValues, pickRunValues, valuesHash,
28
28
  } from '../runvalues.js';
29
29
  import {
30
- capFloorFor, capFloorText, checkInputRows, runInputRows,
30
+ capFloorFor, capFloorText, cardFromSigned, checkInputRows, runInputRows,
31
31
  } from './authorcard.js';
32
32
  import { checkValues } from './authorvalues.js';
33
+ import { getRunControls } from './data.js';
33
34
  import { providerKeys } from './spawn.js';
35
+ import { readModelRecord, writeModelRecord } from '../flowmodel.js';
34
36
 
37
+ /** M6 amendment 1: the sentence the page shows and the sign route refuses with, for a job with a run running or waiting at its ask. @param {string} runId */
38
+ export const editBlockedSay = (runId) => `finish or stop ${runId} first`;
39
+ /** M6 amendment 3: the sentence for a job with a start still alive (its start folder in phase `starting`). */
40
+ export const EDIT_STARTING_SAY = 'a run is starting';
35
41
  const NO_LIMIT = 'no monthly limit set';
36
42
  /** The body keys a run start takes (amendment 5 item 2): the open boxes plus the hash of the second click. Any other key is refused by name. */
37
- const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash'];
43
+ const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash', 'provider', 'model'];
38
44
 
39
45
  /**
40
46
  * What the Run / Resume forms show of a signed flow (read from its own files, never from a model): the job lines as the signed text has them
41
47
  * (an ask line carries its question and its wait), the values the open boxes start from, and the cap floor. Amendment 5 item 2: all the rest is dimmed.
42
- * @param {any} read `readFlow`'s ok result
48
+ * @param {any} read `readFlow`'s ok result @param {string} [home] the config home Settings is read from @param {string} [flowDir] the signed flow's folder: the model recorded beside it is the one it runs with (M4d amendment 6)
49
+ * @param {{ slot: string, model: string }|null} [picked] a flow with no record runs with the model picked in Chat (M4d amendment 7b): its price is the cap floor
43
50
  */
44
- export function formFacts(read) {
51
+ export function formFacts(read, home, flowDir, picked = null) {
45
52
  const asks = new Map((read.arbiter.asks ?? []).map((a) => [a.line, a]));
46
53
  const values = flowValues(read.arbiter);
47
54
  const jobLines = read.lines.map((l) => ({
48
55
  n: l.n, text: l.text, guardrail: l.guardrail || null, ask: asks.has(l.n) ? { wait: values.askWaits[String(l.n)] } : null,
49
56
  }));
50
57
  const hasRound = read.declaration.steps.some((st) => !asks.has(st.fromLine));
58
+ const recorded = flowDir === undefined ? null : readModelRecord(flowDir);
59
+ const pick = recorded ?? picked;
51
60
  return {
52
- values, jobLines, hasSend: values.destination !== null, capFloorUsd: capFloorFor(hasRound), floorText: capFloorText(capFloorFor(hasRound)),
61
+ values, jobLines, hasSend: values.destination !== null, capFloorUsd: capFloorFor(hasRound, home, pick), floorText: capFloorText(capFloorFor(hasRound, home, pick)),
62
+ model: recorded === null ? null : { slot: recorded.slot, model: recorded.model, label: `${recorded.slot} · ${recorded.model}` },
53
63
  };
54
64
  }
55
65
 
56
66
  /**
57
- * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, starter: ReturnType<typeof import('./authorstart.js').createStarter>, monthlyClaim: (usd: number) => any }} opts
67
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, starter: ReturnType<typeof import('./authorstart.js').createStarter>, monthlyClaim: (usd: number) => any, modelRefusal: (card: any, loaded: any) => { field: string, say: string }[] }} opts
58
68
  */
59
69
  export function createFlowsDoor(opts) {
60
70
  const {
61
- root, home, skipMonthly = false, loadEnv, starter, monthlyClaim,
71
+ root, home, skipMonthly = false, loadEnv, starter, monthlyClaim, modelRefusal,
62
72
  } = opts;
63
73
 
64
74
  /** What is left of the monthly limit, as a courtesy line: the limit minus this month's counted spend (holds are the CLI's business). */
@@ -158,9 +168,10 @@ export function createFlowsDoor(opts) {
158
168
  /**
159
169
  * Every $0 check of a run start, shared by `runPrepare` (the first click) and `run`. `{ok:false, reply}` or the facts a start needs.
160
170
  * Amendment 5 items 2-4: the open boxes are Inputs, Destination, Cap $ and each ask's wait; anything else in the body is refused by name.
161
- * @param {any} body
171
+ * @param {any} body @param {any} loaded the keys load
162
172
  */
163
- function inspect(body, keys) {
173
+ function inspect(body, loaded) {
174
+ const keys = providerKeys(loaded);
164
175
  const reply = (status, b) => ({ ok: /** @type {false} */ (false), reply: { status, body: { ok: false, ...b } } });
165
176
  const realRoot = realRootOrNull();
166
177
  if (realRoot === null) return reply(400, { refused: 'root', say: 'The flows folder this panel serves does not exist.' });
@@ -169,19 +180,23 @@ export function createFlowsDoor(opts) {
169
180
  if (!named.ok) return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `${named.red}.` }] });
170
181
  const read = readSigned(realRoot, flow);
171
182
  if (!read.ok) {
172
- return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so it will not run.` }], reds: read.reds.map((r) => scrub(String(r), keys)) });
183
+ return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so it will not run.${changeSentence(read.reds.map((r) => scrub(String(r), keys)))}` }], reds: read.reds.map((r) => scrub(String(r), keys)) });
173
184
  }
174
185
  const can = canFlowRun(read); // amendment 21 item 1: a flow the list shows refused is refused here too, in the same sentence
175
186
  if (!can.ok) {
176
187
  const red = scrub(String(can.red), keys);
177
188
  return reply(409, { refused: 'flow', say: willNotRunSay(flow, red), refusals: [{ field: 'flow', say: willNotRunSay(flow, red) }] });
178
189
  }
190
+ // M4d amendment 7b: a flow with no recorded model takes the one picked in Chat (checked now, at the click); a flow with a record keeps it and ignores the body's pick
191
+ const noRecord = readModelRecord(join(realRoot, flow)) === null;
192
+ const modelReds = noRecord ? modelRefusal({ provider: body?.provider, model: body?.model }, loaded) : [];
193
+ const newPick = noRecord && modelReds.length === 0 ? { slot: body.provider, model: body.model } : null;
179
194
  const checked = checkValues({
180
- allowedKeys: RUN_KEYS, body, base: flowValues(read.arbiter), realRoot, capOnly: false, floorUsd: formFacts(read).capFloorUsd, monthlyClaim,
195
+ allowedKeys: RUN_KEYS, body, base: flowValues(read.arbiter), realRoot, capOnly: false, floorUsd: formFacts(read, home, join(realRoot, flow), newPick).capFloorUsd, monthlyClaim,
181
196
  });
182
197
  if (!checked.ok && checked.refused) return reply(checked.status, { refused: checked.refused, say: checked.say, refusals: checked.refusals });
183
198
  /** @type {{field: string, say: string}[]} */
184
- const refusals = checked.ok ? [] : [...checked.refusals];
199
+ const refusals = checked.ok ? [...modelReds] : [...checked.refusals, ...modelReds];
185
200
  if (!checked.ok && checked.status === 409) return reply(409, { refused: 'monthly', say: checked.say });
186
201
  const rows = runInputRows(body?.inputs);
187
202
  refusals.push(...checkInputRows(rows));
@@ -202,10 +217,29 @@ export function createFlowsDoor(opts) {
202
217
  flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values: checked.values,
203
218
  });
204
219
  return {
205
- ok: /** @type {true} */ (true), flow, read, declared, rows, runId, values: checked.values, differs: checked.differs, hash,
220
+ ok: /** @type {true} */ (true), flow, read, declared, rows, runId, values: checked.values, differs: checked.differs, hash, newPick, flowDir: join(realRoot, flow),
206
221
  };
207
222
  }
208
223
 
224
+ /**
225
+ * Why a job cannot be edited right now, in the sentence the page shows and the sign route refuses with; `null` when it can. M6 amendment 1:
226
+ * the newest run that is running or waiting at its ask, by the panel's ONE decision (`runControls`, via `getRunControls`: `canStop`) ->
227
+ * "finish or stop run-N first". M6 amendment 3: a start folder in phase `starting` for this flow whose child is alive (`starter.startingFor`,
228
+ * the start door's own rule) -> "a run is starting"; a start that is done, refused or dead unlocks. A stopped, finished or expired run does not count.
229
+ * @param {string} realRoot @param {string} name @returns {string|null}
230
+ */
231
+ function editBlockOf(realRoot, name) {
232
+ const cat = loadCatalogue();
233
+ if (!cat.ok) return null;
234
+ if (starter.startingFor(name, []) !== null) return EDIT_STARTING_SAY;
235
+ const ids = listRunIds(join(realRoot, name)).filter((id) => /^run-\d+$/.test(id)).sort((a, b) => Number(b.slice(4)) - Number(a.slice(4)));
236
+ for (const id of ids) {
237
+ const c = getRunControls({ root: realRoot, flow: name, runId: id, catalogue: cat.primitives });
238
+ if (c?.canStop === true) return editBlockedSay(id);
239
+ }
240
+ return null;
241
+ }
242
+
209
243
  /** One flow's record for the page: its signed values and facts, its last run's inputs, its passed runs and its track record. @param {string} realRoot @param {string} name @param {any} read @param {any} left */
210
244
  function entryFor(realRoot, name, read, left) {
211
245
  const roles = (read.arbiter.sources ?? []).map((s) => s.role);
@@ -215,11 +249,23 @@ export function createFlowsDoor(opts) {
215
249
  return {
216
250
  flow: name, capUsd: read.arbiter.capUsd, roles, nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
217
251
  runs: passed, stats,
218
- ...formFacts(read),
252
+ ...formFacts(read, home, flowDir),
253
+ // M6: the job as a card to edit (`ok:true, card, flowHash` = the signature hash it is opened at), or why it cannot be (`ok:false, say`)
254
+ edit: (() => {
255
+ const blocked = editBlockOf(realRoot, name);
256
+ if (blocked !== null) return { ok: false, say: blocked };
257
+ const c = cardFromSigned(read); return c.ok ? { ok: true, card: c.card, flowHash: read.signature.flow } : c;
258
+ })(),
219
259
  };
220
260
  }
221
261
 
222
262
  return {
263
+ /** M6 amendments 1 and 3: the sentence that says why this flow cannot be edited now, or null (the sign route's check). @param {string} name */
264
+ editBlock(name) {
265
+ const realRoot = realRootOrNull();
266
+ return realRoot === null ? null : editBlockOf(realRoot, name);
267
+ },
268
+
223
269
  /** `GET /api/author/flows`. */
224
270
  flows() {
225
271
  const realRoot = realRootOrNull();
@@ -257,7 +303,7 @@ export function createFlowsDoor(opts) {
257
303
  const readRaw = readSigned(realRoot, flow);
258
304
  const can = canFlowRun(readRaw);
259
305
  if (!can.ok) {
260
- const red = scrub(String(can.red), providerKeys(loadEnv().env));
306
+ const red = scrub(String(can.red), providerKeys(loadEnv()));
261
307
  return no(409, willNotRunSay(flow, red), { red });
262
308
  }
263
309
  const read = /** @type {Extract<typeof readRaw, { ok: true }>} */ (readRaw); // canFlowRun refuses every failed read above
@@ -277,7 +323,7 @@ export function createFlowsDoor(opts) {
277
323
  * @param {any} body
278
324
  */
279
325
  runPrepare(body) {
280
- const s = inspect(body, providerKeys(loadEnv().env));
326
+ const s = inspect(body, loadEnv());
281
327
  if (!s.ok) return s.reply;
282
328
  return {
283
329
  status: 200, body: {
@@ -295,7 +341,7 @@ export function createFlowsDoor(opts) {
295
341
  run(body) {
296
342
  const loaded = loadEnv();
297
343
  if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
298
- const s = inspect(body, providerKeys(loaded.env));
344
+ const s = inspect(body, loaded);
299
345
  if (!s.ok) return s.reply;
300
346
  let values = null;
301
347
  if (s.differs) {
@@ -309,9 +355,14 @@ export function createFlowsDoor(opts) {
309
355
  flow: s.flow, flowSignatureHash: s.read.signature.flow, version: 0, values: s.values, hash: s.hash, signedBy: userInfo().username, at: new Date().toISOString(),
310
356
  };
311
357
  }
312
- return starter.start({
313
- kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path })), values,
314
- }, loaded.env);
358
+ const started = starter.start({
359
+ kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path })), values, pick: s.newPick,
360
+ }, loaded);
361
+ // M4d amendment 7b: the pick of a flow that had no record is written only once the start succeeded (a refused start leaves none), beside the signed files, never in them
362
+ if (started.status === 202 && s.newPick !== null) {
363
+ try { writeModelRecord(s.flowDir, s.newPick); } catch { /* a record that appeared meanwhile stays: written once */ }
364
+ }
365
+ return started;
315
366
  },
316
367
  };
317
368
  }
@@ -11,12 +11,12 @@
11
11
  // One writer of each field: `writeRunValues` writes the version file (this door is its only caller for versions >= 1); the runner reads the
12
12
  // highest version through `pickRunValues` and nothing else. The agent, the chat notes and the drafter have no path here.
13
13
  import { realpathSync } from 'node:fs';
14
- import { join } from 'node:path';
14
+ import { dirname, join } from 'node:path';
15
15
  import { userInfo } from 'node:os';
16
16
 
17
17
  import { scrub } from '../authoring.js';
18
18
  import { loadCatalogue } from '../catalogue.js';
19
- import { checkFlowName, readFileInside, readFlow, resolveRunDir } from '../flow.js';
19
+ import { changeSentence, checkFlowName, readFileInside, readFlow, resolveRunDir } from '../flow.js';
20
20
  import { readResumeLock } from '../liveness.js';
21
21
  import { auditSpend } from '../runner.js';
22
22
  import {
@@ -27,15 +27,16 @@ import { formFacts } from './authorflows.js';
27
27
  import { checkValues } from './authorvalues.js';
28
28
  import { getRunControls } from './data.js';
29
29
  import { providerKeys } from './spawn.js';
30
+ import { readModelRecord } from '../flowmodel.js';
30
31
 
31
32
  const KEYS = ['flow', 'runId', 'capUsd', 'hash'];
32
33
 
33
34
  /**
34
- * @param {{ root: string, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, monthlyClaim: (usd: number) => any, starter: ReturnType<typeof import('./authorstart.js').createStarter> }} opts
35
+ * @param {{ root: string, home?: string, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, monthlyClaim: (usd: number) => any, starter: ReturnType<typeof import('./authorstart.js').createStarter> }} opts
35
36
  */
36
37
  export function createResumeDoor(opts) {
37
38
  const {
38
- root, loadEnv, monthlyClaim, starter,
39
+ root, home, loadEnv, monthlyClaim, starter,
39
40
  } = opts;
40
41
 
41
42
  /**
@@ -56,7 +57,7 @@ export function createResumeDoor(opts) {
56
57
  const cat = loadCatalogue();
57
58
  if (!cat.ok) return no(500, { refused: 'catalogue', say: 'The catalogue could not be loaded. Nothing was signed.' });
58
59
  const read = readFlow({ root: realRoot, name: flow, catalogue: cat.primitives });
59
- if (!read.ok) return no(400, { refused: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so a run of it will not resume.` });
60
+ if (!read.ok) return no(400, { refused: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so a run of it will not resume.${changeSentence(read.reds)}` });
60
61
  const controls = getRunControls({
61
62
  root: realRoot, flow, runId, catalogue: cat.primitives,
62
63
  });
@@ -74,7 +75,7 @@ export function createResumeDoor(opts) {
74
75
  const hasRound = read.declaration.steps.some((st) => !(read.arbiter.asks ?? []).some((a) => a.line === st.fromLine));
75
76
  if (formOnly) return { ok: /** @type {true} */ (true), flow, runId, runDir: rd.runDir, version, base, spentUsd: spent.total, read, hasRound };
76
77
  const checked = checkValues({
77
- allowedKeys: KEYS, body: b, base, realRoot, capOnly: true, floorUsd: capFloorFor(hasRound), spentUsd: spent.total, monthlyClaim, always: true,
78
+ allowedKeys: KEYS, body: b, base, realRoot, capOnly: true, floorUsd: capFloorFor(hasRound, home, readModelRecord(join(realRoot, flow))), spentUsd: spent.total, monthlyClaim, always: true,
78
79
  });
79
80
  if (!checked.ok) {
80
81
  return no(checked.status, checked.refused ? { refused: checked.refused, say: checked.say, refusals: checked.refusals } : { refused: 'resume', refusals: checked.refusals, say: checked.refusals[0]?.say ?? 'Not resumed. Fix the marked box.' });
@@ -100,11 +101,11 @@ export function createResumeDoor(opts) {
100
101
  const inputsRead = readFileInside(s.runDir, 'inputs.json');
101
102
  let inputs = [];
102
103
  try { inputs = inputsRead.ok ? JSON.parse(inputsRead.text).map((m) => ({ role: String(m.id), path: String(m.source) })) : []; } catch { inputs = []; }
103
- const floorUsd = capFloorFor(s.hasRound);
104
+ const floorUsd = capFloorFor(s.hasRound, home, readModelRecord(dirname(dirname(s.runDir))));
104
105
  return {
105
106
  status: 200,
106
107
  body: {
107
- ok: true, flow: s.flow, runId: s.runId, version: s.version, values: s.base, spentUsd: s.spentUsd, inputs, floorUsd, floorText: capFloorText(floorUsd), jobLines: formFacts(s.read).jobLines,
108
+ ok: true, flow: s.flow, runId: s.runId, version: s.version, values: s.base, spentUsd: s.spentUsd, inputs, floorUsd, floorText: capFloorText(floorUsd), jobLines: formFacts(s.read, home, dirname(dirname(s.runDir))).jobLines, model: formFacts(s.read, home, dirname(dirname(s.runDir))).model,
108
109
  },
109
110
  };
110
111
  },
@@ -138,10 +139,10 @@ export function createResumeDoor(opts) {
138
139
  flow: s.flow, flowSignatureHash: s.signatureHash, runId: s.runId, version: s.version, values: s.values, hash: s.hash, signedBy: userInfo().username, at: new Date().toISOString(),
139
140
  });
140
141
  if (!w.ok) {
141
- const keys = providerKeys(loaded.env);
142
+ const keys = providerKeys(loaded);
142
143
  return { status: 409, body: { ok: false, refused: 'sign-refused', say: `${scrub(w.red, keys)}. Nothing was started.` } };
143
144
  }
144
- const started = starter.startContinue({ flow: s.flow, runId: s.runId, version: s.version }, loaded.env);
145
+ const started = starter.startContinue({ flow: s.flow, runId: s.runId, version: s.version }, loaded);
145
146
  if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, say: `${started.body.say ?? 'The resume did not start.'} The new cap is signed; try Resume again.` } };
146
147
  return { status: 202, body: { ...started.body, signed: true, version: s.version } };
147
148
  },
@@ -106,8 +106,20 @@ export function createStarter(opts) {
106
106
  return d === null ? null : readStart(join(d, id), id, keys);
107
107
  };
108
108
 
109
+ /** M6 amendment 3: the ONE rule for "a run of this flow is starting": the newest start folder of the flow in phase `starting`, or null. @param {string} flow @param {string[]} keys */
110
+ function startingFor(flow, keys) {
111
+ const sd = startsDir();
112
+ if (sd === null) return null;
113
+ for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
114
+ const v = readStart(join(sd, id), id, keys);
115
+ if (v && v.flow === flow && v.phase === 'starting') return id;
116
+ }
117
+ return null;
118
+ }
119
+
109
120
  return {
110
121
  checkRun,
122
+ startingFor,
111
123
 
112
124
  /**
113
125
  * Start `fwdloop run` for a flow whose every $0 check already passed at the calling door. Re-checks the run id here (nothing
@@ -115,13 +127,14 @@ export function createStarter(opts) {
115
127
  * `runId` '' = no typed id: the start CLAIMS the next `run-<n>` itself (claimRunId, folder created exclusively; amendment 3).
116
128
  * `values` (M4e amendment 5 item 3): the human's signed values for THIS run (the page's second click), written once into the run's own
117
129
  * folder as `signed-values.json` BEFORE the spawn; the run then uses them (`pickRunValues`). None = the flow's own.
118
- * @param {{ kind: 'run'|'sign', flow: string, runId: string, sources: {role: string, path: string}[], values?: any }} a
119
- * @param {Record<string, string|undefined>} env the merged keys env: the child's env AND the scrub list
130
+ * @param {{ kind: 'run'|'sign', flow: string, runId: string, sources: {role: string, path: string}[], values?: any, pick?: {slot: string, model: string}|null }} a
131
+ * @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded the keys load: its env is the child's env AND (with its key names) the scrub list
120
132
  * @returns {{ status: number, body: any }}
121
133
  */
122
134
  start({
123
- kind, flow, runId, sources, values = null,
124
- }, env) {
135
+ kind, flow, runId, sources, values = null, pick = null,
136
+ }, loaded) {
137
+ const { env } = loaded;
125
138
  const sd = startsDir();
126
139
  if (sd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
127
140
  /** @type {string|null} */
@@ -148,14 +161,12 @@ export function createStarter(opts) {
148
161
  const w = writeRunValues(runDirOf(), { ...values, runId });
149
162
  if (!w.ok) { unclaim(); return { status: 500, body: { ok: false, refused: 'values', say: `The signed values could not be saved. ${NOTHING_SPENT}` } }; }
150
163
  }
151
- const keys = providerKeys(env);
164
+ const keys = providerKeys(loaded);
152
165
  // one start at a time while one is still spawning for this flow (a double click, two tabs)
153
- for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
154
- const v = readStart(join(sd, id), id, keys);
155
- if (v && v.flow === flow && v.phase === 'starting') {
156
- unclaim();
157
- return { status: 409, body: { ok: false, refused: 'start-live', startId: id, say: 'A run of this flow is already starting. Wait for it.' } };
158
- }
166
+ const startingId = startingFor(flow, keys);
167
+ if (startingId !== null) {
168
+ unclaim();
169
+ return { status: 409, body: { ok: false, refused: 'start-live', startId: startingId, say: 'A run of this flow is already starting. Wait for it.' } };
159
170
  }
160
171
  const id = newId();
161
172
  const dir = join(sd, id);
@@ -164,7 +175,7 @@ export function createStarter(opts) {
164
175
  writeFileSync(join(dir, 'start.json'), `${JSON.stringify({
165
176
  kind, flow, runId, sources, startedAt: new Date().toISOString(),
166
177
  }, null, 2)}\n`, { mode: 0o600 });
167
- const argv = ['run', flow, '--root', realpathSync(root), ...sources.flatMap((s) => ['--source', `${s.role}=${s.path}`]), '--run-id', runId];
178
+ const argv = ['run', flow, '--root', realpathSync(root), ...sources.flatMap((s) => ['--source', `${s.role}=${s.path}`]), '--run-id', runId, ...(pick ? ['--model', pick.model, '--provider', pick.slot] : [])]; // M4d am7b: a flow with no record runs with the model picked in Chat
168
179
  let child;
169
180
  try {
170
181
  child = spawnDetached({
@@ -183,17 +194,16 @@ export function createStarter(opts) {
183
194
  * Start `fwdloop continue <runId>` (M4e amendment 4 item 4): Resume of a stopped or cap-halted run, after the door wrote the run's new
184
195
  * signed values version. The same detached-child shape as `start`; the start folder reads as `starting` until the child consumes
185
196
  * `halt.json`, then `started`; a child that died with `halt.json` still there is `refused` with its own sentence. One start at a time per flow.
186
- * @param {{ flow: string, runId: string, version: number }} a @param {Record<string, string|undefined>} env the merged keys env
197
+ * @param {{ flow: string, runId: string, version: number }} a @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded the keys load
187
198
  * @returns {{ status: number, body: any }}
188
199
  */
189
- startContinue({ flow, runId, version }, env) {
200
+ startContinue({ flow, runId, version }, loaded) {
201
+ const { env } = loaded;
190
202
  const sd = startsDir();
191
203
  if (sd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
192
- const keys = providerKeys(env);
193
- for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
194
- const v = readStart(join(sd, id), id, keys);
195
- if (v && v.flow === flow && v.phase === 'starting') return { status: 409, body: { ok: false, refused: 'start-live', startId: id, say: 'A run of this flow is already starting. Wait for it.' } };
196
- }
204
+ const keys = providerKeys(loaded);
205
+ const startingId = startingFor(flow, keys);
206
+ if (startingId !== null) return { status: 409, body: { ok: false, refused: 'start-live', startId: startingId, say: 'A run of this flow is already starting. Wait for it.' } };
197
207
  const id = newId();
198
208
  const dir = join(sd, id);
199
209
  mkdirSync(sd, { recursive: true, mode: 0o700 });