fwdloop 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fwdloop +15 -11
- package/package.json +1 -1
- package/src/ask.js +219 -8
- package/src/authoring.js +31 -5
- package/src/books.js +20 -0
- package/src/liveness.js +160 -0
- package/src/model-step.js +4 -3
- package/src/panel/data.js +468 -76
- package/src/panel/index.html +774 -205
- package/src/panel/lock.js +42 -0
- package/src/panel/resume.js +35 -4
- package/src/panel/server.js +261 -45
- package/src/provider.js +9 -1
- package/src/runner.js +112 -21
- package/types/ask.d.ts +82 -1
- package/types/authoring.d.ts +3 -2
- package/types/books.d.ts +19 -0
- package/types/liveness.d.ts +70 -0
- package/types/panel/data.d.ts +210 -20
- package/types/panel/lock.d.ts +21 -0
- package/types/panel/resume.d.ts +4 -0
- package/types/panel/server.d.ts +30 -2
- package/types/runner.d.ts +4 -3
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// M4c-fix amendment 2 (h): the human's "Remove the old lock". The ONE remover of a resume lock, and it lives in the
|
|
2
|
+
// panel: only `POST /api/remove-lock` (src/panel/server.js) calls it. No runner, resume or agent path imports this
|
|
3
|
+
// file — the machine never removes a lock it cannot judge (test: m4c-fix-remove-lock.test.js greps every src file).
|
|
4
|
+
import { realpathSync, unlinkSync } from 'node:fs';
|
|
5
|
+
import { join, sep } from 'node:path';
|
|
6
|
+
import { appendAudit } from '../books.js';
|
|
7
|
+
import { readResumeLock } from '../liveness.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Remove `<runDir>/resume.lock`, only if at THIS moment it has no recorded holder (`readResumeLock` -> `empty`;
|
|
11
|
+
* a live, dead or unknowable holder is never touched), and only if the lock file really sits inside this run dir
|
|
12
|
+
* (realpath of the run dir against realpath of `--root` at use time; a symlinked lock is unlinked as the link itself,
|
|
13
|
+
* never followed).
|
|
14
|
+
* Then one audit row through the one audit writer, shaped like the `ask-reopened` row (a pure note: cost 0, no model).
|
|
15
|
+
* @param {{root: string, runDir: string, nowIso?: string}} a
|
|
16
|
+
* @returns {{ok: true, at: string}|{ok: false, refused: 'no-lock'|'lock-has-holder'|'lock-outside-run', red: string}}
|
|
17
|
+
*/
|
|
18
|
+
export function removeOldLock({ root, runDir, nowIso = new Date().toISOString() }) {
|
|
19
|
+
const lock = readResumeLock(runDir);
|
|
20
|
+
if (lock.state === 'none') return { ok: false, refused: 'no-lock', red: 'there is no resume lock to remove' };
|
|
21
|
+
if (lock.state !== 'empty') return { ok: false, refused: 'lock-has-holder', red: `the resume lock has a recorded holder (${lock.state}) — not removed` };
|
|
22
|
+
let inside = false;
|
|
23
|
+
try {
|
|
24
|
+
const real = realpathSync(runDir);
|
|
25
|
+
const realRoot = realpathSync(root);
|
|
26
|
+
inside = (real + sep).startsWith(realRoot + sep) && real === realpathSync(join(lock.path, '..'));
|
|
27
|
+
} catch { inside = false; }
|
|
28
|
+
if (!inside) return { ok: false, refused: 'lock-outside-run', red: 'the resume lock is not inside this run — not removed' };
|
|
29
|
+
// Amendment 3 (d): look once more right before the unlink. This shrinks the window, it cannot close it: a resume
|
|
30
|
+
// can still take the lock between this read and the unlink — the written known limit of (d).
|
|
31
|
+
if (readResumeLock(runDir).state !== 'empty') return { ok: false, refused: 'lock-has-holder', red: 'the resume lock has a recorded holder — not removed' };
|
|
32
|
+
try { unlinkSync(lock.path); } catch (err) {
|
|
33
|
+
if (err.code === 'ENOENT') return { ok: false, refused: 'no-lock', red: 'there is no resume lock to remove' };
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
appendAudit(runDir, {
|
|
37
|
+
step: 'ask', attempt: null, class: null, verdict: 'lock-removed',
|
|
38
|
+
gap: `removed by human via panel at ${nowIso}`,
|
|
39
|
+
usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: nowIso, tokens: null, tools: null, refused: [],
|
|
40
|
+
});
|
|
41
|
+
return { ok: true, at: nowIso };
|
|
42
|
+
}
|
package/src/panel/resume.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
// numbers). Only the lock refusal is retried.
|
|
18
18
|
// 3. Still unconsumed after the last try (or a non-lock refusal): the attempt
|
|
19
19
|
// record says so, with the child's own refusal text verbatim; `data.js`
|
|
20
|
-
// turns that into "answer saved
|
|
20
|
+
// turns that into "your answer is saved; the run stopped before using it".
|
|
21
21
|
//
|
|
22
22
|
// No second mutex: exactly one resume applies the answer because the resume's
|
|
23
23
|
// own rename-to-consume is atomic (F44). This module only decides whether to
|
|
@@ -35,13 +35,15 @@
|
|
|
35
35
|
// could reach the log only through a provider error body that echoes it.
|
|
36
36
|
|
|
37
37
|
import { spawn } from 'node:child_process';
|
|
38
|
-
import { createHash } from 'node:crypto';
|
|
38
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
39
39
|
import {
|
|
40
40
|
closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync,
|
|
41
41
|
} from 'node:fs';
|
|
42
42
|
import { tmpdir } from 'node:os';
|
|
43
43
|
import { dirname, join } from 'node:path';
|
|
44
44
|
import { fileURLToPath } from 'node:url';
|
|
45
|
+
import { scrub } from '../authoring.js';
|
|
46
|
+
import { PROVIDER_SLOTS } from '../provider.js';
|
|
45
47
|
|
|
46
48
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
47
49
|
const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
|
|
@@ -89,6 +91,9 @@ export function createResumer(opts) {
|
|
|
89
91
|
const rootTag = createHash('sha256').update(root).digest('hex').slice(0, 8);
|
|
90
92
|
/** @type {Map<string, any>} */
|
|
91
93
|
const attempts = new Map();
|
|
94
|
+
/** Run key -> how many resume CHILD processes of this panel are alive for it. The one writer is
|
|
95
|
+
* `tryOnce` (+1 at spawn, -1 once, at the child's exit/error); `busy` only reads it. */
|
|
96
|
+
const live = new Map();
|
|
92
97
|
const keyOf = (flow, runId) => `${flow}/${runId}`;
|
|
93
98
|
|
|
94
99
|
/** One resume process. Resolves as soon as the books show the answer consumed,
|
|
@@ -102,8 +107,22 @@ export function createResumer(opts) {
|
|
|
102
107
|
});
|
|
103
108
|
child.unref();
|
|
104
109
|
closeSync(fd);
|
|
110
|
+
const runKey = keyOf(flow, runId);
|
|
111
|
+
live.set(runKey, (live.get(runKey) ?? 0) + 1);
|
|
112
|
+
let released = false;
|
|
113
|
+
const release = () => {
|
|
114
|
+
if (released) return;
|
|
115
|
+
released = true;
|
|
116
|
+
const n = (live.get(runKey) ?? 1) - 1;
|
|
117
|
+
if (n <= 0) live.delete(runKey); else live.set(runKey, n);
|
|
118
|
+
};
|
|
119
|
+
child.once('exit', release);
|
|
120
|
+
child.once('error', release);
|
|
121
|
+
// The child's output is quoted in a refusal (`reason`) that reaches HTTP responses and the books: the
|
|
122
|
+
// provider key(s) of this panel's env are scrubbed here, the one place that reads the log slice (amendment 1 (e)(3)).
|
|
123
|
+
const keys = Object.values(PROVIDER_SLOTS).map((p) => env[p.envVar]).filter(Boolean);
|
|
105
124
|
const sliceOfLog = () => {
|
|
106
|
-
try { return readFileSync(logPath).subarray(offset).toString('utf8').trim(); } catch { return ''; } // offset is in BYTES
|
|
125
|
+
try { return scrub(readFileSync(logPath).subarray(offset).toString('utf8').trim(), keys); } catch { return ''; } // offset is in BYTES
|
|
107
126
|
};
|
|
108
127
|
const settled = new Promise((resolve) => {
|
|
109
128
|
let done = false;
|
|
@@ -137,7 +156,9 @@ export function createResumer(opts) {
|
|
|
137
156
|
|
|
138
157
|
async function loop(rec, runDir) {
|
|
139
158
|
const t0 = Date.now();
|
|
140
|
-
|
|
159
|
+
// One log file per attempt record (never per run): a second resume of the same run must not
|
|
160
|
+
// append to, nor have its log deleted by, the first one's clean exit (M4c-fix item 7).
|
|
161
|
+
const logPath = join(ensureLogDir(opts.logDir), `resume-${rootTag}-${rec.flow}-${rec.runId}-${randomBytes(4).toString('hex')}.log`);
|
|
141
162
|
rec.logPath = logPath;
|
|
142
163
|
const consumed = () => existsSync(join(runDir, `answer.${rec.askId}.consumed.json`));
|
|
143
164
|
for (let n = 1; n <= maxTries; n += 1) {
|
|
@@ -176,6 +197,9 @@ export function createResumer(opts) {
|
|
|
176
197
|
const key = keyOf(flow, runId);
|
|
177
198
|
const old = attempts.get(key);
|
|
178
199
|
if (old) old.superseded = true;
|
|
200
|
+
// The previous attempt's reason is stale once a newer one starts (routes never start one while a
|
|
201
|
+
// child is alive): drop its log so refusal logs do not pile up, one per attempt (item 7).
|
|
202
|
+
if (old && old.state !== 'in-flight' && old.logPath) { try { unlinkSync(old.logPath); } catch { /* already gone */ } }
|
|
179
203
|
const rec = {
|
|
180
204
|
flow, runId, askId, state: 'in-flight', tries: 0, maxTries, windowMs, refusal: null, startedAt: Date.now(), endedAt: null, logPath: null, superseded: false,
|
|
181
205
|
};
|
|
@@ -183,6 +207,13 @@ export function createResumer(opts) {
|
|
|
183
207
|
loop(rec, runDir).catch((e) => finish(rec, 'stuck', `the panel could not start the resume: ${e.message}`));
|
|
184
208
|
return { ...rec };
|
|
185
209
|
},
|
|
210
|
+
/** True while this run is already resuming: a resume child of this panel is alive for it, or its
|
|
211
|
+
* latest attempt is still starting (between tries). Routes refuse a second resume while true.
|
|
212
|
+
* @param {string} flow @param {string} runId */
|
|
213
|
+
busy(flow, runId) {
|
|
214
|
+
const k = keyOf(flow, runId);
|
|
215
|
+
return (live.get(k) ?? 0) > 0 || attempts.get(k)?.state === 'in-flight';
|
|
216
|
+
},
|
|
186
217
|
/** A copy of the run's attempt record, or null (none yet, or the panel restarted).
|
|
187
218
|
* @param {string} flow @param {string} runId */
|
|
188
219
|
get(flow, runId) {
|
package/src/panel/server.js
CHANGED
|
@@ -28,7 +28,8 @@
|
|
|
28
28
|
// nothing new. The writes are `POST /api/answer`, a thin client of the
|
|
29
29
|
// library's `answerAsk` (the panel is never a second arbiter), and
|
|
30
30
|
// `POST /api/resume`, which only re-starts a resume for a run that already has
|
|
31
|
-
// a saved, unconsumed answer.
|
|
31
|
+
// a saved, unconsumed answer. M4c-fix amendment 1 adds `POST /api/reopen`, the human's one button on an expired ask
|
|
32
|
+
// (`reopenAsk`, `src/ask.js`). All three are refused by name unless the request is
|
|
32
33
|
// a real click from the served page — own `Host` and `Origin`, the per-process
|
|
33
34
|
// token (embedded only in the served page), a small JSON body. An answer must
|
|
34
35
|
// name its `askId`. `Host` is checked on EVERY route, GET included
|
|
@@ -47,24 +48,30 @@
|
|
|
47
48
|
|
|
48
49
|
import { createServer } from 'node:http';
|
|
49
50
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
50
|
-
import {
|
|
51
|
-
|
|
51
|
+
import {
|
|
52
|
+
chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync,
|
|
53
|
+
} from 'node:fs';
|
|
54
|
+
import { homedir } from 'node:os';
|
|
55
|
+
import path, { dirname, join } from 'node:path';
|
|
52
56
|
import { fileURLToPath } from 'node:url';
|
|
53
57
|
|
|
54
58
|
import { loadCatalogue } from '../catalogue.js';
|
|
55
|
-
import { answerAsk, normalizeDecision } from '../ask.js';
|
|
56
|
-
import {
|
|
59
|
+
import { answerAsk, reopenAsk, normalizeDecision } from '../ask.js';
|
|
60
|
+
import { readHistory } from '../books.js';
|
|
61
|
+
import { resolveRunDir } from '../flow.js';
|
|
62
|
+
import { readAsk } from '../runner.js';
|
|
57
63
|
import {
|
|
58
|
-
listRuns, getRunDetail, getRunAudit, getRunJob, listStops, getRunAsks, readSavedAnswer,
|
|
64
|
+
listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
|
|
59
65
|
} from './data.js';
|
|
60
66
|
import { createResumer } from './resume.js';
|
|
67
|
+
import { removeOldLock } from './lock.js';
|
|
61
68
|
|
|
62
69
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
63
70
|
|
|
64
71
|
/** Cap on the answer body — a decision and a short reason, nothing more. */
|
|
65
72
|
const MAX_BODY_BYTES = 8 * 1024;
|
|
66
|
-
/**
|
|
67
|
-
const
|
|
73
|
+
/** Cookie the panel link sets; `<name>_<port>` so two panels on one host never clobber each other. */
|
|
74
|
+
const cookieName = (port) => `fwdloop_panel_${port}`;
|
|
68
75
|
|
|
69
76
|
/** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
|
|
70
77
|
* is 4800 — bareloop owns 4700, and the two panels must be able to run
|
|
@@ -84,6 +91,24 @@ function sendText(res, code, text) {
|
|
|
84
91
|
res.end(text);
|
|
85
92
|
}
|
|
86
93
|
|
|
94
|
+
/**
|
|
95
|
+
* M4c-fix item 5: no absolute path in any error body. A path under `--root` is shown relative to
|
|
96
|
+
* it; any other absolute path (a symlink's far end, a system dir) is shown as `<outside root>`.
|
|
97
|
+
* Throws away: the machine's directory layout above `--root`.
|
|
98
|
+
* @param {string} text @param {string} root
|
|
99
|
+
*/
|
|
100
|
+
function cleanPaths(text, root) {
|
|
101
|
+
const bases = [path.resolve(root)];
|
|
102
|
+
try { bases.push(realpathSync(root)); } catch { /* root gone: the lexical base still applies */ }
|
|
103
|
+
return String(text).replace(/(?<![\w:/.])\/[^\s\x22\x27\x60()<>,;]+/g, (m) => {
|
|
104
|
+
for (const b of bases) {
|
|
105
|
+
if (m === b) return '.';
|
|
106
|
+
if (m.startsWith(`${b}/`)) return m.slice(b.length + 1);
|
|
107
|
+
}
|
|
108
|
+
return '<outside root>';
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
87
112
|
/** A refusal, by name. `refused` is the stable machine name, `red` the words.
|
|
88
113
|
* @param {any} res @param {number} code @param {string} name @param {string} [detail] */
|
|
89
114
|
function refuse(res, code, name, detail) {
|
|
@@ -100,6 +125,85 @@ function tokenMatches(a, b) {
|
|
|
100
125
|
return timingSafeEqual(x, y);
|
|
101
126
|
}
|
|
102
127
|
|
|
128
|
+
const tokenDir = (dir, env) => dir ?? (env.XDG_RUNTIME_DIR ? join(env.XDG_RUNTIME_DIR, 'fwdloop') : join(homedir(), '.cache', 'fwdloop'));
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* hamr's 2026-10-03 ruling "1A": the panel token is REUSED across restarts, so a bookmark of
|
|
132
|
+
* `http://127.0.0.1:<port>/` keeps working once the link was opened. Reads the token file (same path
|
|
133
|
+
* `writeTokenFile` writes); a new token only when the file is missing, unreadable, not a regular file,
|
|
134
|
+
* not mode 0600, not ours, or not 64 hex chars (the caller then rewrites it 0600).
|
|
135
|
+
* @param {{ port: number, dir?: string, env?: Record<string, string|undefined> }} a
|
|
136
|
+
* @returns {string}
|
|
137
|
+
*/
|
|
138
|
+
export function loadOrMakeToken({ port, dir, env = process.env }) {
|
|
139
|
+
try {
|
|
140
|
+
const d = tokenDir(dir, env);
|
|
141
|
+
const file = join(d, `panel-${port}.token`);
|
|
142
|
+
const st = lstatSync(file);
|
|
143
|
+
const dst = lstatSync(d);
|
|
144
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
145
|
+
if (dst.isDirectory() && (dst.mode & 0o777) === 0o700 && st.isFile() && (st.mode & 0o777) === 0o600 && (uid === null || st.uid === uid)) {
|
|
146
|
+
const t = readFileSync(file, 'utf8').trim();
|
|
147
|
+
if (/^[0-9a-f]{64}$/.test(t)) return t;
|
|
148
|
+
}
|
|
149
|
+
} catch { /* missing or unreadable: a new one */ }
|
|
150
|
+
return randomBytes(32).toString('hex');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* M4c-fix item 2: the token's one on-disk home — `<dir>/panel-<port>.token`, dir 0700, file 0600,
|
|
155
|
+
* `dir` = `$XDG_RUNTIME_DIR/fwdloop`, else `~/.cache/fwdloop`. Refuses a dir that is a symlink or
|
|
156
|
+
* not ours. The file is replaced (unlink, then exclusive create at 0600), never rewritten in place,
|
|
157
|
+
* so it never exists with a looser mode. Returns the file's path.
|
|
158
|
+
* @param {{ port: number, token: string, dir?: string, env?: Record<string, string|undefined> }} a
|
|
159
|
+
*/
|
|
160
|
+
export function writeTokenFile({
|
|
161
|
+
port, token, dir, env = process.env,
|
|
162
|
+
}) {
|
|
163
|
+
const d = tokenDir(dir, env);
|
|
164
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
165
|
+
mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
166
|
+
const st = lstatSync(d);
|
|
167
|
+
if (!st.isDirectory() || (uid !== null && st.uid !== uid)) throw new Error('token dir is not a directory owned by this user');
|
|
168
|
+
chmodSync(d, 0o700);
|
|
169
|
+
const file = join(d, `panel-${port}.token`);
|
|
170
|
+
try { unlinkSync(file); } catch { /* none yet */ }
|
|
171
|
+
const fd = openSync(file, 'wx', 0o600);
|
|
172
|
+
try { writeSync(fd, `${token}\n`); } finally { closeSync(fd); }
|
|
173
|
+
return file;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** @param {any} res */
|
|
177
|
+
function refuseBusy(res) {
|
|
178
|
+
refuse(res, 409, 'already-resuming', 'already resuming — this run has a resume in progress; wait for it to end');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The ONE place a write route turns `{flow, runId}` into a run dir: the flow must really sit inside
|
|
183
|
+
* `--root` (`resolveFlowDir`, realpath at use time — a symlinked flow outside root is refused by
|
|
184
|
+
* name), then the runId resolves inside that flow's runs/. On a refusal it has already replied.
|
|
185
|
+
* @param {any} res @param {string} root @param {unknown} flow @param {unknown} runId
|
|
186
|
+
* @returns {string|null} the run dir, or null (already replied)
|
|
187
|
+
*/
|
|
188
|
+
function resolveRun(res, root, flow, runId) {
|
|
189
|
+
const fd = resolveFlowDir(root, /** @type {string} */ (flow));
|
|
190
|
+
if (!fd.ok) {
|
|
191
|
+
if (fd.why === 'outside-root') refuse(res, 403, 'flow-outside-root', cleanPaths(fd.red, root));
|
|
192
|
+
else refuse(res, 400, 'bad-flow', cleanPaths(fd.red, root));
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const rd = resolveRunDir(fd.flowDir, runId);
|
|
196
|
+
if (!rd.ok) { refuse(res, 400, 'bad-runId', cleanPaths(rd.red, root)); return null; }
|
|
197
|
+
return rd.runDir;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Is the run already parked on `askId` and waiting on the human: it is the open `ask.json`, no answer is saved
|
|
201
|
+
* for it and none was consumed? Then a resume child still alive for the run is only closing.
|
|
202
|
+
* @param {string} runDir @param {string} askId */
|
|
203
|
+
function parkedOnYou(runDir, askId) {
|
|
204
|
+
return readAsk(runDir)?.askId === askId && readSavedAnswer(runDir) === null && !hasConsumedAnswer(runDir, askId);
|
|
205
|
+
}
|
|
206
|
+
|
|
103
207
|
/**
|
|
104
208
|
* `POST /api/answer` — runs after the gates. Wraps `answerAsk` with exactly
|
|
105
209
|
* the arguments `bin/fwdloop`'s `cmdAnswer` passes ({ runDir, askId, decision,
|
|
@@ -117,26 +221,88 @@ function answerRoute(res, body, root, resumer) {
|
|
|
117
221
|
refuse(res, 400, 'askid-required', 'an answer must name the askId the page was showing');
|
|
118
222
|
return;
|
|
119
223
|
}
|
|
120
|
-
const
|
|
121
|
-
if (
|
|
122
|
-
|
|
123
|
-
|
|
224
|
+
const runDir = resolveRun(res, root, flow, runId);
|
|
225
|
+
if (runDir === null) return;
|
|
226
|
+
// One resume at a time per run (M4c-fix item 1): refused BEFORE the answer is written, so a refused
|
|
227
|
+
// click leaves the books as they were.
|
|
228
|
+
// Only a real concurrent resume is blocked. A previous resume child that is merely closing — the run has already
|
|
229
|
+
// parked on THIS ask, nothing answered or consumed for it — does not block the human's answer (amendment 1 (e)(1)).
|
|
230
|
+
if (resumer.busy(flow, runId) && !parkedOnYou(runDir, askId)) { refuseBusy(res); return; }
|
|
124
231
|
const result = answerAsk({
|
|
125
|
-
runDir
|
|
232
|
+
runDir, askId, decision, reason,
|
|
126
233
|
});
|
|
127
234
|
if (!result.ok) {
|
|
128
|
-
sendJson(res, 409, { ok: false, refused: 'library', red: result.red });
|
|
235
|
+
sendJson(res, 409, { ok: false, refused: 'library', red: cleanPaths(result.red, root) });
|
|
129
236
|
return;
|
|
130
237
|
}
|
|
131
238
|
const attempt = resumer.start({
|
|
132
|
-
flow, runId, runDir
|
|
239
|
+
flow, runId, runDir, askId,
|
|
133
240
|
});
|
|
134
241
|
sendJson(res, 202, {
|
|
135
|
-
ok: true, answered: true, askId, decision: normalizeDecision(decision), resume: 'started', tries: attempt.tries, maxTries: attempt.maxTries,
|
|
242
|
+
ok: true, answered: true, askId, decision: normalizeDecision(decision), setAside: result.setAside, resume: 'started', tries: attempt.tries, maxTries: attempt.maxTries,
|
|
136
243
|
note: 'answer saved; the resume was started in the background — its state is in the run\'s data (`resume`), not in this reply',
|
|
137
244
|
});
|
|
138
245
|
}
|
|
139
246
|
|
|
247
|
+
/**
|
|
248
|
+
* `POST /api/reopen` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
|
|
249
|
+
* "Reopen for another <wait>" on an expired ask (M4c-fix amendment 1 (b)): `reopenAsk` writes the reopen record
|
|
250
|
+
* (a fresh window of the same signed length, on the same ask) and moves a late answer aside. Nothing else reopens:
|
|
251
|
+
* no runner or agent path calls it. Refused 409 while a resume of the run is alive, and for a run that has ended.
|
|
252
|
+
* @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer
|
|
253
|
+
*/
|
|
254
|
+
function reopenRoute(res, body, root, resumer) {
|
|
255
|
+
const b = body !== null && typeof body === 'object' ? body : {};
|
|
256
|
+
const { flow, runId, askId } = b;
|
|
257
|
+
if (typeof askId !== 'string' || askId.length === 0) {
|
|
258
|
+
refuse(res, 400, 'askid-required', 'a reopen must name the askId the page was showing');
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const runDir = resolveRun(res, root, flow, runId);
|
|
262
|
+
if (runDir === null) return;
|
|
263
|
+
if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
|
|
264
|
+
if (readHistory(dirname(dirname(runDir))).some((r) => r && r.runId === runId)) {
|
|
265
|
+
refuse(res, 409, 'run-ended', 'this run has ended — there is nothing to reopen');
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const result = reopenAsk({ runDir, askId, by: 'human via panel' });
|
|
269
|
+
if (!result.ok) {
|
|
270
|
+
sendJson(res, 409, { ok: false, refused: 'library', red: cleanPaths(result.red, root) });
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
sendJson(res, 200, {
|
|
274
|
+
ok: true, reopened: true, askId, expiresAt: result.expiresAt, n: result.n, setAside: result.setAside,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* `POST /api/remove-lock` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
|
|
280
|
+
* "Remove the old lock" (M4c-fix amendment 2 (h)): only for a run with a saved answer and no resume alive; `removeOldLock`
|
|
281
|
+
* re-checks at this moment that the lock still has no recorded holder, removes it and writes the one audit row; then the
|
|
282
|
+
* run continues exactly like "Continue the run" (the same `resumer.start`). Nothing else calls the remover.
|
|
283
|
+
* @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer
|
|
284
|
+
*/
|
|
285
|
+
function removeLockRoute(res, body, root, resumer) {
|
|
286
|
+
const b = body !== null && typeof body === 'object' ? body : {};
|
|
287
|
+
const { flow, runId } = b;
|
|
288
|
+
const runDir = resolveRun(res, root, flow, runId);
|
|
289
|
+
if (runDir === null) return;
|
|
290
|
+
const saved = readSavedAnswer(runDir);
|
|
291
|
+
if (!saved) {
|
|
292
|
+
refuse(res, 409, 'no-saved-answer', 'this run has no saved, unconsumed answer — a resume would have nothing to apply');
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
|
|
296
|
+
const removed = removeOldLock({ root, runDir });
|
|
297
|
+
if (!removed.ok) { refuse(res, 409, removed.refused, cleanPaths(removed.red, root)); return; }
|
|
298
|
+
const attempt = resumer.start({
|
|
299
|
+
flow, runId, runDir, askId: saved.askId,
|
|
300
|
+
});
|
|
301
|
+
sendJson(res, 202, {
|
|
302
|
+
ok: true, lockRemoved: true, resume: 'started', askId: saved.askId, tries: attempt.tries, maxTries: attempt.maxTries,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
140
306
|
/**
|
|
141
307
|
* `POST /api/resume` — runs after the same gates as the answer. Starts a
|
|
142
308
|
* resume ONLY for a run that has a saved, unconsumed answer; it takes no
|
|
@@ -146,22 +312,16 @@ function answerRoute(res, body, root, resumer) {
|
|
|
146
312
|
function resumeRoute(res, body, root, resumer) {
|
|
147
313
|
const b = body !== null && typeof body === 'object' ? body : {};
|
|
148
314
|
const { flow, runId } = b;
|
|
149
|
-
const
|
|
150
|
-
if (
|
|
151
|
-
const
|
|
152
|
-
if (!rd.ok) { refuse(res, 400, 'bad-runId', rd.red); return; }
|
|
153
|
-
const saved = readSavedAnswer(rd.runDir);
|
|
315
|
+
const runDir = resolveRun(res, root, flow, runId);
|
|
316
|
+
if (runDir === null) return;
|
|
317
|
+
const saved = readSavedAnswer(runDir);
|
|
154
318
|
if (!saved) {
|
|
155
319
|
refuse(res, 409, 'no-saved-answer', 'this run has no saved, unconsumed answer — a resume would have nothing to apply');
|
|
156
320
|
return;
|
|
157
321
|
}
|
|
158
|
-
|
|
159
|
-
if (current && current.state === 'in-flight') {
|
|
160
|
-
refuse(res, 409, 'resume-in-flight', `a resume for this run is already being started (try ${current.tries} of ${current.maxTries})`);
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
322
|
+
if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
|
|
163
323
|
const attempt = resumer.start({
|
|
164
|
-
flow, runId, runDir
|
|
324
|
+
flow, runId, runDir, askId: saved.askId,
|
|
165
325
|
});
|
|
166
326
|
sendJson(res, 202, {
|
|
167
327
|
ok: true, resume: 'started', askId: saved.askId, tries: attempt.tries, maxTries: attempt.maxTries,
|
|
@@ -179,6 +339,12 @@ function resumeRoute(res, body, root, resumer) {
|
|
|
179
339
|
export function handleRequest(req, res, opts) {
|
|
180
340
|
const method = req.method ?? 'GET';
|
|
181
341
|
|
|
342
|
+
// M4c-fix item 3: EVERY response — refusals, redirects, errors, the page — says it must not be
|
|
343
|
+
// framed or cached. Set first, before any branch can write; `writeHead` merges these in.
|
|
344
|
+
res.setHeader('X-Frame-Options', 'DENY');
|
|
345
|
+
res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
|
|
346
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
347
|
+
|
|
182
348
|
// Gate 1 — EVERY route, every method: `Host` must be this server's own
|
|
183
349
|
// address. A foreign Host (DNS rebinding) is refused by name, never 200.
|
|
184
350
|
const host = req.headers.host;
|
|
@@ -187,36 +353,78 @@ export function handleRequest(req, res, opts) {
|
|
|
187
353
|
return;
|
|
188
354
|
}
|
|
189
355
|
|
|
190
|
-
|
|
356
|
+
// Gate 2 — EVERY route, every method (the page included): the panel's own cookie, set by opening
|
|
357
|
+
// the printed `/?t=<token>` link. Without it: 403 by name, and nothing in the body is a token.
|
|
358
|
+
const cookies = Object.fromEntries(String(req.headers.cookie ?? '').split(';').map((c) => {
|
|
359
|
+
const i = c.indexOf('=');
|
|
360
|
+
return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
|
|
361
|
+
}));
|
|
362
|
+
if (!tokenMatches(cookies[cookieName(opts.port)], opts.token)) {
|
|
363
|
+
const link = method === 'GET' || method === 'HEAD' ? new URL(String(req.url), 'http://127.0.0.1') : null;
|
|
364
|
+
if (link && link.pathname === '/' && tokenMatches(link.searchParams.get('t'), opts.token)) {
|
|
365
|
+
res.writeHead(302, {
|
|
366
|
+
'set-cookie': `${cookieName(opts.port)}=${opts.token}; HttpOnly; SameSite=Strict; Path=/`, location: '/', 'content-length': 0,
|
|
367
|
+
});
|
|
368
|
+
res.end();
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
// A browser opening the bare page sees a plain page that says what to do, not a blank JSON "forbidden"
|
|
372
|
+
// that reads as "the panel is down". No token, no script. API routes keep the JSON 403.
|
|
373
|
+
if (link && link.pathname === '/' && /text\/html/.test(String(req.headers.accept ?? ''))) {
|
|
374
|
+
const html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>fwdloop panel</title>'
|
|
375
|
+
+ '<p style="font:16px/1.5 system-ui,sans-serif;max-width:40em;margin:2em auto;padding:0 1em">'
|
|
376
|
+
+ 'fwdloop panel: open the link printed in the terminal where you started <code>fwdloop panel</code> (it ends in ?t=…). '
|
|
377
|
+
+ 'Restarted the panel? Open its new link.</p>';
|
|
378
|
+
res.writeHead(403, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
|
|
379
|
+
res.end(method === 'HEAD' ? undefined : html);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
refuse(res, 403, 'cookie-missing-or-wrong', 'open the link `fwdloop panel` printed');
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (method === 'POST' && (req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock')) {
|
|
191
387
|
const isResume = req.url === '/api/resume';
|
|
388
|
+
const isReopen = req.url === '/api/reopen';
|
|
389
|
+
const isRemoveLock = req.url === '/api/remove-lock';
|
|
192
390
|
const origin = req.headers.origin;
|
|
193
391
|
if (origin !== `http://127.0.0.1:${opts.port}` && origin !== `http://localhost:${opts.port}`) {
|
|
194
392
|
refuse(res, 403, 'origin-not-own', String(origin));
|
|
195
393
|
return;
|
|
196
394
|
}
|
|
197
|
-
if (!tokenMatches(req.headers[TOKEN_HEADER], opts.token)) {
|
|
198
|
-
refuse(res, 403, 'token-missing-or-wrong');
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
395
|
let size = 0;
|
|
202
396
|
const parts = [];
|
|
203
|
-
|
|
397
|
+
let tooBig = false;
|
|
398
|
+
req.on('data', (c) => {
|
|
399
|
+
if (tooBig) return;
|
|
400
|
+
size += c.length;
|
|
401
|
+
if (size <= MAX_BODY_BYTES) { parts.push(c); return; }
|
|
402
|
+
// M4c-fix item 6: over the limit — stop at once. Drop what was collected, refuse (413, then the
|
|
403
|
+
// connection closes), and cut the request off; the rest of the body is never read.
|
|
404
|
+
tooBig = true;
|
|
405
|
+
parts.length = 0;
|
|
406
|
+
res.setHeader('Connection', 'close');
|
|
407
|
+
refuse(res, 413, 'body-too-large');
|
|
408
|
+
res.once('finish', () => req.destroy());
|
|
409
|
+
});
|
|
204
410
|
req.on('end', () => {
|
|
205
411
|
try {
|
|
206
|
-
if (
|
|
412
|
+
if (tooBig) return;
|
|
207
413
|
let body;
|
|
208
414
|
try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
|
|
209
415
|
if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
|
|
416
|
+
else if (isReopen) reopenRoute(res, body, opts.root, opts.resumer);
|
|
417
|
+
else if (isRemoveLock) removeLockRoute(res, body, opts.root, opts.resumer);
|
|
210
418
|
else answerRoute(res, body, opts.root, opts.resumer);
|
|
211
419
|
} catch (e) {
|
|
212
|
-
|
|
420
|
+
sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
|
|
213
421
|
}
|
|
214
422
|
});
|
|
215
423
|
return;
|
|
216
424
|
}
|
|
217
425
|
|
|
218
426
|
if (method !== 'GET' && method !== 'HEAD') {
|
|
219
|
-
sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer and POST /api/
|
|
427
|
+
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');
|
|
220
428
|
return;
|
|
221
429
|
}
|
|
222
430
|
|
|
@@ -249,7 +457,6 @@ export function handleRequest(req, res, opts) {
|
|
|
249
457
|
return;
|
|
250
458
|
}
|
|
251
459
|
html = html.replace(/__FWDLOOP_PANEL_PORT__/g, String(opts.port));
|
|
252
|
-
html = html.replace(/__FWDLOOP_PANEL_TOKEN__/g, opts.token);
|
|
253
460
|
if (method === 'HEAD') {
|
|
254
461
|
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
|
|
255
462
|
res.end();
|
|
@@ -262,7 +469,7 @@ export function handleRequest(req, res, opts) {
|
|
|
262
469
|
|
|
263
470
|
const loaded = loadCatalogue();
|
|
264
471
|
if (!loaded.ok) {
|
|
265
|
-
sendText(res, 500, `catalogue failed to load: ${loaded.reds.join('; ')}`);
|
|
472
|
+
sendText(res, 500, `catalogue failed to load: ${cleanPaths(loaded.reds.join('; '), opts.root)}`);
|
|
266
473
|
return;
|
|
267
474
|
}
|
|
268
475
|
const catalogue = loaded.primitives;
|
|
@@ -274,7 +481,8 @@ export function handleRequest(req, res, opts) {
|
|
|
274
481
|
}
|
|
275
482
|
|
|
276
483
|
if (pathname === '/api/inbox') {
|
|
277
|
-
|
|
484
|
+
const rows = listStops({ root: opts.root, resumeAttempt });
|
|
485
|
+
send(200, { rows, openCount: inboxOpenCount(rows) });
|
|
278
486
|
return;
|
|
279
487
|
}
|
|
280
488
|
|
|
@@ -292,6 +500,11 @@ export function handleRequest(req, res, opts) {
|
|
|
292
500
|
}
|
|
293
501
|
const sub = runMatch[4] ?? null;
|
|
294
502
|
|
|
503
|
+
// A flow symlinked outside --root is refused BY NAME for every read (the data layer alone would
|
|
504
|
+
// only say "no such run"). Anything else about the flow still falls through to the 404.
|
|
505
|
+
const fd = resolveFlowDir(opts.root, flow);
|
|
506
|
+
if (!fd.ok && fd.why === 'outside-root') { refuse(res, 403, 'flow-outside-root', cleanPaths(fd.red, opts.root)); return; }
|
|
507
|
+
|
|
295
508
|
if (sub === 'audit') {
|
|
296
509
|
const result = getRunAudit({ root: opts.root, flow, runId });
|
|
297
510
|
if (!result) { sendText(res, 404, 'no such run'); return; }
|
|
@@ -331,9 +544,9 @@ export function handleRequest(req, res, opts) {
|
|
|
331
544
|
* header). Resolves once actually listening; rejects on a bind error
|
|
332
545
|
* (including `EADDRINUSE`) with a `.port` field on the error for the
|
|
333
546
|
* caller's message.
|
|
334
|
-
* @param {{ port?: number, root: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
|
|
547
|
+
* @param {{ port?: number, root: string, token?: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
|
|
335
548
|
* `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
|
|
336
|
-
* @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
|
|
549
|
+
* @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
|
|
337
550
|
*/
|
|
338
551
|
export function createPanelServer(opts) {
|
|
339
552
|
if (typeof opts?.root !== 'string' || opts.root.length === 0) {
|
|
@@ -345,7 +558,7 @@ export function createPanelServer(opts) {
|
|
|
345
558
|
const resumer = createResumer({ root, ...opts.resume });
|
|
346
559
|
// One token per server process, made once, held only here and in the served
|
|
347
560
|
// page — never logged, never in any /api response.
|
|
348
|
-
const token = randomBytes(32).toString('hex');
|
|
561
|
+
const token = typeof opts.token === 'string' && /^[0-9a-f]{64}$/.test(opts.token) ? opts.token : randomBytes(32).toString('hex');
|
|
349
562
|
return new Promise((resolve, reject) => {
|
|
350
563
|
// Bound port is resolved from the live socket (`server.address().port`)
|
|
351
564
|
// once listening starts, not the requested value — this is what makes
|
|
@@ -359,7 +572,7 @@ export function createPanelServer(opts) {
|
|
|
359
572
|
root, port: boundPort, token, resumer,
|
|
360
573
|
});
|
|
361
574
|
} catch (e) {
|
|
362
|
-
sendText(res, 500,
|
|
575
|
+
sendText(res, 500, 'internal error');
|
|
363
576
|
}
|
|
364
577
|
});
|
|
365
578
|
server.once('error', (e) => {
|
|
@@ -373,6 +586,7 @@ export function createPanelServer(opts) {
|
|
|
373
586
|
resolve({
|
|
374
587
|
server,
|
|
375
588
|
port: boundPort,
|
|
589
|
+
token,
|
|
376
590
|
close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
|
|
377
591
|
});
|
|
378
592
|
});
|
|
@@ -402,8 +616,10 @@ export async function panelMain(argv, ctx) {
|
|
|
402
616
|
}
|
|
403
617
|
}
|
|
404
618
|
try {
|
|
405
|
-
const { port: boundPort } = await createPanelServer({ port, root });
|
|
406
|
-
|
|
619
|
+
const { port: boundPort, token } = await createPanelServer({ port, root, token: loadOrMakeToken({ port }) });
|
|
620
|
+
writeTokenFile({ port: boundPort, token });
|
|
621
|
+
ctx.out(`fwdloop panel — (root: ${root}) (Ctrl-C to stop)`);
|
|
622
|
+
ctx.out(`open this link (it sets the panel's cookie): http://127.0.0.1:${boundPort}/?t=${token}`);
|
|
407
623
|
// never resolves on its own — the process stays up until killed, same
|
|
408
624
|
// shape any other long-running dev server takes.
|
|
409
625
|
await new Promise(() => {});
|
package/src/provider.js
CHANGED
|
@@ -212,7 +212,15 @@ function readSpendTotal(path) {
|
|
|
212
212
|
let total = 0;
|
|
213
213
|
for (const line of lines) {
|
|
214
214
|
const row = JSON.parse(line);
|
|
215
|
-
|
|
215
|
+
// An incomplete row (a call died unmetered) counts its priced floor PLUS one
|
|
216
|
+
// ceiling per unmetered call — never only the floor (unknown cost is never
|
|
217
|
+
// 0). Same shape as poc/m6a/batch.mjs rowCostUsd.
|
|
218
|
+
if (row.spendComplete === false) {
|
|
219
|
+
const unmetered = Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
|
|
220
|
+
total += (row.costUsd ?? 0) + unmetered * ceilingCostUsd(row.model);
|
|
221
|
+
} else {
|
|
222
|
+
total += row.costUsd === null || row.costUsd === undefined ? ceilingCostUsd(row.model) : row.costUsd;
|
|
223
|
+
}
|
|
216
224
|
}
|
|
217
225
|
return total;
|
|
218
226
|
}
|