import { createHash } from 'node:crypto'; import type { ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent'; import type { EvidenceEvent, Observation, Snapshot } from './types.ts'; export function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } export function isArray(value: unknown): value is unknown[] { return Array.isArray(value); } function digest(value: unknown): string { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); } // Only actual text and tool calls are evidence. Hidden reasoning and binary // attachments are marked as omitted, so the observer cannot infer their content. function contentBlock(block: unknown): Record { if (!isRecord(block)) { return { type: 'omitted', originalType: 'unknown' }; } if (block.type === 'text' && typeof block.text === 'string') { return { type: 'text', text: block.text }; } if (block.type === 'toolCall') { return { type: 'toolCall', id: block.id, name: block.name, arguments: block.arguments }; } return { type: 'omitted', originalType: block.type }; } function contentBlocks(content: unknown): Record[] { if (typeof content === 'string') { return [{ type: 'text', text: content }]; } return isArray(content) ? content.map(contentBlock) : []; } function messageEvent(id: string, message: unknown): EvidenceEvent | undefined { if (!isRecord(message) || typeof message.role !== 'string') { return undefined; } if (!['user', 'assistant', 'toolResult', 'custom'].includes(message.role)) { return undefined; } const event: EvidenceEvent = { id, type: 'message', role: message.role, content: contentBlocks(message.content), }; switch (message.role) { case 'assistant': event.stopReason = message.stopReason; break; case 'custom': event.customType = message.customType; break; case 'toolResult': event.toolCallId = message.toolCallId; event.toolName = message.toolName; event.isError = message.isError; break; } return event; } function captureEntry(entry: SessionEntry): EvidenceEvent | undefined { if (entry.type === 'message') { return messageEvent(entry.id, entry.message); } if (entry.type === 'compaction' || entry.type === 'branch_summary') { return { id: entry.id, type: entry.type, summary: entry.summary }; } return undefined; } export function captureSession( ctx: Pick, ): Snapshot { const instructions = { type: 'execution_context', model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : 'unknown', instructions: ctx.getSystemPrompt(), }; const events: EvidenceEvent[] = [ { id: `context-${digest(instructions).slice(0, 16)}`, ...instructions }, ]; for (const entry of ctx.sessionManager.getBranch()) { const event = captureEntry(entry); if (event) { events.push(event); } } // Detach from Pi's live tree before starting asynchronous work. return structuredClone({ sourceId: ctx.sessionManager.getSessionId(), events }); } export function eventKey(event: EvidenceEvent): string { return `${event.id}:${digest(event)}`; } function responseText(response: unknown): string { if (!isRecord(response) || response.stopReason !== 'stop' || !isArray(response.content)) { throw new Error('invalid-response'); } return response.content .map((block) => { if (!isRecord(block) || block.type === 'toolCall') { throw new Error('invalid-response'); } if (block.type !== 'text') { return ''; } if (typeof block.text !== 'string') { throw new Error('invalid-response'); } return block.text; }) .join('\n') .trim(); } function boundedText(value: unknown, limit: number): string { if (typeof value !== 'string' || value.trim().length === 0 || value.length > limit) { throw new Error('invalid-response'); } return value; } function parseObservation(value: unknown, evidenceIds: ReadonlySet): Observation { if ( !isRecord(value) || (value.confidence !== 'observed' && value.confidence !== 'hypothesis') || !isArray(value.evidence) || value.evidence.length === 0 || value.evidence.length > 12 ) { throw new Error('invalid-response'); } const evidence = value.evidence.map((id) => { if (typeof id !== 'string' || !evidenceIds.has(id)) { throw new Error('invalid-response'); } return id; }); return { summary: boundedText(value.summary, 600), evidence: [...new Set(evidence)], confidence: value.confidence, suggestion: boundedText(value.suggestion, 1600), check: boundedText(value.check, 1000), }; } function withoutFence(text: string): string { if (!text.startsWith('```') || !text.endsWith('\n```')) { return text; } const newline = text.indexOf('\n'); const opening = text.slice(0, newline).trimEnd(); return opening === '```' || opening === '```json' ? text.slice(newline + 1, -4) : text; } export function parseReport(response: unknown, evidenceIds: ReadonlySet): Observation[] { const text = responseText(response); let data: unknown; try { data = JSON.parse(withoutFence(text)); } catch { throw new Error('invalid-response'); } if (!isRecord(data) || !isArray(data.observations) || data.observations.length > 6) { throw new Error('invalid-response'); } return data.observations.map((value) => parseObservation(value, evidenceIds)); }