@myclaw163/clawclaw-cli 0.8.41 → 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 (49) 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 +56 -3
  4. package/docs/custom-modules/behavior.md +6 -0
  5. package/docs/custom-modules/examples/first-sighting-v3.ts +29 -0
  6. package/docs/custom-modules/perception.md +139 -58
  7. package/docs/custom-modules/trigger.md +2 -0
  8. package/docs/runtime/README.md +17 -8
  9. package/docs/runtime/agent-notifications.md +32 -15
  10. package/docs/runtime/behavior-runtime.md +28 -21
  11. package/docs/runtime/components-and-boundaries.md +57 -17
  12. package/docs/runtime/events-and-state.md +42 -2
  13. package/docs/runtime/owner-lifecycle-and-observability.md +5 -3
  14. package/docs/user-guide/README.md +50 -0
  15. package/docs/user-guide/api-reference.md +760 -0
  16. package/docs/user-guide/behavior.md +369 -0
  17. package/docs/user-guide/installation.md +123 -0
  18. package/docs/user-guide/perception.md +869 -0
  19. package/docs/user-guide/skill.md +67 -0
  20. package/package.json +4 -2
  21. package/skills/clawclaw/SKILL.md +4 -4
  22. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  23. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +6 -0
  24. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +56 -3
  25. package/skills/clawclaw/references/CUSTOM-MODULES.md +12 -16
  26. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +139 -58
  27. package/src/commands/load.ts +13 -11
  28. package/src/commands/perception.ts +2 -2
  29. package/src/commands/trigger.ts +1 -1
  30. package/src/lib/agent-workspace-sync.ts +2 -2
  31. package/src/runtime/clawclaw/owner.ts +3 -2
  32. package/src/runtime/clawclaw/perception-module-manifest.ts +27 -0
  33. package/src/runtime/clawclaw/plugins/assembly.ts +17 -5
  34. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +28 -0
  35. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  36. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +21 -0
  37. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +47 -12
  38. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +2 -2
  39. package/src/runtime/clawclaw/task-choice-projection.ts +19 -25
  40. package/src/runtime/clawclaw-event-catalog.ts +5 -2
  41. package/src/sdk/behavior-plugin/index.ts +3 -0
  42. package/src/sdk/index.ts +4 -0
  43. package/src/sdk/module-input/index.ts +15 -1
  44. package/src/sdk/perception-plugin/index.ts +25 -8
  45. package/src/sdk/perception-plugin/module.ts +46 -0
  46. package/src/sdk/perception-plugin/reaction.ts +1 -0
  47. package/src/sdk/perception-plugin/reminder.ts +1 -0
  48. package/src/sdk/task-availability.ts +70 -0
  49. package/src/sdk/trigger-plugin/index.ts +1 -0
@@ -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', () => {});
@@ -1,4 +1,6 @@
1
1
  import { loadClawclawMapAsset } from '../../lib/game-context.js';
2
+ import { getCrabSabotageAvailability, getTaskAvailability } from '../../sdk/task-availability.js';
3
+ import type { GameState, GameTask, GameTaskKind } from '../../sdk/module-input/index.js';
2
4
 
3
5
  type RecordValue = Readonly<Record<string, any>>;
4
6
  const record = (value: unknown): RecordValue => value && typeof value === 'object' && !Array.isArray(value)
@@ -13,9 +15,7 @@ export function isCrabPlayer(game: unknown): boolean {
13
15
  }
14
16
 
15
17
  export function crabSabotageReady(game: unknown): boolean {
16
- const state = record(game), sabotage = record(state.crab_sabotage);
17
- return sabotage.status === 'ready' && record(state.emergency).active !== true
18
- && !(typeof sabotage.cooldown_remaining_secs === 'number' && sabotage.cooldown_remaining_secs > 0);
18
+ return getCrabSabotageAvailability(record(game) as unknown as GameState).state === 'ready';
19
19
  }
20
20
 
21
21
  function staticTaskType(task: RecordValue): number | undefined {
@@ -46,15 +46,18 @@ function ongoingTask(game: unknown, task: RecordValue): boolean {
46
46
  return activity.kind === 'task' && taskName(task) && taskName(task) === label(activity.task_name) ? true : false;
47
47
  }
48
48
 
49
- /** Keep execution/completion facts; omit unstarted sabotage choices until authoritative readiness. */
49
+ /** Preserve every assignment and attach a deterministic, bounded public availability projection. */
50
50
  export function projectTaskChoices<T extends RecordValue>(game: unknown, tasks: readonly T[]): T[] {
51
- return tasks.flatMap(task => {
52
- if (!isSabotageTask(game, task) || crabSabotageReady(game)) return [task];
53
- if (task.status === 'completed' || task.status === 'in_progress') return [task];
54
- // Activity is an authoritative execution fact even if its task-status update lags.
55
- if (ongoingTask(game, task)) return [{ ...task, status: 'in_progress' } as T];
56
- return [];
51
+ const state = record(game);
52
+ const projected = tasks.map(task => {
53
+ const kind: GameTaskKind = task.is_fake_shrimp === true ? 'fake_shrimp'
54
+ : isSabotageTask(game, task) ? 'sabotage'
55
+ : staticTaskType(task) === 2 || (record(state.emergency).active === true
56
+ && taskName(task) === label(record(state.emergency).task_name)) ? 'emergency' : 'ordinary';
57
+ return { ...task, kind, ...(ongoingTask(game, task) && task.status !== 'completed' ? { status: 'in_progress' } : {}) };
57
58
  });
59
+ const snapshot = { ...state, you: { ...record(state.you), tasks: projected } } as unknown as GameState;
60
+ return projected.map(task => ({ ...task, availability: getTaskAvailability(snapshot, task as unknown as GameTask) }) as T);
58
61
  }
59
62
 
60
63
  /** A public projection only. Persisted Source snapshots and task-change history remain untouched. */
@@ -64,23 +67,14 @@ export function projectTaskChoiceGameState<T extends Record<string, any>>(source
64
67
  return game as T;
65
68
  }
66
69
 
67
- /** Map task locations are not assignments, but must not recreate blocked sabotage choices. */
68
- export function projectTaskChoiceLocations<T extends RecordValue>(game: unknown, locations: readonly T[]): T[] {
69
- return locations.filter(task => !isSabotageTask(game, task) || crabSabotageReady(game));
70
+ /** Static map points remain visible; they are neither assignments nor a readiness claim. */
71
+ export function projectTaskChoiceLocations<T extends RecordValue>(_game: unknown, locations: readonly T[]): T[] {
72
+ return [...locations];
70
73
  }
71
74
 
72
- /** Current assignment arrays in module input follow the same policy; occurrence facts survive. */
73
- export function projectTaskChoiceEventPayload(game: unknown, type: string, payload: RecordValue): Record<string, any> {
74
- const result: Record<string, any> = structuredClone(payload);
75
- if (type === 'tasks_changed') {
76
- if (Array.isArray(result.tasks)) result.tasks = projectTaskChoices(game, result.tasks);
77
- if (Array.isArray(result.delta)) result.delta = result.delta.filter(change =>
78
- change.change === 'removed' || projectTaskChoices(game, [record(change.task)]).length > 0);
79
- }
80
- if (result.newly_assigned_task && projectTaskChoices(game, [record(result.newly_assigned_task)]).length === 0) {
81
- delete result.newly_assigned_task;
82
- }
83
- return result;
75
+ /** Occurrence facts keep their original complete content; current readiness belongs to State. */
76
+ export function projectTaskChoiceEventPayload(_game: unknown, _type: string, payload: RecordValue): Record<string, any> {
77
+ return structuredClone(payload);
84
78
  }
85
79
 
86
80
  /** Also reject stale/remembered task names at the Action boundary, before HTTP submission. */
@@ -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
  }
@@ -7,6 +7,9 @@ import type { ClawclawResourceLocalizations } from '../resource-metadata.js';
7
7
 
8
8
  export const BEHAVIOR_PLUGIN_API_VERSION = 3 as const;
9
9
 
10
+ export { getTaskAvailability, getAvailableTasks, isTaskAvailable, getTaskKind } from '../task-availability.js';
11
+ export type { GameTaskAvailability, GameTaskKind } from '../module-input/index.js';
12
+
10
13
  export {
11
14
  hasValidClawclawResourceLocalizations,
12
15
  resolveClawclawResourceMetadata,
package/src/sdk/index.ts CHANGED
@@ -25,6 +25,8 @@
25
25
  */
26
26
 
27
27
  export { Action } from './action.js';
28
+ export { getTaskAvailability, getAvailableTasks, isTaskAvailable, getTaskKind } from './task-availability.js';
29
+ export type { GameTaskAvailability, GameTaskKind } from './module-input/index.js';
28
30
  export { GameClient } from '../lib/game-client.js';
29
31
  export type { GameClientConfig } from '../lib/game-client.js';
30
32
  export type {
@@ -55,6 +57,7 @@ export {
55
57
  TRIGGER_PLUGIN_API_VERSION,
56
58
  } from './trigger-plugin/index.js';
57
59
  export type {
60
+ PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleEvent,
58
61
  ClawclawPerceptionClass, ClawclawPerceptionEventMetadata,
59
62
  ClawclawPerceptionManifest, Direction, PerceptionAnalysisInput,
60
63
  PerceptionApi, PerceptionBoundary, PerceptionBoundaryKind,
@@ -66,6 +69,7 @@ export {
66
69
  ClawclawPerception,
67
70
  MOVE_MIN_PX,
68
71
  PERCEPTION_PLUGIN_API_VERSION,
72
+ PERCEPTION_MODULE_API_VERSION,
69
73
  STEP_MOVE_MIN_PX,
70
74
  STILL_STEP_MAX_PX,
71
75
  TICK_MS,
@@ -18,6 +18,17 @@ export interface GamePlayerActivity {
18
18
  readonly target_y?: number;
19
19
  }
20
20
 
21
+ export type GameTaskKind = 'ordinary' | 'fake_shrimp' | 'sabotage' | 'emergency';
22
+
23
+ export interface GameTaskAvailability {
24
+ readonly state: 'ready' | 'cooldown' | 'blocked' | 'in_progress' | 'completed' | 'unknown';
25
+ readonly reason?: 'sabotage_cooldown' | 'emergency_active' | 'sabotage_state_unavailable'
26
+ | 'task_state_unavailable' | 'player_state_unavailable' | 'not_assigned' | 'not_alive'
27
+ | 'not_wandering' | 'emergency_inactive' | 'task_in_progress' | 'task_completed';
28
+ /** Authoritative shared cooldown, not an SDK wall-clock estimate. */
29
+ readonly remaining_secs?: number;
30
+ }
31
+
21
32
  export interface GameTask {
22
33
  /** Stable task identity when the backend provides one. */
23
34
  readonly task_id?: string;
@@ -29,6 +40,9 @@ export interface GameTask {
29
40
  readonly is_fake_shrimp: boolean;
30
41
  readonly status?: 'normal' | 'in_progress' | 'completed';
31
42
  readonly task_note?: string;
43
+ /** CCL read projection; does not change the underlying assignment or execution status. */
44
+ readonly kind?: GameTaskKind;
45
+ readonly availability?: Readonly<GameTaskAvailability>;
32
46
  }
33
47
 
34
48
  export interface GameSelf {
@@ -44,7 +58,7 @@ export interface GameSelf {
44
58
  readonly kills_remaining?: number | null;
45
59
  readonly activity?: Readonly<GamePlayerActivity>;
46
60
  readonly crab_teammates?: readonly Readonly<PlayerRef>[];
47
- /** Current task choices and execution/completion facts. Unstarted crab sabotage is omitted until ready. */
61
+ /** Complete current assignments, including cooldown/blocked tasks and execution/completion facts. */
48
62
  readonly tasks?: readonly Readonly<GameTask>[];
49
63
  }
50
64
 
@@ -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?(