import { normalizeBehaviorInput } from './behavior-input-fields.js'; import type { ClawclawBehaviorCatalog } from './plugins/behavior/behavior-catalog.js'; import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js'; import type { ClawclawPerceptionModulePlugin } from './plugins/perception/perception-module-plugin.js'; import type { ResolvedClawclawPerceptionSource } from './plugins/perception/perception-source.js'; type Scope = Readonly<{ sessionId: string; segmentId: string }>; const same = (a: Scope, b: Scope) => a.sessionId === b.sessionId && a.segmentId === b.segmentId; /** Strategy defaults and automatic activation gates are independent of perception execution. */ export class BehaviorReflexControl { private parameters = new Map>>(); private currentScope?: Scope; private tail: Promise = Promise.resolve(); constructor(private readonly modules: ClawclawPerceptionModulePlugin | undefined, private readonly behavior: Pick, private readonly catalog: Pick, private readonly scope: () => Scope, private readonly embedded: readonly ResolvedClawclawPerceptionSource[] = []) {} status(id?: string) { this.refreshScope(); const active = this.behavior.status().stack.reflex; return (this.modules?.bindings(id) ?? []).map(binding => ({ ...binding, ...(this.embedded.some(source => source.id === binding.perception_id) ? { source: 'strategy', behavior_id: binding.id, config: this.modules?.status(binding.perception_id)[0]?.input } : {}), active: active?.triggerId === binding.trigger_id, ...(active?.triggerId === binding.trigger_id ? { activation_id: active.activationId, instance_generation: active.instanceGeneration } : {}), scope: this.currentScope })); } view(id?: string) { const watches = this.status(id), status = this.behavior.status(); const parameters = [...this.parameters].filter(([key]) => id === undefined || key === id) .map(([key,input]) => ({ id: key, input })); if (id === undefined) return { ...status, parameters, watches }; const { current, ...rest } = status, stack = { ...status.stack }; for (const layer of ['long', 'short', 'reflex'] as const) if (stack[layer]?.behaviorId !== id) delete stack[layer]; if (stack.fallback?.behaviorId !== id) delete stack.fallback; const selected = current?.behaviorId === id ? current : undefined; return { ...rest, running: !!selected, stack, ...(selected ? { current: selected } : {}), parameters, watches }; } apply(operation: 'enable' | 'update' | 'disable', id: string, patch: Readonly>, expected: Scope): Promise { const task = this.tail.then(async () => { this.refreshScope(); const guard = () => same(this.scope(),expected); if (!guard()) throw Error('stale_runtime_scope'); const entry = this.catalog.list().find(entry => entry.id === id); if (!entry) throw Error('behavior_not_found'); if (operation !== 'update') { const bindings = this.modules?.bindings(id) ?? []; if (!bindings.length || operation === 'enable' && !bindings.some(binding => binding.available)) { throw Error('perception_binding_unavailable'); } } let input = this.parameters.get(id) ?? {}, updated = 0; // A detector may inject required targets later; enabling alone does not prepare a Behavior. if (operation === 'update' || Object.keys(patch).length) { const source = this.embedded.find(source => source.embedded?.strategyId === id); const fields = source?.module?.inputs ?? []; const detectorPatch: Record = {}; const executionPatch: Record = {}; for (const [key, value] of Object.entries(patch)) { const observed = fields.some(field => field.id === key); if (observed) detectorPatch[key] = value; if (!observed || entry.inputs.some(field => field.id === key)) executionPatch[key] = value; } const configureDetector = () => { if (source && Object.keys(detectorPatch).length) this.modules?.configure(source.id, detectorPatch, guard); }; if (Object.keys(executionPatch).length || !Object.keys(detectorPatch).length) { input = normalizeBehaviorInput({ ...input, ...executionPatch }, entry.inputs); updated = await this.behavior.configureInput(id, input, executionPatch, guard, () => { configureDetector(); this.parameters.set(id, input); this.modules?.behaviorInputChanged(id); }); } else { configureDetector(); } } if (operation !== 'update') { const triggerIds = this.modules?.setWatch(id,operation === 'enable',guard); if (!triggerIds) throw Error('perception_binding_unavailable'); if (operation === 'disable') for (const triggerId of triggerIds) { updated += Number(await this.behavior.updateReflex(triggerId,undefined,guard)); } } return { operation, applied: true, updated_active: updated > 0, updated_activations: updated, input, watches: this.status(id) }; }); this.tail = task.catch(() => {}); return task; } private refreshScope(): void { const scope = this.scope(); if (!this.currentScope || !same(this.currentScope,scope)) { this.currentScope = { ...scope }; this.parameters.clear(); } } }