fwdloop 0.4.1 → 0.6.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/csv.js ADDED
@@ -0,0 +1,57 @@
1
+ // borrowed-from: fwdloop poc/m0/csv.mjs@76a3607 (verbatim logic). Tiny CSV
2
+ // parser — never quoted-field aware, which every fixture this project reads
3
+ // doesn't need (dependency hierarchy: stdlib/vanilla first). The addressable
4
+ // -cells contract (`parseCellRef`/`colLetter`) is fwdloop's own citation
5
+ // grammar (F13, ruled 2026-09-09 — not a baresuite primitive), so it lives
6
+ // with the reader that produces those addresses.
7
+
8
+ /** Column letter for a 0-based column index: 0 -> 'A', 1 -> 'B', ... */
9
+ export function colLetter(i) {
10
+ let n = i + 1;
11
+ let s = '';
12
+ while (n > 0) {
13
+ const rem = (n - 1) % 26;
14
+ s = String.fromCharCode(65 + rem) + s;
15
+ n = Math.floor((n - 1) / 26);
16
+ }
17
+ return s;
18
+ }
19
+
20
+ /** Column index (0-based) for a column letter: 'A' -> 0, 'B' -> 1, ... */
21
+ export function colIndex(letter) {
22
+ let n = 0;
23
+ for (const ch of letter) n = n * 26 + (ch.charCodeAt(0) - 64);
24
+ return n - 1;
25
+ }
26
+
27
+ /** Parse a cell ref like "E2" into { col: 'E', row: 2 }. */
28
+ export function parseCellRef(cell) {
29
+ const m = /^([A-Z]+)(\d+)$/.exec(cell);
30
+ if (!m) throw new Error(`bad cell ref "${cell}"`);
31
+ return { col: m[1], row: Number(m[2]) };
32
+ }
33
+
34
+ /**
35
+ * Parse CSV text with no quoted fields into { header, rows }.
36
+ * `rows[i]` is `{ rowNumber, cells: { A: '...', B: '...' }, byName: { Customer: '...' } }`
37
+ * where `rowNumber` is the 1-based sheet row (header is row 1, first data row is row 2).
38
+ */
39
+ export function parseCsv(text) {
40
+ const lines = text.split(/\r?\n/).filter((l) => l.length > 0);
41
+ if (lines.length === 0) return { header: [], rows: [] };
42
+ const header = lines[0].split(',');
43
+ const rows = [];
44
+ for (let i = 1; i < lines.length; i += 1) {
45
+ const fields = lines[i].split(',');
46
+ const cells = {};
47
+ const byName = {};
48
+ header.forEach((name, col) => {
49
+ const letter = colLetter(col);
50
+ const val = fields[col] ?? '';
51
+ cells[letter] = val;
52
+ byName[name] = val;
53
+ });
54
+ rows.push({ rowNumber: i + 1, cells, byName });
55
+ }
56
+ return { header, rows };
57
+ }
@@ -623,7 +623,18 @@ export function validateDeclaration(declaration, context = {}) {
623
623
  reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) is not granted a catalogue primitive of class "write"`);
624
624
  }
625
625
 
626
- const earlierAskLines = askLines.filter((a) => a < n);
626
+ // M3 scope item 8 (F42's "Also seen" note): "earlier" is judged by STEP
627
+ // ORDER, never by prose line number — the runner folds over
628
+ // `declaration.steps` in array order (`acceptedAskEmitsThisRun` is
629
+ // populated as steps execute), so a line-number comparison here can
630
+ // disagree with what actually runs. A signed ask whose step sits before
631
+ // the send step in `declaration.steps`, whatever its own prose line
632
+ // number, is "earlier"; one whose step sits at or after the send step
633
+ // never is, even if its line number is smaller.
634
+ const earlierAskLines = askLines.filter((a) => {
635
+ const askIdx = stepInfo.findIndex((st) => st.fromLine === a);
636
+ return askIdx !== -1 && askIdx < sendIdx;
637
+ });
627
638
  if (earlierAskLines.length === 0) {
628
639
  reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) has no signed ask at an earlier line to read from`);
629
640
  } else {
@@ -631,14 +642,42 @@ export function validateDeclaration(declaration, context = {}) {
631
642
  .map((a) => stepInfo.find((st) => st.fromLine === a))
632
643
  .filter((st) => st !== undefined)
633
644
  .map((st) => st.emits);
634
- const readsAnAsk = earlierAskEmits.some((emits) => emits !== null && sendStep.reads.includes(emits));
635
- if (!readsAnAsk) {
645
+ const readAskEmits = earlierAskEmits.filter((emits) => emits !== null && sendStep.reads.includes(emits));
646
+ if (readAskEmits.length === 0) {
636
647
  reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) does not read the emits of any earlier signed `
637
648
  + `ask step (asks at lines ${earlierAskLines.join(', ')})`);
649
+ } else if (readAskEmits.length >= 2) {
650
+ reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) reads the emits of more than one earlier signed `
651
+ + `ask step (${readAskEmits.join(', ')}) — exactly 1 required`);
638
652
  }
639
653
  }
640
654
  }
641
655
 
656
+ // --- M2 amendment 1 item 2 (docs/wiki/the-module-ladder.md, "M2 amendment
657
+ // 1 — SIGNED"): nothing hitl-class may sit after the LAST signed ask,
658
+ // unseen — the send step bound to a signed send line is the one exempt
659
+ // step (it is itself hitl-class by silence in both fixtures, but it is
660
+ // the human-accepted egress, not a second undeclared pause). Anchored on
661
+ // STEP ORDER (a step's position in `declaration.steps`, not its line
662
+ // number) since that is the order the runner actually folds over. No
663
+ // anchor to check against when there is no signed ask at all.
664
+ if (askLines.length > 0) {
665
+ const lastAskLine = Math.max(...askLines);
666
+ const lastAskStepIdx = stepInfo.findIndex((st) => st.fromLine === lastAskLine);
667
+ if (lastAskStepIdx !== -1) {
668
+ const sendStepIndices = new Set();
669
+ for (const n of sendLines) {
670
+ const idx = stepInfo.findIndex((st) => st.fromLine === n);
671
+ if (idx !== -1) sendStepIndices.add(idx);
672
+ }
673
+ stepInfo.forEach((st, i) => {
674
+ if (i > lastAskStepIdx && st.effectiveClass === 'hitl' && !sendStepIndices.has(i)) {
675
+ reds.push(`declaration: step "${st.emits}" (line ${st.fromLine}) is hitl after the last signed ask — nothing may leave unseen`);
676
+ }
677
+ });
678
+ }
679
+ }
680
+
642
681
  // --- check 6: every numbered line must be served or refused, never dropped
643
682
  const claimedLines = new Set(stepInfo.map((st) => st.fromLine).filter((n) => Number.isInteger(n)));
644
683
  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/index.js CHANGED
@@ -10,3 +10,8 @@ export {
10
10
  export {
11
11
  checkFlowName, writeFlow, readFlow, FLOW_FILES,
12
12
  } from './flow.js';
13
+ export {
14
+ runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS,
15
+ } from './runner.js';
16
+ export { closeByClass } from './closers.js';
17
+ export { makeFileAskStep, answerAsk } from './ask.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 2 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 <= 2; 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
+ }