fwdloop 0.12.0 → 0.13.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 (56) hide show
  1. package/bin/fwdloop +136 -21
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +101 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +2 -1
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +41 -3
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/liveness.js +1 -1
  13. package/src/model-step.js +30 -4
  14. package/src/monthly.js +58 -13
  15. package/src/panel/author.js +482 -0
  16. package/src/panel/authorcard.js +297 -0
  17. package/src/panel/authorflows.js +312 -0
  18. package/src/panel/authorresume.js +149 -0
  19. package/src/panel/authorstart.js +257 -0
  20. package/src/panel/authorvalues.js +110 -0
  21. package/src/panel/data.js +228 -34
  22. package/src/panel/index.html +1745 -127
  23. package/src/panel/resume.js +6 -8
  24. package/src/panel/server.js +119 -119
  25. package/src/panel/settings.js +7 -5
  26. package/src/panel/spawn.js +77 -0
  27. package/src/provider.js +12 -17
  28. package/src/runner.js +639 -85
  29. package/src/runvalues.js +178 -0
  30. package/src/send.js +10 -3
  31. package/src/setup.js +120 -0
  32. package/types/authoring.d.ts +24 -2
  33. package/types/books.d.ts +14 -2
  34. package/types/canrun.d.ts +32 -0
  35. package/types/config.d.ts +1 -0
  36. package/types/declaration.d.ts +9 -1
  37. package/types/drafter.d.ts +15 -1
  38. package/types/draftspend.d.ts +21 -0
  39. package/types/flow.d.ts +23 -0
  40. package/types/liveness.d.ts +2 -2
  41. package/types/model-step.d.ts +3 -1
  42. package/types/monthly.d.ts +21 -0
  43. package/types/panel/author.d.ts +335 -0
  44. package/types/panel/authorcard.d.ts +120 -0
  45. package/types/panel/authorflows.d.ts +175 -0
  46. package/types/panel/authorresume.d.ts +32 -0
  47. package/types/panel/authorstart.d.ts +115 -0
  48. package/types/panel/authorvalues.d.ts +62 -0
  49. package/types/panel/data.d.ts +103 -12
  50. package/types/panel/server.d.ts +11 -33
  51. package/types/panel/spawn.d.ts +30 -0
  52. package/types/provider.d.ts +6 -9
  53. package/types/runner.d.ts +120 -5
  54. package/types/runvalues.d.ts +97 -0
  55. package/types/send.d.ts +5 -1
  56. package/types/setup.d.ts +83 -0
@@ -34,16 +34,16 @@
34
34
  // redact: it prints only its own error messages (never the key), so a key
35
35
  // could reach the log only through a provider error body that echoes it.
36
36
 
37
- import { spawn } from 'node:child_process';
38
37
  import { createHash, randomBytes } from 'node:crypto';
39
38
  import {
40
- closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync,
39
+ existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync,
41
40
  } from 'node:fs';
42
41
  import { tmpdir } from 'node:os';
43
42
  import { dirname, join } from 'node:path';
44
43
  import { fileURLToPath } from 'node:url';
45
44
  import { scrub } from '../authoring.js';
46
45
  import { PROVIDER_SLOTS } from '../provider.js';
46
+ import { spawnDetached } from './spawn.js';
47
47
 
48
48
  const HERE = dirname(fileURLToPath(import.meta.url));
49
49
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
@@ -105,13 +105,11 @@ export function createResumer(opts) {
105
105
  const loaded = loadEnv ? loadEnv() : { ok: true, env, refusal: null };
106
106
  if (!loaded.ok) return Promise.resolve({ kind: 'exited', code: null, sig: null, text: String(loaded.refusal) });
107
107
  const runEnv = loaded.env; // ONE object: the spawn env below AND the scrub list further down (POC (a) wiring rule)
108
- const fd = openSync(logPath, 'a', 0o600);
109
- const offset = statSync(logPath).size;
110
- const child = spawn(process.execPath, [bin, 'resume', runId, '--flow', flow, '--root', root], {
111
- detached: true, stdio: ['ignore', fd, fd], env: runEnv,
108
+ let offset = 0; // the log may not exist yet: the one spawn creates it
109
+ try { offset = statSync(logPath).size; } catch { /* a new log starts at 0 */ }
110
+ const child = spawnDetached({
111
+ bin, argv: ['resume', runId, '--flow', flow, '--root', root], env: runEnv, logPath,
112
112
  });
113
- child.unref();
114
- closeSync(fd);
115
113
  const runKey = keyOf(flow, runId);
116
114
  live.set(runKey, (live.get(runKey) ?? 0) + 1);
117
115
  let released = false;
@@ -30,8 +30,8 @@
30
30
  // `POST /api/resume`, which only re-starts a resume for a run that already has
31
31
  // a saved, unconsumed answer. M4c-fix amendment 1 adds `POST /api/reopen`, the human's one button on an expired ask
32
32
  // (`reopenAsk`, `src/ask.js`). All three are refused by name unless the request is
33
- // a real click from the served page — own `Host` and `Origin`, the per-process
34
- // token (embedded only in the served page), a small JSON body. An answer must
33
+ // a real click from the served page — own `Host` and `Origin` (no token, no
34
+ // cookie: M4e amendment 4 item 8), a small JSON body. An answer must
35
35
  // name its `askId`. `Host` is checked on EVERY route, GET included
36
36
  // (DNS-rebinding read). After an accepted answer the panel starts the resume
37
37
  // as a separate detached process and checks from the books that it took over
@@ -47,23 +47,20 @@
47
47
  // directory's own `index.html`, never a URL-derived filename.
48
48
 
49
49
  import { createServer } from 'node:http';
50
- import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
51
- import {
52
- chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync,
53
- } from 'node:fs';
54
- import { homedir } from 'node:os';
50
+ import { readFileSync, realpathSync } from 'node:fs';
55
51
  import path, { dirname, join } from 'node:path';
56
52
  import { fileURLToPath } from 'node:url';
57
53
 
58
54
  import { loadCatalogue } from '../catalogue.js';
59
55
  import { answerAsk, reopenAsk, normalizeDecision } from '../ask.js';
60
- import { readHistory } from '../books.js';
56
+ import { readHistory, endRow } from '../books.js';
61
57
  import { resolveRunDir } from '../flow.js';
62
- import { readAsk } from '../runner.js';
58
+ import { readAsk, requestStop, stopParkedRun } from '../runner.js';
63
59
  import {
64
- listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
60
+ listRuns, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
65
61
  } from './data.js';
66
62
  import { createResumer } from './resume.js';
63
+ import { createAuthor } from './author.js';
67
64
  import { keysForDoor } from '../keysfile.js';
68
65
  import { configDoorHome } from '../config.js';
69
66
  import { createSettings } from './settings.js';
@@ -73,9 +70,8 @@ const HERE = dirname(fileURLToPath(import.meta.url));
73
70
 
74
71
  /** Cap on the answer body — a decision and a short reason, nothing more. */
75
72
  const MAX_BODY_BYTES = 8 * 1024;
76
- /** Cookie the panel link sets; `<name>_<port>` so two panels on one host never clobber each other. */
77
- const cookieName = (port) => `fwdloop_panel_${port}`;
78
-
73
+ /** Cap on a draft-card body — a few numbered job lines, not a document (M4e). */
74
+ const MAX_AUTHOR_BODY_BYTES = 64 * 1024;
79
75
  /** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
80
76
  * is 4800 — bareloop owns 4700, and the two panels must be able to run
81
77
  * side by side. */
@@ -118,64 +114,6 @@ function refuse(res, code, name, detail) {
118
114
  sendJson(res, code, { ok: false, refused: name, red: detail ? `${name}: ${detail}` : name });
119
115
  }
120
116
 
121
- /** Constant-time compare: both sides hashed to equal length first, so neither
122
- * the content nor the length of the real token leaks through timing.
123
- * @param {unknown} a @param {string} b */
124
- function tokenMatches(a, b) {
125
- if (typeof a !== 'string') return false;
126
- const x = createHash('sha256').update(a).digest();
127
- const y = createHash('sha256').update(b).digest();
128
- return timingSafeEqual(x, y);
129
- }
130
-
131
- const tokenDir = (dir, env) => dir ?? (env.XDG_RUNTIME_DIR ? join(env.XDG_RUNTIME_DIR, 'fwdloop') : join(homedir(), '.cache', 'fwdloop'));
132
-
133
- /**
134
- * hamr's 2026-10-03 ruling "1A": the panel token is REUSED across restarts, so a bookmark of
135
- * `http://127.0.0.1:<port>/` keeps working once the link was opened. Reads the token file (same path
136
- * `writeTokenFile` writes); a new token only when the file is missing, unreadable, not a regular file,
137
- * not mode 0600, not ours, or not 64 hex chars (the caller then rewrites it 0600).
138
- * @param {{ port: number, dir?: string, env?: Record<string, string|undefined> }} a
139
- * @returns {string}
140
- */
141
- export function loadOrMakeToken({ port, dir, env = process.env }) {
142
- try {
143
- const d = tokenDir(dir, env);
144
- const file = join(d, `panel-${port}.token`);
145
- const st = lstatSync(file);
146
- const dst = lstatSync(d);
147
- const uid = typeof process.getuid === 'function' ? process.getuid() : null;
148
- if (dst.isDirectory() && (dst.mode & 0o777) === 0o700 && st.isFile() && (st.mode & 0o777) === 0o600 && (uid === null || st.uid === uid)) {
149
- const t = readFileSync(file, 'utf8').trim();
150
- if (/^[0-9a-f]{64}$/.test(t)) return t;
151
- }
152
- } catch { /* missing or unreadable: a new one */ }
153
- return randomBytes(32).toString('hex');
154
- }
155
-
156
- /**
157
- * M4c-fix item 2: the token's one on-disk home — `<dir>/panel-<port>.token`, dir 0700, file 0600,
158
- * `dir` = `$XDG_RUNTIME_DIR/fwdloop`, else `~/.cache/fwdloop`. Refuses a dir that is a symlink or
159
- * not ours. The file is replaced (unlink, then exclusive create at 0600), never rewritten in place,
160
- * so it never exists with a looser mode. Returns the file's path.
161
- * @param {{ port: number, token: string, dir?: string, env?: Record<string, string|undefined> }} a
162
- */
163
- export function writeTokenFile({
164
- port, token, dir, env = process.env,
165
- }) {
166
- const d = tokenDir(dir, env);
167
- const uid = typeof process.getuid === 'function' ? process.getuid() : null;
168
- mkdirSync(d, { recursive: true, mode: 0o700 });
169
- const st = lstatSync(d);
170
- if (!st.isDirectory() || (uid !== null && st.uid !== uid)) throw new Error('token dir is not a directory owned by this user');
171
- chmodSync(d, 0o700);
172
- const file = join(d, `panel-${port}.token`);
173
- try { unlinkSync(file); } catch { /* none yet */ }
174
- const fd = openSync(file, 'wx', 0o600);
175
- try { writeSync(fd, `${token}\n`); } finally { closeSync(fd); }
176
- return file;
177
- }
178
-
179
117
  /** Send a Settings handler's `{status, body}`; a throw is a plain 500, never a stack. @param {any} res @param {Promise<{status:number, body:any}>} pending @param {boolean} [headOnly] */
180
118
  function settingsReply(res, pending, headOnly = false) {
181
119
  pending.then((r) => {
@@ -257,7 +195,7 @@ function answerRoute(res, body, root, resumer) {
257
195
  }
258
196
 
259
197
  /**
260
- * `POST /api/reopen` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
198
+ * `POST /api/reopen` — runs after the same gates as the answer (own Host, own Origin). The human's
261
199
  * "Reopen for another <wait>" on an expired ask (M4c-fix amendment 1 (b)): `reopenAsk` writes the reopen record
262
200
  * (a fresh window of the same signed length, on the same ask) and moves a late answer aside. Nothing else reopens:
263
201
  * no runner or agent path calls it. Refused 409 while a resume of the run is alive, and for a run that has ended.
@@ -273,7 +211,7 @@ function reopenRoute(res, body, root, resumer) {
273
211
  const runDir = resolveRun(res, root, flow, runId);
274
212
  if (runDir === null) return;
275
213
  if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
276
- if (readHistory(dirname(dirname(runDir))).some((r) => r && r.runId === runId)) {
214
+ if (endRow(readHistory(dirname(dirname(runDir))), runDir, runId) !== null) {
277
215
  refuse(res, 409, 'run-ended', 'this run has ended — there is nothing to reopen');
278
216
  return;
279
217
  }
@@ -288,7 +226,7 @@ function reopenRoute(res, body, root, resumer) {
288
226
  }
289
227
 
290
228
  /**
291
- * `POST /api/remove-lock` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
229
+ * `POST /api/remove-lock` — runs after the same gates as the answer (own Host, own Origin). The human's
292
230
  * "Remove the old lock" (M4c-fix amendment 2 (h)): only for a run with a saved answer and no resume alive; `removeOldLock`
293
231
  * re-checks at this moment that the lock still has no recorded holder, removes it and writes the one audit row; then the
294
232
  * run continues exactly like "Continue the run" (the same `resumer.start`). Nothing else calls the remover.
@@ -315,6 +253,45 @@ function removeLockRoute(res, body, root, resumer) {
315
253
  });
316
254
  }
317
255
 
256
+ /** The two words of a refused Stop (bareloop's texts, M4e amendment 4 item 4). */
257
+ const NOT_RUNNING_SAY = 'This run is not running, so there is nothing to stop.';
258
+ const STARTING_SAY = 'The run is still starting — it has not written its log yet. Try again in a moment.';
259
+
260
+ /**
261
+ * `POST /api/stop` — runs after the same gates as the answer (own Host, own Origin). The human's Stop (M4e amendment 4
262
+ * item 4): writes the run's stop file; the runner reads it at the seam after the current step closes. Only a run that is
263
+ * running is stopped; a parked, ended or not-yet-started run is refused in words and nothing is written. The same
264
+ * decision (`runControls`) the Run tab's button reads.
265
+ * @param {any} res @param {any} body @param {string} root
266
+ */
267
+ async function stopRoute(res, body, root) {
268
+ const b = body !== null && typeof body === 'object' ? body : {};
269
+ const { flow, runId } = b;
270
+ const runDir = resolveRun(res, root, flow, runId);
271
+ if (runDir === null) return;
272
+ const loaded = loadCatalogue();
273
+ if (!loaded.ok) { refuse(res, 500, 'catalogue', 'the catalogue failed to load'); return; }
274
+ const controls = getRunControls({
275
+ root, flow, runId, catalogue: loaded.primitives,
276
+ });
277
+ if (controls === null) { refuse(res, 404, 'no-such-run', 'there is no such run'); return; }
278
+ if (controls.starting) { sendJson(res, 409, { ok: false, refused: 'starting', say: STARTING_SAY }); return; }
279
+ if (!controls.canStop) { sendJson(res, 409, { ok: false, refused: 'not-running', say: NOT_RUNNING_SAY }); return; }
280
+ // Amendment 13: a run waiting at its ask is stopped at the ask now; a running one is asked to stop and ends at its next seam.
281
+ // The write comes first and the parked check after it, so a park landing between the two is still caught (the runner checks
282
+ // the request after it writes the ask; whichever sees both wins the rename, the other finds nothing to do).
283
+ const written = requestStop(runDir);
284
+ const ask = readAsk(runDir);
285
+ if (controls.atAsk || (ask && parkedOnYou(runDir, ask.askId))) {
286
+ const stopped = await stopParkedRun({
287
+ root, name: flow, runId, catalogue: loaded.primitives,
288
+ });
289
+ if (stopped.outcome === 'stopped') { sendJson(res, 202, { ok: true, stopping: false, stopped: true }); return; }
290
+ // not parked after all (a resume took its answer) or a resume still closing: the request stays for the runner's own seam
291
+ }
292
+ sendJson(res, 202, { ok: true, stopping: true, already: written === 'exists' });
293
+ }
294
+
318
295
  /**
319
296
  * `POST /api/resume` — runs after the same gates as the answer. Starts a
320
297
  * resume ONLY for a run that has a saved, unconsumed answer; it takes no
@@ -340,13 +317,38 @@ function resumeRoute(res, body, root, resumer) {
340
317
  });
341
318
  }
342
319
 
320
+ /**
321
+ * `POST /api/author/{draft,run,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
322
+ * Anything else under `/api/author/` is a 404 by name.
323
+ * @param {any} res @param {string} url @param {any} body @param {ReturnType<typeof createAuthor>} author
324
+ */
325
+ function authorPost(res, url, body, author) {
326
+ const send = (r) => sendJson(res, r.status, r.body);
327
+ if (url === '/api/author/draft') { send(author.start(body)); return; }
328
+ if (url === '/api/author/run') { send(author.run(body)); return; }
329
+ if (url === '/api/author/run-prepare') { send(author.runPrepare(body)); return; }
330
+ if (url === '/api/author/resume-prepare') { send(author.resumePrepare(body)); return; }
331
+ if (url === '/api/author/resume') { send(author.resume(body)); return; }
332
+ const sp = /^\/api\/author\/([^/]+)\/sign-prepare$/.exec(url);
333
+ if (sp) { send(author.signPrepare(sp[1])); return; }
334
+ const sg = /^\/api\/author\/([^/]+)\/sign$/.exec(url);
335
+ if (sg) { send(author.sign(sg[1], body)); return; }
336
+ const rv = /^\/api\/author\/([^/]+)\/revise$/.exec(url);
337
+ if (rv) { send(author.revise(rv[1], body)); return; }
338
+ const sc = /^\/api\/author\/start\/([^/]+)\/clear$/.exec(url);
339
+ if (sc) { send(author.startClear(sc[1])); return; }
340
+ const m = /^\/api\/author\/([^/]+)\/abandon$/.exec(url);
341
+ if (m) { author.abandon(m[1]).then(send, () => sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' })); return; }
342
+ refuse(res, 404, 'not-found', url);
343
+ }
344
+
343
345
  /**
344
346
  * Handle one request against the API + the page. Exported
345
347
  * separately from {@link createPanelServer} so tests can drive it without a
346
348
  * real listening socket where that is simpler.
347
349
  * @param {import('node:http').IncomingMessage} req
348
350
  * @param {import('node:http').ServerResponse} res
349
- * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings> }} opts
351
+ * @param {{ root: string, port: number, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
350
352
  */
351
353
  export function handleRequest(req, res, opts) {
352
354
  const method = req.method ?? 'GET';
@@ -365,42 +367,18 @@ export function handleRequest(req, res, opts) {
365
367
  return;
366
368
  }
367
369
 
368
- // Gate 2 — EVERY route, every method (the page included): the panel's own cookie, set by opening
369
- // the printed `/?t=<token>` link. Without it: 403 by name, and nothing in the body is a token.
370
- const cookies = Object.fromEntries(String(req.headers.cookie ?? '').split(';').map((c) => {
371
- const i = c.indexOf('=');
372
- return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
373
- }));
374
- if (!tokenMatches(cookies[cookieName(opts.port)], opts.token)) {
375
- const link = method === 'GET' || method === 'HEAD' ? new URL(String(req.url), 'http://127.0.0.1') : null;
376
- if (link && link.pathname === '/' && tokenMatches(link.searchParams.get('t'), opts.token)) {
377
- res.writeHead(302, {
378
- 'set-cookie': `${cookieName(opts.port)}=${opts.token}; HttpOnly; SameSite=Strict; Path=/`, location: '/', 'content-length': 0,
379
- });
380
- res.end();
381
- return;
382
- }
383
- // A browser opening the bare page sees a plain page that says what to do, not a blank JSON "forbidden"
384
- // that reads as "the panel is down". No token, no script. API routes keep the JSON 403.
385
- if (link && link.pathname === '/' && /text\/html/.test(String(req.headers.accept ?? ''))) {
386
- const html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>fwdloop panel</title>'
387
- + '<p style="font:16px/1.5 system-ui,sans-serif;max-width:40em;margin:2em auto;padding:0 1em">'
388
- + 'fwdloop panel: open the link printed in the terminal where you started <code>fwdloop panel</code> (it ends in ?t=…). '
389
- + 'Restarted the panel? Open its new link.</p>';
390
- res.writeHead(403, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
391
- res.end(method === 'HEAD' ? undefined : html);
392
- return;
393
- }
394
- refuse(res, 403, 'cookie-missing-or-wrong', 'open the link `fwdloop panel` printed');
395
- return;
396
- }
370
+ // No token, no cookie (M4e amendment 4 item 8): the panel is local and trusted. What guards it is Gate 1 above
371
+ // (own Host, so a DNS-rebinding name is refused), the 127.0.0.1-only bind, and the Origin check on every POST below.
397
372
 
398
373
  // M4d piece 4: every `/api/settings/...` POST (a known one or not) goes through the same Origin + body-cap gates.
399
374
  const isSettingsPost = method === 'POST' && String(req.url).startsWith('/api/settings/');
400
- if (method === 'POST' && (isSettingsPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock')) {
375
+ // M4e piece 2a: every `/api/author/...` POST goes through the SAME door (own Host, own Origin, body cap) — no second guard.
376
+ const isAuthorPost = method === 'POST' && String(req.url).startsWith('/api/author/');
377
+ if (method === 'POST' && (isSettingsPost || isAuthorPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock' || req.url === '/api/stop')) {
401
378
  const isResume = req.url === '/api/resume';
402
379
  const isReopen = req.url === '/api/reopen';
403
380
  const isRemoveLock = req.url === '/api/remove-lock';
381
+ const isStop = req.url === '/api/stop';
404
382
  const origin = req.headers.origin;
405
383
  if (origin !== `http://127.0.0.1:${opts.port}` && origin !== `http://localhost:${opts.port}`) {
406
384
  refuse(res, 403, 'origin-not-own', String(origin));
@@ -412,7 +390,7 @@ export function handleRequest(req, res, opts) {
412
390
  req.on('data', (c) => {
413
391
  if (tooBig) return;
414
392
  size += c.length;
415
- if (size <= MAX_BODY_BYTES) { parts.push(c); return; }
393
+ if (size <= (isAuthorPost ? MAX_AUTHOR_BODY_BYTES : MAX_BODY_BYTES)) { parts.push(c); return; }
416
394
  // M4c-fix item 6: over the limit — stop at once. Drop what was collected, refuse (413, then the
417
395
  // connection closes), and cut the request off; the rest of the body is never read.
418
396
  tooBig = true;
@@ -426,10 +404,16 @@ export function handleRequest(req, res, opts) {
426
404
  if (tooBig) return;
427
405
  let body;
428
406
  try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
407
+ if (isAuthorPost) { authorPost(res, String(req.url), body, opts.author); return; }
429
408
  if (isSettingsPost) { settingsReply(res, opts.settings.handle({ method, pathname: String(req.url), query: new URLSearchParams(), body })); return; }
430
409
  if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
431
410
  else if (isReopen) reopenRoute(res, body, opts.root, opts.resumer);
432
411
  else if (isRemoveLock) removeLockRoute(res, body, opts.root, opts.resumer);
412
+ else if (isStop) {
413
+ stopRoute(res, body, opts.root).catch(() => {
414
+ if (!res.headersSent) sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
415
+ });
416
+ }
433
417
  else answerRoute(res, body, opts.root, opts.resumer);
434
418
  } catch (e) {
435
419
  sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
@@ -439,7 +423,7 @@ export function handleRequest(req, res, opts) {
439
423
  }
440
424
 
441
425
  if (method !== 'GET' && method !== 'HEAD') {
442
- sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer, POST /api/resume, POST /api/reopen and POST /api/remove-lock');
426
+ sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer, POST /api/resume, POST /api/reopen, POST /api/remove-lock, POST /api/stop, POST /api/settings/... and POST /api/author/...');
443
427
  return;
444
428
  }
445
429
 
@@ -462,6 +446,22 @@ export function handleRequest(req, res, opts) {
462
446
  sendJson(res, code, body);
463
447
  };
464
448
 
449
+ if (pathname.startsWith('/api/author/')) {
450
+ const am = /^\/api\/author\/([^/]+)$/.exec(pathname);
451
+ const sm = /^\/api\/author\/start\/([^/]+)$/.exec(pathname);
452
+ let r = { status: 404, body: /** @type {any} */ ({ ok: false, refused: 'not-found' }) };
453
+ if (pathname === '/api/author/live') r = opts.author.live();
454
+ else if (pathname === '/api/author/flows') r = opts.author.flows();
455
+ else if (pathname === '/api/author/run-again') r = opts.author.runAgain(url.searchParams.get('flow'), url.searchParams.get('runId'));
456
+ else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'));
457
+ else if (pathname === '/api/author/resume-form') r = opts.author.resumeForm(url.searchParams.get('flow'), url.searchParams.get('runId'));
458
+ else if (sm) r = opts.author.startGet(sm[1]);
459
+ else if (am) r = opts.author.get(am[1]);
460
+ if (method === 'HEAD') { res.writeHead(r.status, { 'content-type': 'application/json; charset=utf-8' }); res.end(); return; }
461
+ sendJson(res, r.status, r.body);
462
+ return;
463
+ }
464
+
465
465
  if (pathname.startsWith('/api/settings/')) {
466
466
  settingsReply(res, opts.settings.handle({
467
467
  method: 'GET', pathname, query: url.searchParams, body: null,
@@ -566,9 +566,9 @@ export function handleRequest(req, res, opts) {
566
566
  * header). Resolves once actually listening; rejects on a bind error
567
567
  * (including `EADDRINUSE`) with a `.port` field on the error for the
568
568
  * caller's message.
569
- * @param {{ port?: number, root: string, token?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
570
- * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
571
- * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
569
+ * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
570
+ * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
571
+ * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
572
572
  */
573
573
  export function createPanelServer(opts) {
574
574
  if (typeof opts?.root !== 'string' || opts.root.length === 0) {
@@ -579,15 +579,17 @@ export function createPanelServer(opts) {
579
579
  // One resumer per server: the one owner of every run's resume-attempt record.
580
580
  // M4d: the keys file is re-read before EVERY resume spawn (editing it needs no restart); an env injected by a test is the shell side.
581
581
  const resumer = createResumer({ root, loadEnv: () => keysForDoor({ env: opts.resume?.env }), ...opts.resume });
582
+ // M4e piece 2a: the draft door. Same keys door as the resumer: the merged env is re-read before every spawn and every log quote.
583
+ // The courtesy "left this month" line reads the SAME home the CLI's monthly check does (injected, else the door's).
584
+ const door = configDoorHome();
585
+ const author = createAuthor({
586
+ root, home: opts.settings?.home ?? door.home, skipMonthly: opts.settings?.home === undefined && door.skip, loadEnv: () => keysForDoor({ env: opts.author?.env }), ...opts.author,
587
+ });
582
588
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
583
589
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
584
- const door = configDoorHome();
585
590
  const settings = createSettings({
586
591
  home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now,
587
592
  });
588
- // One token per server process, made once, held only here and in the served
589
- // page — never logged, never in any /api response.
590
- const token = typeof opts.token === 'string' && /^[0-9a-f]{64}$/.test(opts.token) ? opts.token : randomBytes(32).toString('hex');
591
593
  return new Promise((resolve, reject) => {
592
594
  // Bound port is resolved from the live socket (`server.address().port`)
593
595
  // once listening starts, not the requested value — this is what makes
@@ -598,7 +600,7 @@ export function createPanelServer(opts) {
598
600
  const server = createServer((req, res) => {
599
601
  try {
600
602
  handleRequest(req, res, {
601
- root, port: boundPort, token, resumer, settings,
603
+ root, port: boundPort, resumer, settings, author,
602
604
  });
603
605
  } catch (e) {
604
606
  sendText(res, 500, 'internal error');
@@ -615,7 +617,6 @@ export function createPanelServer(opts) {
615
617
  resolve({
616
618
  server,
617
619
  port: boundPort,
618
- token,
619
620
  close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
620
621
  });
621
622
  });
@@ -645,14 +646,13 @@ export async function panelMain(argv, ctx) {
645
646
  }
646
647
  }
647
648
  try {
648
- const { port: boundPort, token } = await createPanelServer({ port, root, token: loadOrMakeToken({ port }) });
649
- writeTokenFile({ port: boundPort, token });
649
+ const { port: boundPort } = await createPanelServer({ port, root });
650
650
  // M4d: read the keys file at start (creates it when missing). The panel itself needs no key, so a file other users can
651
651
  // read is only announced here; every resume re-reads it and refuses by itself.
652
652
  const keys = keysForDoor();
653
653
  if (!keys.ok) ctx.err(String(keys.refusal));
654
654
  ctx.out(`fwdloop panel — (root: ${root}) (Ctrl-C to stop)`);
655
- ctx.out(`open this link (it sets the panel's cookie): http://127.0.0.1:${boundPort}/?t=${token}`);
655
+ ctx.out(`http://127.0.0.1:${boundPort}/`);
656
656
  // never resolves on its own — the process stays up until killed, same
657
657
  // shape any other long-running dev server takes.
658
658
  await new Promise(() => {});
@@ -14,7 +14,7 @@
14
14
  // Every refusal is a plain sentence in `say`; nothing here puts an HTTP code, an id or a path on the page.
15
15
  import { PROVIDER_SLOTS, resolvePrices, resolveSlot, checkKeyPreflight } from '../provider.js';
16
16
  import {
17
- readConfig, updateConfig, ConfigError, PRICE_FIELDS, providerFieldProblem, cleanBaseUrl,
17
+ readConfig, updateConfig, ConfigError, providerFieldProblem, cleanBaseUrl,
18
18
  } from '../config.js';
19
19
  import { SHAPES } from '../providershapes.js';
20
20
  import { keysForDoor } from '../keysfile.js';
@@ -23,8 +23,8 @@ import { spendSummary } from '../monthly.js';
23
23
  const DEEPSEEK_BALANCE_URL = 'https://api.deepseek.com/user/balance';
24
24
  const TIMEOUT_MS = 4000;
25
25
 
26
- /** Plain words for each price field (the page's three boxes). */
27
- const FIELD_LABEL = Object.freeze({ inPerM: 'Input', cachedInPerM: 'Cached input', outPerM: 'Output' });
26
+ /** Plain words for each price field (the page's two boxes; cached input is priced as input, M4d amendment 2). */
27
+ const FIELD_LABEL = Object.freeze({ inPerM: 'Input', outPerM: 'Output' });
28
28
 
29
29
  const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
30
30
 
@@ -87,7 +87,6 @@ export function createSettings(cfg) {
87
87
  tokens: spend.byProvider[slot]?.total.tokens ?? 0,
88
88
  price: {
89
89
  inPerM: one(p.perM.inPerM, p.source.in),
90
- cachedInPerM: one(p.perM.cachedInPerM, p.source.cachedIn),
91
90
  outPerM: one(p.perM.outPerM, p.source.out),
92
91
  },
93
92
  canBalance: canBalance(eff),
@@ -179,7 +178,10 @@ export function createSettings(cfg) {
179
178
  if (!slot) return refuse('unknown-provider', 'That provider is not known.');
180
179
  /** @type {Record<string, number|null>} */
181
180
  const patch = {};
182
- for (const f of PRICE_FIELDS) {
181
+ if (Object.hasOwn(body, 'cachedInPerM')) {
182
+ return refuse('bad-price', 'Cached input has no price of its own: it is priced as input. Nothing was saved.');
183
+ }
184
+ for (const f of /** @type {const} */ (['inPerM', 'outPerM'])) {
183
185
  if (!Object.hasOwn(body, f)) continue;
184
186
  const v = body[f];
185
187
  if (v !== null && !isNumberAbove0(v)) {
@@ -0,0 +1,77 @@
1
+ // M4e piece 2a, item 4 (docs/wiki/the-module-ladder.md, "M4e", scope 5): the ONE detached spawn the panel uses
2
+ // for every CLI child it starts — `fwdloop resume` (src/panel/resume.js) and `fwdloop draft` (src/panel/author.js)
3
+ // (and, later, `fwdloop run`). Extracted from resume.js's tryOnce, shape unchanged:
4
+ // process.execPath + the bin + an ARRAY argv (no shell), `detached: true` (own process group, so the child
5
+ // outlives the panel and a group kill reaches only it), `unref()`, stdio -> the log file (mode 0600 on create),
6
+ // env = exactly the object the caller passes.
7
+ // The caller passes the merged keys env (`keysForDoor`) and uses THAT SAME OBJECT as its scrub list (POC (a)
8
+ // wiring rule, M4d) — this function never reads process.env itself.
9
+ import { spawn } from 'node:child_process';
10
+ import { closeSync, openSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ import { readFileInside } from '../flow.js';
14
+ import { isFwdloopAlive, procStartOf } from '../liveness.js';
15
+ import { PROVIDER_SLOTS } from '../provider.js';
16
+
17
+ /** A pid whose liveness cannot be told (no /proc) counts as running only while its pid.json is this fresh (M4c's 10-minute rule). */
18
+ const UNKNOWN_FRESH_MS = 10 * 60 * 1000;
19
+
20
+ /**
21
+ * @param {{ bin: string, argv: string[], env: Record<string, string|undefined>, logPath: string }} a
22
+ * @returns {import('node:child_process').ChildProcess} the child (already `unref()`ed; the log fd is closed here)
23
+ */
24
+ export function spawnDetached({
25
+ bin, argv, env, logPath,
26
+ }) {
27
+ const fd = openSync(logPath, 'a', 0o600);
28
+ try {
29
+ const child = spawn(process.execPath, [bin, ...argv], { detached: true, stdio: ['ignore', fd, fd], env });
30
+ child.unref();
31
+ return child;
32
+ } finally {
33
+ closeSync(fd);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The ONE writer of a panel child's `pid.json` (`<dir>/pid.json`): the pid, its /proc starttime and when it was started.
39
+ * Called right after the spawn by the draft door and the start door. A child with no pid writes nothing.
40
+ * @param {string} dir @param {import('node:child_process').ChildProcess} child
41
+ */
42
+ export function writePidFile(dir, child) {
43
+ if (!Number.isInteger(child.pid)) return;
44
+ writeFileSync(join(dir, 'pid.json'), `${JSON.stringify({ pid: child.pid, procStart: procStartOf(/** @type {number} */ (child.pid)), startedAt: Date.now() })}\n`, { mode: 0o600 });
45
+ }
46
+
47
+ /** One JSON file of a panel folder through the one safe gateway; null when missing, unreadable or not an object. @param {string} dir @param {string} rel */
48
+ export function readJsonFile(dir, rel) {
49
+ const r = readFileInside(dir, rel);
50
+ if (!r.ok) return null;
51
+ try { const j = JSON.parse(r.text); return j && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; }
52
+ }
53
+
54
+ /**
55
+ * Is the child recorded in `<dir>/pid.json` running? true / false, never null: no pid.json = nothing known to be running =
56
+ * false; a liveness that cannot be told (no /proc) reads as running only while pid.json is fresh (M4c's rule).
57
+ * @param {string} dir
58
+ */
59
+ export function childRunning(dir) {
60
+ const pid = readJsonFile(dir, 'pid.json');
61
+ if (!pid || !Number.isInteger(pid.pid)) return false;
62
+ const alive = isFwdloopAlive(pid.pid, typeof pid.procStart === 'string' ? pid.procStart : null);
63
+ if (alive !== null) return alive;
64
+ return typeof pid.startedAt === 'number' && Date.now() - pid.startedAt <= UNKNOWN_FRESH_MS;
65
+ }
66
+
67
+ /**
68
+ * The provider key VALUES in the merged env — the scrub list. The env that holds them is the SAME object that is the child's
69
+ * spawn env (POC (a), M4d wiring rule), so the list can never differ from what the child was given.
70
+ * @param {Record<string, string|undefined>} env
71
+ */
72
+ export function providerKeys(env) {
73
+ /** @type {string[]} */
74
+ const out = [];
75
+ for (const p of Object.values(PROVIDER_SLOTS)) { const k = env[p.envVar]; if (typeof k === 'string' && k !== '') out.push(k); }
76
+ return out;
77
+ }
package/src/provider.js CHANGED
@@ -115,8 +115,8 @@ export function resolveSlot(slotName, { config = {} } = {}) {
115
115
  * provider slot) wins over a row here, per field, through `resolvePrices` below —
116
116
  * the one lookup every model call is booked and cap-checked by (M4d, signed
117
117
  * 2026-10-05; that REPLACES the 2026-09-21 "edit a row here, never a runtime
118
- * flag" ruling). `cacheIn` (optional) is the cache-READ price per 1K; a row
119
- * without it books cache reads at bare-agent's default 0.1x of `in`.
118
+ * flag" ruling). Cached input is priced as input
119
+ * (M4d amendment 2): a row has no cache rate.
120
120
  */
121
121
  export const RATES_BY_SUFFIX = {
122
122
  'zai-org/GLM-5.2': { in: 0.0006, out: 0.0022, source: 'published' },
@@ -130,9 +130,9 @@ export const RATES_BY_SUFFIX = {
130
130
  'syn:small:text': { in: 0.0006, out: 0.0025, source: 'ceiling' },
131
131
  'deepseek-v4-flash': { in: 0.00044, out: 0.00132, source: 'published' }, // F22: retired name, historical rows only
132
132
  // DeepSeek-V4.1-Flash, peak. Source: https://api-docs.deepseek.com/quick_start/pricing/ (fetched
133
- // 2026-10-05: cache hit $0.006, cache miss $0.30, output $1.20 per 1M). `cacheIn` = the hit price
134
- // (hamr ruling "A", 2026-10-05, poc/m4d/RESULTS.md (b): bare-agent's 0.1x default booked hits 5x real).
135
- 'deepseek-flash': { in: 0.0003, cacheIn: 0.000006, out: 0.0012, source: 'published' },
133
+ // 2026-10-05: cache miss $0.30, output $1.20 per 1M). The cache-hit
134
+ // price is deliberately not used: cached input books at `in` (M4d amendment 2, signed 2026-10-06).
135
+ 'deepseek-flash': { in: 0.0003, out: 0.0012, source: 'published' },
136
136
  'deepseek-v4-pro': { in: 0.00132, out: 0.00396, source: 'published' },
137
137
  };
138
138
 
@@ -172,15 +172,15 @@ const perM = (per1K) => Number((per1K * 1000).toPrecision(12));
172
172
  * THE one price lookup (M4d scope item 6): every model call — run, resume, model step, drafter —
173
173
  * is booked and cap-checked from this. Per field: a Settings price (`config.prices[slot]`, USD per
174
174
  * 1M -> per 1K) wins, else the code table's row, else the table's HIGHEST entry for that field
175
- * (an unknown model; unknown cost is never 0). A cache-read price is known only from Settings or a
176
- * row's `cacheIn`; otherwise it is left out (`cacheReadMult` omitted -> bare-agent's 0.1x of `in`).
175
+ * (an unknown model; unknown cost is never 0). M4d amendment 2: cached input is priced AS input —
176
+ * `cacheReadMult` is always 1; a saved `cachedInPerM` and a row's `cacheIn` are never read here.
177
177
  *
178
178
  * @param {string} modelId
179
179
  * @param {{ slot?: string, config?: Record<string, any>, ratesTable?: Record<string, any> }} [opts]
180
180
  * @returns {{
181
181
  * rates: { in: number, out: number, cacheReadMult?: number },
182
182
  * perM: { inPerM: number, cachedInPerM: number, outPerM: number },
183
- * source: { in: 'settings'|'table'|'ceiling', cachedIn: 'settings'|'table'|'default-multiplier', out: 'settings'|'table'|'ceiling' },
183
+ * source: { in: 'settings'|'table'|'ceiling', cachedIn: 'input', out: 'settings'|'table'|'ceiling' },
184
184
  * suffix: string|null,
185
185
  * }}
186
186
  */
@@ -196,17 +196,12 @@ export function resolvePrices(modelId, { slot, config = {}, ratesTable = RATES_B
196
196
  };
197
197
  const inF = field('inPerM', 'in');
198
198
  const outF = field('outPerM', 'out');
199
- let cachedIn = null;
200
- let cachedSrc = 'default-multiplier';
201
- if (set.cachedInPerM !== undefined) { cachedIn = set.cachedInPerM / 1000; cachedSrc = 'settings'; }
202
- else if (row && row.cacheIn !== undefined) { cachedIn = row.cacheIn; cachedSrc = 'table'; }
203
- /** @type {{ in: number, out: number, cacheReadMult?: number }} */
204
- const rates = { in: inF.v, out: outF.v };
205
- if (cachedIn !== null) rates.cacheReadMult = cachedIn / inF.v;
199
+ /** @type {{ in: number, out: number, cacheReadMult: number }} */
200
+ const rates = { in: inF.v, out: outF.v, cacheReadMult: 1 };
206
201
  return {
207
202
  rates,
208
- perM: { inPerM: perM(inF.v), cachedInPerM: perM(cachedIn ?? inF.v * 0.1), outPerM: perM(outF.v) },
209
- source: { in: /** @type {any} */ (inF.src), cachedIn: /** @type {any} */ (cachedSrc), out: /** @type {any} */ (outF.src) },
203
+ perM: { inPerM: perM(inF.v), cachedInPerM: perM(inF.v), outPerM: perM(outF.v) },
204
+ source: { in: /** @type {any} */ (inF.src), cachedIn: 'input', out: /** @type {any} */ (outF.src) },
210
205
  suffix: resolved ? resolved.suffix : null,
211
206
  };
212
207
  }