import { actionFailureDiagnosticSeverity } from '../framework/action-diagnostics.js'; import { clawclawNotificationFollowUp } from './notification-turn.js'; import type { AuthProfile } from '../../lib/auth.js'; import { getProfileEventLedgerPath, getProfileInputJournalPath, getProfileRuntimeStateDir, getProfileStateHistoryPath, getRuntimeAccountId, } from '../../lib/init-command.js'; import { createClawclawEventCatalog, type ClawclawVisualEventDelivery, } from '../clawclaw-event-catalog.js'; import type { ClawclawPosition } from '../clawclaw-position.js'; import { Runtime, type RuntimeOptions } from '../framework/runtime.js'; import { createMemoryFirstPersistence } from '../framework/persistence/memory-first-persistence.js'; import { AtomicJsonAgentStateSnapshotStore, DurableAgentStateSnapshotObserver, durableAgentStateSnapshotPath, type StateFreshnessPolicy, type StateFreshnessPolicyResolver, } from '../framework/state/index.js'; import { CLAWCLAW_GAME_WS_SOURCE, CLAWCLAW_ROOM_WS_SOURCE, } from './plugins/source/source-transports.js'; import { projectClawclawCurrentState } from './runtime-state.js'; import { createClawclawNotificationPolicy } from './notification-policy.js'; export const CLAWCLAW_ADAPTER_ID = 'clawclaw'; export const CLAWCLAW_GAME_LIVENESS_SILENCE_MS = 35_000; export const CLAWCLAW_ROOM_LIVENESS_SILENCE_MS = 35_000; export type ClawclawRuntimeOptions = Omit< RuntimeOptions, | 'adapterId' | 'accountId' | 'eventCatalog' | 'eventLedgerPath' | 'initialEventConsumerIds' | 'stateHistoryPath' | 'inputJournalPath' | 'historyObserverFactory' | 'currentStateFromRuntimeState' | 'notificationPolicy' | 'followUpInput' > & { /** Tests and embedded hosts may replace or disable the durable current-State cache. */ durableStateSnapshot?: AtomicJsonAgentStateSnapshotStore> | false; /** Frozen delivery policy for visual Events produced by Perception. */ visualEventDelivery?: ClawclawVisualEventDelivery; /** Visual Event types declared by the selected perception modules. */ visualEventTypes?: readonly string[]; perceptionEventTypes?: readonly string[]; /** Event types declared by enabled Intent and Strategy modules at startup. */ behaviorEventTypes?: readonly string[]; }; export function isClawclawTerminalState(state: Record): boolean { return state.phase === 'game_over'; } function clawclawFreshnessResolver( base: StateFreshnessPolicy, custom?: StateFreshnessPolicyResolver, ): StateFreshnessPolicyResolver { return (sourceId, snapshot) => { const configured = custom?.(sourceId, snapshot); if (configured) return configured; if ( sourceId === CLAWCLAW_GAME_WS_SOURCE.sourceId || sourceId === CLAWCLAW_ROOM_WS_SOURCE.sourceId ) { const { maxStateSilenceMs: _periodicStateDeadline, ...shared } = base; return { ...shared, maxLivenessSilenceMs: shared.maxLivenessSilenceMs ?? (sourceId === CLAWCLAW_GAME_WS_SOURCE.sourceId ? CLAWCLAW_GAME_LIVENESS_SILENCE_MS : CLAWCLAW_ROOM_LIVENESS_SILENCE_MS), }; } return base; }; } /** * ClawClaw supplies persistence paths, Event policy and State projection. * Epoch Plugins are never inferred here: callers pass the exact flat plugin * list through RuntimeOptions.runtimeEpochPlugins. */ export function createClawclawRuntime( profile: Pick, options: ClawclawRuntimeOptions, ): Runtime { const { durableStateSnapshot: configuredSnapshot, stateObservers: configuredObservers = [], stateFreshnessPolicy: configuredFreshness = {}, stateFreshnessPolicyResolver: configuredResolver, visualEventDelivery, visualEventTypes, perceptionEventTypes, behaviorEventTypes, ...runtimeOptions } = options; const stateFreshnessPolicy = { ...configuredFreshness }; const stateFreshnessPolicyResolver = clawclawFreshnessResolver( stateFreshnessPolicy, configuredResolver, ); const snapshotStore = configuredSnapshot === false ? null : configuredSnapshot ?? new AtomicJsonAgentStateSnapshotStore>( durableAgentStateSnapshotPath(getProfileRuntimeStateDir(profile)), ); const useDefaultPersistence = !runtimeOptions.eventRepository && !runtimeOptions.stateHistoryRepository && !runtimeOptions.inputJournal; const persistence = useDefaultPersistence ? createMemoryFirstPersistence({ eventLedgerPath: getProfileEventLedgerPath(profile), stateHistoryPath: getProfileStateHistoryPath(profile), inputJournalPath: getProfileInputJournalPath(profile), recovery: { account: { adapterId: CLAWCLAW_ADAPTER_ID, accountId: getRuntimeAccountId(profile) }, resume: runtimeOptions.resume, resumeKey: runtimeOptions.resumeKey, initialSegment: runtimeOptions.initialSegment, }, onDiagnostic: runtimeOptions.observability ? (name, attributes) => runtimeOptions.observability?.log('info', name, { ...attributes }, { component: 'runtime.persistence' }) : undefined, onDegraded: (error, health) => runtimeOptions.observability?.error( 'runtime.persistence.async_degraded', error, { pending_operations: health.pendingOperations, dropped_operations: health.droppedOperations, }, { component: 'runtime.persistence' }, ), }) : null; return new Runtime({ ...runtimeOptions, actionFailureSeverity: actionFailureDiagnosticSeverity, adapterId: CLAWCLAW_ADAPTER_ID, accountId: getRuntimeAccountId(profile), followUpInput: clawclawNotificationFollowUp, notificationPolicy: createClawclawNotificationPolicy(runtimeOptions.runtimeEpochPlugins ?? []), eventCatalog: createClawclawEventCatalog({ visualEventDelivery, visualEventTypes, perceptionEventTypes, behaviorEventTypes, }), // Mailbox ACK adapters own independent durable lanes. Disabled and // acknowledgement:none adapters must not leave an unowned delivery row. initialEventConsumerIds: [], ...(persistence ? { eventRepository: persistence.eventRepository, stateHistoryRepository: persistence.stateHistoryRepository, inputJournal: persistence.inputJournal, } : { eventLedgerPath: getProfileEventLedgerPath(profile), stateHistoryPath: getProfileStateHistoryPath(profile), inputJournalPath: getProfileInputJournalPath(profile), }), currentStateFromRuntimeState: projectClawclawCurrentState, stateFreshnessPolicy, stateFreshnessPolicyResolver, stateObservers: [ ...configuredObservers, ...(snapshotStore ? [new DurableAgentStateSnapshotObserver(snapshotStore, { freshnessPolicy: stateFreshnessPolicy, freshnessPolicyResolver: stateFreshnessPolicyResolver, isTerminal: isClawclawTerminalState, })] : []), ], }); }