neurastream 0.2.14 → 0.2.15
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/README.md +28 -0
- package/package.json +1 -1
- package/src/adapters/omp/traces.ts +41 -2
- package/src/cli/metrics.ts +21 -2
- package/src/core/adapter.ts +4 -0
- package/src/core/config.ts +31 -1
- package/src/core/report.ts +20 -1
- package/src/core/trace-provider.ts +213 -0
- package/templates/config.yml +10 -0
package/README.md
CHANGED
|
@@ -202,6 +202,32 @@ neurastream traces claims --since 24h --json # machine-readable
|
|
|
202
202
|
|
|
203
203
|
Known boundary: a report that cites other runs' work (Main quoting a subagent, a relaunched agent quoting its predecessor) can produce `claim-unbacked` findings that are true in this run's trace but provable only in the cited run's own trace.
|
|
204
204
|
|
|
205
|
+
## Provider honesty
|
|
206
|
+
|
|
207
|
+
Five rules check what came back against what was asked for, over one run's trace, read-only (`src/core/trace-provider.ts`):
|
|
208
|
+
|
|
209
|
+
- `model-swap`: the run announced a model (`model_change`) but an assistant message shows another model or another provider, or the run resolved the request to a fallback (`resolvedModelIsFallback`).
|
|
210
|
+
- `odd-response-id`: an assistant message's `responseId` misses the regex configured for its provider (`traces.provider.id_patterns`; a provider without an entry is not checked, and a message without a responseId is not checked).
|
|
211
|
+
- `unoffered-tool`: a toolCall for a tool the session never showed as offered — not in `traces.provider.allow_tools`, not in the request's own tool list (an http dump), and no result anywhere in the run other than an unknown-tool refusal (`Tool <name> not found`, `No such tool`, `Unknown tool`). An error result such as a guard refusal still proves the tool exists.
|
|
212
|
+
- `phantom-output`: output tokens billed for an assistant message that wrote nothing. A message whose stream was aborted (owner interrupt) or errored is not judged: the harness drops its partial content but keeps the usage of what streamed.
|
|
213
|
+
- `cost-mismatch`: the run's `model_usage` cost misses the `traces.provider.prices` table ($ per million tokens) by more than ±20%, in either direction; a model without a price row is not checked.
|
|
214
|
+
|
|
215
|
+
`neurastream metrics report` ends with a weekly line — `Provider honesty over N runs: …` — counting the findings of every run touched in the window. Both config maps are open: an empty object in the template means "add your own keys" in your config. The id patterns below were sampled from real traces; paste them (or yours) into `~/.config/neurastream/config.yml`:
|
|
216
|
+
|
|
217
|
+
```yaml
|
|
218
|
+
traces:
|
|
219
|
+
provider:
|
|
220
|
+
id_patterns:
|
|
221
|
+
anthropic: '^msg_[A-Za-z0-9]+$'
|
|
222
|
+
zai: '^[0-9]{14}[0-9a-f]+$'
|
|
223
|
+
openai-codex: '^resp_[0-9a-f]+$'
|
|
224
|
+
openrouter: '^gen-[0-9]+-[A-Za-z0-9]+$'
|
|
225
|
+
prices: {} # e.g. glm-test: { input: 2, output: 6, cache_read: 0.2, cache_write: 0.5 }
|
|
226
|
+
allow_tools: []
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Finding evidence is masked (long token-like runs never survive verbatim) and capped at 160 characters, so a response id or a tool call line cannot carry a secret into the findings.
|
|
230
|
+
|
|
205
231
|
## Self-metrics
|
|
206
232
|
|
|
207
233
|
`neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
|
|
@@ -214,6 +240,8 @@ Known boundary: a report that cites other runs' work (Main quoting a subagent, a
|
|
|
214
240
|
|
|
215
241
|
Caveat: M4 is a whole-run measure. A main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.
|
|
216
242
|
|
|
243
|
+
The report ends with a `Provider honesty over N runs: …` line — provider-honesty findings (see Provider honesty above) over every run touched in the window.
|
|
244
|
+
|
|
217
245
|
Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
|
|
218
246
|
|
|
219
247
|
## Self-improvement
|
package/package.json
CHANGED
|
@@ -62,7 +62,14 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
62
62
|
if (!d) continue;
|
|
63
63
|
const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
|
|
64
64
|
if (d.type === "model_change") {
|
|
65
|
-
out.push({
|
|
65
|
+
out.push({
|
|
66
|
+
kind: "modelChange",
|
|
67
|
+
ts,
|
|
68
|
+
runId,
|
|
69
|
+
model: str(d.model),
|
|
70
|
+
provider: str(d.provider),
|
|
71
|
+
fallback: d.resolvedModelIsFallback === true ? true : undefined,
|
|
72
|
+
});
|
|
66
73
|
continue;
|
|
67
74
|
}
|
|
68
75
|
if (d.type === "model_usage") {
|
|
@@ -83,7 +90,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
83
90
|
if (!p) continue;
|
|
84
91
|
if (p.type === "text") {
|
|
85
92
|
const t = String(p.text ?? "");
|
|
86
|
-
if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage });
|
|
93
|
+
if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage, responseId: str(m.responseId) });
|
|
87
94
|
} else if (p.type === "toolCall") {
|
|
88
95
|
out.push({
|
|
89
96
|
kind: "toolCall",
|
|
@@ -94,9 +101,17 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
94
101
|
model,
|
|
95
102
|
provider,
|
|
96
103
|
usage,
|
|
104
|
+
responseId: str(m.responseId),
|
|
97
105
|
});
|
|
98
106
|
}
|
|
99
107
|
}
|
|
108
|
+
// An assistant message with no content at all would vanish (nothing to map); an empty
|
|
109
|
+
// text marks it so the phantom-output rule can see billed tokens with no words. An
|
|
110
|
+
// aborted or errored stream (owner interrupt, provider error) drops its partial content
|
|
111
|
+
// while keeping the usage of what streamed, so it is not marked.
|
|
112
|
+
if (content.length === 0 && m.stopReason !== "aborted" && m.stopReason !== "error") {
|
|
113
|
+
out.push({ kind: "assistantText", ts, runId, text: "", model, provider, usage, responseId: str(m.responseId) });
|
|
114
|
+
}
|
|
100
115
|
} else if (role === "toolResult") {
|
|
101
116
|
out.push({
|
|
102
117
|
kind: "toolResult",
|
|
@@ -130,6 +145,30 @@ export function ompTraceRuns(root: string): { runId: string; file: string; mtime
|
|
|
130
145
|
return Object.entries(newest).map(([runId, v]) => ({ runId, file: v.file, mtimeSec: v.mtimeSec }));
|
|
131
146
|
}
|
|
132
147
|
|
|
148
|
+
/**
|
|
149
|
+
* Tool names one dumped request offered: body.tools[].name of an http-4xx dump. A dump the
|
|
150
|
+
* reader cannot open or parse offers nothing — a broken dump must not widen the offered set.
|
|
151
|
+
*/
|
|
152
|
+
export function offeredFromDump(file: string): string[] {
|
|
153
|
+
let text: string;
|
|
154
|
+
try {
|
|
155
|
+
text = readFileSync(file, "utf8");
|
|
156
|
+
} catch {
|
|
157
|
+
return [];
|
|
158
|
+
}
|
|
159
|
+
let parsed: unknown;
|
|
160
|
+
try {
|
|
161
|
+
parsed = JSON.parse(text);
|
|
162
|
+
} catch {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
const o = asObj(parsed);
|
|
166
|
+
const body = asObj(o?.body) ?? o;
|
|
167
|
+
const tools = body?.tools;
|
|
168
|
+
if (!Array.isArray(tools)) return [];
|
|
169
|
+
return tools.map((t) => str(asObj(t)?.name)).filter((n): n is string => n !== undefined);
|
|
170
|
+
}
|
|
171
|
+
|
|
133
172
|
/** TraceSource over a sessions root: dated main files at depth 1, subagent files at depth 2. */
|
|
134
173
|
export function ompTraceSource(root: string): TraceSource {
|
|
135
174
|
return {
|
package/src/cli/metrics.ts
CHANGED
|
@@ -8,8 +8,10 @@ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
|
8
8
|
import { appendMetric } from "../core/metrics.ts";
|
|
9
9
|
import { nowSec } from "../core/clock.ts";
|
|
10
10
|
import type { RunSource } from "../core/adapter.ts";
|
|
11
|
-
import { buildReport } from "../core/report.ts";
|
|
11
|
+
import { buildReport, type ProviderSummary } from "../core/report.ts";
|
|
12
|
+
import { providerFindings } from "../core/trace-provider.ts";
|
|
12
13
|
import { defaultRunSource } from "../adapters/omp/sessions.ts";
|
|
14
|
+
import { ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
|
|
13
15
|
|
|
14
16
|
export const METRICS_USAGE = [
|
|
15
17
|
"usage: neurastream metrics ci <repo-dir> <mr-id>",
|
|
@@ -89,6 +91,23 @@ export function recordRule(cfg: Config, text: string, decision: "approved" | "re
|
|
|
89
91
|
return 0;
|
|
90
92
|
}
|
|
91
93
|
|
|
94
|
+
/** Provider-honesty counts over every run touched inside the window, folded from the five
|
|
95
|
+
* rules of src/core/trace-provider.ts under the config's provider rules and price table. */
|
|
96
|
+
function providerSummary(cfg: Config, now: number, days: number): ProviderSummary {
|
|
97
|
+
const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
|
|
98
|
+
const cutoff = now - days * 86400;
|
|
99
|
+
const src = ompTraceSource(root);
|
|
100
|
+
const rules = cfg.traces.provider;
|
|
101
|
+
const byKind: Record<string, number> = {};
|
|
102
|
+
let runs = 0;
|
|
103
|
+
for (const r of ompTraceRuns(root)) {
|
|
104
|
+
if (r.mtimeSec < cutoff) continue;
|
|
105
|
+
runs++;
|
|
106
|
+
for (const f of providerFindings(src.events(r.runId), rules, rules.prices)) byKind[f.kind] = (byKind[f.kind] ?? 0) + 1;
|
|
107
|
+
}
|
|
108
|
+
return { runs, byKind };
|
|
109
|
+
}
|
|
110
|
+
|
|
92
111
|
/** Writes notes/metrics.md and prints the same report: this window against the previous one. */
|
|
93
112
|
export function reportCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
|
|
94
113
|
const raw = flagValue(args, "--days");
|
|
@@ -97,7 +116,7 @@ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: n
|
|
|
97
116
|
console.error(METRICS_USAGE);
|
|
98
117
|
return 2;
|
|
99
118
|
}
|
|
100
|
-
const { md, text } = buildReport(cfg, source, days, now);
|
|
119
|
+
const { md, text } = buildReport(cfg, source, days, now, providerSummary(cfg, now, days));
|
|
101
120
|
mkdirSync(cfg.paths.notes, { recursive: true });
|
|
102
121
|
writeFileSync(join(cfg.paths.notes, "metrics.md"), md);
|
|
103
122
|
console.log(text);
|
package/src/core/adapter.ts
CHANGED
|
@@ -68,6 +68,10 @@ export interface TraceEvent {
|
|
|
68
68
|
model?: string;
|
|
69
69
|
provider?: string;
|
|
70
70
|
usage?: TraceUsage;
|
|
71
|
+
/** Provider response id of the assistant message; absent when the line carries none. */
|
|
72
|
+
responseId?: string;
|
|
73
|
+
/** modelChange only: the run resolved the requested model to a fallback. */
|
|
74
|
+
fallback?: boolean;
|
|
71
75
|
}
|
|
72
76
|
|
|
73
77
|
export interface TraceSource {
|
package/src/core/config.ts
CHANGED
|
@@ -168,8 +168,17 @@ export interface Config {
|
|
|
168
168
|
priority: { sleep_sec: number };
|
|
169
169
|
alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
|
|
170
170
|
snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
|
|
171
|
-
/** Trace
|
|
171
|
+
/** Trace rules: provider honesty (src/core/trace-provider.ts) and what a scanned run may read, dial and write (src/core/trace-actions.ts). */
|
|
172
172
|
traces: {
|
|
173
|
+
/** What an honest provider answer looks like. */
|
|
174
|
+
provider: {
|
|
175
|
+
/** Provider -> regex every assistant responseId must match; a provider without an entry is not checked. */
|
|
176
|
+
id_patterns: Record<string, string>;
|
|
177
|
+
/** Tools a run may call even when no result in the run proves the tool was offered. */
|
|
178
|
+
allow_tools: string[];
|
|
179
|
+
/** Model -> $ per million tokens; a model without an entry is not priced, so its cost is not checked. Both maps are open: an empty object in the template means the user may add keys. */
|
|
180
|
+
prices: Record<string, { input: number; output: number; cache_read: number; cache_write: number }>;
|
|
181
|
+
};
|
|
173
182
|
allowed_hosts: string[];
|
|
174
183
|
/** Product names (docs/config.md) whose files another product's run may not read quietly. */
|
|
175
184
|
owned_repos: string[];
|
|
@@ -247,6 +256,12 @@ function merge(base: unknown, over: unknown, path: string): unknown {
|
|
|
247
256
|
out[key] = adapterOverlay(over[key], next);
|
|
248
257
|
continue;
|
|
249
258
|
}
|
|
259
|
+
// An empty object in the template is an open map: the user may add any keys
|
|
260
|
+
// (traces.provider.id_patterns, traces.provider.prices).
|
|
261
|
+
if (Object.keys(base).length === 0) {
|
|
262
|
+
out[key] = over[key];
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
250
265
|
throw new ConfigError(`unknown key ${next}`);
|
|
251
266
|
}
|
|
252
267
|
out[key] = merge(base[key], over[key], next);
|
|
@@ -334,6 +349,21 @@ function check(cfg: Config): void {
|
|
|
334
349
|
throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
|
|
335
350
|
}
|
|
336
351
|
}
|
|
352
|
+
for (const [provider, pattern] of Object.entries(cfg.traces.provider.id_patterns)) {
|
|
353
|
+
if (typeof pattern !== "string") throw new ConfigError(`traces.provider.id_patterns.${provider} must be a string`);
|
|
354
|
+
try {
|
|
355
|
+
new RegExp(pattern);
|
|
356
|
+
} catch {
|
|
357
|
+
throw new ConfigError(`traces.provider.id_patterns.${provider}: not a valid regex: ${pattern}`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
for (const [model, row] of Object.entries(cfg.traces.provider.prices)) {
|
|
361
|
+
for (const key of ["input", "output", "cache_read", "cache_write"] as const) {
|
|
362
|
+
if (typeof row[key] !== "number" || !Number.isFinite(row[key])) {
|
|
363
|
+
throw new ConfigError(`traces.provider.prices.${model}.${key} must be a number`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
337
367
|
for (const rule of cfg.brief.repo_rules) {
|
|
338
368
|
for (const key of ["match", "require", "first", "unless"] as const) {
|
|
339
369
|
const pattern = rule[key];
|
package/src/core/report.ts
CHANGED
|
@@ -172,7 +172,16 @@ export interface Report {
|
|
|
172
172
|
worst: { key: string; name: string; cur: number | null; prev: number | null; change: number | null } | null;
|
|
173
173
|
}
|
|
174
174
|
|
|
175
|
-
|
|
175
|
+
/** Weekly provider-honesty counts the report appends; the CLI caller builds them from the
|
|
176
|
+
* sessions root (core has no adapter), folding src/core/trace-provider.ts findings by kind. */
|
|
177
|
+
export interface ProviderSummary {
|
|
178
|
+
/** Runs scanned inside the window. */
|
|
179
|
+
runs: number;
|
|
180
|
+
/** Findings by rule kind over those runs. */
|
|
181
|
+
byKind: Record<string, number>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function buildReport(cfg: Config, source: RunSource, days: number, now: number, provider?: ProviderSummary): Report {
|
|
176
185
|
const inp = loadInputs(cfg, source, now, days);
|
|
177
186
|
const events = [...inp.events, ...readMetricEvents(cfg)];
|
|
178
187
|
const blocks = readBlocks(cfg);
|
|
@@ -208,6 +217,16 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
208
217
|
"",
|
|
209
218
|
"Approved rules, before vs after:",
|
|
210
219
|
...ruleLines(cfg, source, events, blocks, incidents, days, now),
|
|
220
|
+
...(provider
|
|
221
|
+
? [
|
|
222
|
+
"",
|
|
223
|
+
`Provider honesty over ${provider.runs} runs: ` +
|
|
224
|
+
(Object.entries(provider.byKind)
|
|
225
|
+
.filter(([, n]) => n > 0)
|
|
226
|
+
.map(([k, n]) => `${n} ${k}`)
|
|
227
|
+
.join(", ") || "no findings"),
|
|
228
|
+
]
|
|
229
|
+
: []),
|
|
211
230
|
].join("\n");
|
|
212
231
|
|
|
213
232
|
const md = [
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Provider-honesty rules (plan 20261024_0302): what came back must be what was asked for.
|
|
2
|
+
// Three checks over one run's TraceEvents, each a pure function so tests feed fixtures and the
|
|
3
|
+
// later detector/CLI wiring gathers real runs:
|
|
4
|
+
// model-swap the run announced a model (model_change) but an assistant message shows
|
|
5
|
+
// another model or another provider, or the run resolved to a fallback;
|
|
6
|
+
// odd-response-id an assistant message's responseId misses the shape configured for its
|
|
7
|
+
// provider (traces.provider.id_patterns);
|
|
8
|
+
// unoffered-tool a toolCall for a tool the session was never shown as offered (P2).
|
|
9
|
+
// Finding text passes through the shared mask: evidence holds at most 160 chars and long
|
|
10
|
+
// token-like runs (a responseId can look exactly like a credential) never survive verbatim.
|
|
11
|
+
|
|
12
|
+
import type { TraceEvent } from "./adapter.ts";
|
|
13
|
+
import type { Finding } from "./incident-detectors.ts";
|
|
14
|
+
import { maskEvidence } from "./trace-claims.ts";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Folds one finding into the list unless its fingerprint is already there, so repeats of the
|
|
18
|
+
* same dishonesty in one run stay one finding (first sighting wins the evidence). Every rule
|
|
19
|
+
* uses this, so masking and the evidence cap cannot be forgotten at a call site.
|
|
20
|
+
*/
|
|
21
|
+
function fold(out: Finding[], seen: Set<string>, kind: string, summary: string, evidence: string, fingerprint: string): void {
|
|
22
|
+
if (seen.has(fingerprint)) return;
|
|
23
|
+
seen.add(fingerprint);
|
|
24
|
+
out.push({ kind, summary, evidence: maskEvidence(evidence), fingerprint });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Assistant-message events: the only lines that speak with a provider's voice. */
|
|
28
|
+
function isServed(e: TraceEvent): boolean {
|
|
29
|
+
return e.kind === "toolCall" || e.kind === "assistantText";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The run's announcements vs what the assistant messages show. The announced model is
|
|
34
|
+
* provider-prefixed ("<provider>/<model>") while a message's fields are bare, so the prefix is
|
|
35
|
+
* the promised provider and the rest the promised model; a model without a prefix promises no
|
|
36
|
+
* provider and only the model is judged. A run that never announced a model is not judged:
|
|
37
|
+
* without a claim there is nothing to be honest against. A `resolvedModelIsFallback`
|
|
38
|
+
* announcement is itself a swap — the run was asked for one model and served another.
|
|
39
|
+
*/
|
|
40
|
+
export function modelSwaps(events: TraceEvent[]): Finding[] {
|
|
41
|
+
const out: Finding[] = [];
|
|
42
|
+
const seen = new Set<string>();
|
|
43
|
+
let announced: TraceEvent | undefined;
|
|
44
|
+
for (const e of events) {
|
|
45
|
+
if (e.kind === "modelChange") {
|
|
46
|
+
announced = e;
|
|
47
|
+
if (e.fallback) {
|
|
48
|
+
fold(out, seen, "model-swap", `run ${e.runId}: the requested model was resolved to a fallback`,
|
|
49
|
+
`run ${e.runId}: model_change for ${e.model ?? "?"} says resolvedModelIsFallback`,
|
|
50
|
+
`model-swap:${e.runId}:fallback`);
|
|
51
|
+
}
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (!isServed(e) || !announced?.model) continue;
|
|
55
|
+
const slash = announced.model.indexOf("/");
|
|
56
|
+
const askedModel = slash === -1 ? announced.model : announced.model.slice(slash + 1);
|
|
57
|
+
const askedProvider = slash === -1 ? undefined : announced.model.slice(0, slash);
|
|
58
|
+
if (e.model && e.model !== askedModel) {
|
|
59
|
+
fold(out, seen, "model-swap", `run ${e.runId}: asked for ${askedModel}, an assistant message says ${e.model}`,
|
|
60
|
+
`run ${e.runId}: model_change says ${announced.model}, message says model ${e.model} (provider ${e.provider ?? "?"})`,
|
|
61
|
+
`model-swap:${e.runId}:model:${askedModel}:${e.model}`);
|
|
62
|
+
}
|
|
63
|
+
if (askedProvider && e.provider && e.provider !== askedProvider) {
|
|
64
|
+
fold(out, seen, "model-swap", `run ${e.runId}: asked provider ${askedProvider}, an assistant message says ${e.provider}`,
|
|
65
|
+
`run ${e.runId}: model_change says ${announced.model}, message says provider ${e.provider} (model ${e.model ?? "?"})`,
|
|
66
|
+
`model-swap:${e.runId}:provider:${askedProvider}:${e.provider}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Response-id shapes per provider (traces.provider.id_patterns): an id that misses the
|
|
74
|
+
* configured shape is odd. An absent id is not checked — missing is not malformed, and the
|
|
75
|
+
* 7-day smoke showed absent ids on every run of some providers. A provider without an entry is
|
|
76
|
+
* not checked, and an unparseable pattern disables that one provider rather than guessing what
|
|
77
|
+
* its ids should look like. Repeats fold to one finding per run and provider.
|
|
78
|
+
*/
|
|
79
|
+
export function oddResponseIds(events: TraceEvent[], idPatterns: Record<string, string>): Finding[] {
|
|
80
|
+
const out: Finding[] = [];
|
|
81
|
+
const seen = new Set<string>();
|
|
82
|
+
const shapes = new Map<string, RegExp | null>();
|
|
83
|
+
for (const e of events) {
|
|
84
|
+
if (!isServed(e) || !e.provider) continue;
|
|
85
|
+
const pattern = idPatterns[e.provider];
|
|
86
|
+
if (pattern === undefined) continue;
|
|
87
|
+
if (!shapes.has(e.provider)) {
|
|
88
|
+
let rx: RegExp | null;
|
|
89
|
+
try {
|
|
90
|
+
rx = new RegExp(pattern);
|
|
91
|
+
} catch {
|
|
92
|
+
rx = null;
|
|
93
|
+
}
|
|
94
|
+
shapes.set(e.provider, rx);
|
|
95
|
+
}
|
|
96
|
+
const rx = shapes.get(e.provider);
|
|
97
|
+
if (!rx) continue;
|
|
98
|
+
if (e.responseId === undefined || rx.test(e.responseId)) continue;
|
|
99
|
+
fold(out, seen, "odd-response-id", `run ${e.runId}: ${e.provider} answered with a responseId that misses its configured shape`,
|
|
100
|
+
`${e.provider} responseId "${e.responseId}" must match ${pattern}`,
|
|
101
|
+
`odd-response-id:${e.runId}:${e.provider}`);
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A tool result that says the harness does not know the tool at all (the refusal of a made-up call). */
|
|
107
|
+
const UNKNOWN_TOOL = /^(tool \S+ not found|no such tool|unknown tool)\b/i;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Tool calls for tools the session was never shown as offered. The offered set is the config
|
|
111
|
+
* allow-list plus the names parsed from the request's own tool list (an http dump, passed in by
|
|
112
|
+
* the caller) plus every tool the run itself got a result for — except a result refusing the
|
|
113
|
+
* call as an unknown tool. The plan wording says "earlier successful tool names"; the check
|
|
114
|
+
* accepts any non-refusal result anywhere in the run on purpose: judging only what came earlier
|
|
115
|
+
* would flag the honest first use of every tool, and an error (a guard refusal, bad arguments)
|
|
116
|
+
* still means the harness ran the tool — the 7-day smoke had 14 such real tools flagged.
|
|
117
|
+
*/
|
|
118
|
+
export function unofferedTools(events: TraceEvent[], allowTools: string[], offered: string[] = []): Finding[] {
|
|
119
|
+
const proven = new Set<string>([...allowTools, ...offered]);
|
|
120
|
+
for (const e of events) {
|
|
121
|
+
if (e.kind !== "toolResult" || !e.tool) continue;
|
|
122
|
+
if (e.isError === true && UNKNOWN_TOOL.test(e.text ?? "")) continue;
|
|
123
|
+
proven.add(e.tool);
|
|
124
|
+
}
|
|
125
|
+
const out: Finding[] = [];
|
|
126
|
+
const seen = new Set<string>();
|
|
127
|
+
for (const e of events) {
|
|
128
|
+
if (e.kind !== "toolCall" || !e.tool || e.tool === "?") continue;
|
|
129
|
+
if (proven.has(e.tool)) continue;
|
|
130
|
+
fold(out, seen, "unoffered-tool", `run ${e.runId}: toolCall "${e.tool}" was never offered to the session`,
|
|
131
|
+
`toolCall "${e.tool}" has no successful result in the run, is not allow-listed and is not in the request's tool list`,
|
|
132
|
+
`unoffered-tool:${e.runId}:${e.tool}`);
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Output tokens billed for an assistant message that wrote nothing: the parser marks a
|
|
139
|
+
* content-less message as assistantText with empty text, and billed output with no content is
|
|
140
|
+
* phantom. A message without usage cannot be judged and a real reply never is. Each phantom
|
|
141
|
+
* message is its own finding, keyed by response id (or position when the line carries neither).
|
|
142
|
+
*/
|
|
143
|
+
export function phantomOutput(events: TraceEvent[]): Finding[] {
|
|
144
|
+
const out: Finding[] = [];
|
|
145
|
+
const seen = new Set<string>();
|
|
146
|
+
for (let i = 0; i < events.length; i++) {
|
|
147
|
+
const e = events[i]!;
|
|
148
|
+
if (e.kind !== "assistantText" || e.text !== "" || !e.usage) continue;
|
|
149
|
+
if (!(e.usage.output > 0)) continue;
|
|
150
|
+
const id = e.responseId ?? (e.ts === null ? String(i) : String(e.ts));
|
|
151
|
+
fold(out, seen, "phantom-output", `run ${e.runId}: an assistant message billed ${e.usage.output} output tokens but wrote nothing`,
|
|
152
|
+
`assistant message billed ${e.usage.output} output tokens with empty content (responseId ${e.responseId ?? "<absent>"})`,
|
|
153
|
+
`phantom-output:${e.runId}:${id}`);
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The run's own model_usage accounting vs the configured price table ($ per million tokens).
|
|
160
|
+
* Billed cost beyond ±20% of the table price is a mismatch in either direction — over-billing
|
|
161
|
+
* and under-billing both lie about what the run cost. A zero-priced model that still bills is
|
|
162
|
+
* a mismatch too (no percentage exists against zero). A model without an entry is not priced:
|
|
163
|
+
* a wrong guess would be worse than no check. Repeats fold per run and model.
|
|
164
|
+
*/
|
|
165
|
+
export function costMismatch(events: TraceEvent[], prices: Record<string, ProviderPrice>): Finding[] {
|
|
166
|
+
const out: Finding[] = [];
|
|
167
|
+
const seen = new Set<string>();
|
|
168
|
+
for (const e of events) {
|
|
169
|
+
if (e.kind !== "usage" || !e.model || !e.usage) continue;
|
|
170
|
+
const u = e.usage;
|
|
171
|
+
if (!(u.totalTokens > 0)) continue;
|
|
172
|
+
const bare = e.model.includes("/") ? e.model.slice(e.model.indexOf("/") + 1) : e.model;
|
|
173
|
+
const price = prices[e.model] ?? prices[bare];
|
|
174
|
+
if (!price) continue;
|
|
175
|
+
const expected = (u.input * price.input + u.output * price.output + u.cacheRead * price.cache_read + u.cacheWrite * price.cache_write) / 1_000_000;
|
|
176
|
+
const billed = u.cost;
|
|
177
|
+
const off = expected > 0 ? Math.abs(billed - expected) / expected : Math.abs(billed);
|
|
178
|
+
if (!(off > 0.2)) continue;
|
|
179
|
+
const pct = expected > 0 ? ` (${Math.round((billed / expected - 1) * 100)}%)` : "";
|
|
180
|
+
fold(out, seen, "cost-mismatch", `run ${e.runId}: ${e.model} billed $${billed} but the price table says $${Number(expected.toFixed(6))}${pct}`,
|
|
181
|
+
`model_usage ${e.model}: billed $${billed}, tokens in ${u.input} out ${u.output} cacheRead ${u.cacheRead} cacheWrite ${u.cacheWrite}, table says $${Number(expected.toFixed(6))}${pct}`,
|
|
182
|
+
`cost-mismatch:${e.runId}:${e.model}`);
|
|
183
|
+
}
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** What the provider-honesty rules need from config (cfg.traces.provider). */
|
|
188
|
+
export interface ProviderRules {
|
|
189
|
+
id_patterns: Record<string, string>;
|
|
190
|
+
allow_tools: string[];
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** One model's price row: $ per million tokens (traces.provider.prices). */
|
|
194
|
+
export interface ProviderPrice {
|
|
195
|
+
input: number;
|
|
196
|
+
output: number;
|
|
197
|
+
cache_read: number;
|
|
198
|
+
cache_write: number;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Every rule at once over one run's events, in rule order (P1 swaps, P1 ids, P2 tools, P3
|
|
203
|
+
* phantom, P3 cost) — the shape the metrics report summary and the smoke scan both fold.
|
|
204
|
+
*/
|
|
205
|
+
export function providerFindings(events: TraceEvent[], rules: ProviderRules, prices: Record<string, ProviderPrice> = {}, offered: string[] = []): Finding[] {
|
|
206
|
+
return [
|
|
207
|
+
...modelSwaps(events),
|
|
208
|
+
...oddResponseIds(events, rules.id_patterns),
|
|
209
|
+
...unofferedTools(events, rules.allow_tools, offered),
|
|
210
|
+
...phantomOutput(events),
|
|
211
|
+
...costMismatch(events, prices),
|
|
212
|
+
];
|
|
213
|
+
}
|
package/templates/config.yml
CHANGED
|
@@ -198,6 +198,16 @@ snapshot:
|
|
|
198
198
|
- "*.sock"
|
|
199
199
|
|
|
200
200
|
traces:
|
|
201
|
+
provider:
|
|
202
|
+
# Provider-honesty rules (src/core/trace-provider.ts). The maps below are open: an empty
|
|
203
|
+
# object here means "add your own keys" in your config. id_patterns maps a provider to the
|
|
204
|
+
# regex every assistant responseId must match (a provider without an entry is not checked);
|
|
205
|
+
# sampled defaults live in README.md. prices maps a model to $ per million tokens; a model
|
|
206
|
+
# without an entry is not priced. allow_tools: tools a run may call even when no result in
|
|
207
|
+
# the run proves the tool was offered.
|
|
208
|
+
id_patterns: {}
|
|
209
|
+
prices: {}
|
|
210
|
+
allow_tools: []
|
|
201
211
|
allowed_hosts: # hosts a network command may touch without a finding
|
|
202
212
|
- localhost
|
|
203
213
|
- 127.0.0.1
|