fwdloop 0.16.0 → 0.18.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/README.md +2 -0
- package/bin/fwdloop +10 -7
- package/package.json +1 -1
- package/src/authoring.js +6 -6
- package/src/books.js +6 -1
- package/src/catalogue.json +9 -3
- package/src/ctx-tools.js +245 -0
- package/src/draft-steps.js +89 -30
- package/src/drafter.js +28 -4
- package/src/draftspend.js +109 -3
- package/src/liveness.js +34 -10
- package/src/panel/author.js +125 -37
- package/src/panel/authorcard.js +15 -10
- package/src/panel/authorflows.js +9 -3
- package/src/panel/authorresume.js +5 -4
- package/src/panel/authorstart.js +21 -9
- package/src/panel/authortrigger.js +384 -0
- package/src/panel/authorvalues.js +5 -3
- package/src/panel/data.js +104 -16
- package/src/panel/index.html +257 -44
- package/src/panel/scheduler.js +125 -0
- package/src/panel/server.js +24 -10
- package/src/panel/settings.js +2 -2
- package/src/plain-checks.js +51 -0
- package/src/primitives.js +34 -3
- package/src/provider.js +17 -8
- package/src/run-store.js +47 -0
- package/src/runner.js +2 -0
- package/src/runvalues.js +5 -3
- package/src/setup.js +24 -0
- package/src/signed-text.js +26 -0
- package/src/summary-words.js +155 -0
- package/src/trigger-clock.js +142 -0
- package/src/trigger-files.js +212 -0
- package/src/trigger-line.js +86 -0
- package/src/types.js +1 -0
- package/src/version.js +13 -0
- package/types/authoring.d.ts +1 -3
- package/types/ctx-tools.d.ts +18 -0
- package/types/draft-steps.d.ts +38 -5
- package/types/drafter.d.ts +3 -3
- package/types/draftspend.d.ts +56 -0
- package/types/liveness.d.ts +7 -1
- package/types/panel/author.d.ts +149 -146
- package/types/panel/authorcard.d.ts +12 -2
- package/types/panel/authorflows.d.ts +11 -3
- package/types/panel/authorstart.d.ts +7 -4
- package/types/panel/authortrigger.d.ts +210 -0
- package/types/panel/authorvalues.d.ts +3 -1
- package/types/panel/data.d.ts +14 -7
- package/types/panel/scheduler.d.ts +15 -0
- package/types/panel/server.d.ts +11 -3
- package/types/plain-checks.d.ts +22 -0
- package/types/primitives.d.ts +0 -6
- package/types/provider.d.ts +7 -1
- package/types/run-store.d.ts +11 -0
- package/types/runvalues.d.ts +1 -1
- package/types/setup.d.ts +27 -0
- package/types/summary-words.d.ts +53 -0
- package/types/trigger-clock.d.ts +60 -0
- package/types/trigger-files.d.ts +90 -0
- package/types/trigger-line.d.ts +44 -0
- package/types/types.d.ts +4 -0
- package/types/version.d.ts +2 -0
package/src/panel/authorcard.js
CHANGED
|
@@ -17,6 +17,7 @@ import { isAbsolute, join } from 'node:path';
|
|
|
17
17
|
import { checkFlowName, signedHashOf } from '../flow.js';
|
|
18
18
|
import { checkSendDestination } from '../runner.js';
|
|
19
19
|
import { parseSignedText } from '../signed-text.js';
|
|
20
|
+
import { capTooSmallText } from '../draftspend.js';
|
|
20
21
|
import { readPriceConfig, resolveUsableModel, ceilingCostUsd } from '../provider.js';
|
|
21
22
|
|
|
22
23
|
/** The heading line the prose files use (flows/job2-m6a-3/prose.txt); the parser matches `/^arbiter guardrails\b/i`. */
|
|
@@ -237,7 +238,8 @@ export function cardFromSigned({ lines, arbiter }) {
|
|
|
237
238
|
askWait: firstWait ?? '1h',
|
|
238
239
|
};
|
|
239
240
|
const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
|
|
240
|
-
|
|
241
|
+
// M9 am1: the trigger is not a box on the card, and signing an Edit clears it (By hand again), so it is not part of the fidelity check
|
|
242
|
+
const norm = (a) => JSON.stringify({ ...a, trigger: null, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
|
|
241
243
|
const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
|
|
242
244
|
if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
|
|
243
245
|
return { ok: true, card };
|
|
@@ -300,18 +302,18 @@ export function capFloorUsd(jobText, home, pick) {
|
|
|
300
302
|
|
|
301
303
|
/** The floor itself, for a caller that already knows whether the job has a step that is not an ask (a signed flow: any step off an ask line). @param {boolean} hasRoundStep @param {string} [home] @param {{ slot?: string, provider?: string, model?: string }|null} [pick] */
|
|
302
304
|
export function capFloorFor(hasRoundStep, home, pick) {
|
|
305
|
+
return capFloorOf(hasRoundStep, home, pick).usd;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The floor and the model id it was computed for (M4d am20: the refusal sentence names it). `{ usd: 0, model: null }` when there is nothing to hold. @param {boolean} hasRoundStep @param {string} [home] @param {{ slot?: string, provider?: string, model?: string }|null} [pick] */
|
|
309
|
+
export function capFloorOf(hasRoundStep, home, pick) {
|
|
303
310
|
const slot = pick?.slot ?? pick?.provider;
|
|
304
|
-
if (!hasRoundStep || !slot) return 0;
|
|
311
|
+
if (!hasRoundStep || !slot) return { usd: 0, model: null };
|
|
305
312
|
// No usable model (nothing picked or ticked, a broken config): nothing is held here, and the run itself is refused by name (`resolveUsableModel`).
|
|
306
313
|
try {
|
|
307
314
|
const u = resolveUsableModel(slot, { config: readPriceConfig(home), model: pick?.model });
|
|
308
|
-
return u.ok ? ceilingCostUsd(u.rates) : 0;
|
|
309
|
-
} catch { return 0; }
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/** The one sentence for a cap under the floor (red under Cap, and the Draft / sign refusal). @param {number} floorUsd */
|
|
313
|
-
export function capFloorText(floorUsd) {
|
|
314
|
-
return `needs at least $${(Math.ceil(floorUsd * 100 - 1e-6) / 100).toFixed(2)} per run`;
|
|
315
|
+
return u.ok ? { usd: ceilingCostUsd(u.rates), model: String(u.model) } : { usd: 0, model: null };
|
|
316
|
+
} catch { return { usd: 0, model: null }; }
|
|
315
317
|
}
|
|
316
318
|
|
|
317
319
|
/**
|
|
@@ -364,7 +366,10 @@ export function checkCard(card, { root, keys = [], home }) {
|
|
|
364
366
|
// cap
|
|
365
367
|
if (typeof card.capUsd === 'string' || typeof card.capUsd === 'number') {
|
|
366
368
|
if (!(Number.isFinite(Number(card.capUsd)) && Number(card.capUsd) > 0)) no('capUsd', 'The cap must be a number above 0 (dollars per run).');
|
|
367
|
-
else
|
|
369
|
+
else {
|
|
370
|
+
const floor = capFloorOf(parseJobBox(card.job).steps.some((s) => s.ask === null), home, card);
|
|
371
|
+
if (Number(card.capUsd) < floor.usd) no('capUsd', capTooSmallText('drafting', Number(card.capUsd), floor.usd, String(floor.model)));
|
|
372
|
+
}
|
|
368
373
|
} else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
|
|
369
374
|
|
|
370
375
|
// destination: one folder, or empty for no send (it is sent at the last step)
|
package/src/panel/authorflows.js
CHANGED
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
applyRunValues, flowValues, pickRunValues, valuesHash,
|
|
28
28
|
} from '../runvalues.js';
|
|
29
29
|
import {
|
|
30
|
-
|
|
30
|
+
capFloorOf, cardFromSigned, checkInputRows, runInputRows,
|
|
31
31
|
} from './authorcard.js';
|
|
32
32
|
import { checkValues } from './authorvalues.js';
|
|
33
33
|
import { getRunControls } from './data.js';
|
|
@@ -58,7 +58,7 @@ export function formFacts(read, home, flowDir, picked = null) {
|
|
|
58
58
|
const recorded = flowDir === undefined ? null : readModelRecord(flowDir);
|
|
59
59
|
const pick = recorded ?? picked;
|
|
60
60
|
return {
|
|
61
|
-
values, jobLines, hasSend: values.destination !== null, capFloorUsd:
|
|
61
|
+
values, jobLines, hasSend: values.destination !== null, capFloorUsd: capFloorOf(hasRound, home, pick).usd, floorModel: capFloorOf(hasRound, home, pick).model,
|
|
62
62
|
model: recorded === null ? null : { slot: recorded.slot, model: recorded.model, label: `${recorded.slot} · ${recorded.model}` },
|
|
63
63
|
};
|
|
64
64
|
}
|
|
@@ -192,7 +192,7 @@ export function createFlowsDoor(opts) {
|
|
|
192
192
|
const modelReds = noRecord ? modelRefusal({ provider: body?.provider, model: body?.model }, loaded) : [];
|
|
193
193
|
const newPick = noRecord && modelReds.length === 0 ? { slot: body.provider, model: body.model } : null;
|
|
194
194
|
const checked = checkValues({
|
|
195
|
-
allowedKeys: RUN_KEYS, body, base: flowValues(read.arbiter), realRoot, capOnly: false, floorUsd: formFacts(read, home, join(realRoot, flow), newPick).capFloorUsd, monthlyClaim,
|
|
195
|
+
allowedKeys: RUN_KEYS, body, base: flowValues(read.arbiter), realRoot, capOnly: false, floorUsd: formFacts(read, home, join(realRoot, flow), newPick).capFloorUsd, floorModel: formFacts(read, home, join(realRoot, flow), newPick).floorModel, monthlyClaim,
|
|
196
196
|
});
|
|
197
197
|
if (!checked.ok && checked.refused) return reply(checked.status, { refused: checked.refused, say: checked.say, refusals: checked.refusals });
|
|
198
198
|
/** @type {{field: string, say: string}[]} */
|
|
@@ -266,6 +266,12 @@ export function createFlowsDoor(opts) {
|
|
|
266
266
|
return realRoot === null ? null : editBlockOf(realRoot, name);
|
|
267
267
|
},
|
|
268
268
|
|
|
269
|
+
/** M9: the source paths the newest run of this job used, role -> path (blank = none), for a start a trigger fires. @param {string} name @param {string[]} roles */
|
|
270
|
+
lastSourcesOf(name, roles) {
|
|
271
|
+
const realRoot = realRootOrNull();
|
|
272
|
+
return realRoot === null ? { runId: null, sources: Object.fromEntries(roles.map((r) => [r, ''])) } : lastSources(join(realRoot, name), roles);
|
|
273
|
+
},
|
|
274
|
+
|
|
269
275
|
/** `GET /api/author/flows`. */
|
|
270
276
|
flows() {
|
|
271
277
|
const realRoot = realRootOrNull();
|
|
@@ -22,7 +22,7 @@ import { auditSpend } from '../runner.js';
|
|
|
22
22
|
import {
|
|
23
23
|
flowValues, pickRunValues, valuesHash, writeRunValues,
|
|
24
24
|
} from '../runvalues.js';
|
|
25
|
-
import { capFloorFor,
|
|
25
|
+
import { capFloorFor, capFloorOf } from './authorcard.js';
|
|
26
26
|
import { formFacts } from './authorflows.js';
|
|
27
27
|
import { checkValues } from './authorvalues.js';
|
|
28
28
|
import { getRunControls } from './data.js';
|
|
@@ -75,7 +75,7 @@ export function createResumeDoor(opts) {
|
|
|
75
75
|
const hasRound = read.declaration.steps.some((st) => !(read.arbiter.asks ?? []).some((a) => a.line === st.fromLine));
|
|
76
76
|
if (formOnly) return { ok: /** @type {true} */ (true), flow, runId, runDir: rd.runDir, version, base, spentUsd: spent.total, read, hasRound };
|
|
77
77
|
const checked = checkValues({
|
|
78
|
-
allowedKeys: KEYS, body: b, base, realRoot, capOnly: true, floorUsd: capFloorFor(hasRound, home, readModelRecord(join(realRoot, flow))), spentUsd: spent.total, monthlyClaim, always: true,
|
|
78
|
+
allowedKeys: KEYS, body: b, base, realRoot, capOnly: true, floorUsd: capFloorFor(hasRound, home, readModelRecord(join(realRoot, flow))), floorModel: capFloorOf(hasRound, home, readModelRecord(join(realRoot, flow))).model, spentUsd: spent.total, monthlyClaim, always: true,
|
|
79
79
|
});
|
|
80
80
|
if (!checked.ok) {
|
|
81
81
|
return no(checked.status, checked.refused ? { refused: checked.refused, say: checked.say, refusals: checked.refusals } : { refused: 'resume', refusals: checked.refusals, say: checked.refusals[0]?.say ?? 'Not resumed. Fix the marked box.' });
|
|
@@ -101,11 +101,12 @@ export function createResumeDoor(opts) {
|
|
|
101
101
|
const inputsRead = readFileInside(s.runDir, 'inputs.json');
|
|
102
102
|
let inputs = [];
|
|
103
103
|
try { inputs = inputsRead.ok ? JSON.parse(inputsRead.text).map((m) => ({ role: String(m.id), path: String(m.source) })) : []; } catch { inputs = []; }
|
|
104
|
-
const
|
|
104
|
+
const floor = capFloorOf(s.hasRound, home, readModelRecord(dirname(dirname(s.runDir))));
|
|
105
|
+
const floorUsd = floor.usd;
|
|
105
106
|
return {
|
|
106
107
|
status: 200,
|
|
107
108
|
body: {
|
|
108
|
-
ok: true, flow: s.flow, runId: s.runId, version: s.version, values: s.base, spentUsd: s.spentUsd, inputs, floorUsd,
|
|
109
|
+
ok: true, flow: s.flow, runId: s.runId, version: s.version, values: s.base, spentUsd: s.spentUsd, inputs, floorUsd, floorModel: floor.model, jobLines: formFacts(s.read, home, dirname(dirname(s.runDir))).jobLines, model: formFacts(s.read, home, dirname(dirname(s.runDir))).model,
|
|
109
110
|
},
|
|
110
111
|
};
|
|
111
112
|
},
|
package/src/panel/authorstart.js
CHANGED
|
@@ -34,6 +34,7 @@ import {
|
|
|
34
34
|
} from '../flow.js';
|
|
35
35
|
import { booksFresh, runLiveness } from '../liveness.js';
|
|
36
36
|
import { dropUnstartedValues, writeRunValues } from '../runvalues.js';
|
|
37
|
+
import { TRIGGER_RECORD_FILE } from '../trigger-line.js';
|
|
37
38
|
import {
|
|
38
39
|
childRunning, providerKeys, readJsonFile, spawnDetached, writePidFile,
|
|
39
40
|
} from './spawn.js';
|
|
@@ -106,13 +107,17 @@ export function createStarter(opts) {
|
|
|
106
107
|
return d === null ? null : readStart(join(d, id), id, keys);
|
|
107
108
|
};
|
|
108
109
|
|
|
109
|
-
/**
|
|
110
|
-
|
|
110
|
+
/**
|
|
111
|
+
* M6 amendment 3: the ONE rule for "a run of this flow is starting": the newest start folder of the flow in phase `starting`, or null.
|
|
112
|
+
* With `runId`, only a start of that run (the Runs list reads a run folder as `[▶]` starting by this same rule).
|
|
113
|
+
* @param {string} flow @param {string[]} keys @param {string} [runId]
|
|
114
|
+
*/
|
|
115
|
+
function startingFor(flow, keys, runId) {
|
|
111
116
|
const sd = startsDir();
|
|
112
117
|
if (sd === null) return null;
|
|
113
118
|
for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
|
|
114
119
|
const v = readStart(join(sd, id), id, keys);
|
|
115
|
-
if (v && v.flow === flow && v.phase === 'starting') return id;
|
|
120
|
+
if (v && v.flow === flow && (runId === undefined || v.runId === runId) && v.phase === 'starting') return id;
|
|
116
121
|
}
|
|
117
122
|
return null;
|
|
118
123
|
}
|
|
@@ -127,12 +132,14 @@ export function createStarter(opts) {
|
|
|
127
132
|
* `runId` '' = no typed id: the start CLAIMS the next `run-<n>` itself (claimRunId, folder created exclusively; amendment 3).
|
|
128
133
|
* `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
|
|
129
134
|
* folder as `signed-values.json` BEFORE the spawn; the run then uses them (`pickRunValues`). None = the flow's own.
|
|
130
|
-
*
|
|
135
|
+
* `trigger` (M9): `{kind, reason, catchUp, ...}` for a start a trigger fired (kind 'trigger'): written once into the run's own folder as `trigger.json`
|
|
136
|
+
* BEFORE the spawn; `appendHistory` copies it into the run's history row (the catch-up mark, am2 item 1).
|
|
137
|
+
* @param {{ kind: 'run'|'sign'|'trigger', flow: string, runId: string, sources: {role: string, path: string}[], values?: any, pick?: {slot: string, model: string}|null, trigger?: Record<string, any>|null }} a
|
|
131
138
|
* @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded the keys load: its env is the child's env AND (with its key names) the scrub list
|
|
132
139
|
* @returns {{ status: number, body: any }}
|
|
133
140
|
*/
|
|
134
141
|
start({
|
|
135
|
-
kind, flow, runId, sources, values = null, pick = null,
|
|
142
|
+
kind, flow, runId, sources, values = null, pick = null, trigger = null,
|
|
136
143
|
}, loaded) {
|
|
137
144
|
const { env } = loaded;
|
|
138
145
|
const sd = startsDir();
|
|
@@ -150,17 +157,22 @@ export function createStarter(opts) {
|
|
|
150
157
|
}
|
|
151
158
|
const runDirOf = () => claimedDir ?? join(realpathSync(root), flow, 'runs', runId);
|
|
152
159
|
const unclaim = () => {
|
|
153
|
-
if (claimedDir === null && values === null) return;
|
|
160
|
+
if (claimedDir === null && values === null && trigger === null) return;
|
|
154
161
|
dropUnstartedValues(runDirOf());
|
|
155
162
|
try { rmdirSync(runDirOf()); } catch { /* not empty / gone */ }
|
|
156
163
|
};
|
|
157
|
-
if (values !== null) {
|
|
158
|
-
// the run folder holds its signed values from before the first step: a claimed one already exists,
|
|
159
|
-
// (exclusively: a folder that appeared meanwhile refuses)
|
|
164
|
+
if (values !== null || trigger !== null) {
|
|
165
|
+
// the run folder holds its signed values (and a triggered start's reason) from before the first step: a claimed one already exists,
|
|
166
|
+
// a typed id's is made here (exclusively: a folder that appeared meanwhile refuses)
|
|
160
167
|
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.` } }; }
|
|
168
|
+
}
|
|
169
|
+
if (values !== null) {
|
|
161
170
|
const w = writeRunValues(runDirOf(), { ...values, runId });
|
|
162
171
|
if (!w.ok) { unclaim(); return { status: 500, body: { ok: false, refused: 'values', say: `The signed values could not be saved. ${NOTHING_SPENT}` } }; }
|
|
163
172
|
}
|
|
173
|
+
if (trigger !== null) {
|
|
174
|
+
try { writeFileSync(join(runDirOf(), TRIGGER_RECORD_FILE), `${JSON.stringify(trigger)}\n`, { flag: 'wx', mode: 0o600 }); } catch { unclaim(); return { status: 500, body: { ok: false, refused: 'trigger', say: `The reason this run started could not be saved. ${NOTHING_SPENT}` } }; }
|
|
175
|
+
}
|
|
164
176
|
const keys = providerKeys(loaded);
|
|
165
177
|
// one start at a time while one is still spawning for this flow (a double click, two tabs)
|
|
166
178
|
const startingId = startingFor(flow, keys);
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// M9 pieces 3 and 4 (docs/wiki/the-module-ladder.md, "M9" items 1-6, am1, am2): the TRIGGER door of the panel's backend.
|
|
2
|
+
//
|
|
3
|
+
// prepare(body) POST /api/author/trigger-prepare { flow, trigger } the first click: every $0 check, signs nothing, returns the hash
|
|
4
|
+
// set(body) POST /api/author/trigger { flow, trigger, hash } the second click: re-signs the SAME plan with only the trigger line
|
|
5
|
+
// changed (the M6 replace path), then arms it
|
|
6
|
+
// read(flow) the one read function the cards use: the trigger, whether it is armed, the next slot, the last outcome. No words.
|
|
7
|
+
// fire(...) one fire's outcome, in order: busy -> monthly -> sources -> the ONE start. Every outcome is a `triggers.jsonl` row.
|
|
8
|
+
//
|
|
9
|
+
// ONE WRITER PER FIELD: `set` writes the trigger line (through `proseWithTrigger` and `writeFlow`); `armFor` writes the armed row and the
|
|
10
|
+
// baseline; `recordFire` / the file trigger's `poll` write the fire / ran rows BEFORE a start (a crash loses a run, never doubles one);
|
|
11
|
+
// `appendOutcome` writes `triggers.jsonl`. Nothing here is read from a model: the trigger is typed data in the signed arbiter block.
|
|
12
|
+
//
|
|
13
|
+
// Files, per job, under `<flowDir>/`:
|
|
14
|
+
// triggers.jsonl append-only history of every fire outcome (all signed triggers of the job)
|
|
15
|
+
// triggers/<flowSignatureHash>/ the ledgers of ONE signed trigger. A new signing (a changed trigger, an Edit) is a new hash, so a
|
|
16
|
+
// clock.jsonl new folder: an older trigger's rows can never carry over (a fresh folder per signature, not rows
|
|
17
|
+
// seen.jsonl tagged by hash: nothing to filter, nothing to forget to filter). `clock.jsonl`'s `armed` row is
|
|
18
|
+
// the one "this trigger was set" fact for BOTH kinds; `seen.jsonl` is the file kinds' sha ledger.
|
|
19
|
+
import {
|
|
20
|
+
appendFileSync, mkdirSync, realpathSync,
|
|
21
|
+
} from 'node:fs';
|
|
22
|
+
import { userInfo } from 'node:os';
|
|
23
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
24
|
+
|
|
25
|
+
import { scrub } from '../authoring.js';
|
|
26
|
+
import { endRow, readHistory } from '../books.js';
|
|
27
|
+
import { loadCatalogue } from '../catalogue.js';
|
|
28
|
+
import {
|
|
29
|
+
FLOW_FILES, checkFlowName, listFlowNames, listRunIds, readFileInside, readFlow, resolveRunDir, writeFlow,
|
|
30
|
+
} from '../flow.js';
|
|
31
|
+
import { parseSignedText } from '../signed-text.js';
|
|
32
|
+
import { editClearsWords, scheduledWords } from '../summary-words.js';
|
|
33
|
+
import { armTrigger, nextSlot, readRows, validateSchedule } from '../trigger-clock.js';
|
|
34
|
+
import { checkTarget, createFileTrigger } from '../trigger-files.js';
|
|
35
|
+
import { readModelRecord } from '../flowmodel.js';
|
|
36
|
+
import { carrySetup, readSetup } from '../setup.js';
|
|
37
|
+
import {
|
|
38
|
+
proseWithTrigger, stripTrigger, triggerHash, triggerLine,
|
|
39
|
+
} from '../trigger-line.js';
|
|
40
|
+
|
|
41
|
+
/** @typedef {import('../trigger-line.js').Trigger} Trigger */
|
|
42
|
+
|
|
43
|
+
/** A trigger in the words a row and a run reason use: `daily 09:00`, `new-file jd = file:/home/you/inbox`. @param {Trigger} t */
|
|
44
|
+
const describe = (t) => triggerLine(t).replace('guardrail: trigger ', '');
|
|
45
|
+
|
|
46
|
+
export const NO_GREEN_SAY = 'This job has not had a good run yet. Run it once by hand and get it right first; then you can set when it runs. Nothing was changed.';
|
|
47
|
+
const HISTORY_FILE = 'triggers.jsonl';
|
|
48
|
+
const HASH_RE = /^[0-9a-f]{64}$/;
|
|
49
|
+
|
|
50
|
+
/** The folder holding the ledgers of ONE signed trigger. @param {string} flowDir @param {string} flowHash */
|
|
51
|
+
export function triggerLedgerDir(flowDir, flowHash) {
|
|
52
|
+
if (!HASH_RE.test(flowHash)) throw new Error('trigger ledger: the flow signature hash is not a sha256');
|
|
53
|
+
return join(flowDir, 'triggers', flowHash);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Every fire outcome of a job, oldest first, through the safe gateway. @param {string} flowDir @returns {any[]} */
|
|
57
|
+
export function readOutcomes(flowDir) {
|
|
58
|
+
const f = readFileInside(flowDir, HISTORY_FILE);
|
|
59
|
+
if (!f.ok) return [];
|
|
60
|
+
return f.text.split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The ONE writer of `triggers.jsonl`: append-only, one line per fire outcome. @param {string} flowDir @param {Record<string, any>} row */
|
|
64
|
+
export function appendOutcome(flowDir, row) {
|
|
65
|
+
appendFileSync(join(flowDir, HISTORY_FILE), `${JSON.stringify(row)}\n`, { mode: 0o600 });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The signature hashes that are this job: the current one plus every one it is a trigger-only re-sign of (the `trigger-resign` rows `set` appends to
|
|
70
|
+
* setup.jsonl, followed back by `resignOf`). A real Edit writes a new setup.jsonl with no such rows, so it starts a new chain (am1).
|
|
71
|
+
* @param {string} flowDir @param {string} sig
|
|
72
|
+
*/
|
|
73
|
+
function signingsOf(flowDir, sig) {
|
|
74
|
+
const out = new Set([sig]);
|
|
75
|
+
const s = readSetup(flowDir);
|
|
76
|
+
if (!s.present) return out;
|
|
77
|
+
for (let h = sig; ;) {
|
|
78
|
+
const prev = s.rows.findLast((r) => r.kind === 'trigger-resign' && r.flowHash === h)?.resignOf;
|
|
79
|
+
if (typeof prev !== 'string' || out.has(prev)) return out;
|
|
80
|
+
out.add(prev); h = prev;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* M9 item 1 and 2: does this job have "one green run"? The ONE function that decides it. A passed run counts when the job it ran (its own
|
|
86
|
+
* `job/` copy) is the current job WITHOUT its trigger line: so changing only the trigger keeps the run (item 2), and an Edit that changes
|
|
87
|
+
* the steps, a guardrail or the cap does not (am1). A run from before runs kept a job copy has none to compare, so it counts only when its
|
|
88
|
+
* history row's signature is the job's current one (a job signed since then is not the job it ran, unless that signing only added or changed its trigger line: see signingsOf).
|
|
89
|
+
* @param {string} flowDir
|
|
90
|
+
*/
|
|
91
|
+
export function hasGreenRunForJob(flowDir) {
|
|
92
|
+
const cur = {};
|
|
93
|
+
for (const f of FLOW_FILES) {
|
|
94
|
+
const r = readFileInside(flowDir, f);
|
|
95
|
+
if (!r.ok) return false;
|
|
96
|
+
cur[f] = r.text;
|
|
97
|
+
}
|
|
98
|
+
let sig;
|
|
99
|
+
try { sig = JSON.parse(cur['signature.json']).flow; } catch { return false; }
|
|
100
|
+
const key = (/** @type {string} */ prose, /** @type {string} */ decl) => `${stripTrigger(prose).trimEnd()}\n\u0000${decl}`;
|
|
101
|
+
const want = key(cur['prose.txt'], cur['declaration.json']);
|
|
102
|
+
const signings = signingsOf(flowDir, sig);
|
|
103
|
+
const history = readHistory(flowDir);
|
|
104
|
+
for (const id of listRunIds(flowDir)) {
|
|
105
|
+
const r = resolveRunDir(flowDir, id);
|
|
106
|
+
if (!r.ok) continue;
|
|
107
|
+
const end = endRow(history, r.runDir, id);
|
|
108
|
+
if (end === null || end.outcome !== 'complete') continue;
|
|
109
|
+
const prose = readFileInside(r.runDir, 'job/prose.txt');
|
|
110
|
+
const decl = readFileInside(r.runDir, 'job/declaration.json');
|
|
111
|
+
if (prose.ok && decl.ok) { if (key(prose.text, decl.text) === want) return true; } else if (!prose.ok && prose.missing && signings.has(end.signatureHash)) return true;
|
|
112
|
+
}
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The ONE writer of "this trigger was set": the starting point (am2 item 2). Idempotent. A file kind records what is already there first
|
|
118
|
+
* (never runs), then the armed row, so a failure between the two leaves it unarmed and the next call finishes it. Throws, naming why, when
|
|
119
|
+
* the target is not usable now.
|
|
120
|
+
* @param {string} flowDir @param {string} flowHash @param {Trigger} trigger @param {number} now epoch ms
|
|
121
|
+
* @returns {{armed: boolean, already: boolean}}
|
|
122
|
+
*/
|
|
123
|
+
export function armFor(flowDir, flowHash, trigger, now) {
|
|
124
|
+
const dir = triggerLedgerDir(flowDir, flowHash);
|
|
125
|
+
const clock = join(dir, 'clock.jsonl');
|
|
126
|
+
if (readRows(clock).some((r) => r.kind === 'armed')) return { armed: true, already: true };
|
|
127
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
128
|
+
if (trigger.kind === 'file-updated') createFileTrigger({ mode: 'updated', target: trigger.path, ledger: join(dir, 'seen.jsonl') }).arm();
|
|
129
|
+
else if (trigger.kind === 'new-file') createFileTrigger({ mode: 'new', target: trigger.folder, ledger: join(dir, 'seen.jsonl') }).arm();
|
|
130
|
+
armTrigger(clock, now);
|
|
131
|
+
return { armed: true, already: false };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The trigger a body asks for, checked as data: null (By hand) or exactly one of the five shapes, the role one of the job's inputs, a full
|
|
136
|
+
* path. Returns the typed trigger or the sentence that says what to fix.
|
|
137
|
+
* @param {unknown} t @param {string[]} roles
|
|
138
|
+
* @returns {{ok: true, trigger: Trigger|null} | {ok: false, say: string}}
|
|
139
|
+
*/
|
|
140
|
+
function shapeOf(t, roles) {
|
|
141
|
+
if (t === null) return { ok: true, trigger: null };
|
|
142
|
+
if (!t || typeof t !== 'object' || Array.isArray(t)) return { ok: false, say: 'Pick when it runs from the choices. A schedule is not typed as text. Nothing was changed.' };
|
|
143
|
+
const o = /** @type {Record<string, unknown>} */ (t);
|
|
144
|
+
if (o.kind === 'file-updated' || o.kind === 'new-file') {
|
|
145
|
+
const where = o.kind === 'new-file' ? 'folder' : 'path';
|
|
146
|
+
const extra = Object.keys(o).filter((k) => !['kind', 'role', where].includes(k));
|
|
147
|
+
if (extra.length > 0) return { ok: false, say: `A "${o.kind}" trigger takes a kind, a role and a ${where}, not "${extra[0]}". Nothing was changed.` };
|
|
148
|
+
if (typeof o.role !== 'string' || !roles.includes(o.role)) return { ok: false, say: `This job has no input named "${String(o.role)}" (it takes: ${roles.join(', ') || 'none'}). Pick one of those. Nothing was changed.` };
|
|
149
|
+
const p = o[where];
|
|
150
|
+
// eslint-disable-next-line no-control-regex
|
|
151
|
+
if (typeof p !== 'string' || p === '' || !isAbsolute(p) || /[\x00-\x1f\x7f]/.test(p)) return { ok: false, say: `The ${where} must be a full path on one line, like /home/you/inbox. Nothing was changed.` };
|
|
152
|
+
return { ok: true, trigger: /** @type {Trigger} */ (o.kind === 'new-file' ? { kind: 'new-file', role: o.role, folder: p } : { kind: 'file-updated', role: o.role, path: p }) };
|
|
153
|
+
}
|
|
154
|
+
try { return { ok: true, trigger: validateSchedule(t) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was changed.` }; }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {{ root: string, flowsDoor: ReturnType<typeof import('./authorflows.js').createFlowsDoor>, starter: ReturnType<typeof import('./authorstart.js').createStarter>, loadEnv: () => any, monthlyClaim: (usd: number) => any, modelRefusal: (card: any, loaded: any) => { field: string, say: string }[], now?: () => number }} opts
|
|
159
|
+
*/
|
|
160
|
+
export function createTriggerDoor(opts) {
|
|
161
|
+
const {
|
|
162
|
+
root, flowsDoor, starter, loadEnv, monthlyClaim, modelRefusal, now = Date.now,
|
|
163
|
+
} = opts;
|
|
164
|
+
|
|
165
|
+
const realRootOrNull = () => { try { return realpathSync(root); } catch { return null; } };
|
|
166
|
+
|
|
167
|
+
/** @param {string} realRoot @param {string} name */
|
|
168
|
+
function readSigned(realRoot, name) {
|
|
169
|
+
const cat = loadCatalogue();
|
|
170
|
+
if (!cat.ok) return { ok: /** @type {false} */ (false), reds: [`catalogue: ${cat.reds.join('; ')}`] };
|
|
171
|
+
return readFlow({ root: realRoot, name, catalogue: cat.primitives });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Every $0 check of a trigger change, shared by both clicks. `{ok:false, reply}` or the facts a change needs.
|
|
176
|
+
* @param {any} body
|
|
177
|
+
*/
|
|
178
|
+
function inspect(body) {
|
|
179
|
+
const reply = (/** @type {number} */ status, /** @type {Record<string, any>} */ b) => ({ ok: /** @type {false} */ (false), reply: { status, body: { ok: false, ...b } } });
|
|
180
|
+
const realRoot = realRootOrNull();
|
|
181
|
+
if (realRoot === null) return reply(400, { refused: 'root', say: 'The flows folder this panel serves does not exist.' });
|
|
182
|
+
const flow = typeof body?.flow === 'string' ? body.flow : '';
|
|
183
|
+
const named = checkFlowName(flow);
|
|
184
|
+
if (!named.ok) return reply(400, { refused: 'flow', say: `${named.red}.` });
|
|
185
|
+
const read = readSigned(realRoot, flow);
|
|
186
|
+
if (!read.ok) return reply(400, { refused: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so its trigger cannot be set. Nothing was changed.` });
|
|
187
|
+
const roles = (read.arbiter.sources ?? []).map((s) => s.role);
|
|
188
|
+
const shaped = shapeOf(body?.trigger === undefined ? 'missing' : body.trigger, roles);
|
|
189
|
+
if (!shaped.ok) return reply(400, { refused: 'bad-trigger', say: shaped.say });
|
|
190
|
+
const { trigger } = shaped;
|
|
191
|
+
const flowDir = join(realRoot, flow);
|
|
192
|
+
if (trigger !== null && !hasGreenRunForJob(flowDir)) return reply(409, { refused: 'no-green-run', say: NO_GREEN_SAY });
|
|
193
|
+
const blocked = flowsDoor.editBlock(flow); // the same rule Edit uses: a run starting, running or waiting at its ask
|
|
194
|
+
if (blocked !== null) return reply(409, { refused: 'run-live', say: `${blocked}. Nothing was changed.` });
|
|
195
|
+
if (trigger !== null && 'role' in trigger) {
|
|
196
|
+
try {
|
|
197
|
+
checkTarget(trigger.kind === 'new-file' ? 'new' : 'updated', trigger.kind === 'new-file' ? trigger.folder : trigger.path);
|
|
198
|
+
} catch (e) {
|
|
199
|
+
return reply(400, { refused: 'bad-trigger', say: `${/** @type {Error} */ (e).message}. Nothing was changed.` });
|
|
200
|
+
}
|
|
201
|
+
// a file that does not exist yet may arrive (checkTarget allows it), but its folder must be there: a typo is caught now, not never
|
|
202
|
+
if (trigger.kind === 'file-updated') {
|
|
203
|
+
try { realpathSync(dirname(trigger.path)); } catch { return reply(400, { refused: 'bad-trigger', say: `The folder of ${trigger.path} does not exist. Nothing was changed.` }); }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const proseNow = readFileInside(flowDir, 'prose.txt');
|
|
207
|
+
const declNow = readFileInside(flowDir, 'declaration.json');
|
|
208
|
+
if (!proseNow.ok || !declNow.ok) return reply(400, { refused: 'flow', say: `"${flow}" cannot be read. Nothing was changed.` });
|
|
209
|
+
const proseText = proseWithTrigger(proseNow.text, trigger);
|
|
210
|
+
const parsed = parseSignedText(proseText);
|
|
211
|
+
if (!parsed.ok) return reply(400, { refused: 'bad-trigger', say: `That trigger does not fit the signed text (${parsed.reds[0]}). Nothing was changed.` });
|
|
212
|
+
return {
|
|
213
|
+
ok: /** @type {true} */ (true), flow, read, trigger, flowDir, realRoot, proseText, declaration: JSON.parse(declNow.text),
|
|
214
|
+
hash: triggerHash({ flow, flowSignatureHash: read.signature.flow, trigger }),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return {
|
|
219
|
+
inspect,
|
|
220
|
+
now,
|
|
221
|
+
|
|
222
|
+
/** `POST /api/author/trigger-prepare`: the first click. Checks, signs and writes nothing. @param {any} body */
|
|
223
|
+
prepare(body) {
|
|
224
|
+
const s = inspect(body);
|
|
225
|
+
if (!s.ok) return s.reply;
|
|
226
|
+
return { status: 200, body: { ok: true, flow: s.flow, trigger: s.trigger, words: scheduledWords(s.trigger), hash: s.hash } };
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* `POST /api/author/trigger`: the second click, carrying the hash it was shown. Re-signs the SAME plan (declaration.json byte for byte,
|
|
231
|
+
* prose.txt with only its trigger line changed) through the M6 replace path, then arms the trigger. $0: no drafter, no run.
|
|
232
|
+
* @param {any} body
|
|
233
|
+
*/
|
|
234
|
+
set(body) {
|
|
235
|
+
const s = inspect(body);
|
|
236
|
+
if (!s.ok) return s.reply;
|
|
237
|
+
if (typeof body.hash !== 'string' || body.hash !== s.hash) {
|
|
238
|
+
return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'What you were shown is not what is on the card now (its hash differs). Nothing was signed. Look again, then sign.' } };
|
|
239
|
+
}
|
|
240
|
+
const cat = loadCatalogue();
|
|
241
|
+
if (!cat.ok) return { status: 500, body: { ok: false, refused: 'catalogue', say: 'The catalogue could not be read. Nothing was changed.' } };
|
|
242
|
+
// the setup record of how the job was made is not part of the three signed files: carry it over unchanged
|
|
243
|
+
const setup = readFileInside(s.flowDir, 'setup.jsonl');
|
|
244
|
+
const signedBy = userInfo().username;
|
|
245
|
+
const written = writeFlow({
|
|
246
|
+
root: s.realRoot, name: s.flow, proseText: s.proseText, declaration: s.declaration, signedBy, signedAt: new Date(now()).toISOString(), catalogue: cat.primitives, replaces: { flowHash: s.read.signature.flow },
|
|
247
|
+
});
|
|
248
|
+
if (!written.ok) return { status: 409, body: { ok: false, refused: 'sign-refused', say: 'The trigger was not signed. Nothing was changed.', reds: written.reds.map((r) => scrub(String(r), [])) } };
|
|
249
|
+
if (setup.ok) carrySetup({ flowDir: s.flowDir, oldText: setup.text, oldFlowHash: s.read.signature.flow, newFlowHash: written.signature.flow, at: new Date(now()).toISOString() }); // the record is a courtesy; the job is signed
|
|
250
|
+
let armed = true; let armSay = null;
|
|
251
|
+
if (s.trigger !== null) {
|
|
252
|
+
try { armFor(s.flowDir, written.signature.flow, s.trigger, now()); } catch (e) { armed = false; armSay = /** @type {Error} */ (e).message; }
|
|
253
|
+
}
|
|
254
|
+
return { status: 200, body: { ok: true, flow: s.flow, trigger: s.trigger, words: scheduledWords(s.trigger), flowHash: written.signature.flow, armed, ...(armSay === null ? {} : { say: `The trigger is signed but not armed yet: ${armSay}.` }) } };
|
|
255
|
+
},
|
|
256
|
+
|
|
257
|
+
/** Every signed job that has a trigger, as the scheduler needs it: `{flow, flowDir, read, trigger}`. Reads each job the way the CLI will (signature verified). */
|
|
258
|
+
scan() {
|
|
259
|
+
const realRoot = realRootOrNull();
|
|
260
|
+
if (realRoot === null) return [];
|
|
261
|
+
const jobs = [];
|
|
262
|
+
for (const flow of listFlowNames(realRoot)) {
|
|
263
|
+
const read = readSigned(realRoot, flow);
|
|
264
|
+
if (read.ok && read.arbiter.trigger !== null) jobs.push({ flow, flowDir: join(realRoot, flow), read, trigger: /** @type {Trigger} */ (read.arbiter.trigger) });
|
|
265
|
+
}
|
|
266
|
+
return jobs;
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
/** Arm this job's signed trigger if it is not armed yet (a crash between the sign and the arm). Idempotent; throws naming why. @param {{flowDir: string, read: any, trigger: Trigger}} job */
|
|
270
|
+
ensureArmed(job) {
|
|
271
|
+
return armFor(job.flowDir, job.read.signature.flow, job.trigger, now());
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
/** M9 am3: is a run of this job starting, running or waiting at an ask? (the same check `fire` makes first) @param {{flow: string}} job */
|
|
275
|
+
busy(job) {
|
|
276
|
+
return flowsDoor.editBlock(job.flow) !== null;
|
|
277
|
+
},
|
|
278
|
+
|
|
279
|
+
/** M9 am3: one row for a queued file that is not a fire (deleted / changed before its turn). @param {{flow: string, flowDir: string, trigger: Trigger}} job @param {Record<string, any>} row */
|
|
280
|
+
note(job, row) {
|
|
281
|
+
appendOutcome(job.flowDir, { at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), ...row });
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* One row in `triggers.jsonl` that is not a fire (the trigger could not be watched). @param {{flow: string, flowDir: string, trigger: Trigger}} job @param {string} why
|
|
286
|
+
*/
|
|
287
|
+
refuse(job, why) {
|
|
288
|
+
appendOutcome(job.flowDir, {
|
|
289
|
+
at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), outcome: 'refused', why,
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* M9 item 3-5: one fire, in this order, each outcome ONE row in `triggers.jsonl`: busy -> monthly-exhausted -> refused (an input or the keys
|
|
295
|
+
* are missing) -> started through the ONE start path (kind `trigger`; the reason and the catch-up mark go into the run's own folder first).
|
|
296
|
+
* The fire / ran ledger row was written by the caller BEFORE this, so a crash loses a run and never doubles one.
|
|
297
|
+
* @param {{flow: string, flowDir: string, read: any, trigger: Trigger}} job
|
|
298
|
+
* @param {{kind: 'clock', slot: number, catchUp: boolean, missed: number} | {kind: 'file', path: string, sha: string}} cause
|
|
299
|
+
* @param {{ told?: (outcome: string) => boolean, beforeStart?: () => void }} [hooks] M9 am3 (a queued file): `told(outcome)` true = this file
|
|
300
|
+
* already has a row for that outcome, so none is written again (the outcome is still returned); `beforeStart` runs right before the ONE
|
|
301
|
+
* start, once every check has passed: the scheduler writes the file's `ran` row there.
|
|
302
|
+
*/
|
|
303
|
+
fire(job, cause, hooks = {}) {
|
|
304
|
+
const { flow, flowDir, read, trigger } = job;
|
|
305
|
+
const desc = describe(trigger);
|
|
306
|
+
const base = {
|
|
307
|
+
at: new Date(now()).toISOString(), flow, trigger: desc,
|
|
308
|
+
...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), catchUp: cause.catchUp, missed: cause.missed } : { file: cause.path, sha: cause.sha, catchUp: false }),
|
|
309
|
+
};
|
|
310
|
+
const done = (/** @type {Record<string, any>} */ r) => { const row = /** @type {Record<string, any>} */ ({ ...base, ...r }); if (!(row.outcome !== 'started' && hooks.told?.(row.outcome))) appendOutcome(flowDir, row); return row; };
|
|
311
|
+
const busy = flowsDoor.editBlock(flow); // one run at a time per job: starting, running, or waiting at its ask
|
|
312
|
+
if (busy !== null) return done({ outcome: 'busy', say: busy });
|
|
313
|
+
const claim = monthlyClaim(read.arbiter.capUsd); // the same check the Run door decides on
|
|
314
|
+
if (claim && 'problem' in claim) return done({ outcome: 'refused', why: `${claim.problem}. Nothing spent.` });
|
|
315
|
+
if (claim && !claim.ok) return done({ outcome: 'monthly-exhausted', leftUsd: claim.room.leftUsd, needUsd: claim.room.needUsd, atLeast: claim.room.atLeast === true });
|
|
316
|
+
const roles = (read.arbiter.sources ?? []).map((x) => x.role);
|
|
317
|
+
const last = flowsDoor.lastSourcesOf(flow, roles).sources;
|
|
318
|
+
const sources = [];
|
|
319
|
+
for (const role of roles) {
|
|
320
|
+
const p = 'role' in trigger && trigger.role === role && cause.kind === 'file' ? cause.path : last[role];
|
|
321
|
+
if (!p) return done({ outcome: 'refused', why: `There is no earlier run of this job to take the input "${role}" from. Run it by hand once with that input. Nothing started.` });
|
|
322
|
+
try { sources.push({ role, path: realpathSync(p) }); } catch { return done({ outcome: 'refused', why: `The input "${role}" is not there (${p}). Nothing started.` }); }
|
|
323
|
+
}
|
|
324
|
+
const loaded = loadEnv();
|
|
325
|
+
if (!loaded.ok) return done({ outcome: 'refused', why: String(loaded.refusal) });
|
|
326
|
+
// the Run door's model check (its one `modelRefusal`), on the job's recorded model: a trigger picks no model, so a job without a record, or whose
|
|
327
|
+
// line is no longer ticked / priced / keyed in Settings, is refused here at $0, never started
|
|
328
|
+
const rec = readModelRecord(flowDir);
|
|
329
|
+
if (rec === null) return done({ outcome: 'refused', why: 'This job has no model recorded, so it cannot start by itself. Run it by hand once from the Chat card and pick a model. Nothing started.' });
|
|
330
|
+
const modelSays = modelRefusal({ provider: rec.slot, model: rec.model }, loaded);
|
|
331
|
+
if (modelSays.length > 0) return done({ outcome: 'refused', why: modelSays[0].say.replace(/ Nothing was spent\.$/, '. Nothing started.') });
|
|
332
|
+
const catchUp = base.catchUp === true;
|
|
333
|
+
const record = {
|
|
334
|
+
kind: cause.kind, trigger: desc, reason: `Started by the trigger: ${desc}${catchUp ? ' (catch-up)' : ''}`, catchUp, ...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), missed: cause.missed } : { file: cause.path, sha: cause.sha }),
|
|
335
|
+
};
|
|
336
|
+
hooks.beforeStart?.();
|
|
337
|
+
const started = starter.start({
|
|
338
|
+
kind: 'trigger', flow, runId: '', sources, trigger: record,
|
|
339
|
+
}, loaded);
|
|
340
|
+
if (started.status !== 202) return done({ outcome: 'refused', why: String(started.body.say ?? 'The run did not start.') });
|
|
341
|
+
return done({ outcome: 'started', runId: started.body.runId, startId: started.body.startId });
|
|
342
|
+
},
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* What a card shows of a job's trigger, as data (no words): the signed trigger, whether it is armed, the next slot (clock kinds), the last
|
|
346
|
+
* fire outcome. `null` when the job is not a readable signed job.
|
|
347
|
+
* @param {string} flow
|
|
348
|
+
*/
|
|
349
|
+
read(flow) {
|
|
350
|
+
const realRoot = realRootOrNull();
|
|
351
|
+
if (realRoot === null || !checkFlowName(flow).ok) return null;
|
|
352
|
+
const r = readSigned(realRoot, flow);
|
|
353
|
+
if (!r.ok) return null;
|
|
354
|
+
const flowDir = join(realRoot, flow);
|
|
355
|
+
const { trigger } = r.arbiter;
|
|
356
|
+
const clock = readRows(join(triggerLedgerDir(flowDir, r.signature.flow), 'clock.jsonl'));
|
|
357
|
+
const armed = clock.find((x) => x.kind === 'armed');
|
|
358
|
+
const outcomes = readOutcomes(flowDir);
|
|
359
|
+
const clockKind = trigger !== null && (trigger.kind === 'daily' || trigger.kind === 'weekdays' || trigger.kind === 'weekly');
|
|
360
|
+
return {
|
|
361
|
+
flow, trigger, flowHash: r.signature.flow, armed: armed !== undefined, armedAt: armed ? armed.at : null,
|
|
362
|
+
nextSlotMs: clockKind && armed ? nextSlot(/** @type {any} */ (trigger), now()) : null,
|
|
363
|
+
lastOutcome: outcomes.length > 0 ? outcomes[outcomes.length - 1] : null,
|
|
364
|
+
hasGreenRun: hasGreenRunForJob(flowDir),
|
|
365
|
+
};
|
|
366
|
+
},
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* What the Run card's dropdown needs of one job (M9 piece 5): the typed trigger, its words, whether it is armed, and, when the job has had
|
|
370
|
+
* no good run, the server's refusal sentence (the page shows it and disables the dropdown; it invents no words). `editNote` is am1's
|
|
371
|
+
* warning, set only when the job has a trigger. `null` when the job is not a readable signed job.
|
|
372
|
+
* @param {string} flow
|
|
373
|
+
*/
|
|
374
|
+
card(flow) {
|
|
375
|
+
const r = this.read(flow);
|
|
376
|
+
if (r === null) return null;
|
|
377
|
+
return {
|
|
378
|
+
trigger: r.trigger, words: scheduledWords(r.trigger), armed: r.armed, hasGreenRun: r.hasGreenRun,
|
|
379
|
+
refusal: r.hasGreenRun ? null : NO_GREEN_SAY, editNote: editClearsWords(r.trigger),
|
|
380
|
+
};
|
|
381
|
+
},
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
//
|
|
6
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
7
|
// (the body may not even carry them: an unknown key is refused by name with the new-flow sentence).
|
|
8
|
-
import {
|
|
8
|
+
import { destinationRefusal } from './authorcard.js';
|
|
9
|
+
import { capTooSmallText } from '../draftspend.js';
|
|
9
10
|
import { monthlyRefusalText } from '../monthly.js';
|
|
10
11
|
import { parseWaitMs, valuesHash, sameValues } from '../runvalues.js';
|
|
11
12
|
|
|
@@ -33,6 +34,7 @@ const typed = (v) => (typeof v === 'string' ? v.trim() : v);
|
|
|
33
34
|
* @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
35
|
* @param {string} a.realRoot the flows root (real path)
|
|
35
36
|
* @param {boolean} a.capOnly Resume: destination and waits are never read from the body
|
|
37
|
+
* @param {string|null} [a.floorModel] the model id the floor was computed for (named in the refusal, M4d am20)
|
|
36
38
|
* @param {number} a.floorUsd the smallest cap that funds one round of a step (amendment 4 item 2); 0 = none
|
|
37
39
|
* @param {number} [a.spentUsd] what the run has already spent (Resume): the cap must be above it
|
|
38
40
|
* @param {boolean} [a.always] Resume: the floor and the monthly check always apply. A Run applies them only when its cap differs from the
|
|
@@ -41,7 +43,7 @@ const typed = (v) => (typeof v === 'string' ? v.trim() : v);
|
|
|
41
43
|
* @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
44
|
*/
|
|
43
45
|
export function checkValues({
|
|
44
|
-
allowedKeys, body, base, realRoot, capOnly, floorUsd, spentUsd = 0, monthlyClaim, always = false,
|
|
46
|
+
allowedKeys, body, base, realRoot, capOnly, floorUsd, floorModel = null, spentUsd = 0, monthlyClaim, always = false,
|
|
45
47
|
}) {
|
|
46
48
|
/** @type {{field: string, say: string}[]} */
|
|
47
49
|
const refusals = [];
|
|
@@ -64,7 +66,7 @@ export function checkValues({
|
|
|
64
66
|
if (refusals.length === 0) {
|
|
65
67
|
if (spentUsd > 0 && capUsd <= spentUsd + 1e-9) {
|
|
66
68
|
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',
|
|
69
|
+
} else if (capUsd < floorUsd && (always || capUsd !== base.capUsd)) no('capUsd', capTooSmallText('run', capUsd, floorUsd, String(floorModel)));
|
|
68
70
|
}
|
|
69
71
|
|
|
70
72
|
let destination = base.destination;
|