@myclaw163/clawclaw-cli 0.8.13 → 0.8.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/docs/custom-modules/perception.md +4 -4
  2. package/docs/runtime/README.md +1 -1
  3. package/docs/runtime/behavior-runtime.md +1 -1
  4. package/docs/runtime/official-perception-modules.md +23 -30
  5. package/docs/runtime/perception-replay.md +1 -1
  6. package/package.json +1 -1
  7. package/skills/clawclaw/SKILL.md +8 -4
  8. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  9. package/skills/clawclaw/references/CHANNELS.md +1 -1
  10. package/skills/clawclaw/references/COMMANDS.md +2 -2
  11. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  12. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  13. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  14. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  15. package/skills/clawclaw/references/STREAM.md +4 -2
  16. package/src/lib/game-client.ts +12 -4
  17. package/src/pipeline/event-format.ts +5 -0
  18. package/src/pipeline/event-hints.ts +10 -0
  19. package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
  20. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  21. package/src/runtime/clawclaw/behavior-input.ts +5 -0
  22. package/src/runtime/clawclaw/owner.ts +64 -1
  23. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
  24. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  25. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
  31. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
  32. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
  33. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
  34. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  35. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  36. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
  37. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  38. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  39. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
  40. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  41. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  42. package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
  43. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
  44. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  45. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  46. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  47. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  48. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  49. package/src/runtime/clawclaw/runtime.ts +31 -3
  50. package/src/runtime/clawclaw-event-catalog.ts +3 -0
  51. package/src/runtime/framework/events/event-repository.ts +1 -1
  52. package/src/runtime/framework/events/memory-event-repository.ts +71 -1
  53. package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
  54. package/src/runtime/framework/mailbox/types.ts +2 -0
  55. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  56. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
  57. package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
  58. package/src/runtime/framework/plugins/contracts.ts +5 -2
  59. package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
  60. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
  61. package/src/runtime/framework/runtime.ts +75 -4
  62. package/src/runtime/framework/state/history/contracts.ts +9 -1
  63. package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
  64. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
  65. package/src/runtime/observability/redaction.ts +28 -1
  66. package/src/sdk/behavior-plugin/index.ts +5 -24
  67. package/src/sdk/module-input/index.ts +47 -0
  68. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -7,6 +7,8 @@ import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index
7
7
  import type {
8
8
  BehaviorDecision,
9
9
  BehaviorInput,
10
+ BehaviorTiming,
11
+ ClawclawBehaviorManifest,
10
12
  } from '../../../../sdk/behavior-plugin/index.js';
11
13
  import {
12
14
  behaviorSourceUrl,
@@ -37,6 +39,8 @@ export interface ThreadBehaviorExecutorOptions {
37
39
  /** How long an expanded, idle pool is retained before returning to two Workers. */
38
40
  readonly idleWorkerTimeoutMs?: number;
39
41
  readonly maxOldGenerationSizeMb?: number;
42
+ /** Samples Worker heaps only for explicit full diagnostics. */
43
+ readonly diagnosticsEnabled?: boolean;
40
44
  readonly diagnostic?: (
41
45
  name: string,
42
46
  attributes?: Readonly<Record<string, unknown>>,
@@ -53,6 +57,8 @@ export interface ThreadBehaviorExecutorSnapshot {
53
57
  readonly inFlightRequestCount: number;
54
58
  readonly startedWorkerCount: number;
55
59
  readonly retiredWorkerCount: number;
60
+ readonly workerHeapUsedBytes: number;
61
+ readonly peakWorkerHeapUsedBytes: number;
56
62
  }
57
63
 
58
64
  interface PendingRequest {
@@ -78,6 +84,7 @@ interface WorkerSlot {
78
84
  current?: PendingRequest;
79
85
  readyResolve?: () => void;
80
86
  readyReject?: (error: Error) => void;
87
+ heapUsedBytes?: number;
81
88
  retirement?: Promise<void>;
82
89
  }
83
90
 
@@ -92,6 +99,10 @@ interface WorkerReadyMessage extends WorkerMessageBase {
92
99
  readonly type: 'ready';
93
100
  readonly behaviorId: string;
94
101
  readonly execution: ResolvedClawclawBehaviorSource['execution'];
102
+ readonly manifest?: Readonly<ClawclawBehaviorManifest>;
103
+ readonly input?: Readonly<Record<string, unknown>>;
104
+ readonly timing?: Readonly<BehaviorTiming>;
105
+ readonly heapUsedBytes?: number;
95
106
  }
96
107
 
97
108
  interface WorkerResultMessage extends WorkerMessageBase {
@@ -100,12 +111,14 @@ interface WorkerResultMessage extends WorkerMessageBase {
100
111
  readonly result: BehaviorDecision;
101
112
  readonly queryCount: number;
102
113
  readonly durationMs: number;
114
+ readonly heapUsedBytes?: number;
103
115
  }
104
116
 
105
117
  interface WorkerErrorMessage extends WorkerMessageBase {
106
118
  readonly type: 'error';
107
119
  readonly code: string;
108
120
  readonly message?: string;
121
+ readonly heapUsedBytes?: number;
109
122
  }
110
123
 
111
124
  function asError(value: unknown, fallback: string): Error {
@@ -129,11 +142,106 @@ function roundedElapsed(startedAt: number): number {
129
142
  return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
130
143
  }
131
144
 
145
+ export interface BehaviorThreadPreparation {
146
+ readonly manifest: Readonly<ClawclawBehaviorManifest>;
147
+ readonly input: Readonly<Record<string, unknown>>;
148
+ readonly timing?: Readonly<BehaviorTiming>;
149
+ readonly source: ResolvedClawclawBehaviorSource;
150
+ }
151
+
152
+ /** Imports and normalizes a Behavior without evaluating player code in the Owner. */
153
+ export async function prepareBehaviorInWorker(
154
+ source: ResolvedClawclawBehaviorSource,
155
+ input: Readonly<Record<string, unknown>>,
156
+ options: Readonly<{
157
+ maxOldGenerationSizeMb?: number;
158
+ diagnosticsEnabled?: boolean;
159
+ }> = {},
160
+ ): Promise<BehaviorThreadPreparation> {
161
+ const pinned = pinBehaviorSource(source);
162
+ const sourceUrl = behaviorSourceUrl(pinned);
163
+ const loader = behaviorThreadLoaderConfig();
164
+ const poolId = randomUUID();
165
+ const worker = new Worker(WORKER_BOOTSTRAP, {
166
+ execArgv: [],
167
+ resourceLimits: {
168
+ maxOldGenerationSizeMb: Math.max(16, Math.min(
169
+ 256,
170
+ Math.floor(options.maxOldGenerationSizeMb ?? 64),
171
+ )),
172
+ },
173
+ stdout: true,
174
+ stderr: true,
175
+ workerData: {
176
+ runtimeModuleBootstrap: {
177
+ hostUrl: WORKER_HOST_URL,
178
+ hooksUrl: loader.hooksUrl,
179
+ sdkAliases: loader.sdkAliases,
180
+ esmModuleRoots: [new URL('.', sourceUrl).href],
181
+ },
182
+ poolId,
183
+ slotId: 0,
184
+ source: pinned,
185
+ sourceUrl,
186
+ prepareInput: structuredClone(input),
187
+ diagnosticsEnabled: options.diagnosticsEnabled === true,
188
+ },
189
+ });
190
+ try {
191
+ return await new Promise<BehaviorThreadPreparation>((resolve, reject) => {
192
+ let settled = false;
193
+ const finish = (callback: () => void): void => {
194
+ if (settled) return;
195
+ settled = true;
196
+ clearTimeout(timer);
197
+ callback();
198
+ };
199
+ const timer = setTimeout(() => finish(() => reject(
200
+ new Error('behavior_thread_prepare_timeout'),
201
+ )), START_TIMEOUT_MS);
202
+ timer.unref?.();
203
+ worker.on('message', (value: unknown) => {
204
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return;
205
+ const message = value as WorkerReadyMessage | WorkerErrorMessage;
206
+ if (message.poolId !== poolId || message.slotId !== 0) return;
207
+ if (message.type === 'error') {
208
+ const detail = message.message?.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH);
209
+ finish(() => reject(new Error(detail ? `${message.code}: ${detail}` : message.code)));
210
+ return;
211
+ }
212
+ if (
213
+ message.type !== 'ready'
214
+ || message.behaviorId !== pinned.id
215
+ || message.execution !== pinned.execution
216
+ || !message.manifest
217
+ || !message.input
218
+ ) {
219
+ finish(() => reject(new Error('behavior_thread_prepare_invalid')));
220
+ return;
221
+ }
222
+ finish(() => resolve({
223
+ manifest: structuredClone(message.manifest!),
224
+ input: structuredClone(message.input!),
225
+ ...(message.timing === undefined ? {} : { timing: structuredClone(message.timing) }),
226
+ source: pinned,
227
+ }));
228
+ });
229
+ worker.once('error', (error) => finish(() => reject(error)));
230
+ worker.once('exit', (code) => {
231
+ if (code !== 0) finish(() => reject(new Error(`behavior_thread_worker_exited:${code}`)));
232
+ });
233
+ });
234
+ } finally {
235
+ await worker.terminate().catch(() => -1);
236
+ }
237
+ }
238
+
132
239
  /** Adaptive Worker Thread pool for cross-tick computations. */
133
240
  export class ThreadBehaviorExecutor {
134
241
  readonly runtimeInstanceId = randomUUID();
135
242
 
136
243
  private readonly maxWorkerCount: number;
244
+ private readonly maxPendingRequestCount: number;
137
245
  private readonly minWorkerCount: number;
138
246
  private readonly idleWorkerTimeoutMs: number;
139
247
  private readonly maxOldGenerationSizeMb: number;
@@ -151,6 +259,7 @@ export class ThreadBehaviorExecutor {
151
259
  private nextSlotId = 1;
152
260
  private startedWorkerCount = 0;
153
261
  private retiredWorkerCount = 0;
262
+ private peakWorkerHeapUsedBytes = 0;
154
263
  private desiredWorkerCount: number;
155
264
 
156
265
  private readonly options: ThreadBehaviorExecutorOptions;
@@ -160,10 +269,10 @@ export class ThreadBehaviorExecutor {
160
269
  ...options,
161
270
  source: pinBehaviorSource(options.source),
162
271
  });
163
- if ((options.source.execution ?? 'parallel') !== 'parallel') {
164
- throw new Error('behavior_thread_execution_invalid');
165
- }
166
- const maxWorkerCount = options.poolSize ?? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE;
272
+ const execution = options.source.execution ?? 'parallel';
273
+ const maxWorkerCount = execution === 'serial'
274
+ ? 1
275
+ : options.poolSize ?? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE;
167
276
  if (!Number.isInteger(maxWorkerCount) || maxWorkerCount <= 0 || maxWorkerCount > MAX_POOL_SIZE) {
168
277
  throw new TypeError(`poolSize must be between 1 and ${MAX_POOL_SIZE}.`);
169
278
  }
@@ -172,6 +281,9 @@ export class ThreadBehaviorExecutor {
172
281
  throw new TypeError('idleWorkerTimeoutMs must be a non-negative finite number.');
173
282
  }
174
283
  this.maxWorkerCount = maxWorkerCount;
284
+ this.maxPendingRequestCount = execution === 'serial'
285
+ ? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE
286
+ : maxWorkerCount;
175
287
  this.minWorkerCount = Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
176
288
  this.desiredWorkerCount = this.minWorkerCount;
177
289
  this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
@@ -208,8 +320,13 @@ export class ThreadBehaviorExecutor {
208
320
  worker_count: this.slots.size,
209
321
  min_worker_count: this.minWorkerCount,
210
322
  max_worker_count: this.maxWorkerCount,
323
+ worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
211
324
  started_worker_count: this.startedWorkerCount,
212
325
  retired_worker_count: this.retiredWorkerCount,
326
+ ...(this.options.diagnosticsEnabled === true ? {
327
+ worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
328
+ peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
329
+ } : {}),
213
330
  duration_ms: roundedElapsed(startedAt),
214
331
  }, 'info');
215
332
  }).catch(async (error) => {
@@ -269,6 +386,10 @@ export class ThreadBehaviorExecutor {
269
386
  max_worker_count: this.maxWorkerCount,
270
387
  started_worker_count: this.startedWorkerCount,
271
388
  retired_worker_count: this.retiredWorkerCount,
389
+ ...(this.options.diagnosticsEnabled === true ? {
390
+ worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
391
+ peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
392
+ } : {}),
272
393
  }, 'info');
273
394
  }
274
395
 
@@ -283,6 +404,8 @@ export class ThreadBehaviorExecutor {
283
404
  inFlightRequestCount: this.inFlight.size,
284
405
  startedWorkerCount: this.startedWorkerCount,
285
406
  retiredWorkerCount: this.retiredWorkerCount,
407
+ workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
408
+ peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
286
409
  };
287
410
  }
288
411
 
@@ -305,15 +428,16 @@ export class ThreadBehaviorExecutor {
305
428
  if (signal.aborted) throw abortError(signal);
306
429
  await this.awaitStart(signal);
307
430
  if (this.state !== 'running') throw new Error('behavior_thread_pool_not_running');
308
- if ((this.options.source.execution ?? 'parallel') !== 'parallel') {
309
- throw new Error('behavior_thread_decide_not_available');
431
+ if (this.inFlight.size >= this.maxPendingRequestCount) {
432
+ throw new Error('behavior_thread_window_full');
310
433
  }
311
- if (this.inFlight.size >= this.maxWorkerCount) throw new Error('behavior_thread_window_full');
312
434
  return new Promise<unknown>((resolve, reject) => {
313
435
  const request: PendingRequest = {
314
436
  requestId: randomUUID(),
315
437
  operation,
316
- frame: structuredClone(frame),
438
+ // BehaviorInput is already recursively frozen. Keep the Owner snapshot
439
+ // until postMessage performs the one unavoidable Worker-boundary clone.
440
+ frame,
317
441
  ...(observationSnapshot === undefined
318
442
  ? {}
319
443
  : { observationSnapshot: structuredClone(observationSnapshot) }),
@@ -361,6 +485,7 @@ export class ThreadBehaviorExecutor {
361
485
  slotId,
362
486
  source,
363
487
  sourceUrl,
488
+ diagnosticsEnabled: this.options.diagnosticsEnabled === true,
364
489
  },
365
490
  });
366
491
  const slot: WorkerSlot = { id: slotId, worker, state: 'starting' };
@@ -465,14 +590,22 @@ export class ThreadBehaviorExecutor {
465
590
  slot.state !== 'starting'
466
591
  || message.behaviorId !== this.options.source.id
467
592
  || message.execution !== this.options.source.execution
593
+ || (this.options.diagnosticsEnabled === true && (
594
+ !Number.isFinite(message.heapUsedBytes)
595
+ || Number(message.heapUsedBytes) < 0
596
+ ))
468
597
  ) {
469
598
  this.failSlot(slot, new Error('behavior_thread_ready_invalid'));
470
599
  return;
471
600
  }
601
+ if (typeof message.heapUsedBytes === 'number') this.updateWorkerHeap(slot, message.heapUsedBytes);
472
602
  slot.readyResolve?.();
473
603
  return;
474
604
  }
475
605
  if (message.type === 'error') {
606
+ if (Number.isFinite(message.heapUsedBytes) && Number(message.heapUsedBytes) >= 0) {
607
+ this.updateWorkerHeap(slot, Number(message.heapUsedBytes));
608
+ }
476
609
  const code = typeof message.code === 'string'
477
610
  ? message.code
478
611
  : 'behavior_thread_worker_failed';
@@ -498,6 +631,15 @@ export class ThreadBehaviorExecutor {
498
631
  void this.retireSlot(slot, 'invalid_response');
499
632
  return;
500
633
  }
634
+ if (this.options.diagnosticsEnabled === true && (
635
+ !Number.isFinite(message.heapUsedBytes)
636
+ || Number(message.heapUsedBytes) < 0
637
+ )) {
638
+ this.rejectRequest(request, new Error('behavior_thread_worker_memory_invalid'));
639
+ void this.retireSlot(slot, 'invalid_response');
640
+ return;
641
+ }
642
+ if (typeof message.heapUsedBytes === 'number') this.updateWorkerHeap(slot, message.heapUsedBytes);
501
643
  slot.current = undefined;
502
644
  slot.state = 'idle';
503
645
  slot.idleSince = performance.now();
@@ -527,6 +669,11 @@ export class ThreadBehaviorExecutor {
527
669
  ) / 1_000,
528
670
  worker_duration_ms: message.durationMs,
529
671
  read_query_count: message.queryCount,
672
+ ...(this.options.diagnosticsEnabled === true ? {
673
+ worker_heap_used_bytes: message.heapUsedBytes,
674
+ worker_pool_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
675
+ peak_worker_pool_heap_used_bytes: this.peakWorkerHeapUsedBytes,
676
+ } : {}),
530
677
  }, 'debug');
531
678
  request.resolve(value);
532
679
  this.scheduleIdleScaleDown();
@@ -766,6 +913,21 @@ export class ThreadBehaviorExecutor {
766
913
  return [...this.slots].filter((slot) => slot.state !== 'retiring').length;
767
914
  }
768
915
 
916
+ private currentWorkerHeapUsedBytes(): number {
917
+ return [...this.slots].reduce(
918
+ (total, slot) => total + (slot.state === 'retiring' ? 0 : slot.heapUsedBytes ?? 0),
919
+ 0,
920
+ );
921
+ }
922
+
923
+ private updateWorkerHeap(slot: WorkerSlot, heapUsedBytes: number): void {
924
+ slot.heapUsedBytes = Math.max(0, heapUsedBytes);
925
+ this.peakWorkerHeapUsedBytes = Math.max(
926
+ this.peakWorkerHeapUsedBytes,
927
+ this.currentWorkerHeapUsedBytes(),
928
+ );
929
+ }
930
+
769
931
  private diagnostic(
770
932
  name: string,
771
933
  attributes?: Readonly<Record<string, unknown>>,
@@ -42,7 +42,11 @@ export const DEFAULT_MONITOR_BACKLOG_HINT_WINDOW_ITEM_BUDGET = 4;
42
42
  /** Minimum spacing between directly presented visual telemetry items. */
43
43
  export const DEFAULT_MONITOR_VISUAL_MIN_INTERVAL_MS = 5_000;
44
44
 
45
- const MONITOR_TERMINAL_EVENT_TYPES = new Set(['game_over', 'exile_game_over']);
45
+ const MONITOR_TERMINAL_EVENT_TYPES = new Set([
46
+ 'game_over',
47
+ 'exile_game_over',
48
+ 'game_over_recovered',
49
+ ]);
46
50
  const MONITOR_NOISY_VISUAL_EVENT_TYPES = new Set([
47
51
  'visual.player_moved',
48
52
  'visual.player_motion_changed',
@@ -1,4 +1,3 @@
1
- import { PERCEPTION_PLUGIN_API_VERSION } from './contracts.js';
2
1
  import type {
3
2
  ClawclawPerception,
4
3
  ClawclawPerceptionManifest,
@@ -11,6 +10,13 @@ import type {
11
10
  } from './contracts.js';
12
11
  import type { PerceptionModuleLoader } from './perception-module-loader.js';
13
12
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
13
+ import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
14
+ import { normalizePerceptionEvents } from './perception-module-output.js';
15
+ import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js';
16
+ import {
17
+ PerceptionReducerThreadPool,
18
+ type PerceptionReducerThreadPoolSnapshot,
19
+ } from './perception-reducer-thread-pool.js';
14
20
 
15
21
  function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
16
22
  if (!value || typeof value !== 'object') return value;
@@ -25,28 +31,6 @@ function isolatedClone<T>(value: T): T {
25
31
  return deepFreeze(structuredClone(value));
26
32
  }
27
33
 
28
- function isolatedEvents(
29
- value: readonly PerceptionEventProposal[] | void,
30
- manifest: ClawclawPerceptionManifest,
31
- ): readonly PerceptionEventProposal[] {
32
- if (value === undefined) return [];
33
- if (!Array.isArray(value)) throw new Error('perception_result_must_be_array');
34
- const declared = new Set(manifest.produces);
35
- return value.map((event, index) => {
36
- if (
37
- !event
38
- || typeof event !== 'object'
39
- || !declared.has(event.type)
40
- || typeof event.dedupeKey !== 'string'
41
- || !event.dedupeKey
42
- || !event.payload
43
- || typeof event.payload !== 'object'
44
- || Array.isArray(event.payload)
45
- ) throw new Error(`perception_event_invalid:${index}`);
46
- return structuredClone(event);
47
- });
48
- }
49
-
50
34
  export interface PerceptionModuleRunner {
51
35
  readonly manifest: ClawclawPerceptionManifest;
52
36
  readonly execution: 'ordered_update' | 'parallel_analysis';
@@ -54,6 +38,11 @@ export interface PerceptionModuleRunner {
54
38
  spatialFacts: PerceptionSpatialFacts,
55
39
  api: PerceptionApi,
56
40
  signal: AbortSignal,
41
+ diagnostic?: (
42
+ name: string,
43
+ attributes?: Readonly<Record<string, unknown>>,
44
+ severity?: RuntimeDiagnosticSeverity,
45
+ ) => void,
57
46
  ): void | Promise<void>;
58
47
  update(
59
48
  frame: Readonly<PerceptionFrame>,
@@ -82,6 +71,7 @@ export interface PerceptionModuleRunner {
82
71
  ): void | Promise<void>;
83
72
  stop(reason: 'segment_ending' | 'shutdown'): void | Promise<void>;
84
73
  debugSnapshot(): unknown;
74
+ reducerDiagnosticSnapshot?(): PerceptionReducerThreadPoolSnapshot | null;
85
75
  }
86
76
 
87
77
  export class LocalPerceptionModuleRunner implements PerceptionModuleRunner {
@@ -96,8 +86,8 @@ export class LocalPerceptionModuleRunner implements PerceptionModuleRunner {
96
86
 
97
87
  start(): void {}
98
88
 
99
- update(frame: Readonly<PerceptionFrame>, api: PerceptionApi) {
100
- return this.module.update(frame, api);
89
+ async update(frame: Readonly<PerceptionFrame>, api: PerceptionApi) {
90
+ return normalizePerceptionEvents(await this.module.update(frame, api), this.manifest);
101
91
  }
102
92
 
103
93
  async analyze(input: Readonly<PerceptionAnalysisInput>, api: PerceptionApi): Promise<unknown> {
@@ -110,7 +100,9 @@ export class LocalPerceptionModuleRunner implements PerceptionModuleRunner {
110
100
  ) => unknown | Promise<unknown>;
111
101
  };
112
102
  if (typeof analyzer.analyze !== 'function') throw new Error('parallel_perception_analyze_missing');
113
- return structuredClone(await analyzer.analyze(input, api));
103
+ const analysis = structuredClone(await analyzer.analyze(input, api));
104
+ assertRuntimeModuleOutputSize(analysis, 'perception_analysis_output');
105
+ return analysis;
114
106
  }
115
107
 
116
108
  async commit(frame: Readonly<PerceptionFrame>, analysis: unknown, api: PerceptionApi) {
@@ -126,7 +118,10 @@ export class LocalPerceptionModuleRunner implements PerceptionModuleRunner {
126
118
  };
127
119
  if (typeof reducer.commit !== 'function') throw new Error('parallel_perception_commit_missing');
128
120
  try {
129
- return await reducer.commit(frame, structuredClone(analysis), api);
121
+ return normalizePerceptionEvents(
122
+ await reducer.commit(frame, structuredClone(analysis), api),
123
+ this.manifest,
124
+ );
130
125
  } catch (error) {
131
126
  // commit() is allowed to mutate its private reducer before it throws.
132
127
  // Never reuse that unknowable state on the next ordered frame.
@@ -136,8 +131,8 @@ export class LocalPerceptionModuleRunner implements PerceptionModuleRunner {
136
131
  }
137
132
  }
138
133
 
139
- flush(boundary: Readonly<PerceptionBoundary>, api: PerceptionApi) {
140
- return this.module.flush?.(boundary, api);
134
+ async flush(boundary: Readonly<PerceptionBoundary>, api: PerceptionApi) {
135
+ return normalizePerceptionEvents(await this.module.flush?.(boundary, api), this.manifest);
141
136
  }
142
137
 
143
138
  async reset(reason: Parameters<NonNullable<ClawclawPerception['reset']>>[0]): Promise<void> {
@@ -159,32 +154,39 @@ export class LocalPerceptionModuleRunner implements PerceptionModuleRunner {
159
154
  }
160
155
  }
161
156
 
162
- /** Loads one installed source module, then keeps its reducer on the ordered main thread. */
157
+ /** Proxies one installed module to a persistent, memory-bounded reducer Worker lane. */
163
158
  export class ImportedLocalPerceptionModuleRunner implements PerceptionModuleRunner {
164
159
  readonly manifest: ClawclawPerceptionManifest;
165
160
  readonly execution: 'ordered_update' | 'parallel_analysis';
166
- private delegate?: LocalPerceptionModuleRunner;
161
+ private reducerPool?: PerceptionReducerThreadPool;
167
162
  private startTask?: Promise<void>;
168
163
  private lifecycleGeneration = 0;
164
+ private started = false;
169
165
 
170
166
  constructor(
171
167
  private readonly source: ResolvedClawclawPerceptionSource,
172
168
  private readonly loader: PerceptionModuleLoader,
169
+ reducerPool?: PerceptionReducerThreadPool,
173
170
  ) {
174
171
  this.manifest = source.manifest;
175
172
  this.execution = source.manifest.execution ?? 'ordered_update';
173
+ this.reducerPool = reducerPool;
176
174
  }
177
175
 
178
176
  start(
179
177
  spatialFacts: PerceptionSpatialFacts,
180
- api: PerceptionApi,
178
+ _api: PerceptionApi,
181
179
  signal: AbortSignal,
180
+ diagnostic?: (
181
+ name: string,
182
+ attributes?: Readonly<Record<string, unknown>>,
183
+ severity?: RuntimeDiagnosticSeverity,
184
+ ) => void,
182
185
  ): Promise<void> {
183
- if (this.delegate) return Promise.resolve();
184
186
  if (this.startTask) return this.startTask;
185
187
  const generation = ++this.lifecycleGeneration;
186
188
  let task!: Promise<void>;
187
- task = this.startInternal(spatialFacts, api, signal, generation).finally(() => {
189
+ task = this.startInternal(spatialFacts, signal, diagnostic, generation).finally(() => {
188
190
  if (this.startTask === task) this.startTask = undefined;
189
191
  });
190
192
  this.startTask = task;
@@ -192,101 +194,96 @@ export class ImportedLocalPerceptionModuleRunner implements PerceptionModuleRunn
192
194
  }
193
195
 
194
196
  private async startInternal(
195
- _spatialFacts: PerceptionSpatialFacts,
196
- _api: PerceptionApi,
197
+ spatialFacts: PerceptionSpatialFacts,
197
198
  signal: AbortSignal,
199
+ diagnostic: ((
200
+ name: string,
201
+ attributes?: Readonly<Record<string, unknown>>,
202
+ severity?: RuntimeDiagnosticSeverity,
203
+ ) => void) | undefined,
198
204
  generation: number,
199
205
  ): Promise<void> {
200
206
  signal.throwIfAborted();
201
- const ModuleClass = await this.loader.load(this.source);
207
+ const pool = this.reducerPool ?? new PerceptionReducerThreadPool({
208
+ modules: [this.loader.threadSpec(this.source)],
209
+ loader: this.loader.threadConfig(),
210
+ spatialFacts,
211
+ diagnostic,
212
+ });
213
+ this.reducerPool = pool;
214
+ pool.setDiagnostic(diagnostic);
215
+ await pool.start();
202
216
  signal.throwIfAborted();
203
217
  if (generation !== this.lifecycleGeneration) {
204
218
  throw new Error('perception_module_start_cancelled');
205
219
  }
206
- const manifest = ModuleClass.manifest;
207
- if (
208
- !manifest
209
- || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
210
- || manifest.id !== this.manifest.id
211
- || (manifest.execution ?? 'ordered_update') !== this.execution
212
- || JSON.stringify(manifest.produces) !== JSON.stringify(this.manifest.produces)
213
- ) throw new Error(`Perception module '${this.source.id}' changed after discovery.`);
214
- const instance = new ModuleClass();
215
- if (
216
- !instance
217
- || typeof instance !== 'object'
218
- || (this.execution === 'ordered_update' && typeof instance.update !== 'function')
219
- || (this.execution === 'parallel_analysis' && (
220
- typeof (instance as any).analyze !== 'function'
221
- || typeof (instance as any).commit !== 'function'
222
- ))
223
- ) throw new Error(`Perception module '${this.source.id}' does not implement its execution contract.`);
224
- const delegate = new LocalPerceptionModuleRunner(instance, manifest);
225
- await delegate.start();
226
- try {
227
- signal.throwIfAborted();
228
- if (generation !== this.lifecycleGeneration) {
229
- throw new Error('perception_module_start_cancelled');
230
- }
231
- } catch (error) {
232
- await delegate.stop('shutdown').catch(() => {});
233
- throw error;
234
- }
235
- this.delegate = delegate;
220
+ pool.assertAvailable(this.manifest.id);
221
+ this.started = true;
236
222
  }
237
223
 
238
224
  async update(frame: Readonly<PerceptionFrame>, api: PerceptionApi, signal: AbortSignal) {
239
225
  signal.throwIfAborted();
240
- return isolatedEvents(
241
- await this.required().update(isolatedClone(frame), api),
242
- this.manifest,
226
+ void api;
227
+ return this.required().operate(
228
+ this.manifest.id,
229
+ 'update',
230
+ { frame: isolatedClone(frame) },
231
+ signal,
243
232
  );
244
233
  }
245
234
 
246
235
  async analyze(input: Readonly<PerceptionAnalysisInput>, api: PerceptionApi, signal: AbortSignal) {
247
236
  signal.throwIfAborted();
248
- return structuredClone(await this.required().analyze(isolatedClone(input), api));
237
+ void input;
238
+ void api;
239
+ throw new Error('perception_parallel_analysis_uses_analysis_pool');
249
240
  }
250
241
 
251
242
  async commit(frame: Readonly<PerceptionFrame>, analysis: unknown, api: PerceptionApi, signal: AbortSignal) {
252
243
  signal.throwIfAborted();
253
- return isolatedEvents(
254
- await this.required().commit(
255
- isolatedClone(frame),
256
- isolatedClone(analysis),
257
- api,
258
- ),
259
- this.manifest,
244
+ void api;
245
+ return this.required().operate(
246
+ this.manifest.id,
247
+ 'commit',
248
+ { frame: isolatedClone(frame), analysis: isolatedClone(analysis) },
249
+ signal,
260
250
  );
261
251
  }
262
252
 
263
253
  async flush(boundary: Readonly<PerceptionBoundary>, api: PerceptionApi, signal: AbortSignal) {
264
254
  signal.throwIfAborted();
265
- return isolatedEvents(
266
- await this.required().flush(isolatedClone(boundary), api),
267
- this.manifest,
255
+ void api;
256
+ return this.required().operate(
257
+ this.manifest.id,
258
+ 'flush',
259
+ { boundary: isolatedClone(boundary) },
260
+ signal,
268
261
  );
269
262
  }
270
263
 
271
264
  reset(reason: Parameters<NonNullable<ClawclawPerception['reset']>>[0], signal: AbortSignal) {
272
265
  signal.throwIfAborted();
273
- return this.required().reset(reason);
266
+ return this.required().operate(this.manifest.id, 'reset', { reason }, signal).then(() => {});
274
267
  }
275
268
 
276
269
  async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
277
270
  this.lifecycleGeneration += 1;
278
271
  this.startTask = undefined;
279
- const delegate = this.delegate;
280
- this.delegate = undefined;
281
- if (delegate) await delegate.stop(reason);
272
+ this.started = false;
273
+ await this.reducerPool?.releaseModule(this.manifest.id, reason);
282
274
  }
283
275
 
284
276
  debugSnapshot(): unknown {
285
- return this.delegate?.debugSnapshot() ?? null;
277
+ return this.started ? this.reducerPool?.debugSnapshot(this.manifest.id) ?? null : null;
278
+ }
279
+
280
+ reducerDiagnosticSnapshot(): PerceptionReducerThreadPoolSnapshot | null {
281
+ return this.reducerPool?.snapshot() ?? null;
286
282
  }
287
283
 
288
- private required(): LocalPerceptionModuleRunner {
289
- if (!this.delegate) throw new Error('perception_module_not_started');
290
- return this.delegate;
284
+ private required(): PerceptionReducerThreadPool {
285
+ if (!this.reducerPool || !this.started) throw new Error('perception_module_not_started');
286
+ this.reducerPool.assertAvailable(this.manifest.id);
287
+ return this.reducerPool;
291
288
  }
292
289
  }