@myclaw163/clawclaw-cli 0.9.1 → 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 (82) hide show
  1. package/README.md +1 -1
  2. package/docs/custom-modules/README.md +14 -15
  3. package/docs/custom-modules/api-reference.md +73 -36
  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/nearby-reflex.ts +22 -0
  7. package/docs/custom-modules/perception.md +48 -247
  8. package/docs/custom-modules/trigger.md +5 -5
  9. package/docs/runtime/README.md +5 -5
  10. package/docs/runtime/agent-notifications.md +2 -2
  11. package/docs/runtime/behavior-runtime.md +34 -29
  12. package/docs/runtime/components-and-boundaries.md +55 -147
  13. package/docs/runtime/events-and-state.md +17 -5
  14. package/docs/runtime/owner-lifecycle-and-observability.md +2 -2
  15. package/docs/user-guide/README.md +6 -6
  16. package/docs/user-guide/api-reference.md +69 -34
  17. package/docs/user-guide/behavior.md +116 -22
  18. package/docs/user-guide/perception.md +48 -247
  19. package/package.json +1 -1
  20. package/scripts/check-skill-command-surface.mjs +2 -2
  21. package/skills/clawclaw/SKILL.md +8 -6
  22. package/skills/clawclaw/references/BEHAVIORS.md +18 -7
  23. package/skills/clawclaw/references/COMMANDS.md +19 -0
  24. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +116 -22
  25. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +70 -38
  26. package/skills/clawclaw/references/CUSTOM-MODULES.md +13 -14
  27. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +48 -247
  28. package/skills/clawclaw/references/STREAM.md +1 -1
  29. package/src/commands/behavior.ts +28 -99
  30. package/src/commands/load.ts +15 -23
  31. package/src/commands/module-runtime-control.ts +113 -0
  32. package/src/commands/perception.ts +18 -4
  33. package/src/commands/trigger.ts +1 -1
  34. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  35. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  36. package/src/runtime/clawclaw/owner.ts +50 -5
  37. package/src/runtime/clawclaw/perception-module-manifest.ts +16 -7
  38. package/src/runtime/clawclaw/plugins/assembly.ts +22 -32
  39. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +16 -3
  40. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +4 -0
  41. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +129 -57
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +7 -2
  45. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -1
  46. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +21 -18
  47. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +3 -2
  48. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +2 -0
  49. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  50. package/src/runtime/clawclaw/plugins/{source → derived-event}/task-change-tracker.ts +1 -1
  51. package/src/runtime/clawclaw/plugins/perception/{reaction-plugin.ts → perception-module-plugin.ts} +151 -70
  52. package/src/runtime/clawclaw/plugins/perception/{reaction-runner.ts → perception-module-runner.ts} +26 -13
  53. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +17 -6
  54. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  55. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -9
  56. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2 -103
  57. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  58. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  59. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +61 -10
  60. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  61. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  62. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  63. package/src/runtime/clawclaw/runtime-state.ts +1 -1
  64. package/src/runtime/clawclaw/runtime.ts +3 -3
  65. package/src/runtime/clawclaw/strategy-memory-rpc.ts +63 -0
  66. package/src/runtime/clawclaw/strategy-memory.ts +77 -0
  67. package/src/runtime/clawclaw-event-catalog.ts +5 -5
  68. package/src/runtime/framework/plugins/contracts.ts +8 -0
  69. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +17 -6
  70. package/src/runtime/owner-control.ts +5 -0
  71. package/src/sdk/behavior-plugin/index.ts +4 -1
  72. package/src/sdk/index.ts +4 -1
  73. package/src/sdk/perception-plugin/index.ts +6 -4
  74. package/src/sdk/perception-plugin/module.ts +13 -4
  75. package/src/sdk/perception-plugin/reaction.ts +1 -1
  76. package/src/sdk/strategy-memory.ts +12 -0
  77. package/src/sdk/trigger-plugin/index.ts +3 -3
  78. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  79. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  80. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  81. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  82. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -0,0 +1,84 @@
1
+ import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js';
2
+ import type { StoredStateFrame } from '../../../framework/state/index.js';
3
+ import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
4
+ import { CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
5
+ import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
6
+ import type { ClawclawDerivedEventRule } from './derived-event-rules.js';
7
+ import { nextPlayerProjection, type PlayerSnapshot } from './player-change-tracker.js';
8
+ import { nextTaskProjection, type TaskSnapshot } from './task-change-tracker.js';
9
+
10
+ /** Adapt validated canonical Source facts to the existing player projection's PlayerRef inputs. */
11
+ function trackerFacts(events: readonly RuntimeSourceEvent[]): Array<Record<string, any>> {
12
+ return events.filter(event => event.producer !== 'local_synth').map(event => {
13
+ const value: Record<string, any> = { ...event.payload, type: event.type };
14
+ for (const [field, name, seat] of [
15
+ ['actor','actor_name','actor_seat'], ['target','target_name','target_seat'],
16
+ ['caller','meeting_caller_name','meeting_caller_seat'], ['resolver','resolver_name','resolver_seat'],
17
+ ['current_speaker','current_speaker','current_speaker_seat'], ['result_target','result_target','result_target_seat'],
18
+ ]) {
19
+ if (typeof value[name] === 'string' && Number.isInteger(value[seat])) {
20
+ value[field] = { name: value[name], seat: value[seat] };
21
+ }
22
+ }
23
+ if (value.killer_kind === 'player' && typeof value.killer_name === 'string' && Number.isInteger(value.killer_seat)) {
24
+ value.killer = { kind: 'player', player: { name: value.killer_name, seat: value.killer_seat } };
25
+ } else if (value.killer_kind === 'system' && typeof value.killer_name === 'string') {
26
+ value.killer = { kind: 'system', name: value.killer_name };
27
+ }
28
+ return value;
29
+ });
30
+ }
31
+
32
+ function gameState(frame: StoredStateFrame<Record<string, any>>): Record<string, any> | null {
33
+ const game = freshClawclawGameState(frame.state);
34
+ if (!game) return null;
35
+ return { ...game, ...(frame.backendTick === undefined ? {} : { tick: frame.backendTick }) };
36
+ }
37
+
38
+ function proposal(type: string, frame: StoredStateFrame<Record<string, any>>, payload: Record<string, unknown>,
39
+ sourceEvents: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
40
+ // An open epoch written by the previous Source implementation may already contain this fact.
41
+ // Rebuild rule state, but keep its original Source identity and delivery instead of publishing it twice.
42
+ if (sourceEvents.some(event => event.type === type && event.producer === 'local_synth')) return [];
43
+ return [{ type, payload, dedupeKey: `${type}:${frame.sourceKey}`, dedupeScope: 'segment',
44
+ occurredAt: new Date(frame.observedAtMs ?? frame.receivedAtMs).toISOString() }];
45
+ }
46
+
47
+ export class PlayerChangesDerivedEventRule implements ClawclawDerivedEventRule {
48
+ readonly id = 'player-changes';
49
+ readonly eventTypes = ['players_changed'] as const;
50
+ readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'players_changed'];
51
+ private initialized = false;
52
+ private projection: PlayerProjection[] = [];
53
+ private snapshots: PlayerSnapshot[] = [];
54
+ reset(): void { this.initialized = false; this.projection = []; this.snapshots = []; }
55
+ inspect(frame: StoredStateFrame<Record<string, any>>, events: readonly RuntimeSourceEvent[] = []): RuntimeEventProposal[] {
56
+ const game = gameState(frame);
57
+ if (!game) return [];
58
+ const update = nextPlayerProjection({ previous: this.projection, previousSnapshots: this.snapshots,
59
+ initialized: this.initialized, summary: game, events: trackerFacts(events),
60
+ selfName: game.you?.player?.name ?? game.you?.name });
61
+ this.projection = update.projection; this.snapshots = update.snapshots; this.initialized = true;
62
+ return update.payload ? proposal('players_changed', frame, update.payload, events) : [];
63
+ }
64
+ }
65
+
66
+ export class TaskChangesDerivedEventRule implements ClawclawDerivedEventRule {
67
+ readonly id = 'task-changes';
68
+ readonly eventTypes = ['tasks_changed'] as const;
69
+ readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'tasks_changed'];
70
+ private initialized = false;
71
+ private projection: TaskSnapshot[] = [];
72
+ reset(): void { this.initialized = false; this.projection = []; }
73
+ inspect(frame: StoredStateFrame<Record<string, any>>, events: readonly RuntimeSourceEvent[] = []): RuntimeEventProposal[] {
74
+ const game = gameState(frame);
75
+ if (!game) return [];
76
+ const state = frame.state;
77
+ const update = nextTaskProjection({ previous: this.projection, initialized: this.initialized, summary: game,
78
+ events: trackerFacts(events), selfName: game.you?.player?.name ?? game.you?.name,
79
+ allowUntickedInitialRole: isClawclawRuntimeState(state) && state.game_snapshot.status === 'fresh'
80
+ && state.game_snapshot.origin === 'update' });
81
+ this.projection = update.projection; this.initialized = update.initialized;
82
+ return update.payload ? proposal('tasks_changed', frame, update.payload, events) : [];
83
+ }
84
+ }
@@ -208,7 +208,7 @@ function updateReason(
208
208
 
209
209
  /**
210
210
  * Diff the authoritative task list carried by one complete GameSync State.
211
- * Source emits a private tasks_changed input, separate from backend facts.
211
+ * Derived Event emits tasks_changed from the same accepted input, separate from backend facts.
212
212
  * Reminder scripts own Agent-facing task notifications.
213
213
  */
214
214
  export function nextTaskProjection(input: {
@@ -1,38 +1,37 @@
1
1
  import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult,
2
2
  RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
- import type { ReactionActivation, ReactionInput, ReactionResult } from '../../../../sdk/perception-plugin/reaction.js';
4
- import { normalizeReactionManifest } from '../../reaction-manifest.js';
3
+ import type { ReactionActivation } from '../../../../sdk/perception-plugin/reaction.js';
4
+ import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
5
+ import type { ClawclawStrategyMemory } from '../../strategy-memory.js';
6
+ import { unavailableStrategyMemory } from '../../strategy-memory-rpc.js';
7
+ import type { BehaviorReflexActivationDriver } from '../trigger/contracts.js';
5
8
  import { resolveReactionBehavior, type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
6
- import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
7
- type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
8
9
  import { ObservationFrameProjector } from '../../observation-frame-projector.js';
9
10
  import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
10
11
  import { createCanonicalGameState } from '../../behavior-input.js';
11
12
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
12
13
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
13
- import { ReactionRunner } from './reaction-runner.js';
14
+ import { PerceptionModuleRunner } from './perception-module-runner.js';
14
15
  import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
15
- import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
16
+ import type { PerceptionModuleInput, PerceptionModuleResult } from '../../../../sdk/perception-plugin/module.js';
16
17
  import type { ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
17
18
 
18
- export const CLAWCLAW_REACTION_PLUGIN_ID = 'clawclaw.perception.reactions';
19
19
  export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
20
- export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.reaction_failed'] as const;
20
+ export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.module_failed'] as const;
21
21
  interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
22
22
  interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
23
23
  interface Checkpoint { gameId?: string; phase?: string; connectionId?: string; previousTick?: number; modules: Record<string, ModuleState>; failures: string[] }
24
- export interface ReactionPluginOptions {
25
- /** A shared execution engine; v2 retains its subscription semantics, v3 admits only source/system facts. */
26
- unified?: boolean;
24
+ export interface PerceptionModulePluginOptions {
25
+ /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */
27
26
  sources: readonly ResolvedClawclawPerceptionSource[];
28
27
  after: readonly string[];
29
- behaviors: () => readonly ReactionBehaviorCandidate[];
30
- runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>;
28
+ behaviors?: () => readonly ReactionBehaviorCandidate[];
29
+ runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
31
30
  }
32
31
  const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
33
32
 
34
- /** All modules observe their subscribed facts independently. Only own outputs are produced. */
35
- export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
33
+ /** Observing and notifications remain active independently of fixed Reflex admission. */
34
+ export class ClawclawPerceptionModulePlugin implements RuntimeEpochPlugin<Record<string, any>> {
36
35
  readonly kind = 'epoch' as const;
37
36
  readonly id: string;
38
37
  readonly version = '1';
@@ -41,49 +40,121 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
41
40
  readonly after: readonly string[];
42
41
  readonly consumes: { events: readonly string[] };
43
42
  readonly produces: { events: readonly string[] };
44
- readonly capabilities = { uses: [BEHAVIOR_ACTIVATION_CAPABILITY] };
45
43
  private readonly sources: readonly ResolvedClawclawPerceptionSource[];
46
- private readonly runners = new Map<string, Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>>();
44
+ private readonly runners = new Map<string, Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>>();
47
45
  private readonly failed = new Set<string>();
48
46
  private checkpoint: Checkpoint = { modules: {}, failures: [] };
49
47
  private readonly projector = new ObservationFrameProjector();
50
- constructor(private readonly options: ReactionPluginOptions) {
51
- this.id = options.unified ? CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID : CLAWCLAW_REACTION_PLUGIN_ID;
52
- this.sources = options.sources.filter(source => options.unified ? source.module : source.reaction).map(source => ({
53
- ...source, reaction: options.unified ? { ...source.module!, apiVersion: 2 as const, kind: 'reaction' as const,
54
- consumes: source.module!.consumes ?? [], produces: source.module!.produces ?? [] }
55
- : normalizeReactionManifest(source.reaction),
56
- })).sort((a, b) => a.id.localeCompare(b.id));
48
+ constructor(private readonly options: PerceptionModulePluginOptions) {
49
+ this.id = CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID;
50
+ this.sources = options.sources.filter(s => s.module).sort((a,b) => a.id.localeCompare(b.id));
57
51
  this.after = options.after;
58
- this.consumes = { events: [...new Set([...this.sources.flatMap(source => [...source.reaction!.consumes]),
59
- ...(options.unified ? ['tasks_changed'] : [])])] };
52
+ this.consumes = { events: [...new Set([...this.sources.flatMap(source => [...(source.module!.consumes ?? [])]),
53
+ 'tasks_changed'])] };
60
54
  this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
61
- ...this.sources.flatMap(source => [...source.reaction!.produces])])] };
55
+ ...this.sources.flatMap(source => [...(source.module!.produces ?? [])])])] };
56
+ }
57
+ private driver?: BehaviorReflexActivationDriver;
58
+ private memory?: ClawclawStrategyMemory;
59
+ private scope?: { sessionId: string; segmentId: string };
60
+ private stopped = true;
61
+ private generation = 0;
62
+ private watches = new Set<string>();
63
+ private configs = new Map<string, Readonly<Record<string, unknown>>>();
64
+ attachDriver(driver: BehaviorReflexActivationDriver): void { this.driver = driver; }
65
+ attachMemory(memory: ClawclawStrategyMemory): void { this.memory = memory; }
66
+ private sameScope(scope: { sessionId: string; segmentId: string }): boolean {
67
+ return this.scope?.sessionId === scope.sessionId && this.scope.segmentId === scope.segmentId;
68
+ }
69
+ bindings(id?: string) {
70
+ const candidates = this.options.behaviors?.() ?? [];
71
+ return this.sources.flatMap(source => Object.entries(source.module!.behaviors ?? {}).map(([key,binding]) => {
72
+ const target = resolveReactionBehavior(binding,candidates), state = this.checkpoint.modules[source.id]?.bindings[key];
73
+ return { id: target ?? binding.name, perception_id: source.id, binding: key,
74
+ trigger_id: `perception:${source.id}:${key}`, available: !!target && !this.failed.has(source.id),
75
+ reason: this.failed.has(source.id) ? 'perception_module_failed' : !target ? 'behavior_not_loaded' : undefined,
76
+ enabled: !!target && this.watches.has(target), priority: binding.reflexPriority ?? 0,
77
+ armed: state?.armed ?? true, cooldown_ms: binding.cooldownMs ?? 1000,
78
+ cooldown_remaining_ms: Math.max(0, (binding.cooldownMs ?? 1000) - ((this.lastNow ?? 0) - (state?.lastAcceptedAt ?? -Infinity))) };
79
+ })).filter(binding => id === undefined || binding.id === id);
80
+ }
81
+ private lastNow?: number;
82
+ private busy = 0;
83
+ diagnosticSnapshot() { return { worker_pool: { busy_worker_count: this.busy }, modules: this.status() }; }
84
+ setWatch(id: string, enabled: boolean, guard: () => boolean): string[] {
85
+ if (this.stopped || !guard()) throw Error('stale_runtime_scope');
86
+ const bindings = this.bindings(id);
87
+ if (!bindings.length || enabled && !bindings.some(binding => binding.available)) throw Error('perception_binding_unavailable');
88
+ if (enabled) {
89
+ this.watches.add(id);
90
+ for (const binding of bindings) {
91
+ const state = this.checkpoint.modules[binding.perception_id]?.bindings[binding.binding];
92
+ if (state) { state.armed = true; state.failedAttempt = undefined; }
93
+ }
94
+ } else this.watches.delete(id);
95
+ this.generation++;
96
+ return bindings.map(binding => binding.trigger_id);
97
+ }
98
+ configure(id: string, patch: Readonly<Record<string, unknown>>, guard: () => boolean) {
99
+ if (this.stopped || !guard()) throw Error('stale_runtime_scope');
100
+ const source = this.sources.find(s => s.id === id);
101
+ if (!source) throw Error('perception_not_found');
102
+ if (this.failed.has(id)) throw Error('perception_module_failed');
103
+ const input = normalizeBehaviorInput({ ...(this.configs.get(id) ?? source.module!.config), ...patch }, source.module!.inputs ?? []);
104
+ this.configs.set(id,input); this.generation++;
105
+ for (const state of Object.values(this.checkpoint.modules[id]?.bindings ?? {})) {
106
+ state.failedAttempt = undefined; state.warning = undefined;
107
+ }
108
+ return { applied: true, id, input };
109
+ }
110
+ behaviorInputChanged(id: string): void {
111
+ this.generation++;
112
+ for (const binding of this.bindings(id)) {
113
+ const state = this.checkpoint.modules[binding.perception_id]?.bindings[binding.binding];
114
+ if (state) { state.failedAttempt = undefined; state.warning = undefined; }
115
+ }
116
+ }
117
+ status(id?: string) {
118
+ return this.sources.filter(s => id === undefined || id === s.id).map(s => ({ id: s.id,
119
+ observing: !this.stopped && !this.failed.has(s.id), input: this.configs.get(s.id) ?? s.module!.config ?? {},
120
+ bindings: this.bindings().filter(b => b.perception_id === s.id) }));
62
121
  }
63
122
  async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
123
+ this.stopped = false; this.scope = { ...context.scope }; this.generation++; this.watches.clear(); this.configs.clear();
64
124
  this.checkpoint = { modules: {}, failures: [] }; this.failed.clear(); this.projector.reset();
65
125
  await Promise.all(this.sources.map(async (source, index) => {
66
126
  try {
67
127
  if (index >= 32) throw new Error('REACTION_MODULE_LIMIT');
68
- const runner = this.options.runnerFactory?.(source) ?? new ReactionRunner(source);
128
+ const runner = this.options.runnerFactory?.(source) ?? new PerceptionModuleRunner(source, (input, active) => {
129
+ const resolved = Object.values(source.module!.behaviors ?? {}).map(binding =>
130
+ resolveReactionBehavior(binding, this.options.behaviors?.() ?? []));
131
+ const targets = [...new Set(resolved)];
132
+ return this.memory?.bind(input.scope, targets.length === 1 && targets[0] ? `behavior:${targets[0]}` : `perception:${source.id}`,
133
+ () => active() && !this.stopped && !!this.scope && this.sameScope(input.scope)) ?? unavailableStrategyMemory;
134
+ });
69
135
  this.runners.set(source.id, runner); await runner.start();
70
136
  } catch {
71
137
  this.failed.add(source.id); await this.runners.get(source.id)?.stop();
72
- context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
138
+ context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
73
139
  }
74
140
  }));
75
141
  }
76
142
  recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
77
143
  const saved = context.checkpoint() as Checkpoint | undefined;
78
- if (saved?.modules && Array.isArray(saved.failures)) this.checkpoint = structuredClone(saved);
144
+ if (saved?.modules && Array.isArray(saved.failures)) {
145
+ this.checkpoint = structuredClone(saved);
146
+ // Existing notification-only module checkpoints have no binding state.
147
+ for (const state of Object.values(this.checkpoint.modules)) state.bindings ??= {};
148
+ }
79
149
  this.projector.reset();
80
150
  }
81
- async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
151
+ async stop(): Promise<void> { this.stopped = true; this.generation++; await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
82
152
  localizedModuleDescriptors(locale: string) {
83
153
  return this.sources.filter(source => !this.failed.has(source.id)).map(source =>
84
154
  resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, locale));
85
155
  }
86
156
  async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
157
+ this.scope = { ...input.epoch.scope };
87
158
  const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
88
159
  const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
89
160
  const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
@@ -91,9 +162,9 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
91
162
  const boundary = initial ? 'initial' as const : this.checkpoint.connectionId !== undefined
92
163
  && this.checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
93
164
  if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
94
- if ((!game && (!this.options.unified || this.checkpoint.phase !== undefined))
165
+ if ((!game && this.checkpoint.phase !== undefined)
95
166
  || (game && this.checkpoint.phase !== game.phase)) {
96
- if (this.options.unified) this.checkpoint.previousTick = undefined;
167
+ this.checkpoint.previousTick = undefined;
97
168
  for (const state of Object.values(this.checkpoint.modules)) {
98
169
  state.value = undefined;
99
170
  for (const binding of Object.values(state.bindings)) {
@@ -103,16 +174,15 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
103
174
  this.checkpoint.phase = game?.phase;
104
175
  }
105
176
  const frame = this.projector.project(input.frame);
106
- if (this.options.unified && frame) {
177
+ if (frame) {
107
178
  const delta = this.checkpoint.previousTick === undefined ? null : frame.tick - this.checkpoint.previousTick;
108
179
  Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
109
180
  && this.checkpoint.connectionId === input.epoch.connectionId });
110
181
  this.checkpoint.previousTick = frame.tick;
111
182
  }
112
- const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
113
- const candidates = this.options.behaviors();
114
- const facts = input.pendingEvents.filter(event => !event.replayed && (!this.options.unified
115
- || event.producer === 'backend_push' || event.producerPluginId === undefined
183
+ const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs; this.lastNow = nowMs;
184
+ const candidates = (this.options.behaviors?.() ?? []);
185
+ const facts = input.pendingEvents.filter(event => !event.replayed && (event.producer === 'backend_push' || event.producerPluginId === undefined
116
186
  || event.producerPluginId === 'clawclaw.derived-event')).map(event => ({
117
187
  eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
118
188
  type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
@@ -124,68 +194,80 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
124
194
  baseline: event.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(event.payload.reason)),
125
195
  } as ReminderTaskChange)));
126
196
  const events: RuntimeEventProposal[] = [];
127
- const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState }> = [];
197
+ const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState; generation: number }> = [];
128
198
  for (const source of this.sources) {
129
199
  if (!this.failed.has(source.id)) {
130
200
  try {
131
201
  const state = Object.hasOwn(this.checkpoint.modules, source.id)
132
202
  ? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
133
- const moduleInput: ReactionInput & Partial<PerceptionModuleInput> = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
134
- events: facts.filter(event => source.reaction!.consumes.includes(event.type)), nowMs,
135
- state: state.value, config: source.reaction!.config ?? {}, availableBehaviors: candidates.filter(c => c.loadable).map(c => c.id),
136
- ...(this.options.unified ? { taskChanges, boundary } : {}) };
203
+ const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
204
+ events: facts.filter(event => source.module!.consumes?.includes(event.type)), nowMs,
205
+ state: state.value, config: this.configs.get(source.id) ?? source.module!.config ?? {},
206
+ availableBehaviors: [...new Set([...candidates.filter(c => c.loadable).map(c => c.id),
207
+ ...Object.values(source.module!.behaviors ?? {}).filter(binding => resolveReactionBehavior(binding, candidates)).map(binding => binding.name)])],
208
+ availableBindings: Object.entries(source.module!.behaviors ?? {}).filter(([,binding]) => !!resolveReactionBehavior(binding,candidates)).map(([key]) => key),
209
+ enabledBindings: Object.entries(source.module!.behaviors ?? {}).filter(([,binding]) => {
210
+ const id = resolveReactionBehavior(binding,candidates); return !!id && this.watches.has(id);
211
+ }).map(([key]) => key), taskChanges, boundary };
137
212
  // A control-only epoch is not an observation that clears a visual condition.
138
213
  if (!frame && moduleInput.events.length === 0) continue;
139
- const result = await this.runners.get(source.id)!.evaluate(moduleInput);
214
+ const generation = this.generation;
215
+ this.busy++;
216
+ let result: PerceptionModuleResult;
217
+ try { result = await this.runners.get(source.id)!.evaluate(moduleInput); }
218
+ finally { this.busy--; }
140
219
  this.validate(result, source);
141
220
  state.value = structuredClone(result.state);
142
221
  for (const event of result.events ?? []) events.push({ type: event.type,
143
222
  dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
144
223
  payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
145
224
  const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
146
- for (const [key, binding] of Object.entries(source.reaction!.behaviors ?? {})) {
225
+ for (const [key, binding] of Object.entries(source.module!.behaviors ?? {})) {
147
226
  const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
148
227
  if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) {
149
228
  current.warning = undefined; current.failedAttempt = undefined;
150
229
  }
151
230
  if (!matched.has(key)) { current.armed = true; current.failedAttempt = undefined; continue; }
231
+ const target = resolveReactionBehavior(binding, candidates);
232
+ if (generation !== this.generation || !target || !this.watches.has(target)) continue;
152
233
  if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
153
234
  // Ignore only the missing binding; the module's other outputs continue above.
154
235
  if (current.warning === 'behavior_not_loaded') continue;
155
236
  if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
156
237
  if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
157
- requests.push({ source, activation: matched.get(key)!, state: current });
238
+ requests.push({ source, activation: matched.get(key)!, state: current, generation });
158
239
  }
159
240
  } catch {
160
241
  this.failed.add(source.id); await this.runners.get(source.id)?.stop();
161
- context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
242
+ context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
162
243
  }
163
244
  }
164
245
  if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
165
246
  this.checkpoint.failures.push(source.id);
166
- events.push({ type: 'perception.reaction_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
247
+ events.push({ type: 'perception.module_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
167
248
  payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
168
249
  }
169
250
  }
170
- requests.sort((a, b) => (b.source.reaction!.behaviors![b.activation.behavior].reflexPriority ?? 0)
171
- - (a.source.reaction!.behaviors![a.activation.behavior].reflexPriority ?? 0));
172
- for (const { source, activation, state } of requests) {
173
- if (context.signal.aborted) break;
174
- const binding = source.reaction!.behaviors![activation.behavior];
175
- const behavior = resolveReactionBehavior(binding, this.options.behaviors());
251
+ requests.sort((a, b) => (b.source.module!.behaviors![b.activation.behavior].reflexPriority ?? 0)
252
+ - (a.source.module!.behaviors![a.activation.behavior].reflexPriority ?? 0));
253
+ for (const { source, activation, state, generation } of requests) {
254
+ if (context.signal.aborted || generation !== this.generation) break;
255
+ const binding = source.module!.behaviors![activation.behavior];
256
+ const behavior = resolveReactionBehavior(binding, (this.options.behaviors?.() ?? []));
176
257
  const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
177
258
  if (state.failedAttempt === attempt) continue;
178
- let result: PerceptionBehaviorActivationResult = { accepted: false, reason: 'behavior_not_loaded' };
179
- if (behavior) {
259
+ let result: { accepted: boolean; reason?: string } = { accepted: false, reason: 'behavior_not_loaded' };
260
+ if (behavior && this.watches.has(behavior)) {
180
261
  try {
181
- const response = await context.capabilities.performAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>(
182
- BEHAVIOR_ACTIVATION_CAPABILITY, { moduleId: source.id, bindingKey: activation.behavior, behavior,
183
- input: { ...binding.input, ...activation.input }, layer: binding.layer ?? 'reflex',
184
- reflexPriority: binding.reflexPriority ?? 0,
185
- maxRuntimeMs: binding.maxRuntimeMs ?? ((binding.layer ?? 'reflex') === 'long' ? undefined : 10_000),
186
- epochId: input.epoch.epochSeq, gameId: game!.game_id,
187
- reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` });
188
- result = response.value ?? { accepted: false, reason: 'activation_unavailable' };
262
+ result = await this.driver?.requestReflex({ source: 'perception',
263
+ triggerId: `perception:${source.id}:${activation.behavior}`, scope: input.epoch.scope,
264
+ epochId: input.epoch.epochSeq, configGeneration: generation, behavior,
265
+ behaviorInput: { ...binding.input, ...activation.input }, reflexPriority: binding.reflexPriority ?? 0,
266
+ maxRuntimeMs: binding.maxRuntimeMs ?? 10_000,
267
+ reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` },
268
+ { isCurrent: () => !this.stopped && !context.signal.aborted && generation === this.generation
269
+ && this.watches.has(behavior) && this.sameScope(input.epoch.scope) })
270
+ ?? { accepted: false, reason: 'activation_unavailable' };
189
271
  } catch { result = { accepted: false, reason: 'activation_unavailable' }; }
190
272
  }
191
273
  if (result.accepted) {
@@ -204,26 +286,25 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
204
286
  }
205
287
  }
206
288
  }
207
- if (this.options.unified) this.checkpoint.connectionId = input.epoch.connectionId;
289
+ this.checkpoint.connectionId = input.epoch.connectionId;
208
290
  return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
209
291
  ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
210
292
  }
211
- private validate(result: ReactionResult, source: ResolvedClawclawPerceptionSource): void {
293
+ private validate(result: PerceptionModuleResult, source: ResolvedClawclawPerceptionSource): void {
212
294
  if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
213
295
  || result.events !== undefined && !Array.isArray(result.events)
214
296
  || result.activations !== undefined && !Array.isArray(result.activations)
215
297
  || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
216
298
  || Buffer.byteLength(JSON.stringify(result)) > 128_000) throw new Error('REACTION_OUTPUT_INVALID');
217
299
  for (const event of result.events ?? []) {
218
- if (!record(event) || !source.reaction!.produces.includes(event.type)
300
+ if (!record(event) || !source.module!.produces?.includes(event.type)
219
301
  || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
220
302
  || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
221
- || !record(event.payload) || !this.options.unified
222
- && (typeof event.payload.text !== 'string' || !event.payload.text.trim())) throw new Error('REACTION_EVENT_INVALID');
303
+ || !record(event.payload)) throw new Error('REACTION_EVENT_INVALID');
223
304
  }
224
305
  const bindings = new Set<string>();
225
306
  for (const activation of result.activations ?? []) {
226
- if (!record(activation) || !Object.hasOwn(source.reaction!.behaviors ?? {}, activation.behavior)
307
+ if (!record(activation) || !Object.hasOwn(source.module!.behaviors ?? {}, activation.behavior)
227
308
  || bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
228
309
  || activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
229
310
  || Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key))) throw new Error('REACTION_ACTIVATION_INVALID');
@@ -1,45 +1,58 @@
1
1
  import { Worker } from 'node:worker_threads';
2
2
  import { pathToFileURL } from 'node:url';
3
- import type { ReactionInput, ReactionResult } from '../../../../sdk/perception-plugin/reaction.js';
3
+ import type { PerceptionModuleInput, PerceptionModuleResult } from '../../../../sdk/perception-plugin/module.js';
4
4
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
5
5
  import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
6
+ import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
7
+ import { serveStrategyMemoryRequest, unavailableStrategyMemory } from '../../strategy-memory-rpc.js';
6
8
 
7
- /** Generic reaction execution; no model service, exclusive event routing or delivery rewriting. */
8
- export class ReactionRunner {
9
+ /** Memory-bounded independent perception execution with scoped memory RPC. */
10
+ export class PerceptionModuleRunner {
9
11
  private worker?: Worker;
10
12
  private sequence = 0;
11
13
  private failure?: Error;
12
14
  private pending?: { id?: number; resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> };
13
- constructor(readonly source: ResolvedClawclawPerceptionSource) {}
15
+ private memory?: StrategyMemory;
16
+ constructor(readonly source: ResolvedClawclawPerceptionSource,
17
+ private readonly bindMemory?: (input: PerceptionModuleInput, active: () => boolean) => StrategyMemory) {}
14
18
  async start(): Promise<void> {
15
19
  const ready = this.wait(8_000);
16
20
  this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
17
21
  execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 64 },
18
- workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.module ?? this.source.reaction,
19
- runtimeModuleBootstrap: { hostUrl: new URL(this.source.module ? './perception-module-worker.ts' : './reaction-worker.ts', import.meta.url).href,
22
+ workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.module,
23
+ legacy: !!this.source.reaction,
24
+ runtimeModuleBootstrap: { hostUrl: new URL('./perception-module-worker.ts', import.meta.url).href,
20
25
  ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
21
26
  });
22
27
  this.worker.stdout?.on('data', () => {}); this.worker.stderr?.on('data', () => {});
23
28
  this.worker.on('error', error => this.fail(error));
24
- this.worker.on('exit', () => this.fail(new Error('REACTION_WORKER_EXITED')));
29
+ this.worker.on('exit', () => this.fail(new Error('PERCEPTION_MODULE_WORKER_EXITED')));
25
30
  this.worker.on('message', message => {
31
+ if (message.type === 'strategy_memory') {
32
+ void serveStrategyMemoryRequest(message, () => {
33
+ if (message.requestId !== String(this.pending?.id)) throw Error('strategy_memory_inactive');
34
+ return this.memory ?? unavailableStrategyMemory;
35
+ }, reply => this.worker?.postMessage(reply));
36
+ return;
37
+ }
26
38
  if (!this.pending || (message.id !== undefined && message.id !== this.pending.id)) return;
27
- if (message.type === 'error') { this.fail(new Error('REACTION_MODULE_FAILED')); return; }
39
+ if (message.type === 'error') { this.fail(new Error('PERCEPTION_MODULE_MODULE_FAILED')); return; }
28
40
  const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.resolve(message.result);
29
41
  });
30
42
  await ready;
31
43
  }
32
- async evaluate(input: ReactionInput): Promise<ReactionResult> {
44
+ async evaluate(input: PerceptionModuleInput): Promise<PerceptionModuleResult> {
33
45
  if (this.failure) throw this.failure;
34
- if (!this.worker) throw new Error('REACTION_WORKER_NOT_STARTED');
46
+ if (!this.worker) throw new Error('PERCEPTION_MODULE_WORKER_NOT_STARTED');
35
47
  const id = ++this.sequence; const result = this.wait(500, id);
48
+ this.memory = this.bindMemory?.(input, () => this.pending?.id === id && !this.failure);
36
49
  this.worker.postMessage({ id, input }); return result;
37
50
  }
38
- async stop(): Promise<void> { this.fail(new Error('REACTION_STOPPED')); await this.worker?.terminate(); this.worker = undefined; }
51
+ async stop(): Promise<void> { this.fail(new Error('PERCEPTION_MODULE_STOPPED')); await this.worker?.terminate(); this.worker = undefined; }
39
52
  private wait(ms: number, id?: number): Promise<any> {
40
- if (this.pending) throw new Error('REACTION_CONCURRENT_CALL');
53
+ if (this.pending) throw new Error('PERCEPTION_MODULE_CONCURRENT_CALL');
41
54
  return new Promise((resolve, reject) => {
42
- this.pending = { id, resolve, reject, timer: setTimeout(() => { this.fail(new Error('REACTION_TIMEOUT')); void this.stop(); }, ms) };
55
+ this.pending = { id, resolve, reject, timer: setTimeout(() => { this.fail(new Error('PERCEPTION_MODULE_TIMEOUT')); void this.stop(); }, ms) };
43
56
  });
44
57
  }
45
58
  private fail(error: Error): void {
@@ -1,8 +1,10 @@
1
1
  import { parentPort, workerData } from 'node:worker_threads';
2
2
  import { pathToFileURL } from 'node:url';
3
- import { ClawclawPerception } from '../../../../sdk/perception-plugin/index.js';
3
+ import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception-plugin/index.js';
4
4
  import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
5
5
  import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
6
+ import { normalizeReactionManifest } from '../../reaction-manifest.js';
7
+ import { StrategyMemoryRpcClient } from '../../strategy-memory-rpc.js';
6
8
 
7
9
  function freeze<T>(value: T): T {
8
10
  if (value && typeof value === 'object' && !Object.isFrozen(value)) {
@@ -12,17 +14,26 @@ function freeze<T>(value: T): T {
12
14
  }
13
15
  try {
14
16
  const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
15
- if (!(Module?.prototype instanceof ClawclawPerception)
17
+ if (!(Module?.prototype instanceof (workerData.legacy ? ClawclawReaction : ClawclawPerception))
16
18
  || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw new Error('PERCEPTION_MODULE_CLASS_INVALID');
17
- const manifest = normalizePerceptionModuleManifest(Module.manifest);
19
+ const legacy = workerData.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
20
+ const { kind: _kind, ...common } = legacy ?? {} as any;
21
+ const manifest = legacy ? { ...common, apiVersion: 3 } : normalizePerceptionModuleManifest(Module.manifest);
18
22
  if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
19
23
  parentPort!.postMessage({ type: 'ready' });
20
- parentPort!.on('message', async ({ id, input }: { id: number; input: PerceptionModuleInput }) => {
24
+ const memory = new StrategyMemoryRpcClient(message => parentPort!.postMessage(message));
25
+ let active: number | undefined;
26
+ parentPort!.on('message', async (message: any) => {
27
+ if (memory.receive(message)) return;
28
+ const { id, input }: { id: number; input: PerceptionModuleInput } = message;
29
+ active = id;
21
30
  try {
22
- const result = await new Module().evaluate(freeze({ ...input, config: manifest.config ?? {},
23
- events: input.events.filter(event => manifest.consumes?.includes(event.type)) }));
31
+ const result = await new Module().evaluate(freeze({ ...input,
32
+ events: input.events.filter(event => manifest.consumes?.includes(event.type)) }),
33
+ Object.freeze({ memory: memory.bind(String(id), () => active === id) })) ?? {};
24
34
  if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
25
35
  parentPort!.postMessage({ type: 'result', id, result });
26
36
  } catch { parentPort!.postMessage({ type: 'error', id }); }
37
+ finally { if (active === id) active = undefined; }
27
38
  });
28
39
  } catch { parentPort!.postMessage({ type: 'error' }); }
@@ -327,7 +327,7 @@ function createModuleSlots(
327
327
  const source = sources.get(id);
328
328
  if (!source) throw new Error(`Unknown perception module '${id}'.`);
329
329
  return source;
330
- }).filter(source => !source.reminder && !source.reaction && !source.module);
330
+ }).filter(source => !source.reminder && !source.module);
331
331
  const reducerPool = selected.length > 0
332
332
  ? new PerceptionReducerThreadPool({
333
333
  modules: selected.map((source) => loader.threadSpec(source)),