fwdloop 0.21.0 → 0.23.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/bin/fwdloop +85 -34
- package/package.json +4 -3
- package/src/ask.js +20 -4
- package/src/audit-fold.js +5 -1
- package/src/authoring.js +36 -6
- package/src/canrun.js +5 -0
- package/src/checked.js +32 -4
- package/src/cited-record.js +138 -0
- package/src/cited-source.js +49 -0
- package/src/citedcheck.js +321 -0
- package/src/citedwords.js +197 -0
- package/src/closers.js +37 -198
- package/src/csv.js +69 -12
- package/src/ctx-tools.js +2 -14
- package/src/declaration.js +143 -5
- package/src/diary.js +2 -2
- package/src/docx.js +16 -2
- package/src/draft-steps.js +1 -1
- package/src/drafter.js +322 -33
- package/src/flow.js +33 -7
- package/src/flowmodel.js +21 -0
- package/src/input-facts.js +20 -3
- package/src/model-step.js +38 -21
- 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 +43 -21
- package/src/panel/authorcard.js +20 -3
- 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 +102 -6
- package/src/panel/index.html +321 -12
- package/src/panel/result.js +301 -0
- package/src/panel/server.js +27 -3
- package/src/primitives.js +2 -3
- package/src/provider.js +5 -2
- package/src/redact.js +17 -0
- package/src/runner.js +102 -14
- package/src/schedule.js +3 -3
- package/src/setup.js +16 -1
- package/src/sheet-record.js +57 -0
- package/src/sheetblock.js +170 -0
- package/src/sheetchecks.js +206 -0
- package/src/sheetclaims.js +78 -0
- package/src/sheetfind.js +50 -0
- package/src/sheetlook.js +157 -0
- package/src/sheetoffer.js +125 -0
- package/src/sheetrun.js +105 -0
- package/src/signed-text.js +11 -1
- package/src/thinking.js +1 -1
- package/src/try-checks.js +12 -0
- package/src/types.js +4 -11
- package/types/ask.d.ts +2 -1
- package/types/authoring.d.ts +19 -2
- package/types/checked.d.ts +19 -3
- 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 +37 -10
- package/types/csv.d.ts +25 -4
- package/types/ctx-tools.d.ts +0 -1
- package/types/declaration.d.ts +20 -1
- package/types/docx.d.ts +14 -0
- package/types/drafter.d.ts +264 -8
- package/types/flow.d.ts +21 -0
- package/types/flowmodel.d.ts +15 -0
- package/types/input-facts.d.ts +12 -2
- package/types/model-step.d.ts +40 -19
- 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 +4 -1
- 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 +162 -9
- package/types/schedule.d.ts +0 -11
- package/types/setup.d.ts +13 -0
- package/types/sheet-record.d.ts +24 -0
- package/types/sheetblock.d.ts +116 -0
- package/types/sheetchecks.d.ts +70 -0
- package/types/sheetclaims.d.ts +26 -0
- package/types/sheetfind.d.ts +46 -0
- package/types/sheetlook.d.ts +120 -0
- package/types/sheetoffer.d.ts +25 -0
- package/types/sheetrun.d.ts +35 -0
- package/types/thinking.d.ts +1 -1
- package/types/types.d.ts +27 -14
package/src/drafter.js
CHANGED
|
@@ -22,7 +22,19 @@ 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, sheetTable } from './csv.js';
|
|
36
|
+
import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
|
|
37
|
+
import { uncoveredRules } from './sheetblock.js';
|
|
26
38
|
import {
|
|
27
39
|
makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
|
|
28
40
|
} from './provider.js';
|
|
@@ -40,6 +52,73 @@ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
|
|
|
40
52
|
/** The whole-output-ceiling rule, told once to the drafter (schema and prompt use this string). Amendment 29; no number words (am25). */
|
|
41
53
|
export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
|
|
42
54
|
|
|
55
|
+
/** @param {any[]|undefined} sources @returns {string[]} the roles of the document inputs (.docx / .md / .txt) */
|
|
56
|
+
const docRolesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'file' && DOC_EXTS.some((x) => String(s.path).toLowerCase().endsWith(x))).map((s) => s.role);
|
|
57
|
+
|
|
58
|
+
/** the document inputs a quote can come from (M10 piece 5, item 2) */
|
|
59
|
+
const DOC_EXTS = Object.freeze(['.docx', '.md', '.txt']);
|
|
60
|
+
|
|
61
|
+
/** M10 am8 item 2: the column lock of a green step that reads a CSV input (`close.columns`): the exact header(s) its values come from. */
|
|
62
|
+
const COLUMNS_PROP = Object.freeze({
|
|
63
|
+
type: 'array',
|
|
64
|
+
minItems: 1,
|
|
65
|
+
maxItems: 10,
|
|
66
|
+
description: "only on a green step that reads a CSV input: the exact column names (the sheet's header) its values come from. Omit on any other step",
|
|
67
|
+
items: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
properties: {
|
|
70
|
+
source: { type: 'string', description: 'the role of the CSV input (also in the step\'s reads)' },
|
|
71
|
+
column: { type: 'string', description: "the column's name, copied exactly from the sheet's header" },
|
|
72
|
+
},
|
|
73
|
+
required: ['source', 'column'],
|
|
74
|
+
additionalProperties: false,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
/** 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. */
|
|
79
|
+
const CITED_PROP = Object.freeze({
|
|
80
|
+
type: 'object',
|
|
81
|
+
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',
|
|
82
|
+
properties: {
|
|
83
|
+
source: { type: 'string', description: "the role of the web page input the quotes come from (also in the step's reads)" },
|
|
84
|
+
facts: {
|
|
85
|
+
type: 'array',
|
|
86
|
+
minItems: 1,
|
|
87
|
+
maxItems: 10,
|
|
88
|
+
description: 'one fact per thing a result must hold; at most 10',
|
|
89
|
+
items: {
|
|
90
|
+
type: 'object',
|
|
91
|
+
properties: {
|
|
92
|
+
name: { type: 'string', description: 'letters and spaces only, no digits' },
|
|
93
|
+
shape: { type: 'string', enum: ['money', 'number', 'date', 'time', 'phrase', 'text'] },
|
|
94
|
+
unit: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: the words the page writes after the amount, copied from the page' },
|
|
95
|
+
currency: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: $, € or £' },
|
|
96
|
+
phrase: { type: 'string', description: 'phrase only: the fixed words every result must say, copied from the page' },
|
|
97
|
+
anchor: { type: 'string', description: 'the label right before the value, picked from the kept labels listed under Inputs; never typed' },
|
|
98
|
+
until: { type: 'string', description: 'text only: the words that close the value' },
|
|
99
|
+
rule: {
|
|
100
|
+
type: 'object',
|
|
101
|
+
description: 'under (lt, lte), over (gt, gte) or between: only a number that is in the person\'s own words on the job line',
|
|
102
|
+
properties: { op: { type: 'string', enum: ['lt', 'lte', 'gt', 'gte', 'between'] }, value: {}, lo: {}, hi: {} },
|
|
103
|
+
required: ['op'],
|
|
104
|
+
additionalProperties: false,
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
required: ['name', 'shape'],
|
|
108
|
+
additionalProperties: false,
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
count: {
|
|
112
|
+
type: 'object',
|
|
113
|
+
description: 'how many results the job line asks for ("List 3" is min 3, max 3)',
|
|
114
|
+
properties: { min: { type: 'integer', minimum: 1 }, max: { type: 'integer', minimum: 1 } },
|
|
115
|
+
additionalProperties: false,
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
required: ['source', 'facts'],
|
|
119
|
+
additionalProperties: false,
|
|
120
|
+
});
|
|
121
|
+
|
|
43
122
|
const SHAPE_PROPS = Object.freeze({
|
|
44
123
|
maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
|
|
45
124
|
sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
|
|
@@ -47,8 +126,13 @@ const SHAPE_PROPS = Object.freeze({
|
|
|
47
126
|
mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
|
|
48
127
|
});
|
|
49
128
|
|
|
50
|
-
/**
|
|
51
|
-
|
|
129
|
+
/**
|
|
130
|
+
* The forced tool's parameter schema. `menu` = wiredMenu(). `sheets` (M10b piece 3, optional) = the drafting copy's table of each CSV input role: with it a step may carry
|
|
131
|
+
* `close.sheet`, and every column a check names is an enum of that sheet's exact header (src/sheetoffer.js); without it (no CSV input) no sheet property exists.
|
|
132
|
+
* @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>}} [o]
|
|
133
|
+
*/
|
|
134
|
+
export function buildDeclarationSchema(menu, { sheets } = {}) {
|
|
135
|
+
const sheetProp = sheets ? sheetChecksProp(sheets) : null;
|
|
52
136
|
const shapeProps = {};
|
|
53
137
|
for (const key of SHAPE_KEYS) {
|
|
54
138
|
if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
|
|
@@ -86,6 +170,9 @@ export function buildDeclarationSchema(menu) {
|
|
|
86
170
|
additionalProperties: false,
|
|
87
171
|
description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
|
|
88
172
|
},
|
|
173
|
+
cited: CITED_PROP,
|
|
174
|
+
columns: COLUMNS_PROP,
|
|
175
|
+
...(sheetProp ? { sheet: sheetProp } : {}),
|
|
89
176
|
},
|
|
90
177
|
required: ['class'],
|
|
91
178
|
additionalProperties: false,
|
|
@@ -129,7 +216,7 @@ export const MAX_QUESTIONS = 2;
|
|
|
129
216
|
|
|
130
217
|
/** What fwdloop's typed checks can really check (bareloop F174: give the model the real list, or "Not checked" is invented). */
|
|
131
218
|
export const CHECKABLE = Object.freeze([
|
|
132
|
-
'green: a figure
|
|
219
|
+
'green: a sheet figure is recomputed by bareguard from the saved sheet',
|
|
133
220
|
'softgreen: the output carries named section headings (sections), in order',
|
|
134
221
|
`softgreen: a word ceiling for the whole output (maxWords; ${WHOLE_OUTPUT_CEILING_RULE}) and per section (wordsPerSection)`,
|
|
135
222
|
'softgreen: a line count per invoice (linesPerInvoice) and fields every line must carry (mustCarry)',
|
|
@@ -152,8 +239,9 @@ export const QUESTIONS_PROMPT = [
|
|
|
152
239
|
].join('\n');
|
|
153
240
|
|
|
154
241
|
/** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
|
|
155
|
-
|
|
156
|
-
|
|
242
|
+
/** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined}} [o] */
|
|
243
|
+
export function buildRoundSchema(menu, { questions = false, sheets = undefined } = {}) {
|
|
244
|
+
const s = buildDeclarationSchema(menu, { sheets });
|
|
157
245
|
const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
|
|
158
246
|
if (questions) {
|
|
159
247
|
extra.questions = {
|
|
@@ -219,13 +307,31 @@ function jobLinesText(lines, asks) {
|
|
|
219
307
|
.join('\n');
|
|
220
308
|
}
|
|
221
309
|
|
|
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.
|
|
310
|
+
/** M4d amendment 8: the green step must read an input with cells, so the drafter is told the rule and which inputs have cells.
|
|
311
|
+
* 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
312
|
function greenReadRule(sources) {
|
|
224
313
|
const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
314
|
+
const pageRoles = (sources ?? []).filter((s) => s.kind === 'page').map((s) => s.role);
|
|
315
|
+
// M10 piece 5 (item 2): a quote in a doc - a .docx / .md / .txt input is quoted the way a page is
|
|
316
|
+
const docRoles = docRolesOf(sources);
|
|
317
|
+
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 checked against its sheet; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
|
|
318
|
+
const out = [csvRoles.length
|
|
319
|
+
? `${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 values come from. Where the Inputs list says a line "is column 'X'", that line's step must name that column. A step that has close.sheet is not held to close.columns by a word that merely matches a header (such as a bucket name); but when a line carries a rule "use the column 'X' for ...", at least one of that line's close.sheet checks must use that column. Leave close.columns out when the line names no column.`
|
|
320
|
+
: `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl"${pageRoles.length ? ' (unless it is about a web page, below)' : ''}.`];
|
|
321
|
+
if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
|
|
322
|
+
if (pageRoles.length || docRoles.length) {
|
|
323
|
+
out.push(
|
|
324
|
+
`- ${[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.`,
|
|
325
|
+
'- 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).',
|
|
326
|
+
'- 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.',
|
|
327
|
+
'- 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.',
|
|
328
|
+
'- 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.',
|
|
329
|
+
'- 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.',
|
|
330
|
+
'- 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.',
|
|
331
|
+
...(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.'] : []),
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
return out;
|
|
229
335
|
}
|
|
230
336
|
|
|
231
337
|
/** M7 piece 6 (signed scope item 1): a granted verb ships WITH the line that says when to reach for it, or the
|
|
@@ -243,6 +349,14 @@ function whenToUse(menu) {
|
|
|
243
349
|
return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
|
|
244
350
|
}
|
|
245
351
|
|
|
352
|
+
/** M10b piece 3: with a CSV input, the guardrail rules of each line by number (the numbers `covers` names), in the order the validator counts them. Otherwise nothing. */
|
|
353
|
+
function sheetRuleNumbers(lines, arbiter) {
|
|
354
|
+
const csvRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path));
|
|
355
|
+
if (csvRoles.length === 0) return [];
|
|
356
|
+
const rows = lines.map((l) => ({ n: l.n, rules: lineRules(l.guardrail ? { rule: l.guardrail } : {}) })).filter((x) => x.rules.length > 0);
|
|
357
|
+
return rows.length === 0 ? [] : ['', 'The guardrail rules by number (what "covers" counts):', ...rows.map((x) => `- line ${x.n}: ${x.rules.map((r, i) => `${i + 1}) ${r}`).join(' ')}`)];
|
|
358
|
+
}
|
|
359
|
+
|
|
246
360
|
export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
247
361
|
const askLines = arbiter.asks.map((a) => a.line);
|
|
248
362
|
const sendLines = arbiter.sends.map((s) => s.line);
|
|
@@ -256,7 +370,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
256
370
|
'Rules:',
|
|
257
371
|
'- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
|
|
258
372
|
'- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
|
|
259
|
-
'- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must
|
|
373
|
+
'- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must be checkable against its source: a sheet figure by the bareguard checks of the sheet), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
|
|
260
374
|
'- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
|
|
261
375
|
...greenReadRule(arbiter.sources),
|
|
262
376
|
'- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
|
|
@@ -272,6 +386,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
272
386
|
'',
|
|
273
387
|
'The numbered job lines:',
|
|
274
388
|
jobLinesText(lines, arbiter.asks),
|
|
389
|
+
...sheetRuleNumbers(lines, arbiter),
|
|
275
390
|
].join('\n');
|
|
276
391
|
}
|
|
277
392
|
|
|
@@ -304,11 +419,14 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
|
|
|
304
419
|
*
|
|
305
420
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
306
421
|
* 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}[]
|
|
422
|
+
* questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
|
|
423
|
+
* look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
|
|
424
|
+
* `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
425
|
*/
|
|
309
426
|
export async function draft({
|
|
310
427
|
proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
311
428
|
priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
|
|
429
|
+
draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
|
|
312
430
|
}) {
|
|
313
431
|
// 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
432
|
const thinkingOf = () => {
|
|
@@ -331,8 +449,9 @@ export async function draft({
|
|
|
331
449
|
const sumReds = checkGuardrailSums(lines);
|
|
332
450
|
if (sumReds.length) return fail(sumReds);
|
|
333
451
|
const menu = wiredMenu(skills);
|
|
334
|
-
|
|
335
|
-
|
|
452
|
+
// 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).
|
|
453
|
+
const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
|
|
454
|
+
if (!fileFacts.ok) return fail(fileFacts.reds);
|
|
336
455
|
|
|
337
456
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
338
457
|
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
@@ -346,9 +465,6 @@ export async function draft({
|
|
|
346
465
|
}
|
|
347
466
|
}
|
|
348
467
|
|
|
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
468
|
const lineNums = lines.map((l) => l.n);
|
|
353
469
|
// Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
|
|
354
470
|
const cat = loadCatalogue();
|
|
@@ -362,15 +478,189 @@ export async function draft({
|
|
|
362
478
|
// 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
479
|
const priorUsd = typeof priorSpend === 'function' ? priorSpend(roundCeiling) : 0;
|
|
364
480
|
const budgetUsd = arbiter.capUsd - priorUsd;
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
}
|
|
481
|
+
/** the refusal when one round held at `ceiling` does not fit what is left of the cap (the drafter's own words, one place) */
|
|
482
|
+
const tooSmall = (ceiling) => (priorUsd > 0
|
|
483
|
+
? `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.`
|
|
484
|
+
: capTooSmallText('drafting', arbiter.capUsd, ceiling, modelId));
|
|
485
|
+
if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)]);
|
|
371
486
|
|
|
372
487
|
const meterings = [];
|
|
373
488
|
const log = [];
|
|
489
|
+
let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
|
|
490
|
+
let unmetered = 0; // calls that failed with no metering: their cost is unknown
|
|
491
|
+
const book = (inFlight) => onBook?.({
|
|
492
|
+
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
// 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
|
|
496
|
+
// (`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.
|
|
497
|
+
const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page');
|
|
498
|
+
/** @type {Record<string, {text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}>} */
|
|
499
|
+
const pages = {};
|
|
500
|
+
if (pageSources.length) {
|
|
501
|
+
if (typeof draftDir !== 'string' || draftDir === '') return fail(['draft: a web page input needs a folder to keep its drafting copy']);
|
|
502
|
+
for (const s of pageSources) {
|
|
503
|
+
const fr = await freezePage(draftDir, s.role, s.path, { fetchPage });
|
|
504
|
+
if (!fr.ok) { removeFrozenPages(draftDir, Object.values(pages).map((pg) => pg.entry.frozen)); return fail([fr.red]); }
|
|
505
|
+
pages[s.role] = { text: fr.text, entry: fr.entry };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const facts = readInputFacts(arbiter.sources, { pages });
|
|
509
|
+
if (!facts.ok) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((pg) => pg.entry.frozen)); return fail(facts.reds); }
|
|
510
|
+
|
|
511
|
+
// 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
|
|
512
|
+
// same metering and book as a drafting round, so a pre-send throw from the book stops here with nothing spent.
|
|
513
|
+
/** @type {{facts: any[], dropped: any[]}} */
|
|
514
|
+
const look = { facts: [], dropped: [] };
|
|
515
|
+
/** @type {string[]} */
|
|
516
|
+
const pageNotChecked = [];
|
|
517
|
+
/** @type {any[]} */
|
|
518
|
+
const pageLooks = [];
|
|
519
|
+
/** @type {Record<string, any>} */
|
|
520
|
+
const pageExtras = pageSources.length ? { look, pageLooks } : {};
|
|
521
|
+
let mapCut = null;
|
|
522
|
+
const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
|
|
523
|
+
const pageInfo = [];
|
|
524
|
+
/** 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) */
|
|
525
|
+
const makeCallModel = (kind) => async (content, attempt) => {
|
|
526
|
+
const spentSoFar = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
527
|
+
if (spentSoFar + ceilingCostUsd(rates, content.length + MAP_SYSTEM.length) > budgetUsd) { mapCut = 'budget'; return { error: 'the draft budget is spent' }; }
|
|
528
|
+
const roundEvents = [];
|
|
529
|
+
const mapLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
|
|
530
|
+
calls += 1;
|
|
531
|
+
book(true);
|
|
532
|
+
let res;
|
|
533
|
+
let threw = null;
|
|
534
|
+
try {
|
|
535
|
+
res = await mapLoop.run([{ role: 'system', content: MAP_SYSTEM }, { role: 'user', content }], [], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: attempt === 1 ? draftThinking : 'on' });
|
|
536
|
+
} catch (err) {
|
|
537
|
+
threw = err;
|
|
538
|
+
if (roundEvents.length === 0) unmetered += 1;
|
|
539
|
+
}
|
|
540
|
+
book(false);
|
|
541
|
+
const entry = { round: log.length + 1, kind };
|
|
542
|
+
if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
|
|
543
|
+
if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
|
|
544
|
+
if (threw) { entry.outcome = `provider-red: ${threw.message}`; log.push(entry); mapCut = 'provider-red'; return { error: threw.message }; }
|
|
545
|
+
const cutOff = res?.stopReason === 'max_tokens';
|
|
546
|
+
entry.outcome = cutOff ? 'truncated' : 'answered';
|
|
547
|
+
log.push(entry);
|
|
548
|
+
if (res?.error && !cutOff) return { error: String(res.error) };
|
|
549
|
+
return { text: res?.text ?? '', cutOff };
|
|
550
|
+
};
|
|
551
|
+
for (const s of pageSources) {
|
|
552
|
+
const pg = pages[s.role];
|
|
553
|
+
// 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.
|
|
554
|
+
const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
|
|
555
|
+
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
556
|
+
if (spentBefore + mapCeiling > budgetUsd) {
|
|
557
|
+
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
|
|
558
|
+
}
|
|
559
|
+
const callModel = makeCallModel('page-map');
|
|
560
|
+
const got = await lookAtPage({ label: s.role, text: pg.text, jobLines, callModel });
|
|
561
|
+
if (!got.ok) {
|
|
562
|
+
const m = sumMeterings(meterings);
|
|
563
|
+
return {
|
|
564
|
+
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,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
// A rule the person left Not checked ("drop it", asked earlier) is served by no fact, whatever this look found for it.
|
|
568
|
+
const keptFacts = got.look.facts.filter((f) => !leftRules.some((l) => l.line === f.line && l.rule === f.forRule));
|
|
569
|
+
look.facts.push(...keptFacts);
|
|
570
|
+
look.dropped.push(...got.look.dropped);
|
|
571
|
+
for (const l of got.notChecked) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
|
|
572
|
+
pageLooks.push({
|
|
573
|
+
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,
|
|
574
|
+
});
|
|
575
|
+
pageInfo.push(...pageInfoLines({
|
|
576
|
+
label: s.role, address: s.path, chars: pg.text.length, look: { ...got.look, facts: keptFacts }, notChecked: got.notChecked,
|
|
577
|
+
}));
|
|
578
|
+
}
|
|
579
|
+
// 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.
|
|
580
|
+
if (pageSources.length) {
|
|
581
|
+
/** @type {any[]} */
|
|
582
|
+
const left = [];
|
|
583
|
+
for (const l of leftRules) {
|
|
584
|
+
const jl = jobLines.find((x) => x.n === l.line);
|
|
585
|
+
const text = jl === undefined ? undefined : lineRules(jl)[l.rule - 1];
|
|
586
|
+
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' });
|
|
587
|
+
}
|
|
588
|
+
if (left.length) {
|
|
589
|
+
look.dropped.push(...left);
|
|
590
|
+
const lines = left.map((d) => leftRuleLine(d.fact));
|
|
591
|
+
for (const x of lines) if (!pageNotChecked.includes(x)) pageNotChecked.push(x);
|
|
592
|
+
pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
// 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
|
|
596
|
+
// 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
|
|
597
|
+
// 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.
|
|
598
|
+
const askLines = new Set(arbiter.asks.map((a) => a.line));
|
|
599
|
+
const sheetJobLines = jobLines.filter((l) => !askLines.has(l.n));
|
|
600
|
+
// 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)
|
|
601
|
+
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);
|
|
602
|
+
const sheetRoles = sheetJobLines.some((l) => lineRules(l).length > 0) ? [...Object.keys(facts.sheets ?? {}), ...docxRoles] : [];
|
|
603
|
+
/** @type {any[]} */
|
|
604
|
+
const sheetAsks = [];
|
|
605
|
+
/** @type {any[]} */
|
|
606
|
+
const sheetFacts = [];
|
|
607
|
+
/** @type {any[]} */
|
|
608
|
+
const sheetLooks = [];
|
|
609
|
+
for (const role of sheetRoles) {
|
|
610
|
+
const headings = docxRoles.includes(role) ? facts.inputFacts[role] : undefined;
|
|
611
|
+
const text = headings === undefined ? facts.sheets[role] : '';
|
|
612
|
+
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
613
|
+
const hold = ceilingCostUsd(rates, sheetPrompt({ jobLines: sheetJobLines, label: role, text, headings }).length + MAP_SYSTEM.length);
|
|
614
|
+
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)]); }
|
|
615
|
+
const got = await lookAtSheet({ label: role, text, headings, jobLines: sheetJobLines, callModel: makeCallModel('sheet-map') });
|
|
616
|
+
if (!got.ok) {
|
|
617
|
+
const m = sumMeterings(meterings);
|
|
618
|
+
return {
|
|
619
|
+
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,
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
// 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).
|
|
623
|
+
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 }));
|
|
624
|
+
const dropped = [...got.dropped, ...declined];
|
|
625
|
+
sheetAsks.push(...got.asks); // asked only when the asks block below is open (offerQuestions)
|
|
626
|
+
sheetFacts.push(...got.facts);
|
|
627
|
+
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 });
|
|
628
|
+
const lost = dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
|
|
629
|
+
for (const l of lost) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
|
|
630
|
+
pageInfo.push(
|
|
631
|
+
...(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('; ')}`] : []),
|
|
632
|
+
...(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}`)] : []),
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
|
|
636
|
+
// 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
|
|
637
|
+
// 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.
|
|
638
|
+
// 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.
|
|
639
|
+
if ((pageSources.length || sheetAsks.length) && offerQuestions) {
|
|
640
|
+
const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
|
|
641
|
+
const asks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading')];
|
|
642
|
+
if (asks.length > 0) {
|
|
643
|
+
const m = sumMeterings(meterings);
|
|
644
|
+
const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
|
|
645
|
+
const tooMany = asks.length > MAX_LOOK_ASKS;
|
|
646
|
+
if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
|
|
647
|
+
return {
|
|
648
|
+
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,
|
|
649
|
+
questions: tooMany ? [] : asks.map((a) => ({
|
|
650
|
+
line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null,
|
|
651
|
+
})),
|
|
652
|
+
droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
// 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.
|
|
657
|
+
const factsInfo = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
|
|
658
|
+
|
|
659
|
+
// `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
|
|
660
|
+
// M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
|
|
661
|
+
const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
|
|
662
|
+
const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
|
|
663
|
+
const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
|
|
374
664
|
let structureRetries = 0;
|
|
375
665
|
let revisions = 0;
|
|
376
666
|
let lastReds = [];
|
|
@@ -381,9 +671,7 @@ export async function draft({
|
|
|
381
671
|
let stop = null;
|
|
382
672
|
let failedLines = []; // the job lines try 2's reds named: a question is kept only about one of these (amendment 25)
|
|
383
673
|
/** @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
|
|
674
|
+
let extras = { questions: [], droppedQuestions: [], notChecked: pageNotChecked }; // from the round that produced `lastDecl`, never an earlier one
|
|
387
675
|
|
|
388
676
|
for (;;) {
|
|
389
677
|
// Budget: spend so far (an unpriced round counts at its ceiling) + one more
|
|
@@ -397,7 +685,7 @@ export async function draft({
|
|
|
397
685
|
// Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
|
|
398
686
|
// validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
|
|
399
687
|
const askOpen = offerQuestions && revisions === MAX_REVISIONS;
|
|
400
|
-
const schema = buildRoundSchema(menu, { questions: askOpen });
|
|
688
|
+
const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables });
|
|
401
689
|
const tool = {
|
|
402
690
|
name: TOOL,
|
|
403
691
|
description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
|
|
@@ -411,9 +699,6 @@ export async function draft({
|
|
|
411
699
|
let result;
|
|
412
700
|
let threw = null;
|
|
413
701
|
calls += 1;
|
|
414
|
-
const book = (inFlight) => onBook?.({
|
|
415
|
-
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
416
|
-
});
|
|
417
702
|
book(true);
|
|
418
703
|
try {
|
|
419
704
|
result = await loop.run(
|
|
@@ -490,19 +775,23 @@ export async function draft({
|
|
|
490
775
|
return { ...st, close: { ...st.close, shape: per === null ? shape : { ...shape, wordsPerSection: per } } };
|
|
491
776
|
});
|
|
492
777
|
}
|
|
778
|
+
// M10b piece 4: `covers` (which ~ rules a check verifies) stays on the check and is signed; the validator checks it, the plan card shows it
|
|
493
779
|
const verdict = validateDeclaration(declaration, {
|
|
494
780
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
781
|
+
// 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
|
|
782
|
+
sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column'), tables: sheetTables } : undefined,
|
|
783
|
+
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
784
|
});
|
|
496
785
|
lastDecl = declaration;
|
|
497
786
|
const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
|
|
498
|
-
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: cleanNotChecked(rawNotChecked) };
|
|
787
|
+
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...cleanNotChecked(rawNotChecked), ...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}))])] };
|
|
499
788
|
if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
|
|
500
789
|
if (verdict.ok) {
|
|
501
790
|
entry.outcome = 'valid';
|
|
502
791
|
log.push(entry);
|
|
503
792
|
const m = sumMeterings(meterings);
|
|
504
793
|
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,
|
|
794
|
+
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
795
|
};
|
|
507
796
|
}
|
|
508
797
|
lastReds = [...verdict.reds];
|
|
@@ -524,6 +813,6 @@ export async function draft({
|
|
|
524
813
|
// Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
|
|
525
814
|
// never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
|
|
526
815
|
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,
|
|
816
|
+
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
817
|
};
|
|
529
818
|
}
|
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
|
@@ -65,3 +65,24 @@ export function readRunThinking(runDir) {
|
|
|
65
65
|
export function writeRunThinking(flowDir, runDir) {
|
|
66
66
|
writeOnce(join(runDir, RUN_THINKING_FILE), { thinking: readModelRecord(flowDir)?.thinking === true });
|
|
67
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 });
|
|
88
|
+
}
|