import { normalizePerceptionStrategyNames } from '../../perception-strategy-names.js'; import { prepareNotificationContent, notificationStateAt } from './notification-content.js'; import { preparePerceptionNotification } from './report-content.js'; import { isNotificationTurn } from '../../notification-turn.js'; import type { RuntimeEpochPluginInput, RuntimeEpochPluginContext } from '../../../framework/plugins/index.js'; import { normalizeBehaviorInput } from '../../behavior-input-fields.js'; import { resolveReactionBehavior, type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js'; import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js'; import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js'; import type { ResolvedClawclawPerceptionSource } from './perception-source.js'; import { PerceptionModuleRunner } from './perception-module-runner.js'; import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js'; import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js'; import { comparePerceptionTasks, type PerceptionTaskBaseline } from './task-baseline.js'; import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js'; import type { PerceptionAdapter, PerceptionSource } from '@myclaw163/game-agent-runtime/perception/contracts.js'; import type { ClawclawResolvedResourceMetadata } from '../../../../sdk/resource-metadata.js'; import { perceptionInputBoundary, type PerceptionInputBaseline } from './module-input-boundary.js'; export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules'; export { REACTION_HOST_EVENT_TYPES } from '@myclaw163/game-agent-runtime/perception/perception-host.js'; export interface PerceptionModulePluginOptions { /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */ sources: readonly ResolvedClawclawPerceptionSource[]; after: readonly string[]; behaviors?: () => readonly (ReactionBehaviorCandidate & { readonly activationMode?: 'standard' | 'automatic_only' })[]; runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick; } interface GameCheckpoint { inputBoundary?: PerceptionInputBaseline; gameId?: string; phase?: string; connectionId?: string; previousTick?: number; modules: Record; }>; } function sourceValue(source: PerceptionSource): ResolvedClawclawPerceptionSource { return source.value as ResolvedClawclawPerceptionSource; } function createAdapter(options: PerceptionModulePluginOptions, blockedBindings: ReadonlyMap>): PerceptionAdapter { function prepare(input: RuntimeEpochPluginInput>, previous: unknown, context?: RuntimeEpochPluginContext>) { const checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint; // The shipped host checkpoint already has this baseline under flat names. // Recover it without pretending a running game has just been initialized. const oldBoundary = checkpoint.gameId ? { scope: `${input.epoch.scope.sessionId}:${input.epoch.scope.segmentId}`, gameId: checkpoint.gameId, phase: checkpoint.phase, connectionId: checkpoint.connectionId, tick: checkpoint.previousTick, connected: true } : undefined; const shared = perceptionInputBoundary(input, checkpoint.inputBoundary ?? oldBoundary); const oldGame = checkpoint.gameId, oldPhase = checkpoint.phase; const game = shared.common.gameState; const connected = shared.state.connected === true; const boundary = shared.common.boundary; const frame = shared.common.frame; const nowMs = shared.common.nowMs; const originalFacts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined); const eventStates = Object.fromEntries(originalFacts.map(event => [event.eventId, context ? notificationStateAt(context, event.epochSeq) : null])); const facts = originalFacts.map(event => ({ eventId: event.eventId, epochId: event.epochSeq, producer: event.producer, type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt, payload: projectTaskChoiceEventPayload(eventStates[event.eventId], event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false, })); const resetScope = !!game && oldGame !== game.game_id; const resetBindings = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase); checkpoint.connectionId = input.epoch.connectionId; checkpoint.inputBoundary = shared.state; checkpoint.gameId = game?.game_id ?? oldGame; checkpoint.phase = game?.phase; return { state: checkpoint, identity: game?.game_id, resetScope, resetModules: false, resetBindings, notificationOnly: false, nowMs, reflexAllowed: !!game && game.phase === 'wandering' && game.you?.is_alive === true && connected, value: { input, game, frame, facts, eventStates, boundary, common: shared.common } }; } type Prepared = ReturnType['value']; return { reset: () => {}, recover: saved => { const value = saved as { adapterState?: unknown; modules?: Record>; } & GameCheckpoint; for (const state of Object.values(value.modules ?? {})) if (state.inputState === undefined && 'taskBaseline' in state) { state.inputState = state.taskBaseline; delete state.taskBaseline; } return value.adapterState ?? { gameId: value.gameId, phase: value.phase, connectionId: value.connectionId, previousTick: value.previousTick, modules: {} }; }, prepare: (input, previous, context) => isNotificationTurn(input.epoch.state) ? { state: previous, resetScope: false, resetModules: false, notificationOnly: true, nowMs: 0, reflexAllowed: false, value: null } : prepare(input, previous, context), configure: (source, value) => normalizeBehaviorInput(value, sourceValue(source).module!.inputs ?? []), describe: (source, locale) => { const value = sourceValue(source); return resolveClawclawResourceMetadata({ ...value.manifest, display: value.display }, locale); }, createRunner: (source, bindMemory) => { const value = sourceValue(source); const runner = options.runnerFactory?.(value) ?? new PerceptionModuleRunner(value, (input, active) => bindMemory({ scope: input.scope, value: input }, active)); return { start: () => runner.start(), stop: () => runner.stop(), evaluate: async (input) => normalizePerceptionStrategyNames(await runner.evaluate(input.value as PerceptionModuleInput)) }; }, input: (source, prepared, baseline, state, config, bindings) => { const { input, game, frame, facts, eventStates, boundary, common } = prepared.value as Prepared; const events = facts.filter(event => source.module.consumes?.includes(event.type)); const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary); const blocked = blockedBindings.get(source.id); if (blocked) { bindings = { ...bindings, availableBindings: bindings.availableBindings.filter(key => !blocked.has(key)), enabledBindings: bindings.enabledBindings.filter(key => !blocked.has(key)) }; } const embedded = sourceValue(source).embedded; const declaredTargets = embedded && bindings.availableBindings.length ? Object.values(embedded.declaredManifest.behaviors ?? {}).map(binding => binding.name) : []; const moduleInput: PerceptionModuleInput = { ...common, moduleId: source.id, scope: input.epoch.scope, gameState: game, frame, ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}), events, eventStates: Object.fromEntries(events.map(event => [event.eventId, eventStates[event.eventId]])), nowMs: prepared.nowMs, state, config, ...bindings, availableStrategies: [...new Set([...bindings.availableBehaviors, ...declaredTargets])], taskChanges: comparison.changes, boundary }; return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline, evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || !!common.roomState || !!common.queueState || moduleInput.events.length > 0 || !!moduleInput.lifecycle?.length }; }, notification: (event, prepared, source) => { const { game, input } = prepared.value as Prepared; return source ? preparePerceptionNotification(event.type, event.payload, game, source.id, input.frame.backendTick) : prepareNotificationContent(event.type, event.payload, game, 'custom'); }, }; } export class ClawclawPerceptionModulePlugin extends PerceptionHost { private readonly blockedBindings: ReadonlyMap>; constructor(options: PerceptionModulePluginOptions) { // The Owner pins this catalog for the session. Keep external observers and // their memory bindings alive even when only the embedded perception may start the strategy. const blockedBindings = new Map>(); const candidates = options.behaviors?.() ?? []; const automatic = new Set(candidates.filter(entry => entry.activationMode === 'automatic_only').map(entry => entry.id)); for (const source of options.sources) { if (source.embedded) continue; const blocked = Object.entries(source.module?.behaviors ?? {}).filter(([, binding]) => { const id = resolveReactionBehavior(binding, candidates); return id !== undefined && automatic.has(id); }).map(([key]) => key); if (blocked.length) blockedBindings.set(source.id, new Set(blocked)); } super({ id: CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID, after: options.after, behaviors: options.behaviors, adapter: createAdapter(options, blockedBindings), sources: options.sources.filter(source => source.module).map(source => ({ id: source.id, name: source.name, module: source.module!, value: source })) }); this.blockedBindings = blockedBindings; } override bindings(id?: string) { return super.bindings(id).map(binding => this.blockedBindings.get(binding.perception_id)?.has(binding.binding) ? { ...binding, enabled: false, available: false, reason: 'strategy_automatic_only' } : binding); } override localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] { const descriptors = super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[]; return descriptors.filter(item => !item.id.startsWith('strategy:')); } }