fwdloop 0.20.0 → 0.22.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 +85 -34
- package/package.json +4 -3
- package/src/audit-fold.js +181 -0
- package/src/authoring.js +33 -7
- package/src/books.js +1 -1
- package/src/checked.js +18 -1
- package/src/cited-record.js +138 -0
- package/src/cited-source.js +49 -0
- package/src/citedcheck.js +306 -0
- package/src/citedwords.js +197 -0
- package/src/closers.js +105 -9
- package/src/ctx-tools.js +2 -14
- package/src/declaration.js +85 -5
- package/src/diary.js +49 -0
- package/src/docx.js +16 -2
- package/src/draft-steps.js +1 -1
- package/src/drafter.js +292 -25
- package/src/flow.js +33 -7
- package/src/flowmodel.js +63 -5
- package/src/input-facts.js +20 -3
- package/src/model-step.js +132 -9
- package/src/pageask.js +136 -0
- package/src/pagebits.js +107 -0
- package/src/pagedropwords.js +171 -0
- package/src/pagedry.js +120 -0
- package/src/pagefetch.js +164 -0
- package/src/pagelook.js +155 -0
- package/src/pagemap.js +55 -0
- package/src/pageplace.js +103 -0
- package/src/pagerules.js +318 -0
- package/src/panel/author.js +41 -20
- package/src/panel/authorcard.js +11 -1
- package/src/panel/authorflows.js +21 -15
- package/src/panel/authorstart.js +2 -4
- package/src/panel/authortrigger.js +14 -4
- package/src/panel/data.js +130 -10
- package/src/panel/index.html +499 -41
- package/src/panel/result.js +295 -0
- package/src/panel/server.js +27 -3
- package/src/primitives.js +43 -2
- package/src/provider.js +5 -2
- package/src/redact.js +17 -0
- package/src/runner.js +128 -21
- package/src/schedule.js +3 -3
- package/src/setup.js +16 -1
- package/src/sheetfind.js +50 -0
- package/src/sheetlook.js +157 -0
- package/src/signed-text.js +11 -1
- package/src/thinking.js +39 -0
- package/src/try-checks.js +68 -0
- package/src/types.js +4 -2
- package/types/audit-fold.d.ts +54 -0
- package/types/authoring.d.ts +20 -2
- package/types/books.d.ts +17 -0
- package/types/checked.d.ts +10 -0
- package/types/cited-record.d.ts +21 -0
- package/types/cited-source.d.ts +18 -0
- package/types/citedcheck.d.ts +95 -0
- package/types/citedwords.d.ts +97 -0
- package/types/closers.d.ts +55 -3
- package/types/declaration.d.ts +15 -1
- package/types/diary.d.ts +57 -0
- package/types/docx.d.ts +14 -0
- package/types/drafter.d.ts +244 -2
- package/types/flow.d.ts +21 -0
- package/types/flowmodel.d.ts +40 -3
- package/types/input-facts.d.ts +12 -2
- package/types/model-step.d.ts +38 -3
- package/types/pageask.d.ts +75 -0
- package/types/pagebits.d.ts +32 -0
- package/types/pagedropwords.d.ts +40 -0
- package/types/pagedry.d.ts +38 -0
- package/types/pagefetch.d.ts +86 -0
- package/types/pagelook.d.ts +75 -0
- package/types/pagemap.d.ts +31 -0
- package/types/pageplace.d.ts +22 -0
- package/types/pagerules.d.ts +86 -0
- package/types/panel/authorcard.d.ts +2 -0
- package/types/panel/authorflows.d.ts +2 -0
- package/types/panel/data.d.ts +26 -0
- package/types/panel/result.d.ts +156 -0
- package/types/provider.d.ts +3 -1
- package/types/redact.d.ts +1 -0
- package/types/runner.d.ts +156 -7
- package/types/schedule.d.ts +0 -11
- package/types/setup.d.ts +13 -0
- package/types/sheetfind.d.ts +46 -0
- package/types/sheetlook.d.ts +120 -0
- package/types/thinking.d.ts +31 -0
- package/types/try-checks.d.ts +55 -0
- package/types/types.d.ts +20 -3
package/README.md
CHANGED
|
@@ -64,6 +64,8 @@ Work in progress. Nothing here is ready to install yet.
|
|
|
64
64
|
|
|
65
65
|
The in-run `impact` tool needs ripgrep (`rg`) on PATH; without it the tool is refused with a message, never a wrong answer.
|
|
66
66
|
|
|
67
|
+
The panel test `test/m11-am20.test.js` forces symbol fonts to prove the ◷ chip is sized by measurement, and fails on purpose when fewer than two of Symbola, FreeSans, Noto Sans Mono Condensed and Adwaita Mono are installed. On Debian/Ubuntu: `sudo apt-get install fonts-symbola fonts-freefont-ttf` (CI installs the same two).
|
|
68
|
+
|
|
67
69
|
## License
|
|
68
70
|
|
|
69
71
|
Apache-2.0. See `LICENSE` and `NOTICE`.
|
package/bin/fwdloop
CHANGED
|
@@ -37,7 +37,7 @@ import { resolvePrimitives } from '../src/primitives.js';
|
|
|
37
37
|
import {
|
|
38
38
|
checkKeyPreflight, resolveUsableModel, pickTicked, readPriceConfig, ceilingCostUsd,
|
|
39
39
|
} from '../src/provider.js';
|
|
40
|
-
import { readModelRecord } from '../src/flowmodel.js';
|
|
40
|
+
import { readModelRecord, readRunModel } from '../src/flowmodel.js';
|
|
41
41
|
import { configDoorHome } from '../src/config.js';
|
|
42
42
|
import {
|
|
43
43
|
claimHold, settleHold, nameRunDir, monthlyRefusalText, ConfigError,
|
|
@@ -50,8 +50,9 @@ import { panelMain } from '../src/panel/server.js';
|
|
|
50
50
|
import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
|
|
51
51
|
import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
|
|
52
52
|
import { userInfo } from 'node:os';
|
|
53
|
+
import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
|
|
53
54
|
|
|
54
|
-
// This CLI drives no fixed provider (M4d amendment 6). A job runs with the model recorded beside it (`model.json`, written when it was drafted:
|
|
55
|
+
// This CLI drives no fixed provider (M4d amendment 6). A job runs with the model recorded beside it as its DEFAULT (M4d am33: `run --model` picks any other ticked model for that run) (`model.json`, written when it was drafted:
|
|
55
56
|
// the provider is the name of a key, its key is read from the env under that name and never printed); `draft` takes `--model` (+ `--provider`).
|
|
56
57
|
// Whether that model may be used is `resolveUsableModel` (ticked in Settings > Providers with both prices): this file names no model and no price.
|
|
57
58
|
|
|
@@ -75,7 +76,9 @@ const keyedEnv = () => keyedLoad().env;
|
|
|
75
76
|
* that does not fit refuses at $0 with the one refusal text. A hold that fits is given back when this
|
|
76
77
|
* process ends or parks (the `exit` hook runs on every exit path; a SIGKILL leaves it for the next check,
|
|
77
78
|
* which settles it as "process gone").
|
|
78
|
-
*
|
|
79
|
+
* M4d am32: the draft door also gets `settle(why)`, called when the draft's result is written: the hold is given back then, not at exit. The exit hook calls the same
|
|
80
|
+
* function as a backstop; it settles once (a second call is a no-op), so a hold is never settled twice.
|
|
81
|
+
* @returns {{ addRunDir: (d: string) => void, nameRunDir: (d: string) => void, settle: (why: string) => void }}
|
|
79
82
|
*/
|
|
80
83
|
const NO_CONFIG_HOME_REFUSAL = 'NODE_ENV=test is set without FWDLOOP_CONFIG_HOME, so the keys file, prices and monthly limit would be skipped. Nothing spent. Unset NODE_ENV, or set FWDLOOP_CONFIG_HOME.';
|
|
81
84
|
|
|
@@ -90,7 +93,7 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
|
|
|
90
93
|
if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
|
|
91
94
|
fail(NO_CONFIG_HOME_REFUSAL);
|
|
92
95
|
}
|
|
93
|
-
return { addRunDir: () => {}, nameRunDir: () => {} };
|
|
96
|
+
return { addRunDir: () => {}, nameRunDir: () => {}, settle: () => {} };
|
|
94
97
|
}
|
|
95
98
|
let claim;
|
|
96
99
|
try {
|
|
@@ -102,12 +105,17 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
|
|
|
102
105
|
fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
|
|
103
106
|
}
|
|
104
107
|
if (!claim.ok) fail(monthlyRefusalText(claim.room));
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
108
|
+
let settled = false;
|
|
109
|
+
const settle = (why) => {
|
|
110
|
+
if (settled || claim.holdId === null) return;
|
|
111
|
+
settled = true;
|
|
112
|
+
settleHold({
|
|
113
|
+
holdId: claim.holdId, why, home, alsoRunDirs: also,
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
if (claim.holdId !== null) process.on('exit', () => settle(process.exitCode ? 'ended (red)' : 'ended or parked'));
|
|
110
117
|
return {
|
|
118
|
+
settle,
|
|
111
119
|
addRunDir: (d) => also.push(d),
|
|
112
120
|
// C2: a rerun's new run dir is named in the money record the moment it starts.
|
|
113
121
|
nameRunDir: (d) => { also.push(d); nameRunDir({ holdId: claim.holdId, runDir: d, home }); },
|
|
@@ -160,7 +168,24 @@ function today() {
|
|
|
160
168
|
* be hit by a user typing `--something`. This is how the test suite drives
|
|
161
169
|
* every CLI scenario at $0 with zero chance of a real network call.
|
|
162
170
|
*/
|
|
163
|
-
async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel = null) {
|
|
171
|
+
async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel = null, continuing = false) {
|
|
172
|
+
// M4d am33: the ONE decision of which model this run uses. `runModel` is the model the run already has (a continue: the one it started on; a start: the
|
|
173
|
+
// one it was signed with). `--model` picks any ticked model for a NEW run (the job's recorded model is only the default; model.json is never rewritten);
|
|
174
|
+
// a run that already has its model keeps it: naming another is refused by name, never silently swapped.
|
|
175
|
+
const decide = (config) => {
|
|
176
|
+
const rec = runModel ?? readModelRecord(flowDir); // M6 am5/am6 / M4d am33: the model of THIS run, else the one recorded with the job
|
|
177
|
+
if (runModel !== null && named.model !== undefined && (named.model !== runModel.model || (named.provider !== undefined && named.provider !== runModel.slot))) {
|
|
178
|
+
throw new Error(continuing
|
|
179
|
+
? `This run started on ${runModel.model}; a resume keeps it. Nothing spent.`
|
|
180
|
+
: `This run was signed with its model (${runModel.slot} · ${runModel.model}); --model cannot change it.`);
|
|
181
|
+
}
|
|
182
|
+
if (named.model !== undefined) {
|
|
183
|
+
const p = pickTicked(config, { model: named.model, provider: named.provider ?? (rec !== null && rec.model === named.model ? rec.slot : undefined) });
|
|
184
|
+
if (!p.ok) throw new Error(p.say);
|
|
185
|
+
return p;
|
|
186
|
+
}
|
|
187
|
+
return rec;
|
|
188
|
+
};
|
|
164
189
|
if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
|
|
165
190
|
const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
|
|
166
191
|
const mod = await import(pathToFileURL(modulePath).href);
|
|
@@ -171,33 +196,24 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel =
|
|
|
171
196
|
// is exercised the way a live run's is); with none, the double holds nothing. It is never refused here: it spends nothing.
|
|
172
197
|
const modelStep = await mod.default({ spendPath });
|
|
173
198
|
let usable = null;
|
|
199
|
+
let pick = null;
|
|
174
200
|
try {
|
|
175
|
-
|
|
176
|
-
usable =
|
|
201
|
+
pick = configDoorHome().skip ? null : decide(readPriceConfig());
|
|
202
|
+
usable = pick === null ? null : resolveUsableModel(pick.slot, { config: readPriceConfig(), model: pick.model });
|
|
177
203
|
} catch (err) {
|
|
178
204
|
if (!(err instanceof ConfigError)) throw err; // a broken config is refused by name at the monthly hold, right after this
|
|
179
205
|
}
|
|
180
|
-
return { modelStep, ...(usable?.ok ? { ceilingUsd: ceilingCostUsd(usable.rates) } : {}) };
|
|
206
|
+
return { modelStep, model: pick === null ? null : { slot: pick.slot, model: pick.model }, ...(usable?.ok ? { ceilingUsd: ceilingCostUsd(usable.rates) } : {}) };
|
|
181
207
|
}
|
|
182
208
|
// A test process with no config home reads no Settings: say why, not "tick a model".
|
|
183
209
|
if (configDoorHome().skip) throw new Error(NO_CONFIG_HOME_REFUSAL);
|
|
184
|
-
// The
|
|
185
|
-
// existed takes `--model`), refused by name, at $0, before a run dir or a book row exists. The per-round hold is that model's own Settings price times the token bounds.
|
|
210
|
+
// The per-round hold is that model's own Settings price times the token bounds; a refusal comes before a run dir or a book row exists.
|
|
186
211
|
let usable;
|
|
187
212
|
let slot;
|
|
188
213
|
try {
|
|
189
214
|
const config = readPriceConfig();
|
|
190
|
-
const
|
|
191
|
-
if (
|
|
192
|
-
throw new Error(`This job already has its model recorded (${rec.slot} · ${rec.model}); --model cannot change it.`);
|
|
193
|
-
}
|
|
194
|
-
let pick = rec;
|
|
195
|
-
if (pick === null) {
|
|
196
|
-
if (named.model === undefined) throw new Error('This job has no model recorded. Name one with --model <id>, a model ticked in Settings > Providers with both prices.');
|
|
197
|
-
const p = pickTicked(config, named);
|
|
198
|
-
if (!p.ok) throw new Error(p.say);
|
|
199
|
-
pick = p;
|
|
200
|
-
}
|
|
215
|
+
const pick = decide(config);
|
|
216
|
+
if (pick === null) throw new Error('This job has no model recorded. Name one with --model <id>, a model ticked in Settings > Providers with both prices.');
|
|
201
217
|
slot = pick.slot;
|
|
202
218
|
const keyCheck = checkKeyPreflight(slot, env);
|
|
203
219
|
if (!keyCheck.ok) throw new Error(keyCheck.message);
|
|
@@ -209,10 +225,16 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel =
|
|
|
209
225
|
if (!usable.ok) throw new Error(usable.say);
|
|
210
226
|
return {
|
|
211
227
|
modelStep: makeLiveModelStep({ slot, model: usable.model, spendPath, env }),
|
|
228
|
+
model: { slot, model: usable.model },
|
|
212
229
|
ceilingUsd: ceilingCostUsd(usable.rates),
|
|
213
230
|
};
|
|
214
231
|
}
|
|
215
232
|
|
|
233
|
+
/** M4d am33: the model a run being continued keeps: the one it started on (its record), else the one it was signed with; null = an old run, today's pick. */
|
|
234
|
+
function runModelKept(runDir) {
|
|
235
|
+
return readRunModel(runDir) ?? runModelOf(pickRunValues(runDir));
|
|
236
|
+
}
|
|
237
|
+
|
|
216
238
|
function parseSourceFlags(list) {
|
|
217
239
|
const out = {};
|
|
218
240
|
for (const entry of list ?? []) {
|
|
@@ -221,7 +243,7 @@ function parseSourceFlags(list) {
|
|
|
221
243
|
const role = entry.slice(0, eq);
|
|
222
244
|
const value = entry.slice(eq + 1);
|
|
223
245
|
if (value.length === 0) throw new Error(`--source "${entry}" has an empty path`);
|
|
224
|
-
out[role] =
|
|
246
|
+
out[role] = value; // resolved at use: a file role is a path, a signed page role is an address (M10 am3)
|
|
225
247
|
}
|
|
226
248
|
return out;
|
|
227
249
|
}
|
|
@@ -324,6 +346,13 @@ async function cmdRun(rest) {
|
|
|
324
346
|
return;
|
|
325
347
|
}
|
|
326
348
|
const declaredRoles = (read.arbiter.sources ?? []).map((s) => s.role);
|
|
349
|
+
// M10 am3: a web page input's address is signed with the job; the run takes it from there, and naming any other address is refused at $0
|
|
350
|
+
const pages = pageAddressesOf(read.arbiter);
|
|
351
|
+
for (const role of Object.keys(pages)) {
|
|
352
|
+
if (Object.hasOwn(parsedSources, role) && parsedSources[role] !== pages[role]) fail(`run: ${pageAddressRefusal(role, pages[role])}`);
|
|
353
|
+
parsedSources[role] = pages[role];
|
|
354
|
+
}
|
|
355
|
+
for (const role of Object.keys(parsedSources)) if (!Object.hasOwn(pages, role)) parsedSources[role] = resolve(parsedSources[role]);
|
|
327
356
|
for (const role of declaredRoles) {
|
|
328
357
|
if (!Object.hasOwn(parsedSources, role)) {
|
|
329
358
|
fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
|
|
@@ -336,7 +365,7 @@ async function cmdRun(rest) {
|
|
|
336
365
|
}
|
|
337
366
|
const sources = declaredRoles.map((role) => ({ id: role, path: parsedSources[role] }));
|
|
338
367
|
for (const src of sources) {
|
|
339
|
-
if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
|
|
368
|
+
if (!Object.hasOwn(pages, src.id) && !existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
|
|
340
369
|
}
|
|
341
370
|
|
|
342
371
|
// M4e amendment 3: no --run-id -> the ONE claim (`run-<n>`, the folder created exclusively). A typed id is checked as before; its
|
|
@@ -368,8 +397,9 @@ async function cmdRun(rest) {
|
|
|
368
397
|
const spendPath = join(runDir, 'spend.jsonl');
|
|
369
398
|
let modelStep;
|
|
370
399
|
let ceilingUsd;
|
|
400
|
+
let startedModel;
|
|
371
401
|
try {
|
|
372
|
-
({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
|
|
402
|
+
({ modelStep, ceilingUsd, model: startedModel } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
|
|
373
403
|
} catch (err) {
|
|
374
404
|
fail(err.message);
|
|
375
405
|
return;
|
|
@@ -398,6 +428,7 @@ async function cmdRun(rest) {
|
|
|
398
428
|
root,
|
|
399
429
|
name: flowName,
|
|
400
430
|
runId,
|
|
431
|
+
runModel: startedModel ?? undefined,
|
|
401
432
|
sources,
|
|
402
433
|
catalogue,
|
|
403
434
|
modelStep,
|
|
@@ -626,7 +657,7 @@ async function cmdResume(rest) {
|
|
|
626
657
|
let modelStep;
|
|
627
658
|
let ceilingUsd;
|
|
628
659
|
try {
|
|
629
|
-
({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values,
|
|
660
|
+
({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelKept(runDir), true));
|
|
630
661
|
} catch (err) {
|
|
631
662
|
fail(err.message);
|
|
632
663
|
return;
|
|
@@ -668,6 +699,7 @@ async function cmdResume(rest) {
|
|
|
668
699
|
root,
|
|
669
700
|
name: flowName,
|
|
670
701
|
runId,
|
|
702
|
+
runModel: runModelKept(runDir) ?? undefined, // a rerun (a new run made by this resume) records the model the resumed run keeps
|
|
671
703
|
catalogue,
|
|
672
704
|
modelStep,
|
|
673
705
|
ceilingUsd,
|
|
@@ -727,7 +759,7 @@ async function cmdContinue(rest) {
|
|
|
727
759
|
let modelStep;
|
|
728
760
|
let ceilingUsd;
|
|
729
761
|
try {
|
|
730
|
-
({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values,
|
|
762
|
+
({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelKept(runDir), true));
|
|
731
763
|
} catch (err) {
|
|
732
764
|
fail(err.message);
|
|
733
765
|
return;
|
|
@@ -818,6 +850,8 @@ async function cmdDraft(rest) {
|
|
|
818
850
|
out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' },
|
|
819
851
|
// M4e amendment 24 item 4: the redraft after the human's answers never asks (the panel passes this; a plain draft may ask on try 3)
|
|
820
852
|
'no-questions': { type: 'boolean' },
|
|
853
|
+
// M10 piece 3: the rules the person left Not checked ("drop it"), as `<line>.<rule>` pairs, e.g. `1.2,3.1` (the panel passes this to the redraft after the answers)
|
|
854
|
+
left: { type: 'string' },
|
|
821
855
|
// M4d amendment 6: the model that drafts (and then runs) the job - a line ticked in Settings > Providers; --provider only if two keys tick the same id.
|
|
822
856
|
// --thinking is the Chat "Thinking on" tick (drafting only; off unless given).
|
|
823
857
|
model: { type: 'string' }, provider: { type: 'string' }, thinking: { type: 'boolean' },
|
|
@@ -830,6 +864,13 @@ async function cmdDraft(rest) {
|
|
|
830
864
|
if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow>');
|
|
831
865
|
for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
|
|
832
866
|
|
|
867
|
+
const leftRules = [];
|
|
868
|
+
for (const pair of values.left === undefined ? [] : values.left.split(',')) {
|
|
869
|
+
const m = /^(\d+)\.(\d+)$/.exec(pair.trim());
|
|
870
|
+
if (m === null || Number(m[1]) < 1 || Number(m[2]) < 1) fail(`draft: --left takes <line>.<rule> pairs like 1.2,3.1, got "${values.left}"`);
|
|
871
|
+
leftRules.push({ line: Number(m[1]), rule: Number(m[2]) });
|
|
872
|
+
}
|
|
873
|
+
|
|
833
874
|
let injected = {};
|
|
834
875
|
if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_DRAFT_PROVIDER) {
|
|
835
876
|
const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
|
|
@@ -869,16 +910,25 @@ async function cmdDraft(rest) {
|
|
|
869
910
|
fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
|
|
870
911
|
}
|
|
871
912
|
// M4d am19 item 1: the hold is what is left of the cap (cap minus this job's drafting so far), the most the draft may spend, not one round
|
|
872
|
-
|
|
873
|
-
|
|
913
|
+
// the ONE read of the prose file goes through the safe gateway (a symlink or an outside path is refused); draftToDir is handed this read
|
|
914
|
+
const proseAbs = resolve(proseFile);
|
|
915
|
+
const gate = readFileInside(dirname(proseAbs), basename(proseAbs));
|
|
916
|
+
const proseRead = gate.ok
|
|
917
|
+
? (gate.text.trim() === '' ? { ok: false, red: `prose: "${proseAbs}" is empty` } : gate)
|
|
918
|
+
: { ok: false, red: gate.missing ? `prose: cannot read "${proseAbs}": ENOENT` : `prose: ${gate.red}` };
|
|
919
|
+
const hold = takeMonthlyHold({
|
|
874
920
|
what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: draftHoldUsd(proseRead.ok ? proseRead.text : '', resolve(values.out), ceiling),
|
|
875
921
|
});
|
|
876
922
|
const result = await draftToDir({
|
|
923
|
+
// M4d am32: the hold is given back when the draft's result is written, not when this process exits (the exit hook stays as the backstop)
|
|
924
|
+
onResult: ({ ok }) => hold.settle(ok ? 'ended or parked' : 'ended (red)'),
|
|
877
925
|
proseFile: resolve(proseFile),
|
|
926
|
+
proseRead,
|
|
878
927
|
dir: resolve(values.out),
|
|
879
928
|
root: resolve(values.root),
|
|
880
929
|
name: values.name,
|
|
881
930
|
noQuestions: values['no-questions'] === true,
|
|
931
|
+
...(leftRules.length ? { leftRules } : {}),
|
|
882
932
|
draftThinking: values.thinking === true ? 'on' : 'off',
|
|
883
933
|
env,
|
|
884
934
|
keyNames: keysLoad.keyNames,
|
|
@@ -892,7 +942,8 @@ async function cmdDraft(rest) {
|
|
|
892
942
|
return;
|
|
893
943
|
}
|
|
894
944
|
process.stdout.write(`draft dir: ${resolve(values.out)} cost: ${cost}\n`);
|
|
895
|
-
|
|
945
|
+
// M10 piece 3: a draft that stopped to ask what the page look raised is not red: it waits for the person's answers (the panel takes them)
|
|
946
|
+
if (!result.ok && result.stop !== 'look-asks') {
|
|
896
947
|
process.stderr.write(`fwdloop: draft RED (${result.stop ?? 'scrub'}) — ${result.reds.join('; ')}\n`);
|
|
897
948
|
process.exitCode = 1;
|
|
898
949
|
return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fwdloop",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"bare-suite"
|
|
33
33
|
],
|
|
34
34
|
"engines": {
|
|
35
|
-
"node": ">=
|
|
35
|
+
"node": ">=22"
|
|
36
36
|
},
|
|
37
37
|
"scripts": {
|
|
38
38
|
"test": "node --test",
|
|
@@ -50,7 +50,8 @@
|
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"bare-agent": "^0.52.0",
|
|
53
|
-
"
|
|
53
|
+
"barebrowse": "^0.21.0",
|
|
54
|
+
"bareguard": "^0.25.1",
|
|
54
55
|
"litectx": "^0.32.0"
|
|
55
56
|
},
|
|
56
57
|
"devDependencies": {
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// M4d am29 items 4-8: the Audit step fold, the Run summary's two lines and the step card's one line, all derived HERE from the run's files on disk
|
|
2
|
+
// (audit.jsonl's try rows + the three diaries in src/diary.js). Nothing here calls a model ($0 replay), and the page only draws what this returns,
|
|
3
|
+
// so the Audit rows, the summary and the cards can only agree. A run from before am29 has no diaries: no fold, `—` on the new lines, nothing made up.
|
|
4
|
+
import { readCalls, readTools, readChecks } from './diary.js';
|
|
5
|
+
|
|
6
|
+
/** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). @param {any} r */
|
|
7
|
+
export function isTryRow(r) {
|
|
8
|
+
return r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && !(r.verdict === 'stopped' && !Number.isInteger(r.attempt));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** @param {string} runDir */
|
|
12
|
+
export function loadDiaries(runDir) {
|
|
13
|
+
const calls = readCalls(runDir);
|
|
14
|
+
const tools = readTools(runDir);
|
|
15
|
+
const checks = readChecks(runDir);
|
|
16
|
+
// a diary file only ever exists with a row in it, so "this run has diaries" is "a diary holds a row" (read through the safe gateway, no fs here)
|
|
17
|
+
return {
|
|
18
|
+
present: calls.length + tools.length + checks.length > 0, calls, tools, checks,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const money = (n) => (typeof n === 'number' ? `$${n.toFixed(4)}` : 'cost unknown');
|
|
23
|
+
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
24
|
+
|
|
25
|
+
/** The Decision words of a model call row. @param {any} c */
|
|
26
|
+
function callDecision(c) {
|
|
27
|
+
const bits = [money(c.costUsd)];
|
|
28
|
+
if (c.tokens) bits.push(`${c.tokens.in + c.tokens.out + c.tokens.cache} tokens`);
|
|
29
|
+
if (typeof c.ms === 'number') bits.push(`${(c.ms / 1000).toFixed(1)}s`);
|
|
30
|
+
return bits.join(' · ');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The Decision words of a tool row: allow, deny and the rule that said so, or `no check`. @param {any} t */
|
|
34
|
+
const toolDecision = (t) => (t.decision === 'deny' ? `deny (${t.rule ?? 'no rule recorded'})` : t.decision);
|
|
35
|
+
|
|
36
|
+
/** The Decision words of a try's check row. @param {Array<{n:number, ok:boolean}>} checks */
|
|
37
|
+
function checkDecision(checks) {
|
|
38
|
+
const failed = checks.filter((c) => !c.ok);
|
|
39
|
+
return failed.length === 0 ? `✓ all ${checks.length} passed` : `✗ ${failed.map((c) => `#${c.n}`).join(' ')} failed`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What the human did, in the signed words, from the ask step's own audit row; `null` for a row that is not an answer. @param {any} r */
|
|
43
|
+
export function humanWords(r) {
|
|
44
|
+
if (r.verdict === 'paused') return 'paused for you';
|
|
45
|
+
if (r.verdict === 'green') return 'you accepted';
|
|
46
|
+
if (r.verdict === 'red') return `you said redo: "${r.gap ?? ''}"`;
|
|
47
|
+
if (r.verdict === 'stopped') return 'you cancelled';
|
|
48
|
+
if (r.verdict === 'refused') return String(r.gap ?? 'refused');
|
|
49
|
+
if (r.verdict === 'ask-timeout') return 'the ask timed out';
|
|
50
|
+
if (r.verdict === 'ask-expired') return 'the ask expired';
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The short answer for a card: `accepted`, `redo: "<text>"`, `cancelled`. @param {any} r */
|
|
55
|
+
function answerShort(r) {
|
|
56
|
+
const w = humanWords(r);
|
|
57
|
+
return w === null ? null : w.replace(/^you said /, '').replace(/^you /, '');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The fold of one step, or `null` for a step with nothing new to show (an old run, or a step that is neither a model step with records nor an ask).
|
|
62
|
+
* @param {{rows:any[], tryMarks:string[], closeClass:string|null}} group `deriveAuditGroups`' group for the step
|
|
63
|
+
* @param {ReturnType<typeof loadDiaries>} d
|
|
64
|
+
* @param {{about?: string|null}} [info] `about`: the file an ask is about
|
|
65
|
+
*/
|
|
66
|
+
export function deriveFold(group, d, info = {}) {
|
|
67
|
+
const step = group.rows[0]?.step ?? null;
|
|
68
|
+
const human = group.rows.some((r) => Object.prototype.hasOwnProperty.call(r, 'unjudgedCount'));
|
|
69
|
+
const calls = d.calls.filter((r) => r.step === step);
|
|
70
|
+
const tools = d.tools.filter((r) => r.step === step);
|
|
71
|
+
const checkRows = d.checks.filter((r) => r.step === step);
|
|
72
|
+
if (human ? !d.present : (calls.length + tools.length + checkRows.length === 0)) return null;
|
|
73
|
+
|
|
74
|
+
const tryRows = group.rows.filter(isTryRow);
|
|
75
|
+
const tries = [];
|
|
76
|
+
const rows = [];
|
|
77
|
+
if (human) {
|
|
78
|
+
// a try is a pause and the answer that followed it; an ask answered on the spot (no pause row) is one try per answer. A refusal is a re-ask, not an answer.
|
|
79
|
+
/** @type {any} */
|
|
80
|
+
let open = null;
|
|
81
|
+
for (const r of tryRows) {
|
|
82
|
+
if (r.verdict === 'paused') {
|
|
83
|
+
open = {
|
|
84
|
+
n: r.attempt, mark: '·', thinking: null, gap: null, answer: null, about: info.about ?? null, checks: [], output: null,
|
|
85
|
+
};
|
|
86
|
+
tries.push(open);
|
|
87
|
+
} else if (r.verdict !== 'refused' && humanWords(r) !== null) {
|
|
88
|
+
if (open === null || open.answer !== null) {
|
|
89
|
+
open = {
|
|
90
|
+
n: r.attempt, mark: '·', thinking: null, gap: null, answer: null, about: info.about ?? null, checks: [], output: null,
|
|
91
|
+
};
|
|
92
|
+
tries.push(open);
|
|
93
|
+
}
|
|
94
|
+
open.answer = humanWords(r);
|
|
95
|
+
open.mark = r.verdict === 'green' ? '✓' : (r.verdict === 'red' || r.verdict === 'stopped' ? '✗' : '·');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const r of group.rows) {
|
|
99
|
+
const words = r.verdict === 'paused' || isTryRow(r) ? humanWords(r) : null;
|
|
100
|
+
if (words === null) continue;
|
|
101
|
+
rows.push({
|
|
102
|
+
round: null, try: Number.isInteger(r.attempt) ? r.attempt : null, action: 'human', path: r.verdict === 'paused' ? (info.about ?? null) : null, decision: words, at: r.at ?? null,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
// M4d am30: a try's checks are the check row with ITS number. A number is used once per step, so that is exact. A run from before am30 may repeat a number
|
|
107
|
+
// (the old Redo restarted it): those tries are paired in order only when every one of them saved (as many check rows as try rows); otherwise none is guessed.
|
|
108
|
+
const seen = new Map();
|
|
109
|
+
tryRows.forEach((r, i) => {
|
|
110
|
+
const k = seen.get(r.attempt) ?? 0;
|
|
111
|
+
seen.set(r.attempt, k + 1);
|
|
112
|
+
const saved = checkRows.filter((c) => c.try === r.attempt);
|
|
113
|
+
const alike = tryRows.filter((t) => t.attempt === r.attempt).length;
|
|
114
|
+
const rec = saved.length === alike ? saved[k] : null;
|
|
115
|
+
tries.push({
|
|
116
|
+
n: r.attempt, mark: group.tryMarks[i] ?? '·', thinking: r.thinkingPhrase ?? null, gap: r.gap || null, answer: null, about: null, checks: rec?.checks ?? [], output: rec?.output ?? null,
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
// rounds count on through all of a step's tries, so they order the calls and tool calls; a try's check row goes after the last round it saw
|
|
120
|
+
const items = [];
|
|
121
|
+
calls.forEach((c, i) => items.push({ k: c.round * 2, i, row: { round: c.round, try: c.try, action: 'model call', path: null, decision: callDecision(c), at: c.at } }));
|
|
122
|
+
tools.forEach((t, i) => items.push({ k: t.round * 2 + 1, i: 1e6 + i, row: { round: t.round, try: t.try, action: `model · ${t.tool}`, path: t.path ?? null, decision: toolDecision(t), at: t.at } }));
|
|
123
|
+
checkRows.forEach((c, i) => items.push({ k: (c.lastRound ?? 0) * 2 + 1.5, i: 2e6 + i, row: { round: null, try: c.try, action: 'check', path: c.output?.file ?? null, decision: checkDecision(c.checks), at: c.at } }));
|
|
124
|
+
items.sort((a, b) => a.k - b.k || a.i - b.i);
|
|
125
|
+
for (const it of items) rows.push(it.row);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const tally = {};
|
|
129
|
+
for (const t of tools) tally[t.tool] = (tally[t.tool] ?? 0) + 1;
|
|
130
|
+
const tallyWords = Object.entries(tally).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([k, v]) => `${k} ${v}`).join(', ');
|
|
131
|
+
const lastChecks = checkRows.length ? checkRows[checkRows.length - 1].checks : null;
|
|
132
|
+
const answered = human ? group.rows.filter((r) => r.verdict !== 'paused' && isTryRow(r) && humanWords(r) !== null) : [];
|
|
133
|
+
const lastAnswerRow = answered.length ? answered[answered.length - 1] : null;
|
|
134
|
+
return {
|
|
135
|
+
who: human ? 'human' : 'model',
|
|
136
|
+
tally: tallyWords || null,
|
|
137
|
+
tries,
|
|
138
|
+
rows,
|
|
139
|
+
counts: {
|
|
140
|
+
rounds: calls.length,
|
|
141
|
+
tools: tools.length,
|
|
142
|
+
denied: tools.filter((t) => t.decision === 'deny').length,
|
|
143
|
+
checksRun: checkRows.reduce((n, c) => n + c.checks.length, 0),
|
|
144
|
+
checksFailed: checkRows.reduce((n, c) => n + c.checks.filter((x) => !x.ok).length, 0),
|
|
145
|
+
lastTry: lastChecks ? { run: lastChecks.length, passed: lastChecks.filter((x) => x.ok).length } : null,
|
|
146
|
+
},
|
|
147
|
+
lastAnswer: lastAnswerRow ? { words: answerShort(lastAnswerRow), at: lastAnswerRow.at ?? null } : null,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The step card's one new line (item 6) minus the human step's time (the page formats that); `—` when there is no record. @param {ReturnType<typeof deriveFold>} fold */
|
|
152
|
+
export function cardLine(fold) {
|
|
153
|
+
if (fold === null) return '—';
|
|
154
|
+
if (fold.who === 'human') return fold.lastAnswer ? `last answer: ${fold.lastAnswer.words}` : '—';
|
|
155
|
+
const lt = fold.counts.lastTry;
|
|
156
|
+
const checks = lt ? `${lt.passed}/${lt.run} ${lt.passed === lt.run ? '✓' : '✗'}` : '—';
|
|
157
|
+
return `${plural(fold.counts.rounds, 'round', 'rounds')} · checks on the last try ${checks}`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The Run summary's two new lines (item 5), from the same diary rows the folds read; `—` for a run with no diaries.
|
|
162
|
+
* @param {ReturnType<typeof loadDiaries>} d
|
|
163
|
+
*/
|
|
164
|
+
export function summaryLines(d) {
|
|
165
|
+
if (!d.present) return { calls: '—', checks: '—' };
|
|
166
|
+
const denied = d.tools.filter((t) => t.decision === 'deny').length;
|
|
167
|
+
const run = d.checks.reduce((n, c) => n + c.checks.length, 0);
|
|
168
|
+
const failed = d.checks.reduce((n, c) => n + c.checks.filter((x) => !x.ok).length, 0);
|
|
169
|
+
const byStep = new Map();
|
|
170
|
+
for (const c of d.checks) {
|
|
171
|
+
if (c.checks.every((x) => x.ok)) continue;
|
|
172
|
+
if (!byStep.has(c.step)) byStep.set(c.step, []);
|
|
173
|
+
byStep.get(c.step).push(c.try);
|
|
174
|
+
}
|
|
175
|
+
const list = (ns) => (ns.length === 1 ? `try ${ns[0]}` : `tries ${ns.length === 2 ? ns.join(' and ') : `${ns.slice(0, -1).join(', ')} and ${ns[ns.length - 1]}`}`);
|
|
176
|
+
const where = [...byStep].map(([step, ns]) => `${step} ${list(ns)}`).join('; ');
|
|
177
|
+
return {
|
|
178
|
+
calls: `${d.calls.length} model · ${d.tools.length} tool · ${denied} denied`,
|
|
179
|
+
checks: `${run} run · ${run - failed} passed · ${failed} failed${where ? ` (${where})` : ''}`,
|
|
180
|
+
};
|
|
181
|
+
}
|
package/src/authoring.js
CHANGED
|
@@ -22,6 +22,7 @@ import path from 'node:path';
|
|
|
22
22
|
import { draft } from './drafter.js';
|
|
23
23
|
import { parseSignedText, unsignedAskTtls } from './signed-text.js';
|
|
24
24
|
import { validateDeclaration } from './declaration.js';
|
|
25
|
+
import { factRows } from './citedcheck.js';
|
|
25
26
|
import { loadCatalogue } from './catalogue.js';
|
|
26
27
|
import { WIRED_VERBS } from './primitives.js';
|
|
27
28
|
import { canonicalBytes } from './signature.js';
|
|
@@ -43,6 +44,10 @@ export const LEAK_MARKER_FILE = 'scrub-leak.red';
|
|
|
43
44
|
* and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
|
|
44
45
|
export const QUESTIONS_FILE = 'questions.json';
|
|
45
46
|
export const NOT_CHECKED_FILE = 'not-checked.json';
|
|
47
|
+
/** M10: the drafting copy of each web page input is kept in this folder of the draft folder (a run freezes its own, never this one). */
|
|
48
|
+
export const PAGES_DIR = 'pages';
|
|
49
|
+
/** M10 item 3: what the page-word look kept and dropped, per page input (the map the AI named, the kept facts with their readings, every drop). Not signed. */
|
|
50
|
+
export const PAGE_LOOK_FILE = 'page-look.json';
|
|
46
51
|
export const ANSWER_FILE = (k) => `answer-${k}.json`;
|
|
47
52
|
export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
|
|
48
53
|
|
|
@@ -77,7 +82,8 @@ export function specHash({
|
|
|
77
82
|
* checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
|
|
78
83
|
* answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
|
|
79
84
|
* @param {string} planDir
|
|
80
|
-
*
|
|
85
|
+
* A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
|
|
86
|
+
* @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
|
|
81
87
|
*/
|
|
82
88
|
export function readQuestions(planDir) {
|
|
83
89
|
const none = { questions: [], open: [] };
|
|
@@ -90,8 +96,20 @@ export function readQuestions(planDir) {
|
|
|
90
96
|
const k = i + 1;
|
|
91
97
|
const a = readFileInside(planDir, ANSWER_FILE(k));
|
|
92
98
|
let answer = null;
|
|
93
|
-
|
|
94
|
-
|
|
99
|
+
let at;
|
|
100
|
+
/** @type {string|null|undefined} the `~` rule the answer added (null = it left the rule Not checked), as the answer file recorded it */
|
|
101
|
+
let rule;
|
|
102
|
+
if (a.ok) {
|
|
103
|
+
try {
|
|
104
|
+
const j = JSON.parse(a.text);
|
|
105
|
+
const t = j?.answer;
|
|
106
|
+
if (typeof t === 'string' && t.trim() !== '') { answer = t; if (typeof j.at === 'string') at = j.at; if (j.rule === null || typeof j.rule === 'string') rule = j.rule; }
|
|
107
|
+
} catch { /* unreadable = unanswered */ }
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }),
|
|
111
|
+
...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null } : {}),
|
|
112
|
+
};
|
|
95
113
|
});
|
|
96
114
|
return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
|
|
97
115
|
}
|
|
@@ -178,6 +196,10 @@ export function buildReadout({
|
|
|
178
196
|
out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
|
|
179
197
|
out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
|
|
180
198
|
+ ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
|
|
199
|
+
// M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
|
|
200
|
+
if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
|
|
201
|
+
// M10 am8 item 2: the column lock, signed with the readout (typed fields)
|
|
202
|
+
if (Array.isArray(st.close?.columns)) for (const c of st.close.columns) if (typeof c?.column === 'string' && typeof c?.source === 'string') out.push(` cells only from column '${c.column}' of ${c.source}`);
|
|
181
203
|
// M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
|
|
182
204
|
const shape = st.close?.shape;
|
|
183
205
|
if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
|
|
@@ -246,9 +268,10 @@ export function draftKeyRefusal(slot, env) {
|
|
|
246
268
|
* writer (appendSpendRow); an unpriced round books null, never 0.
|
|
247
269
|
*
|
|
248
270
|
* Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
|
|
271
|
+
* `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
|
|
249
272
|
*/
|
|
250
273
|
export async function draftToDir({
|
|
251
|
-
proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false,
|
|
274
|
+
proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, proseRead,
|
|
252
275
|
}) {
|
|
253
276
|
const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
|
|
254
277
|
const nameCheck = checkFlowName(name);
|
|
@@ -264,7 +287,7 @@ export async function draftToDir({
|
|
|
264
287
|
if (!panelDrafts && (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))) {
|
|
265
288
|
return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
|
|
266
289
|
}
|
|
267
|
-
const read = readProseFile(proseFile);
|
|
290
|
+
const read = proseRead ?? readProseFile(proseFile); // the CLI reads the file once (for its hold) and hands that read in
|
|
268
291
|
if (!read.ok) return refuse([String(read.red)]);
|
|
269
292
|
const prose = { text: String(read.text) };
|
|
270
293
|
const injected = provider != null;
|
|
@@ -307,7 +330,7 @@ export async function draftToDir({
|
|
|
307
330
|
// M4d am16: a panel draft folder (card.json beside this plan folder) is one job's session: what its earlier plans spent comes off the cap first.
|
|
308
331
|
const priorSpend = sessionPriorSpend(dir);
|
|
309
332
|
const result = await draft({
|
|
310
|
-
proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking,
|
|
333
|
+
proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, ...(leftRules === undefined ? {} : { leftRules }),
|
|
311
334
|
});
|
|
312
335
|
if (result.stop === 'pre-flight') {
|
|
313
336
|
try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
|
|
@@ -327,11 +350,12 @@ export async function draftToDir({
|
|
|
327
350
|
files['target.json'] = targetText;
|
|
328
351
|
// M4d am6 item 6: the pick is remembered beside the draft (written below as model.json, outside the signed files) so the signed job runs with it.
|
|
329
352
|
const recordModel = model ?? result.modelId ?? modelId;
|
|
330
|
-
const pick = typeof slot === 'string' && typeof recordModel === 'string' && recordModel !== '' ? { slot, model: recordModel } : null;
|
|
353
|
+
const pick = typeof slot === 'string' && typeof recordModel === 'string' && recordModel !== '' ? { slot, model: recordModel, ...(draftThinking === 'on' ? { thinking: true } : {}) } : null;
|
|
331
354
|
// Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
|
|
332
355
|
// two as "the draft finished"), as their own files: never in the readout, so never in the hash.
|
|
333
356
|
if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
|
|
334
357
|
files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [] }), secrets);
|
|
358
|
+
if (result.pageLooks || result.sheetLooks) files[PAGE_LOOK_FILE] = scrub(dj({ pages: result.pageLooks ?? [], ...(result.sheetLooks ? { sheets: result.sheetLooks } : {}), look: result.look ?? { facts: [], dropped: [] } }), secrets);
|
|
335
359
|
files['log.json'] = scrub(dj({
|
|
336
360
|
ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
|
|
337
361
|
modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
|
|
@@ -376,6 +400,8 @@ export async function draftToDir({
|
|
|
376
400
|
startedAt,
|
|
377
401
|
wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
|
|
378
402
|
});
|
|
403
|
+
// M4d am32: the spend is booked, and the result files are about to be written: the monthly hold is given back now, so a draft never reads done while its hold is still held
|
|
404
|
+
if (typeof onResult === 'function') onResult({ ok: result.ok });
|
|
379
405
|
for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
|
|
380
406
|
if (pick !== null) writeModelRecord(dir, pick);
|
|
381
407
|
leaks = sweepForSecrets(dir, secrets);
|
package/src/books.js
CHANGED
|
@@ -66,7 +66,7 @@ export function readPidRows(runDir) {
|
|
|
66
66
|
* @param {string} relPath - the book's own file name, relative to baseDir
|
|
67
67
|
* @returns {any[]}
|
|
68
68
|
*/
|
|
69
|
-
function readLines(baseDir, relPath) {
|
|
69
|
+
export function readLines(baseDir, relPath) {
|
|
70
70
|
const result = readFileInside(baseDir, relPath);
|
|
71
71
|
if (!result.ok) return [];
|
|
72
72
|
const rows = [];
|