import type { SavedObserver } from './checkpoint.ts'; import { randomUUID } from 'node:crypto'; import type { AssistantMessage, Message, UserMessage } from '@earendil-works/pi-ai'; import { eventKey, isRecord, parseReport } from './evidence.ts'; import { SUPERVISOR_PROMPT } from './prompt.ts'; import { requestWithDeadline } from './transport.ts'; import { pauseReason } from './types.ts'; import type { EvidenceEvent, Observation, ObserverOptions, ObserverState, PauseReason, Snapshot, TokenUsage, } from './types.ts'; function bytes(value: unknown): number { return Buffer.byteLength(typeof value === 'string' ? value : JSON.stringify(value)); } function tokenCount(value: unknown): value is number { return typeof value === 'number' && Number.isFinite(value) && value >= 0; } function readUsage(value: unknown): TokenUsage | null { if ( !isRecord(value) || !tokenCount(value.input) || !tokenCount(value.output) || !tokenCount(value.cacheRead) || !tokenCount(value.cacheWrite) ) { return null; } return { input: value.input, output: value.output, cacheRead: value.cacheRead, cacheWrite: value.cacheWrite, }; } function nextBatch( events: readonly EvidenceEvent[], accepted: number, batchBytes: number, ): EvidenceEvent[] { const batch: EvidenceEvent[] = []; let size = 0; for (const event of events.slice(accepted)) { const eventBytes = bytes(event); if (batch.length > 0 && size + eventBytes > batchBytes) { break; } batch.push(event); size += eventBytes; } return batch; } /** In-memory observer. Transport and UI are injected; neither can edit the worker. */ export class SupervisorObserver { readonly onCommit: NonNullable; readonly request: ObserverOptions['request']; readonly onChange: NonNullable; readonly inputLimit: number; readonly maxOutputTokens: number; readonly timeoutMs: number; readonly batchBytes: number; generation = 0; active = false; task: Promise = Promise.resolve(); sessionId: string = randomUUID(); snapshot: Snapshot | null = null; keys: string[] = []; accepted = 0; skipped = 0; messages: Message[] = []; report: Observation[] = []; knownIds = new Set(); contextTokens = bytes(SUPERVISOR_PROMPT) + 128; usage: TokenUsage | null = null; paused: PauseReason | '' = ''; busy = false; controller: AbortController | null = null; reviews = 0; constructor({ request, onChange = () => {}, onCommit = () => {}, contextWindow, maxOutputTokens = 4096, timeoutMs = 240_000, batchBytes = 32_000, }: ObserverOptions) { const limits = [contextWindow, maxOutputTokens, batchBytes, timeoutMs]; if ( limits.some((value) => !Number.isSafeInteger(value) || value <= 0) || contextWindow <= maxOutputTokens + 2048 ) { throw new Error('invalid-config'); } this.onCommit = onCommit; this.request = request; this.onChange = onChange; this.inputLimit = contextWindow - maxOutputTokens - 2048; this.maxOutputTokens = maxOutputTokens; this.timeoutMs = timeoutMs; this.batchBytes = batchBytes; } private resetState(): void { this.sessionId = randomUUID(); this.snapshot = null; this.keys = []; this.accepted = 0; this.skipped = 0; this.messages = []; this.report = []; this.knownIds = new Set(); this.contextTokens = bytes(SUPERVISOR_PROMPT) + 128; this.usage = null; this.paused = ''; this.busy = false; this.controller = null; this.reviews = 0; } status(): ObserverState { return { active: this.active, busy: this.busy, paused: this.paused, reviewed: this.accepted - this.skipped, pending: (this.snapshot?.events.length ?? this.accepted) - this.accepted, reviews: this.reviews, contextTokens: this.contextTokens, usage: this.usage ? { ...this.usage } : null, report: structuredClone(this.report), }; } private emit(): void { // A disappearing UI must not turn a background failure into an unhandled rejection. try { this.onChange(this.status()); } catch { /* The host may already be gone. */ } } private cancel(): void { this.generation += 1; this.controller?.abort(); this.controller = null; this.busy = false; } start(snapshot: Snapshot): void { this.cancel(); this.resetState(); this.active = true; this.offer(snapshot); } stop(): void { this.cancel(); this.active = false; this.messages = []; this.snapshot = null; this.keys = []; this.knownIds.clear(); this.emit(); } /** Start at an explicit boundary, preserving the worker's execution context. */ clear(snapshot: Snapshot): void { this.cancel(); this.resetState(); this.active = true; this.snapshot = structuredClone(snapshot); this.keys = snapshot.events.map(eventKey); this.accepted = snapshot.events.length; this.skipped = this.accepted; const context = snapshot.events.find((event) => event.type === 'execution_context'); const initial = { source: 'review-boundary', skippedEarlierEvents: snapshot.events.length, ...(context ? { executionContext: context } : {}), }; this.messages = [{ role: 'user', content: JSON.stringify(initial), timestamp: Date.now() }]; if (context) { this.knownIds.add(context.id); } this.contextTokens += bytes(this.messages) + 128; this.commit(); this.emit(); } offer(snapshot: Snapshot): void { if (!this.active) { return; } const keys = snapshot.events.map(eventKey); const diverged = this.snapshot !== null && (this.snapshot.sourceId !== snapshot.sourceId || this.keys.some((key, index) => keys[index] !== key)); if (diverged) { this.cancel(); this.resetState(); } this.snapshot = structuredClone(snapshot); this.keys = keys; this.pump(); this.emit(); } retry(snapshot: Snapshot): void { if (this.paused === 'storage-failed') { this.commit(); } this.paused = ''; this.offer(snapshot); } private pump(): void { if ( !this.active || this.busy || this.paused !== '' || !this.snapshot || this.accepted >= this.snapshot.events.length ) { return; } const generation = this.generation; this.busy = true; // drain handles failures; task retains the promise so callers can await quiescence. this.task = this.drain(generation).finally(() => { if (generation !== this.generation) { return; } this.busy = false; this.controller = null; this.emit(); }); } private acceptResponse( response: AssistantMessage, batch: EvidenceEvent[], messages: Message[], estimate: number, ): void { const ids = new Set([...this.knownIds, ...batch.map((event) => event.id)]); const report = parseReport(response, ids); this.messages = [...messages, structuredClone(response)]; this.knownIds = ids; this.accepted += batch.length; this.report = report; this.reviews += 1; this.usage = readUsage(response.usage); const total = this.usage ? Object.values(this.usage).reduce((sum, count) => sum + count, 0) : 0; this.contextTokens = total > 0 ? total + 128 : estimate + bytes(response) + 128; this.commit(); this.emit(); } private async reviewBatch(batch: EvidenceEvent[], generation: number): Promise { const user: UserMessage = { role: 'user', timestamp: Date.now(), content: JSON.stringify({ source: 'session-evidence', entries: batch }), }; // Bytes conservatively estimate new text; normalized usage accounts for the cached prefix. const estimate = this.contextTokens + bytes(user) + 128; if (estimate > this.inputLimit) { throw new Error('context-limit'); } const messages = [...this.messages, user]; const controller = new AbortController(); this.controller = controller; const response = await requestWithDeadline( () => this.request({ systemPrompt: SUPERVISOR_PROMPT, messages: structuredClone(messages), signal: controller.signal, sessionId: this.sessionId, maxTokens: this.maxOutputTokens, }), controller, this.timeoutMs, ); if (generation !== this.generation || !this.active) { return; } this.acceptResponse(response, batch, messages, estimate); } private async drain(generation: number): Promise { try { // Sequential requests preserve the exact prefix and use a single inference slot. while ( generation === this.generation && this.active && this.snapshot !== null && this.accepted < this.snapshot.events.length ) { await this.reviewBatch( nextBatch(this.snapshot.events, this.accepted, this.batchBytes), generation, ); } } catch (error) { if (generation !== this.generation || !this.active) { return; } this.paused = pauseReason(error); } } checkpoint(): SavedObserver { if (!this.snapshot) { throw new Error('invalid-checkpoint'); } return structuredClone({ checkpoint: { version: 1, sessionId: this.sessionId, sourceId: this.snapshot.sourceId, keys: this.keys.slice(0, this.accepted), skipped: this.skipped, reviews: this.reviews, contextTokens: this.contextTokens, knownIds: [...this.knownIds], }, messages: this.messages, }); } private commit(): void { try { this.onCommit(this.checkpoint()); } catch { this.paused = 'storage-failed'; throw new Error('storage-failed'); } } resume(saved: SavedObserver, snapshot: Snapshot): void { const state = saved.checkpoint; const keys = snapshot.events.map(eventKey); if ( state.sourceId !== snapshot.sourceId || state.keys.some((key, index) => keys[index] !== key) ) { throw new Error('source-changed'); } const knownIds = new Set(state.knownIds); const last = saved.messages.findLast((message) => message.role === 'assistant'); const report = last ? parseReport(last, knownIds) : []; this.cancel(); this.resetState(); this.active = true; this.sessionId = state.sessionId; this.snapshot = structuredClone(snapshot); this.keys = keys; this.accepted = state.keys.length; this.skipped = state.skipped; this.reviews = state.reviews; this.contextTokens = state.contextTokens; this.knownIds = knownIds; this.messages = structuredClone(saved.messages); this.report = report; this.usage = last ? readUsage(last.usage) : null; this.commit(); this.pump(); this.emit(); } async idle(): Promise { await this.task; } }