import type { ClawclawPerception, ClawclawPerceptionManifest, PerceptionApi, PerceptionAnalysisInput, PerceptionBoundary, PerceptionEventProposal, PerceptionSpatialFacts, PerceptionFrame, } from './contracts.js'; import type { PerceptionModuleLoader } from './perception-module-loader.js'; import type { ResolvedClawclawPerceptionSource } from './perception-source.js'; import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js'; import { normalizePerceptionEvents } from './perception-module-output.js'; import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js'; import { PerceptionReducerThreadPool, type PerceptionReducerThreadPoolSnapshot, } from './perception-reducer-thread-pool.js'; function deepFreeze(value: T, seen = new WeakSet()): T { if (!value || typeof value !== 'object') return value; const object = value as object; if (seen.has(object)) return value; seen.add(object); for (const child of Object.values(object)) deepFreeze(child, seen); return Object.freeze(value); } function isolatedClone(value: T): T { return deepFreeze(structuredClone(value)); } export interface PerceptionModuleRunner { readonly manifest: ClawclawPerceptionManifest; readonly execution: 'ordered_update' | 'parallel_analysis'; start( spatialFacts: PerceptionSpatialFacts, api: PerceptionApi, signal: AbortSignal, diagnostic?: ( name: string, attributes?: Readonly>, severity?: RuntimeDiagnosticSeverity, ) => void, ): void | Promise; update( frame: Readonly, api: PerceptionApi, signal: AbortSignal, ): readonly PerceptionEventProposal[] | void | Promise; analyze( input: Readonly, api: PerceptionApi, signal: AbortSignal, ): unknown | Promise; commit( frame: Readonly, analysis: unknown, api: PerceptionApi, signal: AbortSignal, ): readonly PerceptionEventProposal[] | void | Promise; flush( boundary: Readonly, api: PerceptionApi, signal: AbortSignal, ): readonly PerceptionEventProposal[] | void | Promise; reset( reason: Parameters>[0], signal: AbortSignal, ): void | Promise; stop(reason: 'segment_ending' | 'shutdown'): void | Promise; debugSnapshot(): unknown; reducerDiagnosticSnapshot?(): PerceptionReducerThreadPoolSnapshot | null; } export class LocalPerceptionModuleRunner implements PerceptionModuleRunner { readonly execution: 'ordered_update' | 'parallel_analysis'; constructor( private module: ClawclawPerception, readonly manifest: ClawclawPerceptionManifest, ) { this.execution = manifest.execution ?? 'ordered_update'; } start(): void {} async update(frame: Readonly, api: PerceptionApi) { return normalizePerceptionEvents(await this.module.update(frame, api), this.manifest); } async analyze(input: Readonly, api: PerceptionApi): Promise { if (this.execution !== 'parallel_analysis') return undefined; const ModuleClass = this.module.constructor as new() => ClawclawPerception; const analyzer = new ModuleClass() as ClawclawPerception & { analyze?: ( value: Readonly, capability: PerceptionApi, ) => unknown | Promise; }; if (typeof analyzer.analyze !== 'function') throw new Error('parallel_perception_analyze_missing'); const analysis = structuredClone(await analyzer.analyze(input, api)); assertRuntimeModuleOutputSize(analysis, 'perception_analysis_output'); return analysis; } async commit(frame: Readonly, analysis: unknown, api: PerceptionApi) { if (this.execution !== 'parallel_analysis') { throw new Error('ordered_perception_uses_update'); } const reducer = this.module as ClawclawPerception & { commit?: ( value: Readonly, evidence: unknown, capability: PerceptionApi, ) => readonly PerceptionEventProposal[] | void | Promise; }; if (typeof reducer.commit !== 'function') throw new Error('parallel_perception_commit_missing'); try { return normalizePerceptionEvents( await reducer.commit(frame, structuredClone(analysis), api), this.manifest, ); } catch (error) { // commit() is allowed to mutate its private reducer before it throws. // Never reuse that unknowable state on the next ordered frame. const ModuleClass = this.module.constructor as new() => ClawclawPerception; this.module = new ModuleClass(); throw error; } } async flush(boundary: Readonly, api: PerceptionApi) { return normalizePerceptionEvents(await this.module.flush?.(boundary, api), this.manifest); } async reset(reason: Parameters>[0]): Promise { try { await this.module.reset?.(reason); } catch (error) { const ModuleClass = this.module.constructor as new() => ClawclawPerception; this.module = new ModuleClass(); throw error; } } async stop(reason: 'segment_ending' | 'shutdown'): Promise { await this.module.reset?.(reason); } debugSnapshot(): unknown { return this.module.debugSnapshot?.() ?? null; } } /** Proxies one installed module to a persistent, memory-bounded reducer Worker lane. */ export class ImportedLocalPerceptionModuleRunner implements PerceptionModuleRunner { readonly manifest: ClawclawPerceptionManifest; readonly execution: 'ordered_update' | 'parallel_analysis'; private reducerPool?: PerceptionReducerThreadPool; private startTask?: Promise; private lifecycleGeneration = 0; private started = false; constructor( private readonly source: ResolvedClawclawPerceptionSource, private readonly loader: PerceptionModuleLoader, reducerPool?: PerceptionReducerThreadPool, ) { this.manifest = source.manifest; this.execution = source.manifest.execution ?? 'ordered_update'; this.reducerPool = reducerPool; } start( spatialFacts: PerceptionSpatialFacts, _api: PerceptionApi, signal: AbortSignal, diagnostic?: ( name: string, attributes?: Readonly>, severity?: RuntimeDiagnosticSeverity, ) => void, ): Promise { if (this.startTask) return this.startTask; const generation = ++this.lifecycleGeneration; let task!: Promise; task = this.startInternal(spatialFacts, signal, diagnostic, generation).finally(() => { if (this.startTask === task) this.startTask = undefined; }); this.startTask = task; return task; } private async startInternal( spatialFacts: PerceptionSpatialFacts, signal: AbortSignal, diagnostic: (( name: string, attributes?: Readonly>, severity?: RuntimeDiagnosticSeverity, ) => void) | undefined, generation: number, ): Promise { signal.throwIfAborted(); const pool = this.reducerPool ?? new PerceptionReducerThreadPool({ modules: [this.loader.threadSpec(this.source)], loader: this.loader.threadConfig(), spatialFacts, diagnostic, }); this.reducerPool = pool; pool.setDiagnostic(diagnostic); await pool.start(); signal.throwIfAborted(); if (generation !== this.lifecycleGeneration) { throw new Error('perception_module_start_cancelled'); } pool.assertAvailable(this.manifest.id); this.started = true; } async update(frame: Readonly, api: PerceptionApi, signal: AbortSignal) { signal.throwIfAborted(); void api; return this.required().operate( this.manifest.id, 'update', { frame: isolatedClone(frame) }, signal, ); } async analyze(input: Readonly, api: PerceptionApi, signal: AbortSignal) { signal.throwIfAborted(); void input; void api; throw new Error('perception_parallel_analysis_uses_analysis_pool'); } async commit(frame: Readonly, analysis: unknown, api: PerceptionApi, signal: AbortSignal) { signal.throwIfAborted(); void api; return this.required().operate( this.manifest.id, 'commit', { frame: isolatedClone(frame), analysis: isolatedClone(analysis) }, signal, ); } async flush(boundary: Readonly, api: PerceptionApi, signal: AbortSignal) { signal.throwIfAborted(); void api; return this.required().operate( this.manifest.id, 'flush', { boundary: isolatedClone(boundary) }, signal, ); } reset(reason: Parameters>[0], signal: AbortSignal) { signal.throwIfAborted(); return this.required().operate(this.manifest.id, 'reset', { reason }, signal).then(() => {}); } async stop(reason: 'segment_ending' | 'shutdown'): Promise { this.lifecycleGeneration += 1; this.startTask = undefined; this.started = false; await this.reducerPool?.releaseModule(this.manifest.id, reason); } debugSnapshot(): unknown { return this.started ? this.reducerPool?.debugSnapshot(this.manifest.id) ?? null : null; } reducerDiagnosticSnapshot(): PerceptionReducerThreadPoolSnapshot | null { return this.reducerPool?.snapshot() ?? null; } private required(): PerceptionReducerThreadPool { if (!this.reducerPool || !this.started) throw new Error('perception_module_not_started'); this.reducerPool.assertAvailable(this.manifest.id); return this.reducerPool; } }