import { prepareNotificationContent, notificationStateAt } from '../perception/notification-content.js'; import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput } from '../../../framework/plugins/index.js'; import { CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES } from '../../../clawclaw-event-catalog.js'; import { BUILTIN_PERCEPTION_PREFIX, CLAWCLAW_SYSTEM_CONTROL_EVENTS } from '../../notification-policy.js'; import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule, RoomReadyDerivedEventRule, type ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js'; import { PlayerChangesDerivedEventRule } from '../derived-event/state-change-rules.js'; import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perception-plugin/reminder-rules.js'; import { ClawclawPerception, type PerceptionModuleInput, type PerceptionModuleResult } from '../../../../sdk/perception-plugin/index.js'; import type { StoredStateFrame } from '../../../framework/state/index.js'; import type { CanonicalEvent } from '../../../framework/events/index.js'; import { SabotageAvailabilityRule } from './sabotage-availability-rule.js'; import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js'; import type { PerceptionAdapter, PerceptionBoundary } from '@myclaw163/game-agent-runtime/perception/contracts.js'; import { perceptionInputBoundary, type PerceptionInputBaseline } from '../perception/module-input-boundary.js'; import { comparePerceptionTasks, type PerceptionTaskBaseline } from '../perception/task-baseline.js'; import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js'; export const BUILTIN_PERCEPTION_NAMES = { players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务', flow: '房间与游戏流程', meeting: '会议', behavior: '策略消息', } as const; type Domain = keyof typeof BUILTIN_PERCEPTION_NAMES; interface NativeState { rules: Record } /** Native modules use the same evaluate/input/result contract as installed scripts. */ class NativePerceptionModule extends ClawclawPerception { constructor(private readonly domain: Domain, private readonly forwarded: readonly string[], private readonly rules: readonly ClawclawDerivedEventRule[]) { super(); } override evaluate(input: Readonly): PerceptionModuleResult { const prior = input.state as NativeState | undefined; const source = input.source!; const frame: StoredStateFrame> = { frameSeq: source.frameSeq, epochSeq: source.epochId, scope: { ...input.scope, adapterId: 'clawclaw', accountId: '' }, sourceId: 'clawclaw.perception-input', sourceKey: input.frame?.frameKey ?? `epoch:${source.epochId}`, connectionId: source.connectionId, backendTick: source.backendTick, receivedAtMs: source.receivedAtMs, observedAtMs: source.observedAtMs, state: { schema: 'clawclaw.runtime-state.v1', stage: input.roomState ? 'room' : input.gameState?.phase === 'meeting' ? 'meeting' : 'game', connection: 'connected', transport: 'none', cause: 'processing_cycle', room: input.roomState, game_snapshot: input.gameState ? { status: 'cached', state: input.gameState } : { status: 'not_updated' } }, }; const facts = input.events.map(event => ({ type: event.type, payload: { ...event.payload }, producer: event.producer, sourceEventId: event.eventId, observedAt: event.occurredAt, replayed: event.replayed })); const events: NonNullable[number][] = []; const state: NativeState = { rules: {} }; for (const rule of this.rules) { rule.reset(); if (input.boundary !== 'recovery') rule.restore?.(prior?.rules[rule.id]); const proposals = rule.inspect(frame, facts); state.rules[rule.id] = rule.save?.(); if (input.boundary !== 'recovery') for (const event of proposals) events.push({ type: event.type, key: event.dedupeKey ?? `${source.epochId}:${event.type}`, payload: event.payload ?? {}, wakeAgent: event.wakeAgent, occurredAt: event.occurredAt, }); } if (this.domain === 'tasks') { const result = defaultReminder('tasks', { ...input, facts: input.events, taskChanges: [], config: {} }); events.push(...result.events ?? []); } return { state, events, forwards: input.events.filter(event => this.forwarded.includes(event.type)) .map(event => ({ eventId: event.eventId })) }; } } interface PreparedNative { input: RuntimeEpochPluginInput>; common: ReturnType['common']; facts: CanonicalEvent[]; context: RuntimeEpochPluginContext>; } function nativeAdapter(domain: Domain, forwarded: readonly string[], rules: readonly ClawclawDerivedEventRule[]): PerceptionAdapter { const module = new NativePerceptionModule(domain, forwarded, rules); const prepared = (boundary: PerceptionBoundary) => boundary.value as PreparedNative; return { reset: () => {}, recover: checkpoint => (checkpoint as { adapterState?: unknown })?.adapterState, prepare(input, previous, context) { if (!context) throw Error('NATIVE_PERCEPTION_CONTEXT_MISSING'); const shared = perceptionInputBoundary(input, previous as PerceptionInputBaseline | undefined); const eligible = [] as CanonicalEvent[]; let cursor = context.progress().eventCursor; for (const event of input.pendingEvents) { if (domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior' && (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break; cursor = event.commitSeq; if (event.notificationOf) continue; if (domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue; eligible.push(event); } return { state: shared.state, identity: shared.state.scope, resetScope: shared.initial, resetModules: false, notificationOnly: false, nowMs: shared.common.nowMs, reflexAllowed: false, consumeEventsThroughCommitSeq: cursor, value: { input, common: shared.common, facts: eligible, context } satisfies PreparedNative }; }, configure: (_source, config) => config, describe: source => ({ id: source.id, name: source.name }), createRunner: () => ({ start: async () => {}, stop: async () => {}, evaluate: async invocation => module.evaluate(invocation.value as PerceptionModuleInput) }), input(source, boundary, inputState, state, config, bindings) { const p = prepared(boundary); const facts = p.facts.filter(e => source.module.consumes?.includes(e.type)); const eventStates = Object.fromEntries(facts.map(e => [e.eventId, notificationStateAt(p.context, e.epochSeq)])); const comparison = comparePerceptionTasks(inputState as PerceptionTaskBaseline | undefined, p.input, p.common.boundary); const value: PerceptionModuleInput = { ...p.common, moduleId: source.id, config, state, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, events: facts.map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type, occurredAt: e.occurredAt, producer: e.producer, replayed: e.replayed, receivedAt: e.receivedAt, wakeAgent: e.wakeAgent, payload: projectTaskChoiceEventPayload(eventStates[e.eventId], e.type, e.payload) })), eventStates, }; return { invocation: { scope: value.scope, value }, inputState: comparison.baseline, evaluate: true }; }, forward(eventId, boundary) { const event = prepared(boundary).facts.find(e => e.eventId === eventId && forwarded.includes(e.type)); if (!event) throw Error('PERCEPTION_FORWARD_NOT_AUTHORIZED'); return { type: event.type, forwardEventId: eventId, dedupeKey: eventId, payload: {} }; }, notification(proposal, boundary) { const p = prepared(boundary); const original = proposal.forwardEventId ? p.facts.find(e => e.eventId === proposal.forwardEventId) : undefined; return prepareNotificationContent(proposal.type, original?.payload ?? proposal.payload ?? {}, original ? notificationStateAt(p.context, original.epochSeq) : p.common.gameState, 'builtin', original ?? { producer: 'local_synth', producerPluginId: `${BUILTIN_PERCEPTION_PREFIX}${domain}` }); }, }; } /** Host registration, not module text, grants mandatory status and forwarding authority. */ export class SystemPerceptionPlugin extends PerceptionHost { constructor(readonly domain: Domain, forwarded: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) { const consumes = [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwarded, ...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])]; const produces = [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwarded, ...(domain === 'tasks' ? ['reminder.task'] : [])])]; super({ id: `${BUILTIN_PERCEPTION_PREFIX}${domain}`, after: [], sources: [{ id: domain, name: BUILTIN_PERCEPTION_NAMES[domain], module: { consumes, produces }, value: null }], adapter: nativeAdapter(domain, forwarded, rules), // Mandatory native rules must account for every accepted fact in a source batch. // Custom workers retain the host's default per-result budgets. resultLimits: { events: Infinity, bytes: Infinity }, notificationRelay: domain === 'behavior' ? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true }, }); } } /** Every currently public Source gameplay Event has exactly one builtin owner. */ export function createSystemPerceptions(behaviorEventTypes: readonly string[] = []): SystemPerceptionPlugin[] { const groups: Record, string[]> = { players: ['kill', 'killed', 'murder_witnessed', 'body_dropped', 'corpse_spotted', 'warrior_shrimp_self_destruct', 'role_assigned'], tasks: [], abilities: [], emergency: ['emergency_started', 'emergency_resolved', 'emergency_interrupted'], meeting: ['exile', 'no_exile', 'vote_speech_phase_ended', 'death_speech', 'meeting_briefing', 'speech', 'speech_skipped', 'speech_your_turn', 'speech_next_turn', 'vote_phase_start'], flow: [], }; const assigned = new Set(Object.values(groups).flat()); groups.flow = [...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, 'game_over_recovered', 'robot_speak_rule'] .filter(type => !assigned.has(type) && !CLAWCLAW_SYSTEM_CONTROL_EVENTS.has(type)); const behaviorTypes = [...new Set([...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter(type => type.startsWith('behavior.') || type === 'strategy_alert'), ...behaviorEventTypes])]; return [ new SystemPerceptionPlugin('players', groups.players, [new PlayerChangesDerivedEventRule()]), new SystemPerceptionPlugin('tasks', groups.tasks), new SystemPerceptionPlugin('abilities', groups.abilities, [new AbilityStateDerivedEventRule(), new SabotageAvailabilityRule()]), new SystemPerceptionPlugin('emergency', groups.emergency, [new EmergencyCountdownDerivedEventRule()]), new SystemPerceptionPlugin('flow', groups.flow, [new RoomReadyDerivedEventRule()]), new SystemPerceptionPlugin('meeting', groups.meeting), new SystemPerceptionPlugin('behavior', behaviorTypes), ]; }