fwdloop 0.7.0 → 0.8.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/src/drafter.js ADDED
@@ -0,0 +1,324 @@
1
+ // borrowed-from: fwdloop poc/m6a/schema.mjs + poc/m6a/draft.mjs@867c25b (M6a POC, bar met 20/20).
2
+ //
3
+ // M6a — the drafter. One forced tool call (`emit_declaration`, toolChoice by
4
+ // name) whose schema is derived from the wired menu (src/primitives.js
5
+ // wiredMenu, over src/catalogue.json) and src/declaration.js SHAPE_KEYS. The
6
+ // model's args, plus the harness's mechanical `inputFacts`, ARE the src
7
+ // declaration — no converter. validateDeclaration decides pass/fail, with the
8
+ // full catalogue and the WIRED_VERBS set, so an unwired verb reds by name.
9
+ //
10
+ // Rounds: 1 first draft + up to MAX_STRUCTURE_RETRIES when the round gave no
11
+ // usable tool call (malformed JSON, text instead, truncation) + up to
12
+ // MAX_REVISIONS when the validator reds (the reds are fed back verbatim).
13
+ // Every round is metered through Loop's onLlmResult; the tool body throws
14
+ // HaltError after capturing so no second (paid) "wrap-up" round happens.
15
+ // Unknown cost is never 0: sumMeterings gives null, and the budget check
16
+ // prices an unpriced round at the ceiling.
17
+
18
+ import { Loop, HaltError } from 'bare-agent';
19
+ import { parseSignedText, unsignedAskTtls } from './signed-text.js';
20
+ import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
21
+ import { loadCatalogue } from './catalogue.js';
22
+ import { WIRED_VERBS, wiredMenu } from './primitives.js';
23
+ import { readInputFacts } from './input-facts.js';
24
+ import { makeProvider, sumMeterings, ceilingCostUsd } from './provider.js';
25
+ import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
26
+
27
+ export const MAX_STRUCTURE_RETRIES = 2;
28
+ export const MAX_REVISIONS = 2;
29
+ export const DRAFT_MAX_TOKENS = 16000;
30
+ export const DRAFT_SKILLS = Object.freeze(['core']);
31
+
32
+ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
33
+
34
+ const SHAPE_PROPS = Object.freeze({
35
+ maxWords: { type: 'integer', minimum: 1, description: "the whole output's word ceiling" },
36
+ sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
37
+ linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
38
+ mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
39
+ });
40
+
41
+ /** The forced tool's parameter schema. `menu` = wiredMenu(). */
42
+ export function buildDeclarationSchema(menu) {
43
+ const shapeProps = {};
44
+ for (const key of SHAPE_KEYS) {
45
+ if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
46
+ shapeProps[key] = SHAPE_PROPS[key];
47
+ }
48
+ return {
49
+ type: 'object',
50
+ properties: {
51
+ steps: {
52
+ type: 'array',
53
+ minItems: 1,
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ primitives: {
58
+ type: 'array',
59
+ items: { type: 'string', enum: menu.map((e) => e.verb) },
60
+ description: 'verbs this step is granted, from the menu only; [] for a pure stop',
61
+ },
62
+ reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only' },
63
+ emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
64
+ fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
65
+ picks: {
66
+ type: 'object',
67
+ additionalProperties: { type: 'array', items: { type: 'string' } },
68
+ description: 'optional: source role -> heading names this step uses, each copied verbatim from that role\'s headings listed under Inputs; omit when the step names none',
69
+ },
70
+ close: {
71
+ type: 'object',
72
+ properties: {
73
+ class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
74
+ shape: {
75
+ type: 'object',
76
+ properties: shapeProps,
77
+ additionalProperties: false,
78
+ description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
79
+ },
80
+ },
81
+ required: ['class'],
82
+ additionalProperties: false,
83
+ },
84
+ },
85
+ required: ['primitives', 'reads', 'emits', 'fromLine', 'close'],
86
+ additionalProperties: false,
87
+ },
88
+ },
89
+ guardrailClasses: {
90
+ type: 'object',
91
+ additionalProperties: { type: 'string', enum: [...CLASSES] },
92
+ description: 'one class per job line that HAS a guardrail, keyed by line number as a string',
93
+ },
94
+ unjudgeable: {
95
+ type: 'object',
96
+ additionalProperties: { type: 'string' },
97
+ description: 'line number -> reason, only for a guardrail whose wording resisted judgment (its class stays hitl); {} if none',
98
+ },
99
+ refused: {
100
+ type: 'array',
101
+ items: {
102
+ type: 'object',
103
+ properties: { line: { type: 'integer' }, reason: { type: 'string', minLength: 1 } },
104
+ required: ['line', 'reason'],
105
+ additionalProperties: false,
106
+ },
107
+ description: 'job lines that cannot be served at all, with a reason; [] if none',
108
+ },
109
+ },
110
+ required: ['steps', 'guardrailClasses', 'unjudgeable', 'refused'],
111
+ additionalProperties: false,
112
+ };
113
+ }
114
+
115
+ const TOOL = 'emit_declaration';
116
+
117
+ function jobLinesText(lines, asks) {
118
+ const askLines = new Set(asks.map((a) => a.line));
119
+ return lines
120
+ .map((l) => `${l.n}. ${l.text}${askLines.has(l.n) ? ' [SIGNED ASK — a human stop]' : ''}`
121
+ + `${l.guardrail ? ` [guardrail: ${l.guardrail}]` : ' [no guardrail]'}`)
122
+ .join('\n');
123
+ }
124
+
125
+ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
126
+ const askLines = arbiter.asks.map((a) => a.line);
127
+ const sendLines = arbiter.sends.map((s) => s.line);
128
+ return [
129
+ `You are the fwdloop drafter. Answer ONLY by calling ${TOOL} — never plain text. You author steps only.`,
130
+ '',
131
+ 'Primitive menu (a grant list; a verb not listed does not exist):',
132
+ ...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
133
+ '',
134
+ 'Rules:',
135
+ '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step only), 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.',
136
+ '- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
137
+ '- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must cite its source cell), "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".',
138
+ '- 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.',
139
+ '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
140
+ `- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
141
+ `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
142
+ '- Nothing hitl may come after the last signed ask except the send step.',
143
+ '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
144
+ '',
145
+ 'Inputs, mechanically read (facts, not guesses):',
146
+ ...(factsInfo.length ? factsInfo : ['- (none)']),
147
+ '',
148
+ 'The numbered job lines:',
149
+ jobLinesText(lines, arbiter.asks),
150
+ ].join('\n');
151
+ }
152
+
153
+ /**
154
+ * A step's goal = its signed line's text, exactly as parseSignedText's `lines` gives it: the words after
155
+ * "N. " (trailing comma kept; on an ask line the mark is stripped, leaving the question). Continuation
156
+ * lines do not exist in the grammar. A step naming no signed line gets a fixed placeholder, never model prose.
157
+ */
158
+ export function goalForLine(fromLine, lines) {
159
+ const line = Number.isInteger(fromLine) ? lines.find((l) => l.n === fromLine) : undefined;
160
+ return line ? line.text : '(no signed line)';
161
+ }
162
+
163
+ function reviseMessage(reds) {
164
+ return 'The declaration you just emitted was REFUSED by the validator. Fix every one of these and call '
165
+ + `${TOOL} again with the complete corrected declaration:\n${reds.map((r) => `- ${r}`).join('\n')}`;
166
+ }
167
+
168
+ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
169
+
170
+ // F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
171
+ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS, thinking: Object.freeze({ type: 'disabled' }) });
172
+
173
+ /**
174
+ * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
175
+ * the batch); otherwise a live provider is built from `slot` (throws on a bad
176
+ * key — the batch preflights first). `budgetUsd` is this draft's hard cap.
177
+ * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
178
+ *
179
+ * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
180
+ * costUsd:number|null, modelReturned:string|null, modelId?:string, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
181
+ */
182
+ export async function draft({
183
+ proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId,
184
+ budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
185
+ }) {
186
+ const fail = (reds, extra = {}) => ({
187
+ ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
188
+ });
189
+
190
+ // ---- $0 gates, before any provider is built -------------------------------
191
+ const parsed = parseSignedText(proseText);
192
+ if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
193
+ const { lines, arbiter } = parsed;
194
+ const ttlReds = unsignedAskTtls(arbiter);
195
+ if (ttlReds.length) return fail(ttlReds);
196
+ const menu = wiredMenu(skills);
197
+ const facts = readInputFacts(arbiter.sources);
198
+ if (!facts.ok) return fail(facts.reds);
199
+
200
+ let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
201
+ if (provider == null) {
202
+ try {
203
+ ({ provider, rates, modelId } = makeProviderFn(slot, { model, ...DRAFT_PROVIDER_OPTIONS }));
204
+ } catch (err) {
205
+ return fail([`key: ${err.message}`]);
206
+ }
207
+ }
208
+
209
+ const schema = buildDeclarationSchema(menu);
210
+ const system = buildSystemPrompt({ menu, lines, arbiter, factsInfo: facts.info });
211
+ // Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
212
+ const cat = loadCatalogue();
213
+ if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
214
+ const validationCatalogue = cat.primitives;
215
+ const roundCeiling = ceilingCostUsd(modelId);
216
+ // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
217
+ if (roundCeiling > budgetUsd) {
218
+ return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
219
+ }
220
+
221
+ const meterings = [];
222
+ const log = [];
223
+ let structureRetries = 0;
224
+ let revisions = 0;
225
+ let lastReds = [];
226
+ let lastDecl = null;
227
+ let userText = `Call ${TOOL} now.`;
228
+ let nextKind = 'first'; // what the round about to run actually is
229
+ let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
230
+ let stop = null;
231
+ let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
232
+ let unmetered = 0; // calls that failed with no metering: their cost is unknown
233
+
234
+ for (;;) {
235
+ // Budget: spend so far (an unpriced round counts at its ceiling) + one more
236
+ // round at its ceiling must fit, or we stop here, booked.
237
+ const spent = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
238
+ if (spent + roundCeiling > budgetUsd) { stop = 'budget'; break; }
239
+
240
+ let captured;
241
+ const tool = {
242
+ name: TOOL,
243
+ description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
244
+ parameters: schema,
245
+ execute: async (args) => { captured = args; throw new HaltError('declaration captured', { rule: 'captured' }); },
246
+ };
247
+ const roundEvents = [];
248
+ const loop = new Loop({
249
+ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); },
250
+ });
251
+ let result;
252
+ let threw = null;
253
+ calls += 1;
254
+ try {
255
+ result = await loop.run(
256
+ [{ role: 'system', content: system }, { role: 'user', content: userText }],
257
+ [tool],
258
+ { maxTokens: DRAFT_MAX_TOKENS, toolChoice: { name: TOOL } },
259
+ );
260
+ } catch (err) {
261
+ threw = err;
262
+ if (roundEvents.length === 0) unmetered += 1;
263
+ }
264
+ const entry = { round: log.length + 1, kind: nextKind };
265
+
266
+ if (threw) {
267
+ entry.outcome = `provider-red: ${threw.message}`;
268
+ log.push(entry);
269
+ stop = 'provider-red';
270
+ lastReds = [`provider-red: ${threw.message}`];
271
+ break;
272
+ }
273
+
274
+ if (!isPlainObject(captured)) {
275
+ const malformed = provider?.lastMalformedToolCall ?? null;
276
+ const why = result?.stopReason === 'max_tokens' ? 'truncated: the round hit the output cap with no completed tool call'
277
+ : malformed ? `the tool call's arguments were not valid JSON (${malformed.error})`
278
+ : 'no usable tool call (text instead of the tool)';
279
+ entry.outcome = `structure: ${why}`;
280
+ log.push(entry);
281
+ lastReds = [why];
282
+ if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; break; }
283
+ structureRetries += 1;
284
+ nextKind = 'structure-retry';
285
+ userText = `Your last reply was not a usable tool call (${why}). Call ${TOOL} now with a complete, valid JSON declaration.`;
286
+ if (validatorReds.length) userText += `\n\nThe last declaration you emitted was still refused by the validator; keep fixing these too:\n${validatorReds.map((r) => `- ${r}`).join('\n')}`;
287
+ continue;
288
+ }
289
+
290
+ const declaration = { .../** @type {object} */ (captured), inputFacts: facts.inputFacts };
291
+ // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
292
+ if (Array.isArray(declaration.steps)) {
293
+ declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
294
+ }
295
+ const verdict = validateDeclaration(declaration, {
296
+ arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true,
297
+ });
298
+ lastDecl = declaration;
299
+ if (verdict.ok) {
300
+ entry.outcome = 'valid';
301
+ log.push(entry);
302
+ const m = sumMeterings(meterings);
303
+ return {
304
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop: null, log,
305
+ };
306
+ }
307
+ lastReds = [...verdict.reds];
308
+ entry.outcome = `validator: ${verdict.reds.length} red(s)`;
309
+ entry.reds = lastReds;
310
+ log.push(entry);
311
+ if (revisions >= MAX_REVISIONS) { stop = 'validator'; break; }
312
+ revisions += 1;
313
+ validatorReds = lastReds;
314
+ nextKind = 'revision';
315
+ userText = reviseMessage(lastReds);
316
+ }
317
+
318
+ const m = sumMeterings(meterings);
319
+ // Runner convention: `costUsd` is the priced floor (null when nothing priced), and `spendComplete:false` marks a
320
+ // call that failed unmetered or a round left unpriced — the number is then "at least", never the whole.
321
+ return {
322
+ ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop, log,
323
+ };
324
+ }
@@ -0,0 +1,45 @@
1
+ // M6a — input facts, read mechanically at $0 (no model scout).
2
+ //
3
+ // One entry per signed FILE source: `inputFacts[role]` is what the
4
+ // declaration carries (the file's headings — markdown `#` lines, or a .docx's
5
+ // Title/Heading1..n paragraphs), `info` is the drafter's prompt text. A source
6
+ // that cannot be read, or is empty, is a named red — never a silent [].
7
+ //
8
+ // Throws away: everything but heading text (body, order beyond headings,
9
+ // heading level, inline formatting). A .docx with no styled headings gives [].
10
+ // Ported from poc/m6a/schema.mjs readInputFacts@867c25b; the docx side now
11
+ // lists headings (the POC had [] for docx).
12
+
13
+ import { readFileSync } from 'node:fs';
14
+ import { readDocxText, readDocxHeadings } from './docx.js';
15
+
16
+ /**
17
+ * @param {Array<{kind?:string, role:string, path:string}>} sources arbiter.sources
18
+ * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], reds:string[]}}
19
+ */
20
+ export function readInputFacts(sources) {
21
+ /** @type {Record<string,string[]>} */
22
+ const inputFacts = {};
23
+ const info = [];
24
+ const reds = [];
25
+ for (const s of sources ?? []) {
26
+ if (s.kind !== 'file') continue;
27
+ if (String(s.path).toLowerCase().endsWith('.docx')) {
28
+ const r = readDocxText(s.path);
29
+ if (!r.ok) { reds.push(`input "${s.role}": ${r.red}`); continue; }
30
+ const h = readDocxHeadings(s.path);
31
+ if (!h.ok) { reds.push(`input "${s.role}": ${h.red}`); continue; }
32
+ const words = r.text.trim() === '' ? 0 : r.text.trim().split(/\s+/).length;
33
+ inputFacts[s.role] = h.headings;
34
+ info.push(`- ${s.role}: a .docx file, ${r.paragraphs} paragraphs, ~${words} words, headings: ${h.headings.join(', ') || '(none)'} (read it with "readDocx")`);
35
+ } else {
36
+ let raw;
37
+ try { raw = readFileSync(s.path, 'utf8'); } catch (e) { reds.push(`input "${s.role}": cannot read file: ${e.message}`); continue; }
38
+ if (raw.trim() === '') { reds.push(`input "${s.role}": "${s.path}" is empty`); continue; }
39
+ const headings = raw.split(/\r?\n/).filter((l) => /^#{1,6}\s+\S/.test(l)).map((l) => l.replace(/^#{1,6}\s*/, '').trim());
40
+ inputFacts[s.role] = headings;
41
+ info.push(`- ${s.role}: a text/markdown file, ~${raw.trim().split(/\s+/).length} words, headings: ${headings.join(', ') || '(none)'} (read it with "read")`);
42
+ }
43
+ }
44
+ return { ok: reds.length === 0, inputFacts, info, reds };
45
+ }
package/src/primitives.js CHANGED
@@ -28,7 +28,7 @@ import path from 'node:path';
28
28
  import { createShellTools, resolveToolPath } from 'bare-agent/tools';
29
29
  import { Gate } from 'bareguard';
30
30
 
31
- import { primitiveFor } from './catalogue.js';
31
+ import { primitiveFor, loadCatalogue } from './catalogue.js';
32
32
  import { readDocxText } from './docx.js';
33
33
  import { parseCsv } from './csv.js';
34
34
 
@@ -261,6 +261,15 @@ function addressCellsPrimitiveTool(inputsByRole) {
261
261
  * keeping a second copy of the list. */
262
262
  export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'readDocx', 'addressCells']);
263
263
 
264
+ /** The wired menu, one place: the catalogue entries whose verb is in
265
+ * WIRED_VERBS (and, when `skills` is given, in a signed skill). Absence,
266
+ * not refusal. Throws only if catalogue.json itself is unreadable. */
267
+ export function wiredMenu(skills) {
268
+ const cat = loadCatalogue();
269
+ if (!cat.ok) throw new Error(`catalogue unreadable: ${cat.reds.join('; ')}`);
270
+ return cat.primitives.filter((e) => WIRED_VERBS.has(e.verb) && (!skills || skills.includes(e.skill)));
271
+ }
272
+
264
273
  /**
265
274
  * Resolve the granted tools for one step's model call. Never throws —
266
275
  * a verb absent from the catalogue, or present but unimplemented here, is
package/src/provider.js CHANGED
@@ -287,11 +287,12 @@ export function checkKeyPreflight(slotName, env = process.env) {
287
287
  * values this project uses.
288
288
  *
289
289
  * @param {string} slotName
290
- * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number }} [options]
290
+ * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null }} [options]
291
+ * `thinking` (bare-agent >=0.49) is sent verbatim as body.thinking; unset/null leaves the body unchanged.
291
292
  * @returns {{ provider: any, rates: {in:number, out:number}, modelId: string, suffix: string, slot: string }}
292
293
  */
293
294
  export function makeProvider(slotName, options = {}) {
294
- const { model, timeoutMs, deadlineMs } = options;
295
+ const { model, timeoutMs, deadlineMs, thinking } = options;
295
296
  const slot = PROVIDER_SLOTS[slotName];
296
297
  if (!slot) {
297
298
  throw new Error(`unknown provider slot "${slotName}" — known slots: ${Object.keys(PROVIDER_SLOTS).join(', ')}`);
@@ -314,6 +315,7 @@ export function makeProvider(slotName, options = {}) {
314
315
  exposeMalformedArgs: true,
315
316
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
316
317
  ...(deadlineMs !== undefined ? { deadlineMs } : {}),
318
+ ...(thinking != null ? { thinking } : {}),
317
319
  });
318
320
 
319
321
  return {
@@ -0,0 +1,27 @@
1
+ // M6a amendment 2 — only a person at a keyboard can sign. The CLI's `sign` verb calls this
2
+ // BEFORE signDraft; signDraft itself stays a library (tests) and the CLI has no path around this.
3
+ // Raises the bar, is not proof of a person: a determined script can fake a TTY.
4
+ import { createInterface } from 'node:readline';
5
+
6
+ export const NEEDS_TTY = 'sign needs an interactive terminal — run it yourself';
7
+ export const NAME_MISMATCH = 'typed name does not match';
8
+
9
+ /** stdin AND stdout must both be TTYs. */
10
+ export function isInteractive(stdin = process.stdin, stdout = process.stdout) {
11
+ return Boolean(stdin && stdin.isTTY && stdout && stdout.isTTY);
12
+ }
13
+
14
+ /** Show the flow name, read one line, compare exactly (trimmed). Empty answer / EOF / mismatch refuse by name. */
15
+ export function confirmTypedName({ name, input = process.stdin, output = process.stdout }) {
16
+ return new Promise((resolve) => {
17
+ const rl = createInterface({ input, output, terminal: false });
18
+ let done = false;
19
+ const finish = (r) => { if (!done) { done = true; rl.close(); resolve(r); } };
20
+ rl.on('close', () => finish({ ok: false, red: `${NAME_MISMATCH} (no answer)` }));
21
+ output.write(`Signing flow "${name}". Type the flow name to confirm: `);
22
+ rl.once('line', (line) => {
23
+ const typed = line.trim();
24
+ finish(typed !== '' && typed === name ? { ok: true } : { ok: false, red: NAME_MISMATCH });
25
+ });
26
+ });
27
+ }
@@ -38,7 +38,7 @@ const CAP_RE = /^cap \$([^\s]+) per run$/i;
38
38
  // M1 amendment 3 (docs/wiki/the-module-ladder.md, "M1 amendment 3 — the ask
39
39
  // is a mark on its own line — SIGNED by hamr 2026-09-21"): the ask is no
40
40
  // longer a bottom-block arbiter line — it is a mark at the START of a
41
- // numbered job line's own text: `ask:` (default 30m wait) or
41
+ // numbered job line's own text: `ask:` (30m wait — a legacy default, see `unsignedAskTtls`) or
42
42
  // `ask <int><s|m|h>:` (explicit wait), the words after the mark being the
43
43
  // human's own question. OLD_ASK_ARBITER_RE below only detects the RETIRED
44
44
  // bottom-block form (`guardrail: ask at line N`) so it can be refused by
@@ -80,7 +80,7 @@ const DEFAULT_ROUND_BUDGET_MS = 120000;
80
80
  * @param {string} text
81
81
  * @returns {{ attempted: false }
82
82
  * | { attempted: true, ok: false, error: string }
83
- * | { attempted: true, ok: true, ttlMs: number, question: string }}
83
+ * | { attempted: true, ok: true, ttlMs: number, ttlSigned: boolean, question: string }}
84
84
  */
85
85
  function parseAskMark(text) {
86
86
  if (!ASK_MARK_ATTEMPT_RE.test(text)) {
@@ -92,7 +92,7 @@ function parseAskMark(text) {
92
92
  if (question.length === 0) {
93
93
  return { attempted: true, ok: false, error: 'has no words after the mark' };
94
94
  }
95
- return { attempted: true, ok: true, ttlMs: DEFAULT_ASK_TTL_MS, question };
95
+ return { attempted: true, ok: true, ttlMs: DEFAULT_ASK_TTL_MS, ttlSigned: false, question };
96
96
  }
97
97
  const timed = ASK_MARK_TIMED_RE.exec(text);
98
98
  if (timed) {
@@ -105,11 +105,25 @@ function parseAskMark(text) {
105
105
  if (question.length === 0) {
106
106
  return { attempted: true, ok: false, error: 'has no words after the mark' };
107
107
  }
108
- return { attempted: true, ok: true, ttlMs: value * UNIT_MS[unit], question };
108
+ return { attempted: true, ok: true, ttlMs: value * UNIT_MS[unit], ttlSigned: true, question };
109
109
  }
110
110
  return { attempted: true, ok: false, error: 'is not "ask:" or "ask <int><s|m|h>:"' };
111
111
  }
112
112
 
113
+ /**
114
+ * M6a amendment 1: a NEW flow (draft, sign) may not carry an ask whose wait the human never typed. The
115
+ * parser still fills the legacy 30m default for `ask:` so flows signed before the amendment keep running;
116
+ * this names each ask that relies on it. Returns [] when every ask carries `ask <int><s|m|h>:`.
117
+ *
118
+ * @param {{ asks?: Array<{ line: number, ttlSigned?: boolean }> }} arbiter
119
+ * @returns {string[]}
120
+ */
121
+ export function unsignedAskTtls(arbiter) {
122
+ return (arbiter?.asks ?? [])
123
+ .filter((a) => a.ttlSigned !== true)
124
+ .map((a) => `signed-text: the ask on line ${a.line} has no signed wait — write it as "ask <int><s|m|h>:" (e.g. "ask 30m:"); the wait is never a code default`);
125
+ }
126
+
113
127
  /**
114
128
  * Parse the human's signed text. Never throws — any input that isn't a
115
129
  * usable signed text comes back as `{ ok: false, reds }`, never an
@@ -168,7 +182,7 @@ export function parseSignedText(rawText) {
168
182
  reds.push(`signed-text: line ${fileLine} field "asks" ${mark.error}: "${rawLineText}"`);
169
183
  } else {
170
184
  lineText = mark.question;
171
- asks.push({ line: n, ttlMs: mark.ttlMs, question: mark.question });
185
+ asks.push({ line: n, ttlMs: mark.ttlMs, ttlSigned: mark.ttlSigned, question: mark.question });
172
186
  }
173
187
  }
174
188
  current = { n, text: lineText, guardrail: '' };
package/src/types.js CHANGED
@@ -15,6 +15,7 @@
15
15
  * @property {number} line - the numbered line this ask binds to (the line
16
16
  * carries the `ask:`/`ask <int><s|m|h>:` mark itself, M1 amendment 3).
17
17
  * @property {number} ttlMs - the ask's time-to-live in milliseconds.
18
+ * @property {boolean} [ttlSigned] - true when the human typed the wait (`ask <int><s|m|h>:`); false on the legacy `ask:` 30m default, which draft and sign refuse (M6a amendment 1).
18
19
  * @property {string} question - the words after the mark, trimmed — the
19
20
  * human's own question. Nothing reads this yet outside signed-text.js.
20
21
  */
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The one spec hash. sha256 over the four canonical parts, JSON-array framed so no part can
3
+ * bleed into the next. Never throws.
4
+ * @param {{proseText:string, declarationText:string, inputFactsText:string, readoutText:string, targetText:string}} p
5
+ * @returns {{ok:true, hash:string}|{ok:false, red:string}}
6
+ */
7
+ export function specHash({ proseText, declarationText, inputFactsText, readoutText, targetText, }: {
8
+ proseText: string;
9
+ declarationText: string;
10
+ inputFactsText: string;
11
+ readoutText: string;
12
+ targetText: string;
13
+ }): {
14
+ ok: true;
15
+ hash: string;
16
+ } | {
17
+ ok: false;
18
+ red: string;
19
+ };
20
+ /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
21
+ export function scrub(text: any, secrets: any): any;
22
+ /** Count files directly inside `dir` that contain a secret literally. */
23
+ export function sweepForSecrets(dir: any, secrets: any): number;
24
+ /** Exact signed TTL with its unit, never rounded: 2h / 30m / 20s / 1500ms (the largest unit that divides it exactly). */
25
+ export function fmtTtl(ms: any): string;
26
+ /** Plain-text readout of what the human is about to sign. Pure. */
27
+ export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete }: {
28
+ declaration: any;
29
+ arbiter: any;
30
+ lines: any;
31
+ name: any;
32
+ modelId: any;
33
+ costUsd: any;
34
+ rounds: any;
35
+ spendComplete: any;
36
+ }): string;
37
+ /** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
38
+ export function readProseFile(file: any): {
39
+ ok: boolean;
40
+ red: string;
41
+ text?: undefined;
42
+ } | {
43
+ ok: boolean;
44
+ text: string;
45
+ red?: undefined;
46
+ };
47
+ /**
48
+ * Draft into `dir`. $0 refusals (return {ok:false, wrote:false}, nothing on disk): bad key,
49
+ * unreadable/blank prose, prose that contains the key, missing inputs / bad signed text, dir
50
+ * already exists. After a paid round the dir is ALWAYS written — green (spec.hash present) or
51
+ * red (reds, no spec.hash). Spend is booked in `<dir>/spend.jsonl` with the runner's own
52
+ * writer (appendSpendRow); an unpriced round books null, never 0.
53
+ *
54
+ * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
55
+ */
56
+ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd, env, provider, rates, modelId, }: {
57
+ proseFile: any;
58
+ dir: any;
59
+ root: any;
60
+ name: any;
61
+ slot?: string | undefined;
62
+ model: any;
63
+ budgetUsd?: number | undefined;
64
+ env?: NodeJS.ProcessEnv | undefined;
65
+ provider: any;
66
+ rates: any;
67
+ modelId: any;
68
+ }): Promise<{
69
+ ok: boolean;
70
+ wrote: boolean;
71
+ reds: any;
72
+ costUsd: number;
73
+ } | {
74
+ ok: boolean;
75
+ wrote: boolean;
76
+ dir: any;
77
+ reds: any[];
78
+ costUsd: number | null;
79
+ spendComplete: boolean;
80
+ stop: string;
81
+ rounds: number;
82
+ calls: number;
83
+ leaks: number;
84
+ } | {
85
+ ok: boolean;
86
+ wrote: boolean;
87
+ reds: string[];
88
+ costUsd: number | null;
89
+ spendComplete: boolean;
90
+ leaks: number;
91
+ dir?: undefined;
92
+ hash?: undefined;
93
+ stop?: undefined;
94
+ rounds?: undefined;
95
+ calls?: undefined;
96
+ } | {
97
+ ok: boolean;
98
+ wrote: boolean;
99
+ dir: any;
100
+ hash: string | null;
101
+ reds: string[];
102
+ costUsd: number | null;
103
+ spendComplete: boolean;
104
+ stop: string | null;
105
+ rounds: number;
106
+ calls: number;
107
+ leaks: number;
108
+ }>;
109
+ /**
110
+ * The human step, $0. Every refusal returns reds and writes NO flow.
111
+ * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
112
+ */
113
+ export function signDraft({ dir, approve, signedBy, signedAt, env, }: {
114
+ dir: any;
115
+ approve: any;
116
+ signedBy: any;
117
+ signedAt?: string | undefined;
118
+ env?: NodeJS.ProcessEnv | undefined;
119
+ }): {
120
+ ok: boolean;
121
+ reds: any[];
122
+ } | {
123
+ ok: boolean;
124
+ flowDir: string;
125
+ signature: import("./types.js").Signature;
126
+ };
127
+ export const DRAFT_BUDGET_USD: 0.1;
128
+ export const SPEC_HASH_FILE: "spec.hash";
129
+ /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
130
+ export const LEAK_MARKER_FILE: "scrub-leak.red";
131
+ export function SIGN_LINE(dir: any, hash: any): string;
132
+ export function costText(n: any, spendComplete?: boolean): string;