@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
@@ -10,6 +10,7 @@ import {
10
10
  writeFileSync,
11
11
  } from 'node:fs';
12
12
  import { join } from 'node:path';
13
+ import { getHeapStatistics } from 'node:v8';
13
14
  import type { AuthProfile } from '../../lib/auth.js';
14
15
  import { GameClient } from '../../lib/game-client.js';
15
16
  import { getProfileRuntimeStateDir, getWorkspaceDir } from '../../lib/init-command.js';
@@ -118,6 +119,8 @@ import {
118
119
  getUserDataAccountTriggersDir,
119
120
  } from '../../lib/user-data.js';
120
121
 
122
+ const FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS = 5_000;
123
+
121
124
  export interface ClawclawOwnerOptions {
122
125
  profile: AuthProfile;
123
126
  intent: ClawclawSourceStartIntent;
@@ -679,6 +682,7 @@ export async function runClawclawOwner(
679
682
  let relayAbort: AbortController | undefined;
680
683
  let relayPromise: Promise<void> | undefined;
681
684
  let parentWatch: ParentProcessWatchHandle | undefined;
685
+ let diagnosticSampleTimer: ReturnType<typeof setInterval> | undefined;
682
686
  let localStopRequested = false;
683
687
  let forceExitTimer: ReturnType<typeof setTimeout> | undefined;
684
688
  const channelPolicy = channelOwnerDeliveryPolicy(options.channelDelivery);
@@ -696,7 +700,8 @@ export async function runClawclawOwner(
696
700
  force: options.forceExistingRuntime === true,
697
701
  });
698
702
  telemetry = createOwnerTelemetryRecorder(options.profile);
699
- if (resolveOwnerObservabilityLevel() === 'full') {
703
+ const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full';
704
+ if (fullDiagnosticsEnabled) {
700
705
  const retention = observabilityRetention();
701
706
  rawWsLog = new BufferedRawWsLog(
702
707
  ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)),
@@ -784,8 +789,11 @@ export async function runClawclawOwner(
784
789
  ...perceptionConfig.perception,
785
790
  modules: perceptionModules,
786
791
  moduleSources: perceptionSources,
792
+ diagnosticsEnabled: fullDiagnosticsEnabled,
787
793
  },
788
794
  behaviorCatalog,
795
+ behaviorDiagnosticsEnabled: fullDiagnosticsEnabled,
796
+ triggerDiagnosticsEnabled: fullDiagnosticsEnabled,
789
797
  fallbackBehaviors,
790
798
  behaviorEventTypes,
791
799
  triggers,
@@ -808,6 +816,60 @@ export async function runClawclawOwner(
808
816
  visualEventTypes: assembly.perception.produces.events,
809
817
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
810
818
  });
819
+ if (fullDiagnosticsEnabled) {
820
+ const sample = (): void => {
821
+ try {
822
+ const memory = process.memoryUsage();
823
+ const heap = getHeapStatistics();
824
+ const behaviorStatus = assembly.behavior.status();
825
+ const effectiveBehaviorId = behaviorStatus.current?.behaviorId
826
+ ?? behaviorStatus.stack.long?.behaviorId
827
+ ?? behaviorStatus.stack.fallback?.behaviorId;
828
+ const effectiveBehavior = effectiveBehaviorId
829
+ ? behaviorSourceById.get(effectiveBehaviorId)
830
+ : undefined;
831
+ telemetry?.log('debug', 'runtime.diagnostics.sample', {
832
+ sample_interval_ms: FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS,
833
+ process_memory: {
834
+ rss_bytes: memory.rss,
835
+ heap_total_bytes: memory.heapTotal,
836
+ heap_used_bytes: memory.heapUsed,
837
+ external_bytes: memory.external,
838
+ array_buffers_bytes: memory.arrayBuffers,
839
+ heap_size_limit_bytes: heap.heap_size_limit,
840
+ },
841
+ scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
842
+ retained_records: runtime?.runtimeRetainedRecordCounts(),
843
+ behavior: {
844
+ ...assembly.behavior.diagnosticSnapshot(),
845
+ effective_source: effectiveBehavior
846
+ ? {
847
+ id: effectiveBehavior.id,
848
+ execution: effectiveBehavior.execution,
849
+ every_ticks: effectiveBehavior.everyTicks,
850
+ source: effectiveBehavior.management.source,
851
+ managed_by: effectiveBehavior.management.managedBy,
852
+ resource_id: effectiveBehavior.management.resourceId ?? null,
853
+ version_id: effectiveBehavior.management.versionId ?? null,
854
+ resolution: effectiveBehavior.management.resolution ?? null,
855
+ file: effectiveBehavior.sourcePath.split(/[\\/]/).at(-1) ?? null,
856
+ }
857
+ : null,
858
+ },
859
+ perception: assembly.perception.diagnosticSnapshot(),
860
+ trigger: assembly.trigger.diagnosticSnapshot(),
861
+ }, {
862
+ component: 'runtime.diagnostics',
863
+ scope: runtime?.publicScope(),
864
+ });
865
+ } catch {
866
+ // Full diagnostics must remain observational and never affect gameplay.
867
+ }
868
+ };
869
+ sample();
870
+ diagnosticSampleTimer = setInterval(sample, FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS);
871
+ diagnosticSampleTimer.unref?.();
872
+ }
811
873
  if (!isMailboxRepository(runtime.repository)) {
812
874
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
813
875
  }
@@ -1399,6 +1461,7 @@ export async function runClawclawOwner(
1399
1461
  }
1400
1462
  return completion;
1401
1463
  } finally {
1464
+ if (diagnosticSampleTimer) clearInterval(diagnosticSampleTimer);
1402
1465
  process.off('SIGINT', onSignal);
1403
1466
  process.off('SIGTERM', onSignal);
1404
1467
  if (forceExitTimer) clearTimeout(forceExitTimer);
@@ -1,7 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { performance } from 'node:perf_hooks';
2
3
  import type { GameClient } from '../../../../lib/game-client.js';
3
4
  import { ApiError } from '../../../../lib/http-transport.js';
4
5
  import type { TransportResponse } from '../../../../short-command/transport-response.js';
6
+ import { actionFailureDiagnosticSeverity } from '../../../framework/action-diagnostics.js';
5
7
  import type {
6
8
  ActionCaller,
7
9
  ActionControlDescriptor,
@@ -29,6 +31,7 @@ export interface ClawclawActionRequest {
29
31
  audioFile?: { path: string; contentType: string };
30
32
  /** Host-only preconditions for one unified Behavior activation instance. */
31
33
  behaviorOriginEpochSeq?: number;
34
+ behaviorOriginTick?: number;
32
35
  behaviorActionSafetyGeneration?: number;
33
36
  behaviorActivationGeneration?: number;
34
37
  }
@@ -143,6 +146,49 @@ interface AdmittedClawclawAction {
143
146
  route: 'game' | 'room_chat';
144
147
  }
145
148
 
149
+ interface AutomatedProviderTiming {
150
+ readonly queuedAtMs: number;
151
+ readonly queueDepthAtAdmission: number;
152
+ readonly inFlightAtAdmission: number;
153
+ startedAtMs?: number;
154
+ }
155
+
156
+ interface AutomatedSubmission {
157
+ readonly settlement: Promise<ActionResult>;
158
+ readonly timing: AutomatedProviderTiming;
159
+ }
160
+
161
+ function elapsedMs(startedAtMs: number, endedAtMs = performance.now()): number {
162
+ return Math.round(Math.max(0, endedAtMs - startedAtMs) * 1_000) / 1_000;
163
+ }
164
+
165
+ function automatedDiagnosticAttributes(
166
+ request: ClawclawActionRequest,
167
+ admitted: AdmittedClawclawAction,
168
+ caller: AutomatedActionCaller,
169
+ ): Readonly<Record<string, unknown>> {
170
+ return {
171
+ action_id: admitted.actionId,
172
+ action_kind: typeof admitted.action.action === 'string'
173
+ ? admitted.action.action
174
+ : 'unknown',
175
+ route: admitted.route,
176
+ caller_kind: caller.kind,
177
+ behavior_activation_id: caller.activationId,
178
+ behavior_activation_generation: caller.activationGeneration,
179
+ behavior_layer: caller.layer,
180
+ ...(request.behaviorOriginEpochSeq === undefined
181
+ ? {}
182
+ : {
183
+ epoch_seq: request.behaviorOriginEpochSeq,
184
+ origin_epoch_seq: request.behaviorOriginEpochSeq,
185
+ }),
186
+ ...(request.behaviorOriginTick === undefined
187
+ ? {}
188
+ : { origin_tick: request.behaviorOriginTick }),
189
+ };
190
+ }
191
+
146
192
  /** Validates authoritative seat targets without consulting names or roster state. */
147
193
  function prepareActionTarget(action: Record<string, any>): ActionTargetPreparation {
148
194
  if (action.action !== 'kill' && action.action !== 'vote') return { action };
@@ -218,6 +264,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
218
264
  * gameplay endpoint before an earlier one has started.
219
265
  */
220
266
  private readonly automatedProviderStarts = new Map<string, Promise<void>>();
267
+ private readonly automatedProviderQueueDepths = new Map<string, number>();
221
268
 
222
269
  constructor(private readonly client: GameClient) {}
223
270
 
@@ -251,6 +298,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
251
298
  this.unregister = undefined;
252
299
  this.diagnostic = undefined;
253
300
  this.automatedProviderStarts.clear();
301
+ this.automatedProviderQueueDepths.clear();
254
302
  }
255
303
 
256
304
  private automatedProviderQueueKey(scope: ScopeRef): string {
@@ -263,9 +311,17 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
263
311
  caller: AutomatedActionCaller,
264
312
  context: ActionExecutionContext,
265
313
  admitted: AdmittedClawclawAction,
266
- ): Promise<ActionResult> {
314
+ ): AutomatedSubmission {
267
315
  const queueKey = this.automatedProviderQueueKey(scope);
268
316
  const previousStarted = this.automatedProviderStarts.get(queueKey) ?? Promise.resolve();
317
+ const queueDepthAtAdmission = (this.automatedProviderQueueDepths.get(queueKey) ?? 0) + 1;
318
+ this.automatedProviderQueueDepths.set(queueKey, queueDepthAtAdmission);
319
+ const timing: AutomatedProviderTiming = {
320
+ queuedAtMs: performance.now(),
321
+ queueDepthAtAdmission,
322
+ inFlightAtAdmission: this.ownedSettlements.size + 1,
323
+ };
324
+ const diagnostic = this.diagnostic;
269
325
  let markStarted!: () => void;
270
326
  const started = new Promise<void>((resolve) => { markStarted = resolve; });
271
327
  this.automatedProviderStarts.set(queueKey, started);
@@ -274,9 +330,56 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
274
330
  this.automatedProviderStarts.delete(queueKey);
275
331
  }
276
332
  });
277
- return previousStarted
333
+ let queuePositionReleased = false;
334
+ const releaseQueuePosition = (endpointStarted: boolean): void => {
335
+ if (queuePositionReleased) return;
336
+ queuePositionReleased = true;
337
+ const releasedAtMs = performance.now();
338
+ if (endpointStarted) timing.startedAtMs = releasedAtMs;
339
+ const remainingQueueDepth = Math.max(
340
+ 0,
341
+ (this.automatedProviderQueueDepths.get(queueKey) ?? 1) - 1,
342
+ );
343
+ if (remainingQueueDepth === 0) this.automatedProviderQueueDepths.delete(queueKey);
344
+ else this.automatedProviderQueueDepths.set(queueKey, remainingQueueDepth);
345
+ this.emitDiagnostic(
346
+ endpointStarted
347
+ ? 'runtime.action.provider_started'
348
+ : 'runtime.action.provider_skipped',
349
+ {
350
+ ...automatedDiagnosticAttributes(request, admitted, caller),
351
+ queue_wait_ms: elapsedMs(timing.queuedAtMs, releasedAtMs),
352
+ queue_depth_at_admission: timing.queueDepthAtAdmission,
353
+ in_flight_at_admission: timing.inFlightAtAdmission,
354
+ remaining_queue_depth: remainingQueueDepth,
355
+ },
356
+ 'debug',
357
+ diagnostic,
358
+ );
359
+ const queueWaitMs = elapsedMs(timing.queuedAtMs, releasedAtMs);
360
+ if (endpointStarted && (queueWaitMs >= 20 || timing.queueDepthAtAdmission >= 2)) {
361
+ this.emitDiagnostic('runtime.action.provider_queue_delayed', {
362
+ ...automatedDiagnosticAttributes(request, admitted, caller),
363
+ queue_wait_ms: queueWaitMs,
364
+ queue_depth_at_admission: timing.queueDepthAtAdmission,
365
+ in_flight_at_admission: timing.inFlightAtAdmission,
366
+ remaining_queue_depth: remainingQueueDepth,
367
+ budget_exceeded: queueWaitMs >= 100,
368
+ }, 'warn', diagnostic);
369
+ }
370
+ markStarted();
371
+ };
372
+ const settlement = previousStarted
278
373
  .catch(() => {})
279
- .then(() => this.submitAdmitted(request, scope, caller, context, admitted, markStarted));
374
+ .then(() => this.submitAdmitted(
375
+ request,
376
+ scope,
377
+ caller,
378
+ context,
379
+ admitted,
380
+ releaseQueuePosition,
381
+ ));
382
+ return { settlement, timing };
280
383
  }
281
384
 
282
385
  private automationSafetyRejection(
@@ -407,7 +510,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
407
510
  if (!isAutomatedCaller(caller)) {
408
511
  return this.submitAdmitted(request, scope, caller, context, admitted);
409
512
  }
410
- const settled = this.enqueueAutomatedSubmission(
513
+ const queued = this.enqueueAutomatedSubmission(
411
514
  request,
412
515
  scope,
413
516
  caller,
@@ -415,11 +518,20 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
415
518
  admitted,
416
519
  );
417
520
  this.emitDiagnostic('runtime.action.provider_queued', {
418
- action_id: actionId,
419
- caller_kind: caller.kind,
420
- action_kind: typeof action.action === 'string' ? action.action : 'unknown',
521
+ ...automatedDiagnosticAttributes(request, admitted, caller),
522
+ queue_depth: queued.timing.queueDepthAtAdmission,
523
+ in_flight: queued.timing.inFlightAtAdmission,
421
524
  });
422
- const ownedSettlement = this.ownSettlement(scope, caller, action, actionId, settled);
525
+ const ownedSettlement = this.ownSettlement(
526
+ scope,
527
+ caller,
528
+ action,
529
+ actionId,
530
+ admitted.route,
531
+ request,
532
+ queued.settlement,
533
+ queued.timing,
534
+ );
423
535
  const dispatch: ActionDispatch = {
424
536
  receipt: actionResult(scope, actionId, 'success', {
425
537
  accepted: true,
@@ -442,7 +554,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
442
554
  caller: ActionCaller,
443
555
  context: ActionExecutionContext,
444
556
  admitted: AdmittedClawclawAction,
445
- markProviderStartedOrSkipped: () => void = () => {},
557
+ markProviderStartedOrSkipped: (endpointStarted: boolean) => void = () => {},
446
558
  ): Promise<ActionResult> {
447
559
  let actionEndpointStarted = false;
448
560
  const action = { ...admitted.action };
@@ -464,12 +576,13 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
464
576
  request, scope, admitted.actionId, caller, context,
465
577
  );
466
578
  if (rejected) return rejected;
579
+ const pending = this.client.chatRoomConfirmed(action.text);
467
580
  actionEndpointStarted = true;
468
- markProviderStartedOrSkipped();
581
+ markProviderStartedOrSkipped(true);
469
582
  return acknowledgedActionResult(
470
583
  scope,
471
584
  admitted.actionId,
472
- await this.client.chatRoomConfirmed(action.text),
585
+ await pending,
473
586
  );
474
587
  }
475
588
  const preparedAction = await this.client.prepareActionForConfirmedSubmission(action as any);
@@ -477,9 +590,10 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
477
590
  request, scope, admitted.actionId, caller, context,
478
591
  );
479
592
  if (rejected) return rejected;
593
+ const pending = this.client.submitPreparedActionConfirmed(preparedAction);
480
594
  actionEndpointStarted = true;
481
- markProviderStartedOrSkipped();
482
- const response = await this.client.submitPreparedActionConfirmed(preparedAction);
595
+ markProviderStartedOrSkipped(true);
596
+ const response = await pending;
483
597
  return acknowledgedActionResult(scope, admitted.actionId, response);
484
598
  } catch (error) {
485
599
  return actionResult(scope, admitted.actionId, 'failure', undefined, backendError(error), {
@@ -491,7 +605,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
491
605
  } finally {
492
606
  // A local rejection or preparation failure is also a resolved queue
493
607
  // position: later Decisions may continue without waiting forever.
494
- markProviderStartedOrSkipped();
608
+ markProviderStartedOrSkipped(false);
495
609
  }
496
610
  }
497
611
 
@@ -500,23 +614,41 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
500
614
  caller: AutomatedActionCaller,
501
615
  action: Record<string, any>,
502
616
  actionId: string,
617
+ route: AdmittedClawclawAction['route'],
618
+ request: ClawclawActionRequest,
503
619
  settlement: Promise<ActionResult>,
620
+ timing: AutomatedProviderTiming,
504
621
  ): Promise<ActionResult> {
505
622
  // Keep the epoch's diagnostic sink with the owned submission. The plugin
506
623
  // may be stopped after the Runtime starts draining, but the final provider
507
624
  // result still belongs to this Action dispatch and must remain observable.
508
625
  const diagnostic = this.diagnostic;
509
626
  const report = (result: ActionResult): ActionResult => {
627
+ const settledAtMs = performance.now();
510
628
  const errorCode = actionResultErrorCode(result);
511
629
  this.emitDiagnostic('runtime.action.provider_settled', {
512
- action_id: actionId,
513
- caller_kind: caller.kind,
514
- action_kind: typeof action.action === 'string' ? action.action : 'unknown',
630
+ ...automatedDiagnosticAttributes(request, {
631
+ actionId,
632
+ action,
633
+ route,
634
+ }, caller),
515
635
  status: result.status,
516
636
  ...(result.source ? { action_source: result.source } : {}),
517
637
  ...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
518
638
  ...(errorCode ? { error_code: errorCode } : {}),
519
- }, result.status === 'failure' ? 'warn' : 'debug', diagnostic);
639
+ queue_depth_at_admission: timing.queueDepthAtAdmission,
640
+ in_flight_at_admission: timing.inFlightAtAdmission,
641
+ in_flight_at_settlement: this.ownedSettlements.size,
642
+ queue_wait_ms: timing.startedAtMs === undefined
643
+ ? elapsedMs(timing.queuedAtMs, settledAtMs)
644
+ : elapsedMs(timing.queuedAtMs, timing.startedAtMs),
645
+ ...(timing.startedAtMs === undefined
646
+ ? {}
647
+ : { provider_duration_ms: elapsedMs(timing.startedAtMs, settledAtMs) }),
648
+ total_duration_ms: elapsedMs(timing.queuedAtMs, settledAtMs),
649
+ }, result.status === 'failure'
650
+ ? actionFailureDiagnosticSeverity(result)
651
+ : 'debug', diagnostic);
520
652
  return result;
521
653
  };
522
654
  let owned!: Promise<ActionResult>;
@@ -37,6 +37,8 @@ export interface ClawclawPluginAssemblyOptions {
37
37
  epochPlugins?: readonly RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
38
38
  perception?: ClawclawPerceptionConfig;
39
39
  behaviorCatalog?: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
40
+ behaviorDiagnosticsEnabled?: boolean;
41
+ triggerDiagnosticsEnabled?: boolean;
40
42
  fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
41
43
  triggers?: readonly ClawclawTriggerRegistration[];
42
44
  /** All enabled Behavior Event declarations frozen into the startup plugin graph. */
@@ -106,6 +108,7 @@ export function assembleClawclawPlugins(
106
108
  ?? new ClawclawTriggerPlugin({
107
109
  after: [],
108
110
  triggers: options.triggers,
111
+ diagnosticsEnabled: options.triggerDiagnosticsEnabled,
109
112
  });
110
113
  if (!configuredTrigger) plugins.push(trigger);
111
114
 
@@ -125,6 +128,7 @@ export function assembleClawclawPlugins(
125
128
  CLAWCLAW_TRIGGER_PLUGIN_ID,
126
129
  ],
127
130
  eventTypes: options.behaviorEventTypes,
131
+ diagnosticsEnabled: options.behaviorDiagnosticsEnabled,
128
132
  });
129
133
  if (!configuredBehavior) plugins.push(behavior);
130
134
 
@@ -7,6 +7,7 @@ export function normalizeClawclawBehaviorAction(
7
7
  behaviorOriginEpochSeq: number,
8
8
  behaviorActionSafetyGeneration: number | undefined,
9
9
  behaviorActivationGeneration: number,
10
+ behaviorOriginTick?: number,
10
11
  ): ClawclawActionRequest {
11
12
  if (!Number.isInteger(behaviorOriginEpochSeq) || behaviorOriginEpochSeq <= 0) {
12
13
  throw new Error('invalid_behavior_action_epoch');
@@ -20,10 +21,17 @@ export function normalizeClawclawBehaviorAction(
20
21
  if (!Number.isSafeInteger(behaviorActivationGeneration) || behaviorActivationGeneration <= 0) {
21
22
  throw new Error('invalid_behavior_activation_generation');
22
23
  }
24
+ if (
25
+ behaviorOriginTick !== undefined
26
+ && (!Number.isSafeInteger(behaviorOriginTick) || behaviorOriginTick < 0)
27
+ ) {
28
+ throw new Error('invalid_behavior_action_tick');
29
+ }
23
30
  return {
24
31
  route: 'auto',
25
32
  action: normalizeClawclawBehaviorActionPayload(value),
26
33
  behaviorOriginEpochSeq,
34
+ ...(behaviorOriginTick === undefined ? {} : { behaviorOriginTick }),
27
35
  behaviorActionSafetyGeneration,
28
36
  behaviorActivationGeneration,
29
37
  };
@@ -11,14 +11,18 @@ import {
11
11
  validateClawclawBehaviorModule,
12
12
  } from './behavior-module-loader.js';
13
13
  import { deepFreezeBehaviorValue } from './behavior-manifest.js';
14
+ import { prepareClawclawBehavior } from './behavior-normalization.js';
14
15
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
15
16
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
17
+ import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
16
18
 
17
19
  interface BehaviorThreadWorkerData {
18
20
  readonly poolId: string;
19
21
  readonly slotId: number;
20
22
  readonly source: ResolvedClawclawBehaviorSource;
21
23
  readonly sourceUrl: string;
24
+ readonly diagnosticsEnabled?: boolean;
25
+ readonly prepareInput?: Readonly<Record<string, unknown>>;
22
26
  }
23
27
 
24
28
  interface BehaviorThreadRunRequest {
@@ -65,8 +69,16 @@ function send(value: Readonly<Record<string, unknown>>): void {
65
69
  port!.postMessage({ ...value, poolId: data!.poolId!, slotId: data!.slotId! });
66
70
  }
67
71
 
72
+ function diagnosticMemory(): Readonly<Record<string, number>> {
73
+ return data?.diagnosticsEnabled === true
74
+ ? { heapUsedBytes: process.memoryUsage().heapUsed }
75
+ : {};
76
+ }
77
+
68
78
  let loaded: ReturnType<typeof validateClawclawBehaviorModule>;
69
79
  let execution: ResolvedClawclawBehaviorSource['execution'];
80
+ let preparation: ReturnType<typeof prepareClawclawBehavior> | undefined;
81
+ let serialInstance: ClawclawBehavior | undefined;
70
82
  try {
71
83
  const behaviorModule = await import(data.sourceUrl) as Record<string, unknown>;
72
84
  // The parent validates immediately before spawn; repeat after the complete
@@ -74,6 +86,18 @@ try {
74
86
  resolveBehaviorSource(data.source);
75
87
  loaded = validateClawclawBehaviorModule(behaviorModule, data.source);
76
88
  execution = loaded.manifest.execution ?? 'parallel';
89
+ if (data.prepareInput !== undefined) {
90
+ preparation = prepareClawclawBehavior(
91
+ loaded.BehaviorClass,
92
+ loaded.manifest,
93
+ data.prepareInput,
94
+ loaded.source,
95
+ );
96
+ assertRuntimeModuleOutputSize(preparation.input, 'behavior_normalize_output');
97
+ }
98
+ if (execution === 'serial' && data.prepareInput === undefined) {
99
+ serialInstance = new loaded.BehaviorClass();
100
+ }
77
101
  } catch (error) {
78
102
  send({
79
103
  type: 'error',
@@ -107,7 +131,9 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
107
131
  // Cross-tick computations are isolated. The module and constructor are
108
132
  // preloaded once per slot, but no mutable behavior `this` state crosses
109
133
  // frame boundaries or becomes dependent on random slot assignment.
110
- const instance: ClawclawBehavior = new loaded.BehaviorClass();
134
+ const instance: ClawclawBehavior = execution === 'serial'
135
+ ? serialInstance ??= new loaded.BehaviorClass()
136
+ : new loaded.BehaviorClass();
111
137
  if (!instance || typeof instance.decide !== 'function') {
112
138
  throw new Error('behavior_thread_instance_invalid');
113
139
  }
@@ -119,7 +145,6 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
119
145
  : { observationSnapshot: request.observationSnapshot }),
120
146
  });
121
147
  try {
122
- if (execution !== 'parallel') throw new Error('behavior_thread_decide_not_available');
123
148
  const result = normalizeBehaviorDecision(await instance.decide(input, api), { finite: false });
124
149
  send({
125
150
  type: 'result',
@@ -127,6 +152,7 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
127
152
  result,
128
153
  queryCount,
129
154
  durationMs: Math.round((performance.now() - startedAt) * 1_000) / 1_000,
155
+ ...diagnosticMemory(),
130
156
  });
131
157
  } finally {
132
158
  invocationActive = false;
@@ -141,6 +167,7 @@ port.on('message', (request: BehaviorThreadRunRequest | BehaviorThreadStopReques
141
167
  ...(typeof request?.requestId === 'string' ? { requestId: request.requestId } : {}),
142
168
  code: errorCode(error, 'BEHAVIOR_THREAD_OPERATION_FAILED'),
143
169
  message: errorMessage(error),
170
+ ...diagnosticMemory(),
144
171
  });
145
172
  });
146
173
  });
@@ -149,4 +176,10 @@ send({
149
176
  type: 'ready',
150
177
  behaviorId: data.source.id,
151
178
  execution,
179
+ ...(preparation === undefined ? {} : {
180
+ manifest: preparation.manifest,
181
+ input: preparation.input,
182
+ timing: preparation.timing,
183
+ }),
184
+ ...diagnosticMemory(),
152
185
  });
@@ -5,13 +5,14 @@ import {
5
5
  type LoadedClawclawBehaviorModule,
6
6
  } from './behavior-module-loader.js';
7
7
  import {
8
- prepareClawclawBehavior,
9
8
  type PreparedClawclawBehavior,
10
9
  } from './behavior-normalization.js';
11
10
  import {
12
11
  behaviorSourceCompatibilityError,
13
12
  type ResolvedClawclawBehaviorSource,
14
13
  } from './behavior-source.js';
14
+ import { prepareBehaviorInWorker } from './thread-behavior-executor.js';
15
+ import { deepFreezeBehaviorValue } from './behavior-manifest.js';
15
16
 
16
17
  export interface ClawclawBehaviorCatalogEntry {
17
18
  readonly apiVersion: number | null;
@@ -93,12 +94,15 @@ export class ClawclawBehaviorCatalog {
93
94
  async prepare(id: string, input: unknown): Promise<PreparedClawclawBehavior> {
94
95
  const source = this.sources.get(id);
95
96
  if (!source) throw new Error(`Unknown behavior module '${id}'.`);
96
- const loaded = await this.load(id);
97
- return prepareClawclawBehavior(
98
- loaded.BehaviorClass,
99
- loaded.manifest,
100
- input,
101
- loaded.source ?? source,
97
+ const prepared = await prepareBehaviorInWorker(
98
+ source,
99
+ input as Readonly<Record<string, unknown>>,
102
100
  );
101
+ return Object.freeze({
102
+ manifest: deepFreezeBehaviorValue(structuredClone(prepared.manifest)),
103
+ input: deepFreezeBehaviorValue(structuredClone(prepared.input)),
104
+ source: prepared.source,
105
+ ...(prepared.timing === undefined ? {} : { timing: prepared.timing }),
106
+ });
103
107
  }
104
108
  }
@@ -0,0 +1,88 @@
1
+ import type {
2
+ BehaviorDecisionAction,
3
+ BehaviorDecisionFrame,
4
+ BehaviorDecisionFrameStatus,
5
+ } from '../../../../sdk/module-input/index.js';
6
+
7
+ export const BEHAVIOR_DECISION_HISTORY_LIMIT = 100;
8
+
9
+ interface DecisionFrameStart {
10
+ readonly epochId: number;
11
+ readonly tick: number;
12
+ readonly instanceGeneration: number;
13
+ }
14
+
15
+ function cloneActions(
16
+ actions: readonly Readonly<BehaviorDecisionAction>[] | undefined,
17
+ ): readonly Readonly<BehaviorDecisionAction>[] {
18
+ return Object.freeze((actions ?? []).map((action) => Object.freeze(structuredClone(action))));
19
+ }
20
+
21
+ /** One Owner-owned, activation-local ring shared by concurrent Decision computations. */
22
+ export class BehaviorDecisionHistory {
23
+ private readonly frames: BehaviorDecisionFrame[] = [];
24
+ private cachedSnapshot?: readonly Readonly<BehaviorDecisionFrame>[];
25
+
26
+ begin(start: DecisionFrameStart): Readonly<BehaviorDecisionFrame> {
27
+ const existing = this.frames.find((frame) => frame.epochId === start.epochId);
28
+ if (existing) return existing;
29
+ const frame = Object.freeze({
30
+ ...start,
31
+ status: 'pending' as const,
32
+ actions: null,
33
+ });
34
+ this.frames.push(frame);
35
+ if (this.frames.length > BEHAVIOR_DECISION_HISTORY_LIMIT) {
36
+ this.frames.splice(0, this.frames.length - BEHAVIOR_DECISION_HISTORY_LIMIT);
37
+ }
38
+ this.cachedSnapshot = undefined;
39
+ return frame;
40
+ }
41
+
42
+ complete(
43
+ epochId: number,
44
+ actions: readonly Readonly<BehaviorDecisionAction>[] | undefined,
45
+ ): Readonly<BehaviorDecisionFrame> | undefined {
46
+ return this.resolve(epochId, 'completed', cloneActions(actions));
47
+ }
48
+
49
+ notComputed(epochId: number, reason: string): Readonly<BehaviorDecisionFrame> | undefined {
50
+ return this.resolve(epochId, 'not_computed', null, reason);
51
+ }
52
+
53
+ fail(epochId: number, reason: string): Readonly<BehaviorDecisionFrame> | undefined {
54
+ return this.resolve(epochId, 'failed', null, reason);
55
+ }
56
+
57
+ snapshot(): readonly Readonly<BehaviorDecisionFrame>[] {
58
+ this.cachedSnapshot ??= Object.freeze([...this.frames]);
59
+ return this.cachedSnapshot;
60
+ }
61
+
62
+ clear(): void {
63
+ this.frames.length = 0;
64
+ this.cachedSnapshot = undefined;
65
+ }
66
+
67
+ private resolve(
68
+ epochId: number,
69
+ status: Exclude<BehaviorDecisionFrameStatus, 'pending'>,
70
+ actions: readonly Readonly<BehaviorDecisionAction>[] | null,
71
+ reason?: string,
72
+ ): Readonly<BehaviorDecisionFrame> | undefined {
73
+ const index = this.frames.findIndex((frame) => frame.epochId === epochId);
74
+ if (index < 0) return undefined;
75
+ const previous = this.frames[index]!;
76
+ const next = Object.freeze({
77
+ epochId: previous.epochId,
78
+ tick: previous.tick,
79
+ instanceGeneration: previous.instanceGeneration,
80
+ status,
81
+ actions,
82
+ ...(reason ? { reason } : {}),
83
+ });
84
+ this.frames[index] = next;
85
+ this.cachedSnapshot = undefined;
86
+ return next;
87
+ }
88
+ }