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/src/docx.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
// is over raw paragraph markup, not a parsed tree).
|
|
13
13
|
|
|
14
14
|
import { readFileSync } from 'node:fs';
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
15
16
|
import { inflateRawSync } from 'node:zlib';
|
|
16
17
|
|
|
17
18
|
const EOCD_SIG = 0x06054b50;
|
|
@@ -128,7 +129,8 @@ function extractText(xml) {
|
|
|
128
129
|
}
|
|
129
130
|
|
|
130
131
|
/** One reader for word/document.xml: the file, the zip entry, the bounded inflate.
|
|
131
|
-
*
|
|
132
|
+
* `sha256` is of the file's bytes, taken from the SAME read the text comes from (so a text and its hash can never be of two different files).
|
|
133
|
+
* @param {string} path @returns {{ok:true,xml:string,sha256:string}|{ok:false,red:string}} */
|
|
132
134
|
function loadDocumentXml(path) {
|
|
133
135
|
let buf;
|
|
134
136
|
try {
|
|
@@ -140,7 +142,7 @@ function loadDocumentXml(path) {
|
|
|
140
142
|
if (entry.red) return { ok: false, red: entry.red };
|
|
141
143
|
const read = readEntryBytes(buf, entry);
|
|
142
144
|
if (read.red || !read.data) return { ok: false, red: read.red ?? 'no data decoded' };
|
|
143
|
-
return { ok: true, xml: read.data.toString('utf8') };
|
|
145
|
+
return { ok: true, xml: read.data.toString('utf8'), sha256: createHash('sha256').update(buf).digest('hex') };
|
|
144
146
|
}
|
|
145
147
|
|
|
146
148
|
/** @param {string} path @returns {{ok:true,text:string,paragraphs:number}|{ok:false,red:string}} */
|
|
@@ -151,6 +153,18 @@ export function readDocxText(path) {
|
|
|
151
153
|
return { ok: true, text, paragraphs };
|
|
152
154
|
}
|
|
153
155
|
|
|
156
|
+
/**
|
|
157
|
+
* M10 piece 5 (item 2, "a quote in a doc"): the text of a .docx AND the sha256 of its bytes from one read, so a cited check can prove the run's own frozen copy is
|
|
158
|
+
* the file that was frozen. Same text as {@link readDocxText} (what it throws away is declared at the top of this file).
|
|
159
|
+
* @param {string} path @returns {{ok:true,text:string,paragraphs:number,sha256:string}|{ok:false,red:string}}
|
|
160
|
+
*/
|
|
161
|
+
export function readDocxSource(path) {
|
|
162
|
+
const doc = loadDocumentXml(path);
|
|
163
|
+
if (!doc.ok) return doc;
|
|
164
|
+
const { text, paragraphs } = extractText(doc.xml);
|
|
165
|
+
return { ok: true, text, paragraphs, sha256: doc.sha256 };
|
|
166
|
+
}
|
|
167
|
+
|
|
154
168
|
// Heading paragraphs: <w:pStyle w:val="Heading1"/> .. HeadingN, or Title. The
|
|
155
169
|
// style ID is matched, not styles.xml's display name — Word writes the ID
|
|
156
170
|
// "Heading1" for the built-in "heading 1"; a custom-named heading style is
|
package/src/draft-steps.js
CHANGED
|
@@ -69,7 +69,7 @@ export function draftStepList({ log, declaration, questionOpen = false }) {
|
|
|
69
69
|
const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
|
|
70
70
|
const facts = ['drafted', who, `${n} round${n === 1 ? '' : 's'}`, money(log)];
|
|
71
71
|
if (!gotPlan && reds.length > 0) facts.push(reds[0]); // no plan at all (provider red, cut off): its own words, there is no checker text
|
|
72
|
-
out.push({ id: 'drafted', label: facts.join(' · '), status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [] });
|
|
72
|
+
out.push({ id: 'drafted', label: facts.join(' · '), status: /** @type {'done'|'failed'} */ (gotPlan || (questionOpen && reds.length === 0) ? 'done' : 'failed'), details: [] }); // a draft that stopped to ask (the page look's question, no plan yet) has not failed
|
|
73
73
|
|
|
74
74
|
const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
|
|
75
75
|
const rubricReds = [];
|
package/src/drafter.js
CHANGED
|
@@ -22,7 +22,17 @@ import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerS
|
|
|
22
22
|
import { loadCatalogue } from './catalogue.js';
|
|
23
23
|
import { WIRED_VERBS, wiredMenu } from './primitives.js';
|
|
24
24
|
import { readInputFacts } from './input-facts.js';
|
|
25
|
+
import { freezePage } from './runner.js';
|
|
26
|
+
import { removeFrozenPages } from './flow.js';
|
|
27
|
+
import { lookAtPage, pageInfoLines } from './pagelook.js';
|
|
28
|
+
import { lookAtSheet, sheetPrompt } from './sheetlook.js';
|
|
29
|
+
import { leftRuleLine, dropRows, dropLine } from './pagedropwords.js';
|
|
30
|
+
import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
|
|
31
|
+
import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
|
|
32
|
+
import { lineRules } from './pagebits.js';
|
|
33
|
+
import path from 'node:path';
|
|
25
34
|
import { isCellsPath } from './closers.js';
|
|
35
|
+
import { parseCsv } from './csv.js';
|
|
26
36
|
import {
|
|
27
37
|
makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
|
|
28
38
|
} from './provider.js';
|
|
@@ -40,6 +50,73 @@ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
|
|
|
40
50
|
/** The whole-output-ceiling rule, told once to the drafter (schema and prompt use this string). Amendment 29; no number words (am25). */
|
|
41
51
|
export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
|
|
42
52
|
|
|
53
|
+
/** @param {any[]|undefined} sources @returns {string[]} the roles of the document inputs (.docx / .md / .txt) */
|
|
54
|
+
const docRolesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'file' && DOC_EXTS.some((x) => String(s.path).toLowerCase().endsWith(x))).map((s) => s.role);
|
|
55
|
+
|
|
56
|
+
/** the document inputs a quote can come from (M10 piece 5, item 2) */
|
|
57
|
+
const DOC_EXTS = Object.freeze(['.docx', '.md', '.txt']);
|
|
58
|
+
|
|
59
|
+
/** M10 am8 item 2: the column lock of a green step that cites cells (`close.columns`): the exact header(s) its cells come from. */
|
|
60
|
+
const COLUMNS_PROP = Object.freeze({
|
|
61
|
+
type: 'array',
|
|
62
|
+
minItems: 1,
|
|
63
|
+
maxItems: 10,
|
|
64
|
+
description: "only on a green step that cites cells of a CSV input: the exact column names (the sheet's header) every cited cell comes from. Omit on any other step",
|
|
65
|
+
items: {
|
|
66
|
+
type: 'object',
|
|
67
|
+
properties: {
|
|
68
|
+
source: { type: 'string', description: 'the role of the CSV input (also in the step\'s reads)' },
|
|
69
|
+
column: { type: 'string', description: "the column's name, copied exactly from the sheet's header" },
|
|
70
|
+
},
|
|
71
|
+
required: ['source', 'column'],
|
|
72
|
+
additionalProperties: false,
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** M10 am7 item 1: the facts of a green step that cites quotes from a web page (`close.cited`); the same fields src/citedcheck.js checks. */
|
|
77
|
+
const CITED_PROP = Object.freeze({
|
|
78
|
+
type: 'object',
|
|
79
|
+
description: 'only on a green step that checks quotes from a web page or a document input: the facts every result must hold. Omit on any other step',
|
|
80
|
+
properties: {
|
|
81
|
+
source: { type: 'string', description: "the role of the web page input the quotes come from (also in the step's reads)" },
|
|
82
|
+
facts: {
|
|
83
|
+
type: 'array',
|
|
84
|
+
minItems: 1,
|
|
85
|
+
maxItems: 10,
|
|
86
|
+
description: 'one fact per thing a result must hold; at most 10',
|
|
87
|
+
items: {
|
|
88
|
+
type: 'object',
|
|
89
|
+
properties: {
|
|
90
|
+
name: { type: 'string', description: 'letters and spaces only, no digits' },
|
|
91
|
+
shape: { type: 'string', enum: ['money', 'number', 'date', 'time', 'phrase', 'text'] },
|
|
92
|
+
unit: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: the words the page writes after the amount, copied from the page' },
|
|
93
|
+
currency: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: $, € or £' },
|
|
94
|
+
phrase: { type: 'string', description: 'phrase only: the fixed words every result must say, copied from the page' },
|
|
95
|
+
anchor: { type: 'string', description: 'the label right before the value, picked from the kept labels listed under Inputs; never typed' },
|
|
96
|
+
until: { type: 'string', description: 'text only: the words that close the value' },
|
|
97
|
+
rule: {
|
|
98
|
+
type: 'object',
|
|
99
|
+
description: 'under (lt, lte), over (gt, gte) or between: only a number that is in the person\'s own words on the job line',
|
|
100
|
+
properties: { op: { type: 'string', enum: ['lt', 'lte', 'gt', 'gte', 'between'] }, value: {}, lo: {}, hi: {} },
|
|
101
|
+
required: ['op'],
|
|
102
|
+
additionalProperties: false,
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
required: ['name', 'shape'],
|
|
106
|
+
additionalProperties: false,
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
count: {
|
|
110
|
+
type: 'object',
|
|
111
|
+
description: 'how many results the job line asks for ("List 3" is min 3, max 3)',
|
|
112
|
+
properties: { min: { type: 'integer', minimum: 1 }, max: { type: 'integer', minimum: 1 } },
|
|
113
|
+
additionalProperties: false,
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
required: ['source', 'facts'],
|
|
117
|
+
additionalProperties: false,
|
|
118
|
+
});
|
|
119
|
+
|
|
43
120
|
const SHAPE_PROPS = Object.freeze({
|
|
44
121
|
maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
|
|
45
122
|
sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
|
|
@@ -86,6 +163,8 @@ export function buildDeclarationSchema(menu) {
|
|
|
86
163
|
additionalProperties: false,
|
|
87
164
|
description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
|
|
88
165
|
},
|
|
166
|
+
cited: CITED_PROP,
|
|
167
|
+
columns: COLUMNS_PROP,
|
|
89
168
|
},
|
|
90
169
|
required: ['class'],
|
|
91
170
|
additionalProperties: false,
|
|
@@ -219,13 +298,30 @@ function jobLinesText(lines, asks) {
|
|
|
219
298
|
.join('\n');
|
|
220
299
|
}
|
|
221
300
|
|
|
222
|
-
/** M4d amendment 8: the green step must read an input with cells, so the drafter is told the rule and which inputs have cells.
|
|
301
|
+
/** M4d amendment 8: the green step must read an input with cells, so the drafter is told the rule and which inputs have cells.
|
|
302
|
+
* M10 am7: and when the job signs a web page, how a green step checks quotes from it - every rule below is one the validator enforces at $0. */
|
|
223
303
|
function greenReadRule(sources) {
|
|
224
304
|
const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
|
|
305
|
+
const pageRoles = (sources ?? []).filter((s) => s.kind === 'page').map((s) => s.role);
|
|
306
|
+
// M10 piece 5 (item 2): a quote in a doc - a .docx / .md / .txt input is quoted the way a page is
|
|
307
|
+
const docRoles = docRolesOf(sources);
|
|
225
308
|
const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be cited; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
|
|
226
|
-
|
|
227
|
-
? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}.`
|
|
228
|
-
: `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl".`];
|
|
309
|
+
const out = [csvRoles.length
|
|
310
|
+
? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}. close.columns = [{source, column}] names the exact column(s) of the CSV header that the step's cells come from; every cell it cites must be in one of them. Where the Inputs list says a line "is column 'X'", that line's step must name that column. Leave close.columns out when the line names no column.`
|
|
311
|
+
: `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl"${pageRoles.length ? ' (unless it is about a web page, below)' : ''}.`];
|
|
312
|
+
if (pageRoles.length || docRoles.length) {
|
|
313
|
+
out.push(
|
|
314
|
+
`- ${[pageRoles.length ? `Web page inputs in this job: ${pageRoles.join(', ')}.` : '', docRoles.length ? `Document inputs in this job: ${docRoles.join(', ')}.` : ''].filter(Boolean).join(' ')} A step whose line asks for things found in one of them, and whose guardrail is about them, is "green" and checks quotes: it lists that input's role in its reads and carries close.cited = {source, facts, count}. close.cited is for a green step only.`,
|
|
315
|
+
'- close.cited.count is how many results the line asks for ("List 3" is {min: 3, max: 3}); the number must be one the person said on the line or its guardrail, as digits or a word. close.cited.facts is one fact per thing every result must hold, at most 10; a fact name is letters and spaces only (no digit).',
|
|
316
|
+
'- Fact shapes: money takes unit or currency, rule, anchor; number, date and time take rule, anchor; text takes anchor and until (until needs an anchor); phrase takes only phrase (fixed words every result must say). Never put a field on a shape that does not take it.',
|
|
317
|
+
'- A label (anchor, until) is PICKED from the kept labels listed under Inputs for that page, never typed. A phrase, a unit or a currency is copied from the page words listed there. A word listed as Not checked or dropped can never be used.',
|
|
318
|
+
'- A place listed under Inputs as "place phrases" must have EVERY one of its phrases as its own phrase fact (one fact per phrase, the phrase word for word). A place name alone does not tell a result that leaves the other way.',
|
|
319
|
+
'- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none.',
|
|
320
|
+
'- A label or a phrase that sits in each result must appear on the page at least as many times as close.cited.count.min, or the line is refused.',
|
|
321
|
+
...(docRoles.length ? ['- For a document input there is no list of kept labels: a label (anchor) or a phrase is words the document really says, copied from it, and each must be in the document at least as many times as close.cited.count.min.'] : []),
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
return out;
|
|
229
325
|
}
|
|
230
326
|
|
|
231
327
|
/** M7 piece 6 (signed scope item 1): a granted verb ships WITH the line that says when to reach for it, or the
|
|
@@ -304,11 +400,14 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
|
|
|
304
400
|
*
|
|
305
401
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
306
402
|
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
|
|
307
|
-
* questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[]
|
|
403
|
+
* questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
|
|
404
|
+
* look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
|
|
405
|
+
* `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
|
|
308
406
|
*/
|
|
309
407
|
export async function draft({
|
|
310
408
|
proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
311
409
|
priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
|
|
410
|
+
draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
|
|
312
411
|
}) {
|
|
313
412
|
// What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
|
|
314
413
|
const thinkingOf = () => {
|
|
@@ -331,8 +430,9 @@ export async function draft({
|
|
|
331
430
|
const sumReds = checkGuardrailSums(lines);
|
|
332
431
|
if (sumReds.length) return fail(sumReds);
|
|
333
432
|
const menu = wiredMenu(skills);
|
|
334
|
-
|
|
335
|
-
|
|
433
|
+
// The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
|
|
434
|
+
const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
|
|
435
|
+
if (!fileFacts.ok) return fail(fileFacts.reds);
|
|
336
436
|
|
|
337
437
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
338
438
|
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
@@ -346,9 +446,6 @@ export async function draft({
|
|
|
346
446
|
}
|
|
347
447
|
}
|
|
348
448
|
|
|
349
|
-
// `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
|
|
350
|
-
const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo: facts.info });
|
|
351
|
-
const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
|
|
352
449
|
const lineNums = lines.map((l) => l.n);
|
|
353
450
|
// Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
|
|
354
451
|
const cat = loadCatalogue();
|
|
@@ -362,15 +459,187 @@ export async function draft({
|
|
|
362
459
|
// M4d am16 item 2: against the remaining money, not the whole cap. Spend by earlier drafts of this job (a revise, the redraft after answers) is taken off first.
|
|
363
460
|
const priorUsd = typeof priorSpend === 'function' ? priorSpend(roundCeiling) : 0;
|
|
364
461
|
const budgetUsd = arbiter.capUsd - priorUsd;
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
}
|
|
462
|
+
/** the refusal when one round held at `ceiling` does not fit what is left of the cap (the drafter's own words, one place) */
|
|
463
|
+
const tooSmall = (ceiling) => (priorUsd > 0
|
|
464
|
+
? `Cap ${usdText(arbiter.capUsd)} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${ceiling.toFixed(4)}. Raise Cap $ or pick another model.`
|
|
465
|
+
: capTooSmallText('drafting', arbiter.capUsd, ceiling, modelId));
|
|
466
|
+
if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)]);
|
|
371
467
|
|
|
372
468
|
const meterings = [];
|
|
373
469
|
const log = [];
|
|
470
|
+
let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
|
|
471
|
+
let unmetered = 0; // calls that failed with no metering: their cost is unknown
|
|
472
|
+
const book = (inFlight) => onBook?.({
|
|
473
|
+
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
// M10 item 1: a web page input is fetched once and frozen into the DRAFT folder (the drafting copy). A run freezes its own copy at its own start
|
|
477
|
+
// (`freezeInputs`), so a run is never checked against this one. Only now, after the $0 price and cap gates: a draft refused for money fetches nothing.
|
|
478
|
+
const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page');
|
|
479
|
+
/** @type {Record<string, {text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}>} */
|
|
480
|
+
const pages = {};
|
|
481
|
+
if (pageSources.length) {
|
|
482
|
+
if (typeof draftDir !== 'string' || draftDir === '') return fail(['draft: a web page input needs a folder to keep its drafting copy']);
|
|
483
|
+
for (const s of pageSources) {
|
|
484
|
+
const fr = await freezePage(draftDir, s.role, s.path, { fetchPage });
|
|
485
|
+
if (!fr.ok) { removeFrozenPages(draftDir, Object.values(pages).map((pg) => pg.entry.frozen)); return fail([fr.red]); }
|
|
486
|
+
pages[s.role] = { text: fr.text, entry: fr.entry };
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
const facts = readInputFacts(arbiter.sources, { pages });
|
|
490
|
+
if (!facts.ok) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((pg) => pg.entry.frozen)); return fail(facts.reds); }
|
|
491
|
+
|
|
492
|
+
// M10 item 3: ONE map call per page input names the page's own words; code keeps what the saved page proves. Every round goes through the
|
|
493
|
+
// same metering and book as a drafting round, so a pre-send throw from the book stops here with nothing spent.
|
|
494
|
+
/** @type {{facts: any[], dropped: any[]}} */
|
|
495
|
+
const look = { facts: [], dropped: [] };
|
|
496
|
+
/** @type {string[]} */
|
|
497
|
+
const pageNotChecked = [];
|
|
498
|
+
/** @type {any[]} */
|
|
499
|
+
const pageLooks = [];
|
|
500
|
+
/** @type {Record<string, any>} */
|
|
501
|
+
const pageExtras = pageSources.length ? { look, pageLooks } : {};
|
|
502
|
+
let mapCut = null;
|
|
503
|
+
const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
|
|
504
|
+
const pageInfo = [];
|
|
505
|
+
/** one map call (a page's or a sheet's): its hold, its metering and its book are the drafting round's own (the `kind` names it in the round log) */
|
|
506
|
+
const makeCallModel = (kind) => async (content, attempt) => {
|
|
507
|
+
const spentSoFar = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
508
|
+
if (spentSoFar + ceilingCostUsd(rates, content.length + MAP_SYSTEM.length) > budgetUsd) { mapCut = 'budget'; return { error: 'the draft budget is spent' }; }
|
|
509
|
+
const roundEvents = [];
|
|
510
|
+
const mapLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
|
|
511
|
+
calls += 1;
|
|
512
|
+
book(true);
|
|
513
|
+
let res;
|
|
514
|
+
let threw = null;
|
|
515
|
+
try {
|
|
516
|
+
res = await mapLoop.run([{ role: 'system', content: MAP_SYSTEM }, { role: 'user', content }], [], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: attempt === 1 ? draftThinking : 'on' });
|
|
517
|
+
} catch (err) {
|
|
518
|
+
threw = err;
|
|
519
|
+
if (roundEvents.length === 0) unmetered += 1;
|
|
520
|
+
}
|
|
521
|
+
book(false);
|
|
522
|
+
const entry = { round: log.length + 1, kind };
|
|
523
|
+
if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
|
|
524
|
+
if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
|
|
525
|
+
if (threw) { entry.outcome = `provider-red: ${threw.message}`; log.push(entry); mapCut = 'provider-red'; return { error: threw.message }; }
|
|
526
|
+
const cutOff = res?.stopReason === 'max_tokens';
|
|
527
|
+
entry.outcome = cutOff ? 'truncated' : 'answered';
|
|
528
|
+
log.push(entry);
|
|
529
|
+
if (res?.error && !cutOff) return { error: String(res.error) };
|
|
530
|
+
return { text: res?.text ?? '', cutOff };
|
|
531
|
+
};
|
|
532
|
+
for (const s of pageSources) {
|
|
533
|
+
const pg = pages[s.role];
|
|
534
|
+
// The hold of the map call is sized from its own prompt (the saved page is in it): one that cannot fit what is left of the cap is refused here, at $0.
|
|
535
|
+
const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
|
|
536
|
+
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
537
|
+
if (spentBefore + mapCeiling > budgetUsd) {
|
|
538
|
+
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
|
|
539
|
+
}
|
|
540
|
+
const callModel = makeCallModel('page-map');
|
|
541
|
+
const got = await lookAtPage({ label: s.role, text: pg.text, jobLines, callModel });
|
|
542
|
+
if (!got.ok) {
|
|
543
|
+
const m = sumMeterings(meterings);
|
|
544
|
+
return {
|
|
545
|
+
ok: false, declaration: null, reds: [got.reason], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: mapCut ?? 'page-map', log, thinking: thinkingOf(), inputs: facts.list, questions: [], droppedQuestions: [], notChecked: [], ...pageExtras,
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
// A rule the person left Not checked ("drop it", asked earlier) is served by no fact, whatever this look found for it.
|
|
549
|
+
const keptFacts = got.look.facts.filter((f) => !leftRules.some((l) => l.line === f.line && l.rule === f.forRule));
|
|
550
|
+
look.facts.push(...keptFacts);
|
|
551
|
+
look.dropped.push(...got.look.dropped);
|
|
552
|
+
for (const l of got.notChecked) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
|
|
553
|
+
pageLooks.push({
|
|
554
|
+
role: s.role, address: s.path, sha256: pg.entry.sha256, bytes: pg.entry.bytes, frozen: path.basename(pg.entry.frozen), attempts: got.attempts, mapping: got.mapping,
|
|
555
|
+
});
|
|
556
|
+
pageInfo.push(...pageInfoLines({
|
|
557
|
+
label: s.role, address: s.path, chars: pg.text.length, look: { ...got.look, facts: keptFacts }, notChecked: got.notChecked,
|
|
558
|
+
}));
|
|
559
|
+
}
|
|
560
|
+
// The rules the person left Not checked: one drop each (the one table writes the words), told to the drafter too, so it never claims them.
|
|
561
|
+
if (pageSources.length) {
|
|
562
|
+
/** @type {any[]} */
|
|
563
|
+
const left = [];
|
|
564
|
+
for (const l of leftRules) {
|
|
565
|
+
const jl = jobLines.find((x) => x.n === l.line);
|
|
566
|
+
const text = jl === undefined ? undefined : lineRules(jl)[l.rule - 1];
|
|
567
|
+
if (text !== undefined && !left.some((d) => d.line === l.line && d.rule === l.rule)) left.push({ line: l.line, rule: l.rule, fact: text, reason: 'person-left', source: 'person' });
|
|
568
|
+
}
|
|
569
|
+
if (left.length) {
|
|
570
|
+
look.dropped.push(...left);
|
|
571
|
+
const lines = left.map((d) => leftRuleLine(d.fact));
|
|
572
|
+
for (const x of lines) if (!pageNotChecked.includes(x)) pageNotChecked.push(x);
|
|
573
|
+
pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
// M10 piece 5 (item 7): ONE sheet call per CSV input names the job's own word for each `~` rule; code keeps a word only if it is a real column and finds the column
|
|
577
|
+
// to offer when it is not (src/sheetlook.js). Only when a non-ask job line carries a `~` rule: a CSV job without one is unchanged (no extra call). A signed ask
|
|
578
|
+
// line's own guardrail is a human stop, not a sheet check, so it is not sent. Every round goes through the same hold, metering and book as the page's.
|
|
579
|
+
const askLines = new Set(arbiter.asks.map((a) => a.line));
|
|
580
|
+
const sheetJobLines = jobLines.filter((l) => !askLines.has(l.n));
|
|
581
|
+
// am8 item 3: a .docx's headings stand where a sheet's columns do (a word that is no heading is Not checked, nothing is asked)
|
|
582
|
+
const docxRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && String(s.path).toLowerCase().endsWith('.docx') && Array.isArray(facts.inputFacts[s.role])).map((s) => s.role);
|
|
583
|
+
const sheetRoles = sheetJobLines.some((l) => lineRules(l).length > 0) ? [...Object.keys(facts.sheets ?? {}), ...docxRoles] : [];
|
|
584
|
+
/** @type {any[]} */
|
|
585
|
+
const sheetAsks = [];
|
|
586
|
+
/** @type {any[]} */
|
|
587
|
+
const sheetFacts = [];
|
|
588
|
+
/** @type {any[]} */
|
|
589
|
+
const sheetLooks = [];
|
|
590
|
+
for (const role of sheetRoles) {
|
|
591
|
+
const headings = docxRoles.includes(role) ? facts.inputFacts[role] : undefined;
|
|
592
|
+
const text = headings === undefined ? facts.sheets[role] : '';
|
|
593
|
+
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
594
|
+
const hold = ceilingCostUsd(rates, sheetPrompt({ jobLines: sheetJobLines, label: role, text, headings }).length + MAP_SYSTEM.length);
|
|
595
|
+
if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)]); }
|
|
596
|
+
const got = await lookAtSheet({ label: role, text, headings, jobLines: sheetJobLines, callModel: makeCallModel('sheet-map') });
|
|
597
|
+
if (!got.ok) {
|
|
598
|
+
const m = sumMeterings(meterings);
|
|
599
|
+
return {
|
|
600
|
+
ok: false, declaration: null, reds: [got.reason], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: mapCut ?? 'page-map', log, thinking: thinkingOf(), inputs: facts.list, questions: [], droppedQuestions: [], notChecked: [], ...pageExtras,
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
// The redraft after the answers never asks: an offer the person's words did not take is Not checked, with that reason (never dropped silently).
|
|
604
|
+
const declined = offerQuestions ? [] : got.asks.map((a) => ({ line: a.line, ...(a.rule === null ? {} : { rule: a.rule }), fact: a.word, reason: 'column-declined', other: `"${a.column}"`, source: role }));
|
|
605
|
+
const dropped = [...got.dropped, ...declined];
|
|
606
|
+
sheetAsks.push(...got.asks); // asked only when the asks block below is open (offerQuestions)
|
|
607
|
+
sheetFacts.push(...got.facts);
|
|
608
|
+
sheetLooks.push({ role, attempts: got.attempts, facts: got.facts, asks: got.asks.map((a) => ({ line: a.line, rule: a.rule, word: a.word, column: a.column })), dropped });
|
|
609
|
+
const lost = dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
|
|
610
|
+
for (const l of lost) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
|
|
611
|
+
pageInfo.push(
|
|
612
|
+
...(got.facts.length ? [` Code matched the job's words to the ${headings === undefined ? 'columns' : 'headings'} of "${role}": ${got.facts.map((f) => `line ${f.line}${f.forRule === undefined ? '' : ` rule ${f.forRule}`} is ${headings === undefined ? 'column' : 'heading'} '${f.column}'`).join('; ')}`] : []),
|
|
613
|
+
...(lost.length ? [` Code could not make these a check on "${role}", so they are Not checked; never claim them as checked:`, ...lost.map((l) => ` - ${l}`)] : []),
|
|
614
|
+
);
|
|
615
|
+
}
|
|
616
|
+
if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
|
|
617
|
+
// M10 piece 3 (item 4, am1, am2): CODE decides the early asks from the look, after the one map call and BEFORE any drafting round. A signed ask line's own
|
|
618
|
+
// guardrail is a human stop, not a page check, so it is not asked. More than MAX_LOOK_ASKS is a job to rewrite: nothing is asked, nothing more is spent.
|
|
619
|
+
// The redraft after the answers (offerQuestions false) never asks. A sheet's offers are reading asks: they come first with the page's, in line order.
|
|
620
|
+
if ((pageSources.length || sheetAsks.length) && offerQuestions) {
|
|
621
|
+
const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
|
|
622
|
+
const asks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading')];
|
|
623
|
+
if (asks.length > 0) {
|
|
624
|
+
const m = sumMeterings(meterings);
|
|
625
|
+
const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
|
|
626
|
+
const tooMany = asks.length > MAX_LOOK_ASKS;
|
|
627
|
+
if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
|
|
628
|
+
return {
|
|
629
|
+
ok: false, declaration: null, reds: tooMany ? [`${tooManyAsksText(asks)} Spent so far: ${spent}.`] : [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: tooMany ? 'look-asks-too-many' : 'look-asks', log, thinking: thinkingOf(), inputs: facts.list,
|
|
630
|
+
questions: tooMany ? [] : asks.map((a) => ({
|
|
631
|
+
line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null,
|
|
632
|
+
})),
|
|
633
|
+
droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
// The page lines go on the drafter's list of inputs: the first line of a page's block replaces the plain line readInputFacts wrote for it.
|
|
638
|
+
const factsInfo = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
|
|
639
|
+
|
|
640
|
+
// `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
|
|
641
|
+
const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
|
|
642
|
+
const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
|
|
374
643
|
let structureRetries = 0;
|
|
375
644
|
let revisions = 0;
|
|
376
645
|
let lastReds = [];
|
|
@@ -381,9 +650,7 @@ export async function draft({
|
|
|
381
650
|
let stop = null;
|
|
382
651
|
let failedLines = []; // the job lines try 2's reds named: a question is kept only about one of these (amendment 25)
|
|
383
652
|
/** @type {{questions:{line:number, question:string}[], droppedQuestions:object[], notChecked:string[]}} */
|
|
384
|
-
let extras = { questions: [], droppedQuestions: [], notChecked:
|
|
385
|
-
let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
|
|
386
|
-
let unmetered = 0; // calls that failed with no metering: their cost is unknown
|
|
653
|
+
let extras = { questions: [], droppedQuestions: [], notChecked: pageNotChecked }; // from the round that produced `lastDecl`, never an earlier one
|
|
387
654
|
|
|
388
655
|
for (;;) {
|
|
389
656
|
// Budget: spend so far (an unpriced round counts at its ceiling) + one more
|
|
@@ -411,9 +678,6 @@ export async function draft({
|
|
|
411
678
|
let result;
|
|
412
679
|
let threw = null;
|
|
413
680
|
calls += 1;
|
|
414
|
-
const book = (inFlight) => onBook?.({
|
|
415
|
-
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
416
|
-
});
|
|
417
681
|
book(true);
|
|
418
682
|
try {
|
|
419
683
|
result = await loop.run(
|
|
@@ -492,17 +756,20 @@ export async function draft({
|
|
|
492
756
|
}
|
|
493
757
|
const verdict = validateDeclaration(declaration, {
|
|
494
758
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
759
|
+
// M10 am7 item 1: the words of every cited fact are proved on the drafting copy of the page, against what the page-word map kept
|
|
760
|
+
sheetWords: Object.keys(facts.sheets ?? {}).length ? { headers: Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, parseCsv(t).header])), facts: sheetFacts.filter((f) => f.shape === 'column') } : undefined,
|
|
761
|
+
pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: look.facts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
|
|
495
762
|
});
|
|
496
763
|
lastDecl = declaration;
|
|
497
764
|
const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
|
|
498
|
-
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: cleanNotChecked(rawNotChecked) };
|
|
765
|
+
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...pageNotChecked, ...cleanNotChecked(rawNotChecked).filter((x) => !pageNotChecked.includes(x))] };
|
|
499
766
|
if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
|
|
500
767
|
if (verdict.ok) {
|
|
501
768
|
entry.outcome = 'valid';
|
|
502
769
|
log.push(entry);
|
|
503
770
|
const m = sumMeterings(meterings);
|
|
504
771
|
return {
|
|
505
|
-
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras,
|
|
772
|
+
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras,
|
|
506
773
|
};
|
|
507
774
|
}
|
|
508
775
|
lastReds = [...verdict.reds];
|
|
@@ -524,6 +791,6 @@ export async function draft({
|
|
|
524
791
|
// Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
|
|
525
792
|
// never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
|
|
526
793
|
return {
|
|
527
|
-
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, thinking: thinkingOf(), inputs: facts.list, ...extras,
|
|
794
|
+
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras,
|
|
528
795
|
};
|
|
529
796
|
}
|
package/src/flow.js
CHANGED
|
@@ -273,23 +273,39 @@ export function nextRunId(flowDir) {
|
|
|
273
273
|
|
|
274
274
|
const CLAIM_TRIES = 50;
|
|
275
275
|
|
|
276
|
+
/**
|
|
277
|
+
* The ONE decider of an unnamed run's id: the first `run-<n>` from `from` (default: nextRunId) with nothing by that name (a stray file counts as taken, as
|
|
278
|
+
* `mkdir` EEXIST does). Only LOOKS; `claimRunId` claims it and `canStart` (src/panel/authorstart.js) asks it.
|
|
279
|
+
* @param {string} flowDir @param {number} [from]
|
|
280
|
+
* @returns {{ok:true, runId:string, runDir:string, n:number}|{ok:false, red:string}}
|
|
281
|
+
*/
|
|
282
|
+
export function freeRunId(flowDir, from = Number(nextRunId(flowDir).slice(4))) {
|
|
283
|
+
for (let n = from; n < from + CLAIM_TRIES; n += 1) {
|
|
284
|
+
const runId = `run-${n}`;
|
|
285
|
+
const r = resolveRunDir(flowDir, runId);
|
|
286
|
+
if (!r.ok) return r;
|
|
287
|
+
try { lstatSync(r.runDir); } catch { return { ok: true, runId, runDir: r.runDir, n }; }
|
|
288
|
+
}
|
|
289
|
+
return { ok: false, red: `run: could not claim a run name after ${CLAIM_TRIES} tries` };
|
|
290
|
+
}
|
|
291
|
+
|
|
276
292
|
/**
|
|
277
293
|
* @param {string} flowDir
|
|
278
294
|
* @returns {{ok:true, runId:string, runDir:string}|{ok:false, red:string}}
|
|
279
295
|
*/
|
|
280
296
|
export function claimRunId(flowDir) {
|
|
281
297
|
const runsDir = path.join(flowDir, RUNS_DIR);
|
|
282
|
-
let
|
|
283
|
-
for (let i = 0; i < CLAIM_TRIES; i += 1
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
if (!r.ok) return r;
|
|
298
|
+
let from = Number(nextRunId(flowDir).slice(4));
|
|
299
|
+
for (let i = 0; i < CLAIM_TRIES; i += 1) {
|
|
300
|
+
const f = freeRunId(flowDir, from);
|
|
301
|
+
if (!f.ok) return f;
|
|
287
302
|
try {
|
|
288
303
|
mkdirSync(runsDir, { recursive: true });
|
|
289
|
-
mkdirSync(
|
|
290
|
-
return { ok: true, runId, runDir:
|
|
304
|
+
mkdirSync(f.runDir); // NOT recursive: the exclusive create IS the claim
|
|
305
|
+
return { ok: true, runId: f.runId, runDir: f.runDir };
|
|
291
306
|
} catch (err) {
|
|
292
307
|
if (/** @type {any} */ (err)?.code !== 'EEXIST') return { ok: false, red: `run: could not claim a run name — ${/** @type {Error} */ (err).message}` };
|
|
308
|
+
from = f.n + 1; // taken between the look and the claim
|
|
293
309
|
}
|
|
294
310
|
}
|
|
295
311
|
return { ok: false, red: `run: could not claim a run name after ${CLAIM_TRIES} tries` };
|
|
@@ -1053,3 +1069,13 @@ export function suggestFlowName(root, name) {
|
|
|
1053
1069
|
if (!taken(candidate)) return candidate;
|
|
1054
1070
|
}
|
|
1055
1071
|
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* M10: take back the drafting copies of web pages (`files`) a draft froze into `dir` when the draft is then refused at $0, and the folder itself once it is
|
|
1075
|
+
* empty. Only the files named are removed; a folder holding anything else is left.
|
|
1076
|
+
* @param {string} dir @param {string[]} files
|
|
1077
|
+
*/
|
|
1078
|
+
export function removeFrozenPages(dir, files) {
|
|
1079
|
+
for (const f of files) { try { rmSync(f, { force: true }); } catch { /* best-effort */ } }
|
|
1080
|
+
try { if (readdirSync(dir).length === 0) rmSync(dir, { recursive: true, force: true }); } catch { /* not there */ }
|
|
1081
|
+
}
|
package/src/flowmodel.js
CHANGED
|
@@ -11,20 +11,78 @@ export const MODEL_FILE = 'model.json';
|
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* @param {string} dir a draft folder or a flow folder
|
|
14
|
-
*
|
|
14
|
+
* M4d am25: `thinking: true` is the Chat "Thinking on" box as it was when the job was signed; the key is absent when the box was off.
|
|
15
|
+
* @returns {{ slot: string, model: string, thinking?: true }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
|
|
15
16
|
*/
|
|
16
17
|
export function readModelRecord(dir) {
|
|
17
18
|
const r = readFileInside(dir, MODEL_FILE);
|
|
18
19
|
if (!r.ok) return null;
|
|
19
20
|
try {
|
|
20
21
|
const j = JSON.parse(r.text);
|
|
21
|
-
return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
|
|
22
|
+
return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model, ...(j.thinking === true ? { thinking: true } : {}) } : null;
|
|
22
23
|
} catch { return null; }
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
|
-
* Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
|
|
27
|
+
* Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string, thinking?: boolean }} pick
|
|
28
|
+
*/
|
|
29
|
+
export function writeModelRecord(dir, { slot, model, thinking }) {
|
|
30
|
+
writeOnce(join(dir, MODEL_FILE), { slot, model, ...(thinking === true ? { thinking: true } : {}) });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The one file write of this module: JSON, 0600, never over an existing file. */
|
|
34
|
+
function writeOnce(file, obj) {
|
|
35
|
+
writeFileSync(file, `${JSON.stringify(obj, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** M4d am25: the file in a run's folder that keeps the box as the run started with it (outside `job/`, which holds the three signed files only). */
|
|
39
|
+
export const RUN_THINKING_FILE = 'thinking.json';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* M4d am25: the ONE reader of the job's "Thinking on" box for a run. A run reads its OWN record (`<run>/thinking.json`, written once when the run
|
|
43
|
+
* started) when it has one; otherwise the flow folder's `model.json`. No record, an unreadable one, or one without `thinking` is box OFF: a job
|
|
44
|
+
* signed before am25 stored nothing, and it must not start thinking on every try.
|
|
45
|
+
* @param {string} flowDir @param {string|null} runDir @returns {boolean}
|
|
27
46
|
*/
|
|
28
|
-
export function
|
|
29
|
-
|
|
47
|
+
export function readJobThinking(flowDir, runDir) {
|
|
48
|
+
return readRunThinking(runDir) ?? (readModelRecord(flowDir)?.thinking === true);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* M4d am26: the run's OWN record of the box (`<run>/thinking.json`) and nothing else: `true`/`false`, or `null` when the run has none (a run from before am25).
|
|
53
|
+
* An unreadable record is box off, as `readJobThinking` has always read it. @param {string|null} runDir @returns {boolean|null}
|
|
54
|
+
*/
|
|
55
|
+
export function readRunThinking(runDir) {
|
|
56
|
+
const own = typeof runDir === 'string' ? readFileInside(runDir, RUN_THINKING_FILE) : null;
|
|
57
|
+
if (!own?.ok) return null;
|
|
58
|
+
try { return JSON.parse(own.text)?.thinking === true; } catch { return false; }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* M4d am25: a run keeps the box as the job had it when the run started (write-once, so an Edit of the job never changes a run already going).
|
|
63
|
+
* Written for every fresh run, ticked or not. @param {string} flowDir @param {string} runDir
|
|
64
|
+
*/
|
|
65
|
+
export function writeRunThinking(flowDir, runDir) {
|
|
66
|
+
writeOnce(join(runDir, RUN_THINKING_FILE), { thinking: readModelRecord(flowDir)?.thinking === true });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** M4d am33: the file in a run's folder that records the model the run STARTED on (write-once; every continue path keeps it). */
|
|
70
|
+
export const RUN_MODEL_FILE = 'run-model.json';
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* M4d am33: the ONE reader of the model a run started on, or null (a run from before the record, or an unusable one: the caller then keeps today's pick).
|
|
74
|
+
* @param {string|null} runDir @returns {{ slot: string, model: string }|null}
|
|
75
|
+
*/
|
|
76
|
+
export function readRunModel(runDir) {
|
|
77
|
+
const r = typeof runDir === 'string' ? readFileInside(runDir, RUN_MODEL_FILE) : null;
|
|
78
|
+
if (!r?.ok) return null;
|
|
79
|
+
try {
|
|
80
|
+
const j = JSON.parse(r.text);
|
|
81
|
+
return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
|
|
82
|
+
} catch { return null; }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** M4d am33: the ONE writer, called once when a fresh run starts (`runFlow`); never over an existing record. @param {string} runDir @param {{ slot: string, model: string }} pick */
|
|
86
|
+
export function writeRunModel(runDir, { slot, model }) {
|
|
87
|
+
writeOnce(join(runDir, RUN_MODEL_FILE), { slot, model });
|
|
30
88
|
}
|