import { randomUUID } from 'crypto'; import type { CanonicalEvent, EventRepository } from './framework/events/index.js'; import { EventDeliveryService } from './framework/events/index.js'; import { MailboxDispatcher, NotificationProjector, type HostNotificationSink, type MailboxAcceptanceLevel, type MailboxRepository, } from './framework/mailbox/index.js'; export const DEFAULT_SHORT_MONITOR_MAX_CHARS = 500; export const DEFAULT_MONITOR_RETRY_DELAYS_MS = [ 250, 1_000, 4_000, 15_000, 30_000, ] as const; export interface CanonicalMonitorOptions { consumerId?: string; format: (event: CanonicalEvent) => T; /** Legacy stdout/channel compatibility sink; receives presented payload only. */ sink?: (value: T) => void | Promise; /** Platform Host Adapter; receives stable notification/item/Event identities. */ notificationSink?: HostNotificationSink; /** Called after the attempt is durable, before the sink is invoked. */ onAttemptRecorded?: (event: CanonicalEvent) => void; onError?: (error: unknown, event: CanonicalEvent) => void; /** Repository/pump failure that occurs before a concrete Event is selected. */ onPumpError?: (error: unknown) => void; shortMaxChars?: number; /** Persisted with the presented Mailbox payload for stable crash recovery. */ formatterVersion?: string; /** Batching hint only; eligibility remains owned by the Event Catalog. */ coalesceKey?: (event: CanonicalEvent) => string; /** Legacy sink confirmation; defaults to sink_emitted, never Agent-seen. */ acceptanceLevel?: MailboxAcceptanceLevel; /** Delays are retried in order, then the last delay is reused as a cap. */ retryDelaysMs?: readonly number[]; } function truncate(value: string, max: number): string { if (value.length <= max) return value; return max <= 1 ? value.slice(0, max) : `${value.slice(0, max - 1)}…`; } function compactEvent(value: unknown): unknown { if (!value || typeof value !== 'object') return value; const event = value as Record; return Object.fromEntries([ 'type', 'event_id', 'url', 'waited_secs', 'game_mode', ].flatMap((key) => event[key] === undefined ? [] : [[key, event[key]]])); } /** Hard serialized-character budget for the Claude Monitor short surface. */ export function fitShortMonitorPayload( value: T, maxChars = DEFAULT_SHORT_MONITOR_MAX_CHARS, ): T { const budget = Math.max(128, Math.trunc(maxChars) || DEFAULT_SHORT_MONITOR_MAX_CHARS); if (JSON.stringify(value).length <= budget || !value || typeof value !== 'object' || Array.isArray(value)) { return value; } const source = value as Record; const staged: Record = { ...source, ...(typeof source.guidance === 'string' ? { guidance: truncate(source.guidance, 180) } : {}), ...(typeof source.state === 'string' ? { state: truncate(source.state, 96) } : {}), ...(Array.isArray(source.messages) ? { messages: source.messages.slice(0, 2).map((message) => truncate(String(message), 96)) } : {}), truncated: true, }; if (JSON.stringify(staged).length <= budget) return staged as T; const originalEvents = Array.isArray(source.events) ? source.events : []; const detailsRequired = Array.isArray(source.details_required) ? source.details_required.slice(0, 8) : undefined; let events = originalEvents.map(compactEvent); let guidance = typeof source.guidance === 'string' ? truncate(source.guidance, 180) : undefined; let essential: Record = { schema: source.schema ?? 'ccl.monitor.v1', mode: source.mode ?? 'short', events, ...(detailsRequired && detailsRequired.length > 0 ? { details_required: detailsRequired } : {}), ...(guidance ? { guidance } : {}), truncated: true, }; if (JSON.stringify(essential).length <= budget) return essential as T; // Preserve event types before optional lifecycle fields such as a long URL. events = originalEvents.map((event) => ( event && typeof event === 'object' && typeof (event as Record).type === 'string' ? (event as Record).type : event )); essential = { ...essential, events }; while (guidance && JSON.stringify(essential).length > budget) { const excess = JSON.stringify(essential).length - budget; guidance = truncate(guidance, Math.max(24, guidance.length - excess - 1)); essential.guidance = guidance; if (guidance.length <= 24) break; } if (JSON.stringify(essential).length <= budget) return essential as T; // The normal one-event shape always fits 500 chars. This final guard keeps // an adapter with an unusually large event list from violating the contract. essential.events = events.slice(0, 8); delete essential.guidance; return essential as T; } /** * Serial Monitor consumer for the canonical event ledger. * * The sink owns stdout/channel success. A resolved sink accepts the durable * Mailbox item and acknowledges the short Monitor notice. Full detail is * consumed only when the Host explicitly returns `host_accepted`; a raw * stdout write (`sink_emitted`) leaves it recoverable through `ccl events`. * Output mode is fixed at process construction time. */ class NotificationProjectionError extends Error { constructor(readonly cause: unknown) { super('Unable to materialize a canonical Event notification.'); this.name = 'NotificationProjectionError'; } } export class CanonicalMonitor { readonly mode = 'short' as const; private readonly delivery: EventDeliveryService; private readonly consumerId: string; private readonly retryDelaysMs: readonly number[]; private readonly projector: NotificationProjector; private readonly dispatcher: MailboxDispatcher; private reconcileRetryCount = 0; private reconcileRetryTimer?: ReturnType; private reconcileQueued = false; private reconcileChain: Promise = Promise.resolve(); private stopped = false; constructor( private readonly repository: EventRepository & MailboxRepository, private readonly options: CanonicalMonitorOptions, ) { this.consumerId = options.consumerId ?? 'local-agent'; this.delivery = new EventDeliveryService(repository); this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_MONITOR_RETRY_DELAYS_MS; if ( this.retryDelaysMs.length === 0 || this.retryDelaysMs.some((delay) => !Number.isFinite(delay) || delay < 0) ) { throw new TypeError('retryDelaysMs must contain non-negative finite delays.'); } if (!!options.sink === !!options.notificationSink) { throw new TypeError('CanonicalMonitor requires exactly one sink or notificationSink.'); } if (options.notificationSink && options.acceptanceLevel) { throw new TypeError( 'acceptanceLevel belongs to the legacy sink; notificationSink returns its actual level.', ); } this.projector = new NotificationProjector({ repository, consumerId: this.consumerId, mode: this.mode, formatterVersion: options.formatterVersion ?? `ccl.monitor.v1:${this.mode}`, coalesceKey: options.coalesceKey, present: (event) => { const presented = options.format(event); return fitShortMonitorPayload(presented, options.shortMaxChars); }, }); this.dispatcher = new MailboxDispatcher({ repository, ownerId: randomUUID(), scope: () => { const scope = repository.currentScope(); if (!scope) return null; const next = repository.peekMailbox({ consumerId: this.consumerId, sessionId: scope.session.sessionId, modes: [this.mode], states: ['pending', 'claimed'], order: 'asc', limit: 1, })[0]; return { consumerId: this.consumerId, sessionId: scope.session.sessionId, segmentId: next?.segmentId ?? scope.segment.segmentId, mode: this.mode, }; }, retryAt: ({ attemptCount, nowMs }) => { const delay = this.retryDelaysMs[ Math.min(Math.max(0, attemptCount - 1), this.retryDelaysMs.length - 1) ]; return nowMs + delay; }, sink: options.notificationSink ?? { deliver: async (notification) => { await options.sink!(notification.payload); return { acceptedAt: new Date().toISOString(), acceptanceLevel: options.acceptanceLevel ?? 'sink_emitted', }; }, }, onAttempt: (items) => { for (const item of items) { const event = repository.eventById(item.eventId); if (!event) continue; try { options.onAttemptRecorded?.(event); } catch {} } }, onError: (error, items) => { if (!items?.length) { try { options.onPumpError?.(error); } catch {} return; } for (const item of items) { const event = repository.eventById(item.eventId); if (!event) continue; try { options.onError?.(error, event); } catch {} } }, }); } enqueue(event: CanonicalEvent): void { if (this.stopped || !this.isEligible(event)) return; try { this.projector.project(event); const repairPending = this.reconcileRetryCount > 0 || !!this.reconcileRetryTimer; this.cancelReconcileRetry(); if (repairPending) this.requestReconcile(); else this.dispatcher.notifyAvailable(); } catch (error) { try { this.options.onError?.(error, event); } catch {} this.scheduleReconcileRetry(); } } drainCurrent(): void { this.cancelReconcileRetry(); this.requestReconcile(); } /** * At owner subscription setup, never replay untouched history. A pending * current-segment notice with an earlier persisted attempt is retained so a * failed or interrupted delivery can resume. Full details remain pullable. */ suppressPendingBeforeSubscription( preserveEventIds: readonly string[] = [], ): void { if (this.stopped) return; const scope = this.repository.currentScope(); if (!scope) return; const rows = this.repository.listEvents({ sessionId: scope.session.sessionId, deliveryClasses: ['monitor_and_events'], monitorStates: ['pending'], order: 'asc', }, this.consumerId, ['monitor']); const preserved = new Set(preserveEventIds); // A previous owner may have crashed after projecting an Event into the // durable Mailbox but before the dispatcher could claim it. That item has // attemptCount=0 just like pre-subscription history, so the Event delivery // counter alone cannot distinguish the two cases. The persisted Mailbox // row is the durable handoff boundary and must survive owner restart. for (const row of rows) { if (row.event.segmentId !== scope.segment.segmentId) continue; const item = this.repository.mailboxItemForEvent( this.consumerId, row.event.eventId, this.mode, ); if (item?.state === 'pending' || item?.state === 'claimed') { preserved.add(row.event.eventId); } } this.suppressRows(rows.filter((row) => ( !preserved.has(row.event.eventId) && ( row.event.segmentId !== scope.segment.segmentId || row.delivery.monitorAttemptCount === 0 ) ))); } /** @deprecated Use suppressPendingBeforeSubscription at owner subscription setup. */ suppressCurrentPending(): void { this.suppressPendingBeforeSubscription(); } async flush(): Promise { while (true) { const pending = this.reconcileChain; await pending; await this.dispatcher.flush(); if (pending === this.reconcileChain) return; } } async stop(): Promise { this.stopped = true; this.cancelReconcileRetry(); await this.reconcileChain; await this.dispatcher.stop(); } private requestReconcile(): void { if (this.stopped || this.reconcileQueued || this.reconcileRetryTimer) return; this.reconcileQueued = true; this.reconcileChain = this.reconcileChain.then(async () => { try { const hasScope = this.materializeCurrentPending(); this.reconcileRetryCount = 0; if (hasScope) this.dispatcher.notifyAvailable(); } catch (error) { if (!(error instanceof NotificationProjectionError)) { try { this.options.onPumpError?.(error); } catch {} } this.scheduleReconcileRetry(); } finally { this.reconcileQueued = false; } }); } private materializeCurrentPending(): boolean { const scope = this.repository.currentScope(); if (!scope) return false; const rows = this.repository.listEvents({ sessionId: scope.session.sessionId, deliveryClasses: ['monitor_and_events'], monitorStates: ['pending'], order: 'asc', }, this.consumerId, ['monitor']); for (const row of rows) { try { this.projector.project(row.event); } catch (error) { try { this.options.onError?.(error, row.event); } catch {} throw new NotificationProjectionError(error); } } return true; } private scheduleReconcileRetry(): void { if (this.stopped || this.reconcileRetryTimer) return; const delay = this.retryDelaysMs[ Math.min(this.reconcileRetryCount, this.retryDelaysMs.length - 1) ]; this.reconcileRetryCount += 1; const timer = setTimeout(() => { this.reconcileRetryTimer = undefined; this.requestReconcile(); }, delay); if (typeof timer === 'object' && 'unref' in timer) timer.unref(); this.reconcileRetryTimer = timer; } private cancelReconcileRetry(): void { if (!this.reconcileRetryTimer) return; clearTimeout(this.reconcileRetryTimer); this.reconcileRetryTimer = undefined; } private suppressRows(rows: Array<{ event: CanonicalEvent }>): void { for (const row of rows) { const prepared = this.delivery.prepareMonitor(row.event.eventId, { consumerId: this.consumerId, recordAttempt: false, }); if (!prepared?.suppress()) continue; this.repository.suppressMailboxItems({ consumerId: this.consumerId, eventIds: [row.event.eventId], modes: [this.mode], }); } } private isEligible(event: CanonicalEvent): boolean { return event.deliveryClass === 'monitor_and_events'; } }