neurastream 0.2.17 → 0.2.19
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 +32 -2
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +54 -32
- package/src/adapters/omp/sessions.ts +3 -0
- package/src/adapters/omp/traces.ts +170 -3
- package/src/cli/metrics.ts +32 -3
- package/src/cli/traces.ts +199 -9
- package/src/core/adapter.ts +5 -0
- package/src/core/agent-ledger.ts +3 -0
- package/src/core/config.ts +87 -1
- package/src/core/quota-reset.ts +1 -76
- package/src/core/report.ts +20 -1
- package/src/core/reset-time.ts +117 -0
- package/src/core/trace-bloat.ts +199 -0
- package/src/core/trace-briefs.ts +192 -0
- package/src/core/trace-provider.ts +8 -8
- package/templates/config.yml +20 -0
package/README.md
CHANGED
|
@@ -80,6 +80,8 @@ Green is both exiting 0.
|
|
|
80
80
|
|
|
81
81
|
`neurastream traces efficiency --since 7d` reports wasted tool calls from recent traces; pass a run id to inspect one run, or add `--json` for machine-readable per-run records (including step indexes and matched rules). Waste rules cover repeated reads and failed commands, failed edits, repeated guard blocks and idle polling. The agent-score board adds `Calls/acc` and `Waste` columns; `score.waste_weight` (default `0`) scales ranking by the wasted-call fraction while leaving the default ranking unchanged.
|
|
82
82
|
|
|
83
|
+
`neurastream traces briefs --since 30d` lists each spawn brief Main sent (shared context first, then the task's own text) with its features — length, a `file:line`, a verify command, a phase id, a plan path, a `Call budget` line, the number of acceptance lines — next to the spawned agent's waste and whether its work was accepted. `--json` gives the rows, `--report` compares the rows with and without each feature (a side with fewer than `traces.briefs.min_n` rows prints "n too small"). Brief text never prints. Read the report with care: a spawn without a plan is never accepted, and accept records exist only since scoring began, so all-time accept rates mostly measure when and for what an agent was spawned, not how good the brief was. Compare plan briefs from the same period before turning a gap into a rule; on 30 days of real briefs that comparison showed no feature strong enough for a brief-lint warning.
|
|
84
|
+
|
|
83
85
|
`agent-score accept` records accepted work by commit; `agent-score validate <Agent> --plan <plan.md> --phase <P> --evidence <report.md> --section "<heading prefix>"` records a validation phase (checks/tests ran, report section written, no commits) with proof Main cannot fake by typing: the plan line must be ticked `- [x]`, the cited section body must name a heavy-run label run by that agent (from `paths.heavy_log`), and the phase must not be scored already. The ranking board counts it in `Accepted (diag/val)` as `N (d/v)`.
|
|
84
86
|
|
|
85
87
|
## Main reads the code for its plans
|
|
@@ -189,10 +191,14 @@ notify: posted (rate-limit)
|
|
|
189
191
|
RATE-LIMIT resume: new turn sent (waited until 08:12)
|
|
190
192
|
```
|
|
191
193
|
|
|
192
|
-
The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: the wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message
|
|
194
|
+
The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: the wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message takes over and cancels the resume (`RATE-LIMIT resume cancelled: owner message`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves the resume armed. A rate-limited deferred hand-back (an `agent_end` while an async job is pending) arms the same timer instead of logging "no reply text". The words and the waits live in `config.yml` (`guards.rate_limit`, `docs/config.md`); turns that did not end on a rate limit are unaffected.
|
|
193
195
|
|
|
194
196
|
omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what neurastream waits out.
|
|
195
197
|
|
|
198
|
+
## Provider reset times
|
|
199
|
+
|
|
200
|
+
Before Main reads a message, reset timestamps matching `quota.reset_pattern` are annotated with their local time, for example `reset at 2026-10-25 18:56:22 (= 2026-10-25 11:56:22 CET local)`. Set `quota.reset_tz` to the provider's time zone; an explicit zone or UTC offset in the message takes precedence.
|
|
201
|
+
|
|
196
202
|
## Trace claims (`neurastream traces claims`)
|
|
197
203
|
|
|
198
204
|
Agents' final reports assert results — "530 passed", "exit 0", commit SHAs, heavy-run labels, changed files. This command reads a run's trace (its session file, read-only) and checks each claim in the run's last assistant message against what the run's own tool activity shows: a count or exit code must appear in some tool output, a commit SHA must be printed by the output of a git command the run itself ran, a heavy-run label must appear in a quoted heavy-run call, and a changed path must be carried by an edit/write call or a shell write in the path's own command segment. A claim nothing shows becomes a `claim-unbacked` finding.
|
|
@@ -231,6 +237,30 @@ traces:
|
|
|
231
237
|
|
|
232
238
|
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.
|
|
233
239
|
|
|
240
|
+
## Prompt bloat (`neurastream traces bloat`)
|
|
241
|
+
|
|
242
|
+
`neurastream traces bloat [--since 24h] [--json]` (or one run by id) lists, per run, every model call's prompt — `usage.input + usage.cacheRead + usage.cacheWrite`, one row per call — and flags `prompt-bloat` when
|
|
243
|
+
|
|
244
|
+
- the run's FIRST call opens over `traces.bloat.first_call_max` (a run that starts huge stays huge), or
|
|
245
|
+
- any call passes `traces.bloat.ratio_of_limit` × its model's `traces.bloat.context_limits` entry (an open map; a model without an entry is not limit-checked).
|
|
246
|
+
|
|
247
|
+
A failed request dump under `~/.omp/logs/http-400-requests` (named `<epoch-ms>-<id>.json`) belongs to one run only: its trace window must cover the dump, its model must match, and among eligible runs the closest event timestamp at or before the dump wins. An exact tie—or no eligible run—leaves the dump unmatched; text and `--json` output list unmatched dumps once. For the owning run, the report shows what filled the prompt: system, messages and tool groups (tools grouped by the first capture of `traces.bloat.tool_group` on the tool name; no match = `builtin`) plus the five largest individual tools.
|
|
248
|
+
|
|
249
|
+
A rejected call never wrote usage, so a run can carry a 1.17M-token prompt with no usage row and no finding of its own. When a run has no usage finding, the matched dump's error response is read: a stated prompt size ("prompt is too long: 1172629 tokens > 1000000 maximum") becomes the flag, with the dump named as the source. A dump whose error response states no count flags nothing, and no size is ever guessed from bytes.
|
|
250
|
+
|
|
251
|
+
`neurastream metrics report` ends with a weekly line — `Prompt bloat over N runs: K flagged, largest first call X tokens (<run>)` — over every run touched in the window (largest first call = the run's usage, else the matched dump's stated prompt). The agent ledger shows a `tok/call` column: prompt tokens ÷ calls per run.
|
|
252
|
+
|
|
253
|
+
Config (defaults):
|
|
254
|
+
|
|
255
|
+
```yaml
|
|
256
|
+
traces:
|
|
257
|
+
bloat:
|
|
258
|
+
first_call_max: 150000
|
|
259
|
+
ratio_of_limit: 0.8
|
|
260
|
+
context_limits: {} # e.g. claude-opus-5-5: 1000000
|
|
261
|
+
tool_group: '^_?mcp__([A-Za-z0-9]+)_'
|
|
262
|
+
```
|
|
263
|
+
|
|
234
264
|
## Self-metrics
|
|
235
265
|
|
|
236
266
|
`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:
|
|
@@ -243,7 +273,7 @@ Finding evidence is masked (long token-like runs never survive verbatim) and cap
|
|
|
243
273
|
|
|
244
274
|
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.
|
|
245
275
|
|
|
246
|
-
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.
|
|
276
|
+
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 — and a `Prompt bloat over N runs: …` line (see Prompt bloat above) over the same runs.
|
|
247
277
|
|
|
248
278
|
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`.
|
|
249
279
|
|
package/package.json
CHANGED
|
@@ -36,6 +36,7 @@ import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.t
|
|
|
36
36
|
import { parseTraceFile } from "./traces.ts";
|
|
37
37
|
import { packageJsonPath, packageVersion } from "./package-root.ts";
|
|
38
38
|
import * as q from "../../core/queue/lib.ts";
|
|
39
|
+
import { annotateResetTimes } from "../../core/reset-time.ts";
|
|
39
40
|
// Registers the plugin-command matcher into core's writeTargets (side effect).
|
|
40
41
|
import "./package-ops.ts";
|
|
41
42
|
|
|
@@ -462,8 +463,9 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
462
463
|
let stopBlocked = false;
|
|
463
464
|
// Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
|
|
464
465
|
// form one episode. The attempt doubles the wait, the owner chat is told once per episode, and
|
|
465
|
-
// ONE timer gives Main a new turn when the wait is over;
|
|
466
|
-
// over and cancels it.
|
|
466
|
+
// ONE timer gives Main a new turn when the wait is over; a new Main turn before expiry takes
|
|
467
|
+
// over and cancels it. Inputs that do not start a turn leave it armed. Any turn that ends
|
|
468
|
+
// without a limit resets the episode and disarms it.
|
|
467
469
|
let rateAttempt = 0;
|
|
468
470
|
let rateTimer: NodeJS.Timeout | null = null;
|
|
469
471
|
const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
|
|
@@ -619,6 +621,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
619
621
|
|
|
620
622
|
pi.on("before_agent_start", (event, ctx) => {
|
|
621
623
|
if (asCtx(ctx).kind !== "main") return;
|
|
624
|
+
if (rateTimer !== null) {
|
|
625
|
+
clearRateTimer();
|
|
626
|
+
adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
|
|
627
|
+
}
|
|
622
628
|
const d = checkInject({ inject: asString(asRecord(event).prompt), agent: "main" }, cfg);
|
|
623
629
|
callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
|
|
624
630
|
idleStops = d.state?.idleStops ?? idleStops;
|
|
@@ -1085,16 +1091,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
1085
1091
|
return null;
|
|
1086
1092
|
};
|
|
1087
1093
|
|
|
1088
|
-
// An owner message while a rate-limit resume is pending takes over: the resume timer is
|
|
1089
|
-
// cancelled (plan 20261025_0640). Registered before the chat-unlock input handler below, so it
|
|
1090
|
-
// sees every owner input even when the unlock short-circuits with { handled: true }.
|
|
1091
|
-
pi.on("input", (_event, ctx) => {
|
|
1092
|
-
if (!isMain(ctx)) return undefined;
|
|
1093
|
-
if (rateTimer === null) return undefined;
|
|
1094
|
-
clearRateTimer();
|
|
1095
|
-
adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
|
|
1096
|
-
return undefined;
|
|
1097
|
-
});
|
|
1098
1094
|
// Chat unlock (guards.chat_unlock): the owner's whole message "unlock"/"unlock N"/"lock" moves
|
|
1099
1095
|
// the guard unlock file (src/core/queue/lib.ts chatUnlock). Only prompts the owner really typed
|
|
1100
1096
|
// count: the local terminal (input event, source "interactive") and collab guest prompts from
|
|
@@ -1128,29 +1124,55 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
1128
1124
|
const seenChatPrompts = new Set<string>();
|
|
1129
1125
|
const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
|
|
1130
1126
|
pi.on("context", (event, ctx) => {
|
|
1131
|
-
if (!
|
|
1127
|
+
if (!isMain(ctx)) return undefined;
|
|
1132
1128
|
const messages = asRecord(event).messages;
|
|
1133
1129
|
if (!Array.isArray(messages)) return undefined;
|
|
1134
|
-
|
|
1135
|
-
const
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1130
|
+
if (cfg.guards.chat_unlock) {
|
|
1131
|
+
for (const raw of messages) {
|
|
1132
|
+
const m = asRecord(raw);
|
|
1133
|
+
if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
|
|
1134
|
+
const from = asString(asRecord(m.details).from);
|
|
1135
|
+
if (from === "") continue;
|
|
1136
|
+
const text =
|
|
1137
|
+
typeof m.content === "string"
|
|
1138
|
+
? m.content
|
|
1139
|
+
: Array.isArray(m.content)
|
|
1140
|
+
? m.content.map(c => asString(asRecord(c).text)).join("")
|
|
1141
|
+
: "";
|
|
1142
|
+
const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
|
|
1143
|
+
if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
|
|
1144
|
+
const key = `${timestamp}:${text}`;
|
|
1145
|
+
if (seenChatPrompts.has(key)) continue;
|
|
1146
|
+
seenChatPrompts.add(key);
|
|
1147
|
+
const r = q.chatUnlock(text, cfg, `collab:${from}`);
|
|
1148
|
+
if (r.applied) notifyUnlock(ctx, r);
|
|
1149
|
+
}
|
|
1152
1150
|
}
|
|
1153
|
-
|
|
1151
|
+
const rule = { pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz };
|
|
1152
|
+
let changed = false;
|
|
1153
|
+
const mapped = messages.map(raw => {
|
|
1154
|
+
const message = asRecord(raw);
|
|
1155
|
+
if (typeof message.content === "string") {
|
|
1156
|
+
const content = annotateResetTimes(message.content, rule);
|
|
1157
|
+
if (content === message.content) return raw;
|
|
1158
|
+
changed = true;
|
|
1159
|
+
return { ...message, content };
|
|
1160
|
+
}
|
|
1161
|
+
if (!Array.isArray(message.content)) return raw;
|
|
1162
|
+
let contentChanged = false;
|
|
1163
|
+
const content = message.content.map(part => {
|
|
1164
|
+
const block = asRecord(part);
|
|
1165
|
+
if (typeof block.text !== "string") return part;
|
|
1166
|
+
const text = annotateResetTimes(block.text, rule);
|
|
1167
|
+
if (text === block.text) return part;
|
|
1168
|
+
contentChanged = true;
|
|
1169
|
+
return { ...block, text };
|
|
1170
|
+
});
|
|
1171
|
+
if (!contentChanged) return raw;
|
|
1172
|
+
changed = true;
|
|
1173
|
+
return { ...message, content };
|
|
1174
|
+
});
|
|
1175
|
+
return changed ? { messages: mapped } : undefined;
|
|
1154
1176
|
});
|
|
1155
1177
|
|
|
1156
1178
|
// Under the launcher the relaunch is the only rollover path: a plain interactive message in the ready
|
|
@@ -94,6 +94,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
|
|
|
94
94
|
let first: number | null = null;
|
|
95
95
|
let last: number | null = null;
|
|
96
96
|
let inputTokens = 0;
|
|
97
|
+
let prefillTokens = 0;
|
|
97
98
|
const messages: RunMessage[] = [];
|
|
98
99
|
|
|
99
100
|
for (const line of text.split("\n")) {
|
|
@@ -153,6 +154,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
|
|
|
153
154
|
const cr = typeof u.cacheRead === "number" ? u.cacheRead : 0;
|
|
154
155
|
const cw = typeof u.cacheWrite === "number" ? u.cacheWrite : 0;
|
|
155
156
|
inputTokens = input + cr + cw;
|
|
157
|
+
prefillTokens += inputTokens;
|
|
156
158
|
}
|
|
157
159
|
if (typeof m.errorMessage === "string") {
|
|
158
160
|
const head = m.errorMessage.split("\n")[0] ?? "";
|
|
@@ -197,6 +199,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
|
|
|
197
199
|
cacheRead: cache,
|
|
198
200
|
cost,
|
|
199
201
|
inputTokens,
|
|
202
|
+
prefillTokens,
|
|
200
203
|
status,
|
|
201
204
|
statusDetail: state,
|
|
202
205
|
startedAt: first,
|
|
@@ -5,10 +5,12 @@
|
|
|
5
5
|
// trace-relevant data is mapped; anything else (session banners, custom lines, compaction
|
|
6
6
|
// notes, unparseable lines) is skipped.
|
|
7
7
|
|
|
8
|
-
import { readFileSync, statSync } from "node:fs";
|
|
8
|
+
import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
|
|
9
9
|
import { dirname, join } from "node:path";
|
|
10
10
|
import type { Config } from "../../core/config.ts";
|
|
11
11
|
import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
|
|
12
|
+
import type { DumpParts, DumpTokens } from "../../core/trace-bloat.ts";
|
|
13
|
+
import type { SpawnBrief } from "../../core/trace-briefs.ts";
|
|
12
14
|
import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
|
|
13
15
|
|
|
14
16
|
function str(v: unknown): string | undefined {
|
|
@@ -83,6 +85,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
83
85
|
const role = str(m.role);
|
|
84
86
|
const model = str(m.model);
|
|
85
87
|
const provider = str(m.provider);
|
|
88
|
+
const api = str(m.api);
|
|
86
89
|
const usage = usageOf(m.usage);
|
|
87
90
|
if (role === "assistant") {
|
|
88
91
|
const content = Array.isArray(m.content) ? m.content : [];
|
|
@@ -91,7 +94,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
91
94
|
if (!p) continue;
|
|
92
95
|
if (p.type === "text") {
|
|
93
96
|
const t = String(p.text ?? "");
|
|
94
|
-
if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage, responseId: str(m.responseId) });
|
|
97
|
+
if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, api, usage, responseId: str(m.responseId) });
|
|
95
98
|
} else if (p.type === "toolCall") {
|
|
96
99
|
out.push({
|
|
97
100
|
kind: "toolCall",
|
|
@@ -102,6 +105,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
102
105
|
callId: str(p.id),
|
|
103
106
|
model,
|
|
104
107
|
provider,
|
|
108
|
+
api,
|
|
105
109
|
usage,
|
|
106
110
|
responseId: str(m.responseId),
|
|
107
111
|
});
|
|
@@ -112,7 +116,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
|
112
116
|
// aborted or errored stream (owner interrupt, provider error) drops its partial content
|
|
113
117
|
// while keeping the usage of what streamed, so it is not marked.
|
|
114
118
|
if (content.length === 0 && m.stopReason !== "aborted" && m.stopReason !== "error") {
|
|
115
|
-
out.push({ kind: "assistantText", ts, runId, text: "", model, provider, usage, responseId: str(m.responseId) });
|
|
119
|
+
out.push({ kind: "assistantText", ts, runId, text: "", model, provider, api, usage, responseId: str(m.responseId) });
|
|
116
120
|
}
|
|
117
121
|
} else if (role === "toolResult") {
|
|
118
122
|
out.push({
|
|
@@ -148,6 +152,29 @@ export function ompTraceRuns(root: string): { runId: string; file: string; mtime
|
|
|
148
152
|
return Object.entries(newest).map(([runId, v]) => ({ runId, file: v.file, mtimeSec: v.mtimeSec }));
|
|
149
153
|
}
|
|
150
154
|
|
|
155
|
+
/** Read only the session banner at the start of a trace; null means it is unreadable. */
|
|
156
|
+
export function ompTraceStart(file: string): number | null {
|
|
157
|
+
let fd: number;
|
|
158
|
+
try {
|
|
159
|
+
fd = openSync(file, "r");
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
const buffer = Buffer.allocUnsafe(4096);
|
|
164
|
+
try {
|
|
165
|
+
const bytes = readSync(fd, buffer, 0, buffer.length, 0);
|
|
166
|
+
for (const line of buffer.toString("utf8", 0, bytes).split("\n")) {
|
|
167
|
+
try {
|
|
168
|
+
const value = JSON.parse(line) as { type?: unknown; timestamp?: unknown };
|
|
169
|
+
if (value.type === "session" && typeof value.timestamp === "string") return parseTs(value.timestamp);
|
|
170
|
+
} catch {}
|
|
171
|
+
}
|
|
172
|
+
return null;
|
|
173
|
+
} finally {
|
|
174
|
+
closeSync(fd);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
151
178
|
/**
|
|
152
179
|
* Tool names one dumped request offered: body.tools[].name of an http-4xx dump. A dump the
|
|
153
180
|
* reader cannot open or parse offers nothing — a broken dump must not widen the offered set.
|
|
@@ -172,6 +199,110 @@ export function offeredFromDump(file: string): string[] {
|
|
|
172
199
|
return tools.map((t) => str(asObj(t)?.name)).filter((n): n is string => n !== undefined);
|
|
173
200
|
}
|
|
174
201
|
|
|
202
|
+
/** The harness log dir holding the whole failed requests (http-4xx dumps), named by epoch ms. */
|
|
203
|
+
export function ompDumpDir(home: string): string {
|
|
204
|
+
return join(home, ".omp", "logs", "http-400-requests");
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Every request dump under the harness log dir, oldest first. Dumps are named
|
|
209
|
+
* `<epoch ms of the failed request>-<request id>.json`; anything else in the dir is not a dump.
|
|
210
|
+
*/
|
|
211
|
+
export function ompDumps(home: string): { file: string; ms: number }[] {
|
|
212
|
+
let names: string[];
|
|
213
|
+
try {
|
|
214
|
+
names = readdirSync(ompDumpDir(home));
|
|
215
|
+
} catch {
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
const out: { file: string; ms: number }[] = [];
|
|
219
|
+
for (const name of names) {
|
|
220
|
+
const m = /^(\d+)-[A-Za-z0-9]+\.json$/.exec(name);
|
|
221
|
+
if (m) out.push({ file: join(ompDumpDir(home), name), ms: Number(m[1]) });
|
|
222
|
+
}
|
|
223
|
+
return out.sort((a, b) => a.ms - b.ms);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Model requested by a failed request dump, if the JSON contains one. */
|
|
227
|
+
export function dumpModel(file: string): string | undefined {
|
|
228
|
+
try {
|
|
229
|
+
const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
|
|
230
|
+
const o = asObj(parsed);
|
|
231
|
+
const body = asObj(o?.body);
|
|
232
|
+
return str(body?.model) ?? str(o?.model);
|
|
233
|
+
} catch {
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* What a dumped request's prompt is made of, in JSON.stringify characters: body.system,
|
|
240
|
+
* body.messages and every body.tools[] entry with its name (a nameless tool keeps its bytes
|
|
241
|
+
* as "?"). A dump the reader cannot open or parse breaks down to zeros — a broken dump must
|
|
242
|
+
* not look like a prompt that was mostly empty.
|
|
243
|
+
*/
|
|
244
|
+
export function dumpParts(file: string): DumpParts {
|
|
245
|
+
let text: string;
|
|
246
|
+
try {
|
|
247
|
+
text = readFileSync(file, "utf8");
|
|
248
|
+
} catch {
|
|
249
|
+
return { system: 0, messages: 0, tools: [] };
|
|
250
|
+
}
|
|
251
|
+
let parsed: unknown;
|
|
252
|
+
try {
|
|
253
|
+
parsed = JSON.parse(text);
|
|
254
|
+
} catch {
|
|
255
|
+
return { system: 0, messages: 0, tools: [] };
|
|
256
|
+
}
|
|
257
|
+
const o = asObj(parsed);
|
|
258
|
+
const body = asObj(o?.body) ?? o ?? {};
|
|
259
|
+
const tools = Array.isArray(body.tools) ? body.tools : [];
|
|
260
|
+
return {
|
|
261
|
+
system: body.system === undefined ? 0 : JSON.stringify(body.system).length,
|
|
262
|
+
messages: body.messages === undefined ? 0 : JSON.stringify(body.messages).length,
|
|
263
|
+
tools: tools.map((t) => ({ name: str(asObj(t)?.name) ?? "?", bytes: JSON.stringify(t).length })),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* What one dumped request's error response states about its own prompt: "<N> tokens > <M>
|
|
269
|
+
* maximum" (the provider's rejection line) — or, when that shape is missing, a bare
|
|
270
|
+
* "<N> tokens" — plus the request's model. A dump whose error response states no count, or a
|
|
271
|
+
* dump the reader cannot open or parse, states nothing: a flag must never be guessed from
|
|
272
|
+
* bytes alone.
|
|
273
|
+
*/
|
|
274
|
+
export function dumpPromptTokens(file: string): DumpTokens | null {
|
|
275
|
+
let text: string;
|
|
276
|
+
try {
|
|
277
|
+
text = readFileSync(file, "utf8");
|
|
278
|
+
} catch {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
let parsed: unknown;
|
|
282
|
+
try {
|
|
283
|
+
parsed = JSON.parse(text);
|
|
284
|
+
} catch {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
const o = asObj(parsed);
|
|
288
|
+
const body = asObj(o?.body) ?? o ?? {};
|
|
289
|
+
const message = str(asObj(o?.errorResponse)?.message);
|
|
290
|
+
if (message === undefined) return null;
|
|
291
|
+
const count = (v: string | undefined) => {
|
|
292
|
+
const n = v === undefined ? NaN : Number(v.replaceAll(",", ""));
|
|
293
|
+
return Number.isFinite(n) ? n : undefined;
|
|
294
|
+
};
|
|
295
|
+
const m = /(\d[\d,]*)\s*tokens?\s*>\s*([\d,]+)\s*maximum/.exec(message);
|
|
296
|
+
const tokens = count(m?.[1]) ?? count(/(\d[\d,]*)\s*tokens?\b(?!\s*>)/.exec(message)?.[1]);
|
|
297
|
+
if (tokens === undefined) return null;
|
|
298
|
+
const out: DumpTokens = { tokens };
|
|
299
|
+
const limit = count(m?.[2]);
|
|
300
|
+
if (limit !== undefined) out.limit = limit;
|
|
301
|
+
const model = str(body.model);
|
|
302
|
+
if (model !== undefined) out.model = model;
|
|
303
|
+
return out;
|
|
304
|
+
}
|
|
305
|
+
|
|
175
306
|
/** TraceSource over a sessions root: dated main files at depth 1, subagent files at depth 2. */
|
|
176
307
|
export function ompTraceSource(root: string): TraceSource {
|
|
177
308
|
return {
|
|
@@ -212,3 +343,39 @@ export function subagentTraces(root: string, mainRunId: string): RelatedTrace[]
|
|
|
212
343
|
return { name, mtimeSec, events: parseTraceFile(file, name) };
|
|
213
344
|
});
|
|
214
345
|
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* The spawn briefs of one Main run (plan 20261024_0305 traces_06): each `task` spawn whose result
|
|
349
|
+
* is a success, one entry per spawned agent. A refused spawn (`main-guard:` error) spawned nothing.
|
|
350
|
+
* The brief is the shared context, then the task's own text, so the task's trailing sections (such as
|
|
351
|
+
* `# Acceptance`) end the brief. guards.briefBudget reads the first `Call budget` line of it.
|
|
352
|
+
*/
|
|
353
|
+
export function spawnBriefs(root: string, mainRunId: string): SpawnBrief[] {
|
|
354
|
+
const main = ompTraceRuns(root).find((r) => r.runId === mainRunId);
|
|
355
|
+
return main ? spawnBriefsIn(main.file, mainRunId) : [];
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** The spawn briefs in one session file; the CLI calls this per file so it never rescans the root. */
|
|
359
|
+
export function spawnBriefsIn(file: string, runId: string): SpawnBrief[] {
|
|
360
|
+
const events = parseTraceFile(file, runId);
|
|
361
|
+
const results = new Map<string, TraceEvent>();
|
|
362
|
+
for (const e of events) if (e.kind === "toolResult" && e.callId) results.set(e.callId, e);
|
|
363
|
+
const out: SpawnBrief[] = [];
|
|
364
|
+
for (const e of events) {
|
|
365
|
+
if (e.kind !== "toolCall" || e.tool !== "task" || !e.callId) continue;
|
|
366
|
+
const res = results.get(e.callId);
|
|
367
|
+
if (!res || res.isError || !(res.text ?? "").startsWith("Spawned")) continue;
|
|
368
|
+
const named = new Set([...(res.text ?? "").matchAll(/`([^`]+)`/g)].map((m) => m[1] ?? ""));
|
|
369
|
+
const args = e.args ?? {};
|
|
370
|
+
const context = str(args.context) ?? "";
|
|
371
|
+
const tasks = Array.isArray(args.tasks) ? args.tasks : [];
|
|
372
|
+
for (const t of tasks) {
|
|
373
|
+
const task = asObj(t);
|
|
374
|
+
const name = str(task?.name);
|
|
375
|
+
if (!task || !name || !named.has(name)) continue;
|
|
376
|
+
const brief = [context, str(task.task) ?? ""].filter((s) => s !== "").join("\n\n");
|
|
377
|
+
out.push({ agent: name, brief, ts: e.ts });
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return out;
|
|
381
|
+
}
|
package/src/cli/metrics.ts
CHANGED
|
@@ -8,10 +8,12 @@ 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, type ProviderSummary } from "../core/report.ts";
|
|
11
|
+
import { buildReport, type BloatSummary, type ProviderSummary } from "../core/report.ts";
|
|
12
12
|
import { providerFindings } from "../core/trace-provider.ts";
|
|
13
|
+
import { bloatRules } from "../core/trace-bloat.ts";
|
|
13
14
|
import { defaultRunSource } from "../adapters/omp/sessions.ts";
|
|
14
|
-
import { ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
|
|
15
|
+
import { ompDumps, ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
|
|
16
|
+
import { assignDumps, bloatReport } from "./traces.ts";
|
|
15
17
|
|
|
16
18
|
export const METRICS_USAGE = [
|
|
17
19
|
"usage: neurastream metrics ci <repo-dir> <mr-id>",
|
|
@@ -108,6 +110,33 @@ function providerSummary(cfg: Config, now: number, days: number): ProviderSummar
|
|
|
108
110
|
return { runs, byKind };
|
|
109
111
|
}
|
|
110
112
|
|
|
113
|
+
/** Prompt-bloat counts over every run touched inside the window, folded from the
|
|
114
|
+
* src/core/trace-bloat.ts findings the same scans build (dump flag included, since a
|
|
115
|
+
* rejected call flags only through its dump). */
|
|
116
|
+
function bloatSummary(cfg: Config, now: number, days: number): BloatSummary {
|
|
117
|
+
const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
|
|
118
|
+
const cutoff = now - days * 86400;
|
|
119
|
+
const src = ompTraceSource(root);
|
|
120
|
+
const rules = bloatRules(cfg);
|
|
121
|
+
const dumps = ompDumps(cfg.paths.home);
|
|
122
|
+
let runs = 0;
|
|
123
|
+
let flagged = 0;
|
|
124
|
+
let largest: BloatSummary["largest"] = null;
|
|
125
|
+
const allRuns = ompTraceRuns(root);
|
|
126
|
+
const { owners, events: assignmentEvents } = assignDumps(allRuns, src, dumps);
|
|
127
|
+
for (const r of allRuns) {
|
|
128
|
+
if (r.mtimeSec < cutoff) continue;
|
|
129
|
+
runs++;
|
|
130
|
+
const owned = dumps.filter((dump) => owners.get(dump.file) === r.runId);
|
|
131
|
+
const rep = bloatReport(src, r.runId, rules, cfg.traces.bloat.tool_group, owned, r.mtimeSec, assignmentEvents.get(r.runId));
|
|
132
|
+
if (rep.findings.length === 0) continue;
|
|
133
|
+
flagged++;
|
|
134
|
+
const firstCall = Math.max(rep.firstPrompt ?? 0, rep.dumpPrompt?.tokens ?? 0);
|
|
135
|
+
if (firstCall > 0 && (largest === null || firstCall > largest.firstCall)) largest = { runId: r.runId, firstCall };
|
|
136
|
+
}
|
|
137
|
+
return { runs, flagged, largest };
|
|
138
|
+
}
|
|
139
|
+
|
|
111
140
|
/** Writes notes/metrics.md and prints the same report: this window against the previous one. */
|
|
112
141
|
export function reportCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
|
|
113
142
|
const raw = flagValue(args, "--days");
|
|
@@ -116,7 +145,7 @@ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: n
|
|
|
116
145
|
console.error(METRICS_USAGE);
|
|
117
146
|
return 2;
|
|
118
147
|
}
|
|
119
|
-
const { md, text } = buildReport(cfg, source, days, now, providerSummary(cfg, now, days));
|
|
148
|
+
const { md, text } = buildReport(cfg, source, days, now, providerSummary(cfg, now, days), bloatSummary(cfg, now, days));
|
|
120
149
|
mkdirSync(cfg.paths.notes, { recursive: true });
|
|
121
150
|
writeFileSync(join(cfg.paths.notes, "metrics.md"), md);
|
|
122
151
|
console.log(text);
|