fwdloop 0.16.0 → 0.17.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 +8 -6
- package/package.json +1 -1
- package/src/authoring.js +6 -6
- 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 +101 -33
- package/src/panel/authorcard.js +13 -9
- package/src/panel/authorflows.js +3 -3
- package/src/panel/authorresume.js +5 -4
- package/src/panel/authorvalues.js +5 -3
- package/src/panel/data.js +17 -5
- package/src/panel/index.html +74 -42
- package/src/panel/server.js +10 -5
- 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/setup.js +3 -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 +5 -5
- package/types/panel/authorcard.d.ts +12 -2
- package/types/panel/authorflows.d.ts +3 -3
- package/types/panel/authorvalues.d.ts +3 -1
- package/types/panel/server.d.ts +4 -2
- 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/setup.d.ts +8 -0
- package/types/version.d.ts +2 -0
package/src/drafter.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
// prices an unpriced round at the ceiling.
|
|
17
17
|
|
|
18
18
|
import { Loop, HaltError } from 'bare-agent';
|
|
19
|
+
import { capTooSmallText, usdText } from './draftspend.js';
|
|
19
20
|
import { parseSignedText, unsignedAskTtls } from './signed-text.js';
|
|
20
21
|
import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
|
|
21
22
|
import { loadCatalogue } from './catalogue.js';
|
|
@@ -227,6 +228,21 @@ function greenReadRule(sources) {
|
|
|
227
228
|
: `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl".`];
|
|
228
229
|
}
|
|
229
230
|
|
|
231
|
+
/** M7 piece 6 (signed scope item 1): a granted verb ships WITH the line that says when to reach for it, or the
|
|
232
|
+
* model keeps using the familiar one. Only these three get a line; each only when it is on the menu. No number
|
|
233
|
+
* (the tool itself tells a step its size limit). Borrowed in spirit from bareloop src/tools.js@dc06660 strategyFor. */
|
|
234
|
+
const WHEN_TO_USE = Object.freeze({
|
|
235
|
+
compress: '- Use compress when a step only needs what a function IS (its signature and doc) rather than how it works: it returns the head without the body, far cheaper than reading the file. Code only.',
|
|
236
|
+
stash: '- Use stash to park a bulky intermediate result under an id instead of carrying it from step to step; it lasts this run only and each parked item has a size limit.',
|
|
237
|
+
peek: '- Use peek to look at the start and end of something parked with stash without loading all of it.',
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
/** @param {Array<{verb: string}>} menu */
|
|
241
|
+
function whenToUse(menu) {
|
|
242
|
+
const on = new Set(menu.map((e) => e.verb));
|
|
243
|
+
return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
|
|
244
|
+
}
|
|
245
|
+
|
|
230
246
|
export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
231
247
|
const askLines = arbiter.asks.map((a) => a.line);
|
|
232
248
|
const sendLines = arbiter.sends.map((s) => s.line);
|
|
@@ -236,6 +252,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
236
252
|
'Primitive menu (a grant list; a verb not listed does not exist):',
|
|
237
253
|
...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
|
|
238
254
|
'',
|
|
255
|
+
...(whenToUse(menu).length ? ['When to use them:', ...whenToUse(menu), ''] : []),
|
|
239
256
|
'Rules:',
|
|
240
257
|
'- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
|
|
241
258
|
'- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
|
|
@@ -278,7 +295,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
|
|
|
278
295
|
/**
|
|
279
296
|
* Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
|
|
280
297
|
* the batch); otherwise a live provider is built from `slot` (throws on a bad
|
|
281
|
-
* key — the batch preflights first). `
|
|
298
|
+
* key — the batch preflights first). The draft's hard cap is the cap signed in the prose (M4d am13); `priorSpend(ceilingUsd)` (am16) is what this job's earlier drafting already spent, so every round must fit what is LEFT of the cap.
|
|
282
299
|
* `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
|
|
283
300
|
* `onBook` (M4e piece 2a, scope 13): called right BEFORE each provider call (`inFlight: true`, the call counted in
|
|
284
301
|
* `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
|
|
@@ -291,7 +308,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
|
|
|
291
308
|
*/
|
|
292
309
|
export async function draft({
|
|
293
310
|
proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
294
|
-
|
|
311
|
+
priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
|
|
295
312
|
}) {
|
|
296
313
|
// What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
|
|
297
314
|
const thinkingOf = () => {
|
|
@@ -340,9 +357,16 @@ export async function draft({
|
|
|
340
357
|
// The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
|
|
341
358
|
if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
|
|
342
359
|
const roundCeiling = ceilingCostUsd(rates);
|
|
343
|
-
//
|
|
360
|
+
// M4d am13: the draft is capped by the card's Cap $ (the cap signed in the prose), the same number the run is capped at.
|
|
361
|
+
// One round at its ceiling must fit that cap, or refuse at $0 before any provider call.
|
|
362
|
+
// M4d am16 item 2: against the remaining money, not the whole cap. Spend by earlier drafts of this job (a revise, the redraft after answers) is taken off first.
|
|
363
|
+
const priorUsd = typeof priorSpend === 'function' ? priorSpend(roundCeiling) : 0;
|
|
364
|
+
const budgetUsd = arbiter.capUsd - priorUsd;
|
|
344
365
|
if (roundCeiling > budgetUsd) {
|
|
345
|
-
|
|
366
|
+
const capText = usdText(arbiter.capUsd);
|
|
367
|
+
return fail([priorUsd > 0
|
|
368
|
+
? `Cap ${capText} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${roundCeiling.toFixed(4)}. Raise Cap $ or pick another model.`
|
|
369
|
+
: capTooSmallText('drafting', arbiter.capUsd, roundCeiling, modelId)]);
|
|
346
370
|
}
|
|
347
371
|
|
|
348
372
|
const meterings = [];
|
package/src/draftspend.js
CHANGED
|
@@ -17,10 +17,11 @@
|
|
|
17
17
|
// { kind:'draft-live', provider, model, price, tokens, costUsd (metered floor, null when unpriced), rounds, calls,
|
|
18
18
|
// spendComplete (false while a call is in flight or any call is unmetered/unpriced), inFlight, at, startedAt, updatedAt }
|
|
19
19
|
import { renameSync, writeFileSync } from 'node:fs';
|
|
20
|
-
import { join } from 'node:path';
|
|
20
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
21
21
|
|
|
22
|
-
import { readFileInside } from './flow.js';
|
|
23
|
-
import { readSpendRows } from './provider.js';
|
|
22
|
+
import { readdirInside, readFileInside } from './flow.js';
|
|
23
|
+
import { readSpendRows, rowCeilingUsd, spendRowCost, unmeteredCalls } from './provider.js';
|
|
24
|
+
import { parseSignedText } from './signed-text.js';
|
|
24
25
|
|
|
25
26
|
export const DRAFT_SPEND_FILE = 'draft-spend.json';
|
|
26
27
|
|
|
@@ -68,3 +69,108 @@ export function readDirSpendRows(dir) {
|
|
|
68
69
|
const live = readDraftSpend(dir);
|
|
69
70
|
return live ? [live] : [];
|
|
70
71
|
}
|
|
72
|
+
|
|
73
|
+
const PLAN_DIR_RE = /^draft(?:-\d+)?$/;
|
|
74
|
+
/** M4d am21 item 2: the one sentence for a Start over (or revise, or sign) whose chain names an earlier draft that is gone. */
|
|
75
|
+
export const EARLIER_MISSING_SAY = "An earlier draft of this job is missing, so its spend can't be counted.";
|
|
76
|
+
|
|
77
|
+
/** The file a Start over's session folder carries to name the session it started over from (written once by src/panel/author.js). */
|
|
78
|
+
export const STARTED_OVER_FILE = 'started-over-from.json';
|
|
79
|
+
const SESSION_ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* M4d amendment 16 item 1: what ALL of a job's drafting spent — the one writer of that total. A panel draft's session folder holds one plan
|
|
83
|
+
* folder per draft (`draft/`, `draft-<n>/` for each revise and the redraft after answers); each is read by `readDirSpendRows` and priced by
|
|
84
|
+
* `spendRowCost`, the one cost rule. A round whose cost is not known counts at its WORST CASE (item 5): its own booked price's ceiling, else
|
|
85
|
+
* `ceilingUsd` (Settings prices x the fixed token limits), never $0; `notPriced` counts those rounds and `complete` is false.
|
|
86
|
+
* @param {string} sessionDir the panel's draft folder
|
|
87
|
+
* @param {{ ceilingUsd?: number, exclude?: string }} [o] `exclude` = a plan folder name to leave out (the one being written now)
|
|
88
|
+
* @returns {{ usd: number, notPriced: number, complete: boolean, missingEarlier: boolean }}
|
|
89
|
+
*/
|
|
90
|
+
export function draftingSpent(sessionDir, { ceilingUsd = 0, exclude } = {}, seen = new Set()) {
|
|
91
|
+
seen.add(resolve(sessionDir));
|
|
92
|
+
let usd = 0;
|
|
93
|
+
let notPriced = 0;
|
|
94
|
+
let missingEarlier = false;
|
|
95
|
+
for (const name of readdirInside(sessionDir, '.')) {
|
|
96
|
+
if (!PLAN_DIR_RE.test(name) || name === exclude) continue;
|
|
97
|
+
for (const row of readDirSpendRows(join(sessionDir, name))) {
|
|
98
|
+
if (row.spendComplete === false) {
|
|
99
|
+
const n = unmeteredCalls(row);
|
|
100
|
+
const per = rowCeilingUsd(row) > 0 ? rowCeilingUsd(row) : ceilingUsd;
|
|
101
|
+
usd += (row.costUsd ?? 0) + n * per;
|
|
102
|
+
notPriced += n;
|
|
103
|
+
} else if (row.costUsd === null || row.costUsd === undefined) {
|
|
104
|
+
usd += rowCeilingUsd(row) > 0 ? rowCeilingUsd(row) : ceilingUsd;
|
|
105
|
+
notPriced += 1;
|
|
106
|
+
} else usd += spendRowCost(row).usd;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// M4d am19 item 3: a Start over opens a new session folder that names the one it started over from (`started-over-from.json`, written once by the panel):
|
|
110
|
+
// what the earlier session spent is still this job's drafting, so the chain is followed (a name that points back at a folder already counted is not).
|
|
111
|
+
const so = readFileInside(sessionDir, STARTED_OVER_FILE);
|
|
112
|
+
if (so.ok) {
|
|
113
|
+
let from = null;
|
|
114
|
+
try { from = JSON.parse(so.text)?.startedOverFrom; } catch { /* unreadable: no chain */ }
|
|
115
|
+
if (typeof from === 'string' && SESSION_ID_RE.test(from) && !seen.has(resolve(dirname(sessionDir), from))) {
|
|
116
|
+
const prev = join(dirname(sessionDir), from);
|
|
117
|
+
// M4d am21 item 2: a link naming a folder that is gone is NOT $0: what it spent cannot be counted (`missingEarlier`, never a clean figure)
|
|
118
|
+
if (!readFileInside(prev, 'card.json').ok) missingEarlier = true;
|
|
119
|
+
else {
|
|
120
|
+
const before = draftingSpent(prev, { ceilingUsd }, seen);
|
|
121
|
+
usd += before.usd;
|
|
122
|
+
notPriced += before.notPriced;
|
|
123
|
+
missingEarlier = before.missingEarlier;
|
|
124
|
+
}
|
|
125
|
+
} else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
|
|
126
|
+
}
|
|
127
|
+
return { usd, notPriced, complete: notPriced === 0 && !missingEarlier, missingEarlier };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Money to 4 places, trailing zeros kept to 2 (`0.05`, `0.0016`). @param {number} n */
|
|
131
|
+
export const usdText = (n) => `$${String(Math.round(n * 1e4) / 1e4).replace(/^(\d+)$/, '$1.00').replace(/^(\d+\.\d)$/, '$10')}`;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* M4d amendment 16 items 1, 3, 5: the split of the card's Cap $ at Sign & run. `leftUsd` is what the first run may spend, rounded DOWN to 4 places (never
|
|
135
|
+
* more than is left). `line` is the sentence the page shows.
|
|
136
|
+
* @param {number} capUsd @param {{ usd: number, notPriced: number }} spent
|
|
137
|
+
*/
|
|
138
|
+
export function potSplit(capUsd, spent) {
|
|
139
|
+
const leftUsd = Math.max(0, Math.floor((capUsd - spent.usd) * 1e4 + 1e-6) / 1e4);
|
|
140
|
+
const drafting = spent.notPriced > 0
|
|
141
|
+
? `drafting spent at most ${usdText(spent.usd)} (${spent.notPriced} round${spent.notPriced === 1 ? '' : 's'} not priced)`
|
|
142
|
+
: `drafting spent ${usdText(spent.usd)}`;
|
|
143
|
+
return { capUsd, spentUsd: spent.usd, notPriced: spent.notPriced, leftUsd, line: `Cap ${usdText(capUsd)} · ${drafting} · this run up to ${usdText(leftUsd)}` };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The drafter's `priorSpend` for the plan folder `dir`: when it sits in a panel session folder (a `card.json` beside it), what the session's earlier plans spent;
|
|
148
|
+
* null for a plain CLI draft (no session, nothing earlier). The folder being written is left out.
|
|
149
|
+
* @param {string} dir @returns {((ceilingUsd: number) => number)|null}
|
|
150
|
+
*/
|
|
151
|
+
export function sessionPriorSpend(dir) {
|
|
152
|
+
const sessionDir = dirname(resolve(dir));
|
|
153
|
+
if (!readFileInside(sessionDir, 'card.json').ok) return null;
|
|
154
|
+
return (ceilingUsd) => draftingSpent(sessionDir, { ceilingUsd, exclude: basename(dir) }).usd;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* M4d amendment 19 item 1: what a draft reserves against the monthly limit: what is LEFT of the cap in its prose (cap minus what this job's drafting already
|
|
159
|
+
* spent, `sessionPriorSpend`), not one round. A prose that does not parse falls back to one round: the draft itself refuses it at $0.
|
|
160
|
+
* @param {string} proseText @param {string} outDir the plan folder the draft will write @param {number} ceilingUsd one round at its worst case
|
|
161
|
+
*/
|
|
162
|
+
export function draftHoldUsd(proseText, outDir, ceilingUsd) {
|
|
163
|
+
const parsed = parseSignedText(proseText);
|
|
164
|
+
if (!parsed.ok) return ceilingUsd;
|
|
165
|
+
const prior = sessionPriorSpend(outDir);
|
|
166
|
+
return Math.max(0, parsed.arbiter.capUsd - (prior === null ? 0 : prior(ceilingUsd)));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* M4d amendment 19 item 5 / amendment 20: the ONE sentence for a cap that cannot pay for one round. `kind` is "drafting" (the Chat card, the drafter) or "run"
|
|
171
|
+
* (Run a signed flow, Resume); nothing else differs. `modelId` is the model the minimum was computed for, `minUsd` its worst-case round.
|
|
172
|
+
* @param {'drafting'|'run'} kind @param {number} capUsd @param {number} minUsd @param {string} modelId
|
|
173
|
+
*/
|
|
174
|
+
export function capTooSmallText(kind, capUsd, minUsd, modelId) {
|
|
175
|
+
return `Cap ${usdText(capUsd)} is below one ${kind} round's worst case for ${modelId}, $${minUsd.toFixed(4)}. Raise Cap $ or pick another model.`;
|
|
176
|
+
}
|
package/src/liveness.js
CHANGED
|
@@ -23,14 +23,28 @@ const NAME = 'fwdloop';
|
|
|
23
23
|
* @returns {string|null}
|
|
24
24
|
*/
|
|
25
25
|
export function procStartOf(pid) {
|
|
26
|
-
try {
|
|
27
|
-
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
28
|
-
const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
29
|
-
const v = after[19]; // field 3 is after[0], so field 22 is after[19]
|
|
30
|
-
return v !== undefined && /^\d+$/.test(v) ? v : null;
|
|
31
|
-
} catch { return null; }
|
|
26
|
+
try { return startFromStat(readFileSync(`/proc/${pid}/stat`, 'utf8')); } catch { return null; }
|
|
32
27
|
}
|
|
33
28
|
|
|
29
|
+
/** Field 22 of a /proc/<pid>/stat text, or null. @param {string} stat */
|
|
30
|
+
function startFromStat(stat) {
|
|
31
|
+
const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
32
|
+
const v = after[19]; // field 3 is after[0], so field 22 is after[19]
|
|
33
|
+
return v !== undefined && /^\d+$/.test(v) ? v : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Field 3 (state) of a /proc/<pid>/stat text. @param {string} stat */
|
|
37
|
+
const stateFromStat = (stat) => stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3);
|
|
38
|
+
|
|
39
|
+
/** Field 23 (vsize, bytes) of a /proc/<pid>/stat text: 0 for a task that has already released its memory (dying), > 0 for one that is alive (even in its exec window). @param {string} stat */
|
|
40
|
+
const vsizeFromStat = (stat) => Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[20]);
|
|
41
|
+
|
|
42
|
+
/** The two /proc files this module reads, as one seam so a test can hand it a snapshot. */
|
|
43
|
+
const REAL_PROC = {
|
|
44
|
+
cmdline: (/** @type {number} */ pid) => readFileSync(`/proc/${pid}/cmdline`, 'utf8'),
|
|
45
|
+
stat: (/** @type {number} */ pid) => readFileSync(`/proc/${pid}/stat`, 'utf8'),
|
|
46
|
+
};
|
|
47
|
+
|
|
34
48
|
/**
|
|
35
49
|
* Is `pid` a live fwdloop process — and, when `procStart` is given, the SAME
|
|
36
50
|
* process that recorded it?
|
|
@@ -39,16 +53,25 @@ export function procStartOf(pid) {
|
|
|
39
53
|
* null - cannot tell (no /proc, or not ours to read): caller falls back to the 10-minute rule
|
|
40
54
|
* @param {number} pid
|
|
41
55
|
* @param {string|null} [procStart] the starttime recorded by the process itself; absent/null = not compared
|
|
56
|
+
* @param {typeof REAL_PROC} [proc] where /proc is read from (tests pass a snapshot)
|
|
42
57
|
* @returns {boolean|null}
|
|
43
58
|
*/
|
|
44
|
-
export function isFwdloopAlive(pid, procStart) {
|
|
59
|
+
export function isFwdloopAlive(pid, procStart, proc = REAL_PROC) {
|
|
45
60
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
46
61
|
try { process.kill(pid, 0); } catch (e) { if (e?.code !== 'EPERM') return false; /* EPERM: exists, not ours */ }
|
|
47
62
|
let cmdline;
|
|
48
|
-
try { cmdline =
|
|
63
|
+
try { cmdline = proc.cmdline(pid); } catch (e) {
|
|
49
64
|
return e?.code === 'ENOENT' && process.platform === 'linux' && hasProc() ? false : null; // died between the two calls vs no /proc
|
|
50
65
|
}
|
|
51
|
-
if (cmdline === '')
|
|
66
|
+
if (cmdline === '') {
|
|
67
|
+
// A zombie reads empty, but so does a LIVE child for a few ms after its exec (seen under load: state R, starttime equal, cmdline
|
|
68
|
+
// empty), which used to read as dead and showed a fresh draft as "stopped". Only a state of Z/X is dead; otherwise we cannot tell yet.
|
|
69
|
+
// A task that is exiting also reads empty (and R/D) for an instant, but it has already let go of its memory: vsize 0. That is dead, not "cannot tell".
|
|
70
|
+
let state = null;
|
|
71
|
+
let vsize = 0;
|
|
72
|
+
try { const st = proc.stat(pid); state = stateFromStat(st); vsize = vsizeFromStat(st); } catch { /* gone between the reads */ }
|
|
73
|
+
return state === 'Z' || state === 'X' || state === null || !(vsize > 0) ? false : null;
|
|
74
|
+
}
|
|
52
75
|
const [argv0, ...rest] = cmdline.split('\0');
|
|
53
76
|
let isFwdloop;
|
|
54
77
|
if (basename(argv0) === NAME) isFwdloop = true; // direct exec of a renamed/compiled bin
|
|
@@ -60,7 +83,8 @@ export function isFwdloopAlive(pid, procStart) {
|
|
|
60
83
|
}
|
|
61
84
|
if (!isFwdloop) return false;
|
|
62
85
|
if (typeof procStart === 'string') {
|
|
63
|
-
|
|
86
|
+
let live = null;
|
|
87
|
+
try { live = startFromStat(proc.stat(pid)); } catch { /* unreadable */ }
|
|
64
88
|
if (live === null) return null; // cannot compare: never a silent true
|
|
65
89
|
if (live !== procStart) return false; // a different fwdloop process reusing the pid
|
|
66
90
|
}
|
package/src/panel/author.js
CHANGED
|
@@ -45,7 +45,7 @@ import {
|
|
|
45
45
|
checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
|
|
46
46
|
} from '../monthly.js';
|
|
47
47
|
import {
|
|
48
|
-
appendAnswersToJob,
|
|
48
|
+
appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
|
|
49
49
|
} from './authorcard.js';
|
|
50
50
|
import { checkedLines, notCheckedBlock } from '../checked.js';
|
|
51
51
|
import {
|
|
@@ -53,7 +53,11 @@ import {
|
|
|
53
53
|
} from '../provider.js';
|
|
54
54
|
import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
|
|
55
55
|
import { parseSignedText } from '../signed-text.js';
|
|
56
|
-
import { draftStepList } from '../draft-steps.js';
|
|
56
|
+
import { draftStepList, reviseStepList } from '../draft-steps.js';
|
|
57
|
+
import {
|
|
58
|
+
capTooSmallText, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, usdText,
|
|
59
|
+
} from '../draftspend.js';
|
|
60
|
+
import { flowValues, valuesHash } from '../runvalues.js';
|
|
57
61
|
import { leastResumeCapUsd } from './authorvalues.js';
|
|
58
62
|
import { createFlowsDoor } from './authorflows.js';
|
|
59
63
|
import { createResumeDoor } from './authorresume.js';
|
|
@@ -66,7 +70,6 @@ const HERE = dirname(fileURLToPath(import.meta.url));
|
|
|
66
70
|
const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
|
|
67
71
|
|
|
68
72
|
/** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
|
|
69
|
-
const STARTED_OVER_FILE = 'started-over-from.json';
|
|
70
73
|
const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
|
|
71
74
|
const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
|
|
72
75
|
/** The phases that end a card's life: Abandon or a sign. Everything else is still on the card (to read, to sign, to retry). */
|
|
@@ -161,14 +164,36 @@ export function createAuthor(opts) {
|
|
|
161
164
|
/**
|
|
162
165
|
* M4d am10: the Chat list of what this plan's draft really did, READ from its log.json and declaration (never from the readout, which is signed text),
|
|
163
166
|
* built by the ONE function `draftStepList`; every string scrubbed. `null` when the draft left no log (the page then lists what it always did).
|
|
164
|
-
*
|
|
167
|
+
* `questionOpen`: the plan asked a question and the draft has not ended (am15 item 3), so its plan-checks line is not red.
|
|
168
|
+
* @param {string} dir @param {string} rel @param {string[]} keys @param {boolean} [questionOpen]
|
|
165
169
|
*/
|
|
166
|
-
function stepListOf(dir, rel, keys) {
|
|
170
|
+
function stepListOf(dir, rel, keys, questionOpen = false) {
|
|
167
171
|
const declaration = readJson(dir, `${rel}/declaration.json`) ?? readJson(dir, `${rel}/declaration.rejected.json`);
|
|
168
|
-
const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration });
|
|
172
|
+
const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration, questionOpen });
|
|
169
173
|
if (list === null) return null;
|
|
170
174
|
const sc = (x) => scrub(String(x), keys);
|
|
171
|
-
return list.map((st) => ({ ...st, label: sc(st.label), details: st.details.map(sc)
|
|
175
|
+
return list.map((st) => ({ ...st, label: sc(st.label), details: st.details.map(sc) }));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** M4d am19: what ALL of this job's drafting already spent (the session folder and any Start-over chain behind it), unpriced rounds at their worst case. @param {string} dir @param {any} card */
|
|
179
|
+
function draftedSoFar(dir, card) {
|
|
180
|
+
return draftingSpent(dir, { ceilingUsd: capFloorFor(true, home, card) }).usd;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* M4d am16: the split of the card's Cap $ at Sign & run, from ALL of this job's drafting (the one writer of that total, `draftingSpent`). Unpriced rounds count at their
|
|
185
|
+
* worst case (the picked model's Settings ceiling). `refusal` = what is left cannot pay one run round at its worst case: refused at $0.
|
|
186
|
+
* @param {string} dir the draft folder @param {any} card
|
|
187
|
+
*/
|
|
188
|
+
function potOf(dir, card) {
|
|
189
|
+
const ceilingUsd = capFloorFor(true, home, card);
|
|
190
|
+
const spentRead = draftingSpent(dir, { ceilingUsd });
|
|
191
|
+
const split = potSplit(Number(card.capUsd), spentRead);
|
|
192
|
+
const floorUsd = capFloorUsd(typeof card.job === 'string' ? card.job : '', home, card);
|
|
193
|
+
const refusal = spentRead.missingEarlier ? EARLIER_MISSING_SAY : split.leftUsd < floorUsd
|
|
194
|
+
? `${split.line}: not enough for one run round at its worst case, ${usdText(floorUsd)}. Raise Cap $.`
|
|
195
|
+
: null;
|
|
196
|
+
return { split, refusal };
|
|
172
197
|
}
|
|
173
198
|
|
|
174
199
|
/**
|
|
@@ -210,17 +235,26 @@ export function createAuthor(opts) {
|
|
|
210
235
|
const revisesLeft = Math.max(0, MAX_REVISES - used);
|
|
211
236
|
const newest = ns.length > 0 ? ns[ns.length - 1] : 0;
|
|
212
237
|
const card = newest > 0 ? (readJson(dir, `card-${newest}.json`) ?? base.card) : base.card;
|
|
238
|
+
let reviseNo = 0;
|
|
213
239
|
const revises = ns.map((n) => {
|
|
214
240
|
const kind = redrafts.has(n) ? 'answers' : 'revise';
|
|
241
|
+
if (kind === 'revise') reviseNo += 1;
|
|
242
|
+
// M4d am15 (every line of the list): this plan's own line, from its own log, built by `reviseStepList`; the try history is in the Audit Draft group
|
|
243
|
+
const name = kind === 'answers' ? 'drafted again with your answers' : `revise ${reviseNo}`;
|
|
215
244
|
const running = n === newest && childRunning(dir); // C9: running first, then the result
|
|
245
|
+
// the result BEFORE the log: the child writes log.json first and the result (spec.hash, or the red log itself) after, so a result we see has its log already on disk
|
|
216
246
|
const res = resultOf(dir, `draft-${n}`, keys);
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
if (
|
|
220
|
-
return { n, kind, phase: '
|
|
247
|
+
const lines = reviseStepList({ log: readJson(dir, `draft-${n}/log.json`), name });
|
|
248
|
+
const scrubbed = lines === null ? null : lines.map((l) => ({ ...l, label: scrub(l.label, keys) }));
|
|
249
|
+
if (res && res.phase === 'green') return { n, kind, phase: 'green', hash: res.hash, name, lines: scrubbed };
|
|
250
|
+
if (res) return { n, kind, phase: 'red', reds: res.reds, say: kind === 'answers' ? REDRAFT_RED_SAY : REVISE_RED_SAY, name, lines: scrubbed };
|
|
251
|
+
if (running) return { n, kind, phase: 'running', name };
|
|
252
|
+
return { n, kind, name, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
|
|
221
253
|
});
|
|
222
254
|
const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
|
|
223
|
-
|
|
255
|
+
// a first plan that asked questions did not end red, it ended by asking (open or answered): its plan-checks line is never the red one (am15 item 3)
|
|
256
|
+
const asked = readQuestions(join(dir, 'draft')).questions.length > 0;
|
|
257
|
+
const shared = { ...base, card, revises, revisesLeft, stepList: asked ? stepListOf(dir, 'draft', keys, true) : (first.stepList ?? null) };
|
|
224
258
|
const rel = newest > 0 ? `draft-${newest}` : 'draft';
|
|
225
259
|
if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
|
|
226
260
|
if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
|
|
@@ -230,7 +264,7 @@ export function createAuthor(opts) {
|
|
|
230
264
|
if (q.open.length > 0) {
|
|
231
265
|
const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
|
|
232
266
|
const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null }));
|
|
233
|
-
return { ...shared, phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
|
|
267
|
+
return { ...shared, stepList: stepListOf(dir, rel, keys, true), phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
|
|
234
268
|
}
|
|
235
269
|
if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
|
|
236
270
|
if (res.phase === 'green') {
|
|
@@ -325,16 +359,17 @@ export function createAuthor(opts) {
|
|
|
325
359
|
/**
|
|
326
360
|
* The $0 checks both a first draft and a revise run on the card as submitted: the card's own checks (a key value, the flow name,
|
|
327
361
|
* every field), then the monthly room for its cap. `{ ok: true, card, prose }` or `{ ok: false, reply }`. Writes nothing.
|
|
328
|
-
*
|
|
362
|
+
* M4d am19 items 2-3: `priorUsd` = what this job's drafting already spent; the month is checked for what is LEFT of the cap, not the whole cap again.
|
|
363
|
+
* @param {any} body @param {{ ok: boolean, env: Record<string, string|undefined>, keyNames?: string[] }} loaded @param {number} [priorUsd]
|
|
329
364
|
* @returns {{ ok: true, card: any, prose: string }|{ ok: false, reply: { status: number, body: any } }}
|
|
330
365
|
*/
|
|
331
|
-
function vetCard(body, loaded) {
|
|
366
|
+
function vetCard(body, loaded, priorUsd = 0) {
|
|
332
367
|
const card = cardFields(body);
|
|
333
368
|
const checked = checkCard(card, { root: realpathSync(root), keys: providerKeys(loaded), home });
|
|
334
369
|
const modelSays = modelRefusal(card, loaded);
|
|
335
370
|
if (!checked.ok || modelSays.length > 0) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [...(checked.ok ? [] : checked.refusals), ...modelSays] } } };
|
|
336
371
|
// amendment 4 item 1: a cap that does not fit this month refuses here too, at $0, with the one refusal text (the page's red note is only a courtesy)
|
|
337
|
-
const claim = monthlyClaim(Number(card.capUsd));
|
|
372
|
+
const claim = monthlyClaim(Math.max(0, Number(card.capUsd) - priorUsd));
|
|
338
373
|
if (claim && 'problem' in claim) return { ok: false, reply: { status: 409, body: { ok: false, refused: 'monthly', say: `${claim.problem} — refusing rather than guess the monthly limit. Nothing spent.` } } };
|
|
339
374
|
if (claim && !claim.ok) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [{ field: 'capUsd', say: monthlyRefusalText(claim.room) }] } } };
|
|
340
375
|
return { ok: true, card, prose: checked.prose };
|
|
@@ -352,24 +387,31 @@ export function createAuthor(opts) {
|
|
|
352
387
|
/**
|
|
353
388
|
* `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
|
|
354
389
|
* the cap does not fit this month); `floorUsd` is the smallest cap that funds one round of a model step, for the page's
|
|
355
|
-
*
|
|
356
|
-
* @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Resume) the flow whose recorded model it is: its own prices are the floor (M4d am6)
|
|
390
|
+
* floor line (am20: `Cap $X is below one drafting|run round's worst case for <model>, $Y. …`, `kind` picks the word). A cap that is not a number above 0 gets no note. Never spends, never writes.
|
|
391
|
+
* @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Run / Resume) the flow whose recorded model it @param {string} [kind] 'run' for Run a signed flow and Resume, else the Chat card's 'drafting' is: its own prices are the floor (M4d am6)
|
|
357
392
|
*/
|
|
358
|
-
monthlyCheck(cap, spent = null, pick = null) {
|
|
393
|
+
monthlyCheck(cap, spent = null, pick = null, kind = 'drafting', draftId = /** @type {string|null} */ (null)) {
|
|
359
394
|
const n = Number(cap);
|
|
360
|
-
// a Resume names its flow: the model recorded beside the signed job is the one whose prices are the floor
|
|
395
|
+
// a Resume / Run names its flow: the model recorded beside the signed job is the one whose prices are the floor
|
|
361
396
|
const recorded = pick?.flow !== undefined && checkFlowName(pick.flow).ok ? readModelRecord(join(root, pick.flow)) : null;
|
|
362
|
-
const
|
|
363
|
-
|
|
397
|
+
const floor = capFloorOf(true, home, recorded ?? pick);
|
|
398
|
+
const floorUsd = floor.usd;
|
|
399
|
+
// M4d am20: the sentence names the typed cap, so it is written here per cap (one writer, `capTooSmallText`); '' when the cap is not under the floor
|
|
400
|
+
const floorText = Number.isFinite(n) && n > 0 && n < floorUsd ? capTooSmallText(kind === 'run' ? 'run' : 'drafting', n, floorUsd, String(floor.model)) : '';
|
|
401
|
+
if (typeof cap !== 'string' || cap.trim() === '' || !Number.isFinite(n) || n <= 0) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText } };
|
|
364
402
|
// a Resume (amendment 4 item 1): only what the run still has to spend is held, so the note asks for `cap - spent`; a cap not above
|
|
365
403
|
// what is spent says so in the door's own words (red)
|
|
366
404
|
const spentUsd = typeof spent === 'string' && spent.trim() !== '' && Number.isFinite(Number(spent)) && Number(spent) > 0 ? Number(spent) : 0;
|
|
367
405
|
if (spentUsd > 0 && n <= spentUsd + 1e-9) {
|
|
368
|
-
return { status: 200, body: { ok: true, text: `The cap must be above what is already spent (at least $${leastResumeCapUsd(spentUsd, floorUsd).toFixed(2)}).`, red: true, floorUsd, floorText
|
|
406
|
+
return { status: 200, body: { ok: true, text: `The cap must be above what is already spent (at least $${leastResumeCapUsd(spentUsd, floorUsd).toFixed(2)}).`, red: true, floorUsd, floorText } };
|
|
369
407
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
408
|
+
// M4d am21 item 1: a card that belongs to a draft (a revise, or the Start over about to be made) is checked for the pot LEFT, as the doors do
|
|
409
|
+
const dd = draftsDir();
|
|
410
|
+
const priorDir = typeof draftId === 'string' && ID_RE.test(draftId) && dd !== null && listIds().includes(draftId) ? join(dd, draftId) : null;
|
|
411
|
+
const priorUsd = priorDir === null ? 0 : draftingSpent(priorDir, { ceilingUsd: floorUsd }).usd;
|
|
412
|
+
const claim = monthlyClaim(Math.max(0, n - spentUsd - priorUsd));
|
|
413
|
+
if (claim === null || 'problem' in claim) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText } };
|
|
414
|
+
return { status: 200, body: { ok: true, ...monthlyNote(claim), floorUsd, floorText } };
|
|
373
415
|
},
|
|
374
416
|
|
|
375
417
|
/**
|
|
@@ -405,7 +447,17 @@ export function createAuthor(opts) {
|
|
|
405
447
|
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
406
448
|
const dd = draftsDir();
|
|
407
449
|
if (dd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
|
|
408
|
-
|
|
450
|
+
// M4d am19 item 3 / am21 items 1-2: a Start over keeps the pot. The month is checked for the cap LEFT after the earlier session's drafting (the chain behind it too);
|
|
451
|
+
// an earlier draft that is gone is never counted as $0: refused here, at $0, in words
|
|
452
|
+
const startedFrom = body?.startedOverFrom;
|
|
453
|
+
let priorUsd = 0;
|
|
454
|
+
if (typeof startedFrom === 'string' && startedFrom !== '') {
|
|
455
|
+
if (!ID_RE.test(startedFrom) || !listIds().includes(startedFrom)) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
|
|
456
|
+
const spent = draftingSpent(join(dd, startedFrom), { ceilingUsd: capFloorFor(true, home, cardFields(body)) });
|
|
457
|
+
if (spent.missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
|
|
458
|
+
priorUsd = spent.usd;
|
|
459
|
+
}
|
|
460
|
+
const vet = vetCard(body, loaded, priorUsd);
|
|
409
461
|
if (!vet.ok) return vet.reply;
|
|
410
462
|
const { card } = vet;
|
|
411
463
|
for (const id of listIds()) {
|
|
@@ -448,10 +500,12 @@ export function createAuthor(opts) {
|
|
|
448
500
|
signPrepare(id) {
|
|
449
501
|
const seen = greenDraft(id);
|
|
450
502
|
if (!seen.ok) return seen.reply;
|
|
503
|
+
const pot = potOf(seen.dir, seen.v.card);
|
|
504
|
+
if (pot.refusal !== null) return { status: 400, body: { ok: false, refused: 'pot-empty', say: pot.refusal, split: pot.split } };
|
|
451
505
|
return {
|
|
452
506
|
status: 200,
|
|
453
507
|
body: {
|
|
454
|
-
ok: true, draftId: id, hash: seen.v.hash, flowName: seen.name, capUsd: seen.v.card.capUsd, readout: seen.v.readout, answers: seen.v.answers, checked: seen.v.checked, notChecked: seen.v.notChecked, runId: nextRunId(join(root, seen.name)),
|
|
508
|
+
ok: true, split: pot.split, draftId: id, hash: seen.v.hash, flowName: seen.name, capUsd: seen.v.card.capUsd, readout: seen.v.readout, answers: seen.v.answers, checked: seen.v.checked, notChecked: seen.v.notChecked, runId: nextRunId(join(root, seen.name)),
|
|
455
509
|
},
|
|
456
510
|
};
|
|
457
511
|
},
|
|
@@ -471,8 +525,10 @@ export function createAuthor(opts) {
|
|
|
471
525
|
const { v, name, dir } = seen;
|
|
472
526
|
const b = body && typeof body === 'object' ? body : {};
|
|
473
527
|
// amendment 4 item 2: a cap that cannot fund one round of the first model step is never signed (it would cap-halt at $0 spent)
|
|
474
|
-
const floor =
|
|
475
|
-
if (Number(v.card.capUsd) < floor) return { status: 400, body: { ok: false, refused: 'cap-too-small', say:
|
|
528
|
+
const floor = capFloorOf(parseJobBox(typeof v.card.job === 'string' ? v.card.job : '').steps.some((s) => s.ask === null), home, v.card);
|
|
529
|
+
if (Number(v.card.capUsd) < floor.usd) return { status: 400, body: { ok: false, refused: 'cap-too-small', say: capTooSmallText('drafting', Number(v.card.capUsd), floor.usd, String(floor.model)) } };
|
|
530
|
+
const pot = potOf(dir, v.card);
|
|
531
|
+
if (pot.refusal !== null) return { status: 400, body: { ok: false, refused: 'pot-empty', say: pot.refusal, split: pot.split } };
|
|
476
532
|
if (typeof b.hash !== 'string' || b.hash !== v.hash) {
|
|
477
533
|
return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'The plan on disk is not the one you were shown (its hash differs). Nothing was signed. Reload and read the plan again.' } };
|
|
478
534
|
}
|
|
@@ -503,8 +559,19 @@ export function createAuthor(opts) {
|
|
|
503
559
|
writeFileSync(join(dir, 'signed.json'), `${JSON.stringify({
|
|
504
560
|
at: new Date().toISOString(), signedBy, hash: v.hash, flow: name, runId: runId === '' ? null : runId,
|
|
505
561
|
})}\n`, { mode: 0o600 });
|
|
562
|
+
// M4d am16 item 1: the first run gets what is LEFT of the card's cap after drafting, as its own signed values (the flow stays signed at the card's cap, and
|
|
563
|
+
// every later run that does not draft gets the whole of it). Nothing spent on drafting = no values file = the whole cap.
|
|
564
|
+
let values = null;
|
|
565
|
+
if (pot.split.spentUsd > 0) {
|
|
566
|
+
const prose = readFileInside(join(dir, v.plan), 'prose.txt');
|
|
567
|
+
const parsed = prose.ok ? parseSignedText(prose.text) : null;
|
|
568
|
+
if (parsed && parsed.ok) {
|
|
569
|
+
const vals = { ...flowValues(parsed.arbiter), capUsd: pot.split.leftUsd };
|
|
570
|
+
values = { flow: name, flowSignatureHash: result.signature.flow, version: 0, values: vals, hash: valuesHash({ flow: name, flowSignatureHash: result.signature.flow, runId: null, version: 0, values: vals }), signedBy, at: new Date().toISOString() };
|
|
571
|
+
}
|
|
572
|
+
}
|
|
506
573
|
const started = starter.start({
|
|
507
|
-
kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })),
|
|
574
|
+
kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })), values,
|
|
508
575
|
}, loaded);
|
|
509
576
|
if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, flow: name, say: `${started.body.say ?? 'The run did not start.'} The flow is signed; start it from "Run a signed flow".` } };
|
|
510
577
|
return { status: 202, body: { ...started.body, signed: true } };
|
|
@@ -535,7 +602,8 @@ export function createAuthor(opts) {
|
|
|
535
602
|
if (!Array.isArray(v.revises)) return { status: 409, body: { ok: false, refused: 'not-revisable', say: `This draft is ${v.phase}, so it cannot be revised. Draft again from the card.` } };
|
|
536
603
|
if (v.revisesLeft <= 0) return { status: 409, body: { ok: false, refused: 'no-revises-left', say: `This draft has used its ${MAX_REVISES} revises. Start over: it keeps the fields and gives ${MAX_REVISES} new revises.` } };
|
|
537
604
|
if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
|
|
538
|
-
|
|
605
|
+
if (draftingSpent(dir).missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
|
|
606
|
+
const vet = vetCard(body, loaded, draftedSoFar(dir, v.card));
|
|
539
607
|
if (!vet.ok) return vet.reply;
|
|
540
608
|
for (const other of listIds()) {
|
|
541
609
|
if (other === id) continue;
|
|
@@ -599,7 +667,7 @@ export function createAuthor(opts) {
|
|
|
599
667
|
const all = readQuestions(planDir).questions.map((x) => ({ line: x.line, question: x.question, answer: x.k === v.openK ? answer : x.answer }));
|
|
600
668
|
const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', /** @type {{line:number, answer:string}[]} */ (all));
|
|
601
669
|
if (grown.added !== all.length) return { status: 409, body: { ok: false, refused: 'no-such-line', say: 'An answer is about a job line the card no longer has. Draft again from the card. Nothing was signed.' } };
|
|
602
|
-
const vet = vetCard({ ...v.card, job: grown.job }, loaded);
|
|
670
|
+
const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
|
|
603
671
|
if (!vet.ok) return vet.reply;
|
|
604
672
|
for (const other of listIds()) {
|
|
605
673
|
if (other === id) continue;
|
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`. */
|
|
@@ -300,18 +301,18 @@ export function capFloorUsd(jobText, home, pick) {
|
|
|
300
301
|
|
|
301
302
|
/** 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
303
|
export function capFloorFor(hasRoundStep, home, pick) {
|
|
304
|
+
return capFloorOf(hasRoundStep, home, pick).usd;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** 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] */
|
|
308
|
+
export function capFloorOf(hasRoundStep, home, pick) {
|
|
303
309
|
const slot = pick?.slot ?? pick?.provider;
|
|
304
|
-
if (!hasRoundStep || !slot) return 0;
|
|
310
|
+
if (!hasRoundStep || !slot) return { usd: 0, model: null };
|
|
305
311
|
// No usable model (nothing picked or ticked, a broken config): nothing is held here, and the run itself is refused by name (`resolveUsableModel`).
|
|
306
312
|
try {
|
|
307
313
|
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`;
|
|
314
|
+
return u.ok ? { usd: ceilingCostUsd(u.rates), model: String(u.model) } : { usd: 0, model: null };
|
|
315
|
+
} catch { return { usd: 0, model: null }; }
|
|
315
316
|
}
|
|
316
317
|
|
|
317
318
|
/**
|
|
@@ -364,7 +365,10 @@ export function checkCard(card, { root, keys = [], home }) {
|
|
|
364
365
|
// cap
|
|
365
366
|
if (typeof card.capUsd === 'string' || typeof card.capUsd === 'number') {
|
|
366
367
|
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
|
|
368
|
+
else {
|
|
369
|
+
const floor = capFloorOf(parseJobBox(card.job).steps.some((s) => s.ask === null), home, card);
|
|
370
|
+
if (Number(card.capUsd) < floor.usd) no('capUsd', capTooSmallText('drafting', Number(card.capUsd), floor.usd, String(floor.model)));
|
|
371
|
+
}
|
|
368
372
|
} else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
|
|
369
373
|
|
|
370
374
|
// 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}[]} */
|