import { prepareNotificationContent } from '../perception/notification-content.js'; import { preparePerceptionNotification } from '../perception/report-content.js'; import { isNotificationTurn } from '../../notification-turn.js'; import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js'; import type { RuntimeEventProposal } from '../../../framework/plugins/index.js'; import type { ReminderInput, ReminderResult, ReminderTopic } from '../../../../sdk/perception-plugin/reminder.js'; import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js'; import { clawclawComputationGameState } from '../../runtime-state.js'; import { createCanonicalGameState } from '../../behavior-input.js'; import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js'; import { ObservationFrameProjector } from '../../observation-frame-projector.js'; import { REMINDER_EVENT_TYPES, REMINDER_EVENT_TYPE_BY_TOPIC, REMINDER_FACT_TYPES, REMINDER_TOPICS } from './reminder-rules.js'; import { ReminderRunner } from './reminder-runner.js'; import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js'; import { comparePerceptionTasks, type PerceptionTaskBaseline } from '../perception/task-baseline.js'; export const CLAWCLAW_REMINDER_PLUGIN_ID = 'clawclaw.derived-event.reminders'; export interface ReminderPluginOptions { /** Already selected by the ordinary local/Hub perception loadout. No separate settings. */ sources?: readonly ResolvedClawclawPerceptionSource[]; } interface Checkpoint { taskBaseline?: PerceptionTaskBaseline; gameId?: string; previousTick?: number; previousConnectionId?: string; states: Partial>; } function empty(): Checkpoint { return { states: {} }; } export class ClawclawReminderPlugin implements RuntimeEpochPlugin> { readonly agentNotificationProducer = true; readonly kind = 'epoch' as const; readonly id = CLAWCLAW_REMINDER_PLUGIN_ID; readonly version = '2'; readonly after: readonly string[] = []; readonly consumes = { events: REMINDER_FACT_TYPES }; readonly produces = { events: REMINDER_EVENT_TYPES } as const; readonly catchUp = 'strict_ordered' as const; readonly timeoutMs = 3_000; private checkpoint: Checkpoint = empty(); private readonly sources = new Map(); private readonly runners = new Map(); private readonly failed = new Set(); constructor(private readonly options: ReminderPluginOptions = {}) { for (const source of options.sources ?? []) { if (!source.reminder) continue; const selected = this.sources.get(source.reminder.topic) ?? []; selected.push(source); this.sources.set(source.reminder.topic, selected); } } async start(context: RuntimeEpochPluginContext>): Promise { this.checkpoint = empty(); this.failed.clear(); await Promise.all(REMINDER_TOPICS.map(async topic => { const sources = this.sources.get(topic) ?? []; if (!sources.length) return; try { if (sources.length !== 1) throw new Error(`perception_topic_conflict:${topic}:${sources.map(s => s.id).join(',')}`); const runner = new ReminderRunner(sources[0]!); this.runners.set(topic, runner); await runner.start(); } catch (error) { this.markFailed(topic, context, error); await this.runners.get(topic)?.stop(); } })); } recover(context: RuntimeEpochPluginContext>): void { const checkpoint = context.checkpoint() as Checkpoint | undefined; if (checkpoint?.states) this.checkpoint = structuredClone({ taskBaseline: checkpoint.taskBaseline, gameId: checkpoint.gameId, previousTick: checkpoint.previousTick, previousConnectionId: checkpoint.previousConnectionId, states: Object.fromEntries(REMINDER_TOPICS.filter(topic => checkpoint.states[topic]) .map(topic => [topic, checkpoint.states[topic]])), }); } async stop(): Promise { await Promise.all([...this.runners.values()].map(r => r.stop())); this.runners.clear(); } localizedModuleDescriptors(locale: string) { return [...this.sources.entries()].filter(([topic, sources]) => sources.length === 1 && this.runners.has(topic) && !this.failed.has(topic)).map(([, [source]]) => ( resolveClawclawResourceMetadata({ ...source!.manifest, display: source!.display }, locale) )); } async update(input: RuntimeEpochPluginInput>, context: RuntimeEpochPluginContext>): Promise { if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' }; if (this.sources.size === 0) return { outcome: 'noop', reason: 'no_reminder_modules', ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) }; const snapshot = clawclawComputationGameState(input.frame.state); const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null; let next = structuredClone(this.checkpoint); const initial = !!game && next.gameId !== game.game_id; const boundary = initial ? 'initial' as const : (next.previousConnectionId !== undefined && next.previousConnectionId !== input.epoch.connectionId) || input.epochEvents.some(e => e.type === 'game_stream_reconnected') ? 'recovery' as const : null; if (initial) next = { ...empty(), gameId: game!.game_id }; const frame = new ObservationFrameProjector().project(input.frame); if (frame) { const delta = next.previousTick === undefined ? null : frame.tick - next.previousTick; Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1 && next.previousConnectionId === input.epoch.connectionId }); next.previousTick = frame.tick; next.previousConnectionId = input.epoch.connectionId; } else if (!game) { next.previousTick = undefined; next.previousConnectionId = undefined; } next.previousConnectionId = input.epoch.connectionId; const facts = input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({ ...event, payload: projectTaskChoiceEventPayload(game, event.type, event.payload) })); const events: RuntimeEventProposal[] = []; const comparison = comparePerceptionTasks(next.taskBaseline, input, boundary); next.taskBaseline = comparison.baseline; const taskChanges = comparison.changes; const outputs = await Promise.all(REMINDER_TOPICS.map(async topic => { const events: RuntimeEventProposal[] = []; const selected = this.sources.get(topic)?.[0]; if (!selected || this.failed.has(topic)) return events; const previous = next.states[topic]; const moduleInput: ReminderInput = { ...(input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}), scope: input.epoch.scope, frame, gameState: game, taskChanges, boundary, facts: facts.filter(e => topic !== 'speech' || !e.replayed) .map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type, occurredAt: e.occurredAt, producer: e.producer, replayed: e.replayed, payload: e.payload })), config: selected.reminder!.config ?? {}, state: previous?.provider === selected.id ? previous.value : undefined, nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs, }; try { const result: ReminderResult = await this.runners.get(topic)!.update(moduleInput); if (!result || typeof result !== 'object' || Array.isArray(result) || Object.keys(result).some(k => !['state', 'events'].includes(k)) || (result.events !== undefined && !Array.isArray(result.events)) || Buffer.byteLength(JSON.stringify(result)) > 1024 * 1024) throw new Error('Invalid reminder output.'); const accepted: RuntimeEventProposal[] = []; const keys = new Set(); for (const event of result.events ?? []) { if (!event || event.type !== REMINDER_EVENT_TYPE_BY_TOPIC[topic] || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512 || keys.has(event.key) || typeof event.wakeAgent !== 'boolean' || !event.payload || Array.isArray(event.payload) || typeof event.payload.text !== 'string' || !event.payload.text.trim()) { throw new Error(`Invalid ${topic} reminder event.`); } keys.add(event.key); accepted.push({ type: event.type, dedupeKey: JSON.stringify([selected.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent, payload: { ...event.payload }, notificationContent: preparePerceptionNotification(event.type, event.payload, game, selected.id, input.frame.backendTick), occurredAt: new Date(moduleInput.nowMs).toISOString() }); } // Task snapshots establish baselines. Fresh speech remains an occurrence // even in the first/reconnected frame; replayed speech is excluded from input. if (game && (topic === 'speech' || !boundary)) events.push(...accepted); next.states[topic] = { provider: selected.id, value: structuredClone(result.state) }; } catch (error) { this.markFailed(topic, context, error); } return events; })); events.push(...outputs.flat()); this.checkpoint = next; return { outcome: 'processed', events: events.map(event => ({ ...event, notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, game, 'custom') })), checkpoint: next, ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) }; } private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext>, error: unknown): void { this.failed.add(topic); context.diagnostic('reminder.module_failed', { topic, module_ids: this.sources.get(topic)?.map(s => s.id), error: error instanceof Error ? error.message : String(error) }, 'error'); } }