fwdloop 0.4.0 → 0.5.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.
@@ -94,13 +94,37 @@ function checkOwnKeys(obj, allowed, path, reds) {
94
94
  }
95
95
  }
96
96
 
97
- /** Arbiter-key refusal recursively through `close.shape` — any depth, any
98
- * key named after the arbiter's vocabulary, in an object or nested inside
99
- * an array. Every OTHER key inside `shape` is free (the typed shape
100
- * vocabulary is not signed yet, per M1 scope item 2). */
101
- function scanShapeForArbiterKeys(value, path, reds) {
97
+ /** The typed `close.shape` vocabulary, signed by hamr 2026-09-23 (v1):
98
+ * exactly these four top-level keys. Anything else inside `shape` reds by
99
+ * name. */
100
+ export const SHAPE_KEYS = Object.freeze(['maxWords', 'sections', 'linesPerInvoice', 'mustCarry']);
101
+
102
+ const SHAPE_TYPE_CHECKS = Object.freeze({
103
+ maxWords: {
104
+ expected: 'a positive integer',
105
+ check: (v) => Number.isInteger(v) && v > 0,
106
+ },
107
+ linesPerInvoice: {
108
+ expected: 'a positive integer',
109
+ check: (v) => Number.isInteger(v) && v > 0,
110
+ },
111
+ sections: {
112
+ expected: 'a non-empty array of non-empty strings',
113
+ check: (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === 'string' && s.length > 0),
114
+ },
115
+ mustCarry: {
116
+ expected: 'a non-empty array of non-empty strings',
117
+ check: (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === 'string' && s.length > 0),
118
+ },
119
+ });
120
+
121
+ /** Arbiter-key refusal recursively through a `close.shape` value — any
122
+ * depth, any key named after the arbiter's vocabulary, in an object or
123
+ * nested inside an array (e.g. inside a `sections` array entry that turns
124
+ * out to be an object). */
125
+ function scanForArbiterKeys(value, path, reds) {
102
126
  if (Array.isArray(value)) {
103
- value.forEach((entry, i) => scanShapeForArbiterKeys(entry, `${path}[${i}]`, reds));
127
+ value.forEach((entry, i) => scanForArbiterKeys(entry, `${path}[${i}]`, reds));
104
128
  return;
105
129
  }
106
130
  if (isPlainObject(value)) {
@@ -109,11 +133,69 @@ function scanShapeForArbiterKeys(value, path, reds) {
109
133
  if (ARBITER_KEYS.includes(key)) {
110
134
  reds.push(`declaration: arbiter field "${key}" at ${childPath} — the drafter cannot author it`);
111
135
  }
112
- scanShapeForArbiterKeys(value[key], childPath, reds);
136
+ scanForArbiterKeys(value[key], childPath, reds);
113
137
  }
114
138
  }
115
139
  }
116
140
 
141
+ /** `close.shape`'s own top-level keys must each be in SHAPE_KEYS (the signed
142
+ * v1 vocabulary) — an arbiter key gets the existing arbiter-red wording, any
143
+ * other unknown key reds by name, and a known key is type-checked. Nested
144
+ * arbiter-key refusal still applies at any depth inside a shape value. */
145
+ function checkShapeKeys(shape, path, reds) {
146
+ for (const key of Object.keys(shape)) {
147
+ const childPath = `${path}.${key}`;
148
+ const value = shape[key];
149
+ if (ARBITER_KEYS.includes(key)) {
150
+ reds.push(`declaration: arbiter field "${key}" at ${childPath} — the drafter cannot author it`);
151
+ } else if (!SHAPE_KEYS.includes(key)) {
152
+ reds.push(`declaration: unknown shape key "${key}" at ${childPath}`);
153
+ } else {
154
+ const typeCheck = SHAPE_TYPE_CHECKS[key];
155
+ if (!typeCheck.check(value)) {
156
+ reds.push(`declaration: shape key "${key}" at ${childPath} must be ${typeCheck.expected}`);
157
+ }
158
+ }
159
+ scanForArbiterKeys(value, childPath, reds);
160
+ }
161
+ }
162
+
163
+ /**
164
+ * A small, pure walker over `declaration.steps` for callers that only want
165
+ * the shape-key verdict (e.g. poc/m1/slot-batch.mjs's `shape` column) —
166
+ * never a substitute for `validateDeclaration`, which is still the one
167
+ * check that decides pass/fail for a real declaration. Reuses the same
168
+ * `checkShapeKeys` `validateDeclaration` calls, so the two can never drift
169
+ * apart on what counts as a known shape key.
170
+ *
171
+ * A non-array `declaration.steps` (or a non-object `declaration` at all)
172
+ * reds `'no steps array'` rather than throwing. `shapedSteps` counts every
173
+ * step whose `close` carries a `shape` key at all — a step that TRIED to
174
+ * carry a shape, known-key or not, plain-object or not. A `shape` that
175
+ * isn't a plain object (array, string, number, null) reds
176
+ * `"... .close.shape must be an object"`, matching `validateDeclaration`'s
177
+ * own red for the same malformed input.
178
+ */
179
+ export function checkShapes(declaration) {
180
+ const steps = isPlainObject(declaration) && Array.isArray(declaration.steps) ? declaration.steps : null;
181
+ if (steps === null) {
182
+ return { verdict: 'red', reds: ['no steps array'], shapedSteps: 0 };
183
+ }
184
+ const reds = [];
185
+ let shapedSteps = 0;
186
+ steps.forEach((step, i) => {
187
+ if (!isPlainObject(step?.close) || !('shape' in step.close)) return;
188
+ const shape = step.close.shape;
189
+ shapedSteps += 1;
190
+ if (isPlainObject(shape)) {
191
+ checkShapeKeys(shape, `declaration.steps[${i}].close.shape`, reds);
192
+ } else {
193
+ reds.push(`declaration.steps[${i}].close.shape must be an object`);
194
+ }
195
+ });
196
+ return { verdict: reds.length > 0 ? 'red' : 'green', reds, shapedSteps };
197
+ }
198
+
117
199
  /**
118
200
  * Resolve one line's class from `guardrailClasses`, exactly as
119
201
  * poc/m0/validator.mjs's `resolveGuardrailClass` does: blank guardrail is
@@ -417,7 +499,7 @@ export function validateDeclaration(declaration, context = {}) {
417
499
  if (!isPlainObject(step.close.shape)) {
418
500
  reds.push(`declaration: ${label}.close.shape must be an object`);
419
501
  } else {
420
- scanShapeForArbiterKeys(step.close.shape, `declaration.${label}.close.shape`, reds);
502
+ checkShapeKeys(step.close.shape, `declaration.${label}.close.shape`, reds);
421
503
  }
422
504
  }
423
505
  }
@@ -549,14 +631,42 @@ export function validateDeclaration(declaration, context = {}) {
549
631
  .map((a) => stepInfo.find((st) => st.fromLine === a))
550
632
  .filter((st) => st !== undefined)
551
633
  .map((st) => st.emits);
552
- const readsAnAsk = earlierAskEmits.some((emits) => emits !== null && sendStep.reads.includes(emits));
553
- if (!readsAnAsk) {
634
+ const readAskEmits = earlierAskEmits.filter((emits) => emits !== null && sendStep.reads.includes(emits));
635
+ if (readAskEmits.length === 0) {
554
636
  reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) does not read the emits of any earlier signed `
555
637
  + `ask step (asks at lines ${earlierAskLines.join(', ')})`);
638
+ } else if (readAskEmits.length >= 2) {
639
+ reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) reads the emits of more than one earlier signed `
640
+ + `ask step (${readAskEmits.join(', ')}) — exactly 1 required`);
556
641
  }
557
642
  }
558
643
  }
559
644
 
645
+ // --- M2 amendment 1 item 2 (docs/wiki/the-module-ladder.md, "M2 amendment
646
+ // 1 — SIGNED"): nothing hitl-class may sit after the LAST signed ask,
647
+ // unseen — the send step bound to a signed send line is the one exempt
648
+ // step (it is itself hitl-class by silence in both fixtures, but it is
649
+ // the human-accepted egress, not a second undeclared pause). Anchored on
650
+ // STEP ORDER (a step's position in `declaration.steps`, not its line
651
+ // number) since that is the order the runner actually folds over. No
652
+ // anchor to check against when there is no signed ask at all.
653
+ if (askLines.length > 0) {
654
+ const lastAskLine = Math.max(...askLines);
655
+ const lastAskStepIdx = stepInfo.findIndex((st) => st.fromLine === lastAskLine);
656
+ if (lastAskStepIdx !== -1) {
657
+ const sendStepIndices = new Set();
658
+ for (const n of sendLines) {
659
+ const idx = stepInfo.findIndex((st) => st.fromLine === n);
660
+ if (idx !== -1) sendStepIndices.add(idx);
661
+ }
662
+ stepInfo.forEach((st, i) => {
663
+ if (i > lastAskStepIdx && st.effectiveClass === 'hitl' && !sendStepIndices.has(i)) {
664
+ reds.push(`declaration: step "${st.emits}" (line ${st.fromLine}) is hitl after the last signed ask — nothing may leave unseen`);
665
+ }
666
+ });
667
+ }
668
+ }
669
+
560
670
  // --- check 6: every numbered line must be served or refused, never dropped
561
671
  const claimedLines = new Set(stepInfo.map((st) => st.fromLine).filter((n) => Number.isInteger(n)));
562
672
  for (const line of safeLines) {
package/src/docx.js ADDED
@@ -0,0 +1,145 @@
1
+ // borrowed-from: fwdloop poc/m0/docx.mjs@76a3607 (verbatim logic — F13,
2
+ // 2026-09-09 ruling: file-format/domain knowledge is fwdloop's own to
3
+ // write, never an upstream ask). Minimal .docx (OOXML) text reader, stdlib
4
+ // only: parses the zip container by hand and pulls paragraph text out of
5
+ // word/document.xml with regex, not a real XML/zip library.
6
+ //
7
+ // What this discards (every summary declares what it throws away, per
8
+ // AGENT_RULES): run formatting, images/drawings, headers/footers/
9
+ // footnotes/endnotes/comments, table/cell boundaries (cells collapse to
10
+ // paragraph text in document order), revision marks/field codes/bookmarks,
11
+ // and content-control wrappers (their inner text still survives — the scan
12
+ // is over raw paragraph markup, not a parsed tree).
13
+
14
+ import { readFileSync } from 'node:fs';
15
+ import { inflateRawSync } from 'node:zlib';
16
+
17
+ const EOCD_SIG = 0x06054b50;
18
+ const CDIR_SIG = 0x02014b50;
19
+ const LOCAL_SIG = 0x04034b50;
20
+ const TARGET = 'word/document.xml';
21
+
22
+ // Zip-bomb defense: the DECLARED size is checked before any data is
23
+ // touched, and the REAL inflated size is bounded via inflateRawSync's
24
+ // maxOutputLength, so a lying header (small declared size, huge real
25
+ // payload) is also refused.
26
+ export const DOCX_MAX_UNCOMPRESSED_BYTES = 20 * 1024 * 1024;
27
+
28
+ function crc32(buf) {
29
+ let crc = ~0;
30
+ for (let i = 0; i < buf.length; i += 1) {
31
+ crc ^= buf[i];
32
+ for (let j = 0; j < 8; j += 1) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
33
+ }
34
+ return (~crc) >>> 0;
35
+ }
36
+
37
+ function findEocd(buf) {
38
+ const maxComment = 65535;
39
+ const start = Math.max(0, buf.length - 22 - maxComment);
40
+ for (let i = buf.length - 22; i >= start; i -= 1) {
41
+ if (buf.readUInt32LE(i) === EOCD_SIG) return i;
42
+ }
43
+ return -1;
44
+ }
45
+
46
+ function findEntry(buf) {
47
+ const eocd = findEocd(buf);
48
+ if (eocd === -1) return { red: 'no End Of Central Directory record (0x06054b50) found' };
49
+ const total = buf.readUInt16LE(eocd + 10);
50
+ let off = buf.readUInt32LE(eocd + 16);
51
+ for (let i = 0; i < total; i += 1) {
52
+ if (off + 46 > buf.length || buf.readUInt32LE(off) !== CDIR_SIG) {
53
+ return { red: `central directory entry ${i} missing signature (0x02014b50)` };
54
+ }
55
+ const method = buf.readUInt16LE(off + 10);
56
+ const crc = buf.readUInt32LE(off + 16);
57
+ const compSize = buf.readUInt32LE(off + 20);
58
+ const uncompSize = buf.readUInt32LE(off + 24);
59
+ const nameLen = buf.readUInt16LE(off + 28);
60
+ const extraLen = buf.readUInt16LE(off + 30);
61
+ const commentLen = buf.readUInt16LE(off + 32);
62
+ const localOffset = buf.readUInt32LE(off + 42);
63
+ const name = buf.toString('utf8', off + 46, off + 46 + nameLen);
64
+ if (name === TARGET) return {
65
+ method, crc, compSize, uncompSize, localOffset,
66
+ };
67
+ off += 46 + nameLen + extraLen + commentLen;
68
+ }
69
+ return { red: `${TARGET} not found in zip central directory` };
70
+ }
71
+
72
+ function readEntryBytes(buf, entry) {
73
+ const {
74
+ localOffset, method, compSize, uncompSize, crc,
75
+ } = entry;
76
+ if (uncompSize > DOCX_MAX_UNCOMPRESSED_BYTES) {
77
+ return { red: `entry too large: declared ${uncompSize} bytes exceeds cap ${DOCX_MAX_UNCOMPRESSED_BYTES}` };
78
+ }
79
+ if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== LOCAL_SIG) {
80
+ return { red: `local file header missing signature (0x04034b50) at offset ${localOffset}` };
81
+ }
82
+ const nameLen = buf.readUInt16LE(localOffset + 26);
83
+ const extraLen = buf.readUInt16LE(localOffset + 28);
84
+ const dataStart = localOffset + 30 + nameLen + extraLen;
85
+ if (dataStart + compSize > buf.length) return { red: 'compressed data runs past end of file (truncated)' };
86
+ const raw = buf.subarray(dataStart, dataStart + compSize);
87
+ let data;
88
+ if (method === 0) data = Buffer.from(raw);
89
+ else if (method === 8) {
90
+ try {
91
+ data = inflateRawSync(raw, { maxOutputLength: DOCX_MAX_UNCOMPRESSED_BYTES });
92
+ } catch (e) {
93
+ if (e instanceof RangeError) {
94
+ return { red: `inflate exceeded cap ${DOCX_MAX_UNCOMPRESSED_BYTES} bytes` };
95
+ }
96
+ return { red: `inflate failed: ${e.message}` };
97
+ }
98
+ } else return { red: `unsupported compression method ${method} (only 0=stored, 8=deflate)` };
99
+ if (data.length !== uncompSize) return { red: `size mismatch: expected ${uncompSize} bytes, got ${data.length}` };
100
+ if (crc32(data) !== crc) return { red: 'CRC-32 mismatch: decompressed data does not match stored checksum' };
101
+ return { data };
102
+ }
103
+
104
+ const ENTITIES = {
105
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'",
106
+ };
107
+ function decodeEntities(s) {
108
+ return s.replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ENTITIES[e]);
109
+ }
110
+
111
+ const RUN_RE = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>|<w:tab\s*\/>|<w:br\s*\/>/g;
112
+ function paragraphText(block) {
113
+ let out = '';
114
+ RUN_RE.lastIndex = 0;
115
+ let m = RUN_RE.exec(block);
116
+ while (m) {
117
+ if (m[1] !== undefined) out += decodeEntities(m[1]);
118
+ else if (m[0].startsWith('<w:tab')) out += '\t';
119
+ else out += '\n';
120
+ m = RUN_RE.exec(block);
121
+ }
122
+ return out;
123
+ }
124
+
125
+ function extractText(xml) {
126
+ const paragraphs = xml.match(/<w:p[ >][\s\S]*?<\/w:p>/g) || [];
127
+ return { text: paragraphs.map(paragraphText).join('\n'), paragraphs: paragraphs.length };
128
+ }
129
+
130
+ /** @param {string} path @returns {{ok:true,text:string,paragraphs:number}|{ok:false,red:string}} */
131
+ export function readDocxText(path) {
132
+ let buf;
133
+ try {
134
+ buf = readFileSync(path);
135
+ } catch (e) {
136
+ return { ok: false, red: `cannot read file: ${e.message}` };
137
+ }
138
+ const entry = findEntry(buf);
139
+ if (entry.red) return { ok: false, red: entry.red };
140
+ const read = readEntryBytes(buf, entry);
141
+ if (read.red || !read.data) return { ok: false, red: read.red ?? 'no data decoded' };
142
+ const xml = read.data.toString('utf8');
143
+ const { text, paragraphs } = extractText(xml);
144
+ return { ok: true, text, paragraphs };
145
+ }
package/src/flow.js CHANGED
@@ -20,7 +20,8 @@
20
20
  // caught and returned as a red naming the file or path involved.
21
21
 
22
22
  import {
23
- existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync,
23
+ accessSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync,
24
+ writeFileSync,
24
25
  } from 'node:fs';
25
26
  import path from 'node:path';
26
27
 
@@ -284,6 +285,29 @@ export function readFlow({ root, name, catalogue }) {
284
285
  }
285
286
  }
286
287
 
288
+ // runs/ (M1 only creates the empty directory; reading inside it is M2's
289
+ // job — this only checks it exists, isn't a symlink, and is a directory).
290
+ const runsPath = path.join(dir, RUNS_DIR);
291
+ let runsStat;
292
+ try {
293
+ runsStat = lstatSync(runsPath);
294
+ } catch {
295
+ reds.push(`flow: directory "${dir}/${RUNS_DIR}" is missing`);
296
+ }
297
+ if (runsStat) {
298
+ if (runsStat.isSymbolicLink()) {
299
+ reds.push(`flow: directory "${dir}/${RUNS_DIR}" is a symlink, refused`);
300
+ } else if (!runsStat.isDirectory()) {
301
+ reds.push(`flow: "${dir}/${RUNS_DIR}" is not a directory`);
302
+ } else {
303
+ try {
304
+ accessSync(runsPath, fsConstants.R_OK | fsConstants.X_OK);
305
+ } catch (err) {
306
+ reds.push(`flow: directory "${dir}/${RUNS_DIR}" is not readable (${err.code})`);
307
+ }
308
+ }
309
+ }
310
+
287
311
  if (reds.length > 0) return { ok: false, reds };
288
312
 
289
313
  // Verify against the bytes on disk, not a re-serialised object.
package/src/index.js CHANGED
@@ -10,3 +10,7 @@ export {
10
10
  export {
11
11
  checkFlowName, writeFlow, readFlow, FLOW_FILES,
12
12
  } from './flow.js';
13
+ export {
14
+ runFlow, STRIKE_LIMIT, MAX_ATTEMPTS,
15
+ } from './runner.js';
16
+ export { closeByClass } from './closers.js';
@@ -0,0 +1,324 @@
1
+ // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED"): the live `modelStep(executorContext, grantedTools, stepMeta)`
3
+ // piece 1's `runFlow` expects. One attempt = up to 3 rounds (a round is one
4
+ // fresh `bare-agent` `Loop` run; a round retries only on "no usable tool
5
+ // call" or a malformed tool-call, never on a transport fault or a
6
+ // wall-clock deadline). Every round is metered via `appendSpendRow`
7
+ // (`src/provider.js`, one writer for the ledger line); the attempt's
8
+ // returned `costUsd` is the SUM across every round this attempt ran ("meter
9
+ // the whole unit of work" — CLAUDE.md/AGENT_RULES — never the last round's
10
+ // number passed off as the attempt's total).
11
+ //
12
+ // borrowed-from: fwdloop poc/m0/runner.mjs@76a3607
13
+ // (`runModelStepOnPrimitives`'s round/retry rules: rule 1 transport retry,
14
+ // rule 3 no-tool-call retry once then red, rule 4 max_tokens never
15
+ // retried, rule 5 never throw for a model failure; `LIVE_PROVIDER_OPTIONS`
16
+ // timeoutMs 300s / deadlineMs 240s). Piece 1's own ralph loop (M2 scope
17
+ // item 8) owns the ONE retry on a `transport:true` result — this module
18
+ // therefore does NOT retry a transport fault itself; it returns
19
+ // `{ ok:false, transport:true, costUsd, spendComplete:false }` on the
20
+ // FIRST one and lets `runFlow` call this function again fresh for the
21
+ // retry, exactly once, per its own ladder.
22
+ //
23
+ // The tool schema `emit_artifact` is built from `stepMeta.class` ONLY
24
+ // (green/softgreen/anything else) — never from the step's `shape` — the
25
+ // executor context (M2 scope item 3) carries neither.
26
+
27
+ import { Loop } from 'bare-agent';
28
+
29
+ import {
30
+ makeProvider, sumMeterings, appendSpendRow, classifyModelId,
31
+ } from './provider.js';
32
+
33
+ // F27: DeepSeek's `chat/completions` can send HTTP 200 + headers + one byte
34
+ // then nothing — a "zombie stream" that `timeoutMs`'s idle bound never
35
+ // trips on. `deadlineMs` is bare-agent's TOTAL wall-clock ceiling
36
+ // (`code: 'EDEADLINE'`, `retryable: false`) — deliberately shorter than
37
+ // `timeoutMs` so a hung request reds well inside the idle bound. Frozen +
38
+ // exported so a test can assert on the live call's actual config.
39
+ export const LIVE_PROVIDER_OPTIONS = Object.freeze({ timeoutMs: 300_000, deadlineMs: 240_000 });
40
+
41
+ const TRANSPORT_CODES = Object.freeze([
42
+ 'ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED', 'EPIPE', 'ENETUNREACH', 'EAI_AGAIN',
43
+ ]);
44
+
45
+ /**
46
+ * True for a transport-layer fault (a request that never reached or never
47
+ * heard back from the provider) — never true for an application-level
48
+ * failure (an HTTP status the provider server actually sent, a wall-clock
49
+ * deadline). `EDEADLINE` (bare-agent's BA-19 total wall-clock ceiling) is
50
+ * explicitly excluded: M2 scope item 8 says a wall-clock timeout is NEVER
51
+ * retried, so it must never be classified as the retryable `transport`
52
+ * shape however similar its symptom looks.
53
+ *
54
+ * @param {any} err
55
+ */
56
+ export function isTransportFailure(err) {
57
+ if (!err) return false;
58
+ if (err.code === 'EDEADLINE') return false;
59
+ if (typeof err.code === 'string' && TRANSPORT_CODES.includes(err.code)) return true;
60
+ const msg = String(err.message ?? '');
61
+ if (TRANSPORT_CODES.some((code) => msg.includes(code))) return true;
62
+ if (/fetch failed/i.test(msg)) return true;
63
+ if (/\bTLS\b/i.test(msg) || /\bSSL\b/i.test(msg)) return true;
64
+ return false;
65
+ }
66
+
67
+ // M2 amendment 1 item 1 (docs/wiki/the-module-ladder.md, "M2 amendment 1 —
68
+ // SIGNED"): every class's `emit_artifact` schema carries the step's own
69
+ // typed self-report — `done` (required) and `blocker` — so `src/runner.js`
70
+ // can take the model's own word at face value, mechanically, before any
71
+ // close runs. Shared across all three schemas so their wording can never
72
+ // drift apart.
73
+ const DONE_PROPS = Object.freeze({
74
+ done: {
75
+ type: 'boolean',
76
+ description: "true only if this step's goal was actually accomplished with real data; false if anything blocked it",
77
+ },
78
+ blocker: {
79
+ type: ['string', 'null'],
80
+ description: 'when done is false, one sentence naming what blocked you (a file you could not read, a tool that refused, data that was missing); null when done is true',
81
+ },
82
+ });
83
+
84
+ const GREEN_SCHEMA = Object.freeze({
85
+ type: 'object',
86
+ properties: {
87
+ fields: {
88
+ type: 'object',
89
+ additionalProperties: {
90
+ type: 'object',
91
+ properties: { value: {}, cite: { type: 'string' } },
92
+ required: ['value', 'cite'],
93
+ },
94
+ },
95
+ ...DONE_PROPS,
96
+ },
97
+ required: ['fields', 'done'],
98
+ });
99
+
100
+ const SOFTGREEN_SCHEMA = Object.freeze({
101
+ type: 'object',
102
+ properties: {
103
+ text: { type: 'string' },
104
+ lines: { type: 'array', items: { type: 'string' } },
105
+ ...DONE_PROPS,
106
+ },
107
+ required: ['text', 'done'],
108
+ });
109
+
110
+ // hitl/read-style steps: the documented common shapes are {text} or
111
+ // {cells}, but a step with no declared guardrail (M1's own silent-default
112
+ // hitl, e.g. job #1's read steps) may legitimately emit any typed object —
113
+ // `additionalProperties: true` accepts that without ever consulting the
114
+ // step's shape (there is none to consult here; only its class).
115
+ const HITL_SCHEMA = Object.freeze({
116
+ type: 'object',
117
+ properties: {
118
+ text: { type: 'string' },
119
+ cells: { type: 'object' },
120
+ ...DONE_PROPS,
121
+ },
122
+ required: ['done'],
123
+ additionalProperties: true,
124
+ });
125
+
126
+ /**
127
+ * Build the `emit_artifact` tool schema from a step's declared close CLASS
128
+ * only. `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`.
129
+ */
130
+ export function buildEmitArtifactSchema(stepClass) {
131
+ if (stepClass === 'green') return GREEN_SCHEMA;
132
+ if (stepClass === 'softgreen') return SOFTGREEN_SCHEMA;
133
+ return HITL_SCHEMA;
134
+ }
135
+
136
+ function addCost(cumulative, metered) {
137
+ const rounds = cumulative.rounds + metered.rounds;
138
+ if (cumulative.costUsd === null || metered.costUsd === null) return { costUsd: null, rounds };
139
+ return { costUsd: cumulative.costUsd + metered.costUsd, rounds };
140
+ }
141
+
142
+ /**
143
+ * @param {object} opts
144
+ * @param {string} [opts.slot] - a `src/provider.js` PROVIDER_SLOTS name; required when `provider` isn't injected.
145
+ * @param {string} [opts.model] - overrides the slot's default model.
146
+ * @param {string} opts.spendPath - the run's spend.jsonl (never a second ledger).
147
+ * @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
148
+ * @param {{in:number,out:number}} [opts.rates]
149
+ * @param {string} [opts.modelId]
150
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}) => Promise<any>}
151
+ */
152
+ export function makeLiveModelStep({
153
+ slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId,
154
+ }) {
155
+ const live = injectedProvider == null;
156
+
157
+ return async function liveModelStep(executorContext, grantedTools, stepMeta = {}) {
158
+ let provider = injectedProvider;
159
+ let rates = injectedRates;
160
+ let modelId = injectedModelId;
161
+ if (live) {
162
+ // makeProvider throws synchronously on a missing/bad key, an unknown
163
+ // slot, or an unrated model — never let that escape as an unhandled
164
+ // rejection out of the ralph loop; a step's own model failure is
165
+ // always a red, never a crash (rule 5).
166
+ try {
167
+ if (!slot) throw new Error('makeLiveModelStep: "slot" is required when no provider is injected');
168
+ ({ provider, rates, modelId } = makeProvider(slot, { model, ...LIVE_PROVIDER_OPTIONS }));
169
+ } catch (err) {
170
+ return {
171
+ ok: false, red: `key: ${err.message}`, costUsd: null, model: model ?? null,
172
+ };
173
+ }
174
+ }
175
+
176
+ const toolSchema = buildEmitArtifactSchema(stepMeta.class);
177
+ const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
178
+ + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
179
+ + 'reads you were handed or the tools you were granted — never invent a figure.';
180
+ const userContent = JSON.stringify({
181
+ goal: executorContext.goal,
182
+ reads: executorContext.reads,
183
+ gap: executorContext.gap,
184
+ });
185
+ const messages = [
186
+ { role: 'system', content: systemPrompt },
187
+ { role: 'user', content: userContent },
188
+ ];
189
+
190
+ const primitiveTools = Object.values(grantedTools ?? {}).filter(Boolean);
191
+
192
+ let cumulative = { costUsd: 0, rounds: 0 };
193
+ let noToolCallStreak = 0;
194
+
195
+ for (let round = 1; round <= 3; round += 1) {
196
+ let capturedArtifact;
197
+ const emitTool = {
198
+ name: 'emit_artifact',
199
+ description: "Emit this step's one artifact.",
200
+ parameters: toolSchema,
201
+ execute: async (args) => { capturedArtifact = args; return { ok: true }; },
202
+ };
203
+ const tools = [...primitiveTools, emitTool];
204
+ const roundMeterings = [];
205
+ const loop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundMeterings.push(ev); } });
206
+
207
+ const startedAt = Date.now();
208
+ let result;
209
+ try {
210
+ // eslint-disable-next-line no-await-in-loop
211
+ result = await loop.run(messages, tools, { maxTokens: 16000 });
212
+ } catch (err) {
213
+ const wallMs = Date.now() - startedAt;
214
+ const partial = sumMeterings(roundMeterings);
215
+ cumulative = addCost(cumulative, partial);
216
+ appendSpendRow(spendPath, {
217
+ model: modelId,
218
+ modelReturned: partial.model,
219
+ tokens: partial.tokens,
220
+ costUsd: partial.costUsd,
221
+ rounds: partial.rounds,
222
+ wallMs,
223
+ error: err.message,
224
+ });
225
+ if (isTransportFailure(err)) {
226
+ return {
227
+ ok: false,
228
+ transport: true,
229
+ costUsd: cumulative.costUsd,
230
+ spendComplete: false,
231
+ red: `provider-red: ${err.message}`,
232
+ model: modelId,
233
+ modelMatch: classifyModelId(modelId, partial.model),
234
+ };
235
+ }
236
+ if (err?.code === 'EDEADLINE') {
237
+ return {
238
+ ok: false,
239
+ red: `wall-halt: ${err.message}`,
240
+ costUsd: cumulative.costUsd,
241
+ model: modelId,
242
+ modelMatch: classifyModelId(modelId, partial.model),
243
+ };
244
+ }
245
+ // Any other application-level error: a genuine red, never thrown,
246
+ // never retried by this module (piece 1's ralph loop governs a
247
+ // whole new attempt if it wants one).
248
+ return {
249
+ ok: false,
250
+ red: `provider-red: ${err.message}`,
251
+ costUsd: cumulative.costUsd,
252
+ model: modelId,
253
+ modelMatch: classifyModelId(modelId, partial.model),
254
+ };
255
+ }
256
+
257
+ const wallMs = Date.now() - startedAt;
258
+ const metered = sumMeterings(roundMeterings);
259
+ cumulative = addCost(cumulative, metered);
260
+ appendSpendRow(spendPath, {
261
+ model: modelId,
262
+ modelReturned: metered.model,
263
+ tokens: metered.tokens,
264
+ costUsd: metered.costUsd,
265
+ rounds: metered.rounds,
266
+ wallMs,
267
+ stopReason: result.stopReason ?? null,
268
+ });
269
+
270
+ const modelMatch = classifyModelId(modelId, metered.model);
271
+
272
+ if (result.stopReason === 'max_tokens') {
273
+ // Rule 4: deterministic (the step needs a smaller output or a
274
+ // bigger cap), never a transient fault a retry could fix.
275
+ return {
276
+ ok: false,
277
+ red: `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
278
+ costUsd: cumulative.costUsd,
279
+ model: modelId,
280
+ modelMatch,
281
+ };
282
+ }
283
+
284
+ if (capturedArtifact === undefined) {
285
+ noToolCallStreak += 1;
286
+ if (noToolCallStreak >= 2) {
287
+ const malformed = provider?.lastMalformedToolCall ?? null;
288
+ if (malformed) {
289
+ return {
290
+ ok: false,
291
+ red: `the tool call's arguments were not valid JSON twice in a row (${malformed.error}); raw: ${malformed.rawArguments}`,
292
+ costUsd: cumulative.costUsd,
293
+ model: modelId,
294
+ modelMatch,
295
+ };
296
+ }
297
+ return {
298
+ ok: false,
299
+ red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool twice in a row. Text: ${JSON.stringify(result.text)}`,
300
+ costUsd: cumulative.costUsd,
301
+ model: modelId,
302
+ modelMatch,
303
+ };
304
+ }
305
+ // eslint-disable-next-line no-continue
306
+ continue; // retry once, same attempt
307
+ }
308
+
309
+ if (cumulative.costUsd === null) {
310
+ return {
311
+ ok: false, red: 'pricing-red: an unpriced round leaves this attempt\'s cost unknown', costUsd: null, model: modelId, modelMatch,
312
+ };
313
+ }
314
+
315
+ return {
316
+ ok: true, artifact: capturedArtifact, costUsd: cumulative.costUsd, model: modelId, modelMatch,
317
+ };
318
+ }
319
+
320
+ return {
321
+ ok: false, red: 'exhausted rounds without a clean result', costUsd: cumulative.costUsd, model: modelId,
322
+ };
323
+ };
324
+ }