@myclaw163/clawclaw-cli 0.8.38 → 0.8.40

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 (45) hide show
  1. package/docs/custom-modules/README.md +58 -65
  2. package/docs/custom-modules/api-reference.md +16 -3
  3. package/docs/custom-modules/behavior.md +167 -129
  4. package/docs/custom-modules/examples/go-to-point.ts +49 -0
  5. package/docs/custom-modules/examples/nearby-escape.ts +56 -0
  6. package/docs/custom-modules/examples/nearby-notice.ts +36 -0
  7. package/docs/custom-modules/perception-reactions.md +189 -0
  8. package/docs/custom-modules/perception-visual.md +324 -0
  9. package/docs/custom-modules/perception.md +54 -317
  10. package/docs/custom-modules/reminders.md +31 -18
  11. package/docs/custom-modules/trigger.md +2 -0
  12. package/docs/runtime/components-and-boundaries.md +2 -2
  13. package/package.json +1 -1
  14. package/skills/clawclaw/SKILL.md +11 -5
  15. package/skills/clawclaw/references/BEHAVIORS.md +13 -3
  16. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +166 -142
  17. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +19 -3
  18. package/skills/clawclaw/references/CUSTOM-MODULES.md +55 -54
  19. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +54 -320
  20. package/skills/clawclaw/references/CUSTOM-REACTION-DEVELOPMENT.md +189 -0
  21. package/skills/clawclaw/references/CUSTOM-REMINDER-DEVELOPMENT.md +31 -18
  22. package/skills/clawclaw/references/CUSTOM-VISUAL-PERCEPTION-DEVELOPMENT.md +328 -0
  23. package/src/commands/load.ts +25 -1
  24. package/src/commands/perception.ts +1 -0
  25. package/src/lib/agent-workspace-runtime.ts +11 -5
  26. package/src/lib/capability-load-diagnostics.ts +1 -1
  27. package/src/lib/capability-operation-name.ts +1 -0
  28. package/src/runtime/clawclaw/behavior-activation-capability.ts +21 -0
  29. package/src/runtime/clawclaw/owner.ts +8 -3
  30. package/src/runtime/clawclaw/plugins/assembly.ts +20 -3
  31. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
  32. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +4 -0
  33. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +72 -9
  34. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -0
  35. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  36. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +14 -1
  37. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +198 -0
  38. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +49 -0
  39. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +26 -0
  40. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +23 -0
  41. package/src/runtime/clawclaw/reaction-manifest.ts +50 -0
  42. package/src/runtime/clawclaw/runtime.ts +3 -0
  43. package/src/runtime/clawclaw-event-catalog.ts +5 -1
  44. package/src/sdk/perception-plugin/index.ts +1 -0
  45. package/src/sdk/perception-plugin/reaction.ts +78 -0
@@ -2,6 +2,7 @@ import type { GameClient } from '../../../lib/game-client.js';
2
2
  import { ClawclawReminderPlugin, CLAWCLAW_REMINDER_PLUGIN_ID } from './derived-event/reminder-plugin.js';
3
3
  import { listClawclawPerceptionSources } from './perception/perception-source.js';
4
4
  import { DEFAULT_PERCEPTION_MODULES } from './perception/official-module-ids.js';
5
+ import { ClawclawReactionPlugin, CLAWCLAW_REACTION_PLUGIN_ID } from './perception/reaction-plugin.js';
5
6
  import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
6
7
  import {
7
8
  CLAWCLAW_ACTION_PLUGIN_ID,
@@ -39,7 +40,7 @@ import {
39
40
  export interface ClawclawPluginAssemblyOptions {
40
41
  epochPlugins?: readonly RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
41
42
  perception?: ClawclawPerceptionConfig;
42
- behaviorCatalog?: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
43
+ behaviorCatalog?: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'> & Partial<Pick<ClawclawBehaviorCatalog, 'list'>>;
43
44
  behaviorDiagnosticsEnabled?: boolean;
44
45
  triggerDiagnosticsEnabled?: boolean;
45
46
  fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
@@ -49,6 +50,7 @@ export interface ClawclawPluginAssemblyOptions {
49
50
  }
50
51
 
51
52
  export interface ClawclawPluginAssembly {
53
+ reactions?: ClawclawReactionPlugin;
52
54
  plugins: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
53
55
  action: ClawclawActionPlugin;
54
56
  gameQuery: ClawclawGameQueryPlugin;
@@ -92,6 +94,8 @@ export function assembleClawclawPlugins(
92
94
  throw new Error(`Runtime Plugin ${CLAWCLAW_REMINDER_PLUGIN_ID} is not a ClawclawReminderPlugin.`);
93
95
  }
94
96
  const selected = new Set(options.perception?.modules ?? DEFAULT_PERCEPTION_MODULES);
97
+ const reactionSources = (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
98
+ .filter(source => source.reaction && source.apiVersion === 2 && selected.has(source.id));
95
99
  const reminders = configuredReminders as ClawclawReminderPlugin | undefined ?? new ClawclawReminderPlugin({
96
100
  sources: (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
97
101
  .filter(source => source.reminder && selected.has(source.id)),
@@ -121,17 +125,29 @@ export function assembleClawclawPlugins(
121
125
  const trigger = configuredTrigger as ClawclawTriggerPlugin | undefined
122
126
  ?? new ClawclawTriggerPlugin({
123
127
  after: [],
124
- triggers: options.triggers,
128
+ // A migrated, selected perception replaces the same declared legacy Trigger.
129
+ // Its old file/config can remain for rollback without evaluating the rule twice.
130
+ triggers: options.triggers?.map(entry => reactionSources.some(source =>
131
+ (source.declaredId ?? source.id) === entry.source.id) ? { ...entry, enabled: false } : entry),
125
132
  diagnosticsEnabled: options.triggerDiagnosticsEnabled,
126
133
  });
127
134
  if (!configuredTrigger) plugins.push(trigger);
128
135
 
136
+ const reactions = reactionSources.length ? new ClawclawReactionPlugin({
137
+ sources: reactionSources,
138
+ after: [CLAWCLAW_DERIVED_EVENT_PLUGIN_ID, CLAWCLAW_REMINDER_PLUGIN_ID,
139
+ CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID],
140
+ behaviors: () => options.behaviorCatalog?.list?.() ?? [],
141
+ }) : undefined;
142
+ if (reactions) plugins.push(reactions);
143
+
129
144
  const configuredBehavior = plugins.find((plugin) => plugin.id === CLAWCLAW_BEHAVIOR_PLUGIN_ID);
130
145
  if (configuredBehavior && !(configuredBehavior instanceof ClawclawBehaviorPlugin)) {
131
146
  throw new Error(`Runtime Plugin ${CLAWCLAW_BEHAVIOR_PLUGIN_ID} is not a ClawclawBehaviorPlugin.`);
132
147
  }
133
148
  const behavior = configuredBehavior as ClawclawBehaviorPlugin | undefined
134
149
  ?? new ClawclawBehaviorPlugin({
150
+ perceptionActivations: !!reactions,
135
151
  catalog: options.behaviorCatalog ?? new ClawclawBehaviorCatalog([]),
136
152
  fallbackBehaviors: options.fallbackBehaviors,
137
153
  after: [
@@ -141,6 +157,7 @@ export function assembleClawclawPlugins(
141
157
  CLAWCLAW_GAME_QUERY_PLUGIN_ID,
142
158
  CLAWCLAW_PERCEPTION_PLUGIN_ID,
143
159
  CLAWCLAW_TRIGGER_PLUGIN_ID,
160
+ ...(reactions ? [CLAWCLAW_REACTION_PLUGIN_ID] : []),
144
161
  ],
145
162
  eventTypes: options.behaviorEventTypes,
146
163
  diagnosticsEnabled: options.behaviorDiagnosticsEnabled,
@@ -167,5 +184,5 @@ export function assembleClawclawPlugins(
167
184
  ?? new ClawclawMailboxPlugin({ after: eventProducers });
168
185
  if (!configuredMailbox) plugins.push(mailbox);
169
186
 
170
- return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox };
187
+ return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox, reactions };
171
188
  }
@@ -1,6 +1,6 @@
1
1
  import type { BehaviorActivationLayer } from '../../../../sdk/behavior-plugin/index.js';
2
2
 
3
- export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'behavior' | 'system';
3
+ export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'behavior' | 'system' | 'perception';
4
4
  export type BehaviorActivationState = 'running' | 'suspended';
5
5
 
6
6
  export interface BehaviorActivationSpec {
@@ -18,6 +18,8 @@ export interface ClawclawBehaviorCatalogEntry {
18
18
  readonly apiVersion: number | null;
19
19
  readonly expectedApiVersion: typeof BEHAVIOR_PLUGIN_API_VERSION;
20
20
  readonly id: string;
21
+ readonly declaredId?: string;
22
+ readonly resourceId?: string;
21
23
  readonly name: string;
22
24
  readonly description: string;
23
25
  readonly localizations?: ResolvedClawclawBehaviorSource['localizations'];
@@ -45,6 +47,8 @@ function catalogEntry(source: ResolvedClawclawBehaviorSource): ClawclawBehaviorC
45
47
  apiVersion: source.apiVersion ?? null,
46
48
  expectedApiVersion: BEHAVIOR_PLUGIN_API_VERSION,
47
49
  id: source.id,
50
+ ...(source.declaredId === undefined ? {} : { declaredId: source.declaredId }),
51
+ ...(source.resourceId === undefined ? {} : { resourceId: source.resourceId }),
48
52
  name: source.name,
49
53
  description: source.description,
50
54
  ...(source.localizations === undefined ? {} : { localizations: source.localizations }),
@@ -25,6 +25,8 @@ import type {
25
25
  import { createBehaviorInput } from '../../behavior-input.js';
26
26
  import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
27
27
  import { isClawclawRuntimeState } from '../../runtime-state.js';
28
+ import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
29
+ type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
28
30
  import { CLAWCLAW_ACTION_CAPABILITY, CLAWCLAW_ACTION_PLUGIN_ID } from '../action/index.js';
29
31
  import { CLAWCLAW_DERIVED_EVENT_PLUGIN_ID } from '../derived-event/index.js';
30
32
  import { CLAWCLAW_GAME_QUERY_PLUGIN_ID } from '../game-query/index.js';
@@ -109,6 +111,7 @@ function isSuccessfulBackendStrategyReport(value: unknown): boolean {
109
111
  }
110
112
 
111
113
  export interface ClawclawBehaviorPluginOptions {
114
+ readonly perceptionActivations?: boolean;
112
115
  readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
113
116
  readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
114
117
  readonly manager?: BehaviorActivationManager;
@@ -124,8 +127,10 @@ export interface ClawclawBehaviorPluginOptions {
124
127
  }
125
128
 
126
129
  export interface StartBehaviorOptions {
127
- readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system'>;
130
+ readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system' | 'perception'>;
128
131
  readonly maxRuntimeMs?: number;
132
+ /** Revalidate scope/phase after asynchronous preparation, before changing control. */
133
+ readonly isCurrent?: () => boolean;
129
134
  }
130
135
 
131
136
  export interface ClawclawBehaviorHostStatus {
@@ -280,7 +285,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
280
285
  readonly after: readonly string[];
281
286
  readonly consumes = { events: ['*'] } as const;
282
287
  readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
283
- readonly capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY] } as const;
288
+ readonly capabilities: { uses: readonly string[]; provides?: readonly string[] };
289
+ private releasePerceptionActivation?: () => void;
284
290
  readonly catchUp: RuntimeEpochCatchUp;
285
291
  readonly backlogPolicy = 'finish_started' as const;
286
292
  get maxInFlight(): number {
@@ -327,6 +333,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
327
333
  private backendStrategyReportLifecycleGeneration = 0;
328
334
 
329
335
  constructor(options: ClawclawBehaviorPluginOptions) {
336
+ this.capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY],
337
+ ...(options.perceptionActivations ? { provides: [BEHAVIOR_ACTIVATION_CAPABILITY] } : {}) };
330
338
  this.catalog = options.catalog;
331
339
  this.fallbackBehaviors = normalizeRoleFallbackBehaviors(options.fallbackBehaviors);
332
340
  this.manager = options.manager ?? new BehaviorActivationManager();
@@ -363,6 +371,49 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
363
371
  this.scope = context.scope;
364
372
  this.diagnostic = context.diagnostic;
365
373
  this.stopped = false;
374
+ if (this.capabilities.provides?.includes(BEHAVIOR_ACTIVATION_CAPABILITY)) {
375
+ this.releasePerceptionActivation = context.capabilities.provideAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>({
376
+ capability: BEHAVIOR_ACTIVATION_CAPABILITY,
377
+ describeControl: () => ({ domains: [] }),
378
+ perform: async (request, scope, _caller, execution) => {
379
+ const activationBeforePreparation = this.manager.current();
380
+ const current = () => {
381
+ if (execution.signal.aborted || this.stopped || scope.sessionId !== this.scope?.sessionId
382
+ || scope.segmentId !== this.scope?.segmentId || request.epochId <= this.lastCommittedEpochSeq) return false;
383
+ const active = this.manager.current();
384
+ if (active?.activationId !== activationBeforePreparation?.activationId
385
+ || active?.instanceGeneration !== activationBeforePreparation?.instanceGeneration) return false;
386
+ const latest = execution.latestAcceptedState();
387
+ if (!latest) return false;
388
+ const state = latest.state as Record<string, any>;
389
+ const game = isClawclawRuntimeState(state)
390
+ ? state.connection === 'connected' && state.stage === 'game' && state.game_snapshot.status === 'fresh'
391
+ ? state.game_snapshot.state : undefined
392
+ : state;
393
+ return !!game && game.game_id === request.gameId && game.phase === 'wandering' && game.you?.is_alive === true;
394
+ };
395
+ let value: PerceptionBehaviorActivationResult = { accepted: false, reason: 'stale_request' };
396
+ if (current()) {
397
+ try {
398
+ if (!this.catalog.has(request.behavior)) value = { accepted: false, reason: 'behavior_not_loaded' };
399
+ else if (request.layer === 'reflex') value = await this.requestReflex({
400
+ source: 'trigger', triggerId: `perception:${request.moduleId}:${request.bindingKey}`,
401
+ scope: { sessionId: scope.sessionId, segmentId: scope.segmentId }, epochId: request.epochId,
402
+ configGeneration: 0, behavior: request.behavior, behaviorInput: request.input,
403
+ reflexPriority: request.reflexPriority, maxRuntimeMs: request.maxRuntimeMs ?? 10_000,
404
+ reason: request.reason,
405
+ }, { isCurrent: current });
406
+ else {
407
+ const activation = await this.startLayer(request.layer, request.behavior, request.input,
408
+ { source: 'perception', maxRuntimeMs: request.maxRuntimeMs, isCurrent: current });
409
+ value = { accepted: true, activationId: activation.activationId };
410
+ }
411
+ } catch { value = { accepted: false, reason: current() ? 'binding_invalid' : 'stale_request' }; }
412
+ }
413
+ return { scope, actionId: randomUUID(), status: 'success', source: 'local', value };
414
+ },
415
+ });
416
+ }
366
417
  await this.applyTransitions(this.manager.leaveBoundary(this.now()));
367
418
  }
368
419
 
@@ -398,12 +449,19 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
398
449
  });
399
450
  }
400
451
 
401
- configureFallbackBehaviors(bindings: ClawclawRoleFallbackBehaviors): Promise<void> {
452
+ configureFallbackBehaviors(
453
+ bindings: ClawclawRoleFallbackBehaviors,
454
+ currentRole?: string,
455
+ ): Promise<void> {
402
456
  return this.enqueueControl(async () => {
403
457
  this.fallbackBehaviors = normalizeRoleFallbackBehaviors(bindings);
404
458
  this.fallbackConfigGeneration += 1;
405
459
  this.appliedFallbackKey = undefined;
406
460
  this.manualFallbackOverride = false;
461
+ // A control receipt must reflect the current role's effective binding,
462
+ // including meetings with no fresh observation frame. The activation
463
+ // manager still owns boundary suspension and explicit long Behaviors.
464
+ await this.syncRoleFallback(currentRole, this.now());
407
465
  });
408
466
  }
409
467
 
@@ -721,6 +779,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
721
779
  }
722
780
 
723
781
  async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
782
+ this.releasePerceptionActivation?.(); this.releasePerceptionActivation = undefined;
724
783
  await this.enqueueControl(async () => {
725
784
  this.stopped = true;
726
785
  this.resetBackendStrategyReporting();
@@ -760,6 +819,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
760
819
  return this.enqueueControl(async () => {
761
820
  if (this.stopped || !this.scope) throw new Error('behavior_host_not_active');
762
821
  const prepared = await this.catalog.prepare(behaviorId, input);
822
+ if (options.isCurrent && !options.isCurrent()) throw new Error('perception_activation_stale');
763
823
  const activationId = this.createActivationId();
764
824
  const maxRuntimeMs = layer === 'short'
765
825
  ? runtimeMs(prepared, input, options.maxRuntimeMs) ?? DEFAULT_SHORT_MAX_RUNTIME_MS
@@ -808,7 +868,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
808
868
  const now = frameForClock?.nowMs ?? this.now();
809
869
  const runtimeState = input.epoch.state;
810
870
 
811
- await this.syncRoleFallback(frameForClock, now);
871
+ await this.syncRoleFallback(frameForClock?.gameState.you?.role, now);
812
872
  if (
813
873
  !frameForClock
814
874
  && isClawclawRuntimeState(runtimeState)
@@ -1331,10 +1391,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1331
1391
  }
1332
1392
 
1333
1393
  private async syncRoleFallback(
1334
- frame: Readonly<BehaviorInput> | null,
1394
+ role: string | undefined,
1335
1395
  now: number,
1336
1396
  ): Promise<void> {
1337
- const role = frame?.gameState.you?.role;
1338
1397
  if (this.manualFallbackOverride) return;
1339
1398
  if (typeof role !== 'string' || !role) return;
1340
1399
  const configured = this.fallbackBehaviors.get(role);
@@ -1404,7 +1463,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1404
1463
  && state.connection === 'connected'
1405
1464
  && state.stage === 'game'
1406
1465
  && state.game_snapshot.status === 'fresh'
1407
- && state.game_snapshot.state.phase === 'wandering';
1466
+ && state.game_snapshot.state.phase === 'wandering'
1467
+ && state.game_snapshot.state.you?.is_alive === true;
1408
1468
 
1409
1469
  const descriptor = this.backendStrategyDescriptor();
1410
1470
  const nextTarget = descriptor
@@ -1423,7 +1483,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1423
1483
  }
1424
1484
 
1425
1485
  const target = this.backendStrategyReportTarget;
1426
- if (!target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
1486
+ if (!this.backendStrategyReportEligible || !target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
1427
1487
  this.clearBackendStrategyReportTimer();
1428
1488
  return;
1429
1489
  }
@@ -1467,7 +1527,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1467
1527
  || this.backendStrategyReportInFlight
1468
1528
  ) return;
1469
1529
  if (!this.backendStrategyReportEligible || !context || context.signal.aborted) {
1470
- this.scheduleBackendStrategyReport(BACKEND_STRATEGY_REPORT_RETRY_MS);
1471
1530
  return;
1472
1531
  }
1473
1532
 
@@ -1528,6 +1587,10 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1528
1587
  }
1529
1588
 
1530
1589
  if (target?.fingerprint === attempt.fingerprint) {
1590
+ if (!this.backendStrategyReportEligible) {
1591
+ this.clearBackendStrategyReportTimer();
1592
+ return;
1593
+ }
1531
1594
  this.backendStrategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
1532
1595
  strategy_id: target.id,
1533
1596
  retry_ms: BACKEND_STRATEGY_REPORT_RETRY_MS,
@@ -63,6 +63,8 @@ export interface ResolvedClawclawBehaviorSource {
63
63
  readonly id: string;
64
64
  /** Host-assigned operation names never change the ID in the source file. */
65
65
  readonly declaredId?: string;
66
+ /** Host-only Hub identity used for optional perception dependency preferences. */
67
+ readonly resourceId?: string;
66
68
  readonly workingCopyPath?: string;
67
69
  readonly name: string;
68
70
  readonly display?: Readonly<{ name: string; description: string }>;
@@ -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);
330
+ }).filter(source => !source.reminder && !source.reaction);
331
331
  const reducerPool = selected.length > 0
332
332
  ? new PerceptionReducerThreadPool({
333
333
  modules: selected.map((source) => loader.threadSpec(source)),
@@ -25,11 +25,13 @@ import { literalPluginApiVersion } from '../plugin-api-version.js';
25
25
  import { parseLiteralModuleManifest } from '../behavior-input-source.js';
26
26
  import { normalizeReminderManifest } from '../../reminder-manifest.js';
27
27
  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';
28
30
 
29
31
  export const MAX_PERCEPTION_FILES = 512;
30
32
  const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
31
33
  const SAFE_IMPORT = /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/;
32
- const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder)(?:\s*<[^>{}]*>)?\s*\{/;
34
+ const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder|ClawclawReaction)(?:\s*<[^>{}]*>)?\s*\{/;
33
35
  const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/;
34
36
 
35
37
  export interface ResolvedClawclawPerceptionSource {
@@ -44,6 +46,7 @@ export interface ResolvedClawclawPerceptionSource {
44
46
  readonly manifest: ClawclawPerceptionManifest;
45
47
  /** Non-visual execution contract; manifest above is the common resource descriptor. */
46
48
  readonly reminder?: ClawclawReminderManifest;
49
+ readonly reaction?: ClawclawReactionManifest;
47
50
  readonly sourcePath: string;
48
51
  readonly sourceRoot: string;
49
52
  }
@@ -348,6 +351,16 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
348
351
  const manifestBlock = balancedBlock(classBody, manifestOpen, '{', '}');
349
352
  if (!manifestBlock) return null;
350
353
 
354
+ if (classMatch[1] === 'ClawclawReaction') {
355
+ try {
356
+ 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: [] } };
362
+ } catch { return null; }
363
+ }
351
364
  if (classMatch[1] === 'ClawclawReminder') {
352
365
  try {
353
366
  const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
@@ -0,0 +1,198 @@
1
+ import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult,
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';
5
+ 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
+ import { ObservationFrameProjector } from '../../observation-frame-projector.js';
9
+ import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
10
+ import { createCanonicalGameState } from '../../behavior-input.js';
11
+ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
12
+ import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
13
+ import { ReactionRunner } from './reaction-runner.js';
14
+ import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
15
+
16
+ export const CLAWCLAW_REACTION_PLUGIN_ID = 'clawclaw.perception.reactions';
17
+ export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.reaction_failed'] as const;
18
+ interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
19
+ interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
20
+ interface Checkpoint { gameId?: string; phase?: string; modules: Record<string, ModuleState>; failures: string[] }
21
+ export interface ReactionPluginOptions {
22
+ sources: readonly ResolvedClawclawPerceptionSource[];
23
+ after: readonly string[];
24
+ behaviors: () => readonly ReactionBehaviorCandidate[];
25
+ runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>;
26
+ }
27
+ const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
28
+
29
+ /** All modules observe their subscribed facts independently. Only own outputs are produced. */
30
+ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
31
+ readonly kind = 'epoch' as const;
32
+ readonly id = CLAWCLAW_REACTION_PLUGIN_ID;
33
+ readonly version = '1';
34
+ readonly catchUp = 'strict_ordered' as const;
35
+ readonly timeoutMs = 10_000;
36
+ readonly after: readonly string[];
37
+ readonly consumes: { events: readonly string[] };
38
+ readonly produces: { events: readonly string[] };
39
+ readonly capabilities = { uses: [BEHAVIOR_ACTIVATION_CAPABILITY] };
40
+ private readonly sources: readonly ResolvedClawclawPerceptionSource[];
41
+ private readonly runners = new Map<string, Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>>();
42
+ private readonly failed = new Set<string>();
43
+ private checkpoint: Checkpoint = { modules: {}, failures: [] };
44
+ private readonly projector = new ObservationFrameProjector();
45
+ constructor(private readonly options: ReactionPluginOptions) {
46
+ this.sources = options.sources.filter(source => source.reaction).map(source => ({
47
+ ...source, reaction: normalizeReactionManifest(source.reaction),
48
+ })).sort((a, b) => a.id.localeCompare(b.id));
49
+ this.after = options.after;
50
+ this.consumes = { events: [...new Set(this.sources.flatMap(source => [...source.reaction!.consumes]))] };
51
+ this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
52
+ ...this.sources.flatMap(source => [...source.reaction!.produces])])] };
53
+ }
54
+ async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
55
+ this.checkpoint = { modules: {}, failures: [] }; this.failed.clear(); this.projector.reset();
56
+ await Promise.all(this.sources.map(async (source, index) => {
57
+ try {
58
+ if (index >= 32) throw new Error('REACTION_MODULE_LIMIT');
59
+ const runner = this.options.runnerFactory?.(source) ?? new ReactionRunner(source);
60
+ this.runners.set(source.id, runner); await runner.start();
61
+ } catch {
62
+ this.failed.add(source.id); await this.runners.get(source.id)?.stop();
63
+ context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
64
+ }
65
+ }));
66
+ }
67
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
68
+ const saved = context.checkpoint() as Checkpoint | undefined;
69
+ if (saved?.modules && Array.isArray(saved.failures)) this.checkpoint = structuredClone(saved);
70
+ this.projector.reset();
71
+ }
72
+ async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
73
+ localizedModuleDescriptors(locale: string) {
74
+ return this.sources.filter(source => !this.failed.has(source.id)).map(source =>
75
+ resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, locale));
76
+ }
77
+ async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
78
+ const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
79
+ const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
80
+ const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
81
+ if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
82
+ if (!game || this.checkpoint.phase !== game.phase) {
83
+ for (const state of Object.values(this.checkpoint.modules)) {
84
+ state.value = undefined;
85
+ for (const binding of Object.values(state.bindings)) {
86
+ binding.armed = true; binding.lastAcceptedAt = undefined; binding.failedAttempt = undefined;
87
+ }
88
+ }
89
+ this.checkpoint.phase = game?.phase;
90
+ }
91
+ const frame = this.projector.project(input.frame);
92
+ const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
93
+ const candidates = this.options.behaviors();
94
+ const facts = input.pendingEvents.filter(event => !event.replayed).map(event => ({
95
+ eventId: event.eventId, type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
96
+ payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
97
+ }));
98
+ const events: RuntimeEventProposal[] = [];
99
+ const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState }> = [];
100
+ for (const source of this.sources) {
101
+ if (!this.failed.has(source.id)) {
102
+ try {
103
+ const state = Object.hasOwn(this.checkpoint.modules, source.id)
104
+ ? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
105
+ const moduleInput: ReactionInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
106
+ events: facts.filter(event => source.reaction!.consumes.includes(event.type)), nowMs,
107
+ state: state.value, config: source.reaction!.config ?? {}, availableBehaviors: candidates.filter(c => c.loadable).map(c => c.id) };
108
+ // A control-only epoch is not an observation that clears a visual condition.
109
+ if (!frame && moduleInput.events.length === 0) continue;
110
+ const result = await this.runners.get(source.id)!.evaluate(moduleInput);
111
+ this.validate(result, source);
112
+ state.value = structuredClone(result.state);
113
+ for (const event of result.events ?? []) events.push({ type: event.type,
114
+ dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
115
+ payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
116
+ const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
117
+ for (const [key, binding] of Object.entries(source.reaction!.behaviors ?? {})) {
118
+ const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
119
+ if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) current.warning = undefined;
120
+ if (!matched.has(key)) { current.armed = true; current.failedAttempt = undefined; continue; }
121
+ if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
122
+ if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
123
+ if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
124
+ requests.push({ source, activation: matched.get(key)!, state: current });
125
+ }
126
+ } catch {
127
+ this.failed.add(source.id); await this.runners.get(source.id)?.stop();
128
+ context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
129
+ }
130
+ }
131
+ if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
132
+ this.checkpoint.failures.push(source.id);
133
+ events.push({ type: 'perception.reaction_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
134
+ payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
135
+ }
136
+ }
137
+ requests.sort((a, b) => (b.source.reaction!.behaviors![b.activation.behavior].reflexPriority ?? 0)
138
+ - (a.source.reaction!.behaviors![a.activation.behavior].reflexPriority ?? 0));
139
+ for (const { source, activation, state } of requests) {
140
+ if (context.signal.aborted) break;
141
+ const binding = source.reaction!.behaviors![activation.behavior];
142
+ const behavior = resolveReactionBehavior(binding, this.options.behaviors());
143
+ const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
144
+ if (state.failedAttempt === attempt) continue;
145
+ let result: PerceptionBehaviorActivationResult = { accepted: false, reason: 'behavior_not_loaded' };
146
+ if (behavior) {
147
+ try {
148
+ const response = await context.capabilities.performAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>(
149
+ BEHAVIOR_ACTIVATION_CAPABILITY, { moduleId: source.id, bindingKey: activation.behavior, behavior,
150
+ input: { ...binding.input, ...activation.input }, layer: binding.layer ?? 'reflex',
151
+ reflexPriority: binding.reflexPriority ?? 0,
152
+ maxRuntimeMs: binding.maxRuntimeMs ?? ((binding.layer ?? 'reflex') === 'long' ? undefined : 10_000),
153
+ epochId: input.epoch.epochSeq, gameId: game!.game_id,
154
+ reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` });
155
+ result = response.value ?? { accepted: false, reason: 'activation_unavailable' };
156
+ } catch { result = { accepted: false, reason: 'activation_unavailable' }; }
157
+ }
158
+ if (result.accepted) {
159
+ state.armed = false; state.lastAcceptedAt = nowMs; state.warning = undefined; state.failedAttempt = undefined;
160
+ } else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
161
+ const reason = result.reason ?? 'activation_unavailable';
162
+ state.failedAttempt = attempt;
163
+ if (state.warning !== reason) {
164
+ state.warning = reason; state.warningSequence++;
165
+ events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
166
+ dedupeKey: JSON.stringify([game?.game_id, source.id, activation.behavior, state.warningSequence]),
167
+ payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
168
+ ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
169
+ ...(behavior ? { behavior_id: behavior } : {}), reason,
170
+ text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
171
+ }
172
+ }
173
+ }
174
+ return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
175
+ ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
176
+ }
177
+ private validate(result: ReactionResult, source: ResolvedClawclawPerceptionSource): void {
178
+ if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
179
+ || result.events !== undefined && !Array.isArray(result.events)
180
+ || result.activations !== undefined && !Array.isArray(result.activations)
181
+ || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
182
+ || Buffer.byteLength(JSON.stringify(result)) > 128_000) throw new Error('REACTION_OUTPUT_INVALID');
183
+ for (const event of result.events ?? []) {
184
+ if (!record(event) || !source.reaction!.produces.includes(event.type)
185
+ || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
186
+ || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
187
+ || !record(event.payload) || typeof event.payload.text !== 'string' || !event.payload.text.trim()) throw new Error('REACTION_EVENT_INVALID');
188
+ }
189
+ const bindings = new Set<string>();
190
+ for (const activation of result.activations ?? []) {
191
+ if (!record(activation) || !Object.hasOwn(source.reaction!.behaviors ?? {}, activation.behavior)
192
+ || bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
193
+ || activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
194
+ || Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key))) throw new Error('REACTION_ACTIVATION_INVALID');
195
+ bindings.add(activation.behavior);
196
+ }
197
+ }
198
+ }
@@ -0,0 +1,49 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { pathToFileURL } from 'node:url';
3
+ import type { ReactionInput, ReactionResult } from '../../../../sdk/perception-plugin/reaction.js';
4
+ import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
5
+ import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
6
+
7
+ /** Generic reaction execution; no model service, exclusive event routing or delivery rewriting. */
8
+ export class ReactionRunner {
9
+ private worker?: Worker;
10
+ private sequence = 0;
11
+ private failure?: Error;
12
+ private pending?: { id?: number; resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> };
13
+ constructor(readonly source: ResolvedClawclawPerceptionSource) {}
14
+ async start(): Promise<void> {
15
+ const ready = this.wait(8_000);
16
+ this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
17
+ 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,
20
+ ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
21
+ });
22
+ this.worker.stdout?.on('data', () => {}); this.worker.stderr?.on('data', () => {});
23
+ this.worker.on('error', error => this.fail(error));
24
+ this.worker.on('exit', () => this.fail(new Error('REACTION_WORKER_EXITED')));
25
+ this.worker.on('message', message => {
26
+ 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; }
28
+ const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.resolve(message.result);
29
+ });
30
+ await ready;
31
+ }
32
+ async evaluate(input: ReactionInput): Promise<ReactionResult> {
33
+ if (this.failure) throw this.failure;
34
+ if (!this.worker) throw new Error('REACTION_WORKER_NOT_STARTED');
35
+ const id = ++this.sequence; const result = this.wait(500, id);
36
+ this.worker.postMessage({ id, input }); return result;
37
+ }
38
+ async stop(): Promise<void> { this.fail(new Error('REACTION_STOPPED')); await this.worker?.terminate(); this.worker = undefined; }
39
+ private wait(ms: number, id?: number): Promise<any> {
40
+ if (this.pending) throw new Error('REACTION_CONCURRENT_CALL');
41
+ return new Promise((resolve, reject) => {
42
+ this.pending = { id, resolve, reject, timer: setTimeout(() => { this.fail(new Error('REACTION_TIMEOUT')); void this.stop(); }, ms) };
43
+ });
44
+ }
45
+ private fail(error: Error): void {
46
+ this.failure = error;
47
+ if (this.pending) { const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.reject(error); }
48
+ }
49
+ }
@@ -0,0 +1,26 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { ClawclawReaction, type ReactionInput } from '../../../../sdk/perception-plugin/reaction.js';
4
+ import { normalizeReactionManifest } from '../../reaction-manifest.js';
5
+
6
+ function freeze<T>(value: T): T {
7
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
8
+ for (const child of Object.values(value)) freeze(child); Object.freeze(value);
9
+ }
10
+ return value;
11
+ }
12
+ try {
13
+ const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
14
+ if (!(Module?.prototype instanceof ClawclawReaction)) throw new Error('REACTION_CLASS_INVALID');
15
+ const manifest = normalizeReactionManifest(Module.manifest);
16
+ if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('REACTION_MANIFEST_CHANGED');
17
+ parentPort!.postMessage({ type: 'ready' });
18
+ parentPort!.on('message', async ({ id, input }: { id: number; input: ReactionInput }) => {
19
+ try {
20
+ const result = await new Module().evaluate(freeze({ ...input, config: manifest.config ?? {},
21
+ events: input.events.filter(e => manifest.consumes.includes(e.type)) }));
22
+ if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('REACTION_OUTPUT_TOO_LARGE');
23
+ parentPort!.postMessage({ type: 'result', id, result });
24
+ } catch { parentPort!.postMessage({ type: 'error', id }); }
25
+ });
26
+ } catch { parentPort!.postMessage({ type: 'error' }); }