neurastream 0.2.18 → 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 +31 -1
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +47 -20
- 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/src/cli/traces.ts
CHANGED
|
@@ -8,17 +8,23 @@
|
|
|
8
8
|
// machine-readable records.
|
|
9
9
|
// `neurastream traces efficiency …` (plan 20261024_0304 P2): count the run's wasted tool calls
|
|
10
10
|
// under the config's waste rules (src/core/trace-efficiency.ts).
|
|
11
|
+
// `neurastream traces briefs …` (plan 20261024_0305 P1-P2): every spawn brief of the runs touched in a
|
|
12
|
+
// --since window, joined to its agent's waste and acceptance (src/core/trace-briefs.ts). Brief text is
|
|
13
|
+
// never printed; --json carries features and lengths only.
|
|
11
14
|
|
|
12
15
|
import { join } from "node:path";
|
|
13
16
|
import { nowSec } from "../core/clock.ts";
|
|
14
|
-
import type { TraceSource } from "../core/adapter.ts";
|
|
17
|
+
import type { TraceEvent, TraceSource } from "../core/adapter.ts";
|
|
15
18
|
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
16
19
|
import { claimUnbacked } from "../core/incident-detectors.ts";
|
|
17
20
|
import { claimsFromEvents, type RelatedRun } from "../core/trace-claims.ts";
|
|
18
21
|
import { actionsRules, suspiciousActions, type ActionsRules, type SuspiciousAction } from "../core/trace-actions.ts";
|
|
22
|
+
import { bloatBreakdown, bloatFindings, bloatRules, callSizes, dumpFinding, type BloatBreakdown, type BloatRules } from "../core/trace-bloat.ts";
|
|
19
23
|
import { efficiencyRules, runEfficiency, RULE_ORDER, type EfficiencyRules, type WasteRule } from "../core/trace-efficiency.ts";
|
|
20
24
|
import { pyPercent0 } from "../core/pyfmt.ts";
|
|
21
|
-
import { ompTraceRuns, ompTraceSource, subagentTraces } from "../adapters/omp/traces.ts";
|
|
25
|
+
import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompTraceRuns, ompTraceSource, ompTraceStart, spawnBriefsIn, subagentTraces } from "../adapters/omp/traces.ts";
|
|
26
|
+
import { briefReport, briefRows, type SideStat } from "../core/trace-briefs.ts";
|
|
27
|
+
import { readEvents } from "../core/agent-score.ts";
|
|
22
28
|
|
|
23
29
|
export const TRACES_USAGE = [
|
|
24
30
|
"usage: neurastream traces claims <runId> [--json]",
|
|
@@ -27,6 +33,8 @@ export const TRACES_USAGE = [
|
|
|
27
33
|
" neurastream traces actions --since <N m|h|d> [--json]",
|
|
28
34
|
" neurastream traces efficiency <runId> [--json]",
|
|
29
35
|
" neurastream traces efficiency --since <N m|h|d> [--json]",
|
|
36
|
+
" neurastream traces bloat [<runId>] [--since <N m|h|d>] [--json] # default window 24h",
|
|
37
|
+
" neurastream traces briefs [--since <N m|h|d>] [--json] [--report]",
|
|
30
38
|
].join("\n");
|
|
31
39
|
|
|
32
40
|
const SINCE = /^(\d+)(m|h|d)$/;
|
|
@@ -78,10 +86,158 @@ export function efficiencyReport(src: TraceSource, runId: string, rules: Efficie
|
|
|
78
86
|
return { runId, ...runEfficiency(src.events(runId), rules) };
|
|
79
87
|
}
|
|
80
88
|
|
|
81
|
-
|
|
89
|
+
export interface RunBloatReport {
|
|
90
|
+
runId: string;
|
|
91
|
+
/** Model calls in the run (usage-bearing assistant messages, folded per response id). */
|
|
92
|
+
calls: number;
|
|
93
|
+
/** Prompt tokens (input + cacheRead + cacheWrite) of the first call; null when the run made none. */
|
|
94
|
+
firstPrompt: number | null;
|
|
95
|
+
maxPrompt: number | null;
|
|
96
|
+
/** prompt-bloat findings; evidence masked and capped. */
|
|
97
|
+
findings: { kind: string; summary: string; evidence?: string }[];
|
|
98
|
+
/** What filled the prompt, from the uniquely assigned failed-request dump. */
|
|
99
|
+
breakdown?: BloatBreakdown;
|
|
100
|
+
/** The prompt the assigned dump's error response states. */
|
|
101
|
+
dumpPrompt?: { tokens: number; limit?: number };
|
|
102
|
+
/** At least one trace event uses an API whose usage aggregates internal calls. */
|
|
103
|
+
aggregated: boolean;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Scan one run's calls and findings, and report the dump assigned to it by the caller. The
|
|
108
|
+
* command assigns dumps across runs by window, matching model and closest event timestamp.
|
|
109
|
+
*/
|
|
110
|
+
export interface DumpAssignmentRun { runId: string; file: string; mtimeSec: number }
|
|
111
|
+
export interface DumpAssignment { owners: Map<string, string>; unmatched: { file: string; ms: number }[]; events: Map<string, TraceEvent[]> }
|
|
112
|
+
|
|
113
|
+
/** Assign each dump once, parsing only traces whose session start and mtime contain it. */
|
|
114
|
+
export function assignDumps(runs: DumpAssignmentRun[], src: TraceSource, dumps: { file: string; ms: number }[]): DumpAssignment {
|
|
115
|
+
const owners = new Map<string, string>();
|
|
116
|
+
const unmatched: { file: string; ms: number }[] = [];
|
|
117
|
+
const cached = new Map<string, ReturnType<TraceSource["events"]>>();
|
|
118
|
+
for (const dump of dumps) {
|
|
119
|
+
const model = dumpModel(dump.file);
|
|
120
|
+
const eligible: { ts: number; runId: string }[] = [];
|
|
121
|
+
for (const run of runs) {
|
|
122
|
+
if (dump.ms > Math.round(run.mtimeSec * 1000)) continue;
|
|
123
|
+
const start = ompTraceStart(run.file);
|
|
124
|
+
if (start !== null && dump.ms < start * 1000) continue;
|
|
125
|
+
let events = cached.get(run.runId);
|
|
126
|
+
if (!events) {
|
|
127
|
+
events = src.events(run.runId);
|
|
128
|
+
cached.set(run.runId, events);
|
|
129
|
+
}
|
|
130
|
+
let firstTs: number | undefined;
|
|
131
|
+
let closestTs: number | undefined;
|
|
132
|
+
for (const event of events) {
|
|
133
|
+
if (event.ts === null || event.ts * 1000 > dump.ms) continue;
|
|
134
|
+
if (firstTs === undefined || event.ts < firstTs) firstTs = event.ts;
|
|
135
|
+
if (model !== undefined && event.model === model && (closestTs === undefined || event.ts > closestTs)) closestTs = event.ts;
|
|
136
|
+
}
|
|
137
|
+
if (firstTs !== undefined && dump.ms >= firstTs * 1000 && closestTs !== undefined) eligible.push({ runId: run.runId, ts: closestTs });
|
|
138
|
+
}
|
|
139
|
+
const bestTs = eligible.reduce((best, item) => Math.max(best, item.ts), -Infinity);
|
|
140
|
+
const best = eligible.filter((item) => item.ts === bestTs);
|
|
141
|
+
if (best.length === 1) owners.set(dump.file, best[0]!.runId);
|
|
142
|
+
else unmatched.push(dump);
|
|
143
|
+
}
|
|
144
|
+
return { owners, unmatched, events: cached };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function bloatReport(src: TraceSource, runId: string, rules: BloatRules, groupRegex: string, dumps: { file: string; ms: number }[], mtimeSec: number, parsedEvents?: TraceEvent[]): RunBloatReport {
|
|
148
|
+
const events = parsedEvents ?? src.events(runId);
|
|
149
|
+
const sizes = callSizes(events, rules.aggregate_apis);
|
|
150
|
+
const findings = bloatFindings(events, rules);
|
|
151
|
+
const aggregated = events.some((event) => event.api !== undefined && rules.aggregate_apis?.includes(event.api));
|
|
152
|
+
let breakdown: BloatBreakdown | undefined;
|
|
153
|
+
let dumpPrompt: { tokens: number; limit?: number } | undefined;
|
|
154
|
+
let first: number | undefined;
|
|
155
|
+
for (const e of events) {
|
|
156
|
+
if (e.ts !== null) {
|
|
157
|
+
first = e.ts;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (first !== undefined) {
|
|
162
|
+
const dump = dumps.find((d) => d.ms >= first * 1000 && d.ms <= Math.round(mtimeSec * 1000));
|
|
163
|
+
if (dump) {
|
|
164
|
+
breakdown = bloatBreakdown(dumpParts(dump.file), groupRegex);
|
|
165
|
+
const stated = dumpPromptTokens(dump.file);
|
|
166
|
+
if (stated) {
|
|
167
|
+
dumpPrompt = { tokens: stated.tokens, ...(stated.limit !== undefined ? { limit: stated.limit } : {}) };
|
|
168
|
+
if (findings.length === 0) {
|
|
169
|
+
const f = dumpFinding(runId, stated, rules);
|
|
170
|
+
if (f) findings.push(f);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
runId,
|
|
177
|
+
calls: sizes.length,
|
|
178
|
+
firstPrompt: sizes[0]?.prompt ?? null,
|
|
179
|
+
maxPrompt: sizes.length > 0 ? sizes.reduce((m, c) => Math.max(m, c.prompt), 0) : null,
|
|
180
|
+
findings,
|
|
181
|
+
aggregated,
|
|
182
|
+
...(breakdown ? { breakdown } : {}),
|
|
183
|
+
...(dumpPrompt ? { dumpPrompt } : {}),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** `traces briefs`: every spawn brief of the runs touched inside the window (default 30d), joined to its agent's waste and acceptance. */
|
|
188
|
+
function briefsCommand(cfg: Config, root: string, rest: string[]): number {
|
|
189
|
+
let windowSec = 30 * 86400;
|
|
190
|
+
let json = false;
|
|
191
|
+
let report = false;
|
|
192
|
+
for (let i = 0; i < rest.length; i++) {
|
|
193
|
+
const a = rest[i]!;
|
|
194
|
+
if (a === "--json") {
|
|
195
|
+
json = true;
|
|
196
|
+
} else if (a === "--report") {
|
|
197
|
+
report = true;
|
|
198
|
+
} else if (a === "--since") {
|
|
199
|
+
const m = SINCE.exec(rest[++i] ?? "");
|
|
200
|
+
if (!m) {
|
|
201
|
+
console.error(TRACES_USAGE);
|
|
202
|
+
return 2;
|
|
203
|
+
}
|
|
204
|
+
windowSec = Number(m[1]) * (m[2] === "h" ? 3600 : m[2] === "d" ? 86400 : 60);
|
|
205
|
+
} else {
|
|
206
|
+
console.error(TRACES_USAGE);
|
|
207
|
+
return 2;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const cutoff = nowSec() - windowSec;
|
|
211
|
+
const briefs = ompTraceRuns(root)
|
|
212
|
+
.filter((r) => r.mtimeSec >= cutoff)
|
|
213
|
+
.flatMap((r) => spawnBriefsIn(r.file, r.runId));
|
|
214
|
+
const rows = briefRows(briefs, ompTraceSource(root), readEvents(cfg), { brief: cfg.traces.briefs, efficiency: efficiencyRules(cfg) });
|
|
215
|
+
const summary = briefReport(rows, { min_n: cfg.traces.briefs.min_n, char_buckets: cfg.traces.briefs.char_buckets });
|
|
216
|
+
if (json) {
|
|
217
|
+
console.log(JSON.stringify(report ? summary : rows, null, 2));
|
|
218
|
+
return 0;
|
|
219
|
+
}
|
|
220
|
+
if (report) {
|
|
221
|
+
const side = (s: SideStat): string =>
|
|
222
|
+
`n=${s.n} waste=${s.waste === null ? "n too small" : pyPercent0(s.waste)} accept=${s.accept === null ? "n too small" : pyPercent0(s.accept)}`;
|
|
223
|
+
for (const f of summary.features) console.log(`${f.feature}: with [${side(f.with)}] | without [${side(f.without)}]`);
|
|
224
|
+
for (const b of summary.buckets) console.log(`chars ${b.label}: [${side(b.stat)}]`);
|
|
225
|
+
return 0;
|
|
226
|
+
}
|
|
227
|
+
if (rows.length === 0) console.log("no spawn briefs in the window");
|
|
228
|
+
for (const r of rows) {
|
|
229
|
+
const f = r.features;
|
|
230
|
+
const flags = [f.fileLines && "file:line", f.verify && "verify", f.budget && "budget", f.phase && "phase", f.plan && "plan"].filter(Boolean).join(",") || "-";
|
|
231
|
+
const waste = r.waste_pct === null ? "-" : pyPercent0(r.waste_pct);
|
|
232
|
+
console.log(`${r.agent}: ${f.chars} chars, ${f.acceptance} acceptance lines, flags ${flags}, waste ${waste}, ${r.accepted ? "accepted" : "not accepted"}`);
|
|
233
|
+
}
|
|
234
|
+
return 0;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** `neurastream traces claims|actions|efficiency|bloat|briefs`: one run by id, or every run touched inside a --since window (briefs: a window only). */
|
|
82
238
|
export async function runTraces(args: string[], opts: { home?: string } = {}): Promise<number> {
|
|
83
239
|
const sub = args[0];
|
|
84
|
-
if (sub !== "claims" && sub !== "actions" && sub !== "efficiency") {
|
|
240
|
+
if (sub !== "claims" && sub !== "actions" && sub !== "efficiency" && sub !== "bloat" && sub !== "briefs") {
|
|
85
241
|
console.error(TRACES_USAGE);
|
|
86
242
|
return 2;
|
|
87
243
|
}
|
|
@@ -93,6 +249,7 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
|
|
|
93
249
|
return 1;
|
|
94
250
|
}
|
|
95
251
|
const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
|
|
252
|
+
if (sub === "briefs") return briefsCommand(cfg, root, args.slice(1));
|
|
96
253
|
const rest = args.slice(1);
|
|
97
254
|
let runId: string | undefined;
|
|
98
255
|
let windowSec: number | undefined;
|
|
@@ -116,21 +273,33 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
|
|
|
116
273
|
runId = a;
|
|
117
274
|
}
|
|
118
275
|
}
|
|
276
|
+
// `bloat` without a selector scans the plan's default window instead of demanding one.
|
|
277
|
+
if (sub === "bloat" && runId === undefined && windowSec === undefined) windowSec = 24 * 3600;
|
|
119
278
|
if ((runId !== undefined) === (windowSec !== undefined)) {
|
|
120
279
|
console.error(TRACES_USAGE);
|
|
121
280
|
return 2;
|
|
122
281
|
}
|
|
123
282
|
const runs = ompTraceRuns(root);
|
|
124
283
|
const src = ompTraceSource(root);
|
|
125
|
-
const rules = sub === "actions" ? actionsRules(cfg) : sub === "efficiency" ? efficiencyRules(cfg) : null;
|
|
284
|
+
const rules: ActionsRules | EfficiencyRules | BloatRules | null = sub === "actions" ? actionsRules(cfg) : sub === "efficiency" ? efficiencyRules(cfg) : sub === "bloat" ? bloatRules(cfg) : null;
|
|
126
285
|
// A Main run's report cites its subagents' results: their traces under the Main session dir
|
|
127
286
|
// back the pure result-line claims (P5). No time filter — the text match is the guard, and
|
|
128
287
|
// a sub's file keeps being written while its Main run lives, inside whatever window.
|
|
129
288
|
const relatedOf = (id: string): RelatedRun[] =>
|
|
130
289
|
sub === "claims" ? subagentTraces(root, id).map(({ name, events }) => ({ name, events })) : [];
|
|
131
|
-
const
|
|
132
|
-
const
|
|
133
|
-
|
|
290
|
+
const dumps = sub === "bloat" ? ompDumps(cfg.paths.home) : [];
|
|
291
|
+
const assignment = sub === "bloat" ? assignDumps(runs, src, dumps) : { owners: new Map<string, string>(), unmatched: [] as { file: string; ms: number }[], events: new Map<string, TraceEvent[]>() };
|
|
292
|
+
const dumpOwners = assignment.owners;
|
|
293
|
+
const unmatchedDumps = assignment.unmatched;
|
|
294
|
+
const mtimeOf = (id: string): number => runs.find((r) => r.runId === id)?.mtimeSec ?? 0;
|
|
295
|
+
const assignedDumps = (id: string) => dumps.filter((dump) => dumpOwners.get(dump.file) === id);
|
|
296
|
+
const reports: (RunClaimsReport | RunActionsReport | RunEfficiencyReport | RunBloatReport)[] = [];
|
|
297
|
+
const reportOf = (id: string): RunClaimsReport | RunActionsReport | RunEfficiencyReport | RunBloatReport => {
|
|
298
|
+
if (sub === "claims") return claimsReport(src, id, relatedOf(id));
|
|
299
|
+
if (sub === "actions") return actionsReport(src, id, rules as ActionsRules);
|
|
300
|
+
if (sub === "efficiency") return efficiencyReport(src, id, rules as EfficiencyRules);
|
|
301
|
+
return bloatReport(src, id, rules as BloatRules, cfg.traces.bloat.tool_group, assignedDumps(id), mtimeOf(id), assignment.events.get(id));
|
|
302
|
+
};
|
|
134
303
|
if (windowSec !== undefined) {
|
|
135
304
|
const cutoff = nowSec() - windowSec;
|
|
136
305
|
for (const r of runs) {
|
|
@@ -145,7 +314,7 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
|
|
|
145
314
|
reports.push(reportOf(runId!));
|
|
146
315
|
}
|
|
147
316
|
if (json) {
|
|
148
|
-
console.log(JSON.stringify(reports, null, 2));
|
|
317
|
+
console.log(JSON.stringify(sub === "bloat" ? { reports, unmatchedDumps } : reports, null, 2));
|
|
149
318
|
return 0;
|
|
150
319
|
}
|
|
151
320
|
for (const r of reports) {
|
|
@@ -162,6 +331,23 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
|
|
|
162
331
|
} else if ("byRule" in r) {
|
|
163
332
|
console.log(`${r.runId}: ${r.calls} calls, ${r.wasted} wasted (${pyPercent0(r.wastePct)})`);
|
|
164
333
|
for (const rule of RULE_ORDER) console.log(` ${rule}: ${r.byRule[rule]}`);
|
|
334
|
+
} else if ("calls" in r) {
|
|
335
|
+
if (r.aggregated) {
|
|
336
|
+
console.log(`${r.runId}: usage aggregated by provider, per-call size unknown`);
|
|
337
|
+
} else if (r.calls === 0 && r.findings.length === 0) {
|
|
338
|
+
console.log(`${r.runId}: no model calls in the trace`);
|
|
339
|
+
continue;
|
|
340
|
+
} else {
|
|
341
|
+
console.log(`${r.runId}: ${r.calls} calls, first ${r.firstPrompt ?? "-"}, max ${r.maxPrompt ?? "-"} (${r.findings.length === 0 ? "no prompt-bloat" : `${r.findings.length} prompt-bloat`})`);
|
|
342
|
+
}
|
|
343
|
+
for (const f of r.findings) {
|
|
344
|
+
console.log(` ${f.kind}: ${f.summary}`);
|
|
345
|
+
if (f.evidence) console.log(` evidence: ${f.evidence}`);
|
|
346
|
+
}
|
|
347
|
+
if (r.breakdown) {
|
|
348
|
+
console.log(` prompt parts: ${r.breakdown.parts.map((p) => `${p.name} ${p.bytes}`).join(", ")}`);
|
|
349
|
+
console.log(` top tools: ${r.breakdown.tools.map((t) => `${t.name} ${t.bytes}`).join(", ")}`);
|
|
350
|
+
}
|
|
165
351
|
} else {
|
|
166
352
|
if (r.actions.length === 0) {
|
|
167
353
|
console.log(`${r.runId}: no suspicious actions in the trace`);
|
|
@@ -175,5 +361,9 @@ export async function runTraces(args: string[], opts: { home?: string } = {}): P
|
|
|
175
361
|
}
|
|
176
362
|
}
|
|
177
363
|
}
|
|
364
|
+
if (unmatchedDumps.length > 0) {
|
|
365
|
+
console.log("unmatched dumps:");
|
|
366
|
+
for (const dump of unmatchedDumps) console.log(` ${dump.ms} ${dump.file}`);
|
|
367
|
+
}
|
|
178
368
|
return 0;
|
|
179
369
|
}
|
package/src/core/adapter.ts
CHANGED
|
@@ -17,6 +17,9 @@ export interface Run {
|
|
|
17
17
|
cacheRead: number;
|
|
18
18
|
cost: number;
|
|
19
19
|
inputTokens: number;
|
|
20
|
+
/** The run's prefill tokens: the sum of input + cacheRead + cacheWrite over its assistant
|
|
21
|
+
* usage — the prompt side of `tokens`, and the ledger's tok/call numerator. */
|
|
22
|
+
prefillTokens: number;
|
|
20
23
|
status: RunStatus;
|
|
21
24
|
statusDetail: string;
|
|
22
25
|
startedAt: number | null;
|
|
@@ -69,6 +72,8 @@ export interface TraceEvent {
|
|
|
69
72
|
text?: string;
|
|
70
73
|
model?: string;
|
|
71
74
|
provider?: string;
|
|
75
|
+
/** Adapter-provided API identifier for the message carrying this event. */
|
|
76
|
+
api?: string;
|
|
72
77
|
usage?: TraceUsage;
|
|
73
78
|
/** Provider response id of the assistant message; absent when the line carries none. */
|
|
74
79
|
responseId?: string;
|
package/src/core/agent-ledger.ts
CHANGED
|
@@ -16,12 +16,14 @@ function opt(args: string[], name: string): string | undefined {
|
|
|
16
16
|
|
|
17
17
|
function rowLine(r: Run): string {
|
|
18
18
|
const pct = r.tokens ? (100 * r.cacheRead) / r.tokens : 0;
|
|
19
|
+
const perCall = r.calls ? r.prefillTokens / r.calls : 0;
|
|
19
20
|
const when = strftime(r.lastWriteAt, "%m-%d %H:%M");
|
|
20
21
|
return [
|
|
21
22
|
r.id.slice(0, 28).padEnd(28, " "),
|
|
22
23
|
r.model.slice(0, 38).padEnd(38, " "),
|
|
23
24
|
String(r.calls).padStart(5, " "),
|
|
24
25
|
pyFixedWidth(r.tokens / 1e6, 1, 7),
|
|
26
|
+
pyFixedWidth(perCall, 0, 8),
|
|
25
27
|
`${pyFixedWidth(pct, 0, 5)}%`,
|
|
26
28
|
pyFixedWidth(r.cost, 2, 7),
|
|
27
29
|
when,
|
|
@@ -50,6 +52,7 @@ export function agentLedger(args: string[], cfg: Config, source: RunSource): num
|
|
|
50
52
|
"model".padEnd(38, " "),
|
|
51
53
|
"calls".padStart(5, " "),
|
|
52
54
|
"Mtok".padStart(7, " "),
|
|
55
|
+
"tok/call".padStart(8, " "),
|
|
53
56
|
"cache%".padStart(6, " "),
|
|
54
57
|
"$list".padStart(7, " "),
|
|
55
58
|
"last-write ended",
|
package/src/core/config.ts
CHANGED
|
@@ -162,7 +162,7 @@ export interface Config {
|
|
|
162
162
|
watch_sec: number;
|
|
163
163
|
watch_streak: number;
|
|
164
164
|
};
|
|
165
|
-
quota: { reset_tz: string; label: string };
|
|
165
|
+
quota: { reset_tz: string; reset_pattern: string; label: string };
|
|
166
166
|
/** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
|
|
167
167
|
* The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
|
|
168
168
|
notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
|
|
@@ -183,6 +183,19 @@ export interface Config {
|
|
|
183
183
|
allowed_hosts: string[];
|
|
184
184
|
/** Product names (docs/config.md) whose files another product's run may not read quietly. */
|
|
185
185
|
owned_repos: string[];
|
|
186
|
+
/** Prompt-size rules (src/core/trace-bloat.ts): when a run flags prompt-bloat. */
|
|
187
|
+
bloat: {
|
|
188
|
+
/** The largest first-call prompt a healthy run may open with. */
|
|
189
|
+
first_call_max: number;
|
|
190
|
+
/** A call flags when its prompt passes ratio_of_limit × its model's context_limits entry. */
|
|
191
|
+
ratio_of_limit: number;
|
|
192
|
+
/** Model -> context tokens; a model without an entry is not limit-checked. Open map. */
|
|
193
|
+
context_limits: Record<string, number>;
|
|
194
|
+
/** APIs whose usage aggregates multiple internal calls and is not per-call size. */
|
|
195
|
+
aggregate_apis: string[];
|
|
196
|
+
/** First capture of this regex on a tool name names its bloat group (no match: "builtin"). */
|
|
197
|
+
tool_group: string;
|
|
198
|
+
};
|
|
186
199
|
actions: {
|
|
187
200
|
secret_globs: string[];
|
|
188
201
|
net_tools: string[];
|
|
@@ -199,6 +212,19 @@ export interface Config {
|
|
|
199
212
|
/** Shell commands matching this poll while nothing else runs. */
|
|
200
213
|
poll_pattern: string;
|
|
201
214
|
};
|
|
215
|
+
/** Brief-quality rules (src/core/trace-briefs.ts): what a spawn brief names, and how the report buckets briefs by length. */
|
|
216
|
+
briefs: {
|
|
217
|
+
/** A brief whose text matches this names a verify command. */
|
|
218
|
+
verify_pattern: string;
|
|
219
|
+
/** A brief whose text matches this names a phase. */
|
|
220
|
+
phase_pattern: string;
|
|
221
|
+
/** A brief whose text matches this names a plan file. */
|
|
222
|
+
plan_pattern: string;
|
|
223
|
+
/** Ascending char edges that split briefs into length buckets in the report. */
|
|
224
|
+
char_buckets: number[];
|
|
225
|
+
/** The report shows a mean only when at least this many rows sit on that side; >= 1. */
|
|
226
|
+
min_n: number;
|
|
227
|
+
};
|
|
202
228
|
};
|
|
203
229
|
/** Optional overlay written by adapter install. Absent until an adapter is installed. */
|
|
204
230
|
adapter?: { name: string; sessions: string; pins: string; extensions: string };
|
|
@@ -335,6 +361,30 @@ function applyEnv(cfg: Record<string, unknown>, env: NodeJS.ProcessEnv): void {
|
|
|
335
361
|
}
|
|
336
362
|
|
|
337
363
|
function check(cfg: Config): void {
|
|
364
|
+
try {
|
|
365
|
+
const pattern = cfg.quota.reset_pattern;
|
|
366
|
+
new RegExp(pattern);
|
|
367
|
+
let groups = 0;
|
|
368
|
+
let escaped = false;
|
|
369
|
+
let inClass = false;
|
|
370
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
371
|
+
const char = pattern[i];
|
|
372
|
+
if (escaped) {
|
|
373
|
+
escaped = false;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (char === "\\") {
|
|
377
|
+
escaped = true;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (char === "[" && !inClass) inClass = true;
|
|
381
|
+
else if (char === "]" && inClass) inClass = false;
|
|
382
|
+
else if (char === "(" && !inClass && pattern[i + 1] !== "?") groups++;
|
|
383
|
+
}
|
|
384
|
+
if (groups < 1) throw new Error("missing capture group 1");
|
|
385
|
+
} catch {
|
|
386
|
+
throw new ConfigError("quota.reset_pattern must be a valid regex with capture group 1");
|
|
387
|
+
}
|
|
338
388
|
if (!(Number.isFinite(cfg.score.waste_weight) && cfg.score.waste_weight >= 0 && cfg.score.waste_weight <= 1)) {
|
|
339
389
|
throw new ConfigError("score.waste_weight must be between 0 and 1");
|
|
340
390
|
}
|
|
@@ -377,6 +427,28 @@ function check(cfg: Config): void {
|
|
|
377
427
|
}
|
|
378
428
|
}
|
|
379
429
|
}
|
|
430
|
+
if (typeof cfg.traces.bloat.first_call_max !== "number" || !Number.isFinite(cfg.traces.bloat.first_call_max) || !(cfg.traces.bloat.first_call_max > 0)) {
|
|
431
|
+
throw new ConfigError("traces.bloat.first_call_max must be a number > 0");
|
|
432
|
+
}
|
|
433
|
+
if (typeof cfg.traces.bloat.ratio_of_limit !== "number" || !Number.isFinite(cfg.traces.bloat.ratio_of_limit) || !(cfg.traces.bloat.ratio_of_limit > 0) || cfg.traces.bloat.ratio_of_limit > 1) {
|
|
434
|
+
throw new ConfigError("traces.bloat.ratio_of_limit must be a number in (0, 1]");
|
|
435
|
+
}
|
|
436
|
+
if (!Array.isArray(cfg.traces.bloat.aggregate_apis) || cfg.traces.bloat.aggregate_apis.some((api) => typeof api !== "string" || api === "")) {
|
|
437
|
+
throw new ConfigError("traces.bloat.aggregate_apis must be a list of non-empty strings");
|
|
438
|
+
}
|
|
439
|
+
for (const [model, limit] of Object.entries(cfg.traces.bloat.context_limits)) {
|
|
440
|
+
if (typeof limit !== "number" || !Number.isFinite(limit) || !(limit > 0)) {
|
|
441
|
+
throw new ConfigError(`traces.bloat.context_limits.${model} must be a number > 0`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (typeof cfg.traces.bloat.tool_group !== "string" || cfg.traces.bloat.tool_group === "") {
|
|
445
|
+
throw new ConfigError("traces.bloat.tool_group must be a non-empty string");
|
|
446
|
+
}
|
|
447
|
+
try {
|
|
448
|
+
new RegExp(cfg.traces.bloat.tool_group);
|
|
449
|
+
} catch {
|
|
450
|
+
throw new ConfigError(`traces.bloat.tool_group: not a valid regex: ${cfg.traces.bloat.tool_group}`);
|
|
451
|
+
}
|
|
380
452
|
for (const rule of cfg.brief.repo_rules) {
|
|
381
453
|
for (const key of ["match", "require", "first", "unless"] as const) {
|
|
382
454
|
const pattern = rule[key];
|
|
@@ -405,6 +477,20 @@ function check(cfg: Config): void {
|
|
|
405
477
|
} catch {
|
|
406
478
|
throw new ConfigError(`traces.efficiency.poll_pattern: not a valid regex: ${cfg.traces.efficiency.poll_pattern}`);
|
|
407
479
|
}
|
|
480
|
+
const briefs = cfg.traces.briefs;
|
|
481
|
+
for (const key of ["verify_pattern", "phase_pattern", "plan_pattern"] as const) {
|
|
482
|
+
if (typeof briefs[key] !== "string") throw new ConfigError(`traces.briefs.${key} must be a string`);
|
|
483
|
+
try {
|
|
484
|
+
new RegExp(briefs[key]);
|
|
485
|
+
} catch {
|
|
486
|
+
throw new ConfigError(`traces.briefs.${key}: not a valid regex: ${briefs[key]}`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (!Number.isInteger(briefs.min_n) || briefs.min_n < 1) throw new ConfigError("traces.briefs.min_n must be an integer >= 1");
|
|
490
|
+
const edges = briefs.char_buckets;
|
|
491
|
+
if (!Array.isArray(edges) || edges.some((v, i) => !Number.isInteger(v) || v < 1 || (i > 0 && v <= edges[i - 1]!))) {
|
|
492
|
+
throw new ConfigError("traces.briefs.char_buckets must be ascending positive integers");
|
|
493
|
+
}
|
|
408
494
|
for (const [key, value] of Object.entries(cfg.paths)) {
|
|
409
495
|
if (key === "work_roots") {
|
|
410
496
|
if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
|
package/src/core/quota-reset.ts
CHANGED
|
@@ -1,84 +1,9 @@
|
|
|
1
|
-
import { spawnSync } from "node:child_process";
|
|
2
1
|
import type { Config } from "./config.ts";
|
|
3
|
-
|
|
4
|
-
// Converts a provider's rate-limit reset time (wall clock in the provider's zone) into the caller's
|
|
5
|
-
// local time. Intl does the zone math; date(1) supplies the local zone abbreviation, because Intl's
|
|
6
|
-
// short timeZoneName is a tzdata abbreviation only for US zones (Europe/Berlin prints "GMT+2" where
|
|
7
|
-
// date +%Z prints "CEST"). macOS's BSD date is used there, so no GNU date is needed.
|
|
2
|
+
import { localStamp, parseWhen, wallToEpoch } from "./reset-time.ts";
|
|
8
3
|
|
|
9
4
|
const USAGE =
|
|
10
5
|
'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] (reset time from your provider\'s rate-limit message)\n';
|
|
11
6
|
|
|
12
|
-
// Offset in ms of `zone` from UTC at the instant `epochMs` (local wall clock minus UTC).
|
|
13
|
-
function zoneOffsetMs(epochMs: number, zone: string): number {
|
|
14
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
15
|
-
timeZone: zone,
|
|
16
|
-
hourCycle: "h23",
|
|
17
|
-
year: "numeric",
|
|
18
|
-
month: "numeric",
|
|
19
|
-
day: "numeric",
|
|
20
|
-
hour: "numeric",
|
|
21
|
-
minute: "numeric",
|
|
22
|
-
second: "numeric",
|
|
23
|
-
}).formatToParts(new Date(epochMs));
|
|
24
|
-
const get = (type: string): number => Number(parts.find((p) => p.type === type)?.value);
|
|
25
|
-
const wallAsUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
|
|
26
|
-
return wallAsUtc - Math.floor(epochMs / 1000) * 1000;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Epoch seconds for a wall-clock time in `zone`; two passes settle the DST edge.
|
|
30
|
-
function wallToEpoch(wall: { y: number; mo: number; d: number; h: number; mi: number; s: number }, zone: string): number {
|
|
31
|
-
const wallUtc = Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s);
|
|
32
|
-
const first = wallUtc - zoneOffsetMs(wallUtc, zone);
|
|
33
|
-
const second = wallUtc - zoneOffsetMs(first, zone);
|
|
34
|
-
return Math.floor(second / 1000);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const WHEN = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/;
|
|
38
|
-
|
|
39
|
-
function parseWhen(text: string): { y: number; mo: number; d: number; h: number; mi: number; s: number } | null {
|
|
40
|
-
const m = WHEN.exec(text.trim());
|
|
41
|
-
if (!m) return null;
|
|
42
|
-
const [, ys = "", mos = "", ds = "", hs = "", mis = "", ss = ""] = m;
|
|
43
|
-
const wall = { y: +ys, mo: +mos, d: +ds, h: +hs, mi: +mis, s: ss ? +ss : 0 };
|
|
44
|
-
const check = new Date(Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s));
|
|
45
|
-
const valid =
|
|
46
|
-
check.getUTCFullYear() === wall.y &&
|
|
47
|
-
check.getUTCMonth() === wall.mo - 1 &&
|
|
48
|
-
check.getUTCDate() === wall.d &&
|
|
49
|
-
check.getUTCHours() === wall.h &&
|
|
50
|
-
check.getUTCMinutes() === wall.mi &&
|
|
51
|
-
check.getUTCSeconds() === wall.s;
|
|
52
|
-
return valid ? wall : null;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// The tzdata abbreviation for this instant (CEST, CET, CST, +05) as date(1) prints it in the zone
|
|
56
|
-
// env this process runs in (the child inherits it, so the abbreviation always matches the wall
|
|
57
|
-
// clock next to it). Falls back to the Intl short name only when date fails.
|
|
58
|
-
function zoneAbbrev(epoch: number): string {
|
|
59
|
-
const probe =
|
|
60
|
-
process.platform === "darwin"
|
|
61
|
-
? spawnSync("date", ["-r", String(epoch), "+%Z"], { encoding: "utf8" })
|
|
62
|
-
: spawnSync("date", ["-d", `@${epoch}`, "+%Z"], { encoding: "utf8" });
|
|
63
|
-
if (probe.status === 0 && probe.stdout?.trim()) return probe.stdout.trim();
|
|
64
|
-
const parts = new Intl.DateTimeFormat("en-US", { timeZoneName: "short" }).formatToParts(new Date(epoch * 1000));
|
|
65
|
-
return parts.find(p => p.type === "timeZoneName")?.value ?? "";
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// Local wall clock of the process, "YYYY-MM-DD HH:MM:SS ZONE".
|
|
69
|
-
function localStamp(epoch: number): string {
|
|
70
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
71
|
-
hourCycle: "h23",
|
|
72
|
-
year: "numeric",
|
|
73
|
-
month: "2-digit",
|
|
74
|
-
day: "2-digit",
|
|
75
|
-
hour: "2-digit",
|
|
76
|
-
minute: "2-digit",
|
|
77
|
-
second: "2-digit",
|
|
78
|
-
}).formatToParts(new Date(epoch * 1000));
|
|
79
|
-
const get = (type: string): string => parts.find(p => p.type === type)?.value ?? "";
|
|
80
|
-
return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")} ${zoneAbbrev(epoch)}`;
|
|
81
|
-
}
|
|
82
7
|
|
|
83
8
|
export function quotaReset(args: string[], cfg: Config): number {
|
|
84
9
|
let zone = cfg.quota.reset_tz;
|
package/src/core/report.ts
CHANGED
|
@@ -181,7 +181,19 @@ export interface ProviderSummary {
|
|
|
181
181
|
byKind: Record<string, number>;
|
|
182
182
|
}
|
|
183
183
|
|
|
184
|
-
|
|
184
|
+
/** Weekly prompt-bloat counts the report appends; built next to ProviderSummary by the same
|
|
185
|
+
* CLI caller, folding src/core/trace-bloat.ts findings over the runs touched in the window. */
|
|
186
|
+
export interface BloatSummary {
|
|
187
|
+
/** Runs scanned inside the window. */
|
|
188
|
+
runs: number;
|
|
189
|
+
/** Runs with at least one prompt-bloat finding over those runs. */
|
|
190
|
+
flagged: number;
|
|
191
|
+
/** The largest first call among the flagged runs — the run's usage, else its matched
|
|
192
|
+
* dump's stated prompt (a rejected call wrote no usage) — with the run id. */
|
|
193
|
+
largest: { runId: string; firstCall: number } | null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function buildReport(cfg: Config, source: RunSource, days: number, now: number, provider?: ProviderSummary, bloat?: BloatSummary): Report {
|
|
185
197
|
const inp = loadInputs(cfg, source, now, days);
|
|
186
198
|
const events = [...inp.events, ...readMetricEvents(cfg)];
|
|
187
199
|
const blocks = readBlocks(cfg);
|
|
@@ -227,6 +239,13 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
227
239
|
.join(", ") || "no findings"),
|
|
228
240
|
]
|
|
229
241
|
: []),
|
|
242
|
+
...(bloat
|
|
243
|
+
? [
|
|
244
|
+
"",
|
|
245
|
+
`Prompt bloat over ${bloat.runs} runs: ${bloat.flagged} flagged` +
|
|
246
|
+
(bloat.largest ? `, largest first call ${bloat.largest.firstCall} tokens (${bloat.largest.runId})` : ""),
|
|
247
|
+
]
|
|
248
|
+
: []),
|
|
230
249
|
].join("\n");
|
|
231
250
|
|
|
232
251
|
const md = [
|