import { isNotificationTurn } from '../../notification-turn.js'; import { ClawclawStrategyMemory } from '../../strategy-memory.js'; import { resolveDetailCapture } from '../../../observability/detail-capture.js'; import type { BehaviorContinuation, BehaviorDecision, BehaviorInput, ClawclawResolvedResourceMetadata, GameAction } from '../../../../sdk/behavior-plugin/index.js'; import { resolveClawclawResourceMetadata } from '../../../../sdk/behavior-plugin/index.js'; import type { RuntimeEpochCatchUp } from '../../../framework/plugins/contracts.js'; import { createBehaviorInput } from '../../behavior-input.js'; import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js'; import { isClawclawRuntimeState } from '../../runtime-state.js'; import { CLAWCLAW_ACTION_CAPABILITY, CLAWCLAW_ACTION_PLUGIN_ID } from '../action/index.js'; import { CLAWCLAW_GAME_QUERY_PLUGIN_ID } from '../game-query/index.js'; import { CLAWCLAW_PERCEPTION_PLUGIN_ID } from '../perception/index.js'; import { CLAWCLAW_TRIGGER_PLUGIN_ID } from '../trigger/contracts.js'; import { BehaviorActivationManager, type BehaviorActivationSnapshot, type BehaviorActivationSource } from './activation-manager.js'; import { normalizeClawclawBehaviorAction } from './behavior-action.js'; import type { ClawclawBehaviorCatalog } from './behavior-catalog.js'; import type { PreparedClawclawBehavior } from './behavior-normalization.js'; import { ClawclawBehaviorRunner } from './behavior-runner.js'; import type { ClawclawBehaviorControlDriver } from './control-driver.js'; import { StrategyHost } from '@myclaw163/game-agent-runtime/strategy/strategy-host.js'; import type { PreparedStrategy, ReflexRequest, ReflexResult, StrategyAdapter, StrategyFrame } from '@myclaw163/game-agent-runtime/strategy/contracts.js'; import type { BehaviorDecisionFrame } from '../../../../sdk/module-input/index.js'; import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js'; export const CLAWCLAW_BEHAVIOR_PLUGIN_ID = 'clawclaw.behavior'; export const CLAWCLAW_BEHAVIOR_STATE_TOPIC = 'behavior.status'; export const CLAWCLAW_BEHAVIOR_LIFECYCLE_EVENT_TYPES = Object.freeze([ 'behavior.started', 'behavior.suspended', 'behavior.restarted', 'behavior.completed', 'behavior.failed', 'behavior.cancelled', 'behavior.replaced', ] as const); export interface ClawclawRoleFallbackBehavior { readonly behaviorId: string; readonly input?: Readonly>; } export type ClawclawRoleFallbackBehaviors = Readonly | undefined>>; const BACKEND_STRATEGY_REPORT_LOCALE = 'zh-CN'; function isSuccessfulBackendStrategyReport(value: unknown): boolean { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const result = value as Record; if (result.status !== 'success' || result.source !== 'backend' || result.actionOutcome !== 'confirmed') return false; const response = result.value; if (!response || typeof response !== 'object' || Array.isArray(response)) return false; const root = response as Record; const data = root.data; return root.success === true && !!data && typeof data === 'object' && !Array.isArray(data) && (data as Record).ok === true; } export interface ClawclawBehaviorPluginOptions { readonly memory?: ClawclawStrategyMemory; readonly catalog: Pick & Partial>; readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors; readonly manager?: BehaviorActivationManager; readonly driver?: ClawclawBehaviorControlDriver; readonly after?: readonly string[]; readonly eventTypes?: readonly string[]; readonly timeoutMs?: number; readonly decisionTimeoutMs?: number; readonly catchUp?: RuntimeEpochCatchUp; readonly diagnosticsEnabled?: boolean; readonly now?: () => number; readonly createActivationId?: () => string; } export interface StartBehaviorOptions { readonly source: Extract; readonly maxRuntimeMs?: number; /** Revalidate scope/phase after asynchronous preparation, before changing control. */ readonly isCurrent?: () => boolean; } export interface ClawclawBehaviorHostStatus { readonly running: boolean; readonly current?: Readonly; readonly stack: ReturnType; } function sdkFrame(frame: StrategyFrame): Readonly { return frame.value as Readonly; } function preparedValue(prepared: PreparedStrategy): PreparedClawclawBehavior { return { ...(prepared.value as PreparedClawclawBehavior), ...(prepared.module ? { module: prepared.module as PreparedClawclawBehavior['module'] } : {}) }; } function createAdapter(deferredDisplay: () => ClawclawResolvedResourceMetadata | undefined, useAdaptiveWorkers: boolean, assertStartAllowed: (id: string) => void): StrategyAdapter { // The CCL adapter receives normalized decisions from both execution modes. const checkDelegation = (decision: BehaviorDecision) => { if (decision.delegate) { const target = decision.delegate; assertStartAllowed('strategy' in target ? target.strategy : target.behavior); } return decision; }; const observations = new ClawclawBehaviorObservationMemory(); return { input: (input, parameters, continuation, history) => { const frame = createBehaviorInput(input, parameters, continuation as BehaviorContinuation, history as readonly BehaviorDecisionFrame[]); return frame ? { value: frame, epochId: frame.epochId, scope: frame.scope, nowMs: frame.nowMs, tick: Number(frame.gameState.tick ?? frame.epochId), cycle: frame.cycle, events: frame.events } : null; }, boundary: input => { const state = input.epoch.state, typed = isClawclawRuntimeState(state); const observed = typed && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached'); return { notificationOnly: isNotificationTurn(state), cycle: !!state.cycle, terminalReason: typed && state.stage === 'ended' ? 'scope_ended' : undefined, hasObservation: observed, observationTick: observed && 'state' in state.game_snapshot ? Number(state.game_snapshot.state.tick) : undefined, pendingPauseReason: typed && state.stage !== 'game' && state.stage !== 'meeting' ? 'wandering_inactive' : undefined, actionGeneration: typed ? state.action_safety_generation : undefined }; }, policy: (frame, layer) => { const state = frame ? sdkFrame(frame).gameState : undefined; const meeting = state?.phase === 'meeting'; return { terminalReason: state?.phase === 'game_over' ? 'game_over' : undefined, inactiveReason: state?.you?.is_alive === false ? 'player_inactive' : undefined, pauseReason: state && state.phase !== 'wandering' && !(meeting && layer === 'short') ? meeting ? 'meeting_started' : 'wandering_inactive' : undefined, resume: state?.phase === 'wandering', pauseAfterDecision: meeting ? 'meeting_started' : undefined, fallbackKey: state?.you?.role }; }, observations: { capture: frame => observations.capture(sdkFrame(frame)), snapshot: id => observations.snapshot(id), clear: () => observations.clear() }, createRunner: options => { const runner = new ClawclawBehaviorRunner({ ...options, prepared: preparedValue(options.prepared), initialWorkers: useAdaptiveWorkers ? 1 : undefined, memory: options.memory && ((input, active) => options.memory!({ value: input, epochId: input.epochId, scope: input.scope, nowMs: input.nowMs, tick: Number(input.gameState.tick ?? input.epochId), cycle: input.cycle, events: input.events }, active)) }); return { execution: runner.execution, everyTicks: runner.everyTicks, prepare: () => runner.prepare(), stop: reason => runner.stop(reason), diagnosticSnapshot: () => runner.diagnosticSnapshot(), decideSerial: (frame, signal, observation) => runner.decideSerial(sdkFrame(frame), signal, observation as ClawclawBehaviorObservationSnapshot).then(checkDelegation), decideParallel: (frame, signal, observation) => runner.decideParallel(sdkFrame(frame), signal, observation as ClawclawBehaviorObservationSnapshot).then(checkDelegation) }; }, action: (action, epoch, safety, generation, tick) => ({ ...normalizeClawclawBehaviorAction(action as GameAction, epoch, safety, generation, tick) }), display: prepared => deferredDisplay() ?? (prepared ? resolveClawclawResourceMetadata({ ...preparedValue(prepared).manifest, display: prepared.display }, BACKEND_STRATEGY_REPORT_LOCALE) : { id: 'clawclaw:no-active-behavior', name: '无策略在运行', description: '当前没有活跃的策略。' }), reportEligible: input => { const state = input.epoch.state; return isClawclawRuntimeState(state) && state.connection === 'connected' && (state.stage === 'game' || state.stage === 'meeting') && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached') && (state.game_snapshot.state.phase === 'wandering' || state.game_snapshot.state.phase === 'meeting') && state.game_snapshot.state.you?.is_alive === true; }, reportSelection: input => { const state = input.epoch.state; return isClawclawRuntimeState(state) && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached') && state.game_snapshot.state.phase === 'meeting' ? 'selected' : 'active'; }, report: (context, target) => context.capabilities.performAction(CLAWCLAW_ACTION_CAPABILITY, { route: 'game', action: { action: 'strategy', name: target.name, description: target.description } }), reportSucceeded: isSuccessfulBackendStrategyReport, }; } /** Game policy and SDK adapter; activation/control/decision execution belongs to the shared runtime. */ interface DeferredShortControl { display(): ClawclawResolvedResourceMetadata | undefined; afterReady(): void; } export class ClawclawBehaviorPlugin extends StrategyHost { private readonly deferredShort: { control?: DeferredShortControl }; private readonly catalogAccess: ClawclawBehaviorPluginOptions['catalog']; private readonly assertStartAllowed: (id: string) => void; constructor(options: ClawclawBehaviorPluginOptions) { const assertStartAllowed = (id: string) => { const error = options.catalog.activationError?.(id); if (error) throw new Error(error); }; for (const binding of Object.values(options.fallbackBehaviors ?? {})) { if (binding) assertStartAllowed(binding.behaviorId); } const deferredShort: { control?: DeferredShortControl } = {}; super({ ...options, id: CLAWCLAW_BEHAVIOR_PLUGIN_ID, stateTopic: CLAWCLAW_BEHAVIOR_STATE_TOPIC, actionCapability: CLAWCLAW_ACTION_CAPABILITY, adapter: createAdapter(() => deferredShort.control?.display(), !!options.catalog.prepareForActivation, assertStartAllowed), captureActions: resolveDetailCapture().actions, catalog: { has: id => options.catalog.has(id), prepare: async (id, input) => { const prepared = await options.catalog.prepare(id, input); return { ...prepared, value: prepared }; }, ...(options.catalog.prepareForActivation ? { prepareForActivation: async (id: string, input: Readonly>) => { const prepared = await options.catalog.prepareForActivation!(id, input, options.diagnosticsEnabled); return { ...prepared, value: prepared, discardWorker: () => prepared.worker?.dispose() }; } } : {}) }, after: options.after ?? [CLAWCLAW_ACTION_PLUGIN_ID, CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID] }); this.deferredShort = deferredShort; this.catalogAccess = options.catalog; this.assertStartAllowed = assertStartAllowed; } startError(id: string): string | undefined { return this.catalogAccess.activationError?.(id); } override async startLong(id: string, input: Readonly>, options: StartBehaviorOptions) { this.assertStartAllowed(id); return super.startLong(id, input, options); } override async startShort(id: string, input: Readonly>, options: StartBehaviorOptions) { this.assertStartAllowed(id); return super.startShort(id, input, options); } override async bindFallback(id: string, input: Readonly>) { this.assertStartAllowed(id); return super.bindFallback(id, input); } override async configureFallbackBehaviors(bindings: ClawclawRoleFallbackBehaviors, currentRole?: string) { for (const binding of Object.values(bindings)) { if (binding) this.assertStartAllowed(binding.behaviorId); } return super.configureFallbackBehaviors(bindings, currentRole); } override async requestReflex(request: Readonly, guard?: Readonly<{ isCurrent(): boolean }>): Promise { if (this.catalogAccess.activationError?.(request.behavior, request)) { return { accepted: false, reason: 'activation_ineligible' }; } return super.requestReflex(request, guard); } attachDeferredShortControl(control: DeferredShortControl): void { this.deferredShort.control = control; } afterReady(): void { this.deferredShort.control?.afterReady(); } }