@myclaw163/clawclaw-cli 0.9.0 → 0.9.2

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 (86) hide show
  1. package/README.md +5 -3
  2. package/docs/custom-modules/README.md +19 -24
  3. package/docs/custom-modules/api-reference.md +85 -33
  4. package/docs/custom-modules/behavior.md +116 -22
  5. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  6. package/docs/custom-modules/examples/first-sighting-v3.ts +29 -0
  7. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  8. package/docs/custom-modules/perception.md +158 -276
  9. package/docs/custom-modules/trigger.md +5 -3
  10. package/docs/runtime/README.md +17 -8
  11. package/docs/runtime/agent-notifications.md +32 -15
  12. package/docs/runtime/behavior-runtime.md +36 -24
  13. package/docs/runtime/components-and-boundaries.md +56 -108
  14. package/docs/runtime/events-and-state.md +55 -3
  15. package/docs/runtime/owner-lifecycle-and-observability.md +5 -3
  16. package/docs/user-guide/README.md +6 -6
  17. package/docs/user-guide/api-reference.md +80 -30
  18. package/docs/user-guide/behavior.md +116 -22
  19. package/docs/user-guide/perception.md +157 -275
  20. package/package.json +1 -1
  21. package/scripts/check-skill-command-surface.mjs +2 -2
  22. package/skills/clawclaw/SKILL.md +9 -7
  23. package/skills/clawclaw/references/BEHAVIORS.md +19 -6
  24. package/skills/clawclaw/references/COMMANDS.md +19 -0
  25. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +116 -22
  26. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +82 -35
  27. package/skills/clawclaw/references/CUSTOM-MODULES.md +18 -23
  28. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +158 -276
  29. package/skills/clawclaw/references/STREAM.md +1 -1
  30. package/src/commands/behavior.ts +28 -99
  31. package/src/commands/load.ts +23 -29
  32. package/src/commands/module-runtime-control.ts +113 -0
  33. package/src/commands/perception.ts +20 -6
  34. package/src/commands/trigger.ts +1 -1
  35. package/src/lib/agent-workspace-sync.ts +2 -2
  36. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  37. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  38. package/src/runtime/clawclaw/owner.ts +51 -5
  39. package/src/runtime/clawclaw/perception-module-manifest.ts +36 -0
  40. package/src/runtime/clawclaw/plugins/assembly.ts +25 -23
  41. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +16 -3
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +4 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  45. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +129 -57
  46. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +7 -2
  47. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -1
  48. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +21 -18
  49. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +3 -2
  50. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +2 -0
  51. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  52. package/src/runtime/clawclaw/plugins/{source → derived-event}/task-change-tracker.ts +1 -1
  53. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +314 -0
  54. package/src/runtime/clawclaw/plugins/perception/{reaction-runner.ts → perception-module-runner.ts} +26 -13
  55. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +39 -0
  56. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  57. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +30 -7
  58. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2 -103
  59. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  60. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  61. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +61 -10
  62. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  63. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  64. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  65. package/src/runtime/clawclaw/runtime-state.ts +1 -1
  66. package/src/runtime/clawclaw/runtime.ts +3 -3
  67. package/src/runtime/clawclaw/strategy-memory-rpc.ts +63 -0
  68. package/src/runtime/clawclaw/strategy-memory.ts +77 -0
  69. package/src/runtime/clawclaw-event-catalog.ts +9 -6
  70. package/src/runtime/framework/plugins/contracts.ts +8 -0
  71. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +17 -6
  72. package/src/runtime/owner-control.ts +5 -0
  73. package/src/sdk/behavior-plugin/index.ts +4 -1
  74. package/src/sdk/index.ts +5 -0
  75. package/src/sdk/perception-plugin/index.ts +29 -10
  76. package/src/sdk/perception-plugin/module.ts +55 -0
  77. package/src/sdk/perception-plugin/reaction.ts +2 -1
  78. package/src/sdk/perception-plugin/reminder.ts +1 -0
  79. package/src/sdk/strategy-memory.ts +12 -0
  80. package/src/sdk/trigger-plugin/index.ts +3 -2
  81. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  82. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  83. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  84. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -198
  85. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  86. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -50,7 +50,6 @@ import {
50
50
  type RuntimeSourceStopHandle,
51
51
  } from '../../../framework/plugins/index.js';
52
52
  import type { RuntimeScope } from '../../../framework/state/index.js';
53
- import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
54
53
  import { normalizeGameSyncEventsSafely } from '../../../../pipeline/game-sync-event-normalization.js';
55
54
  import { isSelfKillerMurderWitnessed } from '../../../../pipeline/event-hints.js';
56
55
  import {
@@ -94,16 +93,6 @@ import type {
94
93
  ClawclawSourceStartIntent,
95
94
  ClawclawSourceTransportFactory,
96
95
  } from './types.js';
97
- import {
98
- nextPlayerProjection,
99
- type PlayerSnapshot,
100
- type PlayersChangedPayload,
101
- } from './player-change-tracker.js';
102
- import {
103
- nextTaskProjection,
104
- type TaskSnapshot,
105
- type TasksChangedPayload,
106
- } from './task-change-tracker.js';
107
96
 
108
97
  interface RoomFrameMeta {
109
98
  connectionId: string;
@@ -339,11 +328,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
339
328
  private hasFreshGameSnapshot = false;
340
329
  private latestFreshGameState?: Record<string, any>;
341
330
  private latestFreshGameTick?: number;
342
- private playerProjection: PlayerProjection[] = [];
343
- private playerProjectionInitialized = false;
344
- private playerSnapshots: PlayerSnapshot[] = [];
345
- private taskProjection: TaskSnapshot[] = [];
346
- private taskProjectionInitialized = false;
347
331
  private matchStartedAtMs?: number;
348
332
  private lastMatchWaitingAtMs?: number;
349
333
  private matchTimedOut = false;
@@ -1519,10 +1503,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1519
1503
  }, 'warn');
1520
1504
  }
1521
1505
  let acceptedStage: ClawclawRuntimeStage | undefined;
1522
- let acceptedPlayerProjection: PlayerProjection[] | undefined;
1523
- let acceptedPlayerSnapshots: PlayerSnapshot[] | undefined;
1524
- let acceptedTaskProjection: TaskSnapshot[] | undefined;
1525
- let acceptedTaskProjectionInitialized: boolean | undefined;
1526
1506
  const acceptance = await this.enqueueInputIf(() => {
1527
1507
  if (this.currentStage === 'ended') return null;
1528
1508
  try {
@@ -1530,14 +1510,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1530
1510
  CLAWCLAW_GAME_WS_SOURCE.sourceId,
1531
1511
  frame.meta.connectionId,
1532
1512
  );
1533
- const taskUpdate = nextTaskProjection({
1534
- previous: this.taskProjection,
1535
- initialized: this.taskProjectionInitialized,
1536
- summary: gameState,
1537
- events: frame.events,
1538
- selfName: this.profile.agentName,
1539
- allowUntickedInitialRole: frame.meta.origin === 'update',
1540
- });
1541
1513
  const backendEvents = this.sourceEvents(
1542
1514
  frame.events, frame.meta, CLAWCLAW_GAME_WS_SOURCE.sourceId, undefined, gameState,
1543
1515
  );
@@ -1549,36 +1521,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1549
1521
  replayed_event_count: frame.events.length,
1550
1522
  }], `${recoveryIdentity}:recovered`, frame.meta.receivedAt)
1551
1523
  : [];
1552
- const playerUpdate = nextPlayerProjection({
1553
- previous: this.playerProjection,
1554
- previousSnapshots: this.playerSnapshots,
1555
- initialized: this.playerProjectionInitialized,
1556
- summary: gameState,
1557
- events: frame.events,
1558
- selfName: this.profile.agentName,
1559
- });
1560
- const events = [
1561
- ...backendEvents,
1562
- ...recoveryEvents,
1563
- ...(playerUpdate.payload
1564
- ? [this.playersChangedEvent(
1565
- playerUpdate.payload,
1566
- frame.meta.receivedAt,
1567
- `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1568
- )]
1569
- : []),
1570
- ...(taskUpdate.payload
1571
- ? [this.tasksChangedEvent(
1572
- taskUpdate.payload,
1573
- frame.meta.receivedAt,
1574
- `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1575
- )]
1576
- : []),
1577
- ];
1578
- acceptedPlayerProjection = playerUpdate.projection;
1579
- acceptedPlayerSnapshots = playerUpdate.snapshots;
1580
- acceptedTaskProjection = taskUpdate.projection;
1581
- acceptedTaskProjectionInitialized = taskUpdate.initialized;
1524
+ const events = [...backendEvents, ...recoveryEvents];
1582
1525
  this.currentTransport = 'game_ws';
1583
1526
  this.currentConnection = 'connected';
1584
1527
  acceptedStage = clawclawStageFromGameEvents(
@@ -1601,7 +1544,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1601
1544
  state: this.gameRuntimeState(
1602
1545
  acceptedStage,
1603
1546
  acceptedStage === 'ended' ? 'ending' : 'game_snapshot',
1604
- { status: 'fresh', state: structuredClone(gameState) },
1547
+ { status: 'fresh', state: structuredClone(gameState), origin: frame.meta.origin },
1605
1548
  ),
1606
1549
  events,
1607
1550
  completeness: frame.meta.snapshotFallback ? 'best_effort' : 'complete',
@@ -1626,15 +1569,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1626
1569
  this.latestFreshGameState = structuredClone(gameState);
1627
1570
  this.latestFreshGameTick = tick;
1628
1571
  this.gameConnectionsWithState.add(frame.meta.connectionId);
1629
- if (acceptedPlayerProjection) {
1630
- this.playerProjection = acceptedPlayerProjection;
1631
- this.playerSnapshots = acceptedPlayerSnapshots ?? [];
1632
- this.playerProjectionInitialized = true;
1633
- }
1634
- if (acceptedTaskProjection) {
1635
- this.taskProjection = acceptedTaskProjection;
1636
- this.taskProjectionInitialized = acceptedTaskProjectionInitialized ?? false;
1637
- }
1638
1572
  });
1639
1573
  if (!acceptance) return;
1640
1574
  const ingress = frame.meta.ingress;
@@ -2215,11 +2149,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2215
2149
  this.hasFreshGameSnapshot = false;
2216
2150
  this.latestFreshGameState = undefined;
2217
2151
  this.latestFreshGameTick = undefined;
2218
- this.playerProjection = [];
2219
- this.playerProjectionInitialized = false;
2220
- this.playerSnapshots = [];
2221
- this.taskProjection = [];
2222
- this.taskProjectionInitialized = false;
2223
2152
  this.sourceCoalescingBoundaryState = undefined;
2224
2153
  this.actionSafetyGeneration = 0;
2225
2154
  return next;
@@ -2280,36 +2209,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2280
2209
  });
2281
2210
  }
2282
2211
 
2283
- private playersChangedEvent(
2284
- payload: PlayersChangedPayload,
2285
- receivedAt: string,
2286
- sourceSeq: number | string,
2287
- ): RuntimeSourceEvent<Record<string, unknown>> {
2288
- return {
2289
- type: 'players_changed',
2290
- producer: 'local_synth',
2291
- payload,
2292
- sourceEventId: `local:${this.sourceInstanceId}:players-changed:${String(sourceSeq)}`,
2293
- sourceSeq: `${String(sourceSeq)}:players-changed`,
2294
- receivedAt,
2295
- };
2296
- }
2297
-
2298
- private tasksChangedEvent(
2299
- payload: TasksChangedPayload,
2300
- receivedAt: string,
2301
- sourceSeq: number | string,
2302
- ): RuntimeSourceEvent<Record<string, unknown>> {
2303
- return {
2304
- type: 'tasks_changed',
2305
- producer: 'local_synth',
2306
- payload,
2307
- sourceEventId: `local:${this.sourceInstanceId}:tasks-changed:${String(sourceSeq)}`,
2308
- sourceSeq: `${String(sourceSeq)}:tasks-changed`,
2309
- receivedAt,
2310
- };
2311
- }
2312
-
2313
2212
  private runtimeState(
2314
2213
  cause: ClawclawRuntimeCause,
2315
2214
  gameSnapshot?: ClawclawRuntimeState['game_snapshot'],
@@ -9,6 +9,8 @@ export const CLAWCLAW_TRIGGER_PLUGIN_ID = 'clawclaw.trigger';
9
9
 
10
10
  /** Effective outer configuration for one statically discovered Trigger. */
11
11
  export interface ClawclawTriggerRegistration {
12
+ /** Optional scope lease for an explicitly configured standalone Trigger. */
13
+ readonly scope?: Readonly<BehaviorScope>;
12
14
  readonly source: ResolvedClawclawTriggerSource;
13
15
  /** New community Trigger installations are supplied as false by the outer configuration layer. */
14
16
  readonly enabled: boolean;
@@ -23,7 +25,7 @@ export interface ClawclawTriggerRegistration {
23
25
  }
24
26
 
25
27
  export interface BehaviorReflexActivationRequest {
26
- readonly source: 'trigger';
28
+ readonly source: 'trigger' | 'perception';
27
29
  readonly triggerId: string;
28
30
  readonly scope: Readonly<BehaviorScope>;
29
31
  readonly epochId: number;
@@ -88,10 +88,11 @@ export function validateClawclawTriggerModule(
88
88
  loaded: Readonly<Record<string, unknown>>,
89
89
  source: ResolvedClawclawTriggerSource,
90
90
  ): ClawclawTriggerClass {
91
- if (typeof loaded.default !== 'function') {
91
+ const entry = 'default';
92
+ if (typeof loaded[entry] !== 'function') {
92
93
  throw new Error(`Trigger module '${source.id}' has no default class.`);
93
94
  }
94
- const ModuleClass = loaded.default as unknown as ClawclawTriggerClass;
95
+ const ModuleClass = loaded[entry] as unknown as ClawclawTriggerClass;
95
96
  const manifest = normalizedManifest(ModuleClass.manifest);
96
97
  if (!isDeepStrictEqual(manifest, source.manifest)) {
97
98
  throw new Error(`Trigger module '${source.id}' changed after static discovery.`);
@@ -99,6 +100,8 @@ export function validateClawclawTriggerModule(
99
100
  return ModuleClass;
100
101
  }
101
102
 
103
+
104
+
102
105
  /** One Runtime-scoped direct importer. Disabled Trigger sources never reach it. */
103
106
  export class TriggerModuleLoader {
104
107
  private readonly runtimeId = randomUUID();
@@ -36,6 +36,7 @@ import { TriggerModuleLoader } from './trigger-module-loader.js';
36
36
  import type { ResolvedClawclawTriggerSource } from './trigger-source.js';
37
37
  import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
38
38
  import { TriggerThreadPool } from './trigger-thread-pool.js';
39
+ import { ClawclawStrategyMemory } from '../../strategy-memory.js';
39
40
 
40
41
  const TRIGGER_COMPUTATION_SCHEMA = 1;
41
42
  const TRIGGER_CHECKPOINT_SCHEMA = 1;
@@ -44,6 +45,7 @@ export const DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS = 2_000;
44
45
  interface EffectiveTriggerConfig {
45
46
  readonly source: ResolvedClawclawTriggerSource;
46
47
  readonly enabled: boolean;
48
+ readonly scope?: Readonly<{ sessionId: string; segmentId: string }>;
47
49
  readonly input: Readonly<Record<string, unknown>>;
48
50
  readonly behavior: string;
49
51
  readonly behaviorInput: Readonly<Record<string, unknown>>;
@@ -78,6 +80,7 @@ interface TriggerCheckpoint {
78
80
  }
79
81
 
80
82
  export interface ClawclawTriggerPluginOptions {
83
+ readonly memory?: ClawclawStrategyMemory;
81
84
  readonly after?: readonly string[];
82
85
  readonly triggers?: readonly ClawclawTriggerRegistration[];
83
86
  readonly loader?: TriggerModuleLoader;
@@ -123,7 +126,7 @@ function normalizeRegistration(value: ClawclawTriggerRegistration): EffectiveTri
123
126
  const { source } = value;
124
127
  const manifest = source.manifest;
125
128
  if (!source || source.id !== manifest.id) throw new Error('trigger_source_identity_invalid');
126
- const input = normalizeBehaviorInput(value.input ?? {}, manifest.inputs);
129
+ const input = value.enabled ? normalizeBehaviorInput(value.input ?? {}, manifest.inputs) : Object.freeze(structuredClone(value.input ?? {}));
127
130
  const behavior = value.behavior ?? manifest.defaultBehavior;
128
131
  const behaviorInput = {
129
132
  ...structuredClone(manifest.defaultBehaviorInput),
@@ -149,6 +152,7 @@ function normalizeRegistration(value: ClawclawTriggerRegistration): EffectiveTri
149
152
  return Object.freeze({
150
153
  source,
151
154
  enabled: value.enabled,
155
+ scope: value.scope,
152
156
  input,
153
157
  behavior,
154
158
  behaviorInput: Object.freeze(behaviorInput),
@@ -255,6 +259,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
255
259
  private readonly loadFailures = new Set<string>();
256
260
  private readonly states = new Map<string, TriggerRuntimeState>();
257
261
  private readonly observationMemory = new ClawclawBehaviorObservationMemory();
262
+ private memory: ClawclawStrategyMemory;
258
263
  private readonly projector = new ObservationFrameProjector();
259
264
  private readonly threaded: boolean;
260
265
  private readonly diagnosticsEnabled: boolean;
@@ -264,6 +269,11 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
264
269
  private pendingThreadResetReason?: TriggerResetReason;
265
270
  private driver?: BehaviorReflexActivationDriver;
266
271
  private configGeneration = 1;
272
+ private currentScope?: Readonly<{ sessionId: string; segmentId: string }>;
273
+ private isEnabled(config: EffectiveTriggerConfig): boolean {
274
+ return config.enabled && (!config.scope || config.scope.sessionId === this.currentScope?.sessionId
275
+ && config.scope.segmentId === this.currentScope?.segmentId);
276
+ }
267
277
  private started = false;
268
278
  private lastFrameSeq = 0;
269
279
  private lastVisualTick: number | null = null;
@@ -271,6 +281,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
271
281
  private lifecyclePhase: string | null = null;
272
282
 
273
283
  constructor(options: ClawclawTriggerPluginOptions = {}) {
284
+ this.memory = options.memory ?? new ClawclawStrategyMemory();
274
285
  this.after = [...(options.after ?? [])];
275
286
  this.registrations = normalizeRegistrations(options.triggers ?? []);
276
287
  this.loader = options.loader ?? new TriggerModuleLoader();
@@ -279,6 +290,11 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
279
290
  this.diagnosticsEnabled = options.diagnosticsEnabled === true;
280
291
  }
281
292
 
293
+ attachMemory(memory: ClawclawStrategyMemory): void {
294
+ if (this.started) throw Error('strategy_memory_already_started');
295
+ this.memory = memory;
296
+ }
297
+
282
298
  attachDriver(driver: BehaviorReflexActivationDriver): void {
283
299
  if (this.driver && this.driver !== driver) throw new Error('trigger_activation_driver_already_attached');
284
300
  this.driver = driver;
@@ -287,11 +303,17 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
287
303
  /** Atomically replace effective config; newly enabled modules import on the next ordered boundary. */
288
304
  configure(triggers: readonly ClawclawTriggerRegistration[]): void {
289
305
  const next = normalizeRegistrations(triggers);
306
+ for (const [id, config] of next) {
307
+ if (config.enabled && !this.registrations.get(id)?.enabled) {
308
+ const state = this.states.get(id);
309
+ if (state) state.armed = true;
310
+ }
311
+ }
290
312
  this.configGeneration += 1;
291
313
  this.registrations = next;
292
314
  this.slots.clear();
293
315
  this.loadFailures.clear();
294
- this.states.clear();
316
+ for (const id of this.states.keys()) if (!next.has(id)) this.states.delete(id);
295
317
  this.observationMemory.clear();
296
318
  this.clearFrameBoundary();
297
319
  void this.threadPool?.stop();
@@ -305,6 +327,8 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
305
327
  descriptors(): readonly Readonly<{
306
328
  id: string;
307
329
  enabled: boolean;
330
+ armed: boolean;
331
+ cooldownRemainingMs: number;
308
332
  behavior: string;
309
333
  reflexPriority: number;
310
334
  cooldownMs: number;
@@ -313,7 +337,9 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
313
337
  }>[] {
314
338
  return [...this.registrations.values()].map((entry) => Object.freeze({
315
339
  id: entry.source.id,
316
- enabled: entry.enabled,
340
+ enabled: this.isEnabled(entry),
341
+ armed: this.states.get(entry.source.id)?.armed ?? true,
342
+ cooldownRemainingMs: Math.max(0, entry.cooldownMs - (Date.now() - (this.states.get(entry.source.id)?.lastAcceptedAtMs ?? 0))),
317
343
  behavior: entry.behavior,
318
344
  reflexPriority: entry.reflexPriority,
319
345
  cooldownMs: entry.cooldownMs,
@@ -327,7 +353,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
327
353
  return Object.freeze({
328
354
  threaded: this.threaded,
329
355
  configured_trigger_count: this.registrations.size,
330
- enabled_trigger_count: [...this.registrations.values()].filter(({ enabled }) => enabled).length,
356
+ enabled_trigger_count: [...this.registrations.values()].filter(config => this.isEnabled(config)).length,
331
357
  active_trigger_count: this.threaded ? pool?.workerCount ?? 0 : this.slots.size,
332
358
  thread_pool_failed: this.threadPoolFailed,
333
359
  worker_pool: pool
@@ -346,6 +372,8 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
346
372
 
347
373
  async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
348
374
  this.started = true;
375
+ this.memory.open(context.scope);
376
+ this.currentScope = context.scope;
349
377
  if (this.threaded) await this.ensureThreadPool(context);
350
378
  else await this.ensureModules(context);
351
379
  }
@@ -373,6 +401,15 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
373
401
  input: RuntimeEpochPluginInput<Record<string, any>>,
374
402
  context: RuntimeEpochPluginContext<Record<string, any>>,
375
403
  ): Promise<RuntimeEpochPluginResult> {
404
+ this.currentScope = input.epoch.scope;
405
+ // Keep the live configure/enable entry point, but do no observation or Worker work while empty.
406
+ if (![...this.registrations.values()].some(config => this.isEnabled(config))) {
407
+ return { outcome: 'noop', reason: 'no_enabled_triggers', proposal: {
408
+ schema: TRIGGER_COMPUTATION_SCHEMA, configGeneration: this.configGeneration,
409
+ epochId: input.epoch.epochSeq, nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
410
+ ...(input.pendingEvents.length ? { eventCursor: input.pendingEvents.at(-1)!.commitSeq } : {}), evaluations: [],
411
+ } satisfies TriggerComputationProposal };
412
+ }
376
413
  if (this.threaded) return this.updateThreaded(input, context);
377
414
  await this.ensureModules(context);
378
415
  const generation = this.configGeneration;
@@ -451,7 +488,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
451
488
  this.lifecyclePhase = lifecycle;
452
489
 
453
490
  const observationSnapshot = this.observationMemory.capture(emptyInput);
454
- const evaluators = [...this.slots.values()].sort((left, right) => (
491
+ const evaluators = [...this.slots.values()].filter(entry => this.isEnabled(entry.config)).sort((left, right) => (
455
492
  left.config.source.id.localeCompare(right.config.source.id)
456
493
  ));
457
494
  const evaluationsPending = evaluators.map(async (evaluator): Promise<ClawclawTriggerEvaluation> => {
@@ -465,7 +502,9 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
465
502
  try {
466
503
  const value = await evaluator.module.evaluate(
467
504
  triggerInput,
468
- createBehaviorReadApi(readInput, { isActive, observationSnapshot }),
505
+ createBehaviorReadApi(readInput, { isActive, observationSnapshot,
506
+ memory: this.memory.bind(readInput.scope, this.memoryNamespace(config.source),
507
+ () => isActive() && !context.signal.aborted && this.started) }),
469
508
  );
470
509
  if (!isActive()) return { triggerId: config.source.id, outcome: 'error' };
471
510
  const match = normalizeMatch(value);
@@ -578,7 +617,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
578
617
  ? 'phase_changed'
579
618
  : previousStored && !continuousFromPrevious ? 'trajectory_gap' : undefined;
580
619
  const configs = [...this.registrations.values()]
581
- .filter(({ enabled }) => enabled)
620
+ .filter(config => this.isEnabled(config))
582
621
  .sort((left, right) => left.source.id.localeCompare(right.source.id));
583
622
  const settled = await Promise.allSettled(configs.map(async (config): Promise<ClawclawTriggerEvaluation> => {
584
623
  const triggerInput = triggerInputFor(frame, emptyInput, config);
@@ -649,7 +688,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
649
688
  const candidates = computed.evaluations.flatMap((evaluation) => {
650
689
  if (evaluation.outcome !== 'match' || !evaluation.match) return [];
651
690
  const config = this.registrations.get(evaluation.triggerId);
652
- if (!config?.enabled) return [];
691
+ if (!config || !this.isEnabled(config)) return [];
653
692
  const state = this.stateFor(evaluation.triggerId);
654
693
  if (config.rearm === 'after_clear' && !state.armed) return [];
655
694
  if (
@@ -746,6 +785,8 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
746
785
  }
747
786
 
748
787
  async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
788
+ this.started = false;
789
+ if (this.currentScope) this.memory.close(this.currentScope);
749
790
  if (this.threaded) await this.threadPool?.stop();
750
791
  else await this.resetModules(reason, undefined);
751
792
  this.started = false;
@@ -762,6 +803,10 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
762
803
  this.loader.stop();
763
804
  }
764
805
 
806
+ private memoryNamespace(source: ResolvedClawclawTriggerSource): string {
807
+ return `trigger:${source.id}`;
808
+ }
809
+
765
810
  private async ensureThreadPool(
766
811
  context: RuntimeEpochPluginContext<Record<string, any>>,
767
812
  ): Promise<void> {
@@ -780,11 +825,17 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
780
825
  context: RuntimeEpochPluginContext<Record<string, any>>,
781
826
  generation: number,
782
827
  ): Promise<void> {
783
- const enabled = [...this.registrations.values()].filter(({ enabled }) => enabled);
828
+ const enabled = [...this.registrations.values()].filter(config => this.isEnabled(config));
784
829
  if (enabled.length === 0) return;
785
830
  let pool: TriggerThreadPool | undefined;
786
831
  try {
787
832
  pool = new TriggerThreadPool({
833
+ memory: (evaluation, active) => {
834
+ const source = this.registrations.get(evaluation.triggerId)?.source;
835
+ if (!source) throw Error('strategy_memory_inactive');
836
+ return this.memory.bind(evaluation.readInput.scope, this.memoryNamespace(source),
837
+ () => active() && this.started && generation === this.configGeneration);
838
+ },
788
839
  modules: enabled.map(({ source }) => this.loader.threadSpec(source)),
789
840
  loader: this.loader.threadConfig(),
790
841
  diagnosticsEnabled: this.diagnosticsEnabled,
@@ -826,7 +877,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
826
877
 
827
878
  private async ensureModules(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
828
879
  if (!this.started) return;
829
- const enabled = [...this.registrations.values()].filter((entry) => entry.enabled);
880
+ const enabled = [...this.registrations.values()].filter(config => this.isEnabled(config));
830
881
  await Promise.all(enabled.map(async (config) => {
831
882
  const id = config.source.id;
832
883
  if (this.slots.has(id) || this.loadFailures.has(id)) return;
@@ -10,6 +10,8 @@ import type {
10
10
  RuntimeModuleThreadLoaderConfig,
11
11
  } from '../../../framework/modules/runtime-module-loader.js';
12
12
  import type { TriggerThreadModuleSpec } from './trigger-module-loader.js';
13
+ import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
14
+ import { serveStrategyMemoryRequest, unavailableStrategyMemory, type StrategyMemoryRequest } from '../../strategy-memory-rpc.js';
13
15
 
14
16
  const WORKER_BOOTSTRAP_URL = new URL(
15
17
  '../../../framework/modules/runtime-module-worker-bootstrap.mjs',
@@ -20,6 +22,7 @@ const MAX_TRIGGER_WORKERS = 10;
20
22
  const START_TIMEOUT_MS = 20_000;
21
23
 
22
24
  export interface TriggerThreadPoolOptions {
25
+ readonly memory?: (evaluation: TriggerThreadEvaluation, isActive: () => boolean) => StrategyMemory;
23
26
  readonly modules: readonly TriggerThreadModuleSpec[];
24
27
  readonly loader: RuntimeModuleThreadLoaderConfig;
25
28
  readonly maxOldGenerationSizeMb?: number;
@@ -311,11 +314,20 @@ export class TriggerThreadPool {
311
314
  this.failLane(lane, new Error('trigger_thread_protocol_invalid'));
312
315
  return;
313
316
  }
314
- const message = value as WorkerReadyMessage | WorkerResultMessage | WorkerErrorMessage;
317
+ const message = value as WorkerReadyMessage | WorkerResultMessage | WorkerErrorMessage
318
+ | (StrategyMemoryRequest & WorkerMessageBase & { readonly heapUsedBytes?: number });
315
319
  if (message.poolId !== this.poolId || message.laneId !== lane.id) {
316
320
  this.failLane(lane, new Error('trigger_thread_protocol_identity_mismatch'));
317
321
  return;
318
322
  }
323
+ if (message.type === 'strategy_memory') {
324
+ const request = lane.current;
325
+ const isActive = () => this.state === 'running' && !!request && lane.current === request
326
+ && request.requestId === message.requestId && !request.settled && !request.signal.aborted;
327
+ void serveStrategyMemoryRequest(message, () => request && this.options.memory
328
+ ? this.options.memory(request.evaluation, isActive) : unavailableStrategyMemory, reply => lane.worker?.postMessage(reply));
329
+ return;
330
+ }
319
331
  if (typeof message.heapUsedBytes === 'number' && Number.isFinite(message.heapUsedBytes)) {
320
332
  lane.heapUsedBytes = Math.max(0, message.heapUsedBytes);
321
333
  this.peakWorkerHeapUsedBytes = Math.max(
@@ -13,6 +13,7 @@ import {
13
13
  validateClawclawTriggerModule,
14
14
  type TriggerThreadModuleSpec,
15
15
  } from './trigger-module-loader.js';
16
+ import { StrategyMemoryRpcClient } from '../../strategy-memory-rpc.js';
16
17
 
17
18
  interface TriggerThreadWorkerData {
18
19
  readonly poolId: string;
@@ -72,6 +73,7 @@ function send(value: Readonly<Record<string, unknown>>): void {
72
73
  }
73
74
 
74
75
  const classes = new Map<string, ClawclawTriggerClass>();
76
+ const memoryClient = new StrategyMemoryRpcClient(send);
75
77
  const modules = new Map<string, ClawclawTrigger>();
76
78
  const observationMemories = new Map<string, ClawclawBehaviorObservationMemory>();
77
79
  try {
@@ -114,6 +116,7 @@ async function evaluate(request: TriggerEvaluateRequest): Promise<void> {
114
116
  const value = await module.evaluate(
115
117
  deepFreeze(request.input),
116
118
  createBehaviorReadApi(deepFreeze(request.readInput), {
119
+ memory: memoryClient.bind(request.requestId, () => invocationActive),
117
120
  isActive: () => invocationActive,
118
121
  observationSnapshot,
119
122
  }),
@@ -146,6 +149,7 @@ async function evaluate(request: TriggerEvaluateRequest): Promise<void> {
146
149
 
147
150
  let operationTail = Promise.resolve();
148
151
  port.on('message', (request: TriggerEvaluateRequest) => {
152
+ if (memoryClient.receive(request)) return;
149
153
  operationTail = operationTail.then(() => evaluate(request)).catch((error) => {
150
154
  send({
151
155
  type: 'error',
@@ -24,27 +24,33 @@ export function normalizeReactionManifest(value: unknown, requireCurrentVersion
24
24
  || m.config !== undefined && !record(m.config)
25
25
  || Object.keys(m).some(key => !['apiVersion', 'kind', 'id', 'name', 'description', 'localizations',
26
26
  'consumes', 'produces', 'behaviors', 'inputs', 'config'].includes(key))) throw new Error('reaction_manifest_invalid');
27
+ const behaviors = normalizePerceptionBehaviorBindings(m.behaviors);
28
+ const inputs = m.inputs ? normalizeBehaviorInputFields(m.inputs) : undefined;
29
+ const config = inputs ? normalizeBehaviorInput(m.config ?? {}, inputs) : structuredClone(m.config ?? {});
30
+ return { apiVersion: m.apiVersion, kind: 'reaction', id: m.id, description: m.description,
31
+ ...(m.name === undefined ? {} : { name: m.name }),
32
+ ...(m.localizations === undefined ? {} : { localizations: structuredClone(m.localizations) }),
33
+ consumes: [...new Set(m.consumes)], produces: [...new Set(m.produces)], behaviors,
34
+ ...(inputs ? { inputs } : {}), config };
35
+ }
36
+
37
+ export function normalizePerceptionBehaviorBindings(value: unknown): Record<string, ReactionBehaviorBinding> {
38
+ if (value !== undefined && !record(value)) throw Error("perception_behaviors_invalid");
27
39
  const behaviors: Record<string, ReactionBehaviorBinding> = {};
28
- if (Object.keys(m.behaviors ?? {}).length > 16) throw new Error('reaction_behavior_limit');
29
- for (const [key, binding] of Object.entries(m.behaviors ?? {})) {
40
+ if (Object.keys(value ?? {}).length > 16) throw new Error('reaction_behavior_limit');
41
+ for (const [key, binding] of Object.entries(value ?? {})) {
30
42
  if (!ID.test(key) || ['__proto__', 'constructor', 'prototype'].includes(key) || !record(binding)
31
43
  || typeof binding.name !== 'string' || !OPERATION.test(binding.name)
32
44
  || binding.resourceId !== undefined && (typeof binding.resourceId !== 'string' || !binding.resourceId.trim() || binding.resourceId.length > 255)
33
- || binding.layer !== undefined && !['reflex', 'short', 'long'].includes(binding.layer)
45
+ || binding.layer !== undefined && binding.layer !== 'reflex'
34
46
  || binding.input !== undefined && !record(binding.input)
35
47
  || binding.reflexPriority !== undefined && !integer(binding.reflexPriority, -1_000_000, 1_000_000)
36
48
  || binding.cooldownMs !== undefined && !integer(binding.cooldownMs, 0, 86_400_000)
37
49
  || binding.maxRuntimeMs !== undefined && !integer(binding.maxRuntimeMs, 1, 120_000)
38
- || binding.rearm !== undefined && !['after_clear', 'after_cooldown'].includes(binding.rearm)
50
+ || binding.rearm !== undefined && !['after_clear', 'after_cooldown'].includes(String(binding.rearm))
39
51
  || Object.keys(binding).some(field => !['name', 'resourceId', 'layer', 'input', 'reflexPriority',
40
52
  'cooldownMs', 'maxRuntimeMs', 'rearm'].includes(field))) throw new Error(`reaction_behavior_invalid:${key}`);
41
- behaviors[key] = structuredClone(binding);
53
+ behaviors[key] = structuredClone(binding) as unknown as ReactionBehaviorBinding;
42
54
  }
43
- const inputs = m.inputs ? normalizeBehaviorInputFields(m.inputs) : undefined;
44
- const config = inputs ? normalizeBehaviorInput(m.config ?? {}, inputs) : structuredClone(m.config ?? {});
45
- return { apiVersion: m.apiVersion, kind: 'reaction', id: m.id, description: m.description,
46
- ...(m.name === undefined ? {} : { name: m.name }),
47
- ...(m.localizations === undefined ? {} : { localizations: structuredClone(m.localizations) }),
48
- consumes: [...new Set(m.consumes)], produces: [...new Set(m.produces)], behaviors,
49
- ...(inputs ? { inputs } : {}), config };
55
+ return behaviors;
50
56
  }
@@ -25,7 +25,7 @@ export type ClawclawRuntimeCause =
25
25
  | 'ending';
26
26
 
27
27
  export type ClawclawGameSnapshot =
28
- | { status: 'fresh'; state: Record<string, any> }
28
+ | { status: 'fresh'; state: Record<string, any>; origin?: 'snapshot' | 'update' | 'resume' }
29
29
  | { status: 'not_updated' }
30
30
  | { status: 'unavailable' };
31
31
 
@@ -48,7 +48,7 @@ export type ClawclawRuntimeOptions = Omit<
48
48
  visualEventDelivery?: ClawclawVisualEventDelivery;
49
49
  /** Visual Event types declared by the selected perception modules. */
50
50
  visualEventTypes?: readonly string[];
51
- reactionEventTypes?: readonly string[];
51
+ perceptionEventTypes?: readonly string[];
52
52
  /** Event types declared by enabled Intent and Strategy modules at startup. */
53
53
  behaviorEventTypes?: readonly string[];
54
54
  };
@@ -97,7 +97,7 @@ export function createClawclawRuntime(
97
97
  stateFreshnessPolicyResolver: configuredResolver,
98
98
  visualEventDelivery,
99
99
  visualEventTypes,
100
- reactionEventTypes,
100
+ perceptionEventTypes,
101
101
  behaviorEventTypes,
102
102
  ...runtimeOptions
103
103
  } = options;
@@ -146,7 +146,7 @@ export function createClawclawRuntime(
146
146
  eventCatalog: createClawclawEventCatalog({
147
147
  visualEventDelivery,
148
148
  visualEventTypes,
149
- reactionEventTypes,
149
+ perceptionEventTypes,
150
150
  behaviorEventTypes,
151
151
  }),
152
152
  // Mailbox ACK adapters own independent durable lanes. Disabled and