@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
@@ -0,0 +1,314 @@
1
+ import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult,
2
+ RuntimeEventProposal } from '../../../framework/plugins/index.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';
8
+ import { resolveReactionBehavior, type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
9
+ import { ObservationFrameProjector } from '../../observation-frame-projector.js';
10
+ import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
11
+ import { createCanonicalGameState } from '../../behavior-input.js';
12
+ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
13
+ import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
14
+ import { PerceptionModuleRunner } from './perception-module-runner.js';
15
+ import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
16
+ import type { PerceptionModuleInput, PerceptionModuleResult } from '../../../../sdk/perception-plugin/module.js';
17
+ import type { ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
18
+
19
+ export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
20
+ export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.module_failed'] as const;
21
+ interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
22
+ interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
23
+ interface Checkpoint { gameId?: string; phase?: string; connectionId?: string; previousTick?: number; modules: Record<string, ModuleState>; failures: string[] }
24
+ export interface PerceptionModulePluginOptions {
25
+ /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */
26
+ sources: readonly ResolvedClawclawPerceptionSource[];
27
+ after: readonly string[];
28
+ behaviors?: () => readonly ReactionBehaviorCandidate[];
29
+ runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
30
+ }
31
+ const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
32
+
33
+ /** Observing and notifications remain active independently of fixed Reflex admission. */
34
+ export class ClawclawPerceptionModulePlugin implements RuntimeEpochPlugin<Record<string, any>> {
35
+ readonly kind = 'epoch' as const;
36
+ readonly id: string;
37
+ readonly version = '1';
38
+ readonly catchUp = 'strict_ordered' as const;
39
+ readonly timeoutMs = 10_000;
40
+ readonly after: readonly string[];
41
+ readonly consumes: { events: readonly string[] };
42
+ readonly produces: { events: readonly string[] };
43
+ private readonly sources: readonly ResolvedClawclawPerceptionSource[];
44
+ private readonly runners = new Map<string, Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>>();
45
+ private readonly failed = new Set<string>();
46
+ private checkpoint: Checkpoint = { modules: {}, failures: [] };
47
+ private readonly projector = new ObservationFrameProjector();
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));
51
+ this.after = options.after;
52
+ this.consumes = { events: [...new Set([...this.sources.flatMap(source => [...(source.module!.consumes ?? [])]),
53
+ 'tasks_changed'])] };
54
+ this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
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) }));
121
+ }
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();
124
+ this.checkpoint = { modules: {}, failures: [] }; this.failed.clear(); this.projector.reset();
125
+ await Promise.all(this.sources.map(async (source, index) => {
126
+ try {
127
+ if (index >= 32) throw new Error('REACTION_MODULE_LIMIT');
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
+ });
135
+ this.runners.set(source.id, runner); await runner.start();
136
+ } catch {
137
+ this.failed.add(source.id); await this.runners.get(source.id)?.stop();
138
+ context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
139
+ }
140
+ }));
141
+ }
142
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
143
+ const saved = context.checkpoint() as Checkpoint | undefined;
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
+ }
149
+ this.projector.reset();
150
+ }
151
+ async stop(): Promise<void> { this.stopped = true; this.generation++; await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
152
+ localizedModuleDescriptors(locale: string) {
153
+ return this.sources.filter(source => !this.failed.has(source.id)).map(source =>
154
+ resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, locale));
155
+ }
156
+ async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
157
+ this.scope = { ...input.epoch.scope };
158
+ const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
159
+ const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
160
+ const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
161
+ const initial = !!game && this.checkpoint.gameId !== game.game_id;
162
+ const boundary = initial ? 'initial' as const : this.checkpoint.connectionId !== undefined
163
+ && this.checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
164
+ if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
165
+ if ((!game && this.checkpoint.phase !== undefined)
166
+ || (game && this.checkpoint.phase !== game.phase)) {
167
+ this.checkpoint.previousTick = undefined;
168
+ for (const state of Object.values(this.checkpoint.modules)) {
169
+ state.value = undefined;
170
+ for (const binding of Object.values(state.bindings)) {
171
+ binding.armed = true; binding.lastAcceptedAt = undefined; binding.failedAttempt = undefined;
172
+ }
173
+ }
174
+ this.checkpoint.phase = game?.phase;
175
+ }
176
+ const frame = this.projector.project(input.frame);
177
+ if (frame) {
178
+ const delta = this.checkpoint.previousTick === undefined ? null : frame.tick - this.checkpoint.previousTick;
179
+ Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
180
+ && this.checkpoint.connectionId === input.epoch.connectionId });
181
+ this.checkpoint.previousTick = frame.tick;
182
+ }
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
186
+ || event.producerPluginId === 'clawclaw.derived-event')).map(event => ({
187
+ eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
188
+ type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
189
+ payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
190
+ }));
191
+ const taskChanges: ReminderTaskChange[] = facts.filter(event => event.type === 'tasks_changed').flatMap(event =>
192
+ (Array.isArray(event.payload.delta) ? event.payload.delta : []).map((change: Record<string, unknown>, index: number) => ({
193
+ ...change, key: `change:${event.eventId}:${index}`, eventId: event.eventId, epochId: event.epochId,
194
+ baseline: event.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(event.payload.reason)),
195
+ } as ReminderTaskChange)));
196
+ const events: RuntimeEventProposal[] = [];
197
+ const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState; generation: number }> = [];
198
+ for (const source of this.sources) {
199
+ if (!this.failed.has(source.id)) {
200
+ try {
201
+ const state = Object.hasOwn(this.checkpoint.modules, source.id)
202
+ ? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
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 };
212
+ // A control-only epoch is not an observation that clears a visual condition.
213
+ if (!frame && moduleInput.events.length === 0) continue;
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--; }
219
+ this.validate(result, source);
220
+ state.value = structuredClone(result.state);
221
+ for (const event of result.events ?? []) events.push({ type: event.type,
222
+ dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
223
+ payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
224
+ const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
225
+ for (const [key, binding] of Object.entries(source.module!.behaviors ?? {})) {
226
+ const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
227
+ if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) {
228
+ current.warning = undefined; current.failedAttempt = undefined;
229
+ }
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;
233
+ if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
234
+ // Ignore only the missing binding; the module's other outputs continue above.
235
+ if (current.warning === 'behavior_not_loaded') continue;
236
+ if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
237
+ if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
238
+ requests.push({ source, activation: matched.get(key)!, state: current, generation });
239
+ }
240
+ } catch {
241
+ this.failed.add(source.id); await this.runners.get(source.id)?.stop();
242
+ context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
243
+ }
244
+ }
245
+ if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
246
+ this.checkpoint.failures.push(source.id);
247
+ events.push({ type: 'perception.module_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
248
+ payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
249
+ }
250
+ }
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?.() ?? []));
257
+ const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
258
+ if (state.failedAttempt === attempt) continue;
259
+ let result: { accepted: boolean; reason?: string } = { accepted: false, reason: 'behavior_not_loaded' };
260
+ if (behavior && this.watches.has(behavior)) {
261
+ try {
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' };
271
+ } catch { result = { accepted: false, reason: 'activation_unavailable' }; }
272
+ }
273
+ if (result.accepted) {
274
+ state.armed = false; state.lastAcceptedAt = nowMs; state.warning = undefined; state.failedAttempt = undefined;
275
+ } else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
276
+ const reason = result.reason ?? 'activation_unavailable';
277
+ state.failedAttempt = attempt;
278
+ if (state.warning !== reason) {
279
+ state.warning = reason; state.warningSequence++;
280
+ events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
281
+ dedupeKey: JSON.stringify([game?.game_id, source.id, activation.behavior, state.warningSequence]),
282
+ payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
283
+ ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
284
+ ...(behavior ? { behavior_id: behavior } : {}), reason,
285
+ text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
286
+ }
287
+ }
288
+ }
289
+ this.checkpoint.connectionId = input.epoch.connectionId;
290
+ return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
291
+ ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
292
+ }
293
+ private validate(result: PerceptionModuleResult, source: ResolvedClawclawPerceptionSource): void {
294
+ if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
295
+ || result.events !== undefined && !Array.isArray(result.events)
296
+ || result.activations !== undefined && !Array.isArray(result.activations)
297
+ || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
298
+ || Buffer.byteLength(JSON.stringify(result)) > 128_000) throw new Error('REACTION_OUTPUT_INVALID');
299
+ for (const event of result.events ?? []) {
300
+ if (!record(event) || !source.module!.produces?.includes(event.type)
301
+ || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
302
+ || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
303
+ || !record(event.payload)) throw new Error('REACTION_EVENT_INVALID');
304
+ }
305
+ const bindings = new Set<string>();
306
+ for (const activation of result.activations ?? []) {
307
+ if (!record(activation) || !Object.hasOwn(source.module!.behaviors ?? {}, activation.behavior)
308
+ || bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
309
+ || activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
310
+ || Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key))) throw new Error('REACTION_ACTIVATION_INVALID');
311
+ bindings.add(activation.behavior);
312
+ }
313
+ }
314
+ }
@@ -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.reaction,
19
- runtimeModuleBootstrap: { hostUrl: new URL('./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 {
@@ -0,0 +1,39 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception-plugin/index.js';
4
+ import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
5
+ import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
6
+ import { normalizeReactionManifest } from '../../reaction-manifest.js';
7
+ import { StrategyMemoryRpcClient } from '../../strategy-memory-rpc.js';
8
+
9
+ function freeze<T>(value: T): T {
10
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
11
+ for (const child of Object.values(value)) freeze(child); Object.freeze(value);
12
+ }
13
+ return value;
14
+ }
15
+ try {
16
+ const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
17
+ if (!(Module?.prototype instanceof (workerData.legacy ? ClawclawReaction : ClawclawPerception))
18
+ || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw new Error('PERCEPTION_MODULE_CLASS_INVALID');
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);
22
+ if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
23
+ parentPort!.postMessage({ type: 'ready' });
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;
30
+ try {
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) })) ?? {};
34
+ if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
35
+ parentPort!.postMessage({ type: 'result', id, result });
36
+ } catch { parentPort!.postMessage({ type: 'error', id }); }
37
+ finally { if (active === id) active = undefined; }
38
+ });
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);
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)),
@@ -23,10 +23,12 @@ import type {
23
23
  import { PERCEPTION_PLUGIN_API_VERSION } from './contracts.js';
24
24
  import { literalPluginApiVersion } from '../plugin-api-version.js';
25
25
  import { parseLiteralModuleManifest } from '../behavior-input-source.js';
26
+ import { normalizeReactionManifest } from '../../reaction-manifest.js';
27
+ import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
26
28
  import { normalizeReminderManifest } from '../../reminder-manifest.js';
27
29
  import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
28
- import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
29
- import { normalizeReactionManifest } from '../../reaction-manifest.js';
30
+ import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
31
+ import type { PerceptionModuleManifest } from '../../../../sdk/perception-plugin/module.js';
30
32
 
31
33
  export const MAX_PERCEPTION_FILES = 512;
32
34
  const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
@@ -46,11 +48,19 @@ export interface ResolvedClawclawPerceptionSource {
46
48
  readonly manifest: ClawclawPerceptionManifest;
47
49
  /** Non-visual execution contract; manifest above is the common resource descriptor. */
48
50
  readonly reminder?: ClawclawReminderManifest;
51
+ readonly module?: PerceptionModuleManifest;
49
52
  readonly reaction?: ClawclawReactionManifest;
50
53
  readonly sourcePath: string;
51
54
  readonly sourceRoot: string;
52
55
  }
53
56
 
57
+ export function expectedPerceptionApiVersion(source: ResolvedClawclawPerceptionSource): number {
58
+ return source.reaction ? 2 : source.module ? 3 : 2;
59
+ }
60
+ export function isSupportedPerceptionSource(source: ResolvedClawclawPerceptionSource): boolean {
61
+ return source.apiVersion === expectedPerceptionApiVersion(source);
62
+ }
63
+
54
64
  function pathInside(root: string, candidate: string): boolean {
55
65
  const child = relative(root, candidate);
56
66
  return child === '' || (!child.startsWith('..') && !isAbsolute(child));
@@ -351,14 +361,27 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
351
361
  const manifestBlock = balancedBlock(classBody, manifestOpen, '{', '}');
352
362
  if (!manifestBlock) return null;
353
363
 
364
+ if (classMatch[1] === 'ClawclawPerception' && /\bevaluate\s*\(/.test(classBody)
365
+ && literalPluginApiVersion(manifestBlock) !== 2) {
366
+ try {
367
+ const module = normalizePerceptionModuleManifest(parseLiteralModuleManifest(manifestBlock), false);
368
+ const { id, description, localizations } = module;
369
+ return { apiVersion: module.apiVersion, id, name: module.name ?? id, description, module, sourcePath, sourceRoot,
370
+ // Existing resource metadata consumers use this v2-shaped descriptor; executable v3 stays in module.
371
+ manifest: { apiVersion: PERCEPTION_PLUGIN_API_VERSION, id, name: module.name ?? id, description, localizations,
372
+ subjectScope: 'self_and_others', produces: module.produces ?? [] } };
373
+ } catch { return null; }
374
+ }
354
375
  if (classMatch[1] === 'ClawclawReaction') {
355
376
  try {
356
377
  const reaction = normalizeReactionManifest(parseLiteralModuleManifest(manifestBlock), false);
357
- const { id, description, localizations } = reaction;
358
- const name = reaction.name ?? id;
359
- return { apiVersion: reaction.apiVersion, id, name, description, reaction, sourcePath, sourceRoot,
360
- manifest: { apiVersion: reaction.apiVersion, id, name, description, localizations,
361
- subjectScope: 'self_and_others', produces: [] } };
378
+ const { kind: _kind, ...common } = reaction;
379
+ const module: PerceptionModuleManifest = { ...common, apiVersion: 3 };
380
+ return { apiVersion: reaction.apiVersion, id: reaction.id, name: reaction.name ?? reaction.id,
381
+ description: reaction.description, module, reaction, sourcePath, sourceRoot,
382
+ manifest: { apiVersion: 2, id: reaction.id, name: reaction.name ?? reaction.id,
383
+ description: reaction.description, localizations: reaction.localizations,
384
+ subjectScope: 'self_and_others', produces: reaction.produces } };
362
385
  } catch { return null; }
363
386
  }
364
387
  if (classMatch[1] === 'ClawclawReminder') {