@myclaw163/clawclaw-cli 0.8.14 → 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 (44) 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 +5 -1
  8. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  9. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  10. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  11. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  12. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  13. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  14. package/src/runtime/clawclaw/owner.ts +64 -1
  15. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  16. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  17. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  18. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  19. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +46 -50
  20. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +39 -9
  21. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +167 -7
  22. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  23. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  24. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +28 -4
  25. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  26. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  27. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +114 -17
  28. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  29. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  30. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  31. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  32. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  33. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  34. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  35. package/src/runtime/framework/events/memory-event-repository.ts +12 -0
  36. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  37. package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
  38. package/src/runtime/framework/plugins/contracts.ts +3 -0
  39. package/src/runtime/framework/plugins/runtime-input-journal.ts +12 -0
  40. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +150 -23
  41. package/src/runtime/framework/runtime.ts +18 -0
  42. package/src/runtime/framework/state/history/memory-state-history-repository.ts +10 -0
  43. package/src/runtime/observability/redaction.ts +28 -1
  44. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -50,6 +50,8 @@ export interface PerceptionAnalysisBatch {
50
50
  readonly queueDurationMs: number;
51
51
  readonly durationMs: number;
52
52
  readonly workerCount: number;
53
+ readonly workerHeapUsedBytes: number;
54
+ readonly workerPoolHeapUsedBytes: number;
53
55
  }
54
56
 
55
57
  export interface PerceptionAnalysisThreadPoolSnapshot {
@@ -60,10 +62,12 @@ export interface PerceptionAnalysisThreadPoolSnapshot {
60
62
  readonly idleWorkerCount: number;
61
63
  readonly busyWorkerCount: number;
62
64
  readonly queuedBatchCount: number;
65
+ readonly queuedJobCount: number;
63
66
  readonly inFlightBatchCount: number;
64
67
  readonly startedWorkerCount: number;
65
68
  readonly retiredWorkerCount: number;
66
69
  readonly startupWorkerHeapUsedBytes: number;
70
+ readonly workerHeapUsedBytes: number;
67
71
  readonly peakWorkerHeapUsedBytes: number;
68
72
  }
69
73
 
@@ -73,6 +77,8 @@ export interface PerceptionAnalysisThreadPoolOptions {
73
77
  readonly spatialFacts: PerceptionSpatialFacts;
74
78
  readonly maxWorkers?: number;
75
79
  readonly maxOldGenerationSizeMb?: number;
80
+ /** Samples Worker heaps only for explicit full diagnostics. */
81
+ readonly diagnosticsEnabled?: boolean;
76
82
  readonly diagnostic?: (
77
83
  name: string,
78
84
  attributes?: Readonly<Record<string, unknown>>,
@@ -88,16 +94,27 @@ interface PendingBatch {
88
94
  readonly resolve: (value: PerceptionAnalysisBatch) => void;
89
95
  readonly reject: (error: Error) => void;
90
96
  readonly onAbort: () => void;
97
+ readonly results: Array<PerceptionAnalysisResult | undefined>;
98
+ firstAssignedAt?: number;
99
+ remaining: number;
100
+ peakWorkerHeapUsedBytes: number;
101
+ settled: boolean;
102
+ }
103
+
104
+ interface PendingModuleJob {
105
+ readonly requestId: string;
106
+ readonly batch: PendingBatch;
107
+ readonly index: number;
108
+ readonly job: PerceptionAnalysisJob;
91
109
  assignedAt?: number;
92
110
  slot?: WorkerSlot;
93
- settled: boolean;
94
111
  }
95
112
 
96
113
  interface WorkerSlot {
97
114
  readonly id: number;
98
115
  readonly worker: Worker;
99
116
  state: 'starting' | 'idle' | 'busy' | 'retiring';
100
- current?: PendingBatch;
117
+ current?: PendingModuleJob;
101
118
  readyResolve?: () => void;
102
119
  readyReject?: (error: Error) => void;
103
120
  readyHeapUsedBytes?: number;
@@ -113,7 +130,7 @@ interface ReplacementDelay {
113
130
  interface WorkerReadyMessage {
114
131
  readonly type: 'ready';
115
132
  readonly poolId: string;
116
- readonly heapUsedBytes: number;
133
+ readonly heapUsedBytes?: number;
117
134
  }
118
135
 
119
136
  interface WorkerAnalysisMessage {
@@ -121,6 +138,7 @@ interface WorkerAnalysisMessage {
121
138
  readonly poolId: string;
122
139
  readonly requestId: string;
123
140
  readonly results: readonly PerceptionAnalysisResult[];
141
+ readonly heapUsedBytes?: number;
124
142
  }
125
143
 
126
144
  interface WorkerErrorMessage {
@@ -129,6 +147,7 @@ interface WorkerErrorMessage {
129
147
  readonly requestId?: string;
130
148
  readonly code: string;
131
149
  readonly moduleId?: string;
150
+ readonly heapUsedBytes?: number;
132
151
  }
133
152
 
134
153
  interface PerceptionAnalysisWorkerStartError extends Error {
@@ -154,6 +173,16 @@ function abortError(signal: AbortSignal): Error {
154
173
  return asError(signal.reason, 'perception_analysis_aborted');
155
174
  }
156
175
 
176
+ function moduleFailure(error: unknown): PerceptionAnalysisFailure {
177
+ const message = error instanceof Error ? error.message : String(error);
178
+ const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1];
179
+ return {
180
+ errorCode: prefix ?? 'PERCEPTION_MODULE_FAILED',
181
+ messagePresent: message.length > 0,
182
+ ...(message ? { messageLength: message.length } : {}),
183
+ };
184
+ }
185
+
157
186
  export class PerceptionAnalysisThreadPool {
158
187
  private readonly poolId = randomUUID();
159
188
  private readonly minWorkers: number;
@@ -161,7 +190,7 @@ export class PerceptionAnalysisThreadPool {
161
190
  private readonly maxOldGenerationSizeMb: number;
162
191
  private state: PerceptionAnalysisThreadPoolSnapshot['state'] = 'new';
163
192
  private readonly slots = new Set<WorkerSlot>();
164
- private readonly queue: PendingBatch[] = [];
193
+ private readonly queue: PendingModuleJob[] = [];
165
194
  private readonly inFlight = new Set<PendingBatch>();
166
195
  private readonly spawnTasks = new Set<Promise<void>>();
167
196
  private startTask?: Promise<void>;
@@ -230,7 +259,14 @@ export class PerceptionAnalysisThreadPool {
230
259
  signal.throwIfAborted();
231
260
  if (this.state !== 'running') throw new Error('perception_analysis_pool_not_running');
232
261
  if (jobs.length === 0) {
233
- return { results: [], queueDurationMs: 0, durationMs: 0, workerCount: this.slots.size };
262
+ return {
263
+ results: [],
264
+ queueDurationMs: 0,
265
+ durationMs: 0,
266
+ workerCount: this.slots.size,
267
+ workerHeapUsedBytes: 0,
268
+ workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
269
+ };
234
270
  }
235
271
  if (this.inFlight.size >= this.maxWorkers) {
236
272
  throw new Error('perception_analysis_window_full');
@@ -248,12 +284,20 @@ export class PerceptionAnalysisThreadPool {
248
284
  enqueuedAt: performance.now(),
249
285
  resolve,
250
286
  reject,
287
+ results: new Array(jobs.length),
288
+ remaining: jobs.length,
289
+ peakWorkerHeapUsedBytes: 0,
251
290
  settled: false,
252
291
  onAbort: () => this.abortBatch(pending),
253
292
  };
254
293
  signal.addEventListener('abort', pending.onAbort, { once: true });
255
294
  this.inFlight.add(pending);
256
- this.queue.push(pending);
295
+ this.queue.push(...jobs.map((job, index): PendingModuleJob => ({
296
+ requestId: `${pending.requestId}:${index}`,
297
+ batch: pending,
298
+ index,
299
+ job,
300
+ })));
257
301
  this.pump();
258
302
  });
259
303
  }
@@ -303,11 +347,13 @@ export class PerceptionAnalysisThreadPool {
303
347
  workerCount: values.length,
304
348
  idleWorkerCount: values.filter(({ state }) => state === 'idle').length,
305
349
  busyWorkerCount: values.filter(({ state }) => state === 'busy').length,
306
- queuedBatchCount: this.queue.length,
350
+ queuedBatchCount: new Set(this.queue.map(({ batch }) => batch.requestId)).size,
351
+ queuedJobCount: this.queue.length,
307
352
  inFlightBatchCount: this.inFlight.size,
308
353
  startedWorkerCount: this.startedWorkerCount,
309
354
  retiredWorkerCount: this.retiredWorkerCount,
310
355
  startupWorkerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
356
+ workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
311
357
  peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
312
358
  };
313
359
  }
@@ -340,6 +386,7 @@ export class PerceptionAnalysisThreadPool {
340
386
  poolId: this.poolId,
341
387
  spatialFacts: this.options.spatialFacts,
342
388
  modules: this.options.modules,
389
+ diagnosticsEnabled: this.options.diagnosticsEnabled === true,
343
390
  },
344
391
  });
345
392
  const slot: WorkerSlot = { id: this.nextSlotId++, worker, state: 'starting' };
@@ -400,25 +447,28 @@ export class PerceptionAnalysisThreadPool {
400
447
  while (this.queue.length > 0) {
401
448
  const slot = [...this.slots].find((candidate) => candidate.state === 'idle');
402
449
  if (!slot) break;
403
- const batch = this.queue.shift()!;
450
+ const moduleJob = this.queue.shift()!;
451
+ const { batch } = moduleJob;
404
452
  if (batch.settled || batch.signal.aborted) {
405
453
  if (!batch.settled) this.rejectBatch(batch, abortError(batch.signal));
406
454
  continue;
407
455
  }
408
456
  slot.state = 'busy';
409
457
  slot.idleSince = undefined;
410
- slot.current = batch;
411
- batch.slot = slot;
412
- batch.assignedAt = performance.now();
458
+ slot.current = moduleJob;
459
+ moduleJob.slot = slot;
460
+ moduleJob.assignedAt = performance.now();
461
+ batch.firstAssignedAt ??= moduleJob.assignedAt;
413
462
  try {
414
463
  slot.worker.postMessage({
415
464
  type: 'analyze',
416
465
  poolId: this.poolId,
417
- requestId: batch.requestId,
418
- jobs: batch.jobs,
466
+ requestId: moduleJob.requestId,
467
+ jobs: [moduleJob.job],
419
468
  });
420
469
  } catch (error) {
421
- this.rejectBatch(batch, asError(error, 'perception_analysis_submit_failed'));
470
+ this.failModuleJob(moduleJob, asError(error, 'perception_analysis_submit_failed'));
471
+ slot.current = undefined;
422
472
  void this.retireSlot(slot, 'submit_failed');
423
473
  }
424
474
  }
@@ -440,15 +490,27 @@ export class PerceptionAnalysisThreadPool {
440
490
  this.failSlot(slot, new Error('perception_analysis_ready_unexpected'));
441
491
  return;
442
492
  }
443
- if (!Number.isFinite(message.heapUsedBytes) || message.heapUsedBytes < 0) {
493
+ if (this.options.diagnosticsEnabled === true && (
494
+ !Number.isFinite(message.heapUsedBytes)
495
+ || Number(message.heapUsedBytes) < 0
496
+ )) {
444
497
  this.failSlot(slot, new Error('perception_analysis_worker_memory_invalid'));
445
498
  return;
446
499
  }
447
- slot.readyHeapUsedBytes = message.heapUsedBytes;
500
+ if (typeof message.heapUsedBytes === 'number') {
501
+ slot.readyHeapUsedBytes = message.heapUsedBytes;
502
+ }
448
503
  slot.readyResolve?.();
449
504
  return;
450
505
  }
451
506
  if (message.type === 'error') {
507
+ if (typeof message.heapUsedBytes === 'number' && Number.isFinite(message.heapUsedBytes)) {
508
+ slot.readyHeapUsedBytes = Math.max(0, message.heapUsedBytes);
509
+ this.peakWorkerHeapUsedBytes = Math.max(
510
+ this.peakWorkerHeapUsedBytes,
511
+ this.currentWorkerHeapUsedBytes(),
512
+ );
513
+ }
452
514
  const error: PerceptionAnalysisWorkerStartError = new Error(typeof message.code === 'string'
453
515
  ? message.code
454
516
  : 'perception_analysis_worker_failed');
@@ -462,7 +524,9 @@ export class PerceptionAnalysisThreadPool {
462
524
  return;
463
525
  }
464
526
  if (slot.current && (!message.requestId || message.requestId === slot.current.requestId)) {
465
- this.rejectBatch(slot.current, error);
527
+ const moduleJob = slot.current;
528
+ slot.current = undefined;
529
+ this.failModuleJob(moduleJob, error);
466
530
  }
467
531
  void this.retireSlot(slot, 'worker_error');
468
532
  return;
@@ -471,51 +535,82 @@ export class PerceptionAnalysisThreadPool {
471
535
  this.failSlot(slot, new Error('perception_analysis_protocol_invalid'));
472
536
  return;
473
537
  }
474
- const batch = slot.current;
475
- if (!batch || message.requestId !== batch.requestId) {
538
+ if (this.options.diagnosticsEnabled === true && (
539
+ !Number.isFinite(message.heapUsedBytes)
540
+ || Number(message.heapUsedBytes) < 0
541
+ )) {
542
+ this.failSlot(slot, new Error('perception_analysis_worker_memory_invalid'));
543
+ return;
544
+ }
545
+ const moduleJob = slot.current;
546
+ if (!moduleJob || message.requestId !== moduleJob.requestId) {
476
547
  this.failSlot(slot, new Error('perception_analysis_request_mismatch'));
477
548
  return;
478
549
  }
479
- const expected = batch.jobs.map(({ moduleId }) => moduleId);
480
- const actual = message.results.map(({ moduleId }) => moduleId);
481
- if (actual.length !== expected.length || actual.some((id, index) => id !== expected[index])) {
482
- this.rejectBatch(batch, new Error('perception_analysis_results_invalid'));
550
+ const { batch } = moduleJob;
551
+ const result = message.results[0];
552
+ if (
553
+ message.results.length !== 1
554
+ || result?.moduleId !== moduleJob.job.moduleId
555
+ ) {
556
+ slot.current = undefined;
557
+ this.failModuleJob(moduleJob, new Error('perception_analysis_results_invalid'));
483
558
  void this.retireSlot(slot, 'invalid_results');
484
559
  return;
485
560
  }
486
561
  slot.current = undefined;
487
562
  slot.state = 'idle';
488
563
  slot.idleSince = performance.now();
489
- batch.slot = undefined;
490
- this.resolveBatch(batch, message.results);
564
+ if (typeof message.heapUsedBytes === 'number') slot.readyHeapUsedBytes = message.heapUsedBytes;
565
+ this.peakWorkerHeapUsedBytes = Math.max(
566
+ this.peakWorkerHeapUsedBytes,
567
+ this.currentWorkerHeapUsedBytes(),
568
+ );
569
+ moduleJob.slot = undefined;
570
+ if (!batch.settled) {
571
+ batch.results[moduleJob.index] = result;
572
+ batch.remaining -= 1;
573
+ batch.peakWorkerHeapUsedBytes = Math.max(
574
+ batch.peakWorkerHeapUsedBytes,
575
+ message.heapUsedBytes ?? 0,
576
+ );
577
+ if (batch.remaining === 0) this.resolveBatch(batch);
578
+ }
491
579
  this.pump();
492
580
  }
493
581
 
494
582
  private abortBatch(batch: PendingBatch): void {
495
583
  if (batch.settled) return;
496
- const queueIndex = this.queue.indexOf(batch);
497
- if (queueIndex >= 0) this.queue.splice(queueIndex, 1);
498
- const slot = batch.slot;
584
+ const slots = [...this.slots].filter(({ current }) => current?.batch === batch);
499
585
  this.rejectBatch(batch, abortError(batch.signal));
500
- // Worker threads cannot interrupt synchronous module code. Retire only the
501
- // slot that owns this stale frame; reducers and other frame slots survive.
502
- if (slot) void this.retireSlot(slot, 'analysis_aborted');
586
+ // Worker threads cannot interrupt synchronous module code. Retire only
587
+ // slots executing jobs from this stale frame; other frame jobs survive.
588
+ for (const slot of slots) void this.retireSlot(slot, 'analysis_aborted');
503
589
  this.pump();
504
590
  }
505
591
 
506
592
  private resolveBatch(
507
593
  batch: PendingBatch,
508
- results: readonly PerceptionAnalysisResult[],
509
594
  ): void {
510
595
  if (batch.settled) return;
511
596
  batch.settled = true;
512
597
  batch.signal.removeEventListener('abort', batch.onAbort);
513
598
  this.inFlight.delete(batch);
599
+ const results = batch.results.filter((result): result is PerceptionAnalysisResult => !!result);
600
+ if (results.length !== batch.jobs.length) {
601
+ batch.reject(new Error('perception_analysis_results_incomplete'));
602
+ return;
603
+ }
514
604
  batch.resolve({
515
605
  results,
516
- queueDurationMs: Math.round(Math.max(0, (batch.assignedAt ?? performance.now()) - batch.enqueuedAt) * 1_000) / 1_000,
606
+ queueDurationMs: Math.round(Math.max(
607
+ 0,
608
+ (batch.firstAssignedAt ?? performance.now()) - batch.enqueuedAt,
609
+ ) * 1_000) / 1_000,
517
610
  durationMs: roundedElapsed(batch.enqueuedAt),
518
611
  workerCount: this.slots.size,
612
+ workerHeapUsedBytes: batch.peakWorkerHeapUsedBytes,
613
+ workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
519
614
  });
520
615
  }
521
616
 
@@ -524,16 +619,33 @@ export class PerceptionAnalysisThreadPool {
524
619
  batch.settled = true;
525
620
  batch.signal.removeEventListener('abort', batch.onAbort);
526
621
  this.inFlight.delete(batch);
527
- const queueIndex = this.queue.indexOf(batch);
528
- if (queueIndex >= 0) this.queue.splice(queueIndex, 1);
529
- if (batch.slot?.current === batch) batch.slot.current = undefined;
530
- batch.slot = undefined;
622
+ for (let index = this.queue.length - 1; index >= 0; index -= 1) {
623
+ if (this.queue[index]!.batch === batch) this.queue.splice(index, 1);
624
+ }
531
625
  batch.reject(error);
532
626
  }
533
627
 
628
+ private failModuleJob(moduleJob: PendingModuleJob, error: Error): void {
629
+ const { batch } = moduleJob;
630
+ moduleJob.slot = undefined;
631
+ if (batch.settled || batch.results[moduleJob.index]) return;
632
+ batch.results[moduleJob.index] = {
633
+ moduleId: moduleJob.job.moduleId,
634
+ durationMs: roundedElapsed(moduleJob.assignedAt ?? batch.enqueuedAt),
635
+ outcome: 'rejected',
636
+ failure: moduleFailure(error),
637
+ };
638
+ batch.remaining -= 1;
639
+ if (batch.remaining === 0) this.resolveBatch(batch);
640
+ }
641
+
534
642
  private failSlot(slot: WorkerSlot, error: Error): void {
535
643
  slot.readyReject?.(error);
536
- if (slot.current) this.rejectBatch(slot.current, error);
644
+ if (slot.current) {
645
+ const moduleJob = slot.current;
646
+ slot.current = undefined;
647
+ this.failModuleJob(moduleJob, error);
648
+ }
537
649
  void this.retireSlot(slot, 'failed');
538
650
  }
539
651
 
@@ -541,7 +653,9 @@ export class PerceptionAnalysisThreadPool {
541
653
  if (slot.retirement) return slot.retirement;
542
654
  slot.state = 'retiring';
543
655
  if (slot.current) {
544
- this.rejectBatch(slot.current, new Error(`perception_analysis_worker_retired:${reason}`));
656
+ const moduleJob = slot.current;
657
+ slot.current = undefined;
658
+ this.failModuleJob(moduleJob, new Error(`perception_analysis_worker_retired:${reason}`));
545
659
  }
546
660
  const retirement = Promise.resolve().then(() => slot.worker.terminate()).catch(() => -1).then(() => {
547
661
  this.slots.delete(slot);
@@ -590,7 +704,8 @@ export class PerceptionAnalysisThreadPool {
590
704
  consecutive_failures: this.replacementFailureCount,
591
705
  retry_delay_ms: this.replacementRetryDelayMs(),
592
706
  worker_count: this.activeWorkerCount(),
593
- queued_batch_count: this.queue.length,
707
+ queued_batch_count: new Set(this.queue.map(({ batch }) => batch.requestId)).size,
708
+ queued_job_count: this.queue.length,
594
709
  trigger,
595
710
  }, 'error');
596
711
  }).finally(() => {
@@ -632,9 +747,10 @@ export class PerceptionAnalysisThreadPool {
632
747
  }
633
748
 
634
749
  private desiredWorkerCount(): number {
750
+ const busyWorkerCount = [...this.slots].filter(({ state }) => state === 'busy').length;
635
751
  return Math.max(
636
752
  this.minWorkers,
637
- Math.min(this.maxWorkers, this.inFlight.size),
753
+ Math.min(this.maxWorkers, this.queue.length + busyWorkerCount),
638
754
  );
639
755
  }
640
756
 
@@ -11,11 +11,13 @@ import type {
11
11
  PerceptionAnalysisResult,
12
12
  } from './perception-analysis-thread-pool.js';
13
13
  import type { PerceptionThreadModuleSpec } from './perception-module-loader.js';
14
+ import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
14
15
 
15
16
  interface PerceptionAnalysisWorkerData {
16
17
  readonly poolId: string;
17
18
  readonly spatialFacts: SpatialFacts;
18
19
  readonly modules: readonly PerceptionThreadModuleSpec[];
20
+ readonly diagnosticsEnabled?: boolean;
19
21
  }
20
22
 
21
23
  interface PerceptionAnalysisRequest {
@@ -30,12 +32,13 @@ interface PerceptionAnalysisResponse {
30
32
  readonly poolId: string;
31
33
  readonly requestId: string;
32
34
  readonly results: readonly PerceptionAnalysisResult[];
35
+ readonly heapUsedBytes?: number;
33
36
  }
34
37
 
35
38
  interface PerceptionAnalysisWorkerReady {
36
39
  readonly type: 'ready';
37
40
  readonly poolId: string;
38
- readonly heapUsedBytes: number;
41
+ readonly heapUsedBytes?: number;
39
42
  }
40
43
 
41
44
  interface PerceptionAnalysisWorkerError {
@@ -45,12 +48,19 @@ interface PerceptionAnalysisWorkerError {
45
48
  readonly code: string;
46
49
  /** Present only when Worker initialization can attribute the failure. */
47
50
  readonly moduleId?: string;
51
+ readonly heapUsedBytes?: number;
48
52
  }
49
53
 
50
54
  function roundedElapsed(startedAt: number): number {
51
55
  return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
52
56
  }
53
57
 
58
+ function diagnosticMemory(): Readonly<Record<string, number>> {
59
+ return data?.diagnosticsEnabled === true
60
+ ? { heapUsedBytes: process.memoryUsage().heapUsed }
61
+ : {};
62
+ }
63
+
54
64
  function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
55
65
  if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
56
66
  const object = value as object;
@@ -97,6 +107,7 @@ async function analyzeJob(
97
107
  // without cloning the ten-frame history once again per module.
98
108
  const isolatedInput = deepFreeze(job.input);
99
109
  const analysis = structuredClone(await analyzer.analyze(isolatedInput, api));
110
+ assertRuntimeModuleOutputSize(analysis, 'perception_analysis_output');
100
111
  return {
101
112
  moduleId: job.moduleId,
102
113
  outcome: 'fulfilled',
@@ -165,6 +176,7 @@ for (const spec of data.modules) {
165
176
  poolId: data.poolId,
166
177
  code: 'perception_analysis_worker_module_load_failed',
167
178
  ...(moduleId ? { moduleId } : {}),
179
+ ...diagnosticMemory(),
168
180
  });
169
181
  startupFailed = true;
170
182
  break;
@@ -179,7 +191,12 @@ async function handle(value: unknown): Promise<void> {
179
191
  || Array.isArray(value)
180
192
  || (value as Partial<PerceptionAnalysisRequest>).type !== 'analyze'
181
193
  ) {
182
- send({ type: 'error', poolId: data!.poolId!, code: 'perception_analysis_worker_request_invalid' });
194
+ send({
195
+ type: 'error',
196
+ poolId: data!.poolId!,
197
+ code: 'perception_analysis_worker_request_invalid',
198
+ ...diagnosticMemory(),
199
+ });
183
200
  return;
184
201
  }
185
202
  const request = value as Partial<PerceptionAnalysisRequest>;
@@ -194,6 +211,7 @@ async function handle(value: unknown): Promise<void> {
194
211
  poolId: data!.poolId!,
195
212
  ...(typeof request.requestId === 'string' ? { requestId: request.requestId } : {}),
196
213
  code: 'perception_analysis_worker_request_invalid',
214
+ ...diagnosticMemory(),
197
215
  });
198
216
  return;
199
217
  }
@@ -203,6 +221,7 @@ async function handle(value: unknown): Promise<void> {
203
221
  poolId: data!.poolId!,
204
222
  requestId: request.requestId,
205
223
  results,
224
+ ...diagnosticMemory(),
206
225
  });
207
226
  }
208
227
 
@@ -212,14 +231,19 @@ if (!startupFailed) {
212
231
  // so a parent-side protocol regression still cannot overlap two batches in
213
232
  // one isolate.
214
233
  operationTail = operationTail.then(() => handle(value)).catch(() => {
215
- send({ type: 'error', poolId: data!.poolId!, code: 'perception_analysis_worker_failed' });
234
+ send({
235
+ type: 'error',
236
+ poolId: data!.poolId!,
237
+ code: 'perception_analysis_worker_failed',
238
+ ...diagnosticMemory(),
239
+ });
216
240
  });
217
241
  });
218
242
 
219
243
  send({
220
244
  type: 'ready',
221
245
  poolId: data.poolId,
222
- heapUsedBytes: process.memoryUsage().heapUsed,
246
+ ...diagnosticMemory(),
223
247
  });
224
248
  } else {
225
249
  // Keep the port alive until the parent retires this failed startup slot.
@@ -15,6 +15,7 @@ import { assertPluginApiVersion } from '../plugin-api-version.js';
15
15
  export interface PerceptionThreadModuleSpec {
16
16
  readonly moduleId: string;
17
17
  readonly sourceUrl: string;
18
+ readonly manifest: ResolvedClawclawPerceptionSource['manifest'];
18
19
  }
19
20
 
20
21
  export interface PerceptionThreadLoaderConfig {
@@ -22,7 +23,7 @@ export interface PerceptionThreadLoaderConfig {
22
23
  readonly sdkAliases: Readonly<Record<string, string>>;
23
24
  }
24
25
 
25
- /** One Runtime-scoped direct importer shared by reducers and frame Workers. */
26
+ /** Resolves one Runtime-scoped source URL for reducer and analysis Workers. */
26
27
  export class PerceptionModuleLoader {
27
28
  private readonly runtimeId = randomUUID();
28
29
  private readonly loaded = new Map<string, Promise<ClawclawPerceptionClass>>();
@@ -40,6 +41,7 @@ export class PerceptionModuleLoader {
40
41
  return {
41
42
  moduleId: source.id,
42
43
  sourceUrl: this.sourceUrl(source),
44
+ manifest: structuredClone(source.manifest),
43
45
  };
44
46
  }
45
47
 
@@ -0,0 +1,30 @@
1
+ import type {
2
+ ClawclawPerceptionManifest,
3
+ PerceptionEventProposal,
4
+ } from './contracts.js';
5
+ import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
6
+
7
+ /** Validates and detaches user-authored Event output before it reaches Runtime. */
8
+ export function normalizePerceptionEvents(
9
+ value: readonly PerceptionEventProposal[] | void,
10
+ manifest: ClawclawPerceptionManifest,
11
+ ): readonly PerceptionEventProposal[] {
12
+ if (value === undefined) return [];
13
+ if (!Array.isArray(value)) throw new Error('perception_result_must_be_array');
14
+ const declared = new Set(manifest.produces);
15
+ const events = value.map((event, index) => {
16
+ if (
17
+ !event
18
+ || typeof event !== 'object'
19
+ || !declared.has(event.type)
20
+ || typeof event.dedupeKey !== 'string'
21
+ || !event.dedupeKey
22
+ || !event.payload
23
+ || typeof event.payload !== 'object'
24
+ || Array.isArray(event.payload)
25
+ ) throw new Error(`perception_event_invalid:${index}`);
26
+ return structuredClone(event);
27
+ });
28
+ assertRuntimeModuleOutputSize(events, 'perception_event_output');
29
+ return events;
30
+ }