// @generated by scripts/build-runtime.mjs; do not edit. // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader. // src/extension.ts import { randomUUID } from "node:crypto"; // src/entry-index.ts var EntryIndex = class { constructor(entries) { this.entries = entries; for (const entry of entries) if (typeof entry?.id === "string") { if (this.byId.has(entry.id)) this.duplicates.add(entry.id); this.byId.set(entry.id, entry); } } entries; byId = /* @__PURE__ */ new Map(); duplicates = /* @__PURE__ */ new Set(); get(id) { return this.duplicates.has(id) ? void 0 : this.byId.get(id); } }; // src/system-message.ts var SYSTEM_REPLAY_CHARACTERS = 1048576; var SYSTEM_REPLAY_TOOL_DELTAS = 2048; function systemReplayIssue(messages) { let remaining = SYSTEM_REPLAY_CHARACTERS; let deltas = SYSTEM_REPLAY_TOOL_DELTAS; let nodes = 16384; const seen = /* @__PURE__ */ new WeakSet(); function declaration(value, depth = 0) { if (--nodes < 0 || depth > 32) return false; if (typeof value === "string") { remaining -= value.length; return remaining >= 0; } if (!value || typeof value !== "object" || seen.has(value)) return true; seen.add(value); if (Array.isArray(value) && value.length > nodes) return false; for (const key in value) { if (!Object.hasOwn(value, key)) continue; remaining -= key.length + 2; if (remaining < 0) return false; const property = Object.getOwnPropertyDescriptor(value, key); if (property?.get || property?.set || !declaration(property?.value, depth + 1)) return false; } return true; } for (const value of messages) { if (!value || typeof value !== "object" || Array.isArray(value)) continue; const m = value; if (m.role !== "system") continue; for (const [kind, delta] of [ ["added", m.toolsAdded], ["removed", m.toolsRemoved] ]) { if (!Array.isArray(delta)) continue; deltas -= delta.length; if (deltas < 0) return "system tool replay exceeds 2,048 cumulative delta budget"; for (const tool of delta) { if (!declaration( kind === "added" ? { name: tool.name, description: tool.description, parameters: tool.parameters } : { name: tool.name } )) return "system tool replay exceeds metadata character/node/depth budget"; } } remaining -= 2; if (typeof m.content === "string") remaining -= m.content.length; else if (Array.isArray(m.content)) { remaining -= m.content.length; if (remaining < 0) return "system replay exceeds 1,048,576-character input budget"; for (const block of m.content) { if (block?.type === "text" && typeof block.text === "string") remaining -= block.text.length; if (remaining < 0) return "system replay exceeds 1,048,576-character input budget"; } } if (remaining < 0) return "system replay exceeds 1,048,576-character input budget"; if (m.sections && typeof m.sections === "object") { for (const [key, part] of Object.entries(m.sections)) { remaining -= key.length + 2 + (typeof part === "string" ? part.length : 0); if (remaining < 0) return "system replay exceeds 1,048,576-character input budget"; } } } return void 0; } function systemMessageIssue(value) { if (!value || typeof value !== "object" || Array.isArray(value)) return "malformed system-message envelope"; const m = value; if (m.role !== "system") return "malformed system-message role"; if (Array.isArray(m.content) && m.content.length > 2048) return "system content exceeds 2,048-block budget"; if (typeof m.content !== "string" && (!Array.isArray(m.content) || m.content.some( (block) => !block || typeof block !== "object" || Array.isArray(block) || block.type === "text" && typeof block.text !== "string" ))) return "malformed system-message content"; if (m.sections != null && (typeof m.sections !== "object" || Array.isArray(m.sections) || Object.values(m.sections).some((part) => part !== null && typeof part !== "string"))) return "malformed system-message sections"; for (const delta of [m.toolsAdded, m.toolsRemoved]) { if (Array.isArray(delta) && delta.length > SYSTEM_REPLAY_TOOL_DELTAS) return "system tool delta exceeds 2,048-entry budget"; if (delta != null && (!Array.isArray(delta) || delta.some( (tool) => !tool || typeof tool !== "object" || Array.isArray(tool) || typeof tool.name !== "string" || !tool.name.length || tool.name.length > 512 ))) return "malformed system-message tool delta"; } return void 0; } // src/identity.ts var MESSAGE_BLOCKS = 2048; function structuralIssue(entry) { if (typeof entry?.id !== "string" || !entry.id.length) return "missing, empty or non-string entry id"; if (entry.id.length > 512) return "over-budget entry id"; if (typeof entry.parentId === "string" && entry.parentId.length > 512) return "over-budget parent id"; if (entry.type === "label" && entry.label !== void 0 && typeof entry.label !== "string") return "non-string stored label"; if (entry.parentId !== null && (typeof entry.parentId !== "string" || !entry.parentId.length)) return "missing, empty or non-string parent id"; if (entry.type === "session_info" && entry.name !== void 0 && typeof entry.name !== "string") return "non-string stored session name"; if (typeof entry.type !== "string" || !entry.type.length) return "missing, empty or non-string entry type"; if (entry.type === "message" && (typeof entry.message?.role !== "string" || !entry.message.role.length)) return "missing, empty or non-string message role"; if (typeof entry.timestamp !== "string") return "non-string entry timestamp"; if (entry.timestamp.length > 512) return "over-budget entry timestamp"; return void 0; } function identityIssue(entry) { const structure = structuralIssue(entry); if (structure || !entry) return structure; if (entry.type === "message" && "content" in entry.message && Array.isArray(entry.message.content) && entry.message.content.length > MESSAGE_BLOCKS) return "message content exceeds 2,048-block budget"; if (entry.type === "message" && entry.message.role === "system") { const m = entry.message; const issue = systemMessageIssue(m.content == null ? { ...m, content: "" } : m); if (issue) return issue; } if (entry.type === "compaction" && entry.systemMessage) { const issue = systemMessageIssue(entry.systemMessage); if (issue) return `checkpoint: ${issue}`; } if (entry.type === "message" && entry.message.role === "assistant" && entry.message.content != null && (!Array.isArray(entry.message.content) || Array.from(entry.message.content).some((block) => !block || typeof block !== "object" || Array.isArray(block)))) return "malformed assistant content block or envelope"; if (entry.type === "message" && entry.message.role === "assistant" && Array.isArray(entry.message.content) && entry.message.content.some( (block) => block.type === "toolCall" && (!block.arguments || typeof block.arguments !== "object" || Array.isArray(block.arguments) || typeof block.id !== "string" || !block.id.length || block.id.length > 512 || typeof block.name !== "string" || !block.name.length || block.name.length > 512) )) return "malformed tool-call envelope"; if (entry.type === "context_edit") { if (typeof entry.targetId !== "string" || !entry.targetId.length || entry.targetId.length > 512) return "malformed context-edit target id"; const value = entry.replacement; if (Array.isArray(value?.content) && value.content.length > MESSAGE_BLOCKS) return "context-edit content exceeds 2,048-block budget"; if (value !== null && (!value || typeof value !== "object" || Array.isArray(value) || !("content" in value) || typeof value.content !== "string" && !Array.isArray(value.content) || Array.isArray(value.content) && value.content.some((block) => !block || typeof block !== "object" || Array.isArray(block)))) return "malformed context-edit replacement"; } if (entry.type === "message" && entry.message.role === "toolResult" && (typeof entry.message.toolCallId !== "string" || !entry.message.toolCallId.length || entry.message.toolCallId.length > 512)) return "malformed or over-budget tool-result id"; return void 0; } function recordedLeaf(manager, duplicates) { const leaf = manager.getLeafId(); return typeof leaf === "string" && leaf.length > 0 && leaf.length <= 512 && !duplicates?.has(leaf) && !identityIssue(manager.getEntry(leaf)) ? leaf : null; } // src/native-projection.ts import { buildContextEntries, buildSessionProjection } from "@earendil-works/pi-coding-agent"; function nativeProjection(path, leaf) { const contextEntries = buildContextEntries(path, leaf); if (contextEntries[0]?.type === "compaction") { const issue = identityIssue(contextEntries[0]); if (issue) return { issue }; } const edits = new Map( contextEntries.filter((entry) => entry.type === "context_edit").map((entry) => [entry.targetId, entry]) ); for (const entry of edits.values()) { if (entry.type === "context_edit") { const issue = identityIssue(entry); if (issue) return { issue }; } } const projection = buildSessionProjection(path, leaf); for (const projected of projection.entries) for (const message of projected.messages) { const issue = identityIssue({ ...projected.sourceEntry, type: "message", message }); if (issue) return { issue }; } return { projection }; } // src/ancestry.ts function ancestry(manager, id, index = new EntryIndex(manager.getEntries())) { const path = []; const seen = /* @__PURE__ */ new Set(); if (index.duplicates.has(id)) return { path: [], issue: "duplicate entry id" }; let current = index.get(id); while (current) { const issue = structuralIssue(current); if (issue) return { path: path.reverse(), issue }; if (seen.has(current.id)) return { path: path.reverse(), issue: "recorded parent cycle" }; if (path.length >= 1e4) return { path: path.reverse(), issue: "ancestry exceeds the 10,000-entry inspection budget" }; seen.add(current.id); path.push(current); const parent = current.parentId; if (parent && index.duplicates.has(parent)) return { path: path.reverse(), issue: "duplicate ancestor id" }; current = parent ? index.get(parent) : void 0; if (parent && !current) return { path: path.reverse(), issue: "missing recorded parent" }; } path.reverse(); return { path, issue: nativeProjection(path, id).issue }; } // src/privacy.ts import { stripVTControlCharacters } from "node:util"; var secretKey = /^(authorization|proxy.authorization|cookie|set.cookie|password|passwd|secret|client[_-]?secret|secret[_-]?key|private[_-]?key|token|api[_-]?key|access[_-]?token|refresh[_-]?token|session[_-]?token|credentials|env|headers)$|(?:^|[_-])(?:api[_-]?key|(?:access|refresh|session)[_-]?token|token|client[_-]?secret|secret[_-]?key|private[_-]?key|password|passwd|secret)$/i; function displayText(text) { return stripVTControlCharacters(text).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "").replace(/\bBearer\s+[A-Za-z0-9._~+/-]+/gi, "Bearer [redacted]"); } function sessionName(raw) { const clean = typeof raw === "string" ? displayText(raw) : "[unavailable: non-string session name]"; return { name: clean.slice(0, 512), nameTruncated: clean.length > 512 ? true : void 0 }; } function readSessionName(manager) { try { return sessionName(manager.getSessionName() ?? "Current session"); } catch { return { name: "[unavailable: invalid stored session name]" }; } } function readSessionId(manager) { try { const id = manager.getSessionId(); if (typeof id !== "string" || !id.length || id.length > 512) return "[unavailable: invalid or over-budget session ID]"; return displayText(id) || "[unavailable: blank session ID]"; } catch { return "[unavailable: invalid session ID]"; } } function capture(input, maxChars = 32768) { let budget = maxChars; let nodes = 0; let truncated = false; const seen = /* @__PURE__ */ new WeakSet(); function text(value) { const clean = displayText(value); const length = Math.min(clean.length, Math.max(0, budget)); budget -= length; if (length < clean.length) truncated = true; return clean.slice(0, length); } function visit(value, depth) { if (++nodes > 2048 || depth > 12 || budget <= 0) { truncated = true; return "[truncated]"; } budget -= 8; if (value === null || value === void 0) return null; if (typeof value === "string") return text(value); if (typeof value === "boolean") return value; if (typeof value === "number") return Number.isFinite(value) ? value : String(value); if (typeof value !== "object") { truncated = true; return `[unsupported ${typeof value}]`; } if (seen.has(value)) { truncated = true; return "[circular]"; } seen.add(value); if (Array.isArray(value)) { const result2 = []; for (let index = 0; index < value.length; index++) { if (budget <= 0 || nodes >= 2048) { truncated = true; break; } const descriptor = Object.getOwnPropertyDescriptor(value, String(index)); if (descriptor?.get || descriptor?.set) { truncated = true; result2.push("[accessor omitted]"); } else result2.push(visit(descriptor?.value, depth + 1)); } seen.delete(value); return result2; } const record = value; const type = Object.getOwnPropertyDescriptor(record, "type")?.value; const mimeType = Object.getOwnPropertyDescriptor(record, "mimeType")?.value; const data = Object.getOwnPropertyDescriptor(record, "data")?.value; const raster = type === "image" && typeof mimeType === "string" && /^(image\/(png|jpeg|gif|webp))$/.test(mimeType) && typeof data === "string" && data.length <= Math.min(16384, Math.max(0, budget / 2)) && /^[A-Za-z0-9+/]*={0,2}$/.test(data); const result = /* @__PURE__ */ Object.create(null); for (const key in record) { if (!Object.hasOwn(record, key)) continue; if (budget <= 0 || nodes >= 2048) { truncated = true; break; } const cleanKey = displayText(key); const name = text(cleanKey.slice(0, 256)); if (cleanKey.length > 256) truncated = true; const descriptor = Object.getOwnPropertyDescriptor(record, key); if (descriptor?.get || descriptor?.set) { truncated = true; result[name] = "[accessor omitted]"; continue; } const classifiedKey = cleanKey.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2"); result[name] = secretKey.test(classifiedKey) || /(?:^|[_-])secret[_-]?access[_-]?key$/i.test(classifiedKey) ? "[redacted]" : key === "data" && type === "image" ? raster ? text(data) : "[opaque or oversized data omitted]" : /^(thinkingSignature|thoughtSignature|textSignature)$/.test(key) ? "[opaque data omitted]" : visit(descriptor?.value, depth + 1); } seen.delete(value); return result; } return { value: visit(input, 0), truncated }; } // src/collector.ts function validIdentity(value) { return typeof value === "string" && value.length > 0 && value.length <= 512; } var Collector = class { constructor(maxCalls = 128) { this.maxCalls = maxCalls; } maxCalls; startedAt = Date.now(); calls = /* @__PURE__ */ new Map(); partialAt = /* @__PURE__ */ new Map(); sequence = 0; dropped = 0; invalidEvents = 0; admit(event) { if (validIdentity(event.toolCallId) && validIdentity(event.toolName)) return true; this.invalidEvents++; return false; } fenceParent(call, parent) { if (parent !== void 0 && !validIdentity(parent)) { const changed = call.parentUnavailable !== "Invalid or over-budget parent ID; relationship unavailable" || call.parentOccurrenceId !== void 0; call.parentId = void 0; call.parentOccurrenceId = void 0; call.parentUnavailable = "Invalid or over-budget parent ID; relationship unavailable"; return changed; } return false; } create(event, args, anchor) { const parentId = validIdentity(event.parentToolCallId) ? event.parentToolCallId : void 0; const parent = parentId ? this.active(parentId) : void 0; const ambiguousParent = event.parentToolCallId !== void 0 && this.list().filter((item) => item.id === event.parentToolCallId && item.status === "running").length > 1; const call = { id: event.toolCallId, occurrenceId: `call-${++this.sequence}`, parentId, parentUnavailable: ambiguousParent ? "Overlapping running parent IDs; relationship unavailable" : void 0, parentOccurrenceId: parent?.status === "running" ? parent.occurrenceId : void 0, name: displayText(event.toolName), status: "running", args: capture(args, 8192), branchAnchor: parent?.status === "running" ? parent.branchAnchor : validIdentity(anchor) ? anchor : null, correlationUnavailable: anchor !== null && !validIdentity(anchor) ? true : void 0 }; this.fenceParent(call, event.parentToolCallId); this.calls.set(call.occurrenceId, call); while (this.calls.size > this.maxCalls) { const first = this.calls.keys().next().value; if (first === void 0) break; this.calls.delete(first); this.partialAt.delete(first); this.dropped++; } return call; } active(rawId) { const running = this.list().filter((call) => call.id === rawId && call.status === "running"); if (running.length > 1) { for (const call of running) call.correlationUnavailable = true; return void 0; } return running[0]; } start(event, anchor) { if (!this.admit(event)) return; const now = Date.now(); const call = this.create(event, event.args, anchor); call.observedStartedAt = now; if (this.list().filter((parent) => parent.id === call.id && parent.branchAnchor === call.branchAnchor).length === 1) { for (const child of this.calls.values()) if (child.parentId === call.id && !child.parentOccurrenceId && !child.parentUnavailable && child.status === "running" && child.branchAnchor === call.branchAnchor) child.parentOccurrenceId = call.occurrenceId; } const occurrences = this.list().filter((item) => item.id === call.id && item.branchAnchor === call.branchAnchor); if (occurrences.length > 1) { for (const occurrence of occurrences) occurrence.correlationUnavailable = true; for (let i = 0; i < this.calls.size; i++) for (const child of this.calls.values()) if (child.parentOccurrenceId && this.calls.get(child.parentOccurrenceId)?.correlationUnavailable) child.correlationUnavailable = true; } this.active(event.toolCallId); } update(event, anchor) { if (!this.admit(event)) return true; const now = Date.now(); let call = this.active(event.toolCallId); if (!call && this.list().some((call2) => call2.id === event.toolCallId && call2.status === "running")) return false; call ??= this.create(event, event.args, anchor); const parentChanged = this.fenceParent(call, event.parentToolCallId); if (now - (this.partialAt.get(call.occurrenceId) ?? -Infinity) < 250) return parentChanged; this.partialAt.set(call.occurrenceId, now); call.result = capture(event.partialResult); return true; } end(event, anchor) { if (!this.admit(event)) return; const now = Date.now(); const running = this.list().filter((call2) => call2.id === event.toolCallId && call2.status === "running"); const call = this.active(event.toolCallId) ?? this.create(event, "[not captured]", anchor); if (running.length > 1) { call.correlationUnavailable = true; call.parentOccurrenceId = void 0; } this.fenceParent(call, event.parentToolCallId); call.status = event.isError ? "error" : "ok"; call.durationMs = typeof event.durationMs === "number" && Number.isFinite(event.durationMs) && event.durationMs >= 0 ? event.durationMs : void 0; call.observedEndedAt = now; call.result = capture(event.result); } settle() { for (const call of this.calls.values()) if (call.status === "running") call.status = "unfinished"; } list() { return [...this.calls.values()]; } }; // src/context.ts import { createHash } from "node:crypto"; import { buildSessionProjection as buildSessionProjection2 } from "@earendil-works/pi-coding-agent"; function object(value) { return value && typeof value === "object" && !Array.isArray(value) ? value : void 0; } function captureContext(input, source, leafId) { const result = { source, leafId, totalMessages: input.length, messages: [], segments: [], incomplete: false }; const occurrences = /* @__PURE__ */ new Map(); let budget = 1048576; for (const message of input) { if (result.segments.length >= 4e3 || budget <= 64) { result.incomplete = true; break; } const raw = capture(message, Math.min(8192, budget)); const encoded = JSON.stringify(raw); budget -= encoded.length; result.incomplete ||= raw.truncated; const data = object(raw.value); const role = typeof data?.role === "string" ? data.role : "unknown"; const index = result.messages.length; result.messages.push(raw); const hash = createHash("sha256").update(encoded).digest("hex").slice(0, 20); const occurrence = occurrences.get(hash) ?? 0; occurrences.set(hash, occurrence + 1); const content = data?.content === "" && data?.sections ? data.sections : data?.content; const blocks = Array.isArray(content) && content.length ? content : [content ?? data?.sections ?? raw.value]; for (const [blockIndex, block] of blocks.entries()) { if (result.segments.length >= 4e3) { result.incomplete = true; break; } const item = object(block); const kind = typeof item?.type === "string" ? item.type : role; const category = role === "system" || role === "developer" ? "system" : role === "user" ? "user" : role === "toolResult" || role === "tool" ? "toolResult" : role === "assistant" && kind === "toolCall" ? "toolCall" : role === "assistant" ? "assistant" : "other"; const preview = item?.name ?? item?.text ?? item?.thinking ?? block; const timestamp = typeof data?.timestamp === "string" ? data.timestamp : typeof data?.timestamp === "number" && Number.isFinite(data.timestamp) && Math.abs(data.timestamp) < 864e13 ? new Date(data.timestamp).toISOString() : void 0; result.segments.push({ id: `${source}-${hash}-${occurrence}-${blockIndex}`, position: result.segments.length + 1, messageIndex: index, ...Array.isArray(content) && content.length ? { blockIndex } : {}, role, kind, category, preview: (typeof preview === "string" ? preview : JSON.stringify(preview)).slice(0, 240), ...timestamp ? { timestamp } : {} }); } } result.incomplete ||= result.messages.length < input.length; return result; } function sessionContext(manager, index) { const leafId = recordedLeaf(manager, index.duplicates); const validation = leafId ? ancestry(manager, leafId, index) : { path: [], issue: "No unambiguous active leaf" }; if (validation.issue) return { source: "session-derived", leafId, totalMessages: 0, messages: [], segments: [], incomplete: true, unavailable: validation.issue }; try { return captureContext(buildSessionProjection2(validation.path, leafId).messages, "session-derived", leafId); } catch { return { source: "session-derived", leafId, totalMessages: 0, messages: [], segments: [], incomplete: true, unavailable: "Native context projection unavailable" }; } } // src/projection.ts import { getCurrentSystemMessage, getCurrentSystemPrompt, getCurrentTools, getInitialSystemMessage } from "@earendil-works/pi-ai"; import { buildSessionProjection as buildSessionProjection3, parseSkillBlock } from "@earendil-works/pi-coding-agent"; // src/cache-history.ts import { calculateCost } from "@earendil-works/pi-ai"; var ROW_LIMIT = 200; var TREND_LIMIT = 32; var metricKeys = ["input", "cacheRead", "cacheWrite", "promptTokens", "promptCost", "estimatedSavings"]; function number(value) { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; } function sum(values) { if (values.some((value) => value === null)) return null; return number(values.reduce((total, value) => total + (value ?? 0), 0)); } function label(value) { return typeof value === "string" ? displayText(value).slice(0, 128) : "unavailable"; } function emptyTotals() { return { count: 0, input: 0, cacheRead: 0, cacheWrite: 0, promptTokens: 0, hitRatePercent: null, promptCost: 0, estimatedSavings: 0 }; } function pricedUsage(usage, input, read, write) { return { ...usage, input, cacheRead: read, cacheWrite: write, cacheWrite1h: Math.min(write, number(usage.cacheWrite1h) ?? 0), output: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }; } function costs(usage, model, input, read, write) { const fallback = model ? calculateCost(model, pricedUsage(usage, input, read, write)) : void 0; let reported = false; let estimated = false; function component(tokens, actual, estimate) { if (tokens === 0) return 0; const value = number(actual); if (value !== null && value > 0) { reported = true; return value; } const candidate = number(estimate); if (candidate !== null) estimated = true; return candidate; } const inputCost = component(input, usage.cost?.input, fallback?.input); const readCost = component(read, usage.cost?.cacheRead, fallback?.cacheRead); const writeCost = component(write, usage.cost?.cacheWrite, fallback?.cacheWrite); const inputRate = input > 0 ? inputCost === null ? null : inputCost / input : model && read > 0 ? number( calculateCost(model, pricedUsage(usage, Math.min(1, read), read - Math.min(1, read), write)).input / Math.min(1, read) ) : null; const probe = Math.min(1, input + write); const fromInput = Math.min(input, probe); const readRate = read > 0 ? readCost === null ? null : readCost / read : model && probe > 0 ? number( calculateCost(model, pricedUsage(usage, input - fromInput, probe, write - (probe - fromInput))).cacheRead / probe ) : null; const promptCost = sum([inputCost, readCost, writeCost]); return { promptCost, inputRate, readRate, paidRate: input + write > 0 ? divide(sum([inputCost, writeCost]), input + write) : null, source: promptCost === null ? "unavailable" : reported && estimated ? "mixed" : estimated ? "model-estimate" : "reported" }; } function divide(value, denominator) { return value === null || denominator <= 0 ? null : number(value / denominator); } function cacheHistory(manager, index, resolveModel = () => void 0) { const rawLeaf = manager.getLeafId(); const leaf = typeof rawLeaf === "string" && rawLeaf.length > 0 && rawLeaf.length <= 512 ? rawLeaf : null; const walked = leaf === null ? { path: [] } : ancestry(manager, leaf, index); const report = { leafId: leaf, records: [], totalRecords: 0, omittedRecords: 0, totals: emptyTotals(), trend: [], complete: !walked.issue, unavailable: walked.issue }; if (walked.issue || rawLeaf !== null && (leaf === null || !index.get(leaf))) { report.complete = false; report.unavailable ??= "Missing or invalid active leaf"; return report; } const providers = /* @__PURE__ */ new Set(); let epoch = 0; let previous; let accountingComplete = true; for (const entry of walked.path) { const boundary = entry.type === "compaction" || entry.type === "branch_summary"; if (boundary) { epoch++; previous = void 0; } const message = entry.type === "message" && entry.message.role === "assistant" ? entry.message : void 0; const usage = message?.usage ?? (entry.type === "usage" || boundary ? entry.usage : void 0); if (!message && entry.type !== "usage" && !(boundary && entry.usage !== void 0)) continue; const provider = message?.provider ?? (entry.type === "usage" ? entry.provider : void 0); const model = message?.model ?? (entry.type === "usage" ? entry.model : void 0); const record = { entryId: entry.id, epoch, kind: message ? "assistant" : entry.type === "usage" ? entry.kind === "cache_warm" ? "cache_warm" : "usage" : entry.type, provider: label(provider), model: label(model), timestamp: label(entry.timestamp), status: message?.stopReason === "error" ? "error" : message?.stopReason === "aborted" ? "cancelled" : "recorded", input: null, cacheRead: null, cacheWrite: null, promptTokens: null, hitRatePercent: null, promptCost: null, estimatedSavings: null, costSource: "unavailable", comparison: null }; const input = number(usage?.input); const read = number(usage?.cacheRead); const write = number(usage?.cacheWrite); const promptTokens = sum([input, read, write]); const valid = usage && input !== null && read !== null && write !== null && promptTokens !== null; const startedAt = number(message?.timestamp); if (valid) { Object.assign(record, { input, cacheRead: read, cacheWrite: write, promptTokens }); const known = promptTokens > 0 && (read + write > 0 || message && providers.has(provider ?? "")); if (message && read + write > 0 && typeof provider === "string") providers.add(provider); record.hitRatePercent = known ? read / promptTokens * 100 : null; const pricing = costs( usage, typeof provider === "string" && typeof model === "string" ? resolveModel(provider, model) : void 0, input, read, write ); record.promptCost = pricing.promptCost; record.costSource = pricing.source; record.estimatedSavings = !known ? null : read === 0 ? 0 : pricing.inputRate !== null && pricing.readRate !== null ? number(read * Math.max(0, pricing.inputRate - pricing.readRate)) : null; const prior = previous?.record; if (message && record.hitRatePercent !== null && prior?.hitRatePercent != null && prior.promptTokens !== null) { const eligible = Math.min(prior.promptTokens, promptTokens); const rebilled = Math.max(0, eligible - read); const delta = record.hitRatePercent - prior.hitRatePercent; record.comparison = { previousEntryId: prior.entryId, hitRateDeltaPercent: delta, hitRateLossPercent: Math.max(0, -delta), promptTokenDelta: promptTokens - prior.promptTokens, cacheReadDelta: read - (prior.cacheRead ?? 0), eligibleTokens: eligible, rebilledTokens: rebilled, estimatedMissPremium: pricing.paidRate !== null && pricing.readRate !== null ? number(rebilled * Math.max(0, pricing.paidRate - pricing.readRate)) : null, modelChanged: previous?.provider !== provider || previous?.model !== model, requestStartGapMs: startedAt !== null && previous?.startedAt != null ? number(Math.max(0, startedAt - previous.startedAt)) : null }; } } else report.complete = false; if (message) { previous = { record, startedAt, provider, model }; report.trend.push({ entryId: record.entryId, hitRatePercent: record.hitRatePercent, epoch: record.epoch }); if (report.trend.length > TREND_LIMIT) report.trend.shift(); } report.totalRecords++; report.totals.count++; for (const key of metricKeys) report.totals[key] = sum([report.totals[key], record[key]]); if (record.hitRatePercent === null) accountingComplete = false; report.records.push(record); if (report.records.length > ROW_LIMIT) report.records.shift(); } report.omittedRecords = report.totalRecords - report.records.length; report.totals.hitRatePercent = accountingComplete && (report.totals.promptTokens ?? 0) > 0 && report.totals.cacheRead !== null ? report.totals.cacheRead / report.totals.promptTokens * 100 : null; return report; } // src/correlation.ts function correlatedCalls(rawIds, anchor, all) { if (!anchor) return []; const multiplicity = /* @__PURE__ */ new Map(); for (const call of all) if (call.branchAnchor === anchor) multiplicity.set(call.id, (multiplicity.get(call.id) ?? 0) + 1); const ids = new Set( all.filter( (call) => (rawIds.has(call.id) || call.parentId !== void 0 && rawIds.has(call.parentId) && (!call.parentOccurrenceId || !all.some((parent) => parent.occurrenceId === call.parentOccurrenceId))) && call.branchAnchor === anchor && (!call.parentOccurrenceId || !all.some((parent) => parent.occurrenceId === call.parentOccurrenceId)) && !call.correlationUnavailable && (multiplicity.get(call.id) ?? 0) < 2 ).map((call) => call.occurrenceId) ); for (let i = 0; i < all.length; i++) for (const call of all) if (call.parentOccurrenceId && ids.has(call.parentOccurrenceId)) ids.add(call.occurrenceId); return all.filter((call) => ids.has(call.occurrenceId)); } // src/entry-summary.ts function readableSummary(entry) { const source = entry.type === "message" ? "content" in entry.message ? entry.message.content : void 0 : entry.type === "custom_message" ? entry.content : entry.type === "compaction" || entry.type === "branch_summary" ? entry.summary : void 0; if (source === void 0 || source === null) return { summary: "" }; const captured = capture(source, 1024); const text = (value) => { if (typeof value === "string") return value; if (!value || typeof value !== "object") return ""; if (Array.isArray(value)) return value.map(text).filter(Boolean).join(" \xB7 "); if (typeof value.text === "string") return value.text; if (value.type === "thinking") return "Thinking"; if (value.type === "image") return "Image"; if (value.type === "toolCall") return `${value.name ?? "Tool call"} ${JSON.stringify(value.arguments ?? {})}`; return ""; }; const summary = text(captured.value).replace(/\s+/g, " ").trim(); return { summary: summary.slice(0, 180), summaryTruncated: captured.truncated || summary.length > 180 ? true : void 0 }; } // src/tool-catalog.ts import { createHash as createHash2 } from "node:crypto"; function opaqueId(kind, identity) { return createHash2("sha256").update(JSON.stringify([kind, identity])).digest("hex"); } function group(kind, identity, rawLabel) { const id = opaqueId(kind, identity); const label2 = displayText(rawLabel); return { id, kind, label: label2.slice(0, 512), truncated: label2.length > 512 ? true : void 0 }; } function sourceGroup(source) { if (!source) return group("unknown", null, "Unknown source"); if (source.source === "builtin") return group("builtin", null, "Built-in"); const packageIdentity = source.source && source.source !== "auto" && source.source !== "local"; if (source.origin === "package" && (packageIdentity || source.baseDir)) { return group( "package", [source.source, source.scope, source.baseDir], packageIdentity ? source.source : source.baseDir ?? "" ); } return group("extension", [source.source, source.path, source.scope, source.origin, source.baseDir], source.path); } function projectToolCatalog(tools, active) { const activeNames = new Set(active); const occurrences = /* @__PURE__ */ new Map(); return tools.slice(0, 256).map((tool) => { const source = tool.sourceInfo; const namespace = tool.namespace?.name; const identity = opaqueId("tool", [ tool.name, source ? [source.source, source.path, source.scope, source.origin, source.baseDir] : null, namespace ]); const occurrence = occurrences.get(identity) ?? 0; occurrences.set(identity, occurrence + 1); const isActive = activeNames.has(tool.name); return { catalogId: opaqueId("catalog", [identity, occurrence]), name: displayText(tool.name).slice(0, 512), description: displayText(tool.description).slice(0, 512), metadataTruncated: [tool.name, tool.description, namespace ?? ""].some((text) => displayText(text).length > 512), sourceGroup: sourceGroup(source), namespaceGroup: namespace !== void 0 ? group("namespace", namespace, namespace) : void 0, source: source ? capture( { source: source.source, path: source.path, scope: source.scope, origin: source.origin, ...source.baseDir !== void 0 ? { baseDir: source.baseDir } : {} }, 2048 ) : void 0, exposure: tool.exposure, active: isActive, // Pi's generic nested-call predicate, not a claim about a particular runner's availability. callable: tool.exposure === "codemode" || tool.exposure === "deferred" || tool.exposure === "direct" && isActive, namespace: namespace !== void 0 ? displayText(namespace).slice(0, 512) : void 0, schema: capture(tool.parameters, 2048) }; }); } // src/projection.ts function summarize(entry, label2) { const issue = identityIssue(entry); if (issue) throw new Error(issue); const message = entry.type === "message" ? entry.message : void 0; const kind = displayText(message ? message.role : entry.type).slice(0, 512); const value = message && "content" in message ? message.content : entry; const preview = capture(value, 180).value; const name = entry.type === "custom" || entry.type === "custom_message" ? entry.customType : entry.type === "model_change" ? entry.modelId : entry.type === "thinking_level_change" ? entry.thinkingLevel : message?.role === "assistant" ? message.model : message?.role === "toolResult" ? message.toolName : void 0; const displayName = typeof name === "string" ? displayText(name) : void 0; return { id: entry.id, parentId: entry.parentId, ...readableSummary(entry), internal: ["custom", "label", "session_info", "usage"].includes(entry.type) ? true : void 0, kind, timestamp: entry.timestamp, name: displayName?.slice(0, 512), nameTruncated: displayName !== void 0 && displayName.length > 512 ? true : void 0, tokens: message?.role === "assistant" && Number.isFinite(message.usage?.totalTokens) ? message.usage?.totalTokens : void 0, status: message?.role === "toolResult" && typeof message.isError === "boolean" ? message.isError ? "error" : "success" : message?.role === "assistant" && message.stopReason === "error" ? "error" : message?.role === "assistant" && message.stopReason === "aborted" ? "cancelled" : void 0, toolCallId: message?.role === "toolResult" ? message.toolCallId : void 0, label: displayText( typeof label2 === "string" ? label2 : typeof preview === "string" ? preview : JSON.stringify(preview) ).slice(0, 180) }; } function snapshot(manager, collector, generation, revision, prompt, tools, active, skills, index = new EntryIndex(manager.getEntries()), observedContext, resolveCostModel) { const entries = index.entries; const owning = /* @__PURE__ */ new Map(); const invalidEntries = []; let invalidEntryCount = 0; const nodes = []; const leafId = recordedLeaf(manager, index.duplicates); const reserved = new Set(leafId ? ancestry(manager, leafId, index).path.map((entry) => entry.id) : []); let remaining = 1e4 - reserved.size; const included = entries.flatMap( (entry, ordinal) => reserved.has(entry.id) || remaining-- > 0 ? [{ entry, ordinal }] : [] ); for (const { ordinal, entry } of included) { const reason = index.duplicates.has(entry.id) ? "duplicate entry id" : identityIssue(entry); if (reason) { invalidEntryCount++; if (invalidEntries.length < 20) invalidEntries.push({ index: ordinal, reason, raw: capture(entry, 2048) }); continue; } const source = entry.type === "message" && entry.message.role === "assistant" ? { id: entry.id, ids: new Set( (Array.isArray(entry.message.content) ? entry.message.content : []).filter((block) => block.type === "toolCall").map((block) => block.id) ) } : entry.parentId ? owning.get(entry.parentId) : void 0; if (source) owning.set(entry.id, source); const label2 = manager.getLabel(entry.id); if (label2 !== void 0 && typeof label2 !== "string") { invalidEntryCount++; if (invalidEntries.length < 20) invalidEntries.push({ index: ordinal, reason: "non-string resolved label", raw: capture({ entry, label: label2 }, 2048) }); } const node = summarize(entry, label2); if (node.toolCallId && source?.ids.has(node.toolCallId)) node.toolAnchor = source.id; nodes.push(node); } return { protocol: 1, generation, revision, sessionId: readSessionId(manager), ...readSessionName(manager), leafId, totalEntries: entries.length, nodes, incomplete: entries.length > 1e4 || tools.length > 256 || skills.length > 256 || invalidEntryCount > 0, invalidEntryCount, invalidEntries, context: observedContext ?? sessionContext(manager, index), cache: cacheHistory(manager, index, resolveCostModel), currentPrompt: capture(prompt, 65536), tools: projectToolCatalog(tools, active), skills: skills.slice(0, 256).map((s) => ({ name: displayText(s.name).slice(0, 512), path: displayText(s.path).slice(0, 2048), pathTruncated: displayText(s.path).length > 2048, description: displayText(s.description).slice(0, 512), metadataTruncated: displayText(s.name).length > 512 || displayText(s.path).length > 2048 || displayText(s.description).length > 512 })), calls: collector.list(), droppedCalls: collector.dropped, invalidCallEvents: collector.invalidEvents, captureStartedAt: collector.startedAt }; } function branch(manager, leafId, offset, skills, index = new EntryIndex(manager.getEntries())) { if (!index.byId.has(leafId)) throw new Error("Unknown entry"); const walked = ancestry(manager, leafId, index); const { path } = walked; const projection = walked.issue ? void 0 : buildSessionProjection3(path, leafId); const target = index.get(leafId); const previousView = !walked.issue && target?.parentId ? nativeProjection(path, target.parentId) : void 0; const previous = previousView?.projection?.messages ?? []; const issue = walked.issue ?? (projection && systemReplayIssue(projection.messages)) ?? systemReplayIssue(previous); if (issue || !projection) { const unavailable = capture(`[unavailable: ${issue}]`); return { leafId, ancestryIssue: issue, entries: path.slice(offset, offset + 50).filter((entry) => !identityIssue(entry)).map((entry) => summarize(entry, manager.getLabel(entry.id))), total: path.length, offset, prompt: unavailable, previousPrompt: unavailable, sections: unavailable, declaredTools: unavailable, promptUpdates: unavailable, projection: unavailable, context: { source: "session-derived", leafId, totalMessages: 0, messages: [], segments: [], incomplete: true, unavailable: issue }, skillEvidence: unavailable }; } const historicalSystem = getCurrentSystemMessage(projection.messages); const evidence = []; const callPaths = /* @__PURE__ */ new Map(); const byPath = new Map(skills.map((skill) => [skill.path, skill])); let scanned = 0; let evidenceIncomplete = false; function spend() { if (++scanned <= 2048 && evidence.length < 256) return true; evidenceIncomplete = true; return false; } evidenceLoop: for (const entry of path) { if (identityIssue(entry)) continue; if (entry.type !== "message") continue; const m = entry.message; if (m.role === "assistant") { callPaths.clear(); const duplicateIds = /* @__PURE__ */ new Set(); const encountered = /* @__PURE__ */ new Set(); for (const block of Array.isArray(m.content) ? m.content : []) { if (!spend()) break evidenceLoop; if (block.type === "toolCall") { if (encountered.has(block.id)) duplicateIds.add(block.id); encountered.add(block.id); } if (block.type === "toolCall" && block.name === "read" && typeof block.arguments?.path === "string" && block.arguments.path.length <= 8192) { callPaths.set(block.id, block.arguments.path); } } for (const id of duplicateIds) callPaths.delete(id); } if (m.role === "user" && typeof m.content === "string") { if (!spend()) break; if (m.content.length > 8192) { evidenceIncomplete = true; continue; } const invoked = parseSkillBlock(m.content); if (invoked) evidence.push({ name: invoked.name, state: "explicitly invoked", entryId: entry.id }); } if (m.role === "toolResult" && m.isError === false) { if (!spend()) break; const path2 = callPaths.get(m.toolCallId); const skill = path2 ? byPath.get(path2) : void 0; if (skill) evidence.push({ name: skill.name, state: "successfully read", entryId: entry.id }); for (const call of Array.isArray(m.nestedCalls?.calls) ? m.nestedCalls.calls : []) { if (!spend()) break evidenceLoop; if (!call || typeof call !== "object" || call.name !== "read" || call.status !== "ok") continue; const nestedPath = call.arguments?.path; const skill2 = typeof nestedPath === "string" && nestedPath.length <= 8192 ? byPath.get(nestedPath) : void 0; if (skill2) { evidence.push({ name: skill2.name, state: "successfully read (nested metadata)", entryId: entry.id }); } } } } const capturedEvidence = capture(evidence); capturedEvidence.truncated ||= evidenceIncomplete; return { leafId, entries: path.slice(offset, offset + 50).filter((entry) => !identityIssue(entry)).map((e) => summarize(e, manager.getLabel(e.id))), total: path.length, offset, prompt: capture( historicalSystem ? getCurrentSystemPrompt(projection.messages) : "[unavailable: no stored system prompt]", 65536 ), previousPrompt: capture( previousView?.issue ? `[unavailable: ${previousView.issue}]` : getCurrentSystemMessage(previous) ? getCurrentSystemPrompt(previous) : "[unavailable: no stored system prompt]", 65536 ), sections: capture(historicalSystem?.sections), declaredTools: capture( getInitialSystemMessage(projection.messages) ? getCurrentTools(projection.messages).map((t) => ({ name: t.name, description: t.description, parameters: t.parameters })) : "[unavailable: no initial system/tool checkpoint]" ), promptUpdates: capture( path.filter((e) => e.type === "message" && e.message.role === "system").map((e) => ({ id: e.id, message: e.type === "message" ? e.message : null })) ), projection: capture( projection.entries.map((e) => ({ id: e.sourceEntry.id, messages: e.messages })), 65536 ), context: captureContext(projection.messages, "session-derived", leafId), skillEvidence: capturedEvidence }; } function detail(manager, id, leafId, collector, index = new EntryIndex(manager.getEntries())) { if (index.duplicates.has(id) || index.duplicates.has(leafId)) throw new Error("Ambiguous duplicate entry id"); const entry = index.get(id); if (!entry || !index.get(leafId)) throw new Error("Unknown entry"); const selected = ancestry(manager, id, index); const leaf = id === leafId ? selected : ancestry(manager, leafId, index); const issue = selected.issue ?? leaf.issue; if (issue) return { ancestryIssue: issue, raw: capture(entry, 65536), projected: capture(`[unavailable: ${issue}]`), calls: [] }; const projected = buildSessionProjection3(leaf.path, leafId).entries.find((e) => e.sourceEntry.id === id); const ids = /* @__PURE__ */ new Set(); if (entry.type === "message") { const m = entry.message; if (m.role === "assistant" && !identityIssue(entry)) { for (const b of Array.isArray(m.content) ? m.content : []) if (b.type === "toolCall") ids.add(b.id); } if (m.role === "toolResult") ids.add(m.toolCallId); } const toolAnchor = entry.type === "message" && entry.message.role === "assistant" ? entry.id : selected.path.slice().reverse().find( (candidate) => candidate.type === "message" && !identityIssue(candidate) && candidate.message.role === "assistant" && (Array.isArray(candidate.message.content) ? candidate.message.content : []).some( (block) => block.type === "toolCall" && ids.has(block.id) ) )?.id; return { toolAnchor, raw: capture(entry, 65536), projected: capture(projected?.messages), calls: correlatedCalls(ids, toolAnchor, collector.list()) }; } // src/resources.ts function mcpRegistrations(pi) { try { if (typeof pi.getMcpServers !== "function") return { servers: [], truncated: false, unavailable: true }; const registered = pi.getMcpServers(); return { servers: registered.slice(0, 256).map(({ name }) => { const clean = displayText(name); return { name: clean.slice(0, 512), truncated: clean.length > 512 }; }), truncated: registered.length > 256 }; } catch { return { servers: [], truncated: false, unavailable: true }; } } // src/feed.ts var SessionFeed = class { constructor(options) { this.options = options; } options; dirty = true; observed; providerObservation; observeContext(messages) { if (this.closed || this.options.signal.aborted) return; this.observed = captureContext( messages, "observed-pi-context", recordedLeaf(this.options.context().sessionManager, this.index().duplicates) ); this.observed.observedAt = Date.now(); this.changed(false); } observePayload(payload) { if (this.closed || this.options.signal.aborted) return; this.providerObservation = { observedAt: Date.now(), data: capture(payload, 65536) }; this.changed(false); } indexed; closed = false; index() { if (this.closed || this.options.signal.aborted) throw new Error("Inspector stopped"); if (!this.indexed) this.indexed = new EntryIndex(this.options.context().sessionManager.getEntries()); return this.indexed; } cached; revision = 0; stamp = ""; notification; poll; stateStamp() { const ctx = this.options.context(); const manager = ctx.sessionManager; const tools = this.options.pi.getAllTools(); const active = this.options.pi.getActiveTools(); const counted = manager; const count = typeof counted.getEntryCount === "function" ? counted.getEntryCount() : manager.getEntries().length; return JSON.stringify({ count, leaf: recordedLeaf(manager), name: readSessionName(manager), mcp: mcpRegistrations(this.options.pi), toolCount: tools.length, // Opaque catalog/group IDs also detect raw identity changes beyond the display budget. tools: projectToolCatalog(tools, active) }); } start() { if (this.options.signal.aborted || this.poll) return; this.stamp = this.stateStamp(); this.poll = setInterval(() => { if (this.options.signal.aborted) return; try { const next = this.stateStamp(); if (next !== this.stamp) { this.stamp = next; this.changed(true); } } catch { this.changed(true); } }, 1e3); this.poll.unref(); this.options.signal.addEventListener("abort", this.close, { once: true }); } changed(structural) { if (this.options.signal.aborted) return; if (structural) { this.dirty = true; this.indexed = void 0; } if (!this.notification) { this.notification = setTimeout(() => { this.notification = void 0; if (!this.options.signal.aborted) this.options.invalidate(++this.revision); }, 250); this.notification.unref(); } } snapshot() { if (this.closed || this.options.signal.aborted) throw new Error("Inspector stopped"); if (!this.cached || this.dirty) { const ctx = this.options.context(); this.cached = snapshot( ctx.sessionManager, this.options.collector, this.options.generation, this.revision, ctx.getSystemPrompt(), this.options.pi.getAllTools(), this.options.pi.getActiveTools(), this.options.skills, this.index(), this.observed, (provider, model) => ctx.modelRegistry?.find(provider, model) ); this.cached.calls = []; this.dirty = false; } return { ...this.cached, revision: this.revision, context: this.observed ?? this.cached.context, providerObservation: this.providerObservation, mcp: mcpRegistrations(this.options.pi), calls: this.options.collector.list(), droppedCalls: this.options.collector.dropped, invalidCallEvents: this.options.collector.invalidEvents }; } close = () => { this.closed = true; clearTimeout(this.notification); clearInterval(this.poll); this.notification = void 0; this.poll = void 0; this.options.signal.removeEventListener("abort", this.close); this.cached = void 0; this.indexed = void 0; this.observed = void 0; this.providerObservation = void 0; }; }; // src/server.ts import { randomBytes, timingSafeEqual } from "node:crypto"; import { readFile } from "node:fs/promises"; import { createServer } from "node:http"; function sendRevision(response, frame) { if (!response.write(frame)) response.destroy(); } async function startServer(options) { const assetBase = options.assetBase ?? new URL("../browser-dist/", import.meta.url); const assets = options.assets ?? /* @__PURE__ */ new Map([ [ "/", { type: "text/html; charset=utf-8", body: await readFile(new URL("index.html", assetBase), { signal: options.signal }) } ], [ "/app.js", { type: "text/javascript; charset=utf-8", body: await readFile(new URL("app.js", assetBase), { signal: options.signal }) } ], [ "/app.css", { type: "text/css; charset=utf-8", body: await readFile(new URL("app.css", assetBase), { signal: options.signal }) } ] ]); options.signal.throwIfAborted(); const token = randomBytes(32).toString("base64url"); const clients = /* @__PURE__ */ new Set(); const sockets = /* @__PURE__ */ new Set(); let closed = false; let origin = ""; let revision = 0; let closing; const frame = () => `id: ${revision} data: ${JSON.stringify({ protocol: 1, generation: options.generation, revision })} `; const server = createServer((req, res) => { res.setHeader("Cache-Control", "no-store"); res.setHeader("Referrer-Policy", "no-referrer"); res.setHeader("X-Content-Type-Options", "nosniff"); res.setHeader("Cross-Origin-Resource-Policy", "same-origin"); res.setHeader( "Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'" ); const fail = (status, message) => { res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8" }); res.end(message); }; if (closed || options.signal.aborted) return fail(410, "Session closed"); if (req.headers.host !== origin.slice("http://".length) || req.headers.origin !== void 0 && req.headers.origin !== origin || req.headers["sec-fetch-site"] === "cross-site") return fail(403, "Forbidden"); if (req.method !== "GET") return fail(405, "Read-only viewer"); let url; try { url = new URL(req.url ?? "/", origin); } catch { return fail(400, "Invalid URL"); } if (url.origin !== origin) return fail(403, "Forbidden"); const asset = assets.get(url.pathname); if (asset && !url.search) { res.writeHead(200, { "Content-Type": asset.type }); const body = url.pathname === "/" ? asset.body.toString().replace( "", `` ) : asset.body; res.end(body); return; } if (!url.pathname.startsWith("/api/")) return fail(404, "Not found"); const provided = req.headers["x-inspector-token"]; if (typeof provided !== "string" || Buffer.byteLength(provided) !== Buffer.byteLength(token) || !timingSafeEqual(Buffer.from(provided), Buffer.from(token))) return fail(401, "Unauthorized"); if (url.searchParams.get("generation") !== options.generation) return fail(409, "Session generation changed"); if (url.pathname === "/api/events") { if (clients.size >= 8) return fail(429, "Too many viewers"); res.writeHead(200, { "Content-Type": "text/event-stream", Connection: "keep-alive" }); clients.add(res); res.on("close", () => clients.delete(res)); sendRevision(res, frame()); return; } try { let result; if (url.pathname === "/api/snapshot") result = options.snapshot(); else if (url.pathname === "/api/branch") { const offset = url.searchParams.get("offset") ?? "0"; if (!/^\d{1,8}$/.test(offset)) return fail(400, "Invalid offset"); result = options.branch(url.searchParams.get("leaf") ?? "", Number(offset)); } else if (url.pathname === "/api/detail") { result = options.detail(url.searchParams.get("id") ?? "", url.searchParams.get("leaf") ?? ""); } else return fail(404, "Not found"); res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" }); res.end(JSON.stringify(result)); } catch { fail(400, "Unavailable session data"); } }); server.requestTimeout = 1e4; server.headersTimeout = 1e4; server.maxHeadersCount = 32; server.on("connection", (socket) => { if (sockets.size >= 32) { socket.destroy(); return; } sockets.add(socket); socket.on("close", () => sockets.delete(socket)); }); const close = () => { if (closing) return closing; closed = true; options.signal.removeEventListener("abort", abort); for (const client of clients) client.destroy(); clients.clear(); for (const socket of sockets) socket.destroy(); closing = new Promise((resolve) => server.close(() => resolve())); return closing; }; const abort = () => { void close(); }; options.signal.addEventListener("abort", abort, { once: true }); try { await new Promise((resolve, reject) => { const cancelled = () => reject(new Error("Server startup cancelled")); options.signal.addEventListener("abort", cancelled, { once: true }); const failed = (error) => { options.signal.removeEventListener("abort", cancelled); reject(error); }; server.once("error", failed); server.listen({ port: 0, host: "127.0.0.1", signal: options.signal }, () => { options.signal.removeEventListener("abort", cancelled); server.removeListener("error", failed); resolve(); }); }); options.signal.throwIfAborted(); } catch (error) { await close(); throw error; } const address = server.address(); if (!address || typeof address === "string") { await close(); throw new Error("No loopback address"); } origin = `http://127.0.0.1:${address.port}`; return { token, origin, url: `${origin}/#${token}`, invalidate(next) { if (!closed) { revision = next; for (const res of clients) sendRevision(res, frame()); } }, close }; } // src/extension.ts var BROWSER_LAUNCH_MAX_BUFFER = 16 * 1024; var defaults = { start: startServer, async launch(pi, url, signal) { const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer.exe" : "xdg-open"; const result = await pi.exec(command, [url], { signal, timeout: 5e3, maxBuffer: BROWSER_LAUNCH_MAX_BUFFER }); return !result.truncated && !result.killed && result.code === 0; } }; function registerInspector(pi, deps = defaults) { const owners = /* @__PURE__ */ new Map(); const epochs = /* @__PURE__ */ new WeakMap(); function epochFor(ctx) { let epoch = epochs.get(ctx.sessionManager); if (!epoch) { epoch = {}; epochs.set(ctx.sessionManager, epoch); } return epoch; } const alive = (owner) => !owner.controller.signal.aborted && owners.get(owner.ctx.sessionManager) === owner; async function stop(ctx) { const owner = owners.get(ctx.sessionManager); if (!owner) return; owners.delete(ctx.sessionManager); owner.controller.abort(); owner.feed?.close(); await owner.server?.close(); await owner.opening; owner.collector = void 0; } function ownerFor(ctx) { epochFor(ctx); let owner = owners.get(ctx.sessionManager); if (!owner) { owner = { controller: new AbortController(), generation: randomUUID(), ctx, skills: [] }; owners.set(ctx.sessionManager, owner); } owner.ctx = ctx; return owner; } function changed(ctx, structural = true) { const owner = owners.get(ctx.sessionManager); if (!owner || !alive(owner)) return; owner.ctx = ctx; owner.feed?.changed(structural); return owner; } pi.on("session_start", async (_event, ctx) => { const epoch = {}; epochs.set(ctx.sessionManager, epoch); await stop(ctx); if (epochs.get(ctx.sessionManager) === epoch) ownerFor(ctx); }); pi.on("session_shutdown", async (_event, ctx) => { epochs.delete(ctx.sessionManager); await stop(ctx); }); pi.on("context_with_system", (event, ctx) => { const owner = owners.get(ctx.sessionManager); if (owner?.collector && alive(owner)) { owner.ctx = ctx; owner.feed?.observeContext(event.messages); } }); pi.on("before_provider_request", (event, ctx) => { const owner = owners.get(ctx.sessionManager); if (owner?.collector && alive(owner)) owner.feed?.observePayload(event.payload); }); pi.on("message_end", (_event, ctx) => { changed(ctx); }); pi.on("session_tree", (_event, ctx) => { changed(ctx); }); pi.on("session_compact", (_event, ctx) => { changed(ctx); }); pi.on("session_info_changed", (_event, ctx) => { changed(ctx); }); pi.on("model_select", (_event, ctx) => { changed(ctx); }); pi.on("thinking_level_select", (_event, ctx) => { changed(ctx); }); function executionAnchor(ctx, rawId) { const index = owners.get(ctx.sessionManager)?.feed?.index(); const leaf = recordedLeaf(ctx.sessionManager, index?.duplicates); const entry = ctx.sessionManager.getLeafEntry(); if (leaf && entry?.type === "message" && entry.message.role === "assistant") return leaf; return (leaf ? ancestry(ctx.sessionManager, leaf, index).path : []).slice().reverse().find( (entry2) => entry2.type === "message" && entry2.message.role === "assistant" && (Array.isArray(entry2.message.content) ? entry2.message.content : []).some( (block) => block.type === "toolCall" && block.id === rawId ) )?.id ?? leaf; } pi.on("tool_execution_start", (event, ctx) => { const owner = owners.get(ctx.sessionManager); owner?.collector?.start(event, executionAnchor(ctx, event.toolCallId)); changed(ctx, false); }); pi.on("tool_execution_update", (event, ctx) => { const owner = owners.get(ctx.sessionManager); if (owner?.collector?.update(event, recordedLeaf(ctx.sessionManager, owner?.feed?.index().duplicates))) changed(ctx, false); }); pi.on("tool_execution_end", (event, ctx) => { const owner = owners.get(ctx.sessionManager); owner?.collector?.end(event, executionAnchor(ctx, event.toolCallId)); changed(ctx, false); }); pi.on("agent_settled", (_event, ctx) => { owners.get(ctx.sessionManager)?.collector?.settle(); changed(ctx); }); async function open(owner, ctx) { try { if (!owner.server) { const accepted = await ctx.ui.confirm( "Open Session Inspector?", "Serve this session's prompts, code and tool outputs to a local browser and record bounded context, provider payload and child results in memory? Redaction is incomplete. Nothing is uploaded or saved.", { signal: owner.controller.signal } ); if (!alive(owner) || !accepted) return; const options = ctx.getSystemPromptOptions(); owner.skills = (options.skills ?? []).slice(0, 257).map((s) => ({ name: s.name, path: s.filePath, description: s.description })); owner.collector = new Collector(); owner.feed = new SessionFeed({ pi, context: () => owner.ctx, collector: owner.collector, skills: owner.skills, generation: owner.generation, signal: owner.controller.signal, invalidate: (revision) => { if (alive(owner)) owner.server?.invalidate(revision); } }); const server = await deps.start({ // This eager entry module has the same package-root depth in src and dist. // Pass the base explicitly so server chunks never resolve assets from their own directory. assetBase: new URL("../browser-dist/", import.meta.url), generation: owner.generation, signal: owner.controller.signal, snapshot: () => owner.feed?.snapshot(), branch: (id, offset) => branch(ctx.sessionManager, id, offset, owner.skills, owner.feed?.index()), detail: (id, leaf) => detail(ctx.sessionManager, id, leaf, owner.collector ?? new Collector(), owner.feed?.index()) }); if (!alive(owner)) { await server.close(); return; } owner.server = server; owner.feed.start(); } if (!alive(owner)) return; const url = owner.server.url; let launched = false; try { launched = await deps.launch(pi, url, owner.controller.signal); } catch { } if (!alive(owner)) return; ctx.ui.notify( `${launched ? "Session Inspector" : "Browser unavailable; open privately"}: ${url} /inspect stop revokes this URL.`, launched ? "info" : "warning" ); } catch { if (!alive(owner)) return; owner.collector = void 0; owner.feed?.close(); owner.feed = void 0; await owner.server?.close(); owner.server = void 0; if (alive(owner)) ctx.ui.notify( "Could not open Session Inspector. Build its browser assets first; see the local README.", "error" ); } } const command = { description: "Open a private, read-only live session web inspector", getArgumentCompletions: (prefix) => ["stop"].filter((s) => s.startsWith(prefix)).map((value) => ({ value, label: value })), handler: async (args, ctx) => { const route = args.trim(); if (route !== "" && route !== "stop") { if (ctx.hasUI) { ctx.ui.notify("Usage: /inspect [stop]", "warning"); return; } throw new Error("Usage: /inspect [stop]"); } if (route === "stop") { const epoch = epochFor(ctx); await stop(ctx); if (ctx.hasUI && epochs.get(ctx.sessionManager) === epoch) ctx.ui.notify("Session Inspector stopped; URL revoked.", "info"); return; } if (ctx.mode !== "tui") { if (ctx.hasUI) { ctx.ui.notify("Opening Session Inspector requires TUI mode. Stop remains available.", "warning"); return; } throw new Error("Opening Session Inspector requires TUI mode."); } const owner = ownerFor(ctx); if (owner.opening) return; owner.opening = open(owner, ctx); try { await owner.opening; } finally { owner.opening = void 0; } } }; pi.registerCommand("inspect", command); pi.registerCommand("session-inspector", command); } export { registerInspector as default }; //# sourceMappingURL=index.ts.map