fwdloop 0.6.0 → 0.7.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 +143 -64
- package/package.json +3 -3
- package/src/ask.js +260 -6
- package/src/books.js +209 -2
- package/src/flow.js +247 -2
- package/src/index.js +9 -3
- package/src/model-step.js +151 -12
- package/src/panel/data.js +1589 -0
- package/src/panel/index.html +2377 -0
- package/src/panel/server.js +268 -0
- package/src/primitives.js +136 -41
- package/src/provider.js +57 -41
- package/src/runner.js +393 -54
- package/src/send.js +20 -1
- package/src/types.js +18 -0
- package/types/ask.d.ts +77 -0
- package/types/books.d.ts +70 -2
- package/types/flow.d.ts +135 -0
- package/types/index.d.ts +5 -3
- package/types/panel/data.d.ts +433 -0
- package/types/panel/server.d.ts +45 -0
- package/types/primitives.d.ts +29 -0
- package/types/provider.d.ts +11 -0
- package/types/runner.d.ts +66 -5
- package/types/types.d.ts +41 -0
package/src/flow.js
CHANGED
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
// caught and returned as a red naming the file or path involved.
|
|
21
21
|
|
|
22
22
|
import {
|
|
23
|
-
accessSync, constants as fsConstants, existsSync, lstatSync, mkdirSync,
|
|
24
|
-
writeFileSync,
|
|
23
|
+
accessSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync,
|
|
24
|
+
renameSync, rmSync, writeFileSync,
|
|
25
25
|
} from 'node:fs';
|
|
26
26
|
import path from 'node:path';
|
|
27
27
|
|
|
@@ -78,6 +78,251 @@ export function checkFlowName(name) {
|
|
|
78
78
|
return { ok: true };
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Check a runId against the allowed shape: 1..128 characters, letters
|
|
83
|
+
* (upper or lower), digits, `.`, `_`, `-`, starting with a letter or digit.
|
|
84
|
+
* Walked character by character — never a regex — same reasoning as
|
|
85
|
+
* `checkFlowName`: a runId that would escape the flow's runs directory
|
|
86
|
+
* (`..`, a `/` or `\` segment, a NUL byte, an absolute path) is refused by
|
|
87
|
+
* the same loop that refuses a bad character, not a separate ad-hoc check.
|
|
88
|
+
*
|
|
89
|
+
* One writer: every caller that turns an externally-supplied runId into a
|
|
90
|
+
* path (`bin/fwdloop`'s `run`/`resume`, `runFlow`, `resumeRun`) goes through
|
|
91
|
+
* this function (via `resolveRunDir`, below) — a runId is never trusted
|
|
92
|
+
* enough to be joined onto a path any other way. Fixes the path escape a
|
|
93
|
+
* branch review found: `--run-id ../../../../tmp/pwned`.
|
|
94
|
+
*
|
|
95
|
+
* @param {unknown} runId
|
|
96
|
+
* @returns {{ok:true}|{ok:false,red:string}}
|
|
97
|
+
*/
|
|
98
|
+
export function checkRunId(runId) {
|
|
99
|
+
if (typeof runId !== 'string') {
|
|
100
|
+
return { ok: false, red: 'run: runId must be a string' };
|
|
101
|
+
}
|
|
102
|
+
if (runId.length === 0) {
|
|
103
|
+
return { ok: false, red: 'run: runId must not be empty' };
|
|
104
|
+
}
|
|
105
|
+
if (runId.length > 128) {
|
|
106
|
+
return { ok: false, red: `run: runId is ${runId.length} characters, must be 1..128` };
|
|
107
|
+
}
|
|
108
|
+
for (let i = 0; i < runId.length; i += 1) {
|
|
109
|
+
const ch = runId[i];
|
|
110
|
+
const isDigit = ch >= '0' && ch <= '9';
|
|
111
|
+
const isUpper = ch >= 'A' && ch <= 'Z';
|
|
112
|
+
const isLower = ch >= 'a' && ch <= 'z';
|
|
113
|
+
const isDotDashUnderscore = ch === '.' || ch === '-' || ch === '_';
|
|
114
|
+
if (i === 0) {
|
|
115
|
+
if (!isDigit && !isUpper && !isLower) {
|
|
116
|
+
return { ok: false, red: `run: runId "${runId}" must start with a letter or digit, got "${ch}"` };
|
|
117
|
+
}
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (!isDigit && !isUpper && !isLower && !isDotDashUnderscore) {
|
|
121
|
+
return { ok: false, red: `run: runId "${runId}" character ${i} ("${ch}") is not one of A-Z, a-z, 0-9, ".", "-", "_"` };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (runId.includes('..')) {
|
|
125
|
+
return { ok: false, red: `run: runId "${runId}" must not contain ".."` };
|
|
126
|
+
}
|
|
127
|
+
return { ok: true };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Turn a checked runId into its run directory under `flowDir/runs/`, then
|
|
132
|
+
* confirm the built path actually resolves INSIDE that runs directory —
|
|
133
|
+
* belt and braces alongside `checkRunId`'s character allow-list (mirrors
|
|
134
|
+
* `src/runner.js`'s own `checkSendDestination` shape: lexical containment,
|
|
135
|
+
* checked after the path is built, never trusted from the allow-list
|
|
136
|
+
* alone).
|
|
137
|
+
*
|
|
138
|
+
* Lexical containment (`path.resolve` plus a prefix compare) only catches a
|
|
139
|
+
* bad runId string — it does not catch a runId that *passes* the allow-list
|
|
140
|
+
* but names a symlink pointing outside `flowDir/runs/` (F36 fixed `runs/`
|
|
141
|
+
* itself being a symlink; this is the same class one level down, for an
|
|
142
|
+
* entry inside it). So once the lexical check passes, anything that
|
|
143
|
+
* actually EXISTS on disk is re-checked with `realpathSync`: `runs/` itself
|
|
144
|
+
* must realpath inside `flowDir` (mirrors F36's `readFlow` check), and — if
|
|
145
|
+
* the run dir exists — it must realpath inside the real `runs/` dir. A
|
|
146
|
+
* not-yet-existing run dir (a new run being created) has nothing to
|
|
147
|
+
* realpath yet, so only the lexical result is returned for it; the check
|
|
148
|
+
* holds at use time (here, on every call), not only at some earlier
|
|
149
|
+
* preflight.
|
|
150
|
+
*
|
|
151
|
+
* @param {string} flowDir
|
|
152
|
+
* @param {unknown} runId
|
|
153
|
+
* @returns {{ok:true, runDir:string}|{ok:false, red:string}}
|
|
154
|
+
*/
|
|
155
|
+
export function resolveRunDir(flowDir, runId) {
|
|
156
|
+
const check = checkRunId(runId);
|
|
157
|
+
if (!check.ok) return check;
|
|
158
|
+
const runsDir = path.join(flowDir, RUNS_DIR);
|
|
159
|
+
const runDir = path.join(runsDir, /** @type {string} */ (runId));
|
|
160
|
+
const resolvedRunsDir = path.resolve(runsDir);
|
|
161
|
+
const resolvedRunDir = path.resolve(runDir);
|
|
162
|
+
if (resolvedRunDir !== resolvedRunsDir && !resolvedRunDir.startsWith(resolvedRunsDir + path.sep)) {
|
|
163
|
+
return { ok: false, red: `run: runId "${runId}" resolves outside the runs directory — refused` };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (existsSync(runsDir)) {
|
|
167
|
+
let realRunsDir;
|
|
168
|
+
let realFlowDir;
|
|
169
|
+
try {
|
|
170
|
+
realRunsDir = realpathSync(runsDir);
|
|
171
|
+
realFlowDir = realpathSync(flowDir);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
return { ok: false, red: `run: could not resolve "${runsDir}" — ${err.message}` };
|
|
174
|
+
}
|
|
175
|
+
if (realRunsDir !== realFlowDir && !realRunsDir.startsWith(realFlowDir + path.sep)) {
|
|
176
|
+
return { ok: false, red: `run: "${RUNS_DIR}" is a symlink that resolves outside the flow directory (${realRunsDir}) — refused` };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (existsSync(runDir)) {
|
|
180
|
+
let realRunDir;
|
|
181
|
+
try {
|
|
182
|
+
realRunDir = realpathSync(runDir);
|
|
183
|
+
} catch (err) {
|
|
184
|
+
return { ok: false, red: `run: could not resolve "${runDir}" — ${err.message}` };
|
|
185
|
+
}
|
|
186
|
+
if (realRunDir !== realRunsDir && !realRunDir.startsWith(realRunsDir + path.sep)) {
|
|
187
|
+
return { ok: false, red: `run: runId "${runId}" is a symlink that resolves outside the runs directory (${realRunDir}) — refused` };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return { ok: true, runDir: resolvedRunDir };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Every flow name that has a real, readable directory under `root` — M4a
|
|
197
|
+
* piece 2 (docs/wiki/the-module-ladder.md M4a scope item 2: "every flow
|
|
198
|
+
* under --root"). A directory entry that fails `checkFlowName` (should not
|
|
199
|
+
* happen for anything `writeFlow` itself created, but a hand-placed or
|
|
200
|
+
* legacy directory is possible) is skipped rather than crashing the whole
|
|
201
|
+
* listing — this is a best-effort enumeration, not a validator; a caller
|
|
202
|
+
* that wants to know a flow is well-formed calls `readFlow` on it.
|
|
203
|
+
* `[]` when `root` doesn't exist or has no entries — never a thrown error.
|
|
204
|
+
* Sorted so a caller gets a stable, deterministic order.
|
|
205
|
+
* @param {string} root
|
|
206
|
+
* @returns {string[]}
|
|
207
|
+
*/
|
|
208
|
+
export function listFlowNames(root) {
|
|
209
|
+
if (typeof root !== 'string' || root.length === 0 || !existsSync(root)) return [];
|
|
210
|
+
let entries;
|
|
211
|
+
try {
|
|
212
|
+
entries = readdirSync(root, { withFileTypes: true });
|
|
213
|
+
} catch {
|
|
214
|
+
return [];
|
|
215
|
+
}
|
|
216
|
+
return entries
|
|
217
|
+
.filter((e) => e.isDirectory() && checkFlowName(e.name).ok)
|
|
218
|
+
.map((e) => e.name)
|
|
219
|
+
.sort();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Every runId with a real, readable directory under a flow's own `runs/`
|
|
224
|
+
* (M4a scope item 2: "every run"). Same best-effort posture as {@link
|
|
225
|
+
* listFlowNames} — a malformed entry is skipped, never thrown on.
|
|
226
|
+
* @param {string} flowDir
|
|
227
|
+
* @returns {string[]}
|
|
228
|
+
*/
|
|
229
|
+
export function listRunIds(flowDir) {
|
|
230
|
+
const runsDir = path.join(flowDir, RUNS_DIR);
|
|
231
|
+
if (!existsSync(runsDir)) return [];
|
|
232
|
+
let entries;
|
|
233
|
+
try {
|
|
234
|
+
entries = readdirSync(runsDir, { withFileTypes: true });
|
|
235
|
+
} catch {
|
|
236
|
+
return [];
|
|
237
|
+
}
|
|
238
|
+
return entries
|
|
239
|
+
.filter((e) => e.isDirectory() && checkRunId(e.name).ok)
|
|
240
|
+
.map((e) => e.name)
|
|
241
|
+
.sort();
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
|
|
246
|
+
* in src/ and bin/ routes through to read a file that lives inside a run
|
|
247
|
+
* dir or flow dir — closing the symlink-escape class at the source instead
|
|
248
|
+
* of patching each reader a second time. `resolveInside(baseDir, relPath)`
|
|
249
|
+
* requires the target to both (a) not itself be a symlink and (b) realpath
|
|
250
|
+
* to somewhere inside `realpath(baseDir)` — the second check alone also
|
|
251
|
+
* catches a symlinked ANCESTOR directory partway down `relPath` (e.g.
|
|
252
|
+
* `asks/` itself replaced by a symlink to an outside directory), the same
|
|
253
|
+
* shape `readFlow`'s own `runs/` check and `resolveRunDir` already apply one
|
|
254
|
+
* level up. A path that does not exist yet is reported as `missing: true`
|
|
255
|
+
* (never a red) so every existing caller keeps its own "not written yet"
|
|
256
|
+
* behaviour unchanged.
|
|
257
|
+
*
|
|
258
|
+
* @param {string} baseDir
|
|
259
|
+
* @param {string} relPath
|
|
260
|
+
* @returns {{ok:true, full:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
|
|
261
|
+
*/
|
|
262
|
+
export function resolveInside(baseDir, relPath) {
|
|
263
|
+
const full = path.join(baseDir, relPath);
|
|
264
|
+
let stat;
|
|
265
|
+
try {
|
|
266
|
+
stat = lstatSync(full);
|
|
267
|
+
} catch {
|
|
268
|
+
return { ok: false, missing: true };
|
|
269
|
+
}
|
|
270
|
+
if (stat.isSymbolicLink()) {
|
|
271
|
+
return { ok: false, missing: false, red: `"${relPath}" is a symlink, refused` };
|
|
272
|
+
}
|
|
273
|
+
let realBase;
|
|
274
|
+
let realFull;
|
|
275
|
+
try {
|
|
276
|
+
realBase = realpathSync(baseDir);
|
|
277
|
+
realFull = realpathSync(full);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
return { ok: false, missing: false, red: `could not resolve "${relPath}" — ${err.message}` };
|
|
280
|
+
}
|
|
281
|
+
if (realFull !== realBase && !realFull.startsWith(realBase + path.sep)) {
|
|
282
|
+
return { ok: false, missing: false, red: `"${relPath}" resolves outside its directory — refused` };
|
|
283
|
+
}
|
|
284
|
+
return { ok: true, full };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* `resolveInside` plus the actual read — every raw-text book reader's one
|
|
289
|
+
* gateway. Same result shape as `resolveInside`, plus `{ok:true, text}`.
|
|
290
|
+
* @param {string} baseDir
|
|
291
|
+
* @param {string} relPath
|
|
292
|
+
* @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
|
|
293
|
+
*/
|
|
294
|
+
export function readFileInside(baseDir, relPath) {
|
|
295
|
+
const resolved = resolveInside(baseDir, relPath);
|
|
296
|
+
if (!resolved.ok) return resolved;
|
|
297
|
+
try {
|
|
298
|
+
return { ok: true, text: readFileSync(resolved.full, 'utf8') };
|
|
299
|
+
} catch (err) {
|
|
300
|
+
return { ok: false, missing: false, red: `could not read "${relPath}" — ${err.message}` };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
|
|
306
|
+
* itself is a symlink or resolves outside `baseDir`, and skips (never
|
|
307
|
+
* follows) any individual entry that is itself a symlink — a directory
|
|
308
|
+
* listing must never hand a caller a name that, joined back onto `relDir`,
|
|
309
|
+
* would escape `baseDir`. `[]` when `relDir` doesn't exist.
|
|
310
|
+
* @param {string} baseDir
|
|
311
|
+
* @param {string} relDir
|
|
312
|
+
* @returns {string[]}
|
|
313
|
+
*/
|
|
314
|
+
export function readdirInside(baseDir, relDir) {
|
|
315
|
+
const resolved = resolveInside(baseDir, relDir);
|
|
316
|
+
if (!resolved.ok) return [];
|
|
317
|
+
let entries;
|
|
318
|
+
try {
|
|
319
|
+
entries = readdirSync(resolved.full, { withFileTypes: true });
|
|
320
|
+
} catch {
|
|
321
|
+
return [];
|
|
322
|
+
}
|
|
323
|
+
return entries.filter((e) => !e.isSymbolicLink()).map((e) => e.name);
|
|
324
|
+
}
|
|
325
|
+
|
|
81
326
|
function readTextFile(filePath, label, reds) {
|
|
82
327
|
let stat;
|
|
83
328
|
try {
|
package/src/index.js
CHANGED
|
@@ -8,10 +8,16 @@ export {
|
|
|
8
8
|
parseCatalogue, loadCatalogue, menu, primitiveFor, resolveEntry, CATALOGUE_FIELDS,
|
|
9
9
|
} from './catalogue.js';
|
|
10
10
|
export {
|
|
11
|
-
checkFlowName, writeFlow, readFlow, FLOW_FILES,
|
|
11
|
+
checkFlowName, checkRunId, resolveRunDir, writeFlow, readFlow, listFlowNames, listRunIds, FLOW_FILES,
|
|
12
12
|
} from './flow.js';
|
|
13
13
|
export {
|
|
14
|
-
runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS,
|
|
14
|
+
runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS, readAsk, readRunState, readLog,
|
|
15
15
|
} from './runner.js';
|
|
16
16
|
export { closeByClass } from './closers.js';
|
|
17
|
-
export {
|
|
17
|
+
export {
|
|
18
|
+
makeFileAskStep, answerAsk, readAskEvidence, writeAskArchive, listArchivedAsks,
|
|
19
|
+
} from './ask.js';
|
|
20
|
+
export {
|
|
21
|
+
appendAudit, appendHistory, readAudit, readHistory, auditRowTokens, auditRowTools,
|
|
22
|
+
} from './books.js';
|
|
23
|
+
export { readSpendRows } from './provider.js';
|
package/src/model-step.js
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
// executor context (M2 scope item 3) carries neither.
|
|
26
26
|
|
|
27
27
|
import { Loop } from 'bare-agent';
|
|
28
|
+
import { GateRefusal } from './primitives.js';
|
|
28
29
|
|
|
29
30
|
import {
|
|
30
31
|
makeProvider, sumMeterings, appendSpendRow, classifyModelId,
|
|
@@ -133,10 +134,92 @@ export function buildEmitArtifactSchema(stepClass) {
|
|
|
133
134
|
return HITL_SCHEMA;
|
|
134
135
|
}
|
|
135
136
|
|
|
136
|
-
|
|
137
|
+
// M4a-2 (docs/wiki/the-module-ladder.md, "M4a" section, "Amendment M4a-2 —
|
|
138
|
+
// SIGNED by hamr 2026-09-27"): the attempt's `tokens` for the audit row are
|
|
139
|
+
// summed here, at the SAME place `costUsd` already sums across rounds —
|
|
140
|
+
// never re-derived later by position from spend.jsonl (`src/books.js`'s own
|
|
141
|
+
// audit row is a different book with a different granularity: one row per
|
|
142
|
+
// ATTEMPT, not per round). Only the three fields the audit row's contract
|
|
143
|
+
// names (`inputTokens`, `outputTokens`, `cacheReadTokens`) are carried
|
|
144
|
+
// forward; `sumMeterings`' own `cacheCreationTokens` stays in spend.jsonl
|
|
145
|
+
// only. A round with no metering at all (`metered.tokens === null`, e.g. a
|
|
146
|
+
// synchronous throw before any `onLlmResult` fired) contributes zero, never
|
|
147
|
+
// turns the running total null — once ANY round in this attempt actually
|
|
148
|
+
// ran, the attempt's tokens are a known (possibly partial) count, not
|
|
149
|
+
// "unknown".
|
|
150
|
+
function addMeter(cumulative, metered) {
|
|
137
151
|
const rounds = cumulative.rounds + metered.rounds;
|
|
138
|
-
|
|
139
|
-
|
|
152
|
+
const costUsd = (cumulative.costUsd === null || metered.costUsd === null)
|
|
153
|
+
? null
|
|
154
|
+
: cumulative.costUsd + metered.costUsd;
|
|
155
|
+
const tokens = {
|
|
156
|
+
inputTokens: cumulative.tokens.inputTokens + (metered.tokens?.inputTokens ?? 0),
|
|
157
|
+
outputTokens: cumulative.tokens.outputTokens + (metered.tokens?.outputTokens ?? 0),
|
|
158
|
+
cacheReadTokens: cumulative.tokens.cacheReadTokens + (metered.tokens?.cacheReadTokens ?? 0),
|
|
159
|
+
};
|
|
160
|
+
// M4a-3: this function only ever touches cost/rounds/tokens — `tools`/
|
|
161
|
+
// `ungranted` (added by `addToolCounts`, a separate accumulator with a
|
|
162
|
+
// separate source of truth, bare-agent's `metrics.byTool`) must survive a
|
|
163
|
+
// round that never got that far, e.g. a round whose provider call threw
|
|
164
|
+
// before `loop.run` returned anything to count tool calls FROM. Dropping
|
|
165
|
+
// them here (returning a bare {costUsd,rounds,tokens}) would silently
|
|
166
|
+
// erase every earlier round's real tool tally the moment a later round
|
|
167
|
+
// faulted — caught live: `toolFields` threw on `cumulative.ungranted`
|
|
168
|
+
// being undefined the very first time a transport fault hit round 1.
|
|
169
|
+
return {
|
|
170
|
+
costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// M4a-3 (docs/wiki/the-module-ladder.md, "M4a" section, "Amendment M4a-3 —
|
|
175
|
+
// SIGNED by hamr 2026-09-27"): the attempt's `tools` tally, taken from
|
|
176
|
+
// bare-agent's OWN per-round `result.metrics.byTool` — the same counter
|
|
177
|
+
// bare-agent bumps for every tool call the model makes regardless of outcome
|
|
178
|
+
// (BA's own comment: "a denied or unknown call is still an invocation the
|
|
179
|
+
// operator wants to see"). Never re-derived from an `onToolCall` hook: that
|
|
180
|
+
// hook only fires for a call that matched a tool bare-agent actually offered
|
|
181
|
+
// the model (`toolMap.get(tc.name)` succeeded), so a genuinely UNGRANTED
|
|
182
|
+
// name — one the model hallucinated that was never in this attempt's `tools`
|
|
183
|
+
// array at all — never reaches it; `metrics.byTool` is the one place both
|
|
184
|
+
// shapes are counted. `emit_artifact` is the step's own mandatory output
|
|
185
|
+
// call, not a granted primitive, and is deliberately never tallied into
|
|
186
|
+
// `tools` or `ungranted` (flagged for hamr's ruling if this reads
|
|
187
|
+
// differently — the amendment's own example, `{ read: 3, write: 1 }`, never
|
|
188
|
+
// mentions it either).
|
|
189
|
+
//
|
|
190
|
+
// Today, an ungranted name is refused by bare-agent BEFORE `tool.execute`
|
|
191
|
+
// ever runs (loop.js: `toolMap.get` misses -> `[Loop] Unknown tool: <name>`
|
|
192
|
+
// is fed back to the model as the tool result, `continue`s the round) — the
|
|
193
|
+
// model never gets real data back, it only learns the name doesn't exist.
|
|
194
|
+
// This module records that honestly: the name lands in `ungranted`, never
|
|
195
|
+
// silently folded into `tools` as if it had been allowed and had really run.
|
|
196
|
+
function addToolCounts(cumulative, byTool, grantedNames) {
|
|
197
|
+
const tools = { ...cumulative.tools };
|
|
198
|
+
const ungranted = new Set(cumulative.ungranted);
|
|
199
|
+
for (const [name, count] of Object.entries(byTool ?? {})) {
|
|
200
|
+
if (name === 'emit_artifact') continue;
|
|
201
|
+
if (grantedNames.has(name)) {
|
|
202
|
+
tools[name] = (tools[name] ?? 0) + count;
|
|
203
|
+
} else {
|
|
204
|
+
ungranted.add(name);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return { tools, ungranted: [...ungranted].sort() };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// M4a-3: the `tools`/`ungranted` fields every returned result shape carries,
|
|
211
|
+
// built from the running `cumulative` the same way `tokens`/`costUsd` are —
|
|
212
|
+
// `ungranted` is left OFF the result entirely once empty (the audit row
|
|
213
|
+
// contract allows "absent or an array of strings"; an empty array on every
|
|
214
|
+
// clean row would just be noise).
|
|
215
|
+
function toolFields(cumulative) {
|
|
216
|
+
return {
|
|
217
|
+
tools: cumulative.tools,
|
|
218
|
+
// Gate refusals this attempt — always present (empty array when none) so
|
|
219
|
+
// absence can never be confused with "none".
|
|
220
|
+
refused: cumulative.refused,
|
|
221
|
+
...(cumulative.ungranted.length > 0 ? { ungranted: cumulative.ungranted } : {}),
|
|
222
|
+
};
|
|
140
223
|
}
|
|
141
224
|
|
|
142
225
|
/**
|
|
@@ -167,8 +250,12 @@ export function makeLiveModelStep({
|
|
|
167
250
|
if (!slot) throw new Error('makeLiveModelStep: "slot" is required when no provider is injected');
|
|
168
251
|
({ provider, rates, modelId } = makeProvider(slot, { model, ...LIVE_PROVIDER_OPTIONS }));
|
|
169
252
|
} catch (err) {
|
|
253
|
+
// No provider was ever built, so no round could possibly have run —
|
|
254
|
+
// `tokens: null` (and `tools: null`, M4a-3) here is the one honest
|
|
255
|
+
// "no model call at all" case (never a zeroed object standing in for
|
|
256
|
+
// a call that never happened).
|
|
170
257
|
return {
|
|
171
|
-
ok: false, red: `key: ${err.message}`, costUsd: null, model: model ?? null,
|
|
258
|
+
ok: false, red: `key: ${err.message}`, costUsd: null, model: model ?? null, tokens: null, tools: null,
|
|
172
259
|
};
|
|
173
260
|
}
|
|
174
261
|
}
|
|
@@ -187,9 +274,37 @@ export function makeLiveModelStep({
|
|
|
187
274
|
{ role: 'user', content: userContent },
|
|
188
275
|
];
|
|
189
276
|
|
|
190
|
-
|
|
277
|
+
// Per-attempt collector for bareguard gate refusals: each primitive is
|
|
278
|
+
// wrapped so a typed GateRefusal is recorded, then rethrown unchanged so
|
|
279
|
+
// the model still sees the refusal as its tool result.
|
|
280
|
+
const refused = /** @type {Array<{verb:string, path:string, rule:string}>} */ ([]);
|
|
281
|
+
const primitiveTools = Object.values(grantedTools ?? {}).filter(Boolean).map((tool) => ({
|
|
282
|
+
...tool,
|
|
283
|
+
execute: async (...a) => {
|
|
284
|
+
try { return await tool.execute(...a); } catch (err) {
|
|
285
|
+
if (err instanceof GateRefusal) refused.push({ verb: err.verb, path: err.path, rule: err.rule });
|
|
286
|
+
throw err;
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
}));
|
|
290
|
+
// M4a-3: "granted" is the step's own declared verb set — the keys of
|
|
291
|
+
// `grantedTools` — not just the ones that resolved to a real primitive.
|
|
292
|
+
// An unresolved granted verb never becomes a callable tool below (it's
|
|
293
|
+
// filtered out of `primitiveTools` above), so the model could only ever
|
|
294
|
+
// reach it by hallucinating the name, which still counts as `ungranted`
|
|
295
|
+
// being wrong: it WAS granted, just broken. Treating it as granted here
|
|
296
|
+
// (never `ungranted`) is the honest read of what the human actually
|
|
297
|
+
// authorized this step to use.
|
|
298
|
+
const grantedNames = new Set(Object.keys(grantedTools ?? {}));
|
|
191
299
|
|
|
192
|
-
let cumulative = {
|
|
300
|
+
let cumulative = {
|
|
301
|
+
costUsd: 0,
|
|
302
|
+
rounds: 0,
|
|
303
|
+
tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 },
|
|
304
|
+
tools: /** @type {Record<string, number>} */ ({}),
|
|
305
|
+
ungranted: /** @type {string[]} */ ([]),
|
|
306
|
+
refused,
|
|
307
|
+
};
|
|
193
308
|
let noToolCallStreak = 0;
|
|
194
309
|
|
|
195
310
|
for (let round = 1; round <= 2; round += 1) {
|
|
@@ -212,7 +327,7 @@ export function makeLiveModelStep({
|
|
|
212
327
|
} catch (err) {
|
|
213
328
|
const wallMs = Date.now() - startedAt;
|
|
214
329
|
const partial = sumMeterings(roundMeterings);
|
|
215
|
-
cumulative =
|
|
330
|
+
cumulative = addMeter(cumulative, partial);
|
|
216
331
|
appendSpendRow(spendPath, {
|
|
217
332
|
model: modelId,
|
|
218
333
|
modelReturned: partial.model,
|
|
@@ -222,11 +337,18 @@ export function makeLiveModelStep({
|
|
|
222
337
|
wallMs,
|
|
223
338
|
error: err.message,
|
|
224
339
|
});
|
|
340
|
+
// The provider threw before `loop.run` ever returned a result, so no
|
|
341
|
+
// tool call could possibly have happened THIS round (M4a-3) —
|
|
342
|
+
// `cumulative.tools`/`ungranted` here are exactly whatever an
|
|
343
|
+
// earlier round in this same attempt already accumulated, never
|
|
344
|
+
// re-derived or invented for the round that just threw.
|
|
225
345
|
if (isTransportFailure(err)) {
|
|
226
346
|
return {
|
|
227
347
|
ok: false,
|
|
228
348
|
transport: true,
|
|
229
349
|
costUsd: cumulative.costUsd,
|
|
350
|
+
tokens: cumulative.tokens,
|
|
351
|
+
...toolFields(cumulative),
|
|
230
352
|
spendComplete: false,
|
|
231
353
|
red: `provider-red: ${err.message}`,
|
|
232
354
|
model: modelId,
|
|
@@ -238,6 +360,8 @@ export function makeLiveModelStep({
|
|
|
238
360
|
ok: false,
|
|
239
361
|
red: `wall-halt: ${err.message}`,
|
|
240
362
|
costUsd: cumulative.costUsd,
|
|
363
|
+
tokens: cumulative.tokens,
|
|
364
|
+
...toolFields(cumulative),
|
|
241
365
|
model: modelId,
|
|
242
366
|
modelMatch: classifyModelId(modelId, partial.model),
|
|
243
367
|
};
|
|
@@ -249,6 +373,8 @@ export function makeLiveModelStep({
|
|
|
249
373
|
ok: false,
|
|
250
374
|
red: `provider-red: ${err.message}`,
|
|
251
375
|
costUsd: cumulative.costUsd,
|
|
376
|
+
tokens: cumulative.tokens,
|
|
377
|
+
...toolFields(cumulative),
|
|
252
378
|
model: modelId,
|
|
253
379
|
modelMatch: classifyModelId(modelId, partial.model),
|
|
254
380
|
};
|
|
@@ -256,7 +382,8 @@ export function makeLiveModelStep({
|
|
|
256
382
|
|
|
257
383
|
const wallMs = Date.now() - startedAt;
|
|
258
384
|
const metered = sumMeterings(roundMeterings);
|
|
259
|
-
cumulative =
|
|
385
|
+
cumulative = addMeter(cumulative, metered);
|
|
386
|
+
cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
|
|
260
387
|
appendSpendRow(spendPath, {
|
|
261
388
|
model: modelId,
|
|
262
389
|
modelReturned: metered.model,
|
|
@@ -276,6 +403,8 @@ export function makeLiveModelStep({
|
|
|
276
403
|
ok: false,
|
|
277
404
|
red: `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
|
|
278
405
|
costUsd: cumulative.costUsd,
|
|
406
|
+
tokens: cumulative.tokens,
|
|
407
|
+
...toolFields(cumulative),
|
|
279
408
|
model: modelId,
|
|
280
409
|
modelMatch,
|
|
281
410
|
};
|
|
@@ -286,10 +415,18 @@ export function makeLiveModelStep({
|
|
|
286
415
|
if (noToolCallStreak >= 2) {
|
|
287
416
|
const malformed = provider?.lastMalformedToolCall ?? null;
|
|
288
417
|
if (malformed) {
|
|
418
|
+
// bare-agent >=0.48 delivers `rawArguments` only when the provider
|
|
419
|
+
// was built with `exposeMalformedArgs: true`; upstream caps it and
|
|
420
|
+
// sets `rawTruncated` when clipped. Absent -> no "; raw:" suffix.
|
|
421
|
+
const rawSuffix = malformed.rawArguments !== undefined
|
|
422
|
+
? `; raw: ${malformed.rawArguments}${malformed.rawTruncated === true ? ' (truncated)' : ''}`
|
|
423
|
+
: '';
|
|
289
424
|
return {
|
|
290
425
|
ok: false,
|
|
291
|
-
red: `the tool call's arguments were not valid JSON twice in a row (${malformed.error})
|
|
426
|
+
red: `the tool call's arguments were not valid JSON twice in a row (${malformed.error})${rawSuffix}`,
|
|
292
427
|
costUsd: cumulative.costUsd,
|
|
428
|
+
tokens: cumulative.tokens,
|
|
429
|
+
...toolFields(cumulative),
|
|
293
430
|
model: modelId,
|
|
294
431
|
modelMatch,
|
|
295
432
|
};
|
|
@@ -298,6 +435,8 @@ export function makeLiveModelStep({
|
|
|
298
435
|
ok: false,
|
|
299
436
|
red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool twice in a row. Text: ${JSON.stringify(result.text)}`,
|
|
300
437
|
costUsd: cumulative.costUsd,
|
|
438
|
+
tokens: cumulative.tokens,
|
|
439
|
+
...toolFields(cumulative),
|
|
301
440
|
model: modelId,
|
|
302
441
|
modelMatch,
|
|
303
442
|
};
|
|
@@ -308,17 +447,17 @@ export function makeLiveModelStep({
|
|
|
308
447
|
|
|
309
448
|
if (cumulative.costUsd === null) {
|
|
310
449
|
return {
|
|
311
|
-
ok: false, red: 'pricing-red: an unpriced round leaves this attempt\'s cost unknown', costUsd: null, model: modelId, modelMatch,
|
|
450
|
+
ok: false, red: 'pricing-red: an unpriced round leaves this attempt\'s cost unknown', costUsd: null, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
|
|
312
451
|
};
|
|
313
452
|
}
|
|
314
453
|
|
|
315
454
|
return {
|
|
316
|
-
ok: true, artifact: capturedArtifact, costUsd: cumulative.costUsd, model: modelId, modelMatch,
|
|
455
|
+
ok: true, artifact: capturedArtifact, costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
|
|
317
456
|
};
|
|
318
457
|
}
|
|
319
458
|
|
|
320
459
|
return {
|
|
321
|
-
ok: false, red: 'exhausted rounds without a clean result', costUsd: cumulative.costUsd, model: modelId,
|
|
460
|
+
ok: false, red: 'exhausted rounds without a clean result', costUsd: cumulative.costUsd, model: modelId, tokens: cumulative.tokens, ...toolFields(cumulative),
|
|
322
461
|
};
|
|
323
462
|
};
|
|
324
463
|
}
|