- collector, classify, prompt-parser, server (TypeScript) - web panel (app.js, index.html, style.css) - smoke and load-test scripts - DESIGN.md and README.md
523 lines
19 KiB
TypeScript
523 lines
19 KiB
TypeScript
/**
|
|
* collector.ts — TraceStore: append-only observation data for one pi session.
|
|
*
|
|
* Design rules:
|
|
* - Handlers push into the store synchronously and cheaply; heavy work never runs
|
|
* in pi event handlers (they are awaited in stream order).
|
|
* - Full content lives in a bounded content store and is served on demand
|
|
* (/api/content/:id); lists only carry previews and byte counts.
|
|
* - Everything is append-only or patched in place; the SSE layer emits the same
|
|
* events so the web client can append instead of re-rendering.
|
|
*/
|
|
import { parseSystemPrompt, forcedSegment, customPromptSegment } from "./prompt-parser.ts";
|
|
import type {
|
|
PromptBuild,
|
|
PromptSection,
|
|
PromptSourceOptions,
|
|
SkillMeta,
|
|
SkillSpan,
|
|
SkillSpanStatus,
|
|
SkillStep,
|
|
StateSnapshot,
|
|
ToolCallLike,
|
|
ToolResultLike,
|
|
TraceEvent,
|
|
} from "./types.ts";
|
|
import { estimateTokens, previewOf } from "./types.ts";
|
|
|
|
const MAX_EVENTS = 5000;
|
|
const MAX_CONTENTS = 800;
|
|
const MAX_CONTENT_CHARS = 200_000;
|
|
|
|
type Listener = (event: TraceEvent) => void;
|
|
|
|
interface OpenCall {
|
|
toolCallId: string;
|
|
toolName: string;
|
|
at: number;
|
|
input: Record<string, unknown>;
|
|
spanId?: string;
|
|
}
|
|
|
|
export class TraceStore {
|
|
readonly startedAt = Date.now();
|
|
private seq = 0;
|
|
private turn = 0;
|
|
|
|
private events: TraceEvent[] = [];
|
|
private contents = new Map<string, string>();
|
|
private contentOrder: string[] = [];
|
|
private contentSeq = 0;
|
|
|
|
private builds: PromptBuild[] = [];
|
|
private buildSeq = 0;
|
|
private spans: SkillSpan[] = [];
|
|
private spanSeq = 0;
|
|
private skillLedger = new Map<string, SkillMeta>();
|
|
private openSpans = new Map<string, SkillSpan>(); // key: skill name
|
|
private openCalls = new Map<string, OpenCall>();
|
|
private lastInput = "";
|
|
private listeners = new Set<Listener>();
|
|
|
|
state: StateSnapshot = {
|
|
startedAt: this.startedAt,
|
|
updatedAt: this.startedAt,
|
|
totals: {
|
|
turns: 0,
|
|
toolCalls: 0,
|
|
toolErrors: 0,
|
|
promptBuilds: 0,
|
|
skillInvocations: 0,
|
|
compactions: 0,
|
|
inputChars: 0,
|
|
outputChars: 0,
|
|
errors: 0,
|
|
},
|
|
};
|
|
|
|
// ── plumbing ────────────────────────────────────────────────────────────────
|
|
|
|
subscribe(fn: Listener): () => void {
|
|
this.listeners.add(fn);
|
|
return () => this.listeners.delete(fn);
|
|
}
|
|
|
|
private emit(event: TraceEvent): void {
|
|
this.events.push(event);
|
|
if (this.events.length > MAX_EVENTS) this.events.splice(0, this.events.length - MAX_EVENTS);
|
|
for (const fn of this.listeners) {
|
|
try {
|
|
fn(event);
|
|
} catch {
|
|
/* listeners must never break collection */
|
|
}
|
|
}
|
|
}
|
|
|
|
putContent(text: string): string {
|
|
const id = "c" + ++this.contentSeq;
|
|
const clipped = text.length > MAX_CONTENT_CHARS ? text.slice(0, MAX_CONTENT_CHARS) + "\n…[truncated]" : text;
|
|
this.contents.set(id, clipped);
|
|
this.contentOrder.push(id);
|
|
while (this.contentOrder.length > MAX_CONTENTS) {
|
|
const evict = this.contentOrder.shift();
|
|
if (evict) this.contents.delete(evict);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
getContent(id: string): string | undefined {
|
|
return this.contents.get(id);
|
|
}
|
|
|
|
private addEvent(
|
|
type: string,
|
|
kind: TraceEvent["kind"],
|
|
label: string,
|
|
opts: Partial<Pick<TraceEvent, "detail" | "contentId" | "toolCallId" | "spanId" | "turn">> = {},
|
|
): TraceEvent {
|
|
const event: TraceEvent = {
|
|
seq: ++this.seq,
|
|
t: Date.now(),
|
|
type,
|
|
kind,
|
|
label,
|
|
turn: this.turn,
|
|
session: this.state.sessionId,
|
|
...opts,
|
|
};
|
|
this.emit(event);
|
|
return event;
|
|
}
|
|
|
|
// ── state ───────────────────────────────────────────────────────────────────
|
|
|
|
updateState(patch: Partial<StateSnapshot>): void {
|
|
this.state = { ...this.state, ...patch, updatedAt: Date.now() };
|
|
if (patch.skills) {
|
|
for (const meta of patch.skills) {
|
|
const existing = this.skillLedger.get(meta.name);
|
|
if (existing) {
|
|
meta.invokedCount = existing.invokedCount;
|
|
meta.lastInvokedAt = existing.lastInvokedAt;
|
|
meta.injectedChars = existing.injectedChars;
|
|
}
|
|
this.skillLedger.set(meta.name, meta);
|
|
}
|
|
}
|
|
this.state.skills = [...this.skillLedger.values()];
|
|
}
|
|
|
|
getState(): StateSnapshot {
|
|
this.state.updatedAt = Date.now();
|
|
this.state.skills = [...this.skillLedger.values()];
|
|
return this.state;
|
|
}
|
|
|
|
// ── input & skills ──────────────────────────────────────────────────────────
|
|
|
|
recordInput(text: string, source: string): void {
|
|
this.lastInput = text;
|
|
this.state.totals.inputChars += text.length;
|
|
const contentId = this.putContent(text);
|
|
this.addEvent("input", "user", previewOf(text), {
|
|
detail: { source, chars: text.length },
|
|
contentId,
|
|
});
|
|
|
|
const explicit = text.match(/^\/skill:([a-z0-9-]+)(?:\s+([\s\S]*))?$/);
|
|
if (explicit) {
|
|
const [, skillName, args] = explicit;
|
|
const meta = this.skillLedger.get(skillName);
|
|
const span = this.openSpan(skillName, meta?.filePath ?? "", "explicit", `input:${source}`, args);
|
|
span.steps.push({ kind: "trigger", at: Date.now(), label: `/skill:${skillName}`, detail: { args } });
|
|
this.addEvent("skill_trigger", "skill-loaded", `skill trigger: ${skillName} (explicit)`, {
|
|
spanId: span.id,
|
|
contentId,
|
|
});
|
|
}
|
|
}
|
|
|
|
private openSpan(skill: string, location: string, trigger: "explicit" | "model", triggerBy: string, args?: string): SkillSpan {
|
|
let span = this.openSpans.get(skill);
|
|
if (span && span.status === "open" && span.trigger === trigger) return span;
|
|
span = {
|
|
id: "s" + ++this.spanSeq,
|
|
skill,
|
|
location,
|
|
trigger,
|
|
triggerBy,
|
|
args,
|
|
startedAt: Date.now(),
|
|
status: "open",
|
|
steps: [],
|
|
injectedChars: 0,
|
|
};
|
|
this.spans.push(span);
|
|
this.openSpans.set(skill, span);
|
|
const meta = this.skillLedger.get(skill);
|
|
if (meta) {
|
|
meta.invokedCount += 1;
|
|
meta.lastInvokedAt = span.startedAt;
|
|
}
|
|
this.state.totals.skillInvocations += 1;
|
|
return span;
|
|
}
|
|
|
|
/** Called from capturePromptBuild: expanded <skill name=… location=…> blocks in the user prompt. */
|
|
private matchSkillBlocks(prompt: string): void {
|
|
const re = /<skill name="([^"]+)" location="([^"]+)">([\s\S]*?)<\/skill>/g;
|
|
let m: RegExpExecArray | null;
|
|
while ((m = re.exec(prompt)) !== null) {
|
|
const [, name, location] = m;
|
|
const span = this.openSpans.get(name);
|
|
const loadedAt = Date.now();
|
|
const chars = m[0].length;
|
|
// The injected skill body can be tens of KB — store it for the detail card,
|
|
// never inline it into lists.
|
|
const contentId = this.putContent(m[0]);
|
|
if (span && span.status === "open") {
|
|
span.loadedAt = loadedAt;
|
|
span.status = "loaded";
|
|
span.location = span.location || location;
|
|
span.injectedChars += chars;
|
|
span.steps.push({ kind: "load", at: loadedAt, label: `load ${name} (slash expansion)`, chars, contentId });
|
|
const meta = this.skillLedger.get(name);
|
|
if (meta) meta.injectedChars += chars;
|
|
this.addEvent("skill_load", "skill-loaded", `skill loaded: ${name} (slash expansion, ${chars} chars)`, {
|
|
spanId: span.id,
|
|
contentId,
|
|
});
|
|
} else if (!span) {
|
|
const newSpan = this.openSpan(name, location, "explicit", "prompt-expansion");
|
|
newSpan.loadedAt = loadedAt;
|
|
newSpan.status = "loaded";
|
|
newSpan.injectedChars += chars;
|
|
newSpan.steps.push({ kind: "load", at: loadedAt, label: `load ${name} (slash expansion)`, chars, contentId });
|
|
const meta = this.skillLedger.get(name);
|
|
if (meta) meta.injectedChars += chars;
|
|
this.addEvent("skill_load", "skill-loaded", `skill loaded: ${name} (slash expansion, ${chars} chars)`, {
|
|
spanId: newSpan.id,
|
|
contentId,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
private skillForPath(filePath: string): SkillMeta | undefined {
|
|
if (!filePath) return undefined;
|
|
const normalized = filePath.replace(/\\/g, "/");
|
|
for (const meta of this.skillLedger.values()) {
|
|
const base = meta.baseDir.replace(/\\/g, "/");
|
|
const file = meta.filePath.replace(/\\/g, "/");
|
|
if (base && (normalized === base || normalized.startsWith(base + "/"))) return meta;
|
|
if (file && normalized === file) return meta;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
// ── prompt assembly ─────────────────────────────────────────────────────────
|
|
|
|
capturePromptBuild(options: PromptSourceOptions, rendered: string, trigger: string, userPrompt?: string): PromptBuild {
|
|
// Keep the skill ledger fresh from the prompt sources (name, location, origin).
|
|
if (options.skills?.length) {
|
|
const merged: SkillMeta[] = options.skills.map((skill) => ({
|
|
name: skill.name,
|
|
description: skill.description,
|
|
filePath: skill.filePath,
|
|
baseDir: skill.baseDir,
|
|
source: skill.sourceInfo?.source ?? "discovered",
|
|
disableModelInvocation: skill.disableModelInvocation,
|
|
invokedCount: 0,
|
|
injectedChars: 0,
|
|
}));
|
|
this.updateState({ skills: merged });
|
|
}
|
|
|
|
const customTags = Object.keys(options.sections ?? {});
|
|
const segments =
|
|
options.forceSystemPrompt !== undefined
|
|
? forcedSegment(rendered)
|
|
: options.customPrompt
|
|
? customPromptSegment(rendered)
|
|
: parseSystemPrompt(rendered, customTags);
|
|
|
|
const contentIds = segments.map((s) => this.putContent(s.content));
|
|
const prev = this.builds[this.builds.length - 1];
|
|
const prevSections = new Map<string, PromptSection>((prev?.sections ?? []).map((s) => [s.name, s]));
|
|
|
|
const sections: PromptSection[] = segments.map((seg, i) => {
|
|
const before = prevSections.get(seg.name);
|
|
const status: PromptSection["status"] = before
|
|
? this.getContent(before.contentId) === segments[i].content
|
|
? "same"
|
|
: "changed"
|
|
: "added";
|
|
prevSections.delete(seg.name);
|
|
return {
|
|
name: seg.name,
|
|
kind: seg.kind,
|
|
source: seg.source,
|
|
chars: seg.content.length,
|
|
tokensEstimate: estimateTokens(seg.content.length),
|
|
preview: previewOf(seg.content),
|
|
contentId: contentIds[i],
|
|
status,
|
|
};
|
|
});
|
|
// Sections present in the previous build but gone now.
|
|
for (const [name, gone] of prevSections) {
|
|
sections.push({ ...gone, name, status: "removed", chars: gone.chars, tokensEstimate: gone.tokensEstimate });
|
|
}
|
|
|
|
const build: PromptBuild = {
|
|
id: "pb" + ++this.buildSeq,
|
|
turn: this.turn,
|
|
at: Date.now(),
|
|
trigger,
|
|
forced: options.forceSystemPrompt !== undefined || !!options.customPrompt,
|
|
totalChars: segments.reduce((n, s) => n + s.content.length, 0),
|
|
totalTokensEstimate: estimateTokens(segments.reduce((n, s) => n + s.content.length, 0)),
|
|
sections,
|
|
selectedTools: [...options.selectedTools],
|
|
skillCount: options.skills.length,
|
|
contextFileCount: options.contextFiles.length,
|
|
};
|
|
this.builds.push(build);
|
|
if (this.builds.length > 200) this.builds.splice(0, this.builds.length - 200);
|
|
this.state.totals.promptBuilds += 1;
|
|
|
|
this.matchSkillBlocks(userPrompt ?? "");
|
|
this.addEvent("prompt_build", "preamble", `prompt build #${build.id} (${build.totalTokensEstimate} tok est.)`, {
|
|
detail: {
|
|
sections: sections.length,
|
|
forced: build.forced,
|
|
trigger,
|
|
tools: build.selectedTools.length,
|
|
},
|
|
});
|
|
return build;
|
|
}
|
|
|
|
// ── tools ───────────────────────────────────────────────────────────────────
|
|
|
|
recordToolCall(event: ToolCallLike): void {
|
|
this.state.totals.toolCalls += 1;
|
|
const inputStr = JSON.stringify(event.input ?? {});
|
|
const contentId = this.putContent(inputStr);
|
|
let spanId: string | undefined;
|
|
|
|
const pathValue = this.pathFromInput(event.input);
|
|
const meta = this.skillForPath(pathValue);
|
|
if (meta) {
|
|
const isSkillMd = pathValue.replace(/\\/g, "/") === meta.filePath.replace(/\\/g, "/") || /SKILL\.md$/i.test(pathValue);
|
|
const span = this.openSpan(meta.name, meta.filePath, "model", `tool:${event.toolCallId}`);
|
|
spanId = span.id;
|
|
if (isSkillMd && span.status === "open") {
|
|
span.loadedAt = Date.now();
|
|
span.status = "loaded";
|
|
span.injectedChars += inputStr.length;
|
|
meta.injectedChars += inputStr.length;
|
|
span.steps.push({ kind: "load", at: Date.now(), label: `load ${meta.name} (model read)`, toolCallId: event.toolCallId, status: "running" });
|
|
this.addEvent("skill_load", "skill-loaded", `skill loaded: ${meta.name} (model read)`, { spanId: span.id, toolCallId: event.toolCallId });
|
|
} else {
|
|
span.steps.push({
|
|
kind: "reference",
|
|
at: Date.now(),
|
|
label: `${event.toolName} ${pathValue}`,
|
|
toolCallId: event.toolCallId,
|
|
parentToolCallId: event.parentToolCallId,
|
|
status: "running",
|
|
});
|
|
this.addEvent("skill_step", "skill-loaded", `skill ref: ${meta.name} ← ${event.toolName}`, {
|
|
spanId: span.id,
|
|
toolCallId: event.toolCallId,
|
|
});
|
|
}
|
|
}
|
|
|
|
this.openCalls.set(event.toolCallId, {
|
|
toolCallId: event.toolCallId,
|
|
toolName: event.toolName,
|
|
at: Date.now(),
|
|
input: event.input ?? {},
|
|
spanId,
|
|
});
|
|
|
|
this.addEvent("tool_call", "tool", `${event.toolName}(${event.toolCallId})`, {
|
|
toolCallId: event.toolCallId,
|
|
spanId,
|
|
contentId,
|
|
detail: {
|
|
parentToolCallId: event.parentToolCallId,
|
|
preview: previewOf(inputStr, 160),
|
|
},
|
|
});
|
|
}
|
|
|
|
recordToolResult(event: ToolResultLike): void {
|
|
const call = this.openCalls.get(event.toolCallId);
|
|
this.openCalls.delete(event.toolCallId);
|
|
const durationMs = call ? Date.now() - call.at : undefined;
|
|
const contentStr = JSON.stringify(event.content ?? []);
|
|
const contentId = this.putContent(contentStr);
|
|
if (event.isError) this.state.totals.toolErrors += 1;
|
|
|
|
const span = call?.spanId ? this.spans.find((s) => s.id === call.spanId) : undefined;
|
|
if (span) {
|
|
let step: SkillStep | undefined;
|
|
for (const s of span.steps) {
|
|
if (s.toolCallId === event.toolCallId) step = s;
|
|
}
|
|
if (step) {
|
|
step.status = event.isError ? "error" : "ok";
|
|
step.chars = contentStr.length;
|
|
}
|
|
if (/SKILL\.md$/i.test(this.pathFromInput(call?.input)) && span.status === "loaded" && event.isError) {
|
|
span.status = "error";
|
|
}
|
|
}
|
|
|
|
this.addEvent("tool_result", event.isError ? "forced" : "tool", `${event.toolName} → ${event.isError ? "error" : "ok"} (${durationMs ?? 0}ms)`, {
|
|
toolCallId: event.toolCallId,
|
|
spanId: call?.spanId,
|
|
contentId,
|
|
detail: { isError: event.isError, durationMs, chars: contentStr.length },
|
|
});
|
|
}
|
|
|
|
private pathFromInput(input: Record<string, unknown> | undefined): string {
|
|
if (!input) return "";
|
|
for (const key of ["path", "file_path", "filePath", "target_file", "file"]) {
|
|
const value = input[key];
|
|
if (typeof value === "string") return value;
|
|
}
|
|
for (const value of Object.values(input)) {
|
|
if (typeof value === "string" && (value.includes("/") || value.includes("\\")) && value.length < 512) return value;
|
|
}
|
|
return "";
|
|
}
|
|
|
|
// ── agent lifecycle ─────────────────────────────────────────────────────────
|
|
|
|
recordTurnStart(turnIndex: number): void {
|
|
this.turn = turnIndex + 1;
|
|
this.state.totals.turns += 1;
|
|
this.addEvent("turn_start", "other", `turn ${this.turn} start`, { detail: { turnIndex } });
|
|
}
|
|
|
|
recordTurnEnd(turnIndex: number): void {
|
|
this.addEvent("turn_end", "other", `turn ${turnIndex + 1} end`, { detail: { turnIndex } });
|
|
}
|
|
|
|
recordAgentStart(): void {
|
|
this.addEvent("agent_start", "other", "agent start");
|
|
}
|
|
|
|
recordAgentEnd(): void {
|
|
for (const span of this.openSpans.values()) {
|
|
if (span.status === "open") span.status = "unloaded";
|
|
if (span.status === "loaded") span.status = "done";
|
|
span.endedAt = Date.now();
|
|
span.steps.push({
|
|
kind: "output",
|
|
at: Date.now(),
|
|
label: `turn output (${this.state.totals.outputChars} chars total)`,
|
|
chars: this.state.totals.outputChars,
|
|
});
|
|
}
|
|
this.openSpans.clear();
|
|
this.addEvent("agent_end", "other", "agent end");
|
|
}
|
|
|
|
recordMessageEnd(role: string, text: string): void {
|
|
if (role === "assistant") this.state.totals.outputChars += text.length;
|
|
if (role === "assistant" && text.trim()) {
|
|
this.addEvent("message_end", "assistant", previewOf(text), { contentId: this.putContent(text) });
|
|
}
|
|
}
|
|
|
|
recordCompaction(reason: string, chars: number): void {
|
|
this.state.totals.compactions += 1;
|
|
this.addEvent("compaction", "compaction", `compaction (${reason})`, { detail: { chars } });
|
|
}
|
|
|
|
recordLifecycle(type: "session_start" | "session_shutdown" | "state", label: string, detail?: Record<string, unknown>): void {
|
|
this.addEvent(type, "other", label, { detail });
|
|
}
|
|
|
|
// ── queries ─────────────────────────────────────────────────────────────────
|
|
|
|
getPromptBuilds(): PromptBuild[] {
|
|
return this.builds;
|
|
}
|
|
|
|
getSkills(): { ledger: SkillMeta[]; spans: SkillSpan[] } {
|
|
return { ledger: [...this.skillLedger.values()], spans: this.spans };
|
|
}
|
|
|
|
getTimeline(before?: number, limit = 200): { events: TraceEvent[]; hasMore: boolean; total: number } {
|
|
// `before` is an event seq (client cursor), not an array index.
|
|
let end = this.events.length;
|
|
if (before !== undefined) {
|
|
const idx = this.events.findIndex((e) => e.seq >= before);
|
|
end = idx < 0 ? this.events.length : idx;
|
|
}
|
|
const start = Math.max(0, end - limit);
|
|
return {
|
|
events: this.events.slice(start, end),
|
|
hasMore: start > 0,
|
|
total: this.events.length,
|
|
};
|
|
}
|
|
|
|
exportAll(): Record<string, unknown> {
|
|
return {
|
|
state: this.getState(),
|
|
promptBuilds: this.builds,
|
|
skills: this.getSkills(),
|
|
events: this.events,
|
|
};
|
|
}
|
|
}
|