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.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +116 -2
- package/dist/aggregate.js +113 -0
- package/dist/build.js +260 -0
- package/dist/changes.js +170 -0
- package/dist/cli.js +86 -0
- package/dist/coverage.js +34 -0
- package/dist/detectors.js +154 -0
- package/dist/extract/file.js +42 -0
- package/dist/extract/run.js +149 -0
- package/dist/extract/session.js +430 -0
- package/dist/extract/worker.js +12 -0
- package/dist/index.js +165 -0
- package/dist/meta.js +233 -0
- package/dist/model.js +317 -0
- package/dist/observer.js +240 -0
- package/dist/ops.js +93 -0
- package/dist/owners.js +97 -0
- package/dist/paths.js +76 -0
- package/dist/project.js +43 -0
- package/dist/query.js +92 -0
- package/dist/render.js +31 -0
- package/dist/report/concepts.js +37 -0
- package/dist/report/findings.js +73 -0
- package/dist/report/format.js +16 -0
- package/dist/report/sections.js +61 -0
- package/dist/report/style.js +77 -0
- package/dist/report/timeline.js +91 -0
- package/dist/report/week.js +36 -0
- package/dist/schema.js +65 -0
- package/dist/skills.js +41 -0
- package/dist/store.js +51 -0
- package/docs/design.md +106 -0
- package/docs/learn.zh-TW.md +33 -0
- package/docs/schema.md +68 -0
- package/package.json +56 -4
- package/src/aggregate.ts +204 -0
- package/src/build.ts +257 -0
- package/src/changes.ts +178 -0
- package/src/cli.ts +89 -0
- package/src/coverage.ts +44 -0
- package/src/detectors.ts +182 -0
- package/src/extract/file.ts +46 -0
- package/src/extract/run.ts +198 -0
- package/src/extract/session.ts +430 -0
- package/src/extract/worker.ts +12 -0
- package/src/index.ts +160 -0
- package/src/meta.ts +259 -0
- package/src/model.ts +346 -0
- package/src/observer.ts +255 -0
- package/src/ops.ts +110 -0
- package/src/owners.ts +92 -0
- package/src/paths.ts +108 -0
- package/src/project.ts +43 -0
- package/src/query.ts +85 -0
- package/src/render.ts +63 -0
- package/src/report/concepts.ts +94 -0
- package/src/report/findings.ts +84 -0
- package/src/report/format.ts +24 -0
- package/src/report/sections.ts +188 -0
- package/src/report/style.ts +77 -0
- package/src/report/timeline.ts +143 -0
- package/src/report/week.ts +55 -0
- package/src/schema.ts +84 -0
- package/src/skills.ts +46 -0
- package/src/store.ts +49 -0
package/dist/observer.js
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { ownerOf } from "./owners.js";
|
|
2
|
+
import { projectKey } from "./project.js";
|
|
3
|
+
import { NAMES, record, spanId, traceId } from "./schema.js";
|
|
4
|
+
import { skillFromPath, skillsFromBlocks, skillsFromCommand } from "./skills.js";
|
|
5
|
+
import { liveWriter } from "./store.js";
|
|
6
|
+
import { logicalIdOf } from "./extract/session.js";
|
|
7
|
+
const obj = (v) => (v && typeof v === "object" ? v : {});
|
|
8
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
9
|
+
const ASK_TOOLS = new Set(["ask_user_question", "ask_user"]);
|
|
10
|
+
export function observe(pi, options) {
|
|
11
|
+
const now = options.now ?? Date.now;
|
|
12
|
+
let sessionId = "";
|
|
13
|
+
let project = "unknown";
|
|
14
|
+
let trace;
|
|
15
|
+
let snapshotTaken = false;
|
|
16
|
+
let owners = new Map();
|
|
17
|
+
let pending = new Map();
|
|
18
|
+
let remoteAnswers = new Set();
|
|
19
|
+
let monitorStarts = new Map();
|
|
20
|
+
let monitorsDone = new Set();
|
|
21
|
+
let unsubscribe = [];
|
|
22
|
+
let write = () => { };
|
|
23
|
+
let hasUI = false;
|
|
24
|
+
const iso = (t) => new Date(t).toISOString();
|
|
25
|
+
const base = () => ({ "session.id": sessionId, "pi.project": project });
|
|
26
|
+
const emit = (fields) => write(record(fields));
|
|
27
|
+
const skillLoad = (skill, trigger, callId) => emit({ name: NAMES.skill, kind: "event", ts: iso(now()), source: "live", trace_id: trace, attrs: { ...base(), "gen_ai.skill.name": skill, "pi.skill.trigger": trigger, "gen_ai.tool.call.id": callId } });
|
|
28
|
+
const snapshot = () => {
|
|
29
|
+
if (snapshotTaken)
|
|
30
|
+
return;
|
|
31
|
+
snapshotTaken = true;
|
|
32
|
+
try {
|
|
33
|
+
owners = new Map(pi.getAllTools().map((tool) => [tool.name, ownerOf(tool)]));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
owners = new Map();
|
|
37
|
+
}
|
|
38
|
+
const tools = [...owners].map(([name, o]) => `${name}=${o.owner}${o.version ? `@${o.version}` : ""}`).sort();
|
|
39
|
+
emit({ name: NAMES.tools, kind: "event", ts: iso(now()), source: "live", attrs: { ...base(), "pi.tools": tools } });
|
|
40
|
+
};
|
|
41
|
+
const ownerFor = (tool) => {
|
|
42
|
+
if (!owners.has(tool)) {
|
|
43
|
+
try {
|
|
44
|
+
const found = pi.getAllTools().find((t) => t.name === tool);
|
|
45
|
+
if (found)
|
|
46
|
+
owners.set(tool, ownerOf(found));
|
|
47
|
+
}
|
|
48
|
+
catch { }
|
|
49
|
+
}
|
|
50
|
+
return owners.get(tool);
|
|
51
|
+
};
|
|
52
|
+
const monitorEnd = (data, fallback) => {
|
|
53
|
+
const d = obj(data);
|
|
54
|
+
const id = str(d.monitorId) ?? (typeof d.monitorId === "number" ? String(d.monitorId) : undefined);
|
|
55
|
+
if (!id || monitorsDone.has(id))
|
|
56
|
+
return;
|
|
57
|
+
monitorsDone.add(id);
|
|
58
|
+
const started = monitorStarts.get(id);
|
|
59
|
+
const end = now();
|
|
60
|
+
const reported = obj(d.reportedOutcome);
|
|
61
|
+
emit({
|
|
62
|
+
name: NAMES.monitor,
|
|
63
|
+
kind: "span",
|
|
64
|
+
ts: iso(started ?? end),
|
|
65
|
+
end_ts: iso(end),
|
|
66
|
+
duration_ms: started !== undefined ? end - started : undefined,
|
|
67
|
+
source: "live",
|
|
68
|
+
trace_id: trace,
|
|
69
|
+
attrs: {
|
|
70
|
+
...base(),
|
|
71
|
+
"pi.monitor.id": id,
|
|
72
|
+
"pi.monitor.status": str(d.status) ?? fallback,
|
|
73
|
+
"pi.monitor.exit_code": typeof d.exitCode === "number" ? d.exitCode : undefined,
|
|
74
|
+
"pi.monitor.output_lines": typeof d.outputLines === "number" ? d.outputLines : undefined,
|
|
75
|
+
"pi.monitor.reported_status": str(reported.status),
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
pi.on("session_start", (_event, ctx) => {
|
|
80
|
+
for (const off of unsubscribe)
|
|
81
|
+
off();
|
|
82
|
+
sessionId = ctx.sessionManager.getSessionId();
|
|
83
|
+
project = projectKey(ctx.cwd, options.home);
|
|
84
|
+
hasUI = ctx.hasUI;
|
|
85
|
+
trace = undefined;
|
|
86
|
+
snapshotTaken = false;
|
|
87
|
+
owners = new Map();
|
|
88
|
+
pending = new Map();
|
|
89
|
+
remoteAnswers = new Set();
|
|
90
|
+
monitorStarts = new Map();
|
|
91
|
+
monitorsDone = new Set();
|
|
92
|
+
let file;
|
|
93
|
+
try {
|
|
94
|
+
file = ctx.sessionManager.getSessionFile?.();
|
|
95
|
+
}
|
|
96
|
+
catch { }
|
|
97
|
+
const logicalId = file ? logicalIdOf(file) : undefined;
|
|
98
|
+
write = liveWriter(options.layout.events, (message) => {
|
|
99
|
+
try {
|
|
100
|
+
if (ctx.hasUI)
|
|
101
|
+
ctx.ui.notify(message, "warning");
|
|
102
|
+
else
|
|
103
|
+
console.error(message);
|
|
104
|
+
}
|
|
105
|
+
catch { }
|
|
106
|
+
}, now);
|
|
107
|
+
emit({
|
|
108
|
+
name: NAMES.session,
|
|
109
|
+
kind: "event",
|
|
110
|
+
ts: iso(now()),
|
|
111
|
+
source: "live",
|
|
112
|
+
// The session file name marks a subagent; PI_SUBAGENT_ID is inherited by anything a subagent starts, so it is not used.
|
|
113
|
+
attrs: { ...base(), "pi.session.kind": logicalId ? "subagent" : "interactive", "pi.subagent.logical_id": logicalId },
|
|
114
|
+
});
|
|
115
|
+
const on = (channel, handler) => {
|
|
116
|
+
try {
|
|
117
|
+
unsubscribe.push(pi.events.on(channel, handler));
|
|
118
|
+
}
|
|
119
|
+
catch { }
|
|
120
|
+
};
|
|
121
|
+
on("monitor:started", (data) => {
|
|
122
|
+
const d = obj(data);
|
|
123
|
+
const id = str(d.monitorId) ?? (typeof d.monitorId === "number" ? String(d.monitorId) : undefined);
|
|
124
|
+
if (id) {
|
|
125
|
+
monitorStarts.set(id, typeof d.timestamp === "number" ? d.timestamp : now());
|
|
126
|
+
monitorsDone.delete(id);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
on("monitor:finished", (data) => monitorEnd(data, "finished"));
|
|
130
|
+
on("monitor:done", (data) => monitorEnd(data, "completed"));
|
|
131
|
+
on("monitor:error", (data) => monitorEnd(data, "error"));
|
|
132
|
+
// A remote answer (e.g. from a phone) is reported by the answer channel's result; a rejected one is not the answer.
|
|
133
|
+
on("rpiv:ask-user:answer-result", (data) => {
|
|
134
|
+
const d = obj(data);
|
|
135
|
+
const id = str(d.toolCallId);
|
|
136
|
+
if (id && d.ok === true)
|
|
137
|
+
remoteAnswers.add(id);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
pi.on("session_shutdown", () => {
|
|
141
|
+
for (const off of unsubscribe)
|
|
142
|
+
off();
|
|
143
|
+
unsubscribe = [];
|
|
144
|
+
});
|
|
145
|
+
pi.on("before_agent_start", (event) => {
|
|
146
|
+
snapshot();
|
|
147
|
+
const skills = obj(event).systemPromptOptions ? obj(obj(event).systemPromptOptions).skills : undefined;
|
|
148
|
+
if (Array.isArray(skills) && trace === undefined) {
|
|
149
|
+
const names = skills.map((s) => str(obj(s).name)).filter((n) => !!n);
|
|
150
|
+
emit({ name: NAMES.skills, kind: "event", ts: iso(now()), source: "live", attrs: { ...base(), "pi.skills": names } });
|
|
151
|
+
}
|
|
152
|
+
const at = now();
|
|
153
|
+
trace = traceId(sessionId, `live:${at}`);
|
|
154
|
+
emit({
|
|
155
|
+
name: NAMES.prompt,
|
|
156
|
+
kind: "span",
|
|
157
|
+
ts: iso(at),
|
|
158
|
+
source: "live",
|
|
159
|
+
trace_id: trace,
|
|
160
|
+
span_id: spanId(sessionId, `live:${at}`),
|
|
161
|
+
attrs: { ...base(), "gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": "pi", "pi.prompt.origin": obj(event).messageType === "custom" ? "extension" : "user" },
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
pi.on("input", (event) => {
|
|
165
|
+
const text = str(obj(event).text);
|
|
166
|
+
if (text?.startsWith("/skill:")) {
|
|
167
|
+
const name = text.slice(7).split(/\s/)[0];
|
|
168
|
+
if (name)
|
|
169
|
+
skillLoad(name, "slash");
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
pi.on("message_end", (event) => {
|
|
173
|
+
const message = obj(obj(event).message);
|
|
174
|
+
if (message.customType === "pi-herdr-agents:declared-skills") {
|
|
175
|
+
const content = message.content;
|
|
176
|
+
const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => str(obj(p).text) ?? "").join("\n") : "";
|
|
177
|
+
for (const skill of skillsFromBlocks(text))
|
|
178
|
+
skillLoad(skill, "declared");
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
pi.on("tool_execution_start", (event) => {
|
|
182
|
+
const args = obj(event.args);
|
|
183
|
+
const entry = { start: now() };
|
|
184
|
+
if (event.toolName === "read")
|
|
185
|
+
entry.skill = skillFromPath(args.path ?? args.file_path);
|
|
186
|
+
else if (event.toolName === "bash")
|
|
187
|
+
for (const skill of skillsFromCommand(args.command))
|
|
188
|
+
skillLoad(skill, "bash", event.toolCallId);
|
|
189
|
+
else if (ASK_TOOLS.has(event.toolName))
|
|
190
|
+
entry.questions = Array.isArray(args.questions) ? args.questions.length : 1;
|
|
191
|
+
pending.set(event.toolCallId, entry);
|
|
192
|
+
});
|
|
193
|
+
pi.on("tool_execution_end", (event) => {
|
|
194
|
+
const started = pending.get(event.toolCallId);
|
|
195
|
+
pending.delete(event.toolCallId);
|
|
196
|
+
const end = now();
|
|
197
|
+
const owner = ownerFor(event.toolName);
|
|
198
|
+
const details = obj(obj(event.result).details);
|
|
199
|
+
const attrs = {
|
|
200
|
+
...base(),
|
|
201
|
+
"gen_ai.operation.name": "execute_tool",
|
|
202
|
+
"gen_ai.tool.name": event.toolName,
|
|
203
|
+
"gen_ai.tool.call.id": event.toolCallId,
|
|
204
|
+
"error.type": event.isError ? "tool_error" : undefined,
|
|
205
|
+
"pi.tool.owner": owner?.owner,
|
|
206
|
+
"pi.tool.owner_version": owner?.version,
|
|
207
|
+
"pi.tool.parent_call": typeof obj(event).parentToolCallId === "string" ? true : undefined,
|
|
208
|
+
"pi.duration.source": typeof event.durationMs === "number" ? "measured" : "not_run",
|
|
209
|
+
};
|
|
210
|
+
if (started?.skill && !event.isError) {
|
|
211
|
+
attrs["gen_ai.skill.name"] = started.skill.skill;
|
|
212
|
+
if (started.skill.resource)
|
|
213
|
+
attrs["gen_ai.skill.resource.name"] = started.skill.resource;
|
|
214
|
+
else
|
|
215
|
+
skillLoad(started.skill.skill, "read", event.toolCallId);
|
|
216
|
+
}
|
|
217
|
+
if (ASK_TOOLS.has(event.toolName)) {
|
|
218
|
+
attrs["pi.ask_user.questions"] = Array.isArray(details.questions) ? details.questions.length : (started?.questions ?? 1);
|
|
219
|
+
attrs["pi.ask_user.cancelled"] = details.cancelled === true;
|
|
220
|
+
attrs["pi.ask_user.source"] = remoteAnswers.has(event.toolCallId) ? "remote" : hasUI ? "terminal" : "none";
|
|
221
|
+
remoteAnswers.delete(event.toolCallId);
|
|
222
|
+
}
|
|
223
|
+
if (event.toolName === "subagent" && !event.isError) {
|
|
224
|
+
attrs["gen_ai.agent.name"] = str(details.agent) ?? "default";
|
|
225
|
+
attrs["gen_ai.request.model"] = str(details.model) ?? "default";
|
|
226
|
+
attrs["pi.subagent.logical_id"] = str(details.id);
|
|
227
|
+
}
|
|
228
|
+
emit({
|
|
229
|
+
name: NAMES.tool,
|
|
230
|
+
kind: "span",
|
|
231
|
+
ts: iso(started?.start ?? end),
|
|
232
|
+
end_ts: iso(end),
|
|
233
|
+
duration_ms: typeof event.durationMs === "number" ? event.durationMs : undefined,
|
|
234
|
+
source: "live",
|
|
235
|
+
trace_id: trace,
|
|
236
|
+
span_id: spanId(sessionId, event.toolCallId),
|
|
237
|
+
attrs,
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
package/dist/ops.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** The operations behind `/evals`, `evals_query`, and the CLI. */
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { buildIndex, loadIndex, loadRows } from "./build.js";
|
|
5
|
+
import { addMark, readChanges } from "./changes.js";
|
|
6
|
+
import { coverage } from "./coverage.js";
|
|
7
|
+
import { extract, loadCheckpoint } from "./extract/run.js";
|
|
8
|
+
import { buildModel } from "./model.js";
|
|
9
|
+
import { agentDir, home, layout, loadSettings, stateDir } from "./paths.js";
|
|
10
|
+
import { renderHtml } from "./render.js";
|
|
11
|
+
export function context(env = process.env) {
|
|
12
|
+
const settings = loadSettings(env);
|
|
13
|
+
const lay = layout(stateDir(env));
|
|
14
|
+
const agent = agentDir(env);
|
|
15
|
+
const roots = [join(agent, "sessions"), ...settings.extraRoots.map((r) => resolve(r))];
|
|
16
|
+
return { settings, layout: lay, agentDir: agent, roots, home: home(env) };
|
|
17
|
+
}
|
|
18
|
+
export async function runExtract(options = {}) {
|
|
19
|
+
const ctx = context(options.env);
|
|
20
|
+
const roots = [...ctx.roots, ...(options.extraRoots ?? []).map((r) => resolve(r))];
|
|
21
|
+
const { stats, checkpoint } = await extract({ roots, layout: ctx.layout, home: ctx.home, workers: options.workers, onProgress: options.onProgress, signal: options.signal });
|
|
22
|
+
const { index, changes, errors } = buildIndex({ layout: ctx.layout, settings: ctx.settings, checkpoint, agentDir: ctx.agentDir });
|
|
23
|
+
const status = {
|
|
24
|
+
lastExtract: checkpoint.lastExtract ?? new Date().toISOString(),
|
|
25
|
+
stats: { ...stats, mbPerSec: stats.ms ? Math.round((stats.bytes / 1e6 / (stats.ms / 1000)) * 10) / 10 : 0 },
|
|
26
|
+
sessions: index.sessions,
|
|
27
|
+
changes: changes.length,
|
|
28
|
+
};
|
|
29
|
+
mkdirSync(join(ctx.layout.state, "index"), { recursive: true });
|
|
30
|
+
writeFileSync(ctx.layout.status, JSON.stringify({ ...status, errors: [...stats.errors, ...errors] }, null, 2));
|
|
31
|
+
return status;
|
|
32
|
+
}
|
|
33
|
+
export function readStatus(env) {
|
|
34
|
+
const ctx = context(env);
|
|
35
|
+
return existsSync(ctx.layout.status) ? JSON.parse(readFileSync(ctx.layout.status, "utf8")) : undefined;
|
|
36
|
+
}
|
|
37
|
+
export function coverageNow(env, cutDays) {
|
|
38
|
+
const ctx = context(env);
|
|
39
|
+
return coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), cutDays ?? ctx.settings.coverageDays);
|
|
40
|
+
}
|
|
41
|
+
export function model(filter, env, withCoverage = true) {
|
|
42
|
+
const ctx = context(env);
|
|
43
|
+
const index = loadIndex(ctx.layout);
|
|
44
|
+
if (!index)
|
|
45
|
+
return undefined;
|
|
46
|
+
return buildModel({
|
|
47
|
+
index,
|
|
48
|
+
rows: loadRows(ctx.layout),
|
|
49
|
+
changes: readChanges(ctx.layout.changes),
|
|
50
|
+
filter,
|
|
51
|
+
windowDays: ctx.settings.impactWindowDays,
|
|
52
|
+
labelsFile: ctx.layout.labels,
|
|
53
|
+
sessionEvalsFile: ctx.layout.sessionEvals,
|
|
54
|
+
coverage: withCoverage ? coverageNow(env) : undefined,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/** Builds the report; returns the HTML path, or undefined when nothing was extracted yet. */
|
|
58
|
+
export function runReport(options = {}) {
|
|
59
|
+
const ctx = context(options.env);
|
|
60
|
+
const m = model(options.filter ?? {}, options.env);
|
|
61
|
+
if (!m)
|
|
62
|
+
return undefined;
|
|
63
|
+
const dir = resolve(options.outDir ?? ctx.layout.reports);
|
|
64
|
+
mkdirSync(dir, { recursive: true });
|
|
65
|
+
const html = join(dir, "report.html");
|
|
66
|
+
const json = join(dir, "model.json");
|
|
67
|
+
writeFileSync(json, JSON.stringify(m, null, 1));
|
|
68
|
+
writeFileSync(html, renderHtml(m, options.lang ?? "zh"));
|
|
69
|
+
return { html, json };
|
|
70
|
+
}
|
|
71
|
+
export function reportPath(env) {
|
|
72
|
+
return join(context(env).layout.reports, "report.html");
|
|
73
|
+
}
|
|
74
|
+
export function mark(text, env) {
|
|
75
|
+
return addMark(context(env).layout.marks, text);
|
|
76
|
+
}
|
|
77
|
+
const gb = (b) => `${(b / 1e9).toFixed(2)} GB`;
|
|
78
|
+
export function statusText(env) {
|
|
79
|
+
const ctx = context(env);
|
|
80
|
+
const status = readStatus(env);
|
|
81
|
+
const cov = coverageNow(env);
|
|
82
|
+
const lines = [
|
|
83
|
+
status
|
|
84
|
+
? `last extract ${status.lastExtract}: ${status.stats.changed} of ${status.stats.files} files read (${gb(status.stats.bytes)}, ${status.stats.mbPerSec} MB/s), ${status.stats.records} records, ${status.stats.failed} failed`
|
|
85
|
+
: "no extract yet: run /evals extract",
|
|
86
|
+
status ? `sessions indexed ${status.sessions.backfill} (subagent ${status.sessions.subagent}, linked to parent ${status.sessions.linked}), live-only ${status.sessions.live}, both ${status.sessions.both}; changes ${status.changes}` : "",
|
|
87
|
+
`coverage (inactive > ${cov.cutDays} days): ${cov.indexed.files}/${cov.old.files} indexed (${gb(cov.indexed.bytes)} of ${gb(cov.old.bytes)}); not indexed ${cov.notIndexed.files} (${gb(cov.notIndexed.bytes)}); all files ${cov.all.indexedFiles}/${cov.all.files} indexed`,
|
|
88
|
+
`report: ${existsSync(reportPath(env)) ? reportPath(env) : "not built (run /evals report)"}`,
|
|
89
|
+
`state: ${ctx.layout.state}`,
|
|
90
|
+
ctx.settings.error ? `settings: ${ctx.settings.error}` : "",
|
|
91
|
+
];
|
|
92
|
+
return lines.filter(Boolean).join("\n");
|
|
93
|
+
}
|
package/dist/owners.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which package owns a tool. Live sessions record it from `pi.getAllTools()` sourceInfo (canonical);
|
|
3
|
+
* past sessions fall back to the newest live snapshot, then to this static table (scratch/evals/instrumentation.md §2).
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
export const BUILTIN_TOOLS = new Set(["bash", "read", "edit", "write", "grep", "find", "ls"]);
|
|
8
|
+
const STATIC = {
|
|
9
|
+
ask_user_question: "@juicesharp/rpiv-ask-user-question",
|
|
10
|
+
ask_user: "pi-ask-user",
|
|
11
|
+
todo: "pi-todo-ledger",
|
|
12
|
+
show_doc: "pi-better-show",
|
|
13
|
+
intercom: "pi-intercom",
|
|
14
|
+
contact_supervisor: "pi-intercom",
|
|
15
|
+
robot_hand: "pi-robot-hand",
|
|
16
|
+
secret_drop: "pi-robot-hand",
|
|
17
|
+
prose_watch: "pi-prose-watch",
|
|
18
|
+
mcp: "pi-mcp-adapter",
|
|
19
|
+
web_search: "pi-web-access",
|
|
20
|
+
fetch_content: "pi-web-access",
|
|
21
|
+
get_search_content: "pi-web-access",
|
|
22
|
+
source_check: "pi-web-access",
|
|
23
|
+
web_enable: "pi-web-access",
|
|
24
|
+
call_tower: "pi-straw-boss",
|
|
25
|
+
train_car: "pi-straw-boss",
|
|
26
|
+
ally_escalate: "pi-straw-boss",
|
|
27
|
+
evals_query: "pi-evals",
|
|
28
|
+
};
|
|
29
|
+
const PREFIX = [
|
|
30
|
+
[/^(Monitor|Loop)(Create|List|Update|Stop|Delete)$/, "pi-loop-monitor"],
|
|
31
|
+
[/^(subagent|subagents_list|worktree_list|worktree_remove|caller_ping|caller_notify|subagent_done)/, "pi-herdr-agents"],
|
|
32
|
+
[/^(boss|tower|thread|board)_/, "pi-straw-boss"],
|
|
33
|
+
[/^memory_/, "@pify/memory"],
|
|
34
|
+
[/^codex_/, "pi-codex-image-gen"],
|
|
35
|
+
[/^goal_/, "@narumitw/pi-goal"],
|
|
36
|
+
// Retired or renamed packages that appear in older sessions.
|
|
37
|
+
[/^anchorloop_/, "pi-anchorloop"],
|
|
38
|
+
[/^aaaav_/, "pi-aaaav"],
|
|
39
|
+
[/^lens_/, "pi-lens"],
|
|
40
|
+
[/^(google_search|read_url_content)$/, "pi-antigravity"],
|
|
41
|
+
];
|
|
42
|
+
/** The owner of a tool by name, when no live snapshot knows it. */
|
|
43
|
+
export function staticOwner(tool) {
|
|
44
|
+
if (BUILTIN_TOOLS.has(tool))
|
|
45
|
+
return "pi:builtin";
|
|
46
|
+
if (STATIC[tool])
|
|
47
|
+
return STATIC[tool];
|
|
48
|
+
for (const [pattern, owner] of PREFIX)
|
|
49
|
+
if (pattern.test(tool))
|
|
50
|
+
return owner;
|
|
51
|
+
return "unknown";
|
|
52
|
+
}
|
|
53
|
+
const packageCache = new Map();
|
|
54
|
+
/** The nearest package.json above a source path: its name and version. */
|
|
55
|
+
export function packageOf(path) {
|
|
56
|
+
if (!path || path.startsWith("builtin:") || path.startsWith("<"))
|
|
57
|
+
return undefined;
|
|
58
|
+
let dir = dirname(path);
|
|
59
|
+
const seen = [];
|
|
60
|
+
for (let i = 0; i < 12 && dir && dir !== dirname(dir); i++, dir = dirname(dir)) {
|
|
61
|
+
if (packageCache.has(dir)) {
|
|
62
|
+
const hit = packageCache.get(dir);
|
|
63
|
+
for (const d of seen)
|
|
64
|
+
packageCache.set(d, hit);
|
|
65
|
+
return hit;
|
|
66
|
+
}
|
|
67
|
+
seen.push(dir);
|
|
68
|
+
const file = join(dir, "package.json");
|
|
69
|
+
if (existsSync(file)) {
|
|
70
|
+
try {
|
|
71
|
+
const pkg = JSON.parse(readFileSync(file, "utf8"));
|
|
72
|
+
if (pkg.name) {
|
|
73
|
+
const hit = { name: pkg.name, version: pkg.version };
|
|
74
|
+
for (const d of seen)
|
|
75
|
+
packageCache.set(d, hit);
|
|
76
|
+
return hit;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch { }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for (const d of seen)
|
|
83
|
+
packageCache.set(d, undefined);
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
/** `name=owner@version` for one tool from its sourceInfo. */
|
|
87
|
+
export function ownerOf(tool) {
|
|
88
|
+
const info = tool.sourceInfo;
|
|
89
|
+
if (!info || info.source === "builtin")
|
|
90
|
+
return { owner: info?.path?.startsWith("builtin:") && !BUILTIN_TOOLS.has(tool.name) ? info.path : "pi:builtin" };
|
|
91
|
+
if (info.source === "sdk")
|
|
92
|
+
return { owner: "sdk" };
|
|
93
|
+
const pkg = packageOf(info.path);
|
|
94
|
+
if (pkg)
|
|
95
|
+
return { owner: pkg.name, version: pkg.version };
|
|
96
|
+
return { owner: info.source && info.source !== "local" ? info.source : "local-extension" };
|
|
97
|
+
}
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Where pi-evals reads and writes: pi's agent dir, its own state dir, and its settings. */
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
export const home = (env = process.env) => env.HOME || homedir();
|
|
6
|
+
export function agentDir(env = process.env) {
|
|
7
|
+
return env.PI_CODING_AGENT_DIR ? resolve(env.PI_CODING_AGENT_DIR) : join(home(env), ".pi", "agent");
|
|
8
|
+
}
|
|
9
|
+
export function stateDir(env = process.env) {
|
|
10
|
+
if (env.PI_EVALS_STATE_DIR)
|
|
11
|
+
return resolve(env.PI_EVALS_STATE_DIR);
|
|
12
|
+
const base = env.XDG_STATE_HOME ? resolve(env.XDG_STATE_HOME) : join(home(env), ".local", "state");
|
|
13
|
+
return join(base, "pi-evals");
|
|
14
|
+
}
|
|
15
|
+
export function settingsFile(env = process.env) {
|
|
16
|
+
const base = env.XDG_CONFIG_HOME ? resolve(env.XDG_CONFIG_HOME) : join(home(env), ".config");
|
|
17
|
+
return join(base, "pi-evals", "settings.json");
|
|
18
|
+
}
|
|
19
|
+
export function defaultSettings(env = process.env) {
|
|
20
|
+
const projects = join(home(env), "projects");
|
|
21
|
+
return {
|
|
22
|
+
extraRoots: [],
|
|
23
|
+
changeRepos: [join(projects, "weihung-basic-agent"), join(projects, "weihung-agent-root")],
|
|
24
|
+
coverageDays: 60,
|
|
25
|
+
impactWindowDays: 7,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
const expand = (path, env) => (path === "~" || path.startsWith("~/") ? join(home(env), path.slice(1)) : resolve(path));
|
|
29
|
+
/**
|
|
30
|
+
* Settings file merged over the defaults; `PI_EVALS_ROOTS` (path-list) adds roots. A file that cannot be read or parsed
|
|
31
|
+
* yields the defaults and an `error` the caller shows, so a typo never stops the observer from loading.
|
|
32
|
+
*/
|
|
33
|
+
export function loadSettings(env = process.env) {
|
|
34
|
+
const settings = defaultSettings(env);
|
|
35
|
+
const file = settingsFile(env);
|
|
36
|
+
let raw;
|
|
37
|
+
if (existsSync(file)) {
|
|
38
|
+
try {
|
|
39
|
+
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
settings.error = `${file}: ${error instanceof Error ? error.message : String(error)}; using defaults`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (raw) {
|
|
46
|
+
if (Array.isArray(raw.extraRoots))
|
|
47
|
+
settings.extraRoots = raw.extraRoots.map((p) => expand(String(p), env));
|
|
48
|
+
if (Array.isArray(raw.changeRepos))
|
|
49
|
+
settings.changeRepos = raw.changeRepos.map((p) => expand(String(p), env));
|
|
50
|
+
if (typeof raw.coverageDays === "number" && raw.coverageDays > 0)
|
|
51
|
+
settings.coverageDays = raw.coverageDays;
|
|
52
|
+
if (typeof raw.impactWindowDays === "number" && raw.impactWindowDays > 0)
|
|
53
|
+
settings.impactWindowDays = raw.impactWindowDays;
|
|
54
|
+
}
|
|
55
|
+
if (env.PI_EVALS_ROOTS)
|
|
56
|
+
settings.extraRoots.push(...env.PI_EVALS_ROOTS.split(":").filter(Boolean).map((p) => expand(p, env)));
|
|
57
|
+
return settings;
|
|
58
|
+
}
|
|
59
|
+
export function layout(state = stateDir()) {
|
|
60
|
+
return {
|
|
61
|
+
state,
|
|
62
|
+
events: join(state, "events"),
|
|
63
|
+
records: join(state, "index", "records"),
|
|
64
|
+
checkpoint: join(state, "index", "checkpoint.json"),
|
|
65
|
+
days: join(state, "index", "days.json"),
|
|
66
|
+
sessionRows: join(state, "index", "sessions.json"),
|
|
67
|
+
sessionEvals: join(state, "index", "session-evals.json"),
|
|
68
|
+
changes: join(state, "changes.jsonl"),
|
|
69
|
+
marks: join(state, "marks.jsonl"),
|
|
70
|
+
labels: join(state, "labels.jsonl"),
|
|
71
|
+
status: join(state, "index", "status.json"),
|
|
72
|
+
reports: join(state, "reports"),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** UTC day of an epoch-ms or ISO time. */
|
|
76
|
+
export const dayOf = (t) => new Date(t).toISOString().slice(0, 10);
|
package/dist/project.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** A short project key for a working directory: the repository name, never the full path. */
|
|
2
|
+
import { readdirSync } from "node:fs";
|
|
3
|
+
import { join, sep } from "node:path";
|
|
4
|
+
let known;
|
|
5
|
+
/** Repository names under ~/projects, longest first, so a worktree name maps to the longest matching repo. */
|
|
6
|
+
function knownProjects(home) {
|
|
7
|
+
if (!known) {
|
|
8
|
+
try {
|
|
9
|
+
known = readdirSync(join(home, "projects"), { withFileTypes: true })
|
|
10
|
+
.filter((d) => d.isDirectory() && !d.name.startsWith("."))
|
|
11
|
+
.map((d) => d.name)
|
|
12
|
+
.sort((a, b) => b.length - a.length);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
known = [];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return known;
|
|
19
|
+
}
|
|
20
|
+
/** For tests: replace the known repository names. */
|
|
21
|
+
export function setKnownProjects(names) {
|
|
22
|
+
known = names ? [...names].sort((a, b) => b.length - a.length) : undefined;
|
|
23
|
+
}
|
|
24
|
+
export function projectKey(cwd, home) {
|
|
25
|
+
if (!cwd)
|
|
26
|
+
return "unknown";
|
|
27
|
+
const rel = cwd === home ? "" : cwd.startsWith(home + sep) ? cwd.slice(home.length + 1) : undefined;
|
|
28
|
+
if (rel === undefined) {
|
|
29
|
+
const first = cwd.split(sep).filter(Boolean)[0];
|
|
30
|
+
return first === "tmp" || first === "private" || first === "var" ? "tmp" : "other";
|
|
31
|
+
}
|
|
32
|
+
if (rel === "")
|
|
33
|
+
return "home";
|
|
34
|
+
const parts = rel.split(sep);
|
|
35
|
+
if (parts[0] === "projects" && parts[1])
|
|
36
|
+
return parts[1];
|
|
37
|
+
if (parts[0] === ".herdr-worktrees" && parts[1]) {
|
|
38
|
+
const name = parts[1];
|
|
39
|
+
const repo = knownProjects(home).find((p) => name === p || name.startsWith(`${p}-`));
|
|
40
|
+
return repo ?? name.split("-")[0] ?? "worktree";
|
|
41
|
+
}
|
|
42
|
+
return parts[0].startsWith(".") ? parts[0].slice(1) || "home" : parts[0];
|
|
43
|
+
}
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** `evals_query`: bounded plain-text summaries of the index for an agent (names and numbers only, under 2 KB). */
|
|
2
|
+
import { coverageNow, model, reportPath } from "./ops.js";
|
|
3
|
+
export const VIEWS = ["skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"];
|
|
4
|
+
export const MAX_BYTES = 1900;
|
|
5
|
+
const pct = (r) => (r && r.value !== null ? `${(r.value * 100).toFixed(1)}% (n=${r.n})` : `n/a (n=${r?.n ?? 0})`);
|
|
6
|
+
const sec = (v) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)}s`);
|
|
7
|
+
/** Cuts text to the byte limit at a line boundary. */
|
|
8
|
+
export function bound(text, limit = MAX_BYTES) {
|
|
9
|
+
if (Buffer.byteLength(text) <= limit)
|
|
10
|
+
return text;
|
|
11
|
+
const lines = text.split("\n");
|
|
12
|
+
while (lines.length > 1 && Buffer.byteLength(`${lines.join("\n")}\n…`) > limit)
|
|
13
|
+
lines.splice(lines.length - 2, 1);
|
|
14
|
+
return `${lines.join("\n")}\n…`.slice(0, limit);
|
|
15
|
+
}
|
|
16
|
+
export function query(view, options = {}) {
|
|
17
|
+
if (view === "coverage") {
|
|
18
|
+
const c = coverageNow(options.env);
|
|
19
|
+
return bound([
|
|
20
|
+
`coverage, sessions inactive > ${c.cutDays} days (before ${c.cutoff.slice(0, 10)}):`,
|
|
21
|
+
`indexed ${c.indexed.files}/${c.old.files} files, ${(c.indexed.bytes / 1e9).toFixed(2)} of ${(c.old.bytes / 1e9).toFixed(2)} GB; not indexed ${c.notIndexed.files}`,
|
|
22
|
+
`all files: ${c.all.indexedFiles}/${c.all.files} indexed; index keeps ${c.retainedGone} sessions whose file is gone`,
|
|
23
|
+
"meaning: only indexed files keep their numbers if the session files are cleaned up",
|
|
24
|
+
].join("\n"));
|
|
25
|
+
}
|
|
26
|
+
const m = model({ since: options.since, project: options.project }, options.env, false);
|
|
27
|
+
if (!m)
|
|
28
|
+
return "pi-evals: nothing extracted yet; the user can run /evals extract.";
|
|
29
|
+
const head = [
|
|
30
|
+
`pi-evals ${view} · ${m.window.since ?? "?"}..${m.window.until ?? "?"}${m.window.project ? ` · project ${m.window.project}` : ""} · sessions ${m.totals.sessions}`,
|
|
31
|
+
m.freshness.stale ? `STALE: last extract ${m.freshness.lastExtract ?? "never"} (${m.freshness.ageHours ?? "?"}h ago); /evals extract refreshes` : `last extract ${m.freshness.lastExtract}`,
|
|
32
|
+
];
|
|
33
|
+
const body = [];
|
|
34
|
+
if (view === "skills") {
|
|
35
|
+
body.push("skill: loads / sessions");
|
|
36
|
+
for (const s of m.skills.top.slice(0, 15))
|
|
37
|
+
body.push(`${s.name}: ${s.loads} / ${s.sessions}`);
|
|
38
|
+
body.push(`ways: ${Object.entries(m.skills.triggers).map(([k, v]) => `${k} ${v}`).join(", ")}`);
|
|
39
|
+
body.push(`offered but never loaded (${m.skills.neverLoaded.length}/${m.skills.offered}): ${m.skills.neverLoaded.slice(0, 25).join(", ")}`);
|
|
40
|
+
}
|
|
41
|
+
else if (view === "packages") {
|
|
42
|
+
body.push("package: calls, error rate, avg time");
|
|
43
|
+
for (const p of m.packages.slice(0, 15))
|
|
44
|
+
body.push(`${p.owner}${p.version ? `@${p.version}` : ""}: ${p.calls}, ${pct(p.errorRate)}, ${sec(p.avgMs)}`);
|
|
45
|
+
}
|
|
46
|
+
else if (view === "ask_user") {
|
|
47
|
+
const a = m.askUser;
|
|
48
|
+
body.push(`questions ${a.calls}; dismissed ${pct(a.cancelRate)}; avg wait for answer ${sec(a.avgWaitMs)} (n=${a.waitN}); errors ${a.errors}`);
|
|
49
|
+
body.push(`answer source: ${Object.entries(a.sources).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
|
|
50
|
+
}
|
|
51
|
+
else if (view === "monitors") {
|
|
52
|
+
const mo = m.monitors;
|
|
53
|
+
body.push(`started ${mo.started}; ending recorded ${mo.finished}; avg duration ${sec(mo.avgMs)} (n=${mo.durationN})`);
|
|
54
|
+
body.push(`outcomes: ${Object.entries(mo.statuses).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
|
|
55
|
+
}
|
|
56
|
+
else if (view === "subagents") {
|
|
57
|
+
body.push(`subagent sessions ${m.subagents.sessions}; linked to parent ${m.subagents.linked}/${m.subagents.subagentTotal} (all time)`);
|
|
58
|
+
body.push("role / model: launches");
|
|
59
|
+
for (const l of m.subagents.launches.slice(0, 12))
|
|
60
|
+
body.push(`${l.role} / ${l.model}: ${l.n}`);
|
|
61
|
+
body.push(`cost by role: ${m.subagents.costByRole.slice(0, 8).map((r) => `${r.role} $${r.cost}`).join(", ")}`);
|
|
62
|
+
}
|
|
63
|
+
else if (view === "process") {
|
|
64
|
+
body.push(`judged from ${m.process.eraStart} (anchorloop 3.0.0); pass rate = followed / (followed + not followed)`);
|
|
65
|
+
for (const d of m.process.detectors) {
|
|
66
|
+
const label = m.meta.detectors[d.name]?.label.en ?? d.name;
|
|
67
|
+
body.push(`${d.name} (${label}): ${pct(d.passRate)}, not applicable ${d.na}`);
|
|
68
|
+
const versions = d.byVersion.filter((v) => v.pass + v.fail > 0).map((v) => `${v.version} ${pct(v.passRate)}`);
|
|
69
|
+
if (versions.length)
|
|
70
|
+
body.push(` by anchorloop version: ${versions.slice(-4).join("; ")}`);
|
|
71
|
+
}
|
|
72
|
+
body.push(`close-guard reminders: ${Object.entries(m.process.notices).map(([k, v]) => `${k} ${v}`).join(", ") || "none"}`);
|
|
73
|
+
}
|
|
74
|
+
else if (view === "cost") {
|
|
75
|
+
body.push(`total $${m.cost.total}; per session ${m.cost.perSession.value === null ? "n/a" : `$${m.cost.perSession.value.toFixed(2)}`} (n=${m.cost.perSession.n}); tokens ${m.totals.tokens}`);
|
|
76
|
+
body.push("cost of sessions loading skill (not caused by it):");
|
|
77
|
+
for (const s of m.cost.bySkill.slice(0, 10))
|
|
78
|
+
body.push(`${s.skill}: $${s.cost} over ${s.sessions} sessions`);
|
|
79
|
+
}
|
|
80
|
+
else if (view === "changes") {
|
|
81
|
+
body.push("newest changes, sessions split at the change time, metric before -> after; flags: small = <20 sessions a side, incomplete = a window runs past the data, confounded = other commits nearby");
|
|
82
|
+
for (const c of m.changes.slice(-8).reverse()) {
|
|
83
|
+
const what = c.package ? `${c.package} ${c.from ?? "-"}->${c.to ?? "-"}` : c.subject.slice(0, 60);
|
|
84
|
+
const i = c.impact;
|
|
85
|
+
const fx = i
|
|
86
|
+
? `sessions ${i.before.sessions}->${i.after.sessions}, tool errors ${pct(i.before.tool_error_rate)}->${pct(i.after.tool_error_rate)}, anchor-first ${pct(i.before.anchor_before_first_edit)}->${pct(i.after.anchor_before_first_edit)}${i.smallSample ? ", small" : ""}${i.incomplete ? `, incomplete (days with data ${i.daysWithData.before}/${i.daysWithData.after})` : ""}${i.confounded ? `, confounded ${i.confounded}` : ""}`
|
|
87
|
+
: "no data before";
|
|
88
|
+
body.push(`${c.at.slice(0, 10)} ${c.kind} ${what}: ${fx}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return bound([...head, ...body, `report: ${reportPath(options.env)}`].join("\n"));
|
|
92
|
+
}
|