@myclaw163/clawclaw-cli 0.9.2 → 0.10.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 (197) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +23 -35
  7. package/docs/custom-modules/api-reference.md +95 -273
  8. package/docs/custom-modules/behavior.md +94 -78
  9. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +42 -603
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +16 -17
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +47 -46
  19. package/docs/runtime/components-and-boundaries.md +70 -28
  20. package/docs/runtime/events-and-state.md +41 -18
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +10 -7
  26. package/docs/user-guide/api-reference.md +81 -164
  27. package/docs/user-guide/behavior.md +84 -68
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +42 -586
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +8 -13
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +49 -49
  37. package/skills/clawclaw/references/BEHAVIORS.md +42 -73
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +60 -101
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +26 -10
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +3 -2
  53. package/src/commands/perception.ts +5 -0
  54. package/src/commands/strategy.ts +2 -0
  55. package/src/lib/capability-load-diagnostics.ts +3 -3
  56. package/src/lib/perception-config.ts +18 -6
  57. package/src/lib/runtime-cadence-config.ts +16 -0
  58. package/src/lib/workspace-runtime-lock.ts +3 -46
  59. package/src/pipeline/canonical-event-presentation.ts +23 -124
  60. package/src/pipeline/event-format.ts +12 -21
  61. package/src/pipeline/event-hints.ts +6 -6
  62. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  63. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  64. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  65. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  66. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  67. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  68. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  69. package/src/runtime/clawclaw/owner.ts +18 -4
  70. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  71. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  72. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  73. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  74. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  75. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  76. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  77. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  78. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  79. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  82. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  83. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  84. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  85. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  86. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
  87. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  88. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  89. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  90. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  91. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  92. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  93. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  94. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  95. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  96. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  97. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  98. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  99. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  100. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  101. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
  102. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  103. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  104. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
  105. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  106. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  107. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  108. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  109. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  110. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  111. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  112. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  113. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  114. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  115. package/src/runtime/clawclaw/runtime.ts +8 -0
  116. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  117. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  118. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  119. package/src/runtime/framework/action-diagnostics.ts +3 -83
  120. package/src/runtime/framework/capability-registry.ts +2 -395
  121. package/src/runtime/framework/contracts.ts +2 -144
  122. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  123. package/src/runtime/framework/control/domain-set.ts +2 -81
  124. package/src/runtime/framework/control/index.ts +1 -3
  125. package/src/runtime/framework/control/types.ts +2 -191
  126. package/src/runtime/framework/control-coordinator.ts +2 -11
  127. package/src/runtime/framework/events/event-catalog.ts +2 -74
  128. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  129. package/src/runtime/framework/events/event-ingress.ts +2 -99
  130. package/src/runtime/framework/events/event-repository.ts +2 -82
  131. package/src/runtime/framework/events/index.ts +2 -7
  132. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  133. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  134. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  135. package/src/runtime/framework/events/test-helpers.ts +1 -1
  136. package/src/runtime/framework/events/types.ts +2 -312
  137. package/src/runtime/framework/index.ts +3 -7
  138. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  139. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  140. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  141. package/src/runtime/framework/mailbox/identity.ts +2 -38
  142. package/src/runtime/framework/mailbox/index.ts +1 -7
  143. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  144. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  145. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  146. package/src/runtime/framework/mailbox/types.ts +2 -145
  147. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  148. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  149. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  150. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  151. package/src/runtime/framework/participation-manager.ts +2 -253
  152. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  153. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  154. package/src/runtime/framework/plugins/contracts.ts +2 -396
  155. package/src/runtime/framework/plugins/index.ts +1 -4
  156. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  157. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  158. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  159. package/src/runtime/framework/runtime.ts +5 -1843
  160. package/src/runtime/framework/serial-task-queue.ts +2 -14
  161. package/src/runtime/framework/state/contracts.ts +2 -49
  162. package/src/runtime/framework/state/current-state-store.ts +2 -184
  163. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  164. package/src/runtime/framework/state/freshness.ts +2 -72
  165. package/src/runtime/framework/state/history/contracts.ts +2 -158
  166. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  167. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  168. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  169. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  170. package/src/runtime/framework/state/index.ts +1 -13
  171. package/src/runtime/framework/state/state-ingress.ts +2 -95
  172. package/src/runtime/framework/state/state-provider.ts +2 -62
  173. package/src/runtime/framework/state/types.ts +2 -155
  174. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  175. package/src/runtime/mailbox-host-relay.ts +1 -326
  176. package/src/runtime/observability/detail-capture.ts +4 -108
  177. package/src/runtime/observability/process-timing.ts +2 -59
  178. package/src/runtime/observability/recorder.ts +2 -238
  179. package/src/runtime/observability/redaction.ts +2 -181
  180. package/src/runtime/observability/reporter.ts +2 -154
  181. package/src/runtime/observability/sinks.ts +2 -135
  182. package/src/runtime/observability/types.ts +2 -92
  183. package/src/runtime/owner-control.ts +45 -320
  184. package/src/runtime/parent-process-watch.ts +1 -51
  185. package/src/runtime/process-identity.ts +1 -72
  186. package/src/sdk/behavior-plugin/index.ts +9 -3
  187. package/src/sdk/index.ts +40 -2
  188. package/src/sdk/module-input/index.ts +5 -0
  189. package/src/sdk/perception-plugin/index.ts +3 -1
  190. package/src/sdk/perception-plugin/module.ts +12 -2
  191. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  192. package/src/sdk/perception-plugin/reminder.ts +2 -1
  193. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  194. package/src/sdk/strategy-memory.ts +1 -12
  195. package/src/sdk/strategy-plugin/index.ts +36 -0
  196. package/src/sdk/trigger-plugin/index.ts +1 -0
  197. package/docs/custom-modules/trigger.md +0 -295
@@ -0,0 +1 @@
1
+ export * from '@myclaw163/game-agent-runtime/perception/map-concurrent.js';
@@ -0,0 +1,60 @@
1
+ import type { EventNotificationContent } from '../../../framework/events/types.js';
2
+ import type { RuntimeEpochPluginContext } from '../../../framework/plugins/index.js';
3
+ import { compactEventForChannel, formatEventMessage } from '../../../../pipeline/event-format.js';
4
+ import { formatCanonicalEventHint, type EventHintOrigin } from '../../../../pipeline/event-hints.js';
5
+ import { buildLocalGameStartedEnrichment } from '../../../../lib/game-context.js';
6
+ import { projectClawclawCurrentState } from '../../runtime-state.js';
7
+
8
+ export type NotificationOwner = 'builtin' | 'custom' | 'system';
9
+
10
+ /** Policy belongs to the producing perception/system notification, not EventIngress or delivery. */
11
+ export function prepareNotificationContent(
12
+ type: string,
13
+ payload: Readonly<Record<string, unknown>>,
14
+ state: Record<string, any> | null,
15
+ owner: NotificationOwner,
16
+ origin: EventHintOrigin = { producer: 'local_synth' },
17
+ ): EventNotificationContent {
18
+ const { hint, next_step: _next, notice: _notice, ...facts } = structuredClone(payload);
19
+ const event = compactEventForChannel({ ...facts, type }, { summary: state });
20
+ if (owner === 'builtin' && type === 'game_started') Object.assign(event, buildLocalGameStartedEnrichment());
21
+ // meeting_briefing.speech_order is exclusively backend-owned. Never fill a missing order from State.
22
+ const ownedHint = owner === 'custom'
23
+ ? typeof hint === 'string' && hint.trim() ? hint : undefined
24
+ : formatCanonicalEventHint(origin, event, { summary: state });
25
+ if (ownedHint !== undefined) event.hint = ownedHint;
26
+ const content: EventNotificationContent = {
27
+ event,
28
+ monitorText: type.startsWith('visual.') ? `${type} | ${String(event.text ?? '')}`.trimEnd()
29
+ : formatEventMessage(event, { summary: state, maxTextLength: Number.MAX_SAFE_INTEGER }),
30
+ };
31
+ if (owner === 'system' && ['joined', 'room_created', 'room_joined', 'session_resumed'].includes(type)) {
32
+ const omitLinks = (value: any): any => Array.isArray(value) ? value.map(omitLinks)
33
+ : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value)
34
+ .filter(([key]) => !['url', 'spectate_url', 'spectateUrl'].includes(key)).map(([key, item]) => [key, omitLinks(item)])) : value;
35
+ const desktop = omitLinks(event);
36
+ if (type === 'joined') desktop.hint = event.recovered === true || event.resumed === true
37
+ ? 'The game runtime reattached; do not start a duplicate runtime.' : 'The game runtime is attached; do not start a duplicate runtime.';
38
+ if (type === 'room_created') desktop.hint = 'Keep the room runtime attached.';
39
+ if (type === 'room_joined') desktop.hint = event.recovered === true || event.resumed === true
40
+ ? 'The room runtime reattached; keep it attached.' : 'Keep the room runtime attached.';
41
+ content.desktopEvent = desktop;
42
+ }
43
+ return content;
44
+ }
45
+
46
+ /** The event's accepted State boundary, never the newer State at delivery time. */
47
+ export function notificationStateAt(context: RuntimeEpochPluginContext<Record<string, any>>, epochSeq: number | undefined): Record<string, any> | null {
48
+ if (epochSeq === undefined) return null;
49
+ let beforeFrameSeq: number | undefined;
50
+ while (true) {
51
+ const page = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: epochSeq,
52
+ ...(beforeFrameSeq === undefined ? {} : { beforeFrameSeq }), order: 'desc', limit: 64 });
53
+ for (const frame of page.frames) {
54
+ const state = projectClawclawCurrentState(frame.state);
55
+ if (state) return state;
56
+ }
57
+ if (!page.page.hasMore || !page.frames.length) return null;
58
+ beforeFrameSeq = page.frames.at(-1)!.frameSeq;
59
+ }
60
+ }
@@ -1,314 +1,136 @@
1
- import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult,
2
- RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
- import type { ReactionActivation } from '../../../../sdk/perception-plugin/reaction.js';
1
+ import { normalizePerceptionStrategyNames } from '../../perception-strategy-names.js';
2
+ import { prepareNotificationContent } from './notification-content.js';
3
+ import { isNotificationTurn } from '../../notification-turn.js';
4
+ import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
4
5
  import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
5
- import type { ClawclawStrategyMemory } from '../../strategy-memory.js';
6
- import { unavailableStrategyMemory } from '../../strategy-memory-rpc.js';
7
- import type { BehaviorReflexActivationDriver } from '../trigger/contracts.js';
8
- import { resolveReactionBehavior, type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
6
+ import { type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
9
7
  import { ObservationFrameProjector } from '../../observation-frame-projector.js';
10
- import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
8
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
11
9
  import { createCanonicalGameState } from '../../behavior-input.js';
12
10
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
13
11
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
14
12
  import { PerceptionModuleRunner } from './perception-module-runner.js';
15
13
  import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
16
- import type { PerceptionModuleInput, PerceptionModuleResult } from '../../../../sdk/perception-plugin/module.js';
17
- import type { ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
18
-
14
+ import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
15
+ import { comparePerceptionTasks, type PerceptionTaskBaseline } from './task-baseline.js';
16
+ import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
17
+ import type { PerceptionAdapter, PerceptionSource } from '@myclaw163/game-agent-runtime/perception/contracts.js';
18
+ import type { ClawclawResolvedResourceMetadata } from '../../../../sdk/resource-metadata.js';
19
19
  export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
20
- export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.module_failed'] as const;
21
- interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
22
- interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
23
- interface Checkpoint { gameId?: string; phase?: string; connectionId?: string; previousTick?: number; modules: Record<string, ModuleState>; failures: string[] }
20
+ export { REACTION_HOST_EVENT_TYPES } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
24
21
  export interface PerceptionModulePluginOptions {
25
- /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */
26
- sources: readonly ResolvedClawclawPerceptionSource[];
27
- after: readonly string[];
28
- behaviors?: () => readonly ReactionBehaviorCandidate[];
29
- runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
22
+ /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */
23
+ sources: readonly ResolvedClawclawPerceptionSource[];
24
+ after: readonly string[];
25
+ behaviors?: () => readonly ReactionBehaviorCandidate[];
26
+ runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
30
27
  }
31
- const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
32
-
33
- /** Observing and notifications remain active independently of fixed Reflex admission. */
34
- export class ClawclawPerceptionModulePlugin implements RuntimeEpochPlugin<Record<string, any>> {
35
- readonly kind = 'epoch' as const;
36
- readonly id: string;
37
- readonly version = '1';
38
- readonly catchUp = 'strict_ordered' as const;
39
- readonly timeoutMs = 10_000;
40
- readonly after: readonly string[];
41
- readonly consumes: { events: readonly string[] };
42
- readonly produces: { events: readonly string[] };
43
- private readonly sources: readonly ResolvedClawclawPerceptionSource[];
44
- private readonly runners = new Map<string, Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>>();
45
- private readonly failed = new Set<string>();
46
- private checkpoint: Checkpoint = { modules: {}, failures: [] };
47
- private readonly projector = new ObservationFrameProjector();
48
- constructor(private readonly options: PerceptionModulePluginOptions) {
49
- this.id = CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID;
50
- this.sources = options.sources.filter(s => s.module).sort((a,b) => a.id.localeCompare(b.id));
51
- this.after = options.after;
52
- this.consumes = { events: [...new Set([...this.sources.flatMap(source => [...(source.module!.consumes ?? [])]),
53
- 'tasks_changed'])] };
54
- this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
55
- ...this.sources.flatMap(source => [...(source.module!.produces ?? [])])])] };
56
- }
57
- private driver?: BehaviorReflexActivationDriver;
58
- private memory?: ClawclawStrategyMemory;
59
- private scope?: { sessionId: string; segmentId: string };
60
- private stopped = true;
61
- private generation = 0;
62
- private watches = new Set<string>();
63
- private configs = new Map<string, Readonly<Record<string, unknown>>>();
64
- attachDriver(driver: BehaviorReflexActivationDriver): void { this.driver = driver; }
65
- attachMemory(memory: ClawclawStrategyMemory): void { this.memory = memory; }
66
- private sameScope(scope: { sessionId: string; segmentId: string }): boolean {
67
- return this.scope?.sessionId === scope.sessionId && this.scope.segmentId === scope.segmentId;
68
- }
69
- bindings(id?: string) {
70
- const candidates = this.options.behaviors?.() ?? [];
71
- return this.sources.flatMap(source => Object.entries(source.module!.behaviors ?? {}).map(([key,binding]) => {
72
- const target = resolveReactionBehavior(binding,candidates), state = this.checkpoint.modules[source.id]?.bindings[key];
73
- return { id: target ?? binding.name, perception_id: source.id, binding: key,
74
- trigger_id: `perception:${source.id}:${key}`, available: !!target && !this.failed.has(source.id),
75
- reason: this.failed.has(source.id) ? 'perception_module_failed' : !target ? 'behavior_not_loaded' : undefined,
76
- enabled: !!target && this.watches.has(target), priority: binding.reflexPriority ?? 0,
77
- armed: state?.armed ?? true, cooldown_ms: binding.cooldownMs ?? 1000,
78
- cooldown_remaining_ms: Math.max(0, (binding.cooldownMs ?? 1000) - ((this.lastNow ?? 0) - (state?.lastAcceptedAt ?? -Infinity))) };
79
- })).filter(binding => id === undefined || binding.id === id);
80
- }
81
- private lastNow?: number;
82
- private busy = 0;
83
- diagnosticSnapshot() { return { worker_pool: { busy_worker_count: this.busy }, modules: this.status() }; }
84
- setWatch(id: string, enabled: boolean, guard: () => boolean): string[] {
85
- if (this.stopped || !guard()) throw Error('stale_runtime_scope');
86
- const bindings = this.bindings(id);
87
- if (!bindings.length || enabled && !bindings.some(binding => binding.available)) throw Error('perception_binding_unavailable');
88
- if (enabled) {
89
- this.watches.add(id);
90
- for (const binding of bindings) {
91
- const state = this.checkpoint.modules[binding.perception_id]?.bindings[binding.binding];
92
- if (state) { state.armed = true; state.failedAttempt = undefined; }
93
- }
94
- } else this.watches.delete(id);
95
- this.generation++;
96
- return bindings.map(binding => binding.trigger_id);
97
- }
98
- configure(id: string, patch: Readonly<Record<string, unknown>>, guard: () => boolean) {
99
- if (this.stopped || !guard()) throw Error('stale_runtime_scope');
100
- const source = this.sources.find(s => s.id === id);
101
- if (!source) throw Error('perception_not_found');
102
- if (this.failed.has(id)) throw Error('perception_module_failed');
103
- const input = normalizeBehaviorInput({ ...(this.configs.get(id) ?? source.module!.config), ...patch }, source.module!.inputs ?? []);
104
- this.configs.set(id,input); this.generation++;
105
- for (const state of Object.values(this.checkpoint.modules[id]?.bindings ?? {})) {
106
- state.failedAttempt = undefined; state.warning = undefined;
107
- }
108
- return { applied: true, id, input };
109
- }
110
- behaviorInputChanged(id: string): void {
111
- this.generation++;
112
- for (const binding of this.bindings(id)) {
113
- const state = this.checkpoint.modules[binding.perception_id]?.bindings[binding.binding];
114
- if (state) { state.failedAttempt = undefined; state.warning = undefined; }
115
- }
116
- }
117
- status(id?: string) {
118
- return this.sources.filter(s => id === undefined || id === s.id).map(s => ({ id: s.id,
119
- observing: !this.stopped && !this.failed.has(s.id), input: this.configs.get(s.id) ?? s.module!.config ?? {},
120
- bindings: this.bindings().filter(b => b.perception_id === s.id) }));
121
- }
122
- async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
123
- this.stopped = false; this.scope = { ...context.scope }; this.generation++; this.watches.clear(); this.configs.clear();
124
- this.checkpoint = { modules: {}, failures: [] }; this.failed.clear(); this.projector.reset();
125
- await Promise.all(this.sources.map(async (source, index) => {
126
- try {
127
- if (index >= 32) throw new Error('REACTION_MODULE_LIMIT');
128
- const runner = this.options.runnerFactory?.(source) ?? new PerceptionModuleRunner(source, (input, active) => {
129
- const resolved = Object.values(source.module!.behaviors ?? {}).map(binding =>
130
- resolveReactionBehavior(binding, this.options.behaviors?.() ?? []));
131
- const targets = [...new Set(resolved)];
132
- return this.memory?.bind(input.scope, targets.length === 1 && targets[0] ? `behavior:${targets[0]}` : `perception:${source.id}`,
133
- () => active() && !this.stopped && !!this.scope && this.sameScope(input.scope)) ?? unavailableStrategyMemory;
134
- });
135
- this.runners.set(source.id, runner); await runner.start();
136
- } catch {
137
- this.failed.add(source.id); await this.runners.get(source.id)?.stop();
138
- context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
139
- }
140
- }));
141
- }
142
- recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
143
- const saved = context.checkpoint() as Checkpoint | undefined;
144
- if (saved?.modules && Array.isArray(saved.failures)) {
145
- this.checkpoint = structuredClone(saved);
146
- // Existing notification-only module checkpoints have no binding state.
147
- for (const state of Object.values(this.checkpoint.modules)) state.bindings ??= {};
148
- }
149
- this.projector.reset();
150
- }
151
- async stop(): Promise<void> { this.stopped = true; this.generation++; await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
152
- localizedModuleDescriptors(locale: string) {
153
- return this.sources.filter(source => !this.failed.has(source.id)).map(source =>
154
- resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, locale));
155
- }
156
- async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
157
- this.scope = { ...input.epoch.scope };
158
- const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
159
- const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
160
- const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
161
- const initial = !!game && this.checkpoint.gameId !== game.game_id;
162
- const boundary = initial ? 'initial' as const : this.checkpoint.connectionId !== undefined
163
- && this.checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
164
- if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
165
- if ((!game && this.checkpoint.phase !== undefined)
166
- || (game && this.checkpoint.phase !== game.phase)) {
167
- this.checkpoint.previousTick = undefined;
168
- for (const state of Object.values(this.checkpoint.modules)) {
169
- state.value = undefined;
170
- for (const binding of Object.values(state.bindings)) {
171
- binding.armed = true; binding.lastAcceptedAt = undefined; binding.failedAttempt = undefined;
172
- }
173
- }
174
- this.checkpoint.phase = game?.phase;
175
- }
176
- const frame = this.projector.project(input.frame);
177
- if (frame) {
178
- const delta = this.checkpoint.previousTick === undefined ? null : frame.tick - this.checkpoint.previousTick;
179
- Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
180
- && this.checkpoint.connectionId === input.epoch.connectionId });
181
- this.checkpoint.previousTick = frame.tick;
182
- }
183
- const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs; this.lastNow = nowMs;
184
- const candidates = (this.options.behaviors?.() ?? []);
185
- const facts = input.pendingEvents.filter(event => !event.replayed && (event.producer === 'backend_push' || event.producerPluginId === undefined
186
- || event.producerPluginId === 'clawclaw.derived-event')).map(event => ({
187
- eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
188
- type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
189
- payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
190
- }));
191
- const taskChanges: ReminderTaskChange[] = facts.filter(event => event.type === 'tasks_changed').flatMap(event =>
192
- (Array.isArray(event.payload.delta) ? event.payload.delta : []).map((change: Record<string, unknown>, index: number) => ({
193
- ...change, key: `change:${event.eventId}:${index}`, eventId: event.eventId, epochId: event.epochId,
194
- baseline: event.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(event.payload.reason)),
195
- } as ReminderTaskChange)));
196
- const events: RuntimeEventProposal[] = [];
197
- const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState; generation: number }> = [];
198
- for (const source of this.sources) {
199
- if (!this.failed.has(source.id)) {
200
- try {
201
- const state = Object.hasOwn(this.checkpoint.modules, source.id)
202
- ? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
203
- const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
204
- events: facts.filter(event => source.module!.consumes?.includes(event.type)), nowMs,
205
- state: state.value, config: this.configs.get(source.id) ?? source.module!.config ?? {},
206
- availableBehaviors: [...new Set([...candidates.filter(c => c.loadable).map(c => c.id),
207
- ...Object.values(source.module!.behaviors ?? {}).filter(binding => resolveReactionBehavior(binding, candidates)).map(binding => binding.name)])],
208
- availableBindings: Object.entries(source.module!.behaviors ?? {}).filter(([,binding]) => !!resolveReactionBehavior(binding,candidates)).map(([key]) => key),
209
- enabledBindings: Object.entries(source.module!.behaviors ?? {}).filter(([,binding]) => {
210
- const id = resolveReactionBehavior(binding,candidates); return !!id && this.watches.has(id);
211
- }).map(([key]) => key), taskChanges, boundary };
212
- // A control-only epoch is not an observation that clears a visual condition.
213
- if (!frame && moduleInput.events.length === 0) continue;
214
- const generation = this.generation;
215
- this.busy++;
216
- let result: PerceptionModuleResult;
217
- try { result = await this.runners.get(source.id)!.evaluate(moduleInput); }
218
- finally { this.busy--; }
219
- this.validate(result, source);
220
- state.value = structuredClone(result.state);
221
- for (const event of result.events ?? []) events.push({ type: event.type,
222
- dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
223
- payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
224
- const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
225
- for (const [key, binding] of Object.entries(source.module!.behaviors ?? {})) {
226
- const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
227
- if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) {
228
- current.warning = undefined; current.failedAttempt = undefined;
28
+ interface GameCheckpoint {
29
+ gameId?: string;
30
+ phase?: string;
31
+ connectionId?: string;
32
+ previousTick?: number;
33
+ modules: Record<string, {
34
+ value?: unknown;
35
+ bindings: Record<string, {
36
+ armed: boolean;
37
+ lastAcceptedAt?: number;
38
+ failedAttempt?: string;
39
+ }>;
40
+ }>;
41
+ }
42
+ function sourceValue(source: PerceptionSource): ResolvedClawclawPerceptionSource { return source.value as ResolvedClawclawPerceptionSource; }
43
+ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapter {
44
+ const projector = new ObservationFrameProjector();
45
+ function prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown) {
46
+ let checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint;
47
+ checkpoint.modules = {};
48
+ const oldGame = checkpoint.gameId, oldPhase = checkpoint.phase;
49
+ const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
50
+ const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
51
+ const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
52
+ const initial = !!game && checkpoint.gameId !== game.game_id;
53
+ const boundary = initial ? 'initial' as const : checkpoint.connectionId !== undefined
54
+ && checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
55
+ if (game && checkpoint.gameId !== game.game_id)
56
+ checkpoint = { gameId: game.game_id, modules: {} };
57
+ if ((!game && checkpoint.phase !== undefined)
58
+ || (game && checkpoint.phase !== game.phase)) {
59
+ checkpoint.previousTick = undefined;
60
+ for (const state of Object.values(checkpoint.modules)) {
61
+ state.value = undefined;
62
+ for (const binding of Object.values(state.bindings)) {
63
+ binding.armed = true;
64
+ binding.lastAcceptedAt = undefined;
65
+ binding.failedAttempt = undefined;
66
+ }
229
67
  }
230
- if (!matched.has(key)) { current.armed = true; current.failedAttempt = undefined; continue; }
231
- const target = resolveReactionBehavior(binding, candidates);
232
- if (generation !== this.generation || !target || !this.watches.has(target)) continue;
233
- if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
234
- // Ignore only the missing binding; the module's other outputs continue above.
235
- if (current.warning === 'behavior_not_loaded') continue;
236
- if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
237
- if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
238
- requests.push({ source, activation: matched.get(key)!, state: current, generation });
239
- }
240
- } catch {
241
- this.failed.add(source.id); await this.runners.get(source.id)?.stop();
242
- context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
68
+ checkpoint.phase = game?.phase;
243
69
  }
244
- }
245
- if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
246
- this.checkpoint.failures.push(source.id);
247
- events.push({ type: 'perception.module_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
248
- payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
249
- }
250
- }
251
- requests.sort((a, b) => (b.source.module!.behaviors![b.activation.behavior].reflexPriority ?? 0)
252
- - (a.source.module!.behaviors![a.activation.behavior].reflexPriority ?? 0));
253
- for (const { source, activation, state, generation } of requests) {
254
- if (context.signal.aborted || generation !== this.generation) break;
255
- const binding = source.module!.behaviors![activation.behavior];
256
- const behavior = resolveReactionBehavior(binding, (this.options.behaviors?.() ?? []));
257
- const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
258
- if (state.failedAttempt === attempt) continue;
259
- let result: { accepted: boolean; reason?: string } = { accepted: false, reason: 'behavior_not_loaded' };
260
- if (behavior && this.watches.has(behavior)) {
261
- try {
262
- result = await this.driver?.requestReflex({ source: 'perception',
263
- triggerId: `perception:${source.id}:${activation.behavior}`, scope: input.epoch.scope,
264
- epochId: input.epoch.epochSeq, configGeneration: generation, behavior,
265
- behaviorInput: { ...binding.input, ...activation.input }, reflexPriority: binding.reflexPriority ?? 0,
266
- maxRuntimeMs: binding.maxRuntimeMs ?? 10_000,
267
- reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` },
268
- { isCurrent: () => !this.stopped && !context.signal.aborted && generation === this.generation
269
- && this.watches.has(behavior) && this.sameScope(input.epoch.scope) })
270
- ?? { accepted: false, reason: 'activation_unavailable' };
271
- } catch { result = { accepted: false, reason: 'activation_unavailable' }; }
272
- }
273
- if (result.accepted) {
274
- state.armed = false; state.lastAcceptedAt = nowMs; state.warning = undefined; state.failedAttempt = undefined;
275
- } else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
276
- const reason = result.reason ?? 'activation_unavailable';
277
- state.failedAttempt = attempt;
278
- if (state.warning !== reason) {
279
- state.warning = reason; state.warningSequence++;
280
- events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
281
- dedupeKey: JSON.stringify([game?.game_id, source.id, activation.behavior, state.warningSequence]),
282
- payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
283
- ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
284
- ...(behavior ? { behavior_id: behavior } : {}), reason,
285
- text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
70
+ const frame = projector.project(input.frame);
71
+ if (frame) {
72
+ const delta = checkpoint.previousTick === undefined ? null : frame.tick - checkpoint.previousTick;
73
+ Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
74
+ && checkpoint.connectionId === input.epoch.connectionId });
75
+ checkpoint.previousTick = frame.tick;
286
76
  }
287
- }
77
+ const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
78
+ const facts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined).map(event => ({
79
+ eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
80
+ type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
81
+ payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
82
+ }));
83
+ const resetScope = !!game && oldGame !== game.game_id;
84
+ const resetModules = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase);
85
+ checkpoint.connectionId = input.epoch.connectionId;
86
+ return { state: checkpoint, identity: game?.game_id, resetScope, resetModules, notificationOnly: false, nowMs,
87
+ reflexAllowed: !!game && game.phase === 'wandering' && game.you?.is_alive === true && connected,
88
+ value: { input, game, frame, facts, boundary } };
288
89
  }
289
- this.checkpoint.connectionId = input.epoch.connectionId;
290
- return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
291
- ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
292
- }
293
- private validate(result: PerceptionModuleResult, source: ResolvedClawclawPerceptionSource): void {
294
- if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
295
- || result.events !== undefined && !Array.isArray(result.events)
296
- || result.activations !== undefined && !Array.isArray(result.activations)
297
- || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
298
- || Buffer.byteLength(JSON.stringify(result)) > 128_000) throw new Error('REACTION_OUTPUT_INVALID');
299
- for (const event of result.events ?? []) {
300
- if (!record(event) || !source.module!.produces?.includes(event.type)
301
- || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
302
- || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
303
- || !record(event.payload)) throw new Error('REACTION_EVENT_INVALID');
90
+ type Prepared = ReturnType<typeof prepare>['value'];
91
+ return {
92
+ reset: () => projector.reset(),
93
+ recover: saved => {
94
+ const value = saved as {
95
+ adapterState?: unknown;
96
+ modules?: Record<string, Record<string, unknown>>;
97
+ } & GameCheckpoint;
98
+ for (const state of Object.values(value.modules ?? {}))
99
+ if (state.inputState === undefined && 'taskBaseline' in state) {
100
+ state.inputState = state.taskBaseline;
101
+ delete state.taskBaseline;
102
+ }
103
+ return value.adapterState ?? { gameId: value.gameId, phase: value.phase, connectionId: value.connectionId, previousTick: value.previousTick, modules: {} };
104
+ },
105
+ prepare: (input, previous) => isNotificationTurn(input.epoch.state)
106
+ ? { state: previous, resetScope: false, resetModules: false, notificationOnly: true, nowMs: 0, reflexAllowed: false, value: null }
107
+ : prepare(input, previous),
108
+ configure: (source, value) => normalizeBehaviorInput(value, sourceValue(source).module!.inputs ?? []),
109
+ describe: (source, locale) => { const value = sourceValue(source); return resolveClawclawResourceMetadata({ ...value.manifest, display: value.display }, locale); },
110
+ createRunner: (source, bindMemory) => {
111
+ const value = sourceValue(source);
112
+ const runner = options.runnerFactory?.(value) ?? new PerceptionModuleRunner(value, (input, active) => bindMemory({ scope: input.scope, value: input }, active));
113
+ return { start: () => runner.start(), stop: () => runner.stop(), evaluate: async (input) => normalizePerceptionStrategyNames(await runner.evaluate(input.value as PerceptionModuleInput)) };
114
+ },
115
+ input: (source, prepared, baseline, state, config, bindings) => {
116
+ const { input, game, frame, facts, boundary } = prepared.value as Prepared;
117
+ const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
118
+ const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
119
+ ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
120
+ events: facts.filter(event => source.module.consumes?.includes(event.type)), nowMs: prepared.nowMs,
121
+ state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
122
+ return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
123
+ evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || moduleInput.events.length > 0 };
124
+ },
125
+ notification: (event, prepared) => prepareNotificationContent(event.type, event.payload, (prepared.value as Prepared).game, 'custom'),
126
+ };
127
+ }
128
+ export class ClawclawPerceptionModulePlugin extends PerceptionHost {
129
+ constructor(options: PerceptionModulePluginOptions) {
130
+ super({ id: CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID, after: options.after, behaviors: options.behaviors, adapter: createAdapter(options),
131
+ sources: options.sources.filter(source => source.module).map(source => ({ id: source.id, name: source.name, module: source.module!, value: source })) });
304
132
  }
305
- const bindings = new Set<string>();
306
- for (const activation of result.activations ?? []) {
307
- if (!record(activation) || !Object.hasOwn(source.module!.behaviors ?? {}, activation.behavior)
308
- || bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
309
- || activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
310
- || Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key))) throw new Error('REACTION_ACTIVATION_INVALID');
311
- bindings.add(activation.behavior);
133
+ override localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
134
+ return super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
312
135
  }
313
- }
314
136
  }
@@ -1,62 +1,13 @@
1
- import { Worker } from 'node:worker_threads';
2
1
  import { pathToFileURL } from 'node:url';
2
+ import { PerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker.js';
3
3
  import type { PerceptionModuleInput, PerceptionModuleResult } from '../../../../sdk/perception-plugin/module.js';
4
4
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
5
5
  import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
6
6
  import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
7
- import { serveStrategyMemoryRequest, unavailableStrategyMemory } from '../../strategy-memory-rpc.js';
8
-
9
- /** Memory-bounded independent perception execution with scoped memory RPC. */
10
- export class PerceptionModuleRunner {
11
- private worker?: Worker;
12
- private sequence = 0;
13
- private failure?: Error;
14
- private pending?: { id?: number; resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> };
15
- private memory?: StrategyMemory;
16
- constructor(readonly source: ResolvedClawclawPerceptionSource,
17
- private readonly bindMemory?: (input: PerceptionModuleInput, active: () => boolean) => StrategyMemory) {}
18
- async start(): Promise<void> {
19
- const ready = this.wait(8_000);
20
- this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
21
- execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 64 },
22
- workerData: { modulePath: this.source.sourcePath, expectedManifest: this.source.module,
23
- legacy: !!this.source.reaction,
24
- runtimeModuleBootstrap: { hostUrl: new URL('./perception-module-worker.ts', import.meta.url).href,
25
- ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(this.source.sourcePath)).href] } },
26
- });
27
- this.worker.stdout?.on('data', () => {}); this.worker.stderr?.on('data', () => {});
28
- this.worker.on('error', error => this.fail(error));
29
- this.worker.on('exit', () => this.fail(new Error('PERCEPTION_MODULE_WORKER_EXITED')));
30
- this.worker.on('message', message => {
31
- if (message.type === 'strategy_memory') {
32
- void serveStrategyMemoryRequest(message, () => {
33
- if (message.requestId !== String(this.pending?.id)) throw Error('strategy_memory_inactive');
34
- return this.memory ?? unavailableStrategyMemory;
35
- }, reply => this.worker?.postMessage(reply));
36
- return;
37
- }
38
- if (!this.pending || (message.id !== undefined && message.id !== this.pending.id)) return;
39
- if (message.type === 'error') { this.fail(new Error('PERCEPTION_MODULE_MODULE_FAILED')); return; }
40
- const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.resolve(message.result);
41
- });
42
- await ready;
43
- }
44
- async evaluate(input: PerceptionModuleInput): Promise<PerceptionModuleResult> {
45
- if (this.failure) throw this.failure;
46
- if (!this.worker) throw new Error('PERCEPTION_MODULE_WORKER_NOT_STARTED');
47
- const id = ++this.sequence; const result = this.wait(500, id);
48
- this.memory = this.bindMemory?.(input, () => this.pending?.id === id && !this.failure);
49
- this.worker.postMessage({ id, input }); return result;
50
- }
51
- async stop(): Promise<void> { this.fail(new Error('PERCEPTION_MODULE_STOPPED')); await this.worker?.terminate(); this.worker = undefined; }
52
- private wait(ms: number, id?: number): Promise<any> {
53
- if (this.pending) throw new Error('PERCEPTION_MODULE_CONCURRENT_CALL');
54
- return new Promise((resolve, reject) => {
55
- this.pending = { id, resolve, reject, timer: setTimeout(() => { this.fail(new Error('PERCEPTION_MODULE_TIMEOUT')); void this.stop(); }, ms) };
56
- });
57
- }
58
- private fail(error: Error): void {
59
- this.failure = error;
60
- if (this.pending) { const pending = this.pending; this.pending = undefined; clearTimeout(pending.timer); pending.reject(error); }
61
- }
7
+ export class PerceptionModuleRunner extends PerceptionWorker<PerceptionModuleInput, PerceptionModuleResult> {
8
+ constructor(readonly source: ResolvedClawclawPerceptionSource, bindMemory?: (input: PerceptionModuleInput, active: () => boolean) => StrategyMemory) {
9
+ super({ compatibilityError: source.compatibilityError, workerData: { modulePath: source.sourcePath, expectedManifest: source.module,
10
+ legacy: !!source.reaction, runtimeModuleBootstrap: { hostUrl: new URL('./perception-module-worker.ts', import.meta.url).href,
11
+ ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(source.sourcePath)).href] } } }, bindMemory);
12
+ }
62
13
  }