@myclaw163/clawclaw-cli 0.8.37 → 0.8.39

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 (42) hide show
  1. package/docs/custom-modules/README.md +6 -4
  2. package/docs/custom-modules/api-reference.md +10 -0
  3. package/docs/custom-modules/examples/nearby-escape.ts +49 -0
  4. package/docs/custom-modules/perception.md +114 -5
  5. package/docs/custom-modules/trigger.md +2 -0
  6. package/docs/runtime/components-and-boundaries.md +2 -2
  7. package/package.json +1 -1
  8. package/skills/clawclaw/SKILL.md +17 -11
  9. package/skills/clawclaw/references/BEHAVIORS.md +6 -2
  10. package/skills/clawclaw/references/COMMANDS.md +5 -2
  11. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +13 -0
  12. package/skills/clawclaw/references/CUSTOM-MODULES.md +3 -1
  13. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +114 -5
  14. package/src/commands/game/index.ts +10 -9
  15. package/src/commands/load.ts +25 -1
  16. package/src/commands/perception.ts +1 -0
  17. package/src/lib/agent-workspace-runtime.ts +11 -5
  18. package/src/lib/capability-load-diagnostics.ts +1 -1
  19. package/src/lib/capability-operation-name.ts +1 -0
  20. package/src/lib/training-role.ts +24 -0
  21. package/src/pipeline/event-format.ts +2 -0
  22. package/src/runtime/clawclaw/behavior-activation-capability.ts +21 -0
  23. package/src/runtime/clawclaw/owner.ts +14 -8
  24. package/src/runtime/clawclaw/plugins/assembly.ts +20 -3
  25. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +4 -0
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +72 -9
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -0
  29. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  30. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +14 -1
  31. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +198 -0
  32. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +49 -0
  33. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +26 -0
  34. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +3 -1
  35. package/src/runtime/clawclaw/plugins/source/types.ts +2 -1
  36. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +23 -0
  37. package/src/runtime/clawclaw/reaction-manifest.ts +50 -0
  38. package/src/runtime/clawclaw/runtime.ts +3 -0
  39. package/src/runtime/clawclaw-event-catalog.ts +5 -1
  40. package/src/runtime/clawclaw-room-state.ts +3 -0
  41. package/src/sdk/perception-plugin/index.ts +1 -0
  42. package/src/sdk/perception-plugin/reaction.ts +78 -0
@@ -2,6 +2,8 @@ import { Command, InvalidArgumentError, Option } from 'commander';
2
2
  import { AuthStore, type AuthProfile } from '../../lib/auth.js';
3
3
  import { ApiError, GameClient } from '../../lib/game-client.js';
4
4
  import { noAccountMessage } from '../../lib/account-guidance.js';
5
+ import { CLAWCLAW_ROLE_IDS, type ClawclawRoleId } from '../../lib/gameplay-config.js';
6
+ import { isTrainingRole } from '../../lib/training-role.js';
5
7
  import { summarizeLocalClawclawMap } from '../../lib/game-context.js';
6
8
  import {
7
9
  businessFailureFromResult,
@@ -91,12 +93,11 @@ function trainingRoomType(value: string): TrainingRoomType {
91
93
  throw new InvalidArgumentError('Training mode must be simulation or dummy.');
92
94
  }
93
95
 
94
- function positiveCharacterId(value: string): number {
95
- const parsed = Number(value);
96
- if (!Number.isInteger(parsed) || parsed <= 0) {
97
- throw new InvalidArgumentError('character_id must be a positive integer.');
96
+ function trainingRole(value: string): ClawclawRoleId {
97
+ if (!isTrainingRole(value)) {
98
+ throw new InvalidArgumentError(`role must be one of: ${CLAWCLAW_ROLE_IDS.join(', ')}.`);
98
99
  }
99
- return parsed;
100
+ return value;
100
101
  }
101
102
 
102
103
  function addDesktopEventOptions(command: Command): Command {
@@ -843,11 +844,11 @@ export function createGameCommand(dependencies: GameCommandDependencies = {}): C
843
844
 
844
845
  training
845
846
  .command('role-lock')
846
- .description('Lock the player character for future training rounds.')
847
- .argument('<character_id>', 'backend character id', positiveCharacterId)
848
- .action((characterId: number) => runTrainingControl(
847
+ .description('Lock the player role for future training rounds.')
848
+ .argument('<role>', `English role: ${CLAWCLAW_ROLE_IDS.join(', ')}`, trainingRole)
849
+ .action((role: ClawclawRoleId) => runTrainingControl(
849
850
  'training_role_lock',
850
- { character_id: characterId },
851
+ { role },
851
852
  dependencies,
852
853
  ));
853
854
 
@@ -29,6 +29,7 @@ import {
29
29
  import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js';
30
30
  import { TRIGGER_PLUGIN_API_VERSION } from '../sdk/trigger-plugin/index.js';
31
31
  import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
32
+ import { resolveReactionBehavior } from '../runtime/clawclaw/reaction-behavior-resolution.js';
32
33
  import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-version.js';
33
34
  import {
34
35
  readLocalAgentWorkspaceSnapshot,
@@ -421,6 +422,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
421
422
  const enabledBehaviors = mergeAgentWorkspaceBehaviorSources(
422
423
  localBehaviors,
423
424
  hubBehaviors,
425
+ disabledBehaviors,
424
426
  );
425
427
  const behaviorEntry = (source: typeof enabledBehaviors[number]) => {
426
428
  const compatibilityError = behaviorSourceCompatibilityError(source);
@@ -596,6 +598,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
596
598
  const enabledPerceptions = mergeAgentWorkspacePerceptionSources(
597
599
  localPerceptions,
598
600
  hubPerceptions,
601
+ disabledPerceptions,
599
602
  );
600
603
  const reminderTopics = new Map<string, string[]>();
601
604
  for (const source of enabledPerceptions) {
@@ -619,6 +622,24 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
619
622
  const perceptions = enabledPerceptions
620
623
  .filter(({ apiVersion, id }) => apiVersion === PERCEPTION_PLUGIN_API_VERSION && !conflictingPerceptions.has(id))
621
624
  .map(perceptionEntry);
625
+ const behaviorDependencies = new Map<string, Array<Record<string, unknown>>>();
626
+ const availableBehaviorIdsForReactions = new Set(behaviors.map(entry => entry.id));
627
+ const reactionCandidates = enabledBehaviors.map(source => ({ id: source.id, declaredId: source.declaredId,
628
+ resourceId: source.resourceId, loadable: availableBehaviorIdsForReactions.has(source.id) }));
629
+ for (const source of enabledPerceptions.filter(source => source.reaction && source.apiVersion === PERCEPTION_PLUGIN_API_VERSION)) {
630
+ const bindings = Object.entries(source.reaction!.behaviors ?? {}).map(([key, binding]) => {
631
+ const resolved = resolveReactionBehavior(binding, reactionCandidates);
632
+ if (!resolved) configurationWarnings.push({ code: 'PERCEPTION_BEHAVIOR_UNAVAILABLE',
633
+ perception_id: source.id, binding: key, behavior_name: binding.name,
634
+ ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
635
+ reason: 'no_loaded_matching_behavior',
636
+ message: `Perception ${source.id} cannot activate ${binding.name}: no matching Behavior is loaded. Only this reaction is unavailable; other perception output and CCL continue. Equip a matching Behavior and run ccl load again; changes take effect in the next Runtime.` });
637
+ return { binding: key, name: binding.name, layer: binding.layer ?? 'reflex', available: !!resolved,
638
+ ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
639
+ ...(resolved ? { behavior_id: resolved } : {}) };
640
+ });
641
+ behaviorDependencies.set(source.id, bindings);
642
+ }
622
643
  const incompatiblePerceptions = enabledPerceptions
623
644
  .filter(({ apiVersion }) => apiVersion !== PERCEPTION_PLUGIN_API_VERSION)
624
645
  .map(perceptionEntry);
@@ -647,7 +668,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
647
668
  const disabledTriggers = new Set(gameplay.disabled_triggers);
648
669
  const localTriggerDir = getUserDataAccountTriggersDir(workspaceDir, profile);
649
670
  const triggerSources = listClawclawTriggerSources(localTriggerDir);
650
- const enabledTriggers = triggerSources.filter((source) => !disabledTriggers.has(source.id));
671
+ const enabledTriggers = triggerSources.filter((source) => !disabledTriggers.has(source.id)
672
+ && !enabledPerceptions.some(perception => perception.reaction && perception.apiVersion === PERCEPTION_PLUGIN_API_VERSION
673
+ && (perception.declaredId ?? perception.id) === source.id));
651
674
  const triggerSourcePaths = new Set(triggerSources.map(({ sourcePath }) => resolve(sourcePath)));
652
675
  let expectedLocalTriggers = enabledTriggers.length;
653
676
  for (const path of listCapabilityModuleCandidates(localTriggerDir)) {
@@ -943,6 +966,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
943
966
  name: localized.name,
944
967
  description: source.description,
945
968
  source: entry.source,
969
+ ...(source.reaction ? { kind: 'reaction', behavior_dependencies: behaviorDependencies.get(source.id) ?? [] } : {}),
946
970
  };
947
971
  }),
948
972
  triggers: triggers.map((entry) => {
@@ -112,6 +112,7 @@ Perception modules:
112
112
  runtime_source_path: source.sourcePath,
113
113
  name: source.name,
114
114
  description: source.description,
115
+ ...(source.reaction ? { kind: 'reaction', behaviors: source.reaction.behaviors } : {}),
115
116
  source: hubIds.has(source.id) ? 'hub' : 'local',
116
117
  ...pluginApiVersionStatus(
117
118
  'perception',
@@ -91,6 +91,7 @@ export function listAgentWorkspaceBehaviorSources(
91
91
  && item.resolution !== 'local_origin_unrecognized';
92
92
  const managed = {
93
93
  ...source,
94
+ resourceId: item.resourceId,
94
95
  ...(trusted ? { trustedSourceSha256: item.sourceFiles[0]!.sha256 } : {}),
95
96
  management: {
96
97
  source: 'hub',
@@ -168,14 +169,17 @@ export function listAgentWorkspacePerceptionSources(
168
169
  export function mergeAgentWorkspaceBehaviorSources(
169
170
  base: readonly ResolvedClawclawBehaviorSource[],
170
171
  cloud: readonly ResolvedClawclawBehaviorSource[],
172
+ disabled?: ReadonlySet<string>,
171
173
  ): readonly ManagedClawclawBehaviorSource[] {
172
- assertUniqueBehaviorIds(base, 'local');
173
- assertUniqueBehaviorIds(cloud, 'hub');
174
- const merged = new Map<string, ManagedClawclawBehaviorSource>(base.map((source) => [source.id, {
174
+ const activeBase = base.filter(source => !disabled?.has(source.id));
175
+ const activeCloud = cloud.filter(source => !disabled?.has(source.id));
176
+ assertUniqueBehaviorIds(activeBase, 'local');
177
+ assertUniqueBehaviorIds(activeCloud, 'hub');
178
+ const merged = new Map<string, ManagedClawclawBehaviorSource>(activeBase.map((source) => [source.id, {
175
179
  ...source,
176
180
  management: { source: 'local', managedBy: 'local_config' },
177
181
  } satisfies ManagedClawclawBehaviorSource]));
178
- for (const source of cloud) {
182
+ for (const source of activeCloud) {
179
183
  if (merged.has(source.id)) continue;
180
184
  merged.set(source.id, {
181
185
  ...source,
@@ -190,9 +194,11 @@ export function mergeAgentWorkspaceBehaviorSources(
190
194
  export function mergeAgentWorkspacePerceptionSources(
191
195
  base: readonly ResolvedClawclawPerceptionSource[],
192
196
  cloud: readonly ResolvedClawclawPerceptionSource[],
197
+ disabled?: ReadonlySet<string>,
193
198
  ): readonly ResolvedClawclawPerceptionSource[] {
194
- const merged = new Map(base.map((source) => [source.id, source]));
199
+ const merged = new Map(base.filter(source => !disabled?.has(source.id)).map((source) => [source.id, source]));
195
200
  for (const source of cloud) {
201
+ if (disabled?.has(source.id)) continue;
196
202
  if (merged.has(source.id)) {
197
203
  throw new Error(`AGENT_RESOURCE_ID_CONFLICT:perception:${source.id}`);
198
204
  }
@@ -72,7 +72,7 @@ const MODULE_CONTRACTS: Record<ModuleCapabilityType, {
72
72
  perception: {
73
73
  expectedImport: '@myclaw163/clawclaw-cli/perception-plugin',
74
74
  safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/,
75
- defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(?:ClawclawPerception|ClawclawParallelPerception|ClawclawReminder)/,
75
+ defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(?:ClawclawPerception|ClawclawParallelPerception|ClawclawReminder|ClawclawReaction)/,
76
76
  manifest: /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/,
77
77
  },
78
78
  trigger: {
@@ -4,6 +4,7 @@ import type { ResolvedClawclawPerceptionSource } from '../runtime/clawclaw/plugi
4
4
 
5
5
  export function behaviorOperationName<T extends ResolvedClawclawBehaviorSource>(source: T, entry: CapabilityWorkspaceEntry): T {
6
6
  return { ...source, id: entry.runtimeId, declaredId: source.declaredId ?? source.id,
7
+ ...(entry.hub ? { resourceId: entry.hub.resourceId } : {}),
7
8
  display: { name: entry.title, description: entry.description },
8
9
  workingCopyPath: source.workingCopyPath ?? source.sourcePath };
9
10
  }
@@ -0,0 +1,24 @@
1
+ import { CLAWCLAW_ROLE_IDS, type ClawclawRoleId } from './gameplay-config.js';
2
+
3
+ // Backend GameDefinition IDs from config/generated/character/characters/data.json.
4
+ // Keep this protocol mapping inside CCL; Agent commands use the semantic role.
5
+ const TRAINING_CHARACTER_IDS: Readonly<Record<ClawclawRoleId, number>> = {
6
+ shrimp_generic: 1001,
7
+ crab_generic: 1002,
8
+ shrimp_warrior: 1003,
9
+ shrimp_pistol: 1004,
10
+ neutral_paradise_fish: 1005,
11
+ neutral_octopus: 1006,
12
+ };
13
+
14
+ export function isTrainingRole(value: unknown): value is ClawclawRoleId {
15
+ return typeof value === 'string' && Object.hasOwn(TRAINING_CHARACTER_IDS, value);
16
+ }
17
+
18
+ export function trainingCharacterId(role: ClawclawRoleId): number {
19
+ return TRAINING_CHARACTER_IDS[role];
20
+ }
21
+
22
+ export function trainingRoleForCharacterId(value: unknown): ClawclawRoleId | undefined {
23
+ return CLAWCLAW_ROLE_IDS.find(role => TRAINING_CHARACTER_IDS[role] === value);
24
+ }
@@ -919,6 +919,7 @@ export function compactStateForChannel(
919
919
  ready_to_start: room.ready_to_start,
920
920
  role_config: room.role_config,
921
921
  role_lock_character_id: room.role_lock_character_id,
922
+ role_lock: room.role_lock,
922
923
  members: room.members,
923
924
  game_id: room.game_id,
924
925
  game_server_name: room.game_server_name,
@@ -1024,6 +1025,7 @@ export function compactStateForEvents(
1024
1025
  ready_to_start: room.ready_to_start,
1025
1026
  role_config: room.role_config,
1026
1027
  role_lock_character_id: room.role_lock_character_id,
1028
+ role_lock: room.role_lock,
1027
1029
  members: room.members,
1028
1030
  game_id: room.game_id,
1029
1031
  game_server_name: room.game_server_name,
@@ -0,0 +1,21 @@
1
+ import type { ReactionBehaviorBinding } from '../../sdk/perception-plugin/reaction.js';
2
+
3
+ /** Generic module activation port. It is independent of model decision providers. */
4
+ export const BEHAVIOR_ACTIVATION_CAPABILITY = 'clawclaw.behavior.activate';
5
+ export interface PerceptionBehaviorActivation {
6
+ readonly moduleId: string;
7
+ readonly bindingKey: string;
8
+ readonly behavior: string;
9
+ readonly input: Readonly<Record<string, unknown>>;
10
+ readonly layer: NonNullable<ReactionBehaviorBinding['layer']>;
11
+ readonly reflexPriority: number;
12
+ readonly maxRuntimeMs?: number;
13
+ readonly reason: string;
14
+ readonly epochId: number;
15
+ readonly gameId: string;
16
+ }
17
+ export interface PerceptionBehaviorActivationResult {
18
+ readonly accepted: boolean;
19
+ readonly reason?: string;
20
+ readonly activationId?: string;
21
+ }
@@ -14,6 +14,7 @@ import { getHeapStatistics } from 'node:v8';
14
14
  import { RuntimeProcessTimingSampler } from '../observability/process-timing.js';
15
15
  import type { AuthProfile } from '../../lib/auth.js';
16
16
  import { GameClient } from '../../lib/game-client.js';
17
+ import { isTrainingRole } from '../../lib/training-role.js';
17
18
  import { getProfileRuntimeStateDir, getWorkspaceDir } from '../../lib/init-command.js';
18
19
  import { readWorkspacePerceptionConfig } from '../../lib/perception-config.js';
19
20
  import {
@@ -582,6 +583,7 @@ export async function runClawclawOwner(
582
583
  ))
583
584
  .map(({ source }) => source),
584
585
  agentBehaviorSources,
586
+ disabledBehaviors,
585
587
  );
586
588
  const behaviorSourceById = new Map(behaviorSources.map((source) => [source.id, source]));
587
589
  const behaviorCatalog = new ClawclawBehaviorCatalog(behaviorSources);
@@ -617,6 +619,7 @@ export async function runClawclawOwner(
617
619
  const perceptionSources = mergeAgentWorkspacePerceptionSources(
618
620
  localPerceptionSources,
619
621
  agentPerceptionSources,
622
+ disabledPerceptions,
620
623
  );
621
624
  const perceptionModules = [
622
625
  ...localPerceptionSources.map(({ id }) => id),
@@ -654,6 +657,7 @@ export async function runClawclawOwner(
654
657
  visualEventDelivery: perceptionConfig.events.delivery,
655
658
  visualEventTypes: assembly.perception.produces.events,
656
659
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
660
+ reactionEventTypes: assembly.reactions?.produces.events,
657
661
  });
658
662
  if (fullDiagnosticsEnabled) {
659
663
  processTimingSampler = new RuntimeProcessTimingSampler();
@@ -782,7 +786,8 @@ export async function runClawclawOwner(
782
786
  : null;
783
787
  })(),
784
788
  perceptions: [...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
785
- ...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE)],
789
+ ...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
790
+ ...(assembly.reactions?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? [])],
786
791
  }),
787
792
  eventDescriptors: () => assembly.perception
788
793
  .localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE)
@@ -1193,14 +1198,15 @@ export async function runClawclawOwner(
1193
1198
  return { ok: false, type: 'behavior_fallback', error: 'stale_runtime_scope' };
1194
1199
  }
1195
1200
  const latest = readGameplayConfig(workspaceDir, options.profile);
1196
- if (readyRoleForScope(runtime!, expected) === role) {
1201
+ const currentRole = readyRoleForScope(runtime!, expected);
1202
+ if (currentRole === role) {
1197
1203
  await assembly.behavior.noteAgentActivity();
1198
1204
  }
1199
1205
  await assembly.behavior.configureFallbackBehaviors(roleFallbackBehaviors(
1200
1206
  latest,
1201
1207
  behaviorCatalog,
1202
1208
  configurationWarning,
1203
- ));
1209
+ ), currentRole);
1204
1210
  return {
1205
1211
  ok: true,
1206
1212
  type: 'behavior_fallback',
@@ -1267,18 +1273,18 @@ export async function runClawclawOwner(
1267
1273
  return { ok: true, type: request.type, result };
1268
1274
  }
1269
1275
  if (request.type === 'training_role_lock') {
1270
- if (!Number.isInteger(request.character_id) || request.character_id <= 0) {
1271
- return { ok: false, type: request.type, error: 'invalid_character_id' };
1276
+ if (!isTrainingRole(request.role)) {
1277
+ return { ok: false, type: request.type, error: 'invalid_training_role', roles: [...CLAWCLAW_ROLE_IDS] };
1272
1278
  }
1273
1279
  const result = await ownerSource.submitIntent({
1274
1280
  kind: 'training_role_lock',
1275
- characterId: request.character_id,
1281
+ role: request.role,
1276
1282
  });
1277
- return { ok: true, type: request.type, result };
1283
+ return { ok: true, type: request.type, role: request.role, result };
1278
1284
  }
1279
1285
  if (request.type === 'training_role_clear') {
1280
1286
  const result = await ownerSource.submitIntent({ kind: 'training_role_clear' });
1281
- return { ok: true, type: request.type, result };
1287
+ return { ok: true, type: request.type, role: null, result };
1282
1288
  }
1283
1289
  return { ok: false, error: 'owner_request_not_supported' };
1284
1290
  });
@@ -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)),