@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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 (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -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,142 @@
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 { preparePerceptionNotification } from './report-content.js';
4
+ import { isNotificationTurn } from '../../notification-turn.js';
5
+ import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
4
6
  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';
7
+ import { type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
9
8
  import { ObservationFrameProjector } from '../../observation-frame-projector.js';
10
- import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
9
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
11
10
  import { createCanonicalGameState } from '../../behavior-input.js';
12
11
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
13
12
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
14
13
  import { PerceptionModuleRunner } from './perception-module-runner.js';
15
14
  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
-
15
+ import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
16
+ import { comparePerceptionTasks, type PerceptionTaskBaseline } from './task-baseline.js';
17
+ import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
18
+ import type { PerceptionAdapter, PerceptionSource } from '@myclaw163/game-agent-runtime/perception/contracts.js';
19
+ import type { ClawclawResolvedResourceMetadata } from '../../../../sdk/resource-metadata.js';
19
20
  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[] }
21
+ export { REACTION_HOST_EVENT_TYPES } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
24
22
  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'>;
23
+ /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */
24
+ sources: readonly ResolvedClawclawPerceptionSource[];
25
+ after: readonly string[];
26
+ behaviors?: () => readonly ReactionBehaviorCandidate[];
27
+ runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
30
28
  }
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;
29
+ interface GameCheckpoint {
30
+ gameId?: string;
31
+ phase?: string;
32
+ connectionId?: string;
33
+ previousTick?: number;
34
+ modules: Record<string, {
35
+ value?: unknown;
36
+ bindings: Record<string, {
37
+ armed: boolean;
38
+ lastAcceptedAt?: number;
39
+ failedAttempt?: string;
40
+ }>;
41
+ }>;
42
+ }
43
+ function sourceValue(source: PerceptionSource): ResolvedClawclawPerceptionSource { return source.value as ResolvedClawclawPerceptionSource; }
44
+ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapter {
45
+ const projector = new ObservationFrameProjector();
46
+ function prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown) {
47
+ let checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint;
48
+ checkpoint.modules = {};
49
+ const oldGame = checkpoint.gameId, oldPhase = checkpoint.phase;
50
+ const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
51
+ const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
52
+ const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
53
+ const initial = !!game && checkpoint.gameId !== game.game_id;
54
+ const boundary = initial ? 'initial' as const : checkpoint.connectionId !== undefined
55
+ && checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
56
+ if (game && checkpoint.gameId !== game.game_id)
57
+ checkpoint = { gameId: game.game_id, modules: {} };
58
+ if ((!game && checkpoint.phase !== undefined)
59
+ || (game && checkpoint.phase !== game.phase)) {
60
+ checkpoint.previousTick = undefined;
61
+ for (const state of Object.values(checkpoint.modules)) {
62
+ state.value = undefined;
63
+ for (const binding of Object.values(state.bindings)) {
64
+ binding.armed = true;
65
+ binding.lastAcceptedAt = undefined;
66
+ binding.failedAttempt = undefined;
67
+ }
229
68
  }
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');
69
+ checkpoint.phase = game?.phase;
243
70
  }
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 判断处理;其他感知和策略继续运行。` } });
71
+ const frame = projector.project(input.frame);
72
+ if (frame) {
73
+ const delta = checkpoint.previousTick === undefined ? null : frame.tick - checkpoint.previousTick;
74
+ Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
75
+ && checkpoint.connectionId === input.epoch.connectionId });
76
+ checkpoint.previousTick = frame.tick;
286
77
  }
287
- }
78
+ const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
79
+ const facts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined).map(event => ({
80
+ eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
81
+ type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
82
+ payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
83
+ }));
84
+ const resetScope = !!game && oldGame !== game.game_id;
85
+ const resetModules = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase);
86
+ checkpoint.connectionId = input.epoch.connectionId;
87
+ return { state: checkpoint, identity: game?.game_id, resetScope, resetModules, notificationOnly: false, nowMs,
88
+ reflexAllowed: !!game && game.phase === 'wandering' && game.you?.is_alive === true && connected,
89
+ value: { input, game, frame, facts, boundary } };
288
90
  }
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');
91
+ type Prepared = ReturnType<typeof prepare>['value'];
92
+ return {
93
+ reset: () => projector.reset(),
94
+ recover: saved => {
95
+ const value = saved as {
96
+ adapterState?: unknown;
97
+ modules?: Record<string, Record<string, unknown>>;
98
+ } & GameCheckpoint;
99
+ for (const state of Object.values(value.modules ?? {}))
100
+ if (state.inputState === undefined && 'taskBaseline' in state) {
101
+ state.inputState = state.taskBaseline;
102
+ delete state.taskBaseline;
103
+ }
104
+ return value.adapterState ?? { gameId: value.gameId, phase: value.phase, connectionId: value.connectionId, previousTick: value.previousTick, modules: {} };
105
+ },
106
+ prepare: (input, previous) => isNotificationTurn(input.epoch.state)
107
+ ? { state: previous, resetScope: false, resetModules: false, notificationOnly: true, nowMs: 0, reflexAllowed: false, value: null }
108
+ : prepare(input, previous),
109
+ configure: (source, value) => normalizeBehaviorInput(value, sourceValue(source).module!.inputs ?? []),
110
+ describe: (source, locale) => { const value = sourceValue(source); return resolveClawclawResourceMetadata({ ...value.manifest, display: value.display }, locale); },
111
+ createRunner: (source, bindMemory) => {
112
+ const value = sourceValue(source);
113
+ const runner = options.runnerFactory?.(value) ?? new PerceptionModuleRunner(value, (input, active) => bindMemory({ scope: input.scope, value: input }, active));
114
+ return { start: () => runner.start(), stop: () => runner.stop(), evaluate: async (input) => normalizePerceptionStrategyNames(await runner.evaluate(input.value as PerceptionModuleInput)) };
115
+ },
116
+ input: (source, prepared, baseline, state, config, bindings) => {
117
+ const { input, game, frame, facts, boundary } = prepared.value as Prepared;
118
+ const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
119
+ const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
120
+ ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
121
+ events: facts.filter(event => source.module.consumes?.includes(event.type)), nowMs: prepared.nowMs,
122
+ state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
123
+ return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
124
+ evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || moduleInput.events.length > 0 };
125
+ },
126
+ notification: (event, prepared, source) => {
127
+ const { game, input } = prepared.value as Prepared;
128
+ return source
129
+ ? preparePerceptionNotification(event.type, event.payload, game, source.id, input.frame.backendTick)
130
+ : prepareNotificationContent(event.type, event.payload, game, 'custom');
131
+ },
132
+ };
133
+ }
134
+ export class ClawclawPerceptionModulePlugin extends PerceptionHost {
135
+ constructor(options: PerceptionModulePluginOptions) {
136
+ super({ id: CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID, after: options.after, behaviors: options.behaviors, adapter: createAdapter(options),
137
+ sources: options.sources.filter(source => source.module).map(source => ({ id: source.id, name: source.name, module: source.module!, value: source })) });
304
138
  }
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);
139
+ override localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
140
+ return super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
312
141
  }
313
- }
314
142
  }
@@ -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
  }