@myclaw163/clawclaw-cli 0.9.0 → 0.9.1

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 (39) hide show
  1. package/README.md +5 -3
  2. package/docs/custom-modules/README.md +12 -16
  3. package/docs/custom-modules/api-reference.md +18 -3
  4. package/docs/custom-modules/examples/first-sighting-v3.ts +29 -0
  5. package/docs/custom-modules/perception.md +139 -58
  6. package/docs/custom-modules/trigger.md +2 -0
  7. package/docs/runtime/README.md +17 -8
  8. package/docs/runtime/agent-notifications.md +32 -15
  9. package/docs/runtime/behavior-runtime.md +28 -21
  10. package/docs/runtime/components-and-boundaries.md +57 -17
  11. package/docs/runtime/events-and-state.md +42 -2
  12. package/docs/runtime/owner-lifecycle-and-observability.md +5 -3
  13. package/docs/user-guide/api-reference.md +15 -0
  14. package/docs/user-guide/perception.md +138 -57
  15. package/package.json +1 -1
  16. package/skills/clawclaw/SKILL.md +3 -3
  17. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  18. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +18 -3
  19. package/skills/clawclaw/references/CUSTOM-MODULES.md +12 -16
  20. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +139 -58
  21. package/src/commands/load.ts +13 -11
  22. package/src/commands/perception.ts +2 -2
  23. package/src/commands/trigger.ts +1 -1
  24. package/src/lib/agent-workspace-sync.ts +2 -2
  25. package/src/runtime/clawclaw/owner.ts +3 -2
  26. package/src/runtime/clawclaw/perception-module-manifest.ts +27 -0
  27. package/src/runtime/clawclaw/plugins/assembly.ts +17 -5
  28. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +28 -0
  29. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  30. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +21 -0
  31. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +47 -12
  32. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +2 -2
  33. package/src/runtime/clawclaw-event-catalog.ts +5 -2
  34. package/src/sdk/index.ts +2 -0
  35. package/src/sdk/perception-plugin/index.ts +25 -8
  36. package/src/sdk/perception-plugin/module.ts +46 -0
  37. package/src/sdk/perception-plugin/reaction.ts +1 -0
  38. package/src/sdk/perception-plugin/reminder.ts +1 -0
  39. package/src/sdk/trigger-plugin/index.ts +1 -0
@@ -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 { expectedPerceptionApiVersion, isSupportedPerceptionSource } from '../runtime/clawclaw/plugins/perception/perception-source.js';
32
33
  import { resolveReactionBehavior } from '../runtime/clawclaw/reaction-behavior-resolution.js';
33
34
  import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-version.js';
34
35
  import {
@@ -617,17 +618,17 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
617
618
  name: source.name,
618
619
  description: source.description,
619
620
  source: hubPerceptionIds.has(source.id) ? 'hub' : 'workspace',
620
- ...pluginApiVersionStatus('perception', PERCEPTION_PLUGIN_API_VERSION, source.apiVersion),
621
+ ...pluginApiVersionStatus('perception', expectedPerceptionApiVersion(source), source.apiVersion),
621
622
  });
622
623
  const perceptions = enabledPerceptions
623
- .filter(({ apiVersion, id }) => apiVersion === PERCEPTION_PLUGIN_API_VERSION && !conflictingPerceptions.has(id))
624
+ .filter(source => isSupportedPerceptionSource(source) && !conflictingPerceptions.has(source.id))
624
625
  .map(perceptionEntry);
625
626
  const behaviorDependencies = new Map<string, Array<Record<string, unknown>>>();
626
627
  const availableBehaviorIdsForReactions = new Set(behaviors.map(entry => entry.id));
627
628
  const reactionCandidates = enabledBehaviors.map(source => ({ id: source.id, declaredId: source.declaredId,
628
629
  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]) => {
630
+ for (const source of enabledPerceptions.filter(source => (source.reaction || source.module) && isSupportedPerceptionSource(source))) {
631
+ const bindings = Object.entries((source.module ?? source.reaction)!.behaviors ?? {}).map(([key, binding]) => {
631
632
  const resolved = resolveReactionBehavior(binding, reactionCandidates);
632
633
  if (!resolved) configurationWarnings.push({ code: 'PERCEPTION_BEHAVIOR_UNAVAILABLE',
633
634
  perception_id: source.id, binding: key, behavior_name: binding.name,
@@ -641,35 +642,35 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
641
642
  behaviorDependencies.set(source.id, bindings);
642
643
  }
643
644
  const incompatiblePerceptions = enabledPerceptions
644
- .filter(({ apiVersion }) => apiVersion !== PERCEPTION_PLUGIN_API_VERSION)
645
+ .filter(source => !isSupportedPerceptionSource(source))
645
646
  .map(perceptionEntry);
646
647
  for (const source of enabledPerceptions) {
647
- if (source.apiVersion === PERCEPTION_PLUGIN_API_VERSION) continue;
648
+ if (isSupportedPerceptionSource(source)) continue;
648
649
  capabilityWarnings.push(compatibilityWarning(
649
650
  'perception',
650
651
  hubPerceptionIds.has(source.id) ? 'hub' : 'local',
651
652
  source,
652
- `perception_api_version_unsupported:expected=${PERCEPTION_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`,
653
+ `perception_api_version_unsupported:expected=${expectedPerceptionApiVersion(source)}:received=${source.apiVersion ?? 'missing'}`,
653
654
  ));
654
655
  }
655
656
  const selectedLocalPerceptionPaths = new Set(localPerceptions.map(({ sourcePath }) => resolve(sourcePath)));
656
657
  for (const source of allLocalPerceptions) {
657
658
  if (
658
659
  selectedLocalPerceptionPaths.has(resolve(source.sourcePath))
659
- || source.apiVersion === PERCEPTION_PLUGIN_API_VERSION
660
+ || isSupportedPerceptionSource(source)
660
661
  ) continue;
661
662
  capabilityWarnings.push(compatibilityWarning(
662
663
  'perception',
663
664
  'local',
664
665
  source,
665
- `perception_api_version_unsupported:expected=${PERCEPTION_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`,
666
+ `perception_api_version_unsupported:expected=${expectedPerceptionApiVersion(source)}:received=${source.apiVersion ?? 'missing'}`,
666
667
  ));
667
668
  }
668
669
  const disabledTriggers = new Set(gameplay.disabled_triggers);
669
670
  const localTriggerDir = getUserDataAccountTriggersDir(workspaceDir, profile);
670
671
  const triggerSources = listClawclawTriggerSources(localTriggerDir);
671
672
  const enabledTriggers = triggerSources.filter((source) => !disabledTriggers.has(source.id)
672
- && !enabledPerceptions.some(perception => perception.reaction && perception.apiVersion === PERCEPTION_PLUGIN_API_VERSION
673
+ && !enabledPerceptions.some(perception => (perception.reaction || perception.module) && isSupportedPerceptionSource(perception)
673
674
  && (perception.declaredId ?? perception.id) === source.id));
674
675
  const triggerSourcePaths = new Set(triggerSources.map(({ sourcePath }) => resolve(sourcePath)));
675
676
  let expectedLocalTriggers = enabledTriggers.length;
@@ -966,7 +967,8 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
966
967
  name: localized.name,
967
968
  description: source.description,
968
969
  source: entry.source,
969
- ...(source.reaction ? { kind: 'reaction', behavior_dependencies: behaviorDependencies.get(source.id) ?? [] } : {}),
970
+ ...(source.reaction ? { kind: 'reaction' } : {}),
971
+ ...(source.reaction || source.module ? { behavior_dependencies: behaviorDependencies.get(source.id) ?? [] } : {}),
970
972
  };
971
973
  }),
972
974
  triggers: triggers.map((entry) => {
@@ -16,7 +16,7 @@ import {
16
16
  listAgentWorkspacePerceptionSources,
17
17
  mergeAgentWorkspacePerceptionSources,
18
18
  } from '../lib/agent-workspace-runtime.js';
19
- import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
19
+ import { expectedPerceptionApiVersion } from '../runtime/clawclaw/plugins/perception/perception-source.js';
20
20
  import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-version.js';
21
21
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
22
22
  import { capabilityEntryForPath, readCapabilityWorkspaceRegistry } from '../lib/capability-workspace.js';
@@ -116,7 +116,7 @@ Perception modules:
116
116
  source: hubIds.has(source.id) ? 'hub' : 'local',
117
117
  ...pluginApiVersionStatus(
118
118
  'perception',
119
- PERCEPTION_PLUGIN_API_VERSION,
119
+ expectedPerceptionApiVersion(source),
120
120
  source.apiVersion,
121
121
  ),
122
122
  disabled: hubIds.has(source.id)
@@ -223,7 +223,7 @@ async function updateTrigger(
223
223
  export function createTriggerCommand(dependencies: TriggerCommandDependencies = {}): Command {
224
224
  const trigger = new Command('trigger')
225
225
  .alias('trg')
226
- .description('Discover and configure rule-based Reflex triggers')
226
+ .description('Compatibility: configure existing Reflex triggers; may be unsupported in a future release. Use Perception API v3 for new rules.')
227
227
  .addHelpText('after', () => {
228
228
  const workspaceDir = getWorkspaceDir();
229
229
  const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
@@ -41,7 +41,7 @@ import {
41
41
  import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
42
42
  import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js';
43
43
  import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js';
44
- import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
44
+ import { isSupportedPerceptionSource } from '../runtime/clawclaw/plugins/perception/perception-source.js';
45
45
  import { updateGameplayConfig } from './gameplay-config.js';
46
46
 
47
47
  const RESOURCE_TYPES: readonly ResourceType[] = ['skill', 'strategy', 'persona', 'perception'];
@@ -1000,7 +1000,7 @@ export async function syncAgentWorkspaceConfig(
1000
1000
  }
1001
1001
  } else if (type === 'perception') {
1002
1002
  const source = listClawclawPerceptionSourcesInDirectory(dirname(path)).find(source => source.sourcePath === path);
1003
- if (!source || source.apiVersion !== PERCEPTION_PLUGIN_API_VERSION) {
1003
+ if (!source || !isSupportedPerceptionSource(source)) {
1004
1004
  throw new Error(`agent_workspace_resource_failed:perception:${item.resource_id}:cloud_module_invalid`);
1005
1005
  }
1006
1006
  }
@@ -657,7 +657,7 @@ export async function runClawclawOwner(
657
657
  visualEventDelivery: perceptionConfig.events.delivery,
658
658
  visualEventTypes: assembly.perception.produces.events,
659
659
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
660
- reactionEventTypes: assembly.reactions?.produces.events,
660
+ reactionEventTypes: [...(assembly.reactions?.produces.events ?? []), ...(assembly.modules?.produces.events ?? [])],
661
661
  });
662
662
  if (fullDiagnosticsEnabled) {
663
663
  processTimingSampler = new RuntimeProcessTimingSampler();
@@ -787,7 +787,8 @@ export async function runClawclawOwner(
787
787
  })(),
788
788
  perceptions: [...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
789
789
  ...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
790
- ...(assembly.reactions?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? [])],
790
+ ...(assembly.reactions?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? []),
791
+ ...(assembly.modules?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? [])],
791
792
  }),
792
793
  eventDescriptors: () => assembly.perception
793
794
  .localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE)
@@ -0,0 +1,27 @@
1
+ import type { PerceptionModuleManifest } from '../../sdk/perception-plugin/module.js';
2
+ import { normalizeReactionManifest } from './reaction-manifest.js';
3
+ import { isClawclawFixedEventType, CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES,
4
+ CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES, CLAWCLAW_VISUAL_EVENT_TYPES } from '../clawclaw-event-catalog.js';
5
+
6
+ const INPUT_TYPES = new Set<string>([...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, ...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES,
7
+ ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter(type => !/^(behavior|reminder|perception)\./.test(type)),
8
+ 'tasks_changed', 'meeting_state']);
9
+ const PERCEPTION_OWNED_TYPES = new Set<string>([...CLAWCLAW_VISUAL_EVENT_TYPES, 'reminder.task', 'reminder.speech']);
10
+
11
+ const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
12
+ export function normalizePerceptionModuleManifest(value: unknown, current = true): PerceptionModuleManifest {
13
+ if (!record(value) || !Number.isInteger(value.apiVersion) || current && value.apiVersion !== 3
14
+ || Object.keys(value).some(key => !['apiVersion', 'id', 'name', 'description', 'localizations', 'consumes',
15
+ 'produces', 'behaviors', 'inputs', 'config'].includes(key))) throw new Error('perception_module_manifest_invalid');
16
+ const consumes = value.consumes ?? [], produces = value.produces ?? [];
17
+ if (!Array.isArray(produces) || produces.some(type => typeof type !== 'string'
18
+ || !/^[a-z0-9][a-z0-9._-]*$/.test(type)
19
+ || isClawclawFixedEventType(type) && !PERCEPTION_OWNED_TYPES.has(type))
20
+ || !Array.isArray(consumes) || consumes.some(type => typeof type !== 'string' || !INPUT_TYPES.has(type)
21
+ || /^(visual|reminder|reaction|perception|behavior|decision)\./.test(type))) throw new Error('perception_module_event_contract_invalid');
22
+ // Reuse parameter, metadata and fixed Behavior dependency validation, not another plugin's computation.
23
+ const normalized = normalizeReactionManifest({ ...value, apiVersion: 2, kind: 'reaction', consumes,
24
+ produces: [], behaviors: value.behaviors ?? {} });
25
+ const { kind: _kind, ...fields } = normalized;
26
+ return { ...fields, apiVersion: value.apiVersion, produces: [...new Set(produces)] };
27
+ }
@@ -2,7 +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
+ import { ClawclawReactionPlugin, CLAWCLAW_REACTION_PLUGIN_ID, CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID } from './perception/reaction-plugin.js';
6
6
  import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
7
7
  import {
8
8
  CLAWCLAW_ACTION_PLUGIN_ID,
@@ -50,6 +50,7 @@ export interface ClawclawPluginAssemblyOptions {
50
50
  }
51
51
 
52
52
  export interface ClawclawPluginAssembly {
53
+ modules?: ClawclawReactionPlugin;
53
54
  reactions?: ClawclawReactionPlugin;
54
55
  plugins: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
55
56
  action: ClawclawActionPlugin;
@@ -96,6 +97,10 @@ export function assembleClawclawPlugins(
96
97
  const selected = new Set(options.perception?.modules ?? DEFAULT_PERCEPTION_MODULES);
97
98
  const reactionSources = (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
98
99
  .filter(source => source.reaction && source.apiVersion === 2 && selected.has(source.id));
100
+ const moduleSources = (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
101
+ .filter(source => source.module && source.apiVersion === 3 && selected.has(source.id));
102
+ const moduleOutputTypes = new Set(moduleSources.flatMap(source => source.module?.produces ?? []));
103
+ const legacyReadsUnifiedOutput = reactionSources.some(source => source.reaction?.consumes.some(type => moduleOutputTypes.has(type)));
99
104
  const reminders = configuredReminders as ClawclawReminderPlugin | undefined ?? new ClawclawReminderPlugin({
100
105
  sources: (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
101
106
  .filter(source => source.reminder && selected.has(source.id)),
@@ -127,7 +132,7 @@ export function assembleClawclawPlugins(
127
132
  after: [],
128
133
  // A migrated, selected perception replaces the same declared legacy Trigger.
129
134
  // Its old file/config can remain for rollback without evaluating the rule twice.
130
- triggers: options.triggers?.map(entry => reactionSources.some(source =>
135
+ triggers: options.triggers?.map(entry => [...reactionSources, ...moduleSources].some(source =>
131
136
  (source.declaredId ?? source.id) === entry.source.id) ? { ...entry, enabled: false } : entry),
132
137
  diagnosticsEnabled: options.triggerDiagnosticsEnabled,
133
138
  });
@@ -136,10 +141,16 @@ export function assembleClawclawPlugins(
136
141
  const reactions = reactionSources.length ? new ClawclawReactionPlugin({
137
142
  sources: reactionSources,
138
143
  after: [CLAWCLAW_DERIVED_EVENT_PLUGIN_ID, CLAWCLAW_REMINDER_PLUGIN_ID,
139
- CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID],
144
+ CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID,
145
+ ...(legacyReadsUnifiedOutput ? [CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID] : [])],
140
146
  behaviors: () => options.behaviorCatalog?.list?.() ?? [],
141
147
  }) : undefined;
142
148
  if (reactions) plugins.push(reactions);
149
+ const modules = moduleSources.length ? new ClawclawReactionPlugin({ unified: true, sources: moduleSources,
150
+ after: [CLAWCLAW_DERIVED_EVENT_PLUGIN_ID],
151
+ behaviors: () => options.behaviorCatalog?.list?.() ?? [],
152
+ }) : undefined;
153
+ if (modules) plugins.push(modules);
143
154
 
144
155
  const configuredBehavior = plugins.find((plugin) => plugin.id === CLAWCLAW_BEHAVIOR_PLUGIN_ID);
145
156
  if (configuredBehavior && !(configuredBehavior instanceof ClawclawBehaviorPlugin)) {
@@ -147,7 +158,7 @@ export function assembleClawclawPlugins(
147
158
  }
148
159
  const behavior = configuredBehavior as ClawclawBehaviorPlugin | undefined
149
160
  ?? new ClawclawBehaviorPlugin({
150
- perceptionActivations: !!reactions,
161
+ perceptionActivations: !!reactions || !!modules,
151
162
  catalog: options.behaviorCatalog ?? new ClawclawBehaviorCatalog([]),
152
163
  fallbackBehaviors: options.fallbackBehaviors,
153
164
  after: [
@@ -158,6 +169,7 @@ export function assembleClawclawPlugins(
158
169
  CLAWCLAW_PERCEPTION_PLUGIN_ID,
159
170
  CLAWCLAW_TRIGGER_PLUGIN_ID,
160
171
  ...(reactions ? [CLAWCLAW_REACTION_PLUGIN_ID] : []),
172
+ ...(modules ? [CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID] : []),
161
173
  ],
162
174
  eventTypes: options.behaviorEventTypes,
163
175
  diagnosticsEnabled: options.behaviorDiagnosticsEnabled,
@@ -184,5 +196,5 @@ export function assembleClawclawPlugins(
184
196
  ?? new ClawclawMailboxPlugin({ after: eventProducers });
185
197
  if (!configuredMailbox) plugins.push(mailbox);
186
198
 
187
- return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox, reactions };
199
+ return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox, reactions, modules };
188
200
  }
@@ -0,0 +1,28 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { ClawclawPerception } 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
+
7
+ function freeze<T>(value: T): T {
8
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
9
+ for (const child of Object.values(value)) freeze(child); Object.freeze(value);
10
+ }
11
+ return value;
12
+ }
13
+ try {
14
+ const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
15
+ if (!(Module?.prototype instanceof ClawclawPerception)
16
+ || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw new Error('PERCEPTION_MODULE_CLASS_INVALID');
17
+ const manifest = normalizePerceptionModuleManifest(Module.manifest);
18
+ if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
19
+ parentPort!.postMessage({ type: 'ready' });
20
+ parentPort!.on('message', async ({ id, input }: { id: number; input: PerceptionModuleInput }) => {
21
+ try {
22
+ const result = await new Module().evaluate(freeze({ ...input, config: manifest.config ?? {},
23
+ events: input.events.filter(event => manifest.consumes?.includes(event.type)) }));
24
+ if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
25
+ parentPort!.postMessage({ type: 'result', id, result });
26
+ } catch { parentPort!.postMessage({ type: 'error', id }); }
27
+ });
28
+ } 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.reaction && !source.module);
331
331
  const reducerPool = selected.length > 0
332
332
  ? new PerceptionReducerThreadPool({
333
333
  modules: selected.map((source) => loader.threadSpec(source)),
@@ -27,6 +27,8 @@ import { normalizeReminderManifest } from '../../reminder-manifest.js';
27
27
  import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
28
28
  import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
29
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;
@@ -47,10 +49,18 @@ export interface ResolvedClawclawPerceptionSource {
47
49
  /** Non-visual execution contract; manifest above is the common resource descriptor. */
48
50
  readonly reminder?: ClawclawReminderManifest;
49
51
  readonly reaction?: ClawclawReactionManifest;
52
+ readonly module?: PerceptionModuleManifest;
50
53
  readonly sourcePath: string;
51
54
  readonly sourceRoot: string;
52
55
  }
53
56
 
57
+ export function expectedPerceptionApiVersion(source: ResolvedClawclawPerceptionSource): number {
58
+ return 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,6 +361,17 @@ 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);
@@ -12,13 +12,18 @@ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
12
12
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
13
13
  import { ReactionRunner } from './reaction-runner.js';
14
14
  import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
15
+ import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
16
+ import type { ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
15
17
 
16
18
  export const CLAWCLAW_REACTION_PLUGIN_ID = 'clawclaw.perception.reactions';
19
+ export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
17
20
  export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.reaction_failed'] as const;
18
21
  interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
19
22
  interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
20
- interface Checkpoint { gameId?: string; phase?: string; modules: Record<string, ModuleState>; failures: string[] }
23
+ interface Checkpoint { gameId?: string; phase?: string; connectionId?: string; previousTick?: number; modules: Record<string, ModuleState>; failures: string[] }
21
24
  export interface ReactionPluginOptions {
25
+ /** A shared execution engine; v2 retains its subscription semantics, v3 admits only source/system facts. */
26
+ unified?: boolean;
22
27
  sources: readonly ResolvedClawclawPerceptionSource[];
23
28
  after: readonly string[];
24
29
  behaviors: () => readonly ReactionBehaviorCandidate[];
@@ -29,7 +34,7 @@ const record = (value: unknown): value is Record<string, any> => !!value && type
29
34
  /** All modules observe their subscribed facts independently. Only own outputs are produced. */
30
35
  export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
31
36
  readonly kind = 'epoch' as const;
32
- readonly id = CLAWCLAW_REACTION_PLUGIN_ID;
37
+ readonly id: string;
33
38
  readonly version = '1';
34
39
  readonly catchUp = 'strict_ordered' as const;
35
40
  readonly timeoutMs = 10_000;
@@ -43,11 +48,15 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
43
48
  private checkpoint: Checkpoint = { modules: {}, failures: [] };
44
49
  private readonly projector = new ObservationFrameProjector();
45
50
  constructor(private readonly options: ReactionPluginOptions) {
46
- this.sources = options.sources.filter(source => source.reaction).map(source => ({
47
- ...source, reaction: normalizeReactionManifest(source.reaction),
51
+ this.id = options.unified ? CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID : CLAWCLAW_REACTION_PLUGIN_ID;
52
+ this.sources = options.sources.filter(source => options.unified ? source.module : source.reaction).map(source => ({
53
+ ...source, reaction: options.unified ? { ...source.module!, apiVersion: 2 as const, kind: 'reaction' as const,
54
+ consumes: source.module!.consumes ?? [], produces: source.module!.produces ?? [] }
55
+ : normalizeReactionManifest(source.reaction),
48
56
  })).sort((a, b) => a.id.localeCompare(b.id));
49
57
  this.after = options.after;
50
- this.consumes = { events: [...new Set(this.sources.flatMap(source => [...source.reaction!.consumes]))] };
58
+ this.consumes = { events: [...new Set([...this.sources.flatMap(source => [...source.reaction!.consumes]),
59
+ ...(options.unified ? ['tasks_changed'] : [])])] };
51
60
  this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
52
61
  ...this.sources.flatMap(source => [...source.reaction!.produces])])] };
53
62
  }
@@ -78,8 +87,13 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
78
87
  const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
79
88
  const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
80
89
  const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
90
+ const initial = !!game && this.checkpoint.gameId !== game.game_id;
91
+ const boundary = initial ? 'initial' as const : this.checkpoint.connectionId !== undefined
92
+ && this.checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
81
93
  if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
82
- if (!game || this.checkpoint.phase !== game.phase) {
94
+ if ((!game && (!this.options.unified || this.checkpoint.phase !== undefined))
95
+ || (game && this.checkpoint.phase !== game.phase)) {
96
+ if (this.options.unified) this.checkpoint.previousTick = undefined;
83
97
  for (const state of Object.values(this.checkpoint.modules)) {
84
98
  state.value = undefined;
85
99
  for (const binding of Object.values(state.bindings)) {
@@ -89,12 +103,26 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
89
103
  this.checkpoint.phase = game?.phase;
90
104
  }
91
105
  const frame = this.projector.project(input.frame);
106
+ if (this.options.unified && frame) {
107
+ const delta = this.checkpoint.previousTick === undefined ? null : frame.tick - this.checkpoint.previousTick;
108
+ Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
109
+ && this.checkpoint.connectionId === input.epoch.connectionId });
110
+ this.checkpoint.previousTick = frame.tick;
111
+ }
92
112
  const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
93
113
  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,
114
+ const facts = input.pendingEvents.filter(event => !event.replayed && (!this.options.unified
115
+ || event.producer === 'backend_push' || event.producerPluginId === undefined
116
+ || event.producerPluginId === 'clawclaw.derived-event')).map(event => ({
117
+ eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
118
+ type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
96
119
  payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
97
120
  }));
121
+ const taskChanges: ReminderTaskChange[] = facts.filter(event => event.type === 'tasks_changed').flatMap(event =>
122
+ (Array.isArray(event.payload.delta) ? event.payload.delta : []).map((change: Record<string, unknown>, index: number) => ({
123
+ ...change, key: `change:${event.eventId}:${index}`, eventId: event.eventId, epochId: event.epochId,
124
+ baseline: event.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(event.payload.reason)),
125
+ } as ReminderTaskChange)));
98
126
  const events: RuntimeEventProposal[] = [];
99
127
  const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState }> = [];
100
128
  for (const source of this.sources) {
@@ -102,9 +130,10 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
102
130
  try {
103
131
  const state = Object.hasOwn(this.checkpoint.modules, source.id)
104
132
  ? 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,
133
+ const moduleInput: ReactionInput & Partial<PerceptionModuleInput> = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
106
134
  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) };
135
+ state: state.value, config: source.reaction!.config ?? {}, availableBehaviors: candidates.filter(c => c.loadable).map(c => c.id),
136
+ ...(this.options.unified ? { taskChanges, boundary } : {}) };
108
137
  // A control-only epoch is not an observation that clears a visual condition.
109
138
  if (!frame && moduleInput.events.length === 0) continue;
110
139
  const result = await this.runners.get(source.id)!.evaluate(moduleInput);
@@ -116,9 +145,13 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
116
145
  const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
117
146
  for (const [key, binding] of Object.entries(source.reaction!.behaviors ?? {})) {
118
147
  const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
119
- if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) current.warning = undefined;
148
+ if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) {
149
+ current.warning = undefined; current.failedAttempt = undefined;
150
+ }
120
151
  if (!matched.has(key)) { current.armed = true; current.failedAttempt = undefined; continue; }
121
152
  if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
153
+ // Ignore only the missing binding; the module's other outputs continue above.
154
+ if (current.warning === 'behavior_not_loaded') continue;
122
155
  if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
123
156
  if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
124
157
  requests.push({ source, activation: matched.get(key)!, state: current });
@@ -171,6 +204,7 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
171
204
  }
172
205
  }
173
206
  }
207
+ if (this.options.unified) this.checkpoint.connectionId = input.epoch.connectionId;
174
208
  return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
175
209
  ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
176
210
  }
@@ -184,7 +218,8 @@ export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string,
184
218
  if (!record(event) || !source.reaction!.produces.includes(event.type)
185
219
  || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
186
220
  || 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');
221
+ || !record(event.payload) || !this.options.unified
222
+ && (typeof event.payload.text !== 'string' || !event.payload.text.trim())) throw new Error('REACTION_EVENT_INVALID');
188
223
  }
189
224
  const bindings = new Set<string>();
190
225
  for (const activation of result.activations ?? []) {
@@ -15,8 +15,8 @@ export class ReactionRunner {
15
15
  const ready = this.wait(8_000);
16
16
  this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
17
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,
18
+ workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.module ?? this.source.reaction,
19
+ runtimeModuleBootstrap: { hostUrl: new URL(this.source.module ? './perception-module-worker.ts' : './reaction-worker.ts', import.meta.url).href,
20
20
  ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
21
21
  });
22
22
  this.worker.stdout?.on('data', () => {}); this.worker.stderr?.on('data', () => {});
@@ -253,6 +253,9 @@ function visualDelivery(
253
253
  }
254
254
 
255
255
  function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[] {
256
+ const perceptionOutputTypes = new Set(options.reactionEventTypes ?? []);
257
+ const ownOutputDelivery = (type: string) => perceptionOutputTypes.has(type)
258
+ ? visualDelivery(options.visualEventDelivery, type) : 'monitor_and_events' as const;
256
259
  const visualEventTypes = [...new Set([
257
260
  ...CLAWCLAW_VISUAL_EVENT_TYPES,
258
261
  ...(options.visualEventTypes ?? []),
@@ -273,7 +276,7 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
273
276
  ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.map((type) => ({
274
277
  type,
275
278
  producer: 'local_synth' as const,
276
- deliveryClass: 'monitor_and_events' as const,
279
+ deliveryClass: ownOutputDelivery(type),
277
280
  })),
278
281
  ...CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES.map((type) => ({
279
282
  type,
@@ -293,7 +296,7 @@ function entries(options: ClawclawEventCatalogOptions = {}): EventCatalogEntry[]
293
296
  ...behaviorEventTypes.map((type) => ({
294
297
  type,
295
298
  producer: 'local_synth' as const,
296
- deliveryClass: 'monitor_and_events' as const,
299
+ deliveryClass: ownOutputDelivery(type),
297
300
  })),
298
301
  ];
299
302
  }
package/src/sdk/index.ts CHANGED
@@ -57,6 +57,7 @@ export {
57
57
  TRIGGER_PLUGIN_API_VERSION,
58
58
  } from './trigger-plugin/index.js';
59
59
  export type {
60
+ PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleEvent,
60
61
  ClawclawPerceptionClass, ClawclawPerceptionEventMetadata,
61
62
  ClawclawPerceptionManifest, Direction, PerceptionAnalysisInput,
62
63
  PerceptionApi, PerceptionBoundary, PerceptionBoundaryKind,
@@ -68,6 +69,7 @@ export {
68
69
  ClawclawPerception,
69
70
  MOVE_MIN_PX,
70
71
  PERCEPTION_PLUGIN_API_VERSION,
72
+ PERCEPTION_MODULE_API_VERSION,
71
73
  STEP_MOVE_MIN_PX,
72
74
  STILL_STEP_MAX_PX,
73
75
  TICK_MS,
@@ -1,7 +1,15 @@
1
+ /** Frozen API v2 compatibility version; new modules use PERCEPTION_MODULE_API_VERSION (3). */
1
2
  export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
3
+ export * from './module.js';
4
+ import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult } from './module.js';
2
5
  export * from './reminder.js';
3
6
  export * from './reaction.js';
4
- export { defaultReminder as evaluateReminder } from './reminder-rules.js';
7
+ import { defaultReminder } from './reminder-rules.js';
8
+ import type { ReminderInput, ReminderResult, ReminderTopic } from './reminder.js';
9
+ /** Optional task/speech helper accepts both the unified input and its v2 compatibility input. */
10
+ export function evaluateReminder(topic: ReminderTopic, input: ReminderInput | PerceptionModuleInput): ReminderResult {
11
+ return defaultReminder(topic, 'events' in input ? { ...input, facts: input.events } : input);
12
+ }
5
13
 
6
14
  export {
7
15
  hasValidClawclawResourceLocalizations,
@@ -120,6 +128,7 @@ export interface PerceptionEventProposal {
120
128
  readonly occurredAt?: string;
121
129
  }
122
130
 
131
+ /** @deprecated Visual API v2 compatibility; new scripts use PerceptionModuleManifest. */
123
132
  export interface ClawclawPerceptionManifest {
124
133
  /** Whether this Event may initiate Agent delivery; omitted means true. */
125
134
  readonly wakeAgent?: boolean;
@@ -153,18 +162,26 @@ export interface ClawclawPerceptionManifest {
153
162
  /**
154
163
  * Canonical authoring surface for one independent perception module.
155
164
  *
156
- * CCL imports this local code inside a memory-bounded Worker lane. Without
157
- * `parallel_analysis`, one persistent instance runs `update()` in frame order.
158
- * A slow call can be terminated without blocking the Runtime Owner, but authors
159
- * should still keep each call short so the module can keep up with live frames.
165
+ * API v3 runs evaluate() in a bounded Worker with a fresh instance per call;
166
+ * return state for the next call and recovery. API v2 update/parallel_analysis
167
+ * retains its original persistent reducer semantics on the compatibility path.
168
+ * A slow call can be terminated without blocking the Runtime Owner.
160
169
  */
161
170
  export abstract class ClawclawPerception {
162
- static readonly manifest?: ClawclawPerceptionManifest;
171
+ static readonly manifest?: ClawclawPerceptionManifest | PerceptionModuleManifest;
172
+
173
+ /** API v3 combines observation, notification and fixed Behavior activation. */
174
+ evaluate(_input: Readonly<PerceptionModuleInput>): PerceptionModuleResult | Promise<PerceptionModuleResult> {
175
+ throw new Error('PERCEPTION_EVALUATE_NOT_IMPLEMENTED');
176
+ }
163
177
 
164
- abstract update(
178
+ /** @deprecated API v2 compatibility; new modules implement evaluate(). */
179
+ update(
165
180
  frame: Readonly<PerceptionFrame>,
166
181
  api: PerceptionApi,
167
- ): readonly PerceptionEventProposal[] | void | Promise<readonly PerceptionEventProposal[] | void>;
182
+ ): readonly PerceptionEventProposal[] | void | Promise<readonly PerceptionEventProposal[] | void> {
183
+ throw new Error('PERCEPTION_UPDATE_NOT_IMPLEMENTED');
184
+ }
168
185
 
169
186
  /** Called only when CCL requires an open long-running slice to be reported. */
170
187
  flush?(