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.
- package/bin/fwdloop +136 -21
- package/package.json +1 -1
- package/src/ask.js +3 -0
- package/src/authoring.js +101 -13
- package/src/books.js +23 -2
- package/src/canrun.js +36 -0
- package/src/config.js +2 -1
- package/src/declaration.js +72 -2
- package/src/drafter.js +41 -3
- package/src/draftspend.js +70 -0
- package/src/flow.js +43 -0
- package/src/liveness.js +1 -1
- package/src/model-step.js +30 -4
- package/src/monthly.js +58 -13
- package/src/panel/author.js +482 -0
- package/src/panel/authorcard.js +297 -0
- package/src/panel/authorflows.js +312 -0
- package/src/panel/authorresume.js +149 -0
- package/src/panel/authorstart.js +257 -0
- package/src/panel/authorvalues.js +110 -0
- package/src/panel/data.js +228 -34
- package/src/panel/index.html +1745 -127
- package/src/panel/resume.js +6 -8
- package/src/panel/server.js +119 -119
- package/src/panel/settings.js +7 -5
- package/src/panel/spawn.js +77 -0
- package/src/provider.js +12 -17
- package/src/runner.js +639 -85
- package/src/runvalues.js +178 -0
- package/src/send.js +10 -3
- package/src/setup.js +120 -0
- package/types/authoring.d.ts +24 -2
- package/types/books.d.ts +14 -2
- package/types/canrun.d.ts +32 -0
- package/types/config.d.ts +1 -0
- package/types/declaration.d.ts +9 -1
- package/types/drafter.d.ts +15 -1
- package/types/draftspend.d.ts +21 -0
- package/types/flow.d.ts +23 -0
- package/types/liveness.d.ts +2 -2
- package/types/model-step.d.ts +3 -1
- package/types/monthly.d.ts +21 -0
- package/types/panel/author.d.ts +335 -0
- package/types/panel/authorcard.d.ts +120 -0
- package/types/panel/authorflows.d.ts +175 -0
- package/types/panel/authorresume.d.ts +32 -0
- package/types/panel/authorstart.d.ts +115 -0
- package/types/panel/authorvalues.d.ts +62 -0
- package/types/panel/data.d.ts +103 -12
- package/types/panel/server.d.ts +11 -33
- package/types/panel/spawn.d.ts +30 -0
- package/types/provider.d.ts +6 -9
- package/types/runner.d.ts +120 -5
- package/types/runvalues.d.ts +97 -0
- package/types/send.d.ts +5 -1
- package/types/setup.d.ts +83 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// M4e amendment 4 items 1, 4, 6 and amendment 5 item 1 (docs/wiki/the-module-ladder.md): the RESUME door of the panel's backend —
|
|
2
|
+
// `POST /api/author/resume-prepare` (the first click of "Sign & resume": what is about to be signed, a hash) and `POST /api/author/resume`
|
|
3
|
+
// (the second click: the hash must be the one the disk gives now). A Resume continues the SAME run (a run that stopped at its cap or by Stop);
|
|
4
|
+
// the ONLY thing it can change is the cap, written as a NEW signed version beside the old one (`signed-values-r<k>.json`, write-once) —
|
|
5
|
+
// never an edit of the flow's prose.txt / signature.json, never of an earlier version. No spawn of its own: the continue starts only through
|
|
6
|
+
// `authorstart.js`'s `startContinue`.
|
|
7
|
+
//
|
|
8
|
+
// resume-prepare {flow, runId, capUsd} every $0 check, writes NOTHING -> { hash, version, spentUsd, ... }
|
|
9
|
+
// resume {flow, runId, capUsd, hash} the same checks again, the hash recomputed from the disk NOW; a stale or missing hash signs nothing
|
|
10
|
+
//
|
|
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
|
+
// highest version through `pickRunValues` and nothing else. The agent, the chat notes and the drafter have no path here.
|
|
13
|
+
import { realpathSync } from 'node:fs';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { userInfo } from 'node:os';
|
|
16
|
+
|
|
17
|
+
import { scrub } from '../authoring.js';
|
|
18
|
+
import { loadCatalogue } from '../catalogue.js';
|
|
19
|
+
import { checkFlowName, readFileInside, readFlow, resolveRunDir } from '../flow.js';
|
|
20
|
+
import { readResumeLock } from '../liveness.js';
|
|
21
|
+
import { auditSpend } from '../runner.js';
|
|
22
|
+
import {
|
|
23
|
+
flowValues, pickRunValues, valuesHash, writeRunValues,
|
|
24
|
+
} from '../runvalues.js';
|
|
25
|
+
import { capFloorFor, capFloorText } from './authorcard.js';
|
|
26
|
+
import { formFacts } from './authorflows.js';
|
|
27
|
+
import { checkValues } from './authorvalues.js';
|
|
28
|
+
import { getRunControls } from './data.js';
|
|
29
|
+
import { providerKeys } from './spawn.js';
|
|
30
|
+
|
|
31
|
+
const KEYS = ['flow', 'runId', 'capUsd', 'hash'];
|
|
32
|
+
|
|
33
|
+
/**
|
|
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
|
+
*/
|
|
36
|
+
export function createResumeDoor(opts) {
|
|
37
|
+
const {
|
|
38
|
+
root, loadEnv, monthlyClaim, starter,
|
|
39
|
+
} = opts;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Every $0 check, shared by both clicks. `{ok:false, reply}` or the facts the clicks need.
|
|
43
|
+
* @param {any} body
|
|
44
|
+
*/
|
|
45
|
+
function inspect(body, formOnly = false) {
|
|
46
|
+
const no = (status, body2) => ({ ok: /** @type {false} */ (false), reply: { status, body: { ok: false, ...body2 } } });
|
|
47
|
+
let realRoot;
|
|
48
|
+
try { realRoot = realpathSync(root); } catch { return no(400, { refused: 'root', say: 'The flows folder this panel serves does not exist.' }); }
|
|
49
|
+
const b = body && typeof body === 'object' ? body : {};
|
|
50
|
+
const flow = typeof b.flow === 'string' ? b.flow : '';
|
|
51
|
+
const named = checkFlowName(flow);
|
|
52
|
+
if (!named.ok) return no(400, { refused: 'flow', refusals: [{ field: 'flow', say: `${named.red}.` }] });
|
|
53
|
+
const runId = typeof b.runId === 'string' ? b.runId : '';
|
|
54
|
+
const rd = resolveRunDir(join(realRoot, flow), runId);
|
|
55
|
+
if (!rd.ok) return no(400, { refused: 'run-id', say: `${rd.red.replace(/^run: /, '')}.` });
|
|
56
|
+
const cat = loadCatalogue();
|
|
57
|
+
if (!cat.ok) return no(500, { refused: 'catalogue', say: 'The catalogue could not be loaded. Nothing was signed.' });
|
|
58
|
+
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
|
+
const controls = getRunControls({
|
|
61
|
+
root: realRoot, flow, runId, catalogue: cat.primitives,
|
|
62
|
+
});
|
|
63
|
+
if (controls === null) return no(404, { refused: 'no-such-run', say: 'There is no such run.' });
|
|
64
|
+
if (controls.canStop && !controls.atAsk) return no(409, { refused: 'running', say: 'This run is still running. Stop it first, or wait for it to end; a Resume is for a run that stopped.' });
|
|
65
|
+
if (!controls.canResume) return no(409, { refused: 'not-resumable', say: 'This run did not stop at its cap or by Stop, so there is nothing to resume. Start a new run instead.' });
|
|
66
|
+
const lock = readResumeLock(rd.runDir);
|
|
67
|
+
if (lock.state === 'live' || lock.state === 'unknown') return no(409, { refused: 'already-resuming', say: 'This run is already carrying on. Wait a moment, then look again.' });
|
|
68
|
+
const picked = pickRunValues(rd.runDir);
|
|
69
|
+
if (!picked.ok) return no(409, { refused: 'values', say: `${picked.red}. Nothing was signed.` });
|
|
70
|
+
const base = picked.none ? flowValues(read.arbiter) : picked.record.values;
|
|
71
|
+
const version = picked.none ? 1 : picked.version + 1;
|
|
72
|
+
const spent = auditSpend(rd.runDir);
|
|
73
|
+
if (!spent.ok) return no(409, { refused: 'books', say: `The run's books cannot be read (${spent.red}). Nothing was signed.` });
|
|
74
|
+
const hasRound = read.declaration.steps.some((st) => !(read.arbiter.asks ?? []).some((a) => a.line === st.fromLine));
|
|
75
|
+
if (formOnly) return { ok: /** @type {true} */ (true), flow, runId, runDir: rd.runDir, version, base, spentUsd: spent.total, read, hasRound };
|
|
76
|
+
const checked = checkValues({
|
|
77
|
+
allowedKeys: KEYS, body: b, base, realRoot, capOnly: true, floorUsd: capFloorFor(hasRound), spentUsd: spent.total, monthlyClaim, always: true,
|
|
78
|
+
});
|
|
79
|
+
if (!checked.ok) {
|
|
80
|
+
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.' });
|
|
81
|
+
}
|
|
82
|
+
const hash = valuesHash({
|
|
83
|
+
flow, flowSignatureHash: read.signature.flow, runId, version, values: checked.values,
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
ok: /** @type {true} */ (true), flow, runId, runDir: rd.runDir, version, values: checked.values, hash, spentUsd: spent.total, remainingUsd: checked.remainingUsd, signatureHash: read.signature.flow, hashGiven: b.hash,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
/**
|
|
92
|
+
* `GET /api/author/resume-form?flow=&runId=`: what the "Resume run-<n>" form shows — the same locating checks as the clicks (a run that is not
|
|
93
|
+
* stopped or cap-halted gets the same refusal), then the values in force (dimmed on the form except the cap), what the run has spent, the
|
|
94
|
+
* job lines as signed and the files it froze. Writes nothing.
|
|
95
|
+
* @param {string|null} flow @param {string|null} runId
|
|
96
|
+
*/
|
|
97
|
+
form(flow, runId) {
|
|
98
|
+
const s = inspect({ flow: flow ?? '', runId: runId ?? '' }, true);
|
|
99
|
+
if (!s.ok) return s.reply;
|
|
100
|
+
const inputsRead = readFileInside(s.runDir, 'inputs.json');
|
|
101
|
+
let inputs = [];
|
|
102
|
+
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
|
+
return {
|
|
105
|
+
status: 200,
|
|
106
|
+
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
|
+
},
|
|
109
|
+
};
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
/** `POST /api/author/resume-prepare`: the first click. Writes nothing. @param {any} body */
|
|
113
|
+
prepare(body) {
|
|
114
|
+
const s = /** @type {any} */ (inspect(body));
|
|
115
|
+
if (!s.ok) return s.reply;
|
|
116
|
+
return {
|
|
117
|
+
status: 200,
|
|
118
|
+
body: {
|
|
119
|
+
ok: true, flow: s.flow, runId: s.runId, version: s.version, hash: s.hash, capUsd: s.values.capUsd, spentUsd: s.spentUsd, remainingUsd: s.remainingUsd,
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* `POST /api/author/resume`: the second click. The hash must be the one the disk gives now (a changed run, a changed cap, a newer version
|
|
126
|
+
* all make it stale); then the new version is written once and the continue is started. Anything else signs nothing, writes nothing.
|
|
127
|
+
* @param {any} body
|
|
128
|
+
*/
|
|
129
|
+
resume(body) {
|
|
130
|
+
const loaded = loadEnv();
|
|
131
|
+
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
132
|
+
const s = /** @type {any} */ (inspect(body));
|
|
133
|
+
if (!s.ok) return s.reply;
|
|
134
|
+
if (typeof s.hashGiven !== 'string' || s.hashGiven !== s.hash) {
|
|
135
|
+
return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'What you were shown is not what is on disk now (its hash differs). Nothing was signed. Look again, then sign.' } };
|
|
136
|
+
}
|
|
137
|
+
const w = writeRunValues(s.runDir, {
|
|
138
|
+
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
|
+
if (!w.ok) {
|
|
141
|
+
const keys = providerKeys(loaded.env);
|
|
142
|
+
return { status: 409, body: { ok: false, refused: 'sign-refused', say: `${scrub(w.red, keys)}. Nothing was started.` } };
|
|
143
|
+
}
|
|
144
|
+
const started = starter.startContinue({ flow: s.flow, runId: s.runId, version: s.version }, loaded.env);
|
|
145
|
+
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
|
+
return { status: 202, body: { ...started.body, signed: true, version: s.version } };
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/panel/authorroutes.js@524a244 (`signRun`, its ONE spawn site: sign and run both start a run only here;
|
|
2
|
+
// the one-at-a-time rule while a start is still spawning).
|
|
3
|
+
// M4e piece 2b (docs/wiki/the-module-ladder.md, "M4e", scope 5, 7, 8): the ONE run-start path. Both the sign door and the
|
|
4
|
+
// Run-a-signed-flow door call `start` and nothing else spawns `fwdloop run`.
|
|
5
|
+
//
|
|
6
|
+
// A start is a DETACHED CLI CHILD (`fwdloop run <flow> --root <root> --source <role>=<path> ... --run-id <id>`) through the one
|
|
7
|
+
// `spawnDetached`, env = the merged keys env (the same object is the scrub list). The CLI may refuse BEFORE the run dir
|
|
8
|
+
// exists (monthly limit, empty key, preflight), so the start's own files live in a panel-owned folder:
|
|
9
|
+
//
|
|
10
|
+
// <root>/.starts/<startId>/start.json what was started (flow, runId, sources, kind) — no key, ever
|
|
11
|
+
// child.log the child's stdout+stderr, 0600 (quoted to the page only after `scrub`)
|
|
12
|
+
// pid.json { pid, procStart, startedAt } — the ONE liveness fact (spawn.js `writePidFile`)
|
|
13
|
+
//
|
|
14
|
+
// ONE WRITER PER FIELD: `start` writes start.json, pid.json (and child.log through the spawn helper); `clear` writes cleared.json
|
|
15
|
+
// (the human dismissed a refusal, so a reload no longer shows it); the CLI child writes the run dir. The phase is never stored — it is READ from those files each time (`readStart`):
|
|
16
|
+
// starting the child is alive and the run dir has no book row yet
|
|
17
|
+
// started the run dir has its first book row (`pids.jsonl`, written by the run itself before its first step); `state` is
|
|
18
|
+
// working / parked / ended from `runLiveness` + `ask.json` (M4c's one "is it running?" rule), never a timer
|
|
19
|
+
// refused the child is dead and the run dir never got a book row: `say` = the CLI's own sentence (scrubbed) + "Nothing spent."
|
|
20
|
+
//
|
|
21
|
+
// One click, one start: `start` is fully synchronous (check -> mkdir -> spawn -> write pid.json, no await), so two requests that
|
|
22
|
+
// arrive together run one after the other and the second sees the first's `starting` start and is refused.
|
|
23
|
+
import { randomBytes } from 'node:crypto';
|
|
24
|
+
import {
|
|
25
|
+
existsSync, mkdirSync, realpathSync, rmdirSync, writeFileSync,
|
|
26
|
+
} from 'node:fs';
|
|
27
|
+
import { dirname, join } from 'node:path';
|
|
28
|
+
import { fileURLToPath } from 'node:url';
|
|
29
|
+
|
|
30
|
+
import { scrub } from '../authoring.js';
|
|
31
|
+
import { readPidRows } from '../books.js';
|
|
32
|
+
import {
|
|
33
|
+
PANEL_STARTS_DIR, checkRunId, claimRunId, readFileInside, readdirInside, resolveRunDir,
|
|
34
|
+
} from '../flow.js';
|
|
35
|
+
import { booksFresh, runLiveness } from '../liveness.js';
|
|
36
|
+
import { dropUnstartedValues, writeRunValues } from '../runvalues.js';
|
|
37
|
+
import {
|
|
38
|
+
childRunning, providerKeys, readJsonFile, spawnDetached, writePidFile,
|
|
39
|
+
} from './spawn.js';
|
|
40
|
+
|
|
41
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
42
|
+
const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
|
|
43
|
+
const ID_RE = /^s-[0-9a-z]{10}-[0-9a-f]{4}$/;
|
|
44
|
+
const newId = () => `s-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
|
|
45
|
+
const LOG_TAIL_CHARS = 1500;
|
|
46
|
+
const NOTHING_SPENT = 'Nothing spent.';
|
|
47
|
+
const ENDED_SAY = `The run process ended before it started. ${NOTHING_SPENT}`;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {{ root: string, bin?: string }} opts
|
|
51
|
+
*/
|
|
52
|
+
export function createStarter(opts) {
|
|
53
|
+
const { root, bin = BIN } = opts;
|
|
54
|
+
|
|
55
|
+
/** The starts folder's real path, or null when the flows root does not exist. */
|
|
56
|
+
const startsDir = () => {
|
|
57
|
+
try { return join(realpathSync(root), PANEL_STARTS_DIR); } catch { return null; }
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** Is this run id one the CLI would take? Its own check, and no run dir (or file) of that name yet. @param {string} flow @param {unknown} runId */
|
|
61
|
+
function checkRun(flow, runId) {
|
|
62
|
+
const c = checkRunId(runId);
|
|
63
|
+
if (!c.ok) return { ok: false, say: `${c.red.replace(/^run: /, '')}.` };
|
|
64
|
+
const r = resolveRunDir(join(realpathSync(root), flow), runId);
|
|
65
|
+
if (!r.ok) return { ok: false, say: `${r.red.replace(/^run: /, '')}.` };
|
|
66
|
+
if (existsSync(r.runDir)) return { ok: false, say: `There is already a run "${runId}" of this flow. Use a new run id.` };
|
|
67
|
+
return { ok: true, runDir: r.runDir };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The start's state, READ from its files.
|
|
72
|
+
* @param {string} dir the start folder @param {string} id @param {string[]} keys the provider key values to scrub from anything quoted
|
|
73
|
+
*/
|
|
74
|
+
function readStart(dir, id, keys) {
|
|
75
|
+
const st = readJsonFile(dir, 'start.json');
|
|
76
|
+
if (!st || typeof st.flow !== 'string' || typeof st.runId !== 'string') return null;
|
|
77
|
+
const base = { startId: id, kind: st.kind, flow: st.flow, runId: st.runId };
|
|
78
|
+
const resolved = resolveRunDir(join(realpathSync(root), st.flow), st.runId);
|
|
79
|
+
if (!resolved.ok) return null;
|
|
80
|
+
// alive FIRST, then the book row: a child that writes its row and exits between the two reads as started, never refused
|
|
81
|
+
const alive = childRunning(dir);
|
|
82
|
+
const carriedOn = () => {
|
|
83
|
+
const live = runLiveness(resolved.runDir);
|
|
84
|
+
if (live === 'running') return 'working';
|
|
85
|
+
if (readFileInside(resolved.runDir, 'ask.json').ok) return 'parked';
|
|
86
|
+
if (live === 'unknown' && booksFresh(resolved.runDir)) return 'working';
|
|
87
|
+
return 'ended';
|
|
88
|
+
};
|
|
89
|
+
// A Resume (M4e amendment 4): the run already has book rows from its first leg, so "took over" is read from the halt record
|
|
90
|
+
// (`halt.json`), which only the continuing process consumes — still there means the child has not taken the run yet.
|
|
91
|
+
if (st.kind === 'resume') {
|
|
92
|
+
const waiting = readFileInside(resolved.runDir, 'halt.json').ok;
|
|
93
|
+
if (!waiting) return { ...base, phase: 'started', state: carriedOn() };
|
|
94
|
+
if (alive) return { ...base, phase: 'starting' };
|
|
95
|
+
} else if (readPidRows(resolved.runDir).length > 0) {
|
|
96
|
+
return { ...base, phase: 'started', state: carriedOn() };
|
|
97
|
+
} else if (alive) return { ...base, phase: 'starting' };
|
|
98
|
+
const log = readFileInside(dir, 'child.log');
|
|
99
|
+
const tail = log.ok ? scrub(log.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
|
|
100
|
+
const say = tail === '' ? ENDED_SAY : (tail.includes(NOTHING_SPENT) ? tail : `${tail}\n${NOTHING_SPENT}`);
|
|
101
|
+
return { ...base, phase: 'refused', say };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const view = (id, keys) => {
|
|
105
|
+
const d = startsDir();
|
|
106
|
+
return d === null ? null : readStart(join(d, id), id, keys);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
checkRun,
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Start `fwdloop run` for a flow whose every $0 check already passed at the calling door. Re-checks the run id here (nothing
|
|
114
|
+
* awaits between this check and the spawn). 202 { startId, runId } or a refusal; a refusal creates nothing.
|
|
115
|
+
* `runId` '' = no typed id: the start CLAIMS the next `run-<n>` itself (claimRunId, folder created exclusively; amendment 3).
|
|
116
|
+
* `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
|
+
* 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
|
|
120
|
+
* @returns {{ status: number, body: any }}
|
|
121
|
+
*/
|
|
122
|
+
start({
|
|
123
|
+
kind, flow, runId, sources, values = null,
|
|
124
|
+
}, env) {
|
|
125
|
+
const sd = startsDir();
|
|
126
|
+
if (sd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
|
|
127
|
+
/** @type {string|null} */
|
|
128
|
+
let claimedDir = null;
|
|
129
|
+
if (runId === '') {
|
|
130
|
+
const c = claimRunId(join(realpathSync(root), flow));
|
|
131
|
+
if (!c.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: `${c.red.replace(/^run: /, '')}.` } };
|
|
132
|
+
({ runId } = c);
|
|
133
|
+
claimedDir = c.runDir;
|
|
134
|
+
} else {
|
|
135
|
+
const run = checkRun(flow, runId);
|
|
136
|
+
if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
|
|
137
|
+
}
|
|
138
|
+
const runDirOf = () => claimedDir ?? join(realpathSync(root), flow, 'runs', runId);
|
|
139
|
+
const unclaim = () => {
|
|
140
|
+
if (claimedDir === null && values === null) return;
|
|
141
|
+
dropUnstartedValues(runDirOf());
|
|
142
|
+
try { rmdirSync(runDirOf()); } catch { /* not empty / gone */ }
|
|
143
|
+
};
|
|
144
|
+
if (values !== null) {
|
|
145
|
+
// the run folder holds its signed values from before the first step: a claimed one already exists, a typed id's is made here
|
|
146
|
+
// (exclusively: a folder that appeared meanwhile refuses)
|
|
147
|
+
try { if (claimedDir === null) mkdirSync(runDirOf()); } catch { return { status: 400, body: { ok: false, refused: 'run-id', say: `There is already a run "${runId}" of this flow. Use a new run id.` } }; }
|
|
148
|
+
const w = writeRunValues(runDirOf(), { ...values, runId });
|
|
149
|
+
if (!w.ok) { unclaim(); return { status: 500, body: { ok: false, refused: 'values', say: `The signed values could not be saved. ${NOTHING_SPENT}` } }; }
|
|
150
|
+
}
|
|
151
|
+
const keys = providerKeys(env);
|
|
152
|
+
// 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
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const id = newId();
|
|
161
|
+
const dir = join(sd, id);
|
|
162
|
+
mkdirSync(sd, { recursive: true, mode: 0o700 });
|
|
163
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
164
|
+
writeFileSync(join(dir, 'start.json'), `${JSON.stringify({
|
|
165
|
+
kind, flow, runId, sources, startedAt: new Date().toISOString(),
|
|
166
|
+
}, null, 2)}\n`, { mode: 0o600 });
|
|
167
|
+
const argv = ['run', flow, '--root', realpathSync(root), ...sources.flatMap((s) => ['--source', `${s.role}=${s.path}`]), '--run-id', runId];
|
|
168
|
+
let child;
|
|
169
|
+
try {
|
|
170
|
+
child = spawnDetached({
|
|
171
|
+
bin, argv, env, logPath: join(dir, 'child.log'),
|
|
172
|
+
});
|
|
173
|
+
} catch (e) {
|
|
174
|
+
unclaim();
|
|
175
|
+
return { status: 500, body: { ok: false, refused: 'spawn', say: `The run could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). ${NOTHING_SPENT}`, startId: id } };
|
|
176
|
+
}
|
|
177
|
+
child.on('error', () => {}); // a later spawn failure leaves no pid-backed child: the start then reads as refused
|
|
178
|
+
writePidFile(dir, child);
|
|
179
|
+
return { status: 202, body: { ok: true, startId: id, flow, runId } };
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 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
|
+
* signed values version. The same detached-child shape as `start`; the start folder reads as `starting` until the child consumes
|
|
185
|
+
* `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
|
|
187
|
+
* @returns {{ status: number, body: any }}
|
|
188
|
+
*/
|
|
189
|
+
startContinue({ flow, runId, version }, env) {
|
|
190
|
+
const sd = startsDir();
|
|
191
|
+
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
|
+
}
|
|
197
|
+
const id = newId();
|
|
198
|
+
const dir = join(sd, id);
|
|
199
|
+
mkdirSync(sd, { recursive: true, mode: 0o700 });
|
|
200
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
201
|
+
writeFileSync(join(dir, 'start.json'), `${JSON.stringify({
|
|
202
|
+
kind: 'resume', flow, runId, version, sources: [], startedAt: new Date().toISOString(),
|
|
203
|
+
}, null, 2)}\n`, { mode: 0o600 });
|
|
204
|
+
let child;
|
|
205
|
+
try {
|
|
206
|
+
child = spawnDetached({
|
|
207
|
+
bin, argv: ['continue', runId, '--flow', flow, '--root', realpathSync(root)], env, logPath: join(dir, 'child.log'),
|
|
208
|
+
});
|
|
209
|
+
} catch (e) {
|
|
210
|
+
return { status: 500, body: { ok: false, refused: 'spawn', say: `The resume could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). ${NOTHING_SPENT}`, startId: id } };
|
|
211
|
+
}
|
|
212
|
+
child.on('error', () => {});
|
|
213
|
+
writePidFile(dir, child);
|
|
214
|
+
return { status: 202, body: { ok: true, startId: id, flow, runId } };
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The newest start the human has not cleared, for a page that was reloaded: `starting` (re-attach the poll) or `refused` (show the
|
|
219
|
+
* CLI's sentence). Null when that start began (`started`: the run is in Runs) or there is none.
|
|
220
|
+
* @param {string[]} keys
|
|
221
|
+
*/
|
|
222
|
+
newestOpen(keys) {
|
|
223
|
+
const sd = startsDir();
|
|
224
|
+
if (sd === null) return null;
|
|
225
|
+
for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
|
|
226
|
+
if (readFileInside(join(sd, id), 'cleared.json').ok) continue;
|
|
227
|
+
const v = readStart(join(sd, id), id, keys);
|
|
228
|
+
if (v === null) continue;
|
|
229
|
+
return v.phase === 'started' ? null : v;
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
},
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* `POST /api/author/start/:startId/clear`: the human dismisses a REFUSED start. Writes `cleared.json` once; any other phase is refused.
|
|
236
|
+
* @param {string} id @param {string[]} keys
|
|
237
|
+
*/
|
|
238
|
+
clear(id, keys) {
|
|
239
|
+
const v = ID_RE.test(id) ? view(id, keys) : null;
|
|
240
|
+
if (v === null) return { status: 404, body: { ok: false, refused: 'no-such-start' } };
|
|
241
|
+
if (v.phase !== 'refused') return { status: 409, body: { ok: false, refused: 'not-clearable', say: 'Only a refused start can be cleared.' } };
|
|
242
|
+
try {
|
|
243
|
+
writeFileSync(join(/** @type {string} */ (startsDir()), id, 'cleared.json'), `${JSON.stringify({ at: new Date().toISOString() })}\n`, { mode: 0o600, flag: 'wx' });
|
|
244
|
+
} catch (e) {
|
|
245
|
+
if (/** @type {any} */ (e)?.code !== 'EEXIST') return { status: 500, body: { ok: false, refused: 'clear', say: 'The refusal could not be cleared.' } };
|
|
246
|
+
}
|
|
247
|
+
return { status: 200, body: { ok: true, startId: id } };
|
|
248
|
+
},
|
|
249
|
+
|
|
250
|
+
/** `GET /api/author/start/:startId`. @param {string} id @param {string[]} keys */
|
|
251
|
+
get(id, keys) {
|
|
252
|
+
if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-start' } };
|
|
253
|
+
const v = view(id, keys);
|
|
254
|
+
return v === null ? { status: 404, body: { ok: false, refused: 'no-such-start' } } : { status: 200, body: { ok: true, ...v } };
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// M4e amendment 5 items 2-4 and amendment 4 items 1, 4, 6: the values ONE RUN may be signed with, checked in ONE place for both the
|
|
2
|
+
// Run-a-signed-flow door (open: Inputs, Destination, Cap $, each ask's wait) and the Resume door (open: Cap $ only). Pure of the panel:
|
|
3
|
+
// no HTTP, no spawn, no writes — it reads the disk only to check a destination (realpath at the click, amendment 1) and asks the caller's
|
|
4
|
+
// monthly check. Every refusal is `{ field, say }`, spends $0 and writes nothing.
|
|
5
|
+
//
|
|
6
|
+
// What a run can change without a new flow is exactly these values; a job line, an ask's words or position, or the steps are not a run
|
|
7
|
+
// (the body may not even carry them: an unknown key is refused by name with the new-flow sentence).
|
|
8
|
+
import { capFloorText, destinationRefusal } from './authorcard.js';
|
|
9
|
+
import { monthlyRefusalText } from '../monthly.js';
|
|
10
|
+
import { parseWaitMs, valuesHash, sameValues } from '../runvalues.js';
|
|
11
|
+
|
|
12
|
+
export const NEW_FLOW_SAY = 'Only the files, the destination, the money cap and an ask\'s wait can change from one run to the next. A change to a job line, an ask\'s words or the steps is a new flow: use New job.';
|
|
13
|
+
export const RESUME_ONLY_CAP_SAY = 'A resume changes only the cap. New files or a new destination or ask wait is a new run of this flow (Run a signed flow); a change to a job line or an ask is a new flow (New job).';
|
|
14
|
+
const WAIT_SAY = 'The ask wait must be a whole number with s, m or h, such as 30m or 1h.';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The smallest cap a Resume accepts: the next whole cent above what is spent, but never under the cap floor. ONE function for the
|
|
18
|
+
* door's refusal and the page's note, so the "at least $X" it names is itself accepted.
|
|
19
|
+
* @param {number} spentUsd @param {number} floorUsd
|
|
20
|
+
*/
|
|
21
|
+
export function leastResumeCapUsd(spentUsd, floorUsd) {
|
|
22
|
+
const aboveSpent = Math.ceil(spentUsd * 100 + 1e-6) / 100;
|
|
23
|
+
return Math.max(aboveSpent, Math.ceil(floorUsd * 100 - 1e-6) / 100);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {unknown} v */
|
|
27
|
+
const typed = (v) => (typeof v === 'string' ? v.trim() : v);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {object} a
|
|
31
|
+
* @param {string[]} a.allowedKeys the body keys this door takes; any other key is refused by name
|
|
32
|
+
* @param {any} a.body
|
|
33
|
+
* @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>}} a.base the values in force now (the flow's own, or the run's newest signed version)
|
|
34
|
+
* @param {string} a.realRoot the flows root (real path)
|
|
35
|
+
* @param {boolean} a.capOnly Resume: destination and waits are never read from the body
|
|
36
|
+
* @param {number} a.floorUsd the smallest cap that funds one round of a step (amendment 4 item 2); 0 = none
|
|
37
|
+
* @param {number} [a.spentUsd] what the run has already spent (Resume): the cap must be above it
|
|
38
|
+
* @param {boolean} [a.always] Resume: the floor and the monthly check always apply. A Run applies them only when its cap differs from the
|
|
39
|
+
* flow's own (a plain Run keeps the CLI's own gate, as it always did), so an old flow signed below today's floor still runs plain.
|
|
40
|
+
* @param {(remainingUsd: number) => null | { problem: string } | { ok: boolean, room: any }} a.monthlyClaim the one monthly check
|
|
41
|
+
* @returns {{ ok: true, values: {capUsd: number, destination: string|null, askWaits: Record<string,string>}, differs: boolean, remainingUsd: number } | { ok: false, status: number, refusals: {field: string, say: string}[], refused?: string, say?: string }}
|
|
42
|
+
*/
|
|
43
|
+
export function checkValues({
|
|
44
|
+
allowedKeys, body, base, realRoot, capOnly, floorUsd, spentUsd = 0, monthlyClaim, always = false,
|
|
45
|
+
}) {
|
|
46
|
+
/** @type {{field: string, say: string}[]} */
|
|
47
|
+
const refusals = [];
|
|
48
|
+
const no = (field, say) => refusals.push({ field, say });
|
|
49
|
+
const b = body && typeof body === 'object' ? body : {};
|
|
50
|
+
const extra = Object.keys(b).filter((k) => !allowedKeys.includes(k));
|
|
51
|
+
if (extra.length > 0) {
|
|
52
|
+
return {
|
|
53
|
+
ok: false, status: 400, refused: capOnly ? 'not-a-resume' : 'not-a-run', say: capOnly ? RESUME_ONLY_CAP_SAY : NEW_FLOW_SAY, refusals: [{ field: extra[0], say: capOnly ? RESUME_ONLY_CAP_SAY : NEW_FLOW_SAY }],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let { capUsd } = base;
|
|
58
|
+
const capIn = typed(b.capUsd);
|
|
59
|
+
if (capIn !== undefined && capIn !== '' && capIn !== null) {
|
|
60
|
+
const n = Number(capIn);
|
|
61
|
+
if (!(Number.isFinite(n) && n > 0)) no('capUsd', 'The cap must be a number above 0 (dollars per run).');
|
|
62
|
+
else capUsd = n;
|
|
63
|
+
}
|
|
64
|
+
if (refusals.length === 0) {
|
|
65
|
+
if (spentUsd > 0 && capUsd <= spentUsd + 1e-9) {
|
|
66
|
+
no('capUsd', `The cap must be above what is already spent (at least $${leastResumeCapUsd(spentUsd, floorUsd).toFixed(2)}).`);
|
|
67
|
+
} else if (capUsd < floorUsd && (always || capUsd !== base.capUsd)) no('capUsd', capFloorText(floorUsd));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let destination = base.destination;
|
|
71
|
+
const destIn = capOnly ? undefined : typed(b.destination);
|
|
72
|
+
if (destIn !== undefined && destIn !== null && destIn !== '') {
|
|
73
|
+
if (typeof destIn !== 'string') no('destination', 'The destination must be the full path of a folder.');
|
|
74
|
+
else if (base.destination === null) no('destination', 'This flow has no send step, so it has no destination to change. A destination needs a new flow (New job).');
|
|
75
|
+
else {
|
|
76
|
+
const why = destinationRefusal(destIn, realRoot);
|
|
77
|
+
if (why !== null) no('destination', why);
|
|
78
|
+
else destination = destIn;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const askWaits = { ...base.askWaits };
|
|
83
|
+
if (!capOnly && b.askWaits !== undefined && b.askWaits !== null) {
|
|
84
|
+
if (typeof b.askWaits !== 'object' || Array.isArray(b.askWaits)) no('askWaits', WAIT_SAY);
|
|
85
|
+
else {
|
|
86
|
+
for (const [line, raw] of Object.entries(b.askWaits)) {
|
|
87
|
+
if (!Object.hasOwn(base.askWaits, line)) { no(`askWaits.${line}`, `This flow has no ask on line ${line}.`); continue; }
|
|
88
|
+
const t = typeof raw === 'string' ? raw.trim() : '';
|
|
89
|
+
if (t === '') continue; // blank = the value in force
|
|
90
|
+
if (parseWaitMs(t) === null) no(`askWaits.${line}`, WAIT_SAY);
|
|
91
|
+
else askWaits[line] = t.toLowerCase();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (refusals.length === 0 && (always || capUsd !== base.capUsd)) {
|
|
97
|
+
// the one monthly check: what this run can still spend (a fresh run: its cap; a resume: the cap above what it already spent)
|
|
98
|
+
const remainingUsd = capUsd - spentUsd;
|
|
99
|
+
const claim = monthlyClaim(remainingUsd);
|
|
100
|
+
if (claim && 'problem' in claim) return { ok: false, status: 409, refused: 'monthly', say: `${claim.problem} — refusing rather than guess the monthly limit. Nothing spent.`, refusals: [] };
|
|
101
|
+
if (claim && !claim.ok) no('capUsd', monthlyRefusalText(claim.room));
|
|
102
|
+
}
|
|
103
|
+
if (refusals.length > 0) return { ok: false, status: 400, refusals };
|
|
104
|
+
const values = { capUsd, destination, askWaits };
|
|
105
|
+
return {
|
|
106
|
+
ok: true, values, differs: !sameValues(values, base), remainingUsd: capUsd - spentUsd,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export { valuesHash };
|