import type { ExtensionAPI, ExtensionContext, } from "@earendil-works/pi-coding-agent"; import { Key } from "@earendil-works/pi-tui"; import { closeDebug, dbg, span } from "./src/debug.ts"; import type { PromptSnapshot } from "./src/types.ts"; const MAX_SNAPSHOTS = 32; const MAX_PROMPT_CHARS = 4 * 1024 * 1024; const LABEL = { preamble: "[PREAMBLE]", core: "[CORE]", tools: "[TOOLS]", rules: "[RULES]", generalGuidelines: "[GENERAL GUIDELINES]", toolGuidelines: "[TOOL GUIDELINES]", docs: "[DOCS]", append: "[APPEND]", context: "[CTX]", skills: "[SKILLS]", cwd: "[CWD]", } as const; const SECTION_LABEL: Readonly> = { tools: LABEL.tools, rules: LABEL.rules, general_guidelines: LABEL.generalGuidelines, tool_guidelines: LABEL.toolGuidelines, docs: LABEL.docs, addendum: LABEL.append, project_context: LABEL.context, skills: LABEL.skills, cwd: LABEL.cwd, }; const SECTION_START = /(?:^|\n)<([a-z][a-z0-9_-]*)>\n/g; type Range = { start: number; end: number; label: string }; type CapturedPrompt = { cwd: string; prompt: string }; export function groupSystemPrompt(prompt: string): string { const ranges = findSectionRanges(prompt); let pos = 0; const out: string[] = []; for (const [index, range] of ranges.entries()) { appendSection( out, index === 0 ? LABEL.preamble : LABEL.core, prompt.slice(pos, range.start), ); appendSection(out, range.label, prompt.slice(range.start, range.end)); pos = range.end; } appendSection(out, LABEL.core, prompt.slice(pos)); return out.join("\n\n"); } function findSectionRanges(prompt: string): Range[] { const ranges: Range[] = []; const pattern = new RegExp(SECTION_START.source, "g"); let consumed = 0; for (let match = pattern.exec(prompt); match; match = pattern.exec(prompt)) { const start = match.index + (match[0].startsWith("\n") ? 1 : 0); if (start < consumed) continue; const name = match[1]; if (name === undefined) continue; const end = findSectionEnd(prompt, name, pattern.lastIndex); if (end === undefined) continue; ranges.push({ start, end, label: SECTION_LABEL[name] ?? `[SECTION ${name}]`, }); consumed = end; pattern.lastIndex = end; } return ranges; } function findSectionEnd( prompt: string, name: string, contentStart: number, ): number | undefined { const opening = `<${name}>\n`; const closing = `\n`; let depth = 1; let cursor = contentStart; while (depth > 0) { const nextOpening = findLineOpening(prompt, opening, cursor); const closeStart = prompt.indexOf(closing, cursor); if (closeStart < 0) return undefined; if (nextOpening >= 0 && nextOpening < closeStart) { depth++; cursor = nextOpening + opening.length; continue; } depth--; cursor = closeStart + closing.length; if (depth === 0) return cursor; } return undefined; } function findLineOpening( prompt: string, opening: string, from: number, ): number { for ( let index = prompt.indexOf(opening, from); index >= 0; index = prompt.indexOf(opening, index + opening.length) ) { if (index === 0 || prompt[index - 1] === "\n") return index; } return -1; } function appendSection(out: string[], label: string, text: string): void { const body = text.trim(); if (body) out.push(`${label}\n${body}`); } export default function (pi: ExtensionAPI): void { let last: CapturedPrompt | undefined; let prompts: PromptSnapshot[] = []; let nextId = 0; let dropped = 0; let generation = 0; let stopped = false; let inspector: | Promise< Awaited> > | undefined; pi.on("session_start", () => { dbg?.("session.start"); stopped = false; last = undefined; prompts = []; nextId = 0; dropped = 0; }); pi.on("session_shutdown", async () => { dbg?.("session.shutdown"); stopped = true; generation++; const pending = inspector; inspector = undefined; last = undefined; prompts = []; try { await (await pending?.catch(() => undefined))?.close(); } finally { closeDebug(); } }); pi.on("before_agent_start", (event, ctx) => { last = { cwd: ctx.cwd, prompt: event.systemPrompt }; }); pi.on("agent_start", (_event, ctx) => { if (stopped || last?.cwd !== ctx.cwd) return; // Same capture boundary as the editor: after all before_agent_start handlers. last.prompt = ctx.getSystemPrompt(); prompts.push({ id: ++nextId, timestamp: new Date().toISOString(), entryId: ctx.sessionManager.getLeafId(), prompt: last.prompt, grouped: groupSystemPrompt(last.prompt), }); let chars = prompts.reduce( (sum, p) => sum + p.prompt.length + p.grouped.length, 0, ); while ( prompts.length > 1 && (prompts.length > MAX_SNAPSHOTS || chars > MAX_PROMPT_CHARS) ) { const oldest = prompts.shift(); if (oldest) chars -= oldest.prompt.length + oldest.grouped.length; dropped++; } }); const run = async (ctx: ExtensionContext) => { if (stopped) return; const currentGeneration = generation; let owned: typeof inspector; if (!prompts.length) dbg?.("prompt.skip", { reason: "not_captured" }); const finish = span?.("prompt.open"); try { const { buildInspectorData, startInspector, streamInspectorMetrics } = await import("./inspector.ts"); if (generation !== currentGeneration) return; inspector ??= startInspector( (query, signal) => buildInspectorData( ctx, prompts, [ ...(dropped ? [ `${dropped} older prompt captures expired; the latest capture is retained unchanged.`, ] : []), ], (provider, model) => ctx.modelRegistry.find(provider, model)?.cost, query, signal, ), (id) => ctx.sessionManager.getEntry(id), (query, signal) => streamInspectorMetrics( ctx, (provider, model) => ctx.modelRegistry.find(provider, model)?.cost, query, signal, ), () => prompts.map((prompt) => ({ ...prompt })), ); owned = inspector; const server = await owned; if (generation !== currentGeneration) return; const { openUrl } = await import("./src/pi-ext-browser-open.ts"); if (generation !== currentGeneration) return; const opened = await openUrl(server.url, {}); if (generation !== currentGeneration) return; ctx.ui.notify( `${opened ? "Inspector" : "Browser launch failed; open"}: ${server.url}`, opened ? "info" : "warning", ); finish?.("finish", { outcome: opened ? "opened" : "browser_failed" }); } catch { if (generation === currentGeneration && inspector === owned) inspector = undefined; await (await owned?.catch(() => undefined))?.close(); finish?.("error", { outcome: "failed" }); if (generation === currentGeneration) ctx.ui.notify("Could not open autopsy. Retry /autopsy.", "error"); } }; pi.registerCommand("autopsy", { description: "Inspect session history, usage, and captured prompts in your browser", handler: async (_args, ctx) => run(ctx), }); pi.registerShortcut(Key.ctrlAlt("a"), { description: "Inspect session history, usage, and captured prompts in your browser", handler: run, }); }