fwdloop 0.15.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 +113 -36
- package/package.json +2 -2
- package/src/authoring.js +27 -15
- package/src/catalogue.json +9 -3
- package/src/closers.js +5 -0
- package/src/config.js +66 -4
- package/src/ctx-tools.js +245 -0
- package/src/declaration.js +25 -1
- package/src/draft-steps.js +138 -0
- package/src/drafter.js +81 -18
- package/src/draftspend.js +109 -3
- package/src/flowmodel.js +30 -0
- package/src/input-facts.js +12 -3
- package/src/keysfile.js +51 -16
- package/src/liveness.js +34 -10
- package/src/model-step.js +13 -11
- package/src/monthly.js +9 -1
- package/src/panel/author.js +170 -43
- package/src/panel/authorcard.js +32 -20
- package/src/panel/authorflows.js +34 -19
- package/src/panel/authorresume.js +11 -9
- package/src/panel/authorstart.js +11 -9
- package/src/panel/authorvalues.js +5 -3
- package/src/panel/data.js +20 -8
- package/src/panel/index.html +584 -182
- package/src/panel/resume.js +3 -3
- package/src/panel/server.js +12 -6
- package/src/panel/settings.js +138 -80
- package/src/panel/spawn.js +15 -9
- package/src/plain-checks.js +51 -0
- package/src/primitives.js +34 -3
- package/src/provider.js +148 -181
- package/src/providershapes.js +7 -7
- package/src/run-store.js +47 -0
- package/src/runner.js +40 -22
- package/src/setup.js +3 -0
- package/src/thinking.js +55 -0
- package/src/version.js +13 -0
- package/types/authoring.d.ts +11 -6
- package/types/closers.d.ts +2 -0
- package/types/config.d.ts +9 -1
- package/types/ctx-tools.d.ts +18 -0
- package/types/draft-steps.d.ts +47 -0
- package/types/drafter.d.ts +15 -12
- package/types/draftspend.d.ts +56 -0
- package/types/flowmodel.d.ts +16 -0
- package/types/input-facts.d.ts +6 -1
- package/types/keysfile.d.ts +23 -6
- package/types/liveness.d.ts +7 -1
- package/types/model-step.d.ts +1 -1
- package/types/monthly.d.ts +1 -0
- package/types/panel/author.d.ts +47 -9
- package/types/panel/authorcard.d.ts +33 -10
- package/types/panel/authorflows.d.ts +32 -9
- package/types/panel/authorresume.d.ts +2 -1
- package/types/panel/authorstart.d.ts +16 -6
- package/types/panel/authorvalues.d.ts +3 -1
- package/types/panel/data.d.ts +2 -2
- package/types/panel/resume.d.ts +2 -1
- package/types/panel/server.d.ts +6 -2
- package/types/panel/settings.d.ts +3 -1
- package/types/panel/spawn.d.ts +13 -4
- package/types/plain-checks.d.ts +22 -0
- package/types/primitives.d.ts +0 -6
- package/types/provider.d.ts +100 -284
- package/types/providershapes.d.ts +3 -4
- package/types/run-store.d.ts +11 -0
- package/types/runner.d.ts +2 -4
- package/types/setup.d.ts +8 -0
- package/types/thinking.d.ts +25 -0
- package/types/version.d.ts +2 -0
package/src/model-step.js
CHANGED
|
@@ -29,15 +29,20 @@ import { GateRefusal } from './primitives.js';
|
|
|
29
29
|
import { ConfigError } from './config.js';
|
|
30
30
|
|
|
31
31
|
import {
|
|
32
|
-
makeProvider, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
|
|
32
|
+
makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
|
|
33
33
|
} from './provider.js';
|
|
34
34
|
|
|
35
|
-
// F27:
|
|
35
|
+
// F27: a provider's `chat/completions` can send HTTP 200 + headers + one byte
|
|
36
36
|
// then nothing — a "zombie stream" that `timeoutMs`'s idle bound never
|
|
37
37
|
// trips on. `deadlineMs` is bare-agent's TOTAL wall-clock ceiling
|
|
38
38
|
// (`code: 'EDEADLINE'`, `retryable: false`) — deliberately shorter than
|
|
39
39
|
// `timeoutMs` so a hung request reds well inside the idle bound. Frozen +
|
|
40
40
|
// exported so a test can assert on the live call's actual config.
|
|
41
|
+
/** How much of a malformed tool call's raw arguments is logged/shown (bare-agent hands over all of it). */
|
|
42
|
+
const RAW_ARGS_BOUND = 2000;
|
|
43
|
+
/** The raw text cut at `RAW_ARGS_BOUND` chars with the cut said out loud, never silently. @param {string} raw */
|
|
44
|
+
const boundRaw = (raw) => (raw.length > RAW_ARGS_BOUND ? `${raw.slice(0, RAW_ARGS_BOUND)}… (${raw.length - RAW_ARGS_BOUND} more chars)` : raw);
|
|
45
|
+
|
|
41
46
|
export const LIVE_PROVIDER_OPTIONS = Object.freeze({ timeoutMs: 300_000, deadlineMs: 240_000 });
|
|
42
47
|
|
|
43
48
|
const TRANSPORT_CODES = Object.freeze([
|
|
@@ -236,7 +241,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
|
|
|
236
241
|
|
|
237
242
|
/**
|
|
238
243
|
* @param {object} opts
|
|
239
|
-
* @param {string} [opts.slot] - a
|
|
244
|
+
* @param {string} [opts.slot] - a provider row (the name of a key in the keys file); required when `provider` isn't injected.
|
|
240
245
|
* @param {string} [opts.model] - overrides the slot's default model.
|
|
241
246
|
* @param {string} opts.spendPath - the run's spend.jsonl (never a second ledger).
|
|
242
247
|
* @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
|
|
@@ -260,7 +265,7 @@ export function makeLiveModelStep({
|
|
|
260
265
|
let prices = null;
|
|
261
266
|
if (live) {
|
|
262
267
|
// makeProvider throws synchronously on a missing/bad key, an unknown
|
|
263
|
-
// slot, or
|
|
268
|
+
// slot, or a model that is not ticked in Settings with both prices — never let that escape as an unhandled
|
|
264
269
|
// rejection out of the ralph loop; a step's own model failure is
|
|
265
270
|
// always a red, never a crash (rule 5).
|
|
266
271
|
try {
|
|
@@ -275,7 +280,7 @@ export function makeLiveModelStep({
|
|
|
275
280
|
// a call that never happened). A row that names a model must carry its
|
|
276
281
|
// tokens (appendAudit refuses it otherwise), so the model is not named.
|
|
277
282
|
return {
|
|
278
|
-
ok: false, red: `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
|
|
283
|
+
ok: false, red: err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
|
|
279
284
|
};
|
|
280
285
|
}
|
|
281
286
|
}
|
|
@@ -451,12 +456,9 @@ export function makeLiveModelStep({
|
|
|
451
456
|
if (noToolCallStreak >= 2) {
|
|
452
457
|
const malformed = provider?.lastMalformedToolCall ?? null;
|
|
453
458
|
if (malformed) {
|
|
454
|
-
// bare-agent >=0.
|
|
455
|
-
//
|
|
456
|
-
|
|
457
|
-
const rawSuffix = malformed.rawArguments !== undefined
|
|
458
|
-
? `; raw: ${malformed.rawArguments}${malformed.rawTruncated === true ? ' (truncated)' : ''}`
|
|
459
|
-
: '';
|
|
459
|
+
// bare-agent >=0.50 delivers the FULL `rawArguments` (verbatim, uncapped; `rawTruncated` is never set), and only when the provider was
|
|
460
|
+
// built with `exposeMalformedArgs: true`. We bound what is logged and shown, with the cut said out loud. Absent -> no "; raw:" suffix.
|
|
461
|
+
const rawSuffix = malformed.rawArguments !== undefined ? `; raw: ${boundRaw(malformed.rawArguments)}` : '';
|
|
460
462
|
return {
|
|
461
463
|
ok: false,
|
|
462
464
|
red: `the tool call's arguments were not valid JSON twice in a row (${malformed.error})${rawSuffix}`,
|
package/src/monthly.js
CHANGED
|
@@ -100,6 +100,7 @@ function reduceRow(row) {
|
|
|
100
100
|
t: tokensOf(row.tokens),
|
|
101
101
|
w: Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null,
|
|
102
102
|
p: typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED,
|
|
103
|
+
...(typeof row.model === 'string' && row.model !== '' ? { m: row.model } : {}),
|
|
103
104
|
...(row.at === undefined ? {} : { a: row.at }),
|
|
104
105
|
};
|
|
105
106
|
}
|
|
@@ -171,6 +172,8 @@ export function spendSummary(opts = {}) {
|
|
|
171
172
|
const month = newBucket();
|
|
172
173
|
/** @type {Record<string, {label: string, month: ReturnType<typeof newBucket>, total: ReturnType<typeof newBucket>}>} */
|
|
173
174
|
const byProvider = {};
|
|
175
|
+
/** Tokens per provider key per model, from the rows that name their model (a row that names none, or a rolled row from before this, counts in no model). @type {Record<string, Record<string, number>>} */
|
|
176
|
+
const byModel = {};
|
|
174
177
|
let undatedRows = 0;
|
|
175
178
|
const add = (b, usd, complete, tokens, wall) => {
|
|
176
179
|
b.rows += 1; b.usd += usd; b.tokens += tokens;
|
|
@@ -183,8 +186,12 @@ export function spendSummary(opts = {}) {
|
|
|
183
186
|
for (const dir of namedDirs(record)) {
|
|
184
187
|
for (const row of rolled.get(dir) ?? diskRows(dir)) {
|
|
185
188
|
const {
|
|
186
|
-
u: usd, c: complete, t: tokens, w: wall, p: key,
|
|
189
|
+
u: usd, c: complete, t: tokens, w: wall, p: key, m: model,
|
|
187
190
|
} = row;
|
|
191
|
+
if (model !== undefined) {
|
|
192
|
+
const per = (byModel[key] ??= {});
|
|
193
|
+
per[model] = (per[model] ?? 0) + tokens;
|
|
194
|
+
}
|
|
188
195
|
const p = (byProvider[key] ??= { label: key, month: newBucket(), total: newBucket() });
|
|
189
196
|
add(total, usd, complete, tokens, wall);
|
|
190
197
|
add(p.total, usd, complete, tokens, wall);
|
|
@@ -205,6 +212,7 @@ export function spendSummary(opts = {}) {
|
|
|
205
212
|
month: fin(month),
|
|
206
213
|
total: fin(total),
|
|
207
214
|
byProvider: Object.fromEntries(Object.entries(byProvider).map(([k, v]) => [k, { label: v.label, month: fin(v.month), total: fin(v.total) }])),
|
|
215
|
+
byModel,
|
|
208
216
|
undatedRows,
|
|
209
217
|
// Runs from before M4d were never written to runs.jsonl: their money is in no figure here.
|
|
210
218
|
preM4dRunsNotCounted: true,
|
package/src/panel/author.js
CHANGED
|
@@ -38,16 +38,26 @@ import { fileURLToPath } from 'node:url';
|
|
|
38
38
|
import {
|
|
39
39
|
ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, readQuestions, readoutHeadIndexes, scrub, signDraft,
|
|
40
40
|
} from '../authoring.js';
|
|
41
|
-
import { nextRunId, readFileInside, readdirInside } from '../flow.js';
|
|
41
|
+
import { checkFlowName, nextRunId, readFileInside, readdirInside } from '../flow.js';
|
|
42
|
+
import { readModelRecord } from '../flowmodel.js';
|
|
42
43
|
import { isFwdloopAlive } from '../liveness.js';
|
|
43
44
|
import {
|
|
44
45
|
checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
|
|
45
46
|
} from '../monthly.js';
|
|
46
47
|
import {
|
|
47
|
-
appendAnswersToJob,
|
|
48
|
+
appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
|
|
48
49
|
} from './authorcard.js';
|
|
49
50
|
import { checkedLines, notCheckedBlock } from '../checked.js';
|
|
51
|
+
import {
|
|
52
|
+
readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
|
|
53
|
+
} from '../provider.js';
|
|
54
|
+
import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
|
|
50
55
|
import { parseSignedText } from '../signed-text.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';
|
|
51
61
|
import { leastResumeCapUsd } from './authorvalues.js';
|
|
52
62
|
import { createFlowsDoor } from './authorflows.js';
|
|
53
63
|
import { createResumeDoor } from './authorresume.js';
|
|
@@ -60,7 +70,6 @@ const HERE = dirname(fileURLToPath(import.meta.url));
|
|
|
60
70
|
const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
|
|
61
71
|
|
|
62
72
|
/** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
|
|
63
|
-
const STARTED_OVER_FILE = 'started-over-from.json';
|
|
64
73
|
const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
|
|
65
74
|
const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
|
|
66
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). */
|
|
@@ -84,23 +93,23 @@ const KILL_HARD_WAIT_MS = 2000;
|
|
|
84
93
|
const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
|
|
85
94
|
|
|
86
95
|
/**
|
|
87
|
-
* @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, childRunning?: (dir: string) => boolean }} opts
|
|
96
|
+
* @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, childRunning?: (dir: string) => boolean, thinkingSupport?: typeof bareagentThinkingSupport }} opts
|
|
88
97
|
* `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
|
|
89
98
|
* the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
|
|
90
99
|
*/
|
|
91
100
|
export function createAuthor(opts) {
|
|
92
101
|
const {
|
|
93
|
-
root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow,
|
|
102
|
+
root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow, thinkingSupport = bareagentThinkingSupport,
|
|
94
103
|
} = opts;
|
|
95
104
|
// the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
|
|
96
105
|
const starter = createStarter({ root, bin });
|
|
97
106
|
const flowsDoor = createFlowsDoor({
|
|
98
|
-
root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd),
|
|
107
|
+
root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd), modelRefusal: (card, loaded) => modelRefusal(card, loaded),
|
|
99
108
|
});
|
|
100
109
|
|
|
101
110
|
/** The ONE monthly check, defined below (a function declaration, so the doors above may take it now). */
|
|
102
111
|
const resumeDoor = createResumeDoor({
|
|
103
|
-
root, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
|
|
112
|
+
root, home, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
|
|
104
113
|
});
|
|
105
114
|
|
|
106
115
|
/** The drafts folder's real path, or null when the flows root does not exist. */
|
|
@@ -152,6 +161,41 @@ export function createAuthor(opts) {
|
|
|
152
161
|
return logText.ok ? scrub(logText.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
|
|
153
162
|
}
|
|
154
163
|
|
|
164
|
+
/**
|
|
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),
|
|
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).
|
|
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]
|
|
169
|
+
*/
|
|
170
|
+
function stepListOf(dir, rel, keys, questionOpen = false) {
|
|
171
|
+
const declaration = readJson(dir, `${rel}/declaration.json`) ?? readJson(dir, `${rel}/declaration.rejected.json`);
|
|
172
|
+
const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration, questionOpen });
|
|
173
|
+
if (list === null) return null;
|
|
174
|
+
const sc = (x) => scrub(String(x), keys);
|
|
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 };
|
|
197
|
+
}
|
|
198
|
+
|
|
155
199
|
/**
|
|
156
200
|
* One plan folder's result, READ from its files: green (spec.hash), red (a log that says not ok, or a leak marker), or null (no result yet).
|
|
157
201
|
* @param {string} dir the draft folder @param {string} rel `draft` or `draft-<n>` @param {string[]} keys
|
|
@@ -162,14 +206,14 @@ export function createAuthor(opts) {
|
|
|
162
206
|
if (hashFile.ok && hashFile.text.trim() !== '') {
|
|
163
207
|
const readout = readFileInside(dir, `${rel}/readout.txt`);
|
|
164
208
|
const text = readout.ok ? scrub(readout.text, keys) : '';
|
|
165
|
-
return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text) };
|
|
209
|
+
return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text), stepList: stepListOf(dir, rel, keys) };
|
|
166
210
|
}
|
|
167
211
|
const leak = readFileInside(dir, `${rel}/scrub-leak.red`);
|
|
168
212
|
const log = readJson(dir, `${rel}/log.json`);
|
|
169
213
|
if (leak.ok || (log && log.ok === false)) {
|
|
170
214
|
const reds = Array.isArray(log?.reds) ? log.reds.map((r) => scrub(String(r), keys)) : [];
|
|
171
215
|
if (leak.ok) reds.push(scrub(leak.text.trim(), keys));
|
|
172
|
-
return { phase: 'red', reds, say: RED_SAY };
|
|
216
|
+
return { phase: 'red', reds, say: RED_SAY, stepList: stepListOf(dir, rel, keys) };
|
|
173
217
|
}
|
|
174
218
|
return null;
|
|
175
219
|
}
|
|
@@ -191,17 +235,26 @@ export function createAuthor(opts) {
|
|
|
191
235
|
const revisesLeft = Math.max(0, MAX_REVISES - used);
|
|
192
236
|
const newest = ns.length > 0 ? ns[ns.length - 1] : 0;
|
|
193
237
|
const card = newest > 0 ? (readJson(dir, `card-${newest}.json`) ?? base.card) : base.card;
|
|
238
|
+
let reviseNo = 0;
|
|
194
239
|
const revises = ns.map((n) => {
|
|
195
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}`;
|
|
196
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
|
|
197
246
|
const res = resultOf(dir, `draft-${n}`, keys);
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (
|
|
201
|
-
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 };
|
|
202
253
|
});
|
|
203
254
|
const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
|
|
204
|
-
|
|
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) };
|
|
205
258
|
const rel = newest > 0 ? `draft-${newest}` : 'draft';
|
|
206
259
|
if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
|
|
207
260
|
if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
|
|
@@ -211,7 +264,7 @@ export function createAuthor(opts) {
|
|
|
211
264
|
if (q.open.length > 0) {
|
|
212
265
|
const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
|
|
213
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 }));
|
|
214
|
-
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 };
|
|
215
268
|
}
|
|
216
269
|
if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
|
|
217
270
|
if (res.phase === 'green') {
|
|
@@ -257,7 +310,7 @@ export function createAuthor(opts) {
|
|
|
257
310
|
/** The one request-time read of the keys door: the merged env (scrub list + child env) or null on its refusal. */
|
|
258
311
|
const keysNow = () => {
|
|
259
312
|
const loaded = loadEnv();
|
|
260
|
-
return { loaded, keys: providerKeys(loaded
|
|
313
|
+
return { loaded, keys: providerKeys(loaded) };
|
|
261
314
|
};
|
|
262
315
|
|
|
263
316
|
/**
|
|
@@ -282,18 +335,41 @@ export function createAuthor(opts) {
|
|
|
282
335
|
};
|
|
283
336
|
}
|
|
284
337
|
|
|
338
|
+
/**
|
|
339
|
+
* M4d amendment 6 item 6: the model the card picked must still be a ticked, priced line of a provider that has its key set up; nothing ticked says
|
|
340
|
+
* what to do. `[]` = fine. Reads Settings now, at the click: a line unticked since Chat drew its menu is refused by name, at $0.
|
|
341
|
+
* @param {any} card @param {{ keyNames?: string[] }} loaded @returns {{ field: string, say: string }[]}
|
|
342
|
+
*/
|
|
343
|
+
function modelRefusal(card, loaded) {
|
|
344
|
+
const no = (say) => [{ field: 'model', say }];
|
|
345
|
+
let config;
|
|
346
|
+
try { config = readPriceConfig(home); } catch { return no('Your settings file (config.json) cannot be read. Fix or remove it, then look again. Nothing was spent.'); }
|
|
347
|
+
const rows = loaded.keyNames ?? [];
|
|
348
|
+
if (typeof card.provider !== 'string' || card.provider === '' || typeof card.model !== 'string' || card.model === '') {
|
|
349
|
+
return no(tickedLines(config, rows).length === 0 ? 'Tick a model in Settings > Providers. Nothing was spent.' : 'Pick a model. Nothing was spent.');
|
|
350
|
+
}
|
|
351
|
+
if (!rows.includes(card.provider)) return no(`${card.provider} is not set up: put its key in your keys file and type its Base URL in Settings > Providers. Nothing was spent.`);
|
|
352
|
+
const u = resolveUsableModel(card.provider, { config, model: card.model });
|
|
353
|
+
return u.ok ? [] : no(`${u.say} Nothing was spent.`);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The flags that make a draft child use the card's model and thinking choice. @param {any} card */
|
|
357
|
+
const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : [])];
|
|
358
|
+
|
|
285
359
|
/**
|
|
286
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,
|
|
287
361
|
* every field), then the monthly room for its cap. `{ ok: true, card, prose }` or `{ ok: false, reply }`. Writes nothing.
|
|
288
|
-
*
|
|
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]
|
|
289
364
|
* @returns {{ ok: true, card: any, prose: string }|{ ok: false, reply: { status: number, body: any } }}
|
|
290
365
|
*/
|
|
291
|
-
function vetCard(body, loaded) {
|
|
366
|
+
function vetCard(body, loaded, priorUsd = 0) {
|
|
292
367
|
const card = cardFields(body);
|
|
293
|
-
const checked = checkCard(card, { root: realpathSync(root),
|
|
294
|
-
|
|
368
|
+
const checked = checkCard(card, { root: realpathSync(root), keys: providerKeys(loaded), home });
|
|
369
|
+
const modelSays = modelRefusal(card, loaded);
|
|
370
|
+
if (!checked.ok || modelSays.length > 0) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [...(checked.ok ? [] : checked.refusals), ...modelSays] } } };
|
|
295
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)
|
|
296
|
-
const claim = monthlyClaim(Number(card.capUsd));
|
|
372
|
+
const claim = monthlyClaim(Math.max(0, Number(card.capUsd) - priorUsd));
|
|
297
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.` } } };
|
|
298
374
|
if (claim && !claim.ok) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [{ field: 'capUsd', say: monthlyRefusalText(claim.room) }] } } };
|
|
299
375
|
return { ok: true, card, prose: checked.prose };
|
|
@@ -311,22 +387,47 @@ export function createAuthor(opts) {
|
|
|
311
387
|
/**
|
|
312
388
|
* `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
|
|
313
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
|
|
314
|
-
*
|
|
315
|
-
* @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4)
|
|
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)
|
|
316
392
|
*/
|
|
317
|
-
monthlyCheck(cap, spent = null) {
|
|
393
|
+
monthlyCheck(cap, spent = null, pick = null, kind = 'drafting', draftId = /** @type {string|null} */ (null)) {
|
|
318
394
|
const n = Number(cap);
|
|
319
|
-
|
|
320
|
-
|
|
395
|
+
// a Resume / Run names its flow: the model recorded beside the signed job is the one whose prices are the floor
|
|
396
|
+
const recorded = pick?.flow !== undefined && checkFlowName(pick.flow).ok ? readModelRecord(join(root, pick.flow)) : null;
|
|
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 } };
|
|
321
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
|
|
322
403
|
// what is spent says so in the door's own words (red)
|
|
323
404
|
const spentUsd = typeof spent === 'string' && spent.trim() !== '' && Number.isFinite(Number(spent)) && Number(spent) > 0 ? Number(spent) : 0;
|
|
324
405
|
if (spentUsd > 0 && n <= spentUsd + 1e-9) {
|
|
325
|
-
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 } };
|
|
326
407
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
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 } };
|
|
415
|
+
},
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* `GET /api/author/models` (M4d amendment 6 item 6): what Chat's Model menu offers - every ticked, priced line of a provider whose key is set up, as
|
|
419
|
+
* "provider · model" - and, per line, whether "Thinking on" can change (`canChange`; bareagent's answer through `src/thinking.js`, am7). Read-only.
|
|
420
|
+
*/
|
|
421
|
+
models() {
|
|
422
|
+
const { loaded } = keysNow();
|
|
423
|
+
let config;
|
|
424
|
+
try { config = readPriceConfig(home); } catch { return { status: 200, body: { ok: true, lines: [], say: 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.' } }; }
|
|
425
|
+
const lines = tickedLines(config, loaded.keyNames ?? []).map((l) => {
|
|
426
|
+
const row = resolveSlot(l.slot, { config });
|
|
427
|
+
const support = thinkingSupport(row.shape, l.model, { baseUrl: row.baseUrl }); // the Base URL lets bareagent resolve the row by its host, as its request path does
|
|
428
|
+
return { ...l, thinking: { support, canChange: support !== false, say: support === false ? THINKING_FIXED_SAY : (support === 'unverified' ? THINKING_UNVERIFIED_SAY : '') } };
|
|
429
|
+
});
|
|
430
|
+
return { status: 200, body: { ok: true, lines, say: lines.length === 0 ? 'Tick a model in Settings > Providers.' : '' } };
|
|
330
431
|
},
|
|
331
432
|
|
|
332
433
|
/** `GET /api/author/start/:startId`: the start's phase, read from its files. @param {string} id */
|
|
@@ -346,7 +447,17 @@ export function createAuthor(opts) {
|
|
|
346
447
|
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
347
448
|
const dd = draftsDir();
|
|
348
449
|
if (dd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
|
|
349
|
-
|
|
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);
|
|
350
461
|
if (!vet.ok) return vet.reply;
|
|
351
462
|
const { card } = vet;
|
|
352
463
|
for (const id of listIds()) {
|
|
@@ -370,7 +481,7 @@ export function createAuthor(opts) {
|
|
|
370
481
|
let child;
|
|
371
482
|
try {
|
|
372
483
|
child = spawnDetached({
|
|
373
|
-
bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName], env: loaded.env, logPath: join(dir, 'child.log'),
|
|
484
|
+
bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...modelArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
|
|
374
485
|
});
|
|
375
486
|
} catch (e) {
|
|
376
487
|
return { status: 500, body: { ok: false, refused: 'spawn', say: `The draft could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
|
|
@@ -389,10 +500,12 @@ export function createAuthor(opts) {
|
|
|
389
500
|
signPrepare(id) {
|
|
390
501
|
const seen = greenDraft(id);
|
|
391
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 } };
|
|
392
505
|
return {
|
|
393
506
|
status: 200,
|
|
394
507
|
body: {
|
|
395
|
-
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)),
|
|
396
509
|
},
|
|
397
510
|
};
|
|
398
511
|
},
|
|
@@ -412,8 +525,10 @@ export function createAuthor(opts) {
|
|
|
412
525
|
const { v, name, dir } = seen;
|
|
413
526
|
const b = body && typeof body === 'object' ? body : {};
|
|
414
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)
|
|
415
|
-
const floor =
|
|
416
|
-
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 } };
|
|
417
532
|
if (typeof b.hash !== 'string' || b.hash !== v.hash) {
|
|
418
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.' } };
|
|
419
534
|
}
|
|
@@ -435,18 +550,29 @@ export function createAuthor(opts) {
|
|
|
435
550
|
const editBlock = editOf !== null ? flowsDoor.editBlock(name) : null;
|
|
436
551
|
if (editBlock !== null) return { status: 409, body: { ok: false, refused: 'run-live', say: editBlock } };
|
|
437
552
|
const result = signDraft({
|
|
438
|
-
dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir, replaces: editOf !== null ? { flowHash: String(editOf.flowHash) } : undefined,
|
|
553
|
+
dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, keyNames: loaded.keyNames, sessionDir: dir, replaces: editOf !== null ? { flowHash: String(editOf.flowHash) } : undefined,
|
|
439
554
|
});
|
|
440
555
|
if (!result.ok) {
|
|
441
|
-
const keys = providerKeys(loaded
|
|
556
|
+
const keys = providerKeys(loaded);
|
|
442
557
|
return { status: 409, body: { ok: false, refused: 'sign-refused', say: 'The draft did not pass the signing checks. Nothing was signed.', reds: result.reds.map((r) => scrub(String(r), keys)) } };
|
|
443
558
|
}
|
|
444
559
|
writeFileSync(join(dir, 'signed.json'), `${JSON.stringify({
|
|
445
560
|
at: new Date().toISOString(), signedBy, hash: v.hash, flow: name, runId: runId === '' ? null : runId,
|
|
446
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
|
+
}
|
|
447
573
|
const started = starter.start({
|
|
448
|
-
kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })),
|
|
449
|
-
}, loaded
|
|
574
|
+
kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })), values,
|
|
575
|
+
}, loaded);
|
|
450
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".` } };
|
|
451
577
|
return { status: 202, body: { ...started.body, signed: true } };
|
|
452
578
|
},
|
|
@@ -476,7 +602,8 @@ export function createAuthor(opts) {
|
|
|
476
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.` } };
|
|
477
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.` } };
|
|
478
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.' } };
|
|
479
|
-
|
|
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));
|
|
480
607
|
if (!vet.ok) return vet.reply;
|
|
481
608
|
for (const other of listIds()) {
|
|
482
609
|
if (other === id) continue;
|
|
@@ -493,7 +620,7 @@ export function createAuthor(opts) {
|
|
|
493
620
|
try {
|
|
494
621
|
child = spawnDetached({
|
|
495
622
|
bin,
|
|
496
|
-
argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName],
|
|
623
|
+
argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName, ...modelArgv(vet.card)],
|
|
497
624
|
env: loaded.env,
|
|
498
625
|
logPath: join(dir, `revise-${n}.log`),
|
|
499
626
|
});
|
|
@@ -540,7 +667,7 @@ export function createAuthor(opts) {
|
|
|
540
667
|
const all = readQuestions(planDir).questions.map((x) => ({ line: x.line, question: x.question, answer: x.k === v.openK ? answer : x.answer }));
|
|
541
668
|
const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', /** @type {{line:number, answer:string}[]} */ (all));
|
|
542
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.' } };
|
|
543
|
-
const vet = vetCard({ ...v.card, job: grown.job }, loaded);
|
|
670
|
+
const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
|
|
544
671
|
if (!vet.ok) return vet.reply;
|
|
545
672
|
for (const other of listIds()) {
|
|
546
673
|
if (other === id) continue;
|
|
@@ -565,7 +692,7 @@ export function createAuthor(opts) {
|
|
|
565
692
|
writeFileSync(files[2], `${JSON.stringify({ fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })) })}\n`, { mode: 0o600, flag: 'wx' });
|
|
566
693
|
child = spawnDetached({
|
|
567
694
|
bin,
|
|
568
|
-
argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions'],
|
|
695
|
+
argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions', ...modelArgv(redraft.vet.card)],
|
|
569
696
|
env: loaded.env,
|
|
570
697
|
logPath: join(dir, `redraft-${n}.log`),
|
|
571
698
|
});
|
package/src/panel/authorcard.js
CHANGED
|
@@ -15,9 +15,10 @@ import {
|
|
|
15
15
|
import { isAbsolute, join } from 'node:path';
|
|
16
16
|
|
|
17
17
|
import { checkFlowName, signedHashOf } from '../flow.js';
|
|
18
|
-
import { checkSendDestination
|
|
18
|
+
import { checkSendDestination } from '../runner.js';
|
|
19
19
|
import { parseSignedText } from '../signed-text.js';
|
|
20
|
-
import {
|
|
20
|
+
import { capTooSmallText } from '../draftspend.js';
|
|
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`. */
|
|
23
24
|
export const ARBITER_HEADING = 'Arbiter guardrails (belong to no line; human-signed, tighten-only — never authored or claimed by the drafter):';
|
|
@@ -170,6 +171,9 @@ export function cardFields(body) {
|
|
|
170
171
|
inputs: str(b.inputs).replace(/\r\n?/g, '\n'),
|
|
171
172
|
capUsd: typeof b.capUsd === 'string' && b.capUsd.trim() !== '' ? Number(b.capUsd) : b.capUsd,
|
|
172
173
|
askWait: str(b.askWait).trim(),
|
|
174
|
+
// M4d amendment 6: the picked model (a key name and a model id from Chat's menu) and the per-job "Thinking on" tick; present only when sent
|
|
175
|
+
...(str(b.provider).trim() !== '' || str(b.model).trim() !== '' ? { provider: str(b.provider).trim(), model: str(b.model).trim() } : {}),
|
|
176
|
+
...(b.thinking === true ? { thinking: true } : {}),
|
|
173
177
|
// M6: present only when this card EDITS a signed job: which job, and the signature hash it was opened at
|
|
174
178
|
...(typeof b.editOf?.flow === 'string' && typeof b.editOf?.flowHash === 'string' && b.editOf.flowHash !== '' ? { editOf: { flow: b.editOf.flow, flowHash: b.editOf.flowHash } } : {}),
|
|
175
179
|
};
|
|
@@ -286,22 +290,29 @@ export function checkInputRows(rows) {
|
|
|
286
290
|
/**
|
|
287
291
|
* M4e amendment 4 item 2: the smallest per-run cap that funds ONE round of the first model step. The runner halts a step when
|
|
288
292
|
* `spent + ceiling > cap` (`runStepRalph`), and every ordinary (non-ask) step is a model step, so the floor is the runner's own
|
|
289
|
-
* per-round
|
|
293
|
+
* per-round hold (the picked model's own Settings prices times the token bounds) as soon as the job has one such line; a job of only asks spends nothing before its stop.
|
|
290
294
|
* ONE function: the card's Draft check, Sign, and the page's note all read it. Returns 0 when no step needs a round.
|
|
291
|
-
* @param {string} jobText
|
|
295
|
+
* @param {string} jobText @param {string} [home] the config home the panel reads Settings from (default: the process door)
|
|
296
|
+
* @param {{ slot?: string, provider?: string, model?: string }|null} [pick] the job's picked model (M4d amendment 6): its own Settings prices are the hold (a card names its key as `provider`)
|
|
292
297
|
*/
|
|
293
|
-
export function capFloorUsd(jobText) {
|
|
294
|
-
return capFloorFor(parseJobBox(jobText).steps.some((s) => s.ask === null));
|
|
298
|
+
export function capFloorUsd(jobText, home, pick) {
|
|
299
|
+
return capFloorFor(parseJobBox(jobText).steps.some((s) => s.ask === null), home, pick);
|
|
295
300
|
}
|
|
296
301
|
|
|
297
|
-
/** 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 */
|
|
298
|
-
export function capFloorFor(hasRoundStep) {
|
|
299
|
-
return hasRoundStep
|
|
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] */
|
|
303
|
+
export function capFloorFor(hasRoundStep, home, pick) {
|
|
304
|
+
return capFloorOf(hasRoundStep, home, pick).usd;
|
|
300
305
|
}
|
|
301
306
|
|
|
302
|
-
/** The
|
|
303
|
-
export function
|
|
304
|
-
|
|
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) {
|
|
309
|
+
const slot = pick?.slot ?? pick?.provider;
|
|
310
|
+
if (!hasRoundStep || !slot) return { usd: 0, model: null };
|
|
311
|
+
// No usable model (nothing picked or ticked, a broken config): nothing is held here, and the run itself is refused by name (`resolveUsableModel`).
|
|
312
|
+
try {
|
|
313
|
+
const u = resolveUsableModel(slot, { config: readPriceConfig(home), model: pick?.model });
|
|
314
|
+
return u.ok ? { usd: ceilingCostUsd(u.rates), model: String(u.model) } : { usd: 0, model: null };
|
|
315
|
+
} catch { return { usd: 0, model: null }; }
|
|
305
316
|
}
|
|
306
317
|
|
|
307
318
|
/**
|
|
@@ -320,10 +331,10 @@ export function destinationRefusal(dest, root) {
|
|
|
320
331
|
/**
|
|
321
332
|
* Every $0 check on the card, before any spawn (scope 6). Collects all refusals so the page can name every box.
|
|
322
333
|
* @param {ReturnType<typeof cardFields>} card
|
|
323
|
-
* @param {{ root: string,
|
|
334
|
+
* @param {{ root: string, keys?: string[], home?: string }} ctx `keys` = the provider key values (the keys load's scrub list): a key value typed into any box is refused; `home` = the config home Settings is read from (the cap floor)
|
|
324
335
|
* @returns {{ ok: true, prose: string }|{ ok: false, refusals: {field: string, say: string}[] }}
|
|
325
336
|
*/
|
|
326
|
-
export function checkCard(card, { root,
|
|
337
|
+
export function checkCard(card, { root, keys = [], home }) {
|
|
327
338
|
/** @type {{field: string, say: string}[]} */
|
|
328
339
|
const refusals = [];
|
|
329
340
|
const no = (field, say) => refusals.push({ field, say });
|
|
@@ -354,7 +365,10 @@ export function checkCard(card, { root, env = {} }) {
|
|
|
354
365
|
// cap
|
|
355
366
|
if (typeof card.capUsd === 'string' || typeof card.capUsd === 'number') {
|
|
356
367
|
if (!(Number.isFinite(Number(card.capUsd)) && Number(card.capUsd) > 0)) no('capUsd', 'The cap must be a number above 0 (dollars per run).');
|
|
357
|
-
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
|
+
}
|
|
358
372
|
} else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
|
|
359
373
|
|
|
360
374
|
// destination: one folder, or empty for no send (it is sent at the last step)
|
|
@@ -368,12 +382,10 @@ export function checkCard(card, { root, env = {} }) {
|
|
|
368
382
|
refusals.push(...checkInputRows(parseInputLines(card.inputs)));
|
|
369
383
|
|
|
370
384
|
// a provider key typed into any box never reaches a file
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
for (const p of Object.values(PROVIDER_SLOTS)) { const k = env[p.envVar]; if (typeof k === 'string' && k.length >= 8) keys.push(k); }
|
|
374
|
-
if (keys.length > 0) {
|
|
385
|
+
const longKeys = keys.filter((k) => k.length >= 8);
|
|
386
|
+
if (longKeys.length > 0) {
|
|
375
387
|
const boxes = [['job', card.job], ['flowName', card.flowName], ['destination', dest], ['inputs', card.inputs]];
|
|
376
|
-
for (const [field, text] of boxes) if (
|
|
388
|
+
for (const [field, text] of boxes) if (longKeys.some((k) => String(text).includes(k))) no(String(field), 'This box contains an API key. Keys go in Settings only. Nothing was saved.');
|
|
377
389
|
}
|
|
378
390
|
|
|
379
391
|
if (refusals.length > 0) return { ok: false, refusals };
|