@myclaw163/clawclaw-cli 0.7.16 → 0.8.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 (335) hide show
  1. package/QUICKSTART_HERMES.md +1 -1
  2. package/QUICKSTART_OPENCLAW.md +3 -11
  3. package/QUICKSTART_OTHER.md +8 -8
  4. package/README.md +18 -9
  5. package/bin/clawclaw-channel.mjs +13 -0
  6. package/docs/configuration.md +86 -33
  7. package/docs/custom-modules/README.md +148 -0
  8. package/docs/custom-modules/api-reference.md +767 -0
  9. package/docs/custom-modules/behavior.md +318 -0
  10. package/docs/custom-modules/perception.md +305 -0
  11. package/docs/custom-modules/trigger.md +292 -0
  12. package/docs/desktop-event-push.md +6 -4
  13. package/docs/runtime/README.md +28 -10
  14. package/docs/runtime/agent-notifications.md +48 -29
  15. package/docs/runtime/behavior-runtime.md +139 -0
  16. package/docs/runtime/components-and-boundaries.md +89 -173
  17. package/docs/runtime/events-and-state.md +55 -66
  18. package/docs/runtime/official-perception-modules.md +17 -9
  19. package/docs/runtime/owner-lifecycle-and-observability.md +62 -39
  20. package/docs/runtime/perception-replay.md +6 -6
  21. package/docs/runtime/short-commands-and-capabilities.md +35 -37
  22. package/package.json +10 -7
  23. package/scripts/check-skill-command-surface.mjs +54 -10
  24. package/scripts/compare-perception-replays.test.ts +10 -10
  25. package/scripts/compare-perception-replays.ts +14 -10
  26. package/scripts/replay-perception.ts +3 -3
  27. package/scripts/watch-perception-events.test.ts +1 -1
  28. package/skills/clawclaw/SKILL.md +97 -59
  29. package/skills/clawclaw/references/BEHAVIORS.md +154 -0
  30. package/skills/clawclaw/references/CHANNELS.md +115 -0
  31. package/skills/clawclaw/references/CHATTERBOX.md +3 -2
  32. package/skills/clawclaw/references/COMMANDS.md +108 -58
  33. package/skills/clawclaw/references/GAME-MECHANICS.md +4 -3
  34. package/skills/clawclaw/references/HUB.md +27 -23
  35. package/skills/clawclaw/references/STREAM.md +18 -14
  36. package/skills/clawclaw/references/TACTICS.md +2 -2
  37. package/src/behaviors/official-finite/do-task.ts +141 -0
  38. package/src/behaviors/official-finite/evade.ts +78 -0
  39. package/src/behaviors/official-finite/find-player.ts +50 -0
  40. package/src/behaviors/official-finite/follow-player.ts +70 -0
  41. package/src/behaviors/official-finite/go-to.ts +69 -0
  42. package/src/behaviors/official-finite/hide-temporarily.ts +77 -0
  43. package/src/behaviors/official-finite/hold-position.ts +48 -0
  44. package/src/behaviors/official-finite/hunt-player.ts +47 -0
  45. package/src/behaviors/official-finite/index.test.ts +202 -0
  46. package/src/behaviors/official-finite/index.ts +47 -0
  47. package/src/behaviors/official-finite/inspect-corpse.ts +64 -0
  48. package/src/behaviors/official-finite/patrol-area.ts +80 -0
  49. package/src/behaviors/official-finite/report-corpse.ts +73 -0
  50. package/src/behaviors/official-finite/seek-kill-opportunity.ts +152 -0
  51. package/src/behaviors/official-finite/shared.ts +27 -0
  52. package/src/behaviors/official-finite/trigger-alarm.ts +53 -0
  53. package/src/channel/claude-channel-ipc-server.ts +295 -0
  54. package/src/channel/claude-channel-ipc.ts +152 -0
  55. package/src/channel/claude-channel-server.test.ts +202 -0
  56. package/src/channel/claude-channel-server.ts +221 -0
  57. package/src/cli.ts +4 -2
  58. package/src/commands/account.test.ts +17 -17
  59. package/src/commands/behavior.test.ts +158 -0
  60. package/src/commands/behavior.ts +443 -0
  61. package/src/commands/communication.test.ts +12 -0
  62. package/src/commands/communication.ts +6 -3
  63. package/src/commands/data.test.ts +1 -1
  64. package/src/commands/data.ts +1 -1
  65. package/src/commands/events-canonical-state.test.ts +221 -2
  66. package/src/commands/events.ts +205 -12
  67. package/src/commands/game/index.test.ts +172 -3
  68. package/src/commands/game/index.ts +69 -32
  69. package/src/commands/hub.test.ts +25 -14
  70. package/src/commands/hub.ts +15 -19
  71. package/src/commands/load.test.ts +228 -6
  72. package/src/commands/load.ts +102 -18
  73. package/src/commands/memory.ts +1 -1
  74. package/src/commands/peek.ts +1 -1
  75. package/src/commands/perception.test.ts +30 -1
  76. package/src/commands/perception.ts +15 -17
  77. package/src/commands/trigger.test.ts +140 -0
  78. package/src/commands/trigger.ts +314 -0
  79. package/src/lib/account-guidance.test.ts +4 -0
  80. package/src/lib/account-guidance.ts +1 -1
  81. package/src/lib/behavior-export.test.ts +282 -0
  82. package/src/lib/behavior-export.ts +514 -0
  83. package/src/lib/game-client.test.ts +4 -17
  84. package/src/lib/game-client.ts +1 -0
  85. package/src/lib/gameplay-config.test.ts +258 -37
  86. package/src/lib/gameplay-config.ts +175 -35
  87. package/src/lib/hub-install.test.ts +19 -41
  88. package/src/lib/hub-install.ts +10 -38
  89. package/src/lib/hub-reminder.ts +7 -9
  90. package/src/lib/init-command.ts +1 -1
  91. package/src/lib/official-resource-sync.test.ts +199 -0
  92. package/src/lib/official-resource-sync.ts +221 -0
  93. package/src/lib/perception-config.test.ts +9 -4
  94. package/src/lib/perception-config.ts +10 -13
  95. package/src/lib/perception-export.test.ts +145 -0
  96. package/src/lib/perception-export.ts +178 -0
  97. package/src/lib/trigger-config.test.ts +102 -0
  98. package/src/lib/trigger-config.ts +217 -0
  99. package/src/lib/user-data.test.ts +23 -6
  100. package/src/lib/user-data.ts +15 -123
  101. package/src/pipeline/canonical-event-presentation.test.ts +5 -5
  102. package/src/pipeline/canonical-event-presentation.ts +13 -5
  103. package/src/pipeline/event-format.test.ts +106 -3
  104. package/src/pipeline/event-format.ts +172 -4
  105. package/src/pipeline/event-hints.test.ts +57 -4
  106. package/src/pipeline/event-hints.ts +34 -8
  107. package/src/runtime/canonical-monitor.test.ts +2 -0
  108. package/src/runtime/canonical-monitor.ts +6 -2
  109. package/src/runtime/clawclaw/agent-event-policy.test.ts +23 -2
  110. package/src/runtime/clawclaw/agent-event-policy.ts +12 -5
  111. package/src/runtime/clawclaw/behavior-decision.test.ts +29 -0
  112. package/src/runtime/clawclaw/behavior-decision.ts +82 -0
  113. package/src/runtime/clawclaw/behavior-input-fields.test.ts +175 -0
  114. package/src/runtime/clawclaw/behavior-input-fields.ts +270 -0
  115. package/src/runtime/clawclaw/behavior-input.test.ts +151 -0
  116. package/src/runtime/clawclaw/behavior-input.ts +70 -0
  117. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +59 -0
  118. package/src/runtime/clawclaw/behavior-observation-memory.ts +142 -0
  119. package/src/runtime/clawclaw/behavior-read-api.test.ts +123 -0
  120. package/src/runtime/clawclaw/behavior-read-api.ts +158 -0
  121. package/src/runtime/clawclaw/{plugins/perception/visual-state-projector.ts → observation-frame-projector.ts} +44 -25
  122. package/src/runtime/clawclaw/owner.test.ts +187 -0
  123. package/src/runtime/clawclaw/owner.ts +431 -69
  124. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +304 -0
  125. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +285 -41
  126. package/src/runtime/clawclaw/plugins/action/automated-action-normalization.ts +82 -0
  127. package/src/runtime/clawclaw/plugins/assembly.test.ts +135 -29
  128. package/src/runtime/clawclaw/plugins/assembly.ts +54 -28
  129. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +180 -0
  130. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +468 -0
  131. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +40 -0
  132. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +30 -0
  133. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +152 -0
  134. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +156 -0
  135. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +104 -0
  136. package/src/runtime/clawclaw/plugins/behavior/behavior-manifest.ts +173 -0
  137. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +182 -0
  138. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +223 -0
  139. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +157 -0
  140. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +848 -0
  141. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +1347 -0
  142. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +212 -0
  143. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +174 -0
  144. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +621 -0
  145. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +195 -0
  146. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +180 -0
  147. package/src/runtime/clawclaw/plugins/behavior/index.ts +11 -0
  148. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +766 -0
  149. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +283 -0
  150. package/src/runtime/clawclaw/plugins/{strategy/thread-strategy-executor.ts → behavior/thread-behavior-executor.ts} +109 -121
  151. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +80 -0
  152. package/src/runtime/clawclaw/plugins/behavior-input-source.ts +247 -0
  153. package/src/runtime/clawclaw/plugins/{strategy → game-query}/context-capabilities.ts +1 -1
  154. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +13 -10
  155. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +26 -14
  156. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  157. package/src/runtime/clawclaw/plugins/index.ts +3 -1
  158. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +239 -0
  159. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +100 -0
  160. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +346 -0
  161. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +230 -12
  162. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +118 -90
  163. package/src/runtime/clawclaw/plugins/mailbox/consumer-ids.ts +5 -0
  164. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  165. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +1 -1
  166. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +4 -0
  167. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +87 -0
  168. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +70 -12
  169. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +94 -11
  170. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1229 -345
  171. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +479 -35
  172. package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -3
  173. package/src/runtime/clawclaw/plugins/perception/index.ts +1 -1
  174. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +23 -13
  175. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +11 -9
  176. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +39 -38
  177. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +92 -0
  178. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +248 -0
  179. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +39 -37
  180. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +1 -0
  181. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +22 -21
  182. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +15 -9
  183. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +3 -3
  184. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +33 -18
  185. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +6 -7
  186. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +22 -16
  187. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +6 -7
  188. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +18 -12
  189. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +14 -10
  190. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +20 -14
  191. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +5 -6
  192. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +5 -6
  193. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +49 -34
  194. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +1 -0
  195. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +126 -20
  196. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +24 -3
  197. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +59 -46
  198. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +27 -5
  199. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +381 -49
  200. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +267 -245
  201. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +98 -0
  202. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +89 -16
  203. package/src/runtime/clawclaw/plugins/perception/perception-test-fixtures.ts +34 -0
  204. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +27 -15
  205. package/src/runtime/clawclaw/plugins/perception/replay.ts +10 -5
  206. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +1 -107
  207. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +7 -10
  208. package/src/runtime/clawclaw/plugins/plugin-api-version.ts +112 -0
  209. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +388 -559
  210. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +56 -5
  211. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +135 -26
  212. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +249 -16
  213. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +99 -2
  214. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +212 -0
  215. package/src/runtime/clawclaw/plugins/source/task-change-tracker.ts +259 -0
  216. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +97 -0
  217. package/src/runtime/clawclaw/plugins/trigger/index.ts +4 -0
  218. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +118 -0
  219. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +548 -0
  220. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +655 -0
  221. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +169 -0
  222. package/src/runtime/clawclaw/plugins/trigger/trigger-source.ts +457 -0
  223. package/src/runtime/clawclaw/runtime.ts +8 -0
  224. package/src/runtime/clawclaw/spatial-api.ts +76 -0
  225. package/src/runtime/clawclaw-event-catalog.test.ts +46 -1
  226. package/src/runtime/clawclaw-event-catalog.ts +40 -3
  227. package/src/runtime/framework/capability-registry.test.ts +196 -55
  228. package/src/runtime/framework/capability-registry.ts +99 -17
  229. package/src/runtime/framework/contracts.ts +30 -4
  230. package/src/runtime/framework/control/control-scheduler.ts +13 -5
  231. package/src/runtime/framework/control/types.ts +11 -4
  232. package/src/runtime/framework/control-coordinator.test.ts +95 -80
  233. package/src/runtime/framework/events/event-delivery-service.ts +4 -2
  234. package/src/runtime/framework/events/event-ingress.test.ts +25 -0
  235. package/src/runtime/framework/events/event-ingress.ts +2 -1
  236. package/src/runtime/framework/events/event-repository.ts +24 -2
  237. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +124 -8
  238. package/src/runtime/framework/events/memory-event-repository.ts +92 -28
  239. package/src/runtime/framework/events/sqlite-event-repository.test.ts +604 -2
  240. package/src/runtime/framework/events/sqlite-event-repository.ts +531 -21
  241. package/src/runtime/framework/events/types.ts +24 -8
  242. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +38 -1
  243. package/src/runtime/framework/modules/runtime-module-loader.test.ts +233 -7
  244. package/src/runtime/framework/modules/runtime-module-loader.ts +69 -4
  245. package/src/runtime/framework/plugins/contracts.ts +12 -18
  246. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +81 -71
  247. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +38 -20
  248. package/src/runtime/framework/runtime.ts +20 -23
  249. package/src/runtime/host-monitor-rate-gate.test.ts +73 -0
  250. package/src/runtime/host-monitor-rate-gate.ts +123 -0
  251. package/src/runtime/mailbox-host-relay.test.ts +45 -0
  252. package/src/runtime/mailbox-host-relay.ts +25 -0
  253. package/src/runtime/observability/factory.ts +4 -4
  254. package/src/runtime/observability/observability.test.ts +25 -3
  255. package/src/runtime/observability/reporter.ts +1 -1
  256. package/src/runtime/observability/types.ts +2 -2
  257. package/src/runtime/owner-control.ts +10 -2
  258. package/src/runtime/runtime-logger.test.ts +1 -1
  259. package/src/runtime/runtime-logger.ts +4 -6
  260. package/src/runtime/runtime.test.ts +88 -22
  261. package/src/sdk/action.ts +2 -2
  262. package/src/sdk/behavior-plugin/index.test.ts +74 -0
  263. package/src/sdk/behavior-plugin/index.ts +335 -0
  264. package/src/sdk/behavior-toolkit/corpse-search.ts +87 -0
  265. package/src/sdk/behavior-toolkit/escape.ts +40 -0
  266. package/src/sdk/behavior-toolkit/index.ts +7 -0
  267. package/src/sdk/behavior-toolkit/kill-flow.ts +299 -0
  268. package/src/sdk/behavior-toolkit/model.ts +263 -0
  269. package/src/sdk/behavior-toolkit/move-gate.ts +52 -0
  270. package/src/sdk/behavior-toolkit/patrol.ts +53 -0
  271. package/src/sdk/behavior-toolkit/search.ts +102 -0
  272. package/src/sdk/index.test.ts +45 -0
  273. package/src/sdk/index.ts +67 -73
  274. package/src/sdk/module-input/index.test.ts +49 -0
  275. package/src/sdk/module-input/index.ts +229 -0
  276. package/src/sdk/perception-plugin/index.test.ts +2 -2
  277. package/src/sdk/perception-plugin/index.ts +51 -142
  278. package/src/sdk/perception-plugin/math.ts +107 -0
  279. package/src/sdk/trigger-plugin/index.test.ts +41 -0
  280. package/src/sdk/trigger-plugin/index.ts +128 -0
  281. package/src/strategies/avoid-lone.ts +21 -10
  282. package/src/strategies/avoid-players.ts +26 -16
  283. package/src/strategies/corpse-patrol.ts +25 -14
  284. package/src/strategies/crab-sabotage.ts +20 -9
  285. package/src/strategies/find-player.ts +33 -21
  286. package/src/strategies/game-utils.ts +1 -1
  287. package/src/strategies/goals/crab-sabotage-top.test.ts +145 -0
  288. package/src/strategies/goals/crab-sabotage-top.ts +32 -69
  289. package/src/strategies/hide.ts +25 -15
  290. package/src/strategies/kill-frenzy.ts +21 -10
  291. package/src/strategies/kill-lone.ts +27 -17
  292. package/src/strategies/kill-target.ts +33 -22
  293. package/src/strategies/lone-kill-task.ts +20 -9
  294. package/src/strategies/move-room.ts +29 -18
  295. package/src/strategies/official-long-behavior.test.ts +89 -0
  296. package/src/strategies/paradise-fish.ts +29 -18
  297. package/src/strategies/pathfind/astar-path.test.ts +127 -2
  298. package/src/strategies/pathfind/astar-path.ts +136 -26
  299. package/src/strategies/patrol.ts +21 -10
  300. package/src/strategies/player-targets.test.ts +10 -0
  301. package/src/strategies/player-targets.ts +13 -0
  302. package/src/strategies/report-patrol.ts +21 -10
  303. package/src/strategies/shrimp-memory.ts +30 -19
  304. package/src/strategies/social-task.ts +34 -23
  305. package/src/strategies/task-kill-report.ts +33 -22
  306. package/src/strategies/task-only.test.ts +99 -85
  307. package/src/strategies/task-only.ts +23 -12
  308. package/src/strategies/task-report.ts +25 -14
  309. package/src/strategies/types.ts +8 -8
  310. package/src/strategies/warrior-memory.ts +29 -19
  311. package/docs/runtime/strategy-runtime.md +0 -111
  312. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +0 -502
  313. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +0 -395
  314. package/skills/clawclaw/references/STRATEGIES.md +0 -76
  315. package/src/commands/strategy.test.ts +0 -209
  316. package/src/commands/strategy.ts +0 -242
  317. package/src/lib/strategy-export.test.ts +0 -406
  318. package/src/lib/strategy-export.ts +0 -381
  319. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +0 -31
  320. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +0 -177
  321. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +0 -191
  322. package/src/runtime/clawclaw/plugins/strategy/index.ts +0 -8
  323. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +0 -412
  324. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +0 -80
  325. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +0 -183
  326. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +0 -29
  327. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +0 -693
  328. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +0 -57
  329. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +0 -168
  330. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +0 -2175
  331. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +0 -1774
  332. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +0 -153
  333. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +0 -443
  334. package/src/sdk/strategy-plugin/index.test.ts +0 -958
  335. package/src/sdk/strategy-plugin/index.ts +0 -1350
@@ -0,0 +1,468 @@
1
+ import type { BehaviorActivationLayer } from '../../../../sdk/behavior-plugin/index.js';
2
+
3
+ export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'system';
4
+ export type BehaviorActivationState = 'running' | 'suspended';
5
+
6
+ export interface BehaviorActivationSpec {
7
+ readonly activationId: string;
8
+ readonly behaviorId: string;
9
+ readonly layer: BehaviorActivationLayer;
10
+ readonly source: BehaviorActivationSource;
11
+ readonly input: Readonly<Record<string, unknown>>;
12
+ readonly requestedAt: number;
13
+ readonly maxRuntimeMs?: number;
14
+ readonly deadlineOutcome?: 'completed' | 'failed';
15
+ readonly triggerId?: string;
16
+ readonly reflexPriority?: number;
17
+ }
18
+
19
+ export interface BehaviorFallbackBinding {
20
+ readonly behaviorId: string;
21
+ readonly input: Readonly<Record<string, unknown>>;
22
+ }
23
+
24
+ export interface BehaviorActivationSnapshot extends BehaviorActivationSpec {
25
+ readonly state: BehaviorActivationState;
26
+ readonly instanceGeneration: number;
27
+ readonly startedAt?: number;
28
+ readonly deadlineAt?: number;
29
+ }
30
+
31
+ export type BehaviorActivationTransitionType =
32
+ | 'started'
33
+ | 'suspended'
34
+ | 'restarted'
35
+ | 'completed'
36
+ | 'failed'
37
+ | 'cancelled'
38
+ | 'replaced'
39
+ | 'ignored';
40
+
41
+ export interface BehaviorActivationTransition {
42
+ readonly type: BehaviorActivationTransitionType;
43
+ readonly activationId: string;
44
+ readonly behaviorId: string;
45
+ readonly layer: BehaviorActivationLayer;
46
+ readonly at: number;
47
+ readonly reason: string;
48
+ readonly instanceGeneration: number;
49
+ readonly replacedByActivationId?: string;
50
+ }
51
+
52
+ export interface BehaviorActivationManagerOptions {
53
+ readonly idleMs?: number;
54
+ readonly createActivationId?: () => string;
55
+ }
56
+
57
+ interface MutableActivation {
58
+ spec: BehaviorActivationSpec;
59
+ state: BehaviorActivationState;
60
+ instanceGeneration: number;
61
+ startedAt?: number;
62
+ deadlineAt?: number;
63
+ }
64
+
65
+ const DEFAULT_IDLE_MS = 500;
66
+
67
+ function cloneInput(input: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>> {
68
+ return Object.freeze(structuredClone(input));
69
+ }
70
+
71
+ function validateIdleMs(value: number): number {
72
+ if (!Number.isSafeInteger(value) || value < 0 || value > 60_000) {
73
+ throw new Error('behavior_idle_ms_invalid');
74
+ }
75
+ return value;
76
+ }
77
+
78
+ function validateSpec(spec: BehaviorActivationSpec): BehaviorActivationSpec {
79
+ if (!spec.activationId.trim()) throw new Error('behavior_activation_id_invalid');
80
+ if (!spec.behaviorId.trim()) throw new Error('behavior_id_invalid');
81
+ if (!['long', 'short', 'reflex'].includes(spec.layer)) {
82
+ throw new Error('behavior_activation_layer_invalid');
83
+ }
84
+ if (!Number.isFinite(spec.requestedAt)) throw new Error('behavior_activation_time_invalid');
85
+ if (
86
+ spec.maxRuntimeMs !== undefined
87
+ && (!Number.isSafeInteger(spec.maxRuntimeMs) || spec.maxRuntimeMs <= 0)
88
+ ) throw new Error('behavior_activation_runtime_invalid');
89
+ if (
90
+ spec.deadlineOutcome !== undefined
91
+ && spec.deadlineOutcome !== 'completed'
92
+ && spec.deadlineOutcome !== 'failed'
93
+ ) throw new Error('behavior_activation_deadline_outcome_invalid');
94
+ if (spec.deadlineOutcome !== undefined && spec.maxRuntimeMs === undefined) {
95
+ throw new Error('behavior_activation_deadline_outcome_without_runtime');
96
+ }
97
+ if (spec.layer === 'reflex') {
98
+ if (!spec.triggerId?.trim()) throw new Error('behavior_reflex_trigger_id_invalid');
99
+ if (!Number.isSafeInteger(spec.reflexPriority)) {
100
+ throw new Error('behavior_reflex_priority_invalid');
101
+ }
102
+ } else if (spec.triggerId !== undefined || spec.reflexPriority !== undefined) {
103
+ throw new Error('behavior_reflex_fields_not_allowed');
104
+ }
105
+ return Object.freeze({
106
+ ...spec,
107
+ input: cloneInput(spec.input),
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Owns the bounded physical-control stack: one long, one short, one reflex.
113
+ * It never imports modules or submits Actions; Behavior Host applies transitions.
114
+ */
115
+ export class BehaviorActivationManager {
116
+ private idleMs: number;
117
+ private readonly createActivationId: () => string;
118
+ private fallback?: BehaviorFallbackBinding;
119
+ private long?: MutableActivation;
120
+ private short?: MutableActivation;
121
+ private reflex?: MutableActivation;
122
+ private longEligibleAt?: number;
123
+ private idleGeneration = 0;
124
+ private fallbackStartedGeneration = -1;
125
+ private sequence = 0;
126
+
127
+ constructor(options: BehaviorActivationManagerOptions = {}) {
128
+ this.idleMs = validateIdleMs(options.idleMs ?? DEFAULT_IDLE_MS);
129
+ this.createActivationId = options.createActivationId
130
+ ?? (() => `behavior-${++this.sequence}`);
131
+ }
132
+
133
+ setIdleMs(idleMs: number, now: number): readonly BehaviorActivationTransition[] {
134
+ this.idleMs = validateIdleMs(idleMs);
135
+ if (!this.short && !this.reflex && (!this.long || this.long.state === 'suspended')) {
136
+ this.longEligibleAt = now + this.idleMs;
137
+ }
138
+ return this.advance(now);
139
+ }
140
+
141
+ idleDelayMs(): number {
142
+ return this.idleMs;
143
+ }
144
+
145
+ bindFallback(binding: BehaviorFallbackBinding | undefined, now: number): readonly BehaviorActivationTransition[] {
146
+ this.fallback = binding
147
+ ? Object.freeze({ behaviorId: binding.behaviorId, input: cloneInput(binding.input) })
148
+ : undefined;
149
+ this.idleGeneration += 1;
150
+ this.fallbackStartedGeneration = -1;
151
+ if (!this.short && !this.reflex && !this.long) this.longEligibleAt = now + this.idleMs;
152
+ return this.advance(now);
153
+ }
154
+
155
+ noteAgentActivity(now: number): readonly BehaviorActivationTransition[] {
156
+ this.idleGeneration += 1;
157
+ this.fallbackStartedGeneration = -1;
158
+ this.longEligibleAt = now + this.idleMs;
159
+ if (this.long?.spec.source !== 'idle') return [];
160
+ const transitions = [this.transition(this.long, 'cancelled', now, 'agent_activity')];
161
+ this.long = undefined;
162
+ return transitions;
163
+ }
164
+
165
+ /**
166
+ * Enter a game boundary where wandering Behaviors cannot keep authority.
167
+ * Finite foreground work is cancelled; an explicit/fallback long Activation
168
+ * is retained as configuration but must later restart from a fresh runner.
169
+ */
170
+ enterBoundary(reason: string, now: number): readonly BehaviorActivationTransition[] {
171
+ const transitions: BehaviorActivationTransition[] = [];
172
+ if (this.reflex) {
173
+ transitions.push(this.transition(this.reflex, 'cancelled', now, reason));
174
+ this.reflex = undefined;
175
+ }
176
+ if (this.short) {
177
+ transitions.push(this.transition(this.short, 'cancelled', now, reason));
178
+ this.short = undefined;
179
+ }
180
+ if (this.long?.state === 'running') {
181
+ this.long.state = 'suspended';
182
+ transitions.push(this.transition(this.long, 'suspended', now, reason));
183
+ }
184
+ this.longEligibleAt = undefined;
185
+ return transitions;
186
+ }
187
+
188
+ /** Starts the one shared hand-back delay after a meeting/loading boundary. */
189
+ leaveBoundary(now: number): readonly BehaviorActivationTransition[] {
190
+ if (this.reflex || this.short) return [];
191
+ if (this.long?.state === 'suspended' || (!this.long && this.fallback)) {
192
+ this.longEligibleAt = now + this.idleMs;
193
+ }
194
+ return this.advance(now);
195
+ }
196
+
197
+ /** Ends every Activation in the current game scope while retaining policy bindings. */
198
+ clearScope(reason: string, now: number): readonly BehaviorActivationTransition[] {
199
+ const transitions: BehaviorActivationTransition[] = [];
200
+ for (const layer of ['reflex', 'short', 'long'] as const) {
201
+ const activation = this[layer];
202
+ if (!activation) continue;
203
+ transitions.push(this.transition(activation, 'cancelled', now, reason));
204
+ this[layer] = undefined;
205
+ }
206
+ this.idleGeneration += 1;
207
+ this.fallbackStartedGeneration = -1;
208
+ this.longEligibleAt = undefined;
209
+ return transitions;
210
+ }
211
+
212
+ startLong(
213
+ spec: Omit<BehaviorActivationSpec, 'layer'> & { readonly layer?: 'long' },
214
+ now: number,
215
+ ): readonly BehaviorActivationTransition[] {
216
+ const next = this.activation({ ...spec, layer: 'long' }, now);
217
+ const transitions: BehaviorActivationTransition[] = [];
218
+ if (this.long) {
219
+ transitions.push(this.transition(this.long, 'replaced', now, 'long_replaced', next.spec.activationId));
220
+ }
221
+ this.long = next;
222
+ this.longEligibleAt = undefined;
223
+ if (this.short || this.reflex) {
224
+ next.state = 'suspended';
225
+ transitions.push(this.transition(next, 'suspended', now, 'higher_layer_active'));
226
+ } else {
227
+ transitions.push(this.transition(next, 'started', now, 'explicit_long_started'));
228
+ }
229
+ return transitions;
230
+ }
231
+
232
+ startShort(
233
+ spec: Omit<BehaviorActivationSpec, 'layer'> & { readonly layer?: 'short' },
234
+ now: number,
235
+ ): readonly BehaviorActivationTransition[] {
236
+ const next = this.activation({ ...spec, layer: 'short' }, now);
237
+ const transitions: BehaviorActivationTransition[] = [];
238
+ if (this.short) {
239
+ transitions.push(this.transition(this.short, 'replaced', now, 'short_replaced', next.spec.activationId));
240
+ }
241
+ this.short = next;
242
+ if (this.long?.state === 'running') {
243
+ this.long.state = 'suspended';
244
+ transitions.push(this.transition(this.long, 'suspended', now, 'short_started'));
245
+ }
246
+ if (this.reflex) {
247
+ next.state = 'suspended';
248
+ transitions.push(this.transition(next, 'suspended', now, 'reflex_active'));
249
+ } else {
250
+ transitions.push(this.transition(next, 'started', now, 'short_started'));
251
+ }
252
+ return transitions;
253
+ }
254
+
255
+ requestReflex(
256
+ spec: Omit<BehaviorActivationSpec, 'layer' | 'source'> & {
257
+ readonly layer?: 'reflex';
258
+ readonly source?: 'trigger';
259
+ },
260
+ now: number,
261
+ ): readonly BehaviorActivationTransition[] {
262
+ const candidate = this.activation({ ...spec, layer: 'reflex', source: 'trigger' }, now);
263
+ const active = this.reflex;
264
+ if (active) {
265
+ const sameTrigger = active.spec.triggerId === candidate.spec.triggerId;
266
+ const higher = (candidate.spec.reflexPriority as number) > (active.spec.reflexPriority as number);
267
+ if (sameTrigger || !higher) {
268
+ return [this.transition(
269
+ candidate,
270
+ 'ignored',
271
+ now,
272
+ sameTrigger ? 'reflex_trigger_already_active' : 'reflex_priority_not_higher',
273
+ )];
274
+ }
275
+ }
276
+
277
+ const transitions: BehaviorActivationTransition[] = [];
278
+ if (active) {
279
+ transitions.push(this.transition(active, 'replaced', now, 'higher_priority_reflex', candidate.spec.activationId));
280
+ }
281
+ this.reflex = candidate;
282
+ if (this.short?.state === 'running') {
283
+ this.short.state = 'suspended';
284
+ transitions.push(this.transition(this.short, 'suspended', now, 'reflex_started'));
285
+ }
286
+ if (this.long?.state === 'running') {
287
+ this.long.state = 'suspended';
288
+ transitions.push(this.transition(this.long, 'suspended', now, 'reflex_started'));
289
+ }
290
+ transitions.push(this.transition(candidate, 'started', now, 'reflex_started'));
291
+ return transitions;
292
+ }
293
+
294
+ finish(
295
+ activationId: string,
296
+ outcome: 'completed' | 'failed',
297
+ reason: string,
298
+ now: number,
299
+ ): readonly BehaviorActivationTransition[] {
300
+ return this.remove(activationId, outcome, reason, now);
301
+ }
302
+
303
+ cancel(activationId: string, reason: string, now: number): readonly BehaviorActivationTransition[] {
304
+ return this.remove(activationId, 'cancelled', reason, now);
305
+ }
306
+
307
+ advance(now: number): readonly BehaviorActivationTransition[] {
308
+ const transitions: BehaviorActivationTransition[] = [];
309
+ for (const activation of [this.reflex, this.short, this.long]) {
310
+ if (activation?.deadlineAt !== undefined && now >= activation.deadlineAt) {
311
+ const outcome = activation.spec.deadlineOutcome ?? 'failed';
312
+ transitions.push(...this.remove(
313
+ activation.spec.activationId,
314
+ outcome,
315
+ outcome === 'completed' ? 'duration_elapsed' : 'deadline_elapsed',
316
+ now,
317
+ ));
318
+ }
319
+ }
320
+ if (this.reflex || this.short) return transitions;
321
+
322
+ if (this.long?.state === 'suspended') {
323
+ if (this.longEligibleAt !== undefined && now >= this.longEligibleAt) {
324
+ this.longEligibleAt = undefined;
325
+ transitions.push(this.restart(this.long, now, 'idle_delay_elapsed'));
326
+ }
327
+ return transitions;
328
+ }
329
+
330
+ if (!this.long && this.fallback && this.longEligibleAt !== undefined && now >= this.longEligibleAt) {
331
+ if (this.fallbackStartedGeneration === this.idleGeneration) return transitions;
332
+ this.fallbackStartedGeneration = this.idleGeneration;
333
+ this.longEligibleAt = undefined;
334
+ const activation = this.activation({
335
+ activationId: this.createActivationId(),
336
+ behaviorId: this.fallback.behaviorId,
337
+ input: this.fallback.input,
338
+ layer: 'long',
339
+ source: 'idle',
340
+ requestedAt: now,
341
+ }, now);
342
+ this.long = activation;
343
+ transitions.push(this.transition(activation, 'started', now, 'idle_fallback_started'));
344
+ }
345
+ return transitions;
346
+ }
347
+
348
+ current(): BehaviorActivationSnapshot | undefined {
349
+ return this.snapshotActivation(
350
+ this.reflex ?? this.short ?? (this.long?.state === 'running' ? this.long : undefined),
351
+ );
352
+ }
353
+
354
+ snapshot(): Readonly<{
355
+ long?: BehaviorActivationSnapshot;
356
+ short?: BehaviorActivationSnapshot;
357
+ reflex?: BehaviorActivationSnapshot;
358
+ fallback?: BehaviorFallbackBinding;
359
+ idleMs: number;
360
+ longEligibleAt?: number;
361
+ }> {
362
+ return Object.freeze({
363
+ ...(this.long ? { long: this.snapshotActivation(this.long) } : {}),
364
+ ...(this.short ? { short: this.snapshotActivation(this.short) } : {}),
365
+ ...(this.reflex ? { reflex: this.snapshotActivation(this.reflex) } : {}),
366
+ ...(this.fallback ? { fallback: structuredClone(this.fallback) } : {}),
367
+ idleMs: this.idleMs,
368
+ ...(this.longEligibleAt !== undefined ? { longEligibleAt: this.longEligibleAt } : {}),
369
+ });
370
+ }
371
+
372
+ isCurrent(activationId: string, instanceGeneration: number): boolean {
373
+ const current = this.current();
374
+ return current?.activationId === activationId
375
+ && current.instanceGeneration === instanceGeneration
376
+ && current.state === 'running';
377
+ }
378
+
379
+ private remove(
380
+ activationId: string,
381
+ outcome: 'completed' | 'failed' | 'cancelled',
382
+ reason: string,
383
+ now: number,
384
+ ): BehaviorActivationTransition[] {
385
+ const layer = this.findLayer(activationId);
386
+ if (!layer) return [];
387
+ const activation = this[layer] as MutableActivation;
388
+ const transitions: BehaviorActivationTransition[] = [
389
+ this.transition(activation, outcome, now, reason),
390
+ ];
391
+ this[layer] = undefined;
392
+
393
+ if (layer === 'reflex') {
394
+ if (this.short) transitions.push(this.restart(this.short, now, 'reflex_ended'));
395
+ else this.longEligibleAt = now + this.idleMs;
396
+ } else if (layer === 'short') {
397
+ if (!this.reflex) this.longEligibleAt = now + this.idleMs;
398
+ } else if (!this.short && !this.reflex) {
399
+ this.longEligibleAt = now + this.idleMs;
400
+ }
401
+ return transitions;
402
+ }
403
+
404
+ private findLayer(activationId: string): BehaviorActivationLayer | undefined {
405
+ if (this.reflex?.spec.activationId === activationId) return 'reflex';
406
+ if (this.short?.spec.activationId === activationId) return 'short';
407
+ if (this.long?.spec.activationId === activationId) return 'long';
408
+ return undefined;
409
+ }
410
+
411
+ private activation(spec: BehaviorActivationSpec, now: number): MutableActivation {
412
+ const validated = validateSpec(spec);
413
+ return {
414
+ spec: validated,
415
+ state: 'running',
416
+ instanceGeneration: 1,
417
+ startedAt: now,
418
+ ...(validated.maxRuntimeMs !== undefined
419
+ ? { deadlineAt: now + validated.maxRuntimeMs }
420
+ : {}),
421
+ };
422
+ }
423
+
424
+ private restart(activation: MutableActivation, now: number, reason: string): BehaviorActivationTransition {
425
+ activation.state = 'running';
426
+ activation.instanceGeneration += 1;
427
+ activation.startedAt = now;
428
+ if (activation.spec.maxRuntimeMs !== undefined) {
429
+ // A suspended activation keeps its original deadline. Fresh restart is
430
+ // about module state and input, not extending its authority lease.
431
+ activation.deadlineAt ??= activation.spec.requestedAt + activation.spec.maxRuntimeMs;
432
+ }
433
+ return this.transition(activation, 'restarted', now, reason);
434
+ }
435
+
436
+ private transition(
437
+ activation: MutableActivation,
438
+ type: BehaviorActivationTransitionType,
439
+ at: number,
440
+ reason: string,
441
+ replacedByActivationId?: string,
442
+ ): BehaviorActivationTransition {
443
+ return Object.freeze({
444
+ type,
445
+ activationId: activation.spec.activationId,
446
+ behaviorId: activation.spec.behaviorId,
447
+ layer: activation.spec.layer,
448
+ at,
449
+ reason,
450
+ instanceGeneration: activation.instanceGeneration,
451
+ ...(replacedByActivationId ? { replacedByActivationId } : {}),
452
+ });
453
+ }
454
+
455
+ private snapshotActivation(
456
+ activation: MutableActivation | undefined,
457
+ ): BehaviorActivationSnapshot | undefined {
458
+ if (!activation) return undefined;
459
+ return Object.freeze({
460
+ ...activation.spec,
461
+ input: cloneInput(activation.spec.input),
462
+ state: activation.state,
463
+ instanceGeneration: activation.instanceGeneration,
464
+ ...(activation.startedAt !== undefined ? { startedAt: activation.startedAt } : {}),
465
+ ...(activation.deadlineAt !== undefined ? { deadlineAt: activation.deadlineAt } : {}),
466
+ });
467
+ }
468
+ }
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { normalizeClawclawBehaviorAction } from './behavior-action.js';
3
+
4
+ describe('normalizeClawclawBehaviorAction', () => {
5
+ it('preserves only the shared allowed Action payload and adds Behavior fences', () => {
6
+ expect(normalizeClawclawBehaviorAction({
7
+ action: 'kill',
8
+ target_seat: 7,
9
+ thinking_content: 'commit',
10
+ }, 12, 4, 3)).toEqual({
11
+ route: 'auto',
12
+ action: {
13
+ action: 'kill',
14
+ target_seat: 7,
15
+ thinking_content: 'commit',
16
+ },
17
+ behaviorOriginEpochSeq: 12,
18
+ behaviorActionSafetyGeneration: 4,
19
+ behaviorActivationGeneration: 3,
20
+ });
21
+ });
22
+
23
+ it('applies authoritative seat validation and rejects voting', () => {
24
+ expect(() => normalizeClawclawBehaviorAction({
25
+ action: 'kill', target_seat: 0,
26
+ }, 12, 4, 1)).toThrowError('invalid_behavior_target');
27
+ expect(() => normalizeClawclawBehaviorAction({
28
+ action: 'vote', target_seat: 3,
29
+ }, 12, 4, 1)).toThrowError('unsupported_behavior_action');
30
+ });
31
+
32
+ it('requires epoch, safety, and activation-generation fences', () => {
33
+ expect(() => normalizeClawclawBehaviorAction({ action: 'think' }, 0, 4, 1))
34
+ .toThrowError('invalid_behavior_action_epoch');
35
+ expect(() => normalizeClawclawBehaviorAction({ action: 'think' }, 12, undefined, 1))
36
+ .toThrowError('invalid_behavior_action_safety_generation');
37
+ expect(() => normalizeClawclawBehaviorAction({ action: 'think' }, 12, 4, 0))
38
+ .toThrowError('invalid_behavior_activation_generation');
39
+ });
40
+ });
@@ -0,0 +1,30 @@
1
+ import type { ClawclawActionRequest } from '../action/index.js';
2
+ import { normalizeClawclawBehaviorActionPayload } from '../action/automated-action-normalization.js';
3
+
4
+ /** Converts a credential-free Behavior Decision into the unified Action capability input. */
5
+ export function normalizeClawclawBehaviorAction(
6
+ value: unknown,
7
+ behaviorOriginEpochSeq: number,
8
+ behaviorActionSafetyGeneration: number | undefined,
9
+ behaviorActivationGeneration: number,
10
+ ): ClawclawActionRequest {
11
+ if (!Number.isInteger(behaviorOriginEpochSeq) || behaviorOriginEpochSeq <= 0) {
12
+ throw new Error('invalid_behavior_action_epoch');
13
+ }
14
+ if (
15
+ !Number.isInteger(behaviorActionSafetyGeneration)
16
+ || behaviorActionSafetyGeneration! < 0
17
+ ) {
18
+ throw new Error('invalid_behavior_action_safety_generation');
19
+ }
20
+ if (!Number.isSafeInteger(behaviorActivationGeneration) || behaviorActivationGeneration <= 0) {
21
+ throw new Error('invalid_behavior_activation_generation');
22
+ }
23
+ return {
24
+ route: 'auto',
25
+ action: normalizeClawclawBehaviorActionPayload(value),
26
+ behaviorOriginEpochSeq,
27
+ behaviorActionSafetyGeneration,
28
+ behaviorActivationGeneration,
29
+ };
30
+ }
@@ -0,0 +1,152 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import { parentPort, workerData } from 'node:worker_threads';
3
+ import type {
4
+ BehaviorInput,
5
+ ClawclawBehavior,
6
+ } from '../../../../sdk/behavior-plugin/index.js';
7
+ import { createBehaviorReadApi } from '../../behavior-read-api.js';
8
+ import { normalizeBehaviorDecision } from '../../behavior-decision.js';
9
+ import {
10
+ resolveBehaviorSource,
11
+ validateClawclawBehaviorModule,
12
+ } from './behavior-module-loader.js';
13
+ import { deepFreezeBehaviorValue } from './behavior-manifest.js';
14
+ import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
15
+ import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
16
+
17
+ interface BehaviorThreadWorkerData {
18
+ readonly poolId: string;
19
+ readonly slotId: number;
20
+ readonly source: ResolvedClawclawBehaviorSource;
21
+ readonly sourceUrl: string;
22
+ }
23
+
24
+ interface BehaviorThreadRunRequest {
25
+ readonly type: 'run';
26
+ readonly poolId: string;
27
+ readonly requestId: string;
28
+ readonly operation: 'decide';
29
+ readonly frame: BehaviorInput;
30
+ readonly observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>;
31
+ }
32
+
33
+ interface BehaviorThreadStopRequest {
34
+ readonly type: 'stop';
35
+ readonly poolId: string;
36
+ readonly requestId: string;
37
+ readonly reason: 'switched' | 'scope_ended' | 'shutdown';
38
+ }
39
+
40
+ function errorMessage(error: unknown): string {
41
+ return error instanceof Error ? error.message : String(error);
42
+ }
43
+
44
+ function errorCode(error: unknown, fallback: string): string {
45
+ const explicit = error && typeof error === 'object' && typeof (error as any).code === 'string'
46
+ ? (error as any).code.trim()
47
+ : '';
48
+ if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(explicit)) return explicit;
49
+ const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(errorMessage(error).trim())?.[1];
50
+ return prefix ?? fallback;
51
+ }
52
+
53
+ const port = parentPort;
54
+ if (!port) throw new Error('behavior_thread_parent_missing');
55
+ const data = workerData as Partial<BehaviorThreadWorkerData> | undefined;
56
+ if (
57
+ !data
58
+ || typeof data.poolId !== 'string'
59
+ || typeof data.slotId !== 'number'
60
+ || !data.source
61
+ || typeof data.sourceUrl !== 'string'
62
+ ) throw new Error('behavior_thread_worker_data_invalid');
63
+
64
+ function send(value: Readonly<Record<string, unknown>>): void {
65
+ port!.postMessage({ ...value, poolId: data!.poolId!, slotId: data!.slotId! });
66
+ }
67
+
68
+ let loaded: ReturnType<typeof validateClawclawBehaviorModule>;
69
+ let execution: ResolvedClawclawBehaviorSource['execution'];
70
+ try {
71
+ const behaviorModule = await import(data.sourceUrl) as Record<string, unknown>;
72
+ // The parent validates immediately before spawn; repeat after the complete
73
+ // module graph has loaded so an edit in that narrow window cannot enter the pool.
74
+ resolveBehaviorSource(data.source);
75
+ loaded = validateClawclawBehaviorModule(behaviorModule, data.source);
76
+ execution = loaded.manifest.execution ?? 'parallel';
77
+ } catch (error) {
78
+ send({
79
+ type: 'error',
80
+ code: errorCode(error, 'BEHAVIOR_THREAD_START_FAILED'),
81
+ message: errorMessage(error),
82
+ });
83
+ throw error;
84
+ }
85
+
86
+ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest): Promise<void> {
87
+ if (
88
+ !request
89
+ || typeof request !== 'object'
90
+ || request.poolId !== data!.poolId
91
+ || typeof request.requestId !== 'string'
92
+ ) throw new Error('behavior_thread_request_invalid');
93
+ if (request.type === 'stop') {
94
+ send({ type: 'stopped', requestId: request.requestId });
95
+ return;
96
+ }
97
+ if (request.type !== 'run' || request.operation !== 'decide') {
98
+ throw new Error('behavior_thread_request_invalid');
99
+ }
100
+ if (!request.frame || typeof request.frame !== 'object') {
101
+ throw new Error('behavior_thread_frame_invalid');
102
+ }
103
+ const startedAt = performance.now();
104
+ let queryCount = 0;
105
+ let invocationActive = true;
106
+ const input = deepFreezeBehaviorValue(structuredClone(request.frame));
107
+ // Cross-tick computations are isolated. The module and constructor are
108
+ // preloaded once per slot, but no mutable behavior `this` state crosses
109
+ // frame boundaries or becomes dependent on random slot assignment.
110
+ const instance: ClawclawBehavior = new loaded.BehaviorClass();
111
+ if (!instance || typeof instance.decide !== 'function') {
112
+ throw new Error('behavior_thread_instance_invalid');
113
+ }
114
+ const api = createBehaviorReadApi(input, {
115
+ onQuery: () => { queryCount += 1; },
116
+ isActive: () => invocationActive,
117
+ ...(request.observationSnapshot === undefined
118
+ ? {}
119
+ : { observationSnapshot: request.observationSnapshot }),
120
+ });
121
+ try {
122
+ if (execution !== 'parallel') throw new Error('behavior_thread_decide_not_available');
123
+ const result = normalizeBehaviorDecision(await instance.decide(input, api), { finite: false });
124
+ send({
125
+ type: 'result',
126
+ requestId: request.requestId,
127
+ result,
128
+ queryCount,
129
+ durationMs: Math.round((performance.now() - startedAt) * 1_000) / 1_000,
130
+ });
131
+ } finally {
132
+ invocationActive = false;
133
+ }
134
+ }
135
+
136
+ let operationTail = Promise.resolve();
137
+ port.on('message', (request: BehaviorThreadRunRequest | BehaviorThreadStopRequest) => {
138
+ operationTail = operationTail.then(() => run(request)).catch((error) => {
139
+ send({
140
+ type: 'error',
141
+ ...(typeof request?.requestId === 'string' ? { requestId: request.requestId } : {}),
142
+ code: errorCode(error, 'BEHAVIOR_THREAD_OPERATION_FAILED'),
143
+ message: errorMessage(error),
144
+ });
145
+ });
146
+ });
147
+
148
+ send({
149
+ type: 'ready',
150
+ behaviorId: data.source.id,
151
+ execution,
152
+ });