pi-evals 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +116 -2
  4. package/dist/aggregate.js +113 -0
  5. package/dist/build.js +260 -0
  6. package/dist/changes.js +170 -0
  7. package/dist/cli.js +86 -0
  8. package/dist/coverage.js +34 -0
  9. package/dist/detectors.js +154 -0
  10. package/dist/extract/file.js +42 -0
  11. package/dist/extract/run.js +149 -0
  12. package/dist/extract/session.js +430 -0
  13. package/dist/extract/worker.js +12 -0
  14. package/dist/index.js +165 -0
  15. package/dist/meta.js +233 -0
  16. package/dist/model.js +317 -0
  17. package/dist/observer.js +240 -0
  18. package/dist/ops.js +93 -0
  19. package/dist/owners.js +97 -0
  20. package/dist/paths.js +76 -0
  21. package/dist/project.js +43 -0
  22. package/dist/query.js +92 -0
  23. package/dist/render.js +31 -0
  24. package/dist/report/concepts.js +37 -0
  25. package/dist/report/findings.js +73 -0
  26. package/dist/report/format.js +16 -0
  27. package/dist/report/sections.js +61 -0
  28. package/dist/report/style.js +77 -0
  29. package/dist/report/timeline.js +91 -0
  30. package/dist/report/week.js +36 -0
  31. package/dist/schema.js +65 -0
  32. package/dist/skills.js +41 -0
  33. package/dist/store.js +51 -0
  34. package/docs/design.md +106 -0
  35. package/docs/learn.zh-TW.md +33 -0
  36. package/docs/schema.md +68 -0
  37. package/package.json +56 -4
  38. package/src/aggregate.ts +204 -0
  39. package/src/build.ts +257 -0
  40. package/src/changes.ts +178 -0
  41. package/src/cli.ts +89 -0
  42. package/src/coverage.ts +44 -0
  43. package/src/detectors.ts +182 -0
  44. package/src/extract/file.ts +46 -0
  45. package/src/extract/run.ts +198 -0
  46. package/src/extract/session.ts +430 -0
  47. package/src/extract/worker.ts +12 -0
  48. package/src/index.ts +160 -0
  49. package/src/meta.ts +259 -0
  50. package/src/model.ts +346 -0
  51. package/src/observer.ts +255 -0
  52. package/src/ops.ts +110 -0
  53. package/src/owners.ts +92 -0
  54. package/src/paths.ts +108 -0
  55. package/src/project.ts +43 -0
  56. package/src/query.ts +85 -0
  57. package/src/render.ts +63 -0
  58. package/src/report/concepts.ts +94 -0
  59. package/src/report/findings.ts +84 -0
  60. package/src/report/format.ts +24 -0
  61. package/src/report/sections.ts +188 -0
  62. package/src/report/style.ts +77 -0
  63. package/src/report/timeline.ts +143 -0
  64. package/src/report/week.ts +55 -0
  65. package/src/schema.ts +84 -0
  66. package/src/skills.ts +46 -0
  67. package/src/store.ts +49 -0
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Reads one pi session file (JSONL v3) line by line and derives records and a summary.
3
+ * Only names, counts, durations, exit codes, outcomes, token and cost numbers leave this module; arguments,
4
+ * results and text are looked at (to recognise a skill path, an Anchor line, a monitor id) and dropped.
5
+ */
6
+ import { basename } from "node:path";
7
+ import { bucketOf, bump, type DayAgg, emptyDay, type SessionSummary } from "../aggregate.ts";
8
+ import { ERA_START, ProcessTracker } from "../detectors.ts";
9
+ import { dayOf } from "../paths.ts";
10
+ import { projectKey } from "../project.ts";
11
+ import { type Attrs, type EvalRecord, NAMES, record, safeName, type SkillTrigger, spanId, traceId } from "../schema.ts";
12
+ import { skillFromPath, skillsFromBlocks, skillsFromCatalog, skillsFromCommand } from "../skills.ts";
13
+
14
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
15
+ const CHILD_FILE = new RegExp(`_(${UUID})-[0-9a-f]{8}-[0-9a-f]{8}-[0-9a-f]{4}\\.jsonl$`);
16
+ const BRIEF_PARENT = new RegExp(`/artifacts/(${UUID})/context/`);
17
+ const ASK_TOOLS = new Set(["ask_user_question", "ask_user"]);
18
+
19
+ interface PendingCall {
20
+ name: string;
21
+ ts: string;
22
+ trace?: string;
23
+ skill?: { skill: string; resource?: string };
24
+ monitor?: boolean;
25
+ role?: string;
26
+ model?: string;
27
+ questions?: number;
28
+ }
29
+
30
+ type Obj = Record<string, unknown>;
31
+ const obj = (v: unknown): Obj => (v && typeof v === "object" ? (v as Obj) : {});
32
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
33
+ const str = (v: unknown) => (typeof v === "string" ? v : undefined);
34
+
35
+ /** A subagent's logical id, from a file name `<ts>_<logicalId>-<gen8>-<gen8>-<gen4>.jsonl`. */
36
+ export const logicalIdOf = (path: string) => basename(path).match(CHILD_FILE)?.[1];
37
+
38
+ function textOf(content: unknown): string {
39
+ if (typeof content === "string") return content;
40
+ if (!Array.isArray(content)) return "";
41
+ return content.map((p) => (p && typeof p === "object" && (p as Obj).type === "text" ? String((p as Obj).text ?? "") : "")).join("\n");
42
+ }
43
+
44
+ export class SessionReader {
45
+ readonly records: EvalRecord[] = [];
46
+ private sessionId = "";
47
+ private project = "unknown";
48
+ private start = "";
49
+ private end = "";
50
+ private trace?: string;
51
+ private traceUsage?: { rec: EvalRecord; input: number; output: number; cacheRead: number; cacheWrite: number; cost: number; tools: number };
52
+ private calls = new Map<string, PendingCall>();
53
+ private monitorStart = new Map<string, string>();
54
+ private tracker = new ProcessTracker();
55
+ private days: Record<string, DayAgg> = {};
56
+ private spawned: SessionSummary["spawned"] = [];
57
+ private loaded = new Set<string>();
58
+ private parentId?: string;
59
+ private catalog?: string[];
60
+ private cost = 0;
61
+ private tokens = 0;
62
+ private toolCalls = 0;
63
+ private notices: SessionSummary["notices"] = {};
64
+ private firstUser = true;
65
+ private model?: string;
66
+ readonly logicalId?: string;
67
+ private readonly home: string;
68
+ private readonly emit: (r: EvalRecord) => void;
69
+
70
+ /** `emit` receives each record as it is made; by default they collect in `records`. */
71
+ constructor(path: string, home: string, emit?: (r: EvalRecord) => void) {
72
+ this.logicalId = logicalIdOf(path);
73
+ this.home = home;
74
+ this.emit = emit ?? ((r) => void this.records.push(r));
75
+ }
76
+
77
+ private day(ts: string): DayAgg {
78
+ const key = dayOf(ts || this.start || 0);
79
+ return (this.days[key] ??= emptyDay());
80
+ }
81
+
82
+ private base(): Attrs {
83
+ return { "session.id": this.sessionId, "pi.project": this.project };
84
+ }
85
+
86
+ feedLine(line: string): void {
87
+ if (!line || line.charCodeAt(0) !== 123) return;
88
+ let entry: Obj;
89
+ try {
90
+ entry = JSON.parse(line) as Obj;
91
+ } catch {
92
+ return;
93
+ }
94
+ this.feed(entry);
95
+ }
96
+
97
+ feed(entry: Obj): void {
98
+ const ts = str(entry.timestamp) ?? this.end;
99
+ if (ts && (!this.end || ts > this.end)) this.end = ts;
100
+ const type = entry.type;
101
+ if (type === "session") return this.header(entry);
102
+ if (!this.start && ts) this.start = ts;
103
+ const kind = this.tracker.feed(entry);
104
+ if (type === "model_change") {
105
+ this.model = safeName(`${str(entry.provider) ?? "?"}/${str(entry.modelId) ?? "?"}`);
106
+ } else if (type === "compaction") {
107
+ this.day(ts).compactions += 1;
108
+ this.emit(record({ name: NAMES.compaction, kind: "event", ts, source: "backfill", trace_id: this.trace, attrs: this.base() }));
109
+ } else if (type === "custom_message") {
110
+ this.customMessage(entry, ts, kind);
111
+ } else if (type === "message") {
112
+ const message = obj(entry.message);
113
+ const role = message.role;
114
+ if (role === "user") this.user(entry, message, ts);
115
+ else if (role === "assistant") this.assistant(message, ts);
116
+ else if (role === "toolResult") this.toolResult(message, ts);
117
+ else if (role === "system") this.system(message);
118
+ }
119
+ }
120
+
121
+ private header(entry: Obj) {
122
+ this.sessionId = safeName(str(entry.id) ?? "");
123
+ this.start = str(entry.timestamp) ?? this.start;
124
+ this.project = safeName(projectKey(str(entry.cwd), this.home));
125
+ }
126
+
127
+ private system(message: Obj) {
128
+ const sections = obj(message.sections);
129
+ const names = skillsFromCatalog(sections.skills ?? textOf(message.content));
130
+ if (names.length) this.catalog = names.map(safeName);
131
+ }
132
+
133
+ private user(entry: Obj, message: Obj, ts: string) {
134
+ const text = textOf(message.content);
135
+ if (this.firstUser) {
136
+ this.firstUser = false;
137
+ const parent = text.slice(0, 2000).match(BRIEF_PARENT)?.[1];
138
+ if (parent && this.logicalId) this.parentId = parent;
139
+ }
140
+ const anchor = str(entry.id) ?? ts;
141
+ this.closeTrace();
142
+ this.trace = traceId(this.sessionId, anchor);
143
+ const slash = text.startsWith("<skill name=") ? skillsFromBlocks(text.slice(0, 4000)) : [];
144
+ const rec = record({
145
+ name: NAMES.prompt,
146
+ kind: "span",
147
+ ts,
148
+ source: "backfill",
149
+ trace_id: this.trace,
150
+ span_id: spanId(this.sessionId, anchor),
151
+ attrs: { ...this.base(), "gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": "pi", "pi.prompt.origin": slash.length ? "skill_command" : "user" },
152
+ });
153
+ this.traceUsage = { rec, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, tools: 0 };
154
+ this.day(ts).prompts += 1;
155
+ for (const skill of slash) this.skillLoad(skill, "slash", ts);
156
+ }
157
+
158
+ private closeTrace() {
159
+ const t = this.traceUsage;
160
+ if (!t) return;
161
+ Object.assign(t.rec.attrs, {
162
+ "gen_ai.usage.input_tokens": t.input,
163
+ "gen_ai.usage.output_tokens": t.output,
164
+ "gen_ai.usage.cache_read.input_tokens": t.cacheRead,
165
+ "gen_ai.usage.cache_write.input_tokens": t.cacheWrite,
166
+ "pi.usage.cost_usd": Math.round(t.cost * 1e6) / 1e6,
167
+ "pi.tool_calls": t.tools,
168
+ });
169
+ if (this.end > t.rec.ts) {
170
+ t.rec.end_ts = this.end;
171
+ t.rec.duration_ms = Date.parse(this.end) - Date.parse(t.rec.ts);
172
+ }
173
+ this.emit(t.rec);
174
+ this.traceUsage = undefined;
175
+ }
176
+
177
+ private assistant(message: Obj, ts: string) {
178
+ const model = safeName(`${str(message.provider) ?? "?"}/${str(message.model) ?? "?"}`);
179
+ this.model = model;
180
+ const usage = obj(message.usage);
181
+ const day = this.day(ts);
182
+ const u = { input: num(usage.input), output: num(usage.output), cacheRead: num(usage.cacheRead), cacheWrite: num(usage.cacheWrite), cost: num(obj(usage.cost).total) };
183
+ day.usage.input += u.input;
184
+ day.usage.output += u.output;
185
+ day.usage.cacheRead += u.cacheRead;
186
+ day.usage.cacheWrite += u.cacheWrite;
187
+ day.usage.cost += u.cost;
188
+ day.usage.calls += 1;
189
+ bump(day.models, model);
190
+ this.cost += u.cost;
191
+ this.tokens += num(usage.totalTokens) || u.input + u.output + u.cacheRead + u.cacheWrite;
192
+ if (this.traceUsage) {
193
+ this.traceUsage.input += u.input;
194
+ this.traceUsage.output += u.output;
195
+ this.traceUsage.cacheRead += u.cacheRead;
196
+ this.traceUsage.cacheWrite += u.cacheWrite;
197
+ this.traceUsage.cost += u.cost;
198
+ }
199
+ if (!Array.isArray(message.content)) return;
200
+ for (const raw of message.content) {
201
+ const part = obj(raw);
202
+ if (part.type !== "toolCall" || typeof part.id !== "string") continue;
203
+ const name = safeName(str(part.name) ?? "unknown");
204
+ const args = obj(part.arguments);
205
+ const call: PendingCall = { name, ts, trace: this.trace };
206
+ if (name === "read") call.skill = skillFromPath(args.path ?? args.file_path);
207
+ else if (name === "bash") for (const skill of skillsFromCommand(args.command)) this.skillLoad(skill, "bash", ts, part.id);
208
+ else if (name === "subagent") {
209
+ call.role = safeName(str(args.agent) ?? "default");
210
+ call.model = safeName(str(args.model) ?? "default");
211
+ } else if (ASK_TOOLS.has(name)) call.questions = Array.isArray(args.questions) ? args.questions.length : 1;
212
+ else if (name === "MonitorCreate") call.monitor = true;
213
+ this.calls.set(part.id, call);
214
+ }
215
+ }
216
+
217
+ private toolResult(message: Obj, ts: string) {
218
+ const id = str(message.toolCallId);
219
+ const call = id ? this.calls.get(id) : undefined;
220
+ const name = call?.name ?? safeName(str(message.toolName) ?? "unknown");
221
+ if (id) this.calls.delete(id);
222
+ const isError = message.isError === true;
223
+ const measured = typeof message.durationMs === "number";
224
+ const duration = measured ? num(message.durationMs) : call ? Math.max(0, Date.parse(ts) - Date.parse(call.ts)) : undefined;
225
+ const details = obj(message.details);
226
+ const exit = obj(message.structuredContent).exit_code;
227
+ const day = this.day(ts);
228
+ const agg = (day.tools[name] ??= { calls: 0, errors: 0, durSum: 0, durN: 0 });
229
+ agg.calls += 1;
230
+ if (isError) agg.errors += 1;
231
+ if (duration !== undefined) {
232
+ agg.durSum += duration;
233
+ agg.durN += 1;
234
+ }
235
+ this.toolCalls += 1;
236
+ if (this.traceUsage) this.traceUsage.tools += 1;
237
+ const attrs: Attrs = {
238
+ ...this.base(),
239
+ "gen_ai.operation.name": "execute_tool",
240
+ "gen_ai.tool.name": name,
241
+ "gen_ai.tool.call.id": id,
242
+ "error.type": isError ? "tool_error" : undefined,
243
+ "pi.duration.source": measured ? "measured" : "timestamps",
244
+ "pi.tool.exit_code": typeof exit === "number" ? exit : undefined,
245
+ };
246
+ if (call?.skill && !isError) {
247
+ attrs["gen_ai.skill.name"] = call.skill.skill; // record() checks it; skillLoad keys the summary by safeName
248
+ if (call.skill.resource) attrs["gen_ai.skill.resource.name"] = call.skill.resource;
249
+ else this.skillLoad(call.skill.skill, "read", ts, id);
250
+ }
251
+ if (ASK_TOOLS.has(name)) this.ask(attrs, details, isError, duration, call, day);
252
+ if (name === "subagent" && !isError) {
253
+ const child = str(details.id) ? safeName(details.id) : undefined;
254
+ const role = safeName(str(details.agent) ?? call?.role ?? "default");
255
+ const model = safeName(str(details.model) ?? call?.model ?? "default");
256
+ attrs["gen_ai.agent.name"] = role;
257
+ attrs["gen_ai.request.model"] = model;
258
+ attrs["pi.subagent.logical_id"] = child;
259
+ bump(day.subagents, `${role}|${model}`);
260
+ if (child) this.spawned.push({ id: child, role, model });
261
+ }
262
+ if (call?.monitor && !isError) {
263
+ const monitorId = textOf(message.content).concat(" ", str(details.summary) ?? "").match(/Monitor #(\d+)/)?.[1];
264
+ day.monitors.started += 1;
265
+ if (monitorId) this.monitorStart.set(monitorId, ts);
266
+ }
267
+ this.emit(
268
+ record({
269
+ name: NAMES.tool,
270
+ kind: "span",
271
+ ts: call?.ts ?? ts,
272
+ end_ts: ts,
273
+ duration_ms: duration,
274
+ source: "backfill",
275
+ trace_id: call?.trace ?? this.trace,
276
+ span_id: id ? spanId(this.sessionId, id) : undefined,
277
+ attrs,
278
+ }),
279
+ );
280
+ }
281
+
282
+ private ask(attrs: Attrs, details: Obj, isError: boolean, duration: number | undefined, call: PendingCall | undefined, day: DayAgg) {
283
+ const cancelled = details.cancelled === true;
284
+ const questions = Array.isArray(details.questions) ? details.questions.length : Array.isArray(details.answers) ? details.answers.length : (call?.questions ?? 1);
285
+ attrs["pi.ask_user.questions"] = questions;
286
+ attrs["pi.ask_user.cancelled"] = cancelled;
287
+ attrs["pi.ask_user.source"] = "unknown";
288
+ day.ask.calls += 1;
289
+ if (cancelled) day.ask.cancelled += 1;
290
+ if (isError) day.ask.errors += 1;
291
+ bump(day.ask.sources, "unknown");
292
+ if (duration !== undefined && !isError) {
293
+ day.ask.durSum += duration;
294
+ day.ask.durN += 1;
295
+ day.ask.buckets[bucketOf(duration)] += 1;
296
+ }
297
+ }
298
+
299
+ private customMessage(entry: Obj, ts: string, kind: string | undefined) {
300
+ const type = entry.customType;
301
+ if (type === "pi-herdr-agents:declared-skills") {
302
+ for (const skill of skillsFromBlocks(textOf(entry.content))) this.skillLoad(skill, "declared", ts);
303
+ } else if (kind) {
304
+ bump(this.notices as Record<string, number>, kind);
305
+ bump(this.day(ts).notices, kind);
306
+ this.emit(record({ name: NAMES.notice, kind: "event", ts, source: "backfill", trace_id: this.trace, attrs: { ...this.base(), "anchorloop.notice.kind": kind } }));
307
+ } else if (type === "pi-loop-monitor") {
308
+ const details = obj(entry.details);
309
+ if (details.deliveryGroup !== "monitor-terminal") return;
310
+ const outcome = obj(details.monitorOutcome);
311
+ const monitorId = str(outcome.monitorId) ?? str(details.monitorId);
312
+ const started = monitorId ? this.monitorStart.get(monitorId) : undefined;
313
+ const duration = started ? Date.parse(ts) - Date.parse(started) : undefined;
314
+ if (monitorId) this.monitorStart.delete(monitorId);
315
+ const status = safeName(str(outcome.status) ?? "unknown");
316
+ const day = this.day(ts);
317
+ day.monitors.finished += 1;
318
+ bump(day.monitors.statuses, status);
319
+ if (duration !== undefined) {
320
+ day.monitors.durSum += duration;
321
+ day.monitors.durN += 1;
322
+ }
323
+ this.emit(
324
+ record({
325
+ name: NAMES.monitor,
326
+ kind: "span",
327
+ ts: started ?? ts,
328
+ end_ts: ts,
329
+ duration_ms: duration,
330
+ source: "backfill",
331
+ trace_id: this.trace,
332
+ attrs: { ...this.base(), "pi.monitor.id": monitorId, "pi.monitor.status": status, "pi.monitor.exit_code": typeof outcome.exitCode === "number" ? outcome.exitCode : undefined, "pi.monitor.output_lines": num(outcome.outputLines) },
333
+ }),
334
+ );
335
+ }
336
+ }
337
+
338
+ private skillLoad(raw: string, trigger: SkillTrigger, ts: string, callId?: string) {
339
+ const skill = safeName(raw);
340
+ const day = this.day(ts);
341
+ bump(day.skills, skill);
342
+ bump(day.skillTriggers, trigger);
343
+ this.loaded.add(skill);
344
+ this.emit(
345
+ record({
346
+ name: NAMES.skill,
347
+ kind: "event",
348
+ ts,
349
+ source: "backfill",
350
+ trace_id: this.trace,
351
+ attrs: { ...this.base(), "gen_ai.skill.name": skill, "pi.skill.trigger": trigger, "gen_ai.tool.call.id": callId },
352
+ }),
353
+ );
354
+ }
355
+
356
+ /** Ends the session: closes the open trace, runs the detectors, and returns the summary and offered skills. */
357
+ finish(): { summary: SessionSummary; catalog?: string[] } {
358
+ this.closeTrace();
359
+ const startDay = this.day(this.start);
360
+ startDay.sessions += 1;
361
+ if (this.logicalId) startDay.subagentSessions += 1;
362
+ for (const skill of this.loaded) {
363
+ bump(startDay.skillSessions, skill);
364
+ bump(startDay.skillCost, skill, this.cost);
365
+ }
366
+ const inScope = (this.start || "") >= ERA_START;
367
+ const evals: SessionSummary["evals"] = {};
368
+ for (const result of this.tracker.results(inScope)) {
369
+ evals[result.name] = { label: result.label, value: result.value, explanation: result.explanation };
370
+ if (inScope) {
371
+ const t = (startDay.detectors[result.name] ??= { pass: 0, fail: 0, na: 0 });
372
+ t[result.label] += 1;
373
+ }
374
+ this.emit(
375
+ record({
376
+ name: NAMES.evaluation,
377
+ kind: "event",
378
+ ts: this.end || this.start,
379
+ source: "backfill",
380
+ attrs: {
381
+ ...this.base(),
382
+ "gen_ai.evaluation.name": result.name,
383
+ "gen_ai.evaluation.score.label": result.label,
384
+ "gen_ai.evaluation.score.value": result.value ?? (result.label === "pass" ? 1 : result.label === "fail" ? 0 : undefined),
385
+ "gen_ai.evaluation.explanation": result.explanation,
386
+ "eval.annotator_kind": "CODE",
387
+ "eval.scope": "session",
388
+ "eval.detector.version": 1,
389
+ },
390
+ }),
391
+ );
392
+ }
393
+ this.emit(
394
+ record({
395
+ name: NAMES.session,
396
+ kind: "event",
397
+ ts: this.start,
398
+ end_ts: this.end,
399
+ source: "backfill",
400
+ attrs: {
401
+ ...this.base(),
402
+ "pi.session.kind": this.logicalId ? "subagent" : "interactive",
403
+ "pi.subagent.logical_id": this.logicalId,
404
+ "pi.session.parent_id": this.parentId,
405
+ "gen_ai.request.model": this.model,
406
+ "pi.tool_calls": this.toolCalls,
407
+ "pi.usage.cost_usd": Math.round(this.cost * 1e6) / 1e6,
408
+ },
409
+ }),
410
+ );
411
+ const summary: SessionSummary = {
412
+ v: 1,
413
+ sessionId: this.sessionId,
414
+ project: this.project,
415
+ start: this.start,
416
+ end: this.end,
417
+ kind: this.logicalId ? "subagent" : "interactive",
418
+ logicalId: this.logicalId,
419
+ parentId: this.parentId,
420
+ spawned: this.spawned,
421
+ cost: this.cost,
422
+ tokens: this.tokens,
423
+ toolCalls: this.toolCalls,
424
+ evals,
425
+ notices: this.notices,
426
+ days: this.days,
427
+ };
428
+ return { summary, catalog: this.catalog };
429
+ }
430
+ }
@@ -0,0 +1,12 @@
1
+ /** Worker thread: extracts the files the main thread sends, one at a time. */
2
+ import { parentPort } from "node:worker_threads";
3
+ import { extractFile } from "./file.ts";
4
+
5
+ parentPort?.on("message", async (job: { id: number; path: string; out: string; home: string }) => {
6
+ try {
7
+ const result = await extractFile(job.path, job.out, job.home);
8
+ parentPort?.postMessage({ id: job.id, result });
9
+ } catch (error) {
10
+ parentPort?.postMessage({ id: job.id, error: error instanceof Error ? error.message : String(error) });
11
+ }
12
+ });
package/src/index.ts ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * pi-evals: the live observer, the `/evals` command (status, extract, report, mark), and the `evals_query` tool.
3
+ */
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
8
+ import { Type } from "typebox";
9
+ import { observe } from "./observer.ts";
10
+ import { context, mark, reportPath, runReport, statusText } from "./ops.ts";
11
+ import { query, type View, VIEWS } from "./query.ts";
12
+
13
+ type Env = Record<string, string | undefined>;
14
+
15
+ /** The CLI to run a back-fill in a child process: the source in a checkout, the build in an installed package. */
16
+ export function cliPath(): { cmd: string; args: string[] } | undefined {
17
+ const src = fileURLToPath(new URL("./cli.ts", import.meta.url));
18
+ const dist = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
19
+ const installed = src.includes("/node_modules/");
20
+ const candidates = installed ? [dist] : [src, dist];
21
+ const found = candidates.find((p) => existsSync(p));
22
+ return found ? { cmd: process.execPath, args: [found] } : undefined;
23
+ }
24
+
25
+ const SUBCOMMANDS = ["status", "extract", "report", "mark"];
26
+
27
+ function parseFlags(args: string[]): { since?: string; project?: string; rest: string[] } {
28
+ const out: { since?: string; project?: string; rest: string[] } = { rest: [] };
29
+ for (let i = 0; i < args.length; i++) {
30
+ if (args[i] === "--since") out.since = args[++i];
31
+ else if (args[i] === "--project") out.project = args[++i];
32
+ else out.rest.push(args[i]);
33
+ }
34
+ return out;
35
+ }
36
+
37
+ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; now?: () => number } = {}) {
38
+ const env = options.env ?? process.env;
39
+ const spawnFn = options.spawnExtract ?? spawn;
40
+ return function evals(pi: ExtensionAPI): void {
41
+ const ctx0 = context(env);
42
+ observe(pi, { layout: ctx0.layout, home: ctx0.home, now: options.now });
43
+ let settingsWarned = false;
44
+ pi.on("session_start", (_event, ctx) => {
45
+ if (settingsWarned || !ctx0.settings.error) return;
46
+ settingsWarned = true;
47
+ try {
48
+ if (ctx.hasUI) ctx.ui.notify(`pi-evals settings: ${ctx0.settings.error}`, "warning");
49
+ } catch {}
50
+ });
51
+ let running: Promise<void> | undefined;
52
+
53
+ const extractInChild = (ctx: ExtensionCommandContext, workers: number): Promise<void> => {
54
+ const cli = cliPath();
55
+ if (!cli) {
56
+ ctx.ui.notify("pi-evals: cannot find its CLI (dist/cli.js); run npm run build in the package.", "error");
57
+ return Promise.resolve();
58
+ }
59
+ return new Promise<void>((resolve) => {
60
+ const child = spawnFn(cli.cmd, [...cli.args, "extract", "--json", "--workers", String(workers)], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
61
+ let buffer = "";
62
+ let last = "";
63
+ let errText = "";
64
+ child.stdout?.on("data", (chunk: Buffer) => {
65
+ buffer += chunk.toString();
66
+ const lines = buffer.split("\n");
67
+ buffer = lines.pop() ?? "";
68
+ for (const line of lines) {
69
+ try {
70
+ const msg = JSON.parse(line) as { progress?: { done: number; total: number; bytes: number }; result?: { stats: { changed: number; files: number; records: number; mbPerSec: number; failed: number } } };
71
+ if (msg.progress) ctx.ui.setStatus("evals", `evals extract ${msg.progress.done}/${msg.progress.total} files, ${(msg.progress.bytes / 1e9).toFixed(2)} GB`);
72
+ if (msg.result) {
73
+ const s = msg.result.stats;
74
+ last = `pi-evals: extracted ${s.changed} changed of ${s.files} files, ${s.records} records, ${s.mbPerSec} MB/s${s.failed ? `, ${s.failed} failed` : ""}.`;
75
+ }
76
+ } catch {}
77
+ }
78
+ });
79
+ child.stderr?.on("data", (chunk: Buffer) => {
80
+ errText = (errText + chunk.toString()).slice(-600);
81
+ });
82
+ const finish = (code: number | null) => {
83
+ ctx.ui.setStatus("evals", undefined);
84
+ if (code === 0) ctx.ui.notify(last || "pi-evals: extract finished.", "info");
85
+ else ctx.ui.notify(`pi-evals: extract failed (exit ${code}): ${errText.trim()}`, "error");
86
+ resolve();
87
+ };
88
+ child.on("error", (error) => {
89
+ errText = error.message;
90
+ finish(-1);
91
+ });
92
+ child.on("close", finish);
93
+ });
94
+ };
95
+
96
+ pi.registerCommand("evals", {
97
+ description: "Usage and process records: /evals [status|extract|report|mark <note>]",
98
+ getArgumentCompletions: (prefix: string) => {
99
+ const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
100
+ return items.length ? items : null;
101
+ },
102
+ handler: async (args, ctx) => {
103
+ const words = args.trim().split(/\s+/).filter(Boolean);
104
+ const sub = words[0] ?? "status";
105
+ if (sub === "status") {
106
+ ctx.ui.notify(statusText(env), "info");
107
+ } else if (sub === "extract") {
108
+ if (running) {
109
+ ctx.ui.notify("pi-evals: an extract is already running.", "warning");
110
+ return;
111
+ }
112
+ const workers = words.length === 1 ? 2 : words.length === 3 && words[1] === "--workers" && /^\d+$/.test(words[2]) ? Number(words[2]) : NaN;
113
+ if (!Number.isSafeInteger(workers)) {
114
+ ctx.ui.notify("Usage: /evals extract [--workers <non-negative integer>]", "warning");
115
+ return;
116
+ }
117
+ ctx.ui.notify("pi-evals: extract started in the background; progress shows in the footer.", "info");
118
+ running = extractInChild(ctx, workers).finally(() => {
119
+ running = undefined;
120
+ });
121
+ } else if (sub === "report") {
122
+ const flags = parseFlags(words.slice(1));
123
+ const out = runReport({ env, filter: { since: flags.since, project: flags.project } });
124
+ ctx.ui.notify(out ? `pi-evals report: ${out.html}\nmodel: ${out.json}` : "pi-evals: nothing extracted yet; run /evals extract first.", out ? "info" : "warning");
125
+ } else if (sub === "mark") {
126
+ const text = words.slice(1).join(" ").trim();
127
+ if (!text) {
128
+ ctx.ui.notify("Usage: /evals mark <what you changed>", "warning");
129
+ return;
130
+ }
131
+ const change = mark(text, env);
132
+ ctx.ui.notify(`pi-evals: marked ${change.at}: ${text}`, "info");
133
+ } else {
134
+ ctx.ui.notify(`Unknown subcommand "${sub}". Use: ${SUBCOMMANDS.join(", ")}.`, "warning");
135
+ }
136
+ },
137
+ });
138
+
139
+ pi.registerTool({
140
+ name: "evals_query",
141
+ label: "Evals Query",
142
+ description: "Summaries of how skills, packages, ask-user, monitors and subagents were used, process-rule adherence, cost, the user's architecture changes with before/after numbers, and index coverage. Numbers and names only.",
143
+ promptSnippet: "Read pi usage and process summaries (skills, packages, process, cost, changes)",
144
+ parameters: Type.Object({
145
+ view: Type.Unsafe<View>({ type: "string", enum: [...VIEWS], description: "Which summary" }),
146
+ since: Type.Optional(Type.String({ description: "YYYY-MM-DD; default all data" })),
147
+ project: Type.Optional(Type.String({ description: "Project key, e.g. a repo name" })),
148
+ }),
149
+ async execute(_id, params) {
150
+ const view = params.view as View;
151
+ if (!VIEWS.includes(view)) throw new Error(`Unknown view "${view}". Views: ${VIEWS.join(", ")}.`);
152
+ if (params.since && !/^\d{4}-\d{2}-\d{2}$/.test(params.since)) throw new Error("since must be YYYY-MM-DD.");
153
+ const text = query(view, { since: params.since, project: params.project, env });
154
+ return { content: [{ type: "text", text }], details: { view, report: reportPath(env) } };
155
+ },
156
+ });
157
+ };
158
+ }
159
+
160
+ export default createEvals();