@myclaw163/clawclaw-cli 0.7.15 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +7 -4
  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 +3 -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 +286 -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 +389 -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 -1994
  331. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +0 -1579
  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,1347 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type {
3
+ BehaviorDecision,
4
+ BehaviorFinish,
5
+ BehaviorInput,
6
+ BehaviorStatus,
7
+ ClawclawResolvedResourceMetadata,
8
+ GameAction,
9
+ } from '../../../../sdk/behavior-plugin/index.js';
10
+ import { resolveClawclawResourceMetadata } from '../../../../sdk/behavior-plugin/index.js';
11
+ import type { ActionCaller } from '../../../framework/contracts.js';
12
+ import type { RuntimeScope } from '../../../framework/state/types.js';
13
+ import type {
14
+ RuntimeEpochCatchUp,
15
+ RuntimeEpochPlugin,
16
+ RuntimeEpochPluginContext,
17
+ RuntimeEpochPluginInput,
18
+ RuntimeEpochPluginResult,
19
+ RuntimeEventProposal,
20
+ } from '../../../framework/plugins/contracts.js';
21
+ import { createBehaviorInput } from '../../behavior-input.js';
22
+ import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
23
+ import { isClawclawRuntimeState } from '../../runtime-state.js';
24
+ import { CLAWCLAW_ACTION_CAPABILITY, CLAWCLAW_ACTION_PLUGIN_ID } from '../action/index.js';
25
+ import { CLAWCLAW_DERIVED_EVENT_PLUGIN_ID } from '../derived-event/index.js';
26
+ import { CLAWCLAW_GAME_QUERY_PLUGIN_ID } from '../game-query/index.js';
27
+ import { CLAWCLAW_PERCEPTION_PLUGIN_ID } from '../perception/index.js';
28
+ import {
29
+ CLAWCLAW_TRIGGER_PLUGIN_ID,
30
+ type BehaviorReflexActivationDriver,
31
+ type BehaviorReflexActivationRequest,
32
+ type BehaviorReflexActivationResult,
33
+ } from '../trigger/contracts.js';
34
+ import {
35
+ BehaviorActivationManager,
36
+ type BehaviorActivationSnapshot,
37
+ type BehaviorActivationSource,
38
+ type BehaviorActivationTransition,
39
+ } from './activation-manager.js';
40
+ import { normalizeClawclawBehaviorAction } from './behavior-action.js';
41
+ import type { ClawclawBehaviorCatalog } from './behavior-catalog.js';
42
+ import type { PreparedClawclawBehavior } from './behavior-normalization.js';
43
+ import { ClawclawBehaviorRunner } from './behavior-runner.js';
44
+ import type {
45
+ ClawclawBehaviorControlDriver,
46
+ ClawclawBehaviorControlHandle,
47
+ } from './control-driver.js';
48
+
49
+ export const CLAWCLAW_BEHAVIOR_PLUGIN_ID = 'clawclaw.behavior';
50
+ export const CLAWCLAW_BEHAVIOR_STATE_TOPIC = 'behavior.status';
51
+ export const CLAWCLAW_BEHAVIOR_LIFECYCLE_EVENT_TYPES = Object.freeze([
52
+ 'behavior.started',
53
+ 'behavior.suspended',
54
+ 'behavior.restarted',
55
+ 'behavior.completed',
56
+ 'behavior.failed',
57
+ 'behavior.cancelled',
58
+ 'behavior.replaced',
59
+ ] as const);
60
+
61
+ export interface ClawclawRoleFallbackBehavior {
62
+ readonly behaviorId: string;
63
+ readonly input?: Readonly<Record<string, unknown>>;
64
+ }
65
+
66
+ export type ClawclawRoleFallbackBehaviors = Readonly<Record<
67
+ string,
68
+ Readonly<ClawclawRoleFallbackBehavior> | undefined
69
+ >>;
70
+
71
+ const BEHAVIOR_COMPUTATION_SCHEMA = 1;
72
+ const DEFAULT_DECISION_TIMEOUT_MS = 4_000;
73
+ const DEFAULT_SHORT_MAX_RUNTIME_MS = 120_000;
74
+ const BACKEND_STRATEGY_REPORT_LOCALE = 'zh-CN';
75
+ const BACKEND_STRATEGY_REPORT_RETRY_MS = 1_000;
76
+
77
+ interface BackendStrategyReportTarget extends ClawclawResolvedResourceMetadata {
78
+ readonly fingerprint: string;
79
+ }
80
+
81
+ interface BackendStrategyReportAttempt {
82
+ readonly lifecycleGeneration: number;
83
+ readonly fingerprint: string;
84
+ }
85
+
86
+ function isSuccessfulBackendStrategyReport(value: unknown): boolean {
87
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
88
+ const result = value as Record<string, unknown>;
89
+ if (
90
+ result.status !== 'success'
91
+ || result.source !== 'backend'
92
+ || result.actionOutcome !== 'confirmed'
93
+ ) return false;
94
+ const response = result.value;
95
+ if (!response || typeof response !== 'object' || Array.isArray(response)) return false;
96
+ const root = response as Record<string, unknown>;
97
+ const data = root.data;
98
+ return root.success === true
99
+ && !!data
100
+ && typeof data === 'object'
101
+ && !Array.isArray(data)
102
+ && (data as Record<string, unknown>).ok === true;
103
+ }
104
+
105
+ export interface ClawclawBehaviorPluginOptions {
106
+ readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
107
+ readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
108
+ readonly manager?: BehaviorActivationManager;
109
+ readonly driver?: ClawclawBehaviorControlDriver;
110
+ readonly after?: readonly string[];
111
+ readonly eventTypes?: readonly string[];
112
+ readonly timeoutMs?: number;
113
+ readonly decisionTimeoutMs?: number;
114
+ readonly catchUp?: RuntimeEpochCatchUp;
115
+ readonly now?: () => number;
116
+ readonly createActivationId?: () => string;
117
+ }
118
+
119
+ export interface StartBehaviorOptions {
120
+ readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system'>;
121
+ readonly maxRuntimeMs?: number;
122
+ }
123
+
124
+ export interface ClawclawBehaviorHostStatus {
125
+ readonly running: boolean;
126
+ readonly current?: Readonly<BehaviorActivationSnapshot>;
127
+ readonly stack: ReturnType<BehaviorActivationManager['snapshot']>;
128
+ }
129
+
130
+ interface ActivationRuntime {
131
+ readonly activationId: string;
132
+ readonly behaviorId: string;
133
+ prepared: PreparedClawclawBehavior;
134
+ runner?: ClawclawBehaviorRunner;
135
+ instanceGeneration?: number;
136
+ lastCommittedBackendTick?: number;
137
+ lastStatus?: Readonly<BehaviorStatus>;
138
+ committedActionDedupeKeys: Map<string, number>;
139
+ }
140
+
141
+ interface BehaviorComputationProposal {
142
+ readonly schema: typeof BEHAVIOR_COMPUTATION_SCHEMA;
143
+ readonly kind:
144
+ | 'inactive'
145
+ | 'waiting_for_state'
146
+ | 'boundary'
147
+ | 'game_over'
148
+ | 'player_inactive'
149
+ | 'control_held'
150
+ | 'cadence_skip'
151
+ | 'serial'
152
+ | 'parallel'
153
+ | 'module_error';
154
+ readonly activationId?: string;
155
+ readonly instanceGeneration?: number;
156
+ readonly eventIds?: readonly string[];
157
+ readonly observationRevision?: number;
158
+ readonly decision?: Readonly<BehaviorDecision>;
159
+ readonly errorCode?: string;
160
+ }
161
+
162
+ function errorCode(error: unknown, fallback = 'BEHAVIOR_HOST_FAILED'): string {
163
+ const message = error instanceof Error ? error.message : String(error);
164
+ return /^[A-Za-z][A-Za-z0-9_.:-]{0,159}$/.test(message) ? message : fallback;
165
+ }
166
+
167
+ function proposal(value: unknown): BehaviorComputationProposal {
168
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
169
+ throw new Error('behavior_computation_invalid');
170
+ }
171
+ const parsed = value as BehaviorComputationProposal;
172
+ if (parsed.schema !== BEHAVIOR_COMPUTATION_SCHEMA) {
173
+ throw new Error('behavior_computation_invalid');
174
+ }
175
+ return parsed;
176
+ }
177
+
178
+ function currentRuntimeSnapshot(
179
+ manager: BehaviorActivationManager,
180
+ activationId: string,
181
+ ): BehaviorActivationSnapshot | undefined {
182
+ const snapshot = manager.snapshot();
183
+ return [snapshot.reflex, snapshot.short, snapshot.long]
184
+ .find((candidate) => candidate?.activationId === activationId);
185
+ }
186
+
187
+ function runtimeMs(
188
+ prepared: PreparedClawclawBehavior,
189
+ rawInput: Readonly<Record<string, unknown>>,
190
+ override?: number,
191
+ ): number | undefined {
192
+ const base = override ?? prepared.timing?.duration_ms
193
+ ?? prepared.timing?.timeout_ms
194
+ ?? prepared.manifest.runtime?.defaultMs;
195
+ return base === undefined
196
+ ? undefined
197
+ : base + (prepared.manifest.runtime?.controlGraceMs ?? 0);
198
+ }
199
+
200
+ function deadlineOutcome(
201
+ prepared: PreparedClawclawBehavior,
202
+ rawInput: Readonly<Record<string, unknown>>,
203
+ ): 'completed' | 'failed' | undefined {
204
+ if (rawInput.duration_ms !== undefined) return 'completed';
205
+ if (rawInput.timeout_ms !== undefined) return 'failed';
206
+ return prepared.manifest.runtime?.deadlineOutcome;
207
+ }
208
+
209
+ function eventIds(input: Readonly<BehaviorInput>): readonly string[] {
210
+ return input.events.map((event) => event.eventId);
211
+ }
212
+
213
+ function sameStrings(left: readonly string[], right: readonly string[]): boolean {
214
+ return left.length === right.length && left.every((value, index) => value === right[index]);
215
+ }
216
+
217
+ function normalizeRoleFallbackBehaviors(
218
+ value: ClawclawRoleFallbackBehaviors | undefined,
219
+ ): Map<string, Readonly<ClawclawRoleFallbackBehavior>> {
220
+ const result = new Map<string, Readonly<ClawclawRoleFallbackBehavior>>();
221
+ for (const [role, binding] of Object.entries(value ?? {})) {
222
+ if (!role.trim() || !binding) continue;
223
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(binding.behaviorId)) {
224
+ throw new Error('behavior_fallback_id_invalid');
225
+ }
226
+ result.set(role, Object.freeze({
227
+ behaviorId: binding.behaviorId,
228
+ input: Object.freeze(structuredClone(binding.input ?? {})),
229
+ }));
230
+ }
231
+ return result;
232
+ }
233
+
234
+ function lifecycleEvent(transition: BehaviorActivationTransition): RuntimeEventProposal | undefined {
235
+ if (transition.type === 'ignored') return undefined;
236
+ return {
237
+ type: `behavior.${transition.type}`,
238
+ dedupeKey: `${transition.activationId}:${transition.instanceGeneration}:${transition.type}`,
239
+ payload: {
240
+ activation_id: transition.activationId,
241
+ behavior: transition.behaviorId,
242
+ layer: transition.layer,
243
+ transition: transition.type,
244
+ reason: transition.reason,
245
+ instance_generation: transition.instanceGeneration,
246
+ ...(transition.replacedByActivationId === undefined
247
+ ? {}
248
+ : { replaced_by_activation_id: transition.replacedByActivationId }),
249
+ },
250
+ };
251
+ }
252
+
253
+ function asActionCaller(caller: ClawclawBehaviorControlHandle['caller']): ActionCaller {
254
+ return caller as unknown as ActionCaller;
255
+ }
256
+
257
+ /**
258
+ * The sole long/short/reflex execution host. Activation policy is separate
259
+ * from module code; every layer runs the same ClawclawBehavior contract.
260
+ */
261
+ export class ClawclawBehaviorPlugin
262
+ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriver {
263
+ readonly kind = 'epoch' as const;
264
+ readonly id = CLAWCLAW_BEHAVIOR_PLUGIN_ID;
265
+ readonly version = '3';
266
+ readonly after: readonly string[];
267
+ readonly consumes = { events: ['*'] } as const;
268
+ readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
269
+ readonly capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY] } as const;
270
+ readonly catchUp: RuntimeEpochCatchUp;
271
+ readonly maxInFlight = 10;
272
+ readonly timeoutMs: number;
273
+ readonly failurePolicy = 'failed_completion' as const;
274
+
275
+ private readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
276
+ private readonly manager: BehaviorActivationManager;
277
+ private readonly now: () => number;
278
+ private readonly createActivationId: () => string;
279
+ private readonly decisionTimeoutMs: number;
280
+ private readonly observationMemory = new ClawclawBehaviorObservationMemory();
281
+ private readonly runtimes = new Map<string, ActivationRuntime>();
282
+ private readonly controls = new Map<string, ClawclawBehaviorControlHandle>();
283
+ private readonly pendingLifecycleEvents: RuntimeEventProposal[] = [];
284
+ private readonly decisionControllers = new Map<string, Set<AbortController>>();
285
+ private controlTail = Promise.resolve();
286
+ private driver?: ClawclawBehaviorControlDriver;
287
+ private scope?: Readonly<RuntimeScope>;
288
+ private diagnostic?: RuntimeEpochPluginContext<Record<string, any>>['diagnostic'];
289
+ private boundaryActive = false;
290
+ private stopped = false;
291
+ private lastCommittedEpochSeq = 0;
292
+ private fallbackPrepared?: PreparedClawclawBehavior;
293
+ private fallbackPreparedUsed = false;
294
+ private fallbackBehaviors = new Map<string, Readonly<ClawclawRoleFallbackBehavior>>();
295
+ private fallbackConfigGeneration = 1;
296
+ private appliedFallbackKey?: string;
297
+ private manualFallbackOverride = false;
298
+ private backendStrategyReportTarget?: BackendStrategyReportTarget;
299
+ private backendStrategyReportAcknowledgedFingerprint?: string;
300
+ private backendStrategyReportInFlight?: BackendStrategyReportAttempt;
301
+ private backendStrategyReportTimer?: ReturnType<typeof setTimeout>;
302
+ private backendStrategyReportContext?: RuntimeEpochPluginContext<Record<string, any>>;
303
+ private backendStrategyReportEligible = false;
304
+ private backendStrategyReportLifecycleGeneration = 0;
305
+
306
+ constructor(options: ClawclawBehaviorPluginOptions) {
307
+ this.catalog = options.catalog;
308
+ this.fallbackBehaviors = normalizeRoleFallbackBehaviors(options.fallbackBehaviors);
309
+ this.manager = options.manager ?? new BehaviorActivationManager();
310
+ this.driver = options.driver;
311
+ this.now = options.now ?? Date.now;
312
+ this.createActivationId = options.createActivationId ?? randomUUID;
313
+ this.decisionTimeoutMs = options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
314
+ this.after = [...(options.after ?? [
315
+ CLAWCLAW_ACTION_PLUGIN_ID,
316
+ CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
317
+ CLAWCLAW_GAME_QUERY_PLUGIN_ID,
318
+ CLAWCLAW_PERCEPTION_PLUGIN_ID,
319
+ CLAWCLAW_TRIGGER_PLUGIN_ID,
320
+ ])];
321
+ this.catchUp = options.catchUp ?? 'strict_ordered';
322
+ this.timeoutMs = options.timeoutMs ?? Math.max(this.decisionTimeoutMs + 1_000, 5_000);
323
+ const eventTypes = new Set([
324
+ ...CLAWCLAW_BEHAVIOR_LIFECYCLE_EVENT_TYPES,
325
+ ...(options.eventTypes ?? []),
326
+ ]);
327
+ this.produces = {
328
+ states: [CLAWCLAW_BEHAVIOR_STATE_TOPIC],
329
+ events: [...eventTypes],
330
+ };
331
+ }
332
+
333
+ attachDriver(driver: ClawclawBehaviorControlDriver): void {
334
+ if (this.driver && this.driver !== driver) throw new Error('behavior_control_driver_already_attached');
335
+ this.driver = driver;
336
+ }
337
+
338
+ async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
339
+ this.scope = context.scope;
340
+ this.diagnostic = context.diagnostic;
341
+ this.stopped = false;
342
+ await this.applyTransitions(this.manager.leaveBoundary(this.now()));
343
+ }
344
+
345
+ status(): ClawclawBehaviorHostStatus {
346
+ const current = this.manager.current();
347
+ return Object.freeze({
348
+ running: current !== undefined,
349
+ ...(current === undefined ? {} : { current }),
350
+ stack: this.manager.snapshot(),
351
+ });
352
+ }
353
+
354
+ setIdleMs(idleMs: number): Promise<void> {
355
+ return this.enqueueControl(async () => {
356
+ await this.applyTransitions(this.manager.setIdleMs(idleMs, this.now()));
357
+ });
358
+ }
359
+
360
+ configureFallbackBehaviors(bindings: ClawclawRoleFallbackBehaviors): Promise<void> {
361
+ return this.enqueueControl(async () => {
362
+ this.fallbackBehaviors = normalizeRoleFallbackBehaviors(bindings);
363
+ this.fallbackConfigGeneration += 1;
364
+ this.appliedFallbackKey = undefined;
365
+ this.manualFallbackOverride = false;
366
+ });
367
+ }
368
+
369
+ bindFallback(
370
+ behaviorId: string,
371
+ input: Readonly<Record<string, unknown>>,
372
+ ): Promise<void> {
373
+ return this.enqueueControl(async () => {
374
+ const prepared = await this.catalog.prepare(behaviorId, input);
375
+ this.manualFallbackOverride = true;
376
+ this.fallbackPrepared = prepared;
377
+ this.fallbackPreparedUsed = false;
378
+ await this.applyTransitions(this.manager.bindFallback({
379
+ behaviorId,
380
+ input: prepared.input,
381
+ }, this.now()));
382
+ });
383
+ }
384
+
385
+ clearFallback(): Promise<void> {
386
+ return this.enqueueControl(async () => {
387
+ this.manualFallbackOverride = true;
388
+ this.fallbackPrepared = undefined;
389
+ this.fallbackPreparedUsed = false;
390
+ await this.applyTransitions(this.manager.bindFallback(undefined, this.now()));
391
+ });
392
+ }
393
+
394
+ startLong(
395
+ behaviorId: string,
396
+ input: Readonly<Record<string, unknown>>,
397
+ options: StartBehaviorOptions,
398
+ ): Promise<Readonly<BehaviorActivationSnapshot>> {
399
+ return this.startLayer('long', behaviorId, input, options);
400
+ }
401
+
402
+ startShort(
403
+ behaviorId: string,
404
+ input: Readonly<Record<string, unknown>>,
405
+ options: StartBehaviorOptions,
406
+ ): Promise<Readonly<BehaviorActivationSnapshot>> {
407
+ return this.startLayer('short', behaviorId, input, options);
408
+ }
409
+
410
+ cancel(activationId: string, reason = 'cancelled_by_control'): Promise<void> {
411
+ return this.enqueueControl(async () => {
412
+ await this.applyTransitions(this.manager.cancel(activationId, reason, this.now()));
413
+ });
414
+ }
415
+
416
+ noteAgentActivity(): Promise<void> {
417
+ return this.enqueueControl(async () => {
418
+ await this.applyTransitions(this.manager.noteAgentActivity(this.now()));
419
+ });
420
+ }
421
+
422
+ async requestReflex(
423
+ request: Readonly<BehaviorReflexActivationRequest>,
424
+ guard?: Readonly<{ isCurrent(): boolean }>,
425
+ ): Promise<BehaviorReflexActivationResult> {
426
+ if (this.stopped || !this.scope) return { accepted: false, reason: 'activation_ineligible' };
427
+ if (guard && !guard.isCurrent()) return { accepted: false, reason: 'stale_request' };
428
+ if (
429
+ request.scope.sessionId !== this.scope.sessionId
430
+ || request.scope.segmentId !== this.scope.segmentId
431
+ || request.epochId <= this.lastCommittedEpochSeq
432
+ ) return { accepted: false, reason: 'stale_request' };
433
+ if (!this.catalog.has(request.behavior)) return { accepted: false, reason: 'binding_invalid' };
434
+ let prepared: PreparedClawclawBehavior;
435
+ try {
436
+ prepared = await this.catalog.prepare(request.behavior, request.behaviorInput);
437
+ } catch {
438
+ return { accepted: false, reason: 'binding_invalid' };
439
+ }
440
+ if (guard && !guard.isCurrent()) return { accepted: false, reason: 'stale_request' };
441
+ const activeReflex = this.manager.snapshot().reflex;
442
+ if (activeReflex) {
443
+ if (activeReflex.triggerId === request.triggerId) {
444
+ return { accepted: false, reason: 'same_trigger_active' };
445
+ }
446
+ if ((activeReflex.reflexPriority ?? 0) >= request.reflexPriority) {
447
+ return { accepted: false, reason: 'reflex_priority_not_higher' };
448
+ }
449
+ }
450
+ const interrupted = this.manager.current();
451
+ if (interrupted) this.interruptDecisions(interrupted.activationId, 'behavior_reflex_preempted');
452
+ return this.enqueueControl(async () => {
453
+ if (this.stopped || !this.scope) return { accepted: false, reason: 'activation_ineligible' };
454
+ if (guard && !guard.isCurrent()) return { accepted: false, reason: 'stale_request' };
455
+ if (
456
+ request.scope.sessionId !== this.scope.sessionId
457
+ || request.scope.segmentId !== this.scope.segmentId
458
+ || request.epochId <= this.lastCommittedEpochSeq
459
+ ) return { accepted: false, reason: 'stale_request' };
460
+ const activationId = this.createActivationId();
461
+ const transitions = this.manager.requestReflex({
462
+ activationId,
463
+ behaviorId: request.behavior,
464
+ input: prepared.input,
465
+ requestedAt: this.now(),
466
+ maxRuntimeMs: request.maxRuntimeMs,
467
+ deadlineOutcome: 'failed',
468
+ triggerId: request.triggerId,
469
+ reflexPriority: request.reflexPriority,
470
+ }, this.now());
471
+ const ignored = transitions.find((entry) => entry.type === 'ignored');
472
+ if (ignored) {
473
+ return {
474
+ accepted: false,
475
+ reason: ignored.reason === 'reflex_trigger_already_active'
476
+ ? 'same_trigger_active'
477
+ : 'reflex_priority_not_higher',
478
+ };
479
+ }
480
+ this.runtimes.set(activationId, {
481
+ activationId,
482
+ behaviorId: request.behavior,
483
+ prepared,
484
+ committedActionDedupeKeys: new Map(),
485
+ });
486
+ const replaced = transitions.find((entry) => entry.type === 'replaced');
487
+ await this.applyTransitions(transitions);
488
+ return {
489
+ accepted: true,
490
+ activationId,
491
+ ...(replaced === undefined ? {} : { replacedActivationId: replaced.activationId }),
492
+ };
493
+ });
494
+ }
495
+
496
+ async update(
497
+ input: RuntimeEpochPluginInput<Record<string, any>>,
498
+ context: RuntimeEpochPluginContext<Record<string, any>>,
499
+ ): Promise<RuntimeEpochPluginResult> {
500
+ this.scope = context.scope;
501
+ const current = this.manager.current();
502
+ const base = {
503
+ schema: BEHAVIOR_COMPUTATION_SCHEMA,
504
+ ...(current === undefined ? {} : {
505
+ activationId: current.activationId,
506
+ instanceGeneration: current.instanceGeneration,
507
+ }),
508
+ } as const;
509
+ if (!current) {
510
+ return { outcome: 'processed', proposal: { ...base, kind: 'inactive' } satisfies BehaviorComputationProposal };
511
+ }
512
+ const frame = createBehaviorInput(input, current.input);
513
+ if (!frame) {
514
+ return { outcome: 'processed', proposal: { ...base, kind: 'waiting_for_state' } satisfies BehaviorComputationProposal };
515
+ }
516
+ if (frame.gameState.phase === 'game_over') {
517
+ return { outcome: 'processed', proposal: { ...base, kind: 'game_over' } satisfies BehaviorComputationProposal };
518
+ }
519
+ if (frame.gameState.you?.is_alive === false) {
520
+ return { outcome: 'processed', proposal: { ...base, kind: 'player_inactive' } satisfies BehaviorComputationProposal };
521
+ }
522
+ const meetingShort = frame.gameState.phase === 'meeting' && current.layer === 'short';
523
+ if (frame.gameState.phase !== 'wandering' && !meetingShort) {
524
+ return { outcome: 'processed', proposal: { ...base, kind: 'boundary' } satisfies BehaviorComputationProposal };
525
+ }
526
+ const runtime = this.runtimes.get(current.activationId);
527
+ const control = this.controls.get(current.activationId);
528
+ if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration) {
529
+ return { outcome: 'processed', proposal: { ...base, kind: 'control_held' } satisfies BehaviorComputationProposal };
530
+ }
531
+ if (!control?.isAuthorized()) {
532
+ return { outcome: 'processed', proposal: { ...base, kind: 'control_held' } satisfies BehaviorComputationProposal };
533
+ }
534
+ const backendTick = Number(frame.gameState.tick ?? frame.epochId);
535
+ if (
536
+ runtime.lastCommittedBackendTick !== undefined
537
+ && backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks
538
+ ) {
539
+ return { outcome: 'processed', proposal: { ...base, kind: 'cadence_skip' } satisfies BehaviorComputationProposal };
540
+ }
541
+ const observation = this.observationMemory.capture(frame);
542
+ if (runtime.runner.execution === 'serial') {
543
+ return {
544
+ outcome: 'processed',
545
+ proposal: {
546
+ ...base,
547
+ kind: 'serial',
548
+ eventIds: eventIds(frame),
549
+ observationRevision: observation.revision,
550
+ } satisfies BehaviorComputationProposal,
551
+ };
552
+ }
553
+ try {
554
+ const decision = await this.withDecisionTimeout(
555
+ signal => runtime.runner!.decideParallel(frame, signal, observation),
556
+ context.signal,
557
+ current.activationId,
558
+ );
559
+ return {
560
+ outcome: 'processed',
561
+ proposal: {
562
+ ...base,
563
+ kind: 'parallel',
564
+ eventIds: eventIds(frame),
565
+ observationRevision: observation.revision,
566
+ decision,
567
+ } satisfies BehaviorComputationProposal,
568
+ };
569
+ } catch (error) {
570
+ return {
571
+ outcome: 'processed',
572
+ proposal: {
573
+ ...base,
574
+ kind: 'module_error',
575
+ errorCode: errorCode(error, 'BEHAVIOR_DECIDE_FAILED'),
576
+ } satisfies BehaviorComputationProposal,
577
+ };
578
+ }
579
+ }
580
+
581
+ commit(
582
+ input: RuntimeEpochPluginInput<Record<string, any>>,
583
+ computation: Readonly<RuntimeEpochPluginResult>,
584
+ context: RuntimeEpochPluginContext<Record<string, any>>,
585
+ ): Promise<RuntimeEpochPluginResult> {
586
+ return this.enqueueControl(() => this.commitOrdered(input, proposal(computation.proposal), context));
587
+ }
588
+
589
+ async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
590
+ await this.enqueueControl(async () => {
591
+ this.stopped = true;
592
+ this.resetBackendStrategyReporting();
593
+ for (const controllers of this.decisionControllers.values()) {
594
+ for (const controller of controllers) controller.abort(new Error(reason));
595
+ }
596
+ this.decisionControllers.clear();
597
+ const runnerReason = reason === 'shutdown' ? 'shutdown' : 'scope_ended';
598
+ const runners = [...this.runtimes.values()].flatMap((runtime) => {
599
+ const runner = runtime.runner;
600
+ runtime.runner = undefined;
601
+ runtime.instanceGeneration = undefined;
602
+ return runner ? [runner] : [];
603
+ });
604
+ await Promise.all(runners.map((runner) => runner.stop(runnerReason)));
605
+ await this.applyTransitions(this.manager.clearScope(reason, this.now()));
606
+ this.runtimes.clear();
607
+ for (const handle of this.controls.values()) handle.release(reason);
608
+ this.controls.clear();
609
+ this.observationMemory.clear();
610
+ this.scope = undefined;
611
+ this.diagnostic = undefined;
612
+ this.boundaryActive = false;
613
+ this.pendingLifecycleEvents.length = 0;
614
+ this.lastCommittedEpochSeq = 0;
615
+ });
616
+ }
617
+
618
+ private startLayer(
619
+ layer: 'long' | 'short',
620
+ behaviorId: string,
621
+ input: Readonly<Record<string, unknown>>,
622
+ options: StartBehaviorOptions,
623
+ ): Promise<Readonly<BehaviorActivationSnapshot>> {
624
+ return this.enqueueControl(async () => {
625
+ if (this.stopped || !this.scope) throw new Error('behavior_host_not_active');
626
+ const prepared = await this.catalog.prepare(behaviorId, input);
627
+ const activationId = this.createActivationId();
628
+ const maxRuntimeMs = layer === 'short'
629
+ ? runtimeMs(prepared, input, options.maxRuntimeMs) ?? DEFAULT_SHORT_MAX_RUNTIME_MS
630
+ : options.maxRuntimeMs;
631
+ const outcome = maxRuntimeMs === undefined
632
+ ? undefined
633
+ : deadlineOutcome(prepared, input) ?? 'failed';
634
+ const spec = {
635
+ activationId,
636
+ behaviorId,
637
+ source: options.source,
638
+ input: prepared.input,
639
+ requestedAt: this.now(),
640
+ ...(maxRuntimeMs === undefined ? {} : {
641
+ maxRuntimeMs,
642
+ deadlineOutcome: outcome,
643
+ }),
644
+ } as const;
645
+ this.runtimes.set(activationId, {
646
+ activationId,
647
+ behaviorId,
648
+ prepared,
649
+ committedActionDedupeKeys: new Map(),
650
+ });
651
+ const transitions = layer === 'long'
652
+ ? this.manager.startLong(spec, this.now())
653
+ : this.manager.startShort(spec, this.now());
654
+ await this.applyTransitions(transitions);
655
+ const snapshot = currentRuntimeSnapshot(this.manager, activationId);
656
+ if (!snapshot) throw new Error('behavior_activation_start_failed');
657
+ return snapshot;
658
+ });
659
+ }
660
+
661
+ private async commitOrdered(
662
+ input: RuntimeEpochPluginInput<Record<string, any>>,
663
+ computed: BehaviorComputationProposal,
664
+ context: RuntimeEpochPluginContext<Record<string, any>>,
665
+ ): Promise<RuntimeEpochPluginResult> {
666
+ this.scope = context.scope;
667
+ this.diagnostic = context.diagnostic;
668
+ this.lastCommittedEpochSeq = Math.max(this.lastCommittedEpochSeq, input.epoch.epochSeq);
669
+ const cursor = input.pendingEvents.at(-1)?.commitSeq;
670
+ const frameForClock = createBehaviorInput(input, Object.freeze({}));
671
+ const now = frameForClock?.nowMs ?? this.now();
672
+ const runtimeState = input.epoch.state;
673
+
674
+ await this.syncRoleFallback(frameForClock, now);
675
+ this.refreshBackendStrategyReport(input, context);
676
+
677
+ await this.applyTransitions(this.manager.advance(now));
678
+ const frame = this.manager.current()
679
+ ? createBehaviorInput(input, this.manager.current()!.input)
680
+ : frameForClock;
681
+ if (frame?.gameState.phase === 'game_over' || computed.kind === 'game_over') {
682
+ await this.applyTransitions(this.manager.clearScope('game_over', now));
683
+ this.boundaryActive = true;
684
+ return this.output(cursor);
685
+ }
686
+ if (frame?.gameState.you?.is_alive === false || computed.kind === 'player_inactive') {
687
+ await this.applyTransitions(this.manager.clearScope('player_inactive', now));
688
+ this.boundaryActive = true;
689
+ return this.output(cursor);
690
+ }
691
+
692
+ const meeting = frame?.gameState.phase === 'meeting';
693
+ const outsideWandering = frame !== null && frame !== undefined && frame.gameState.phase !== 'wandering';
694
+ if (outsideWandering && !(meeting && this.manager.current()?.layer === 'short')) {
695
+ await this.applyTransitions(this.manager.enterBoundary(
696
+ meeting ? 'meeting_started' : 'wandering_inactive',
697
+ now,
698
+ ));
699
+ this.boundaryActive = true;
700
+ return this.output(cursor);
701
+ }
702
+ if (frame?.gameState.phase === 'wandering' && this.boundaryActive) {
703
+ this.boundaryActive = false;
704
+ await this.applyTransitions(this.manager.leaveBoundary(now));
705
+ return this.output(cursor);
706
+ }
707
+
708
+ const current = this.manager.current();
709
+ if (
710
+ !current
711
+ || computed.activationId !== current.activationId
712
+ || computed.instanceGeneration !== current.instanceGeneration
713
+ || !this.manager.isCurrent(current.activationId, current.instanceGeneration)
714
+ ) return this.output(undefined);
715
+
716
+ if (!frame) return this.output(undefined);
717
+ const runtime = this.runtimes.get(current.activationId);
718
+ const control = this.controls.get(current.activationId);
719
+ if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration || !control?.isAuthorized()) {
720
+ return this.output(undefined);
721
+ }
722
+ const backendTick = Number(frame.gameState.tick ?? frame.epochId);
723
+ if (
724
+ runtime.lastCommittedBackendTick !== undefined
725
+ && backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks
726
+ ) return this.output(undefined);
727
+ if (computed.kind === 'cadence_skip' || computed.kind === 'control_held') {
728
+ return this.output(undefined);
729
+ }
730
+ if (computed.kind === 'module_error') {
731
+ await this.failCurrent(current, computed.errorCode ?? 'BEHAVIOR_DECIDE_FAILED', now);
732
+ return this.output(cursor);
733
+ }
734
+ if (computed.kind !== 'serial' && computed.kind !== 'parallel') {
735
+ return this.output(computed.kind === 'inactive' ? cursor : undefined);
736
+ }
737
+
738
+ const observation = this.observationMemory.snapshot(frame.epochId)
739
+ ?? this.observationMemory.capture(frame);
740
+ let decision = computed.decision;
741
+ const mustRecompute = computed.kind === 'serial'
742
+ || !sameStrings(computed.eventIds ?? [], eventIds(frame))
743
+ || computed.observationRevision !== observation.revision;
744
+ if (mustRecompute) {
745
+ try {
746
+ decision = await this.withDecisionTimeout(
747
+ signal => runtime.runner!.execution === 'serial'
748
+ ? runtime.runner!.decideSerial(frame, signal, observation)
749
+ : runtime.runner!.decideParallel(frame, signal, observation),
750
+ context.signal,
751
+ current.activationId,
752
+ );
753
+ } catch (error) {
754
+ if (errorCode(error) === 'behavior_reflex_preempted') return this.output(undefined);
755
+ await this.failCurrent(current, errorCode(error, 'BEHAVIOR_DECIDE_FAILED'), now);
756
+ return this.output(cursor);
757
+ }
758
+ }
759
+ if (!decision || !this.manager.isCurrent(current.activationId, current.instanceGeneration)) {
760
+ return this.output(undefined);
761
+ }
762
+ runtime.lastCommittedBackendTick = backendTick;
763
+ let output: Readonly<{
764
+ status?: Readonly<BehaviorStatus>;
765
+ events: readonly RuntimeEventProposal[];
766
+ }>;
767
+ try {
768
+ output = await this.applyDecision(
769
+ current,
770
+ runtime,
771
+ frame,
772
+ decision,
773
+ input,
774
+ context,
775
+ );
776
+ } catch (error) {
777
+ await this.failCurrent(current, errorCode(error, 'BEHAVIOR_DECISION_INVALID'), now);
778
+ return this.output(cursor);
779
+ }
780
+ runtime.lastStatus = output.status ?? runtime.lastStatus;
781
+
782
+ if (meeting) {
783
+ await this.applyTransitions(this.manager.enterBoundary('meeting_started', now));
784
+ this.boundaryActive = true;
785
+ }
786
+ return this.output(cursor, output.status, output.events);
787
+ }
788
+
789
+ private async applyDecision(
790
+ activation: Readonly<BehaviorActivationSnapshot>,
791
+ runtime: ActivationRuntime,
792
+ frame: Readonly<BehaviorInput>,
793
+ decision: Readonly<BehaviorDecision>,
794
+ input: RuntimeEpochPluginInput<Record<string, any>>,
795
+ context: RuntimeEpochPluginContext<Record<string, any>>,
796
+ ): Promise<Readonly<{
797
+ status?: Readonly<BehaviorStatus>;
798
+ events: readonly RuntimeEventProposal[];
799
+ }>> {
800
+ if (decision.finish && (decision.actions?.length ?? 0) > 0) {
801
+ throw new Error('behavior_finish_with_actions_invalid');
802
+ }
803
+ const declaredEvents = new Set(runtime.prepared.manifest.produces ?? []);
804
+ for (const event of decision.events ?? []) {
805
+ if (!declaredEvents.has(event.type)) throw new Error('behavior_event_output_invalid');
806
+ }
807
+ const state = input.epoch.state;
808
+ const safetyGeneration = isClawclawRuntimeState(state)
809
+ ? state.action_safety_generation
810
+ : undefined;
811
+ for (const [index, rawAction] of (decision.actions ?? []).entries()) {
812
+ if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) break;
813
+ const control = this.controls.get(activation.activationId);
814
+ if (!control?.isAuthorized()) break;
815
+ const action = rawAction as Readonly<GameAction>;
816
+ const dedupeKey = `${activation.instanceGeneration}:${frame.gameState.tick}:${index}:${JSON.stringify(action)}`;
817
+ if (runtime.committedActionDedupeKeys.has(dedupeKey)) continue;
818
+ const request = normalizeClawclawBehaviorAction(
819
+ action,
820
+ frame.epochId,
821
+ safetyGeneration,
822
+ activation.instanceGeneration,
823
+ );
824
+ try {
825
+ const result = await context.capabilities.performAction(
826
+ CLAWCLAW_ACTION_CAPABILITY,
827
+ request,
828
+ asActionCaller(control.caller),
829
+ );
830
+ if (result.actionOutcome !== 'not_submitted') {
831
+ runtime.committedActionDedupeKeys.set(dedupeKey, frame.epochId);
832
+ while (runtime.committedActionDedupeKeys.size > 2_048) {
833
+ const oldest = runtime.committedActionDedupeKeys.keys().next().value as string | undefined;
834
+ if (oldest === undefined) break;
835
+ runtime.committedActionDedupeKeys.delete(oldest);
836
+ }
837
+ }
838
+ if (result.actionOutcome === 'not_submitted' && !control.isAuthorized()) break;
839
+ } catch (error) {
840
+ context.diagnostic('behavior.action.failed', {
841
+ behavior_id: activation.behaviorId,
842
+ activation_id: activation.activationId,
843
+ instance_generation: activation.instanceGeneration,
844
+ epoch_id: frame.epochId,
845
+ error_code: errorCode(error, 'BEHAVIOR_ACTION_FAILED'),
846
+ }, 'error');
847
+ }
848
+ }
849
+ if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) {
850
+ return { events: [] };
851
+ }
852
+ const events = (decision.events ?? []).map((event, index): RuntimeEventProposal => ({
853
+ type: event.type,
854
+ dedupeKey: `${activation.activationId}:${activation.instanceGeneration}:${frame.gameState.tick ?? frame.epochId}:${event.type}:${index}`,
855
+ payload: { ...event.payload },
856
+ ...(event.occurredAt === undefined ? {} : { occurredAt: event.occurredAt }),
857
+ }));
858
+ if (decision.finish) {
859
+ await this.finishCurrent(activation, decision.finish, frame.nowMs);
860
+ }
861
+ return {
862
+ ...(decision.status === undefined ? {} : { status: decision.status }),
863
+ events,
864
+ };
865
+ }
866
+
867
+ private async finishCurrent(
868
+ activation: Readonly<BehaviorActivationSnapshot>,
869
+ finish: Readonly<BehaviorFinish>,
870
+ now: number,
871
+ ): Promise<void> {
872
+ if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) return;
873
+ await this.applyTransitions(this.manager.finish(
874
+ activation.activationId,
875
+ finish.outcome,
876
+ finish.reason,
877
+ now,
878
+ ));
879
+ }
880
+
881
+ private async failCurrent(
882
+ activation: Readonly<BehaviorActivationSnapshot>,
883
+ reason: string,
884
+ now: number,
885
+ ): Promise<void> {
886
+ if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) return;
887
+ await this.applyTransitions(this.manager.finish(activation.activationId, 'failed', reason, now));
888
+ }
889
+
890
+ private async applyTransitions(
891
+ transitions: readonly BehaviorActivationTransition[],
892
+ ): Promise<void> {
893
+ for (const transition of transitions) {
894
+ const event = lifecycleEvent(transition);
895
+ if (event) this.pendingLifecycleEvents.push(event);
896
+ }
897
+ const failures: BehaviorActivationTransition[] = [];
898
+ // Reserve the incoming controller before releasing the outgoing layer.
899
+ // Equal-layer replacement is held until the old controller is released;
900
+ // a higher layer becomes active immediately, leaving no takeover gap.
901
+ for (const transition of transitions) {
902
+ if (transition.type !== 'started' && transition.type !== 'restarted') continue;
903
+ const snapshot = currentRuntimeSnapshot(this.manager, transition.activationId);
904
+ if (!snapshot) continue;
905
+ try {
906
+ const runtime = await this.ensureRuntime(snapshot);
907
+ if (!this.driver || !this.scope) throw new Error('behavior_control_driver_unavailable');
908
+ const handle = await this.driver.acquire(snapshot, this.scope);
909
+ if (
910
+ handle.caller.activationId !== snapshot.activationId
911
+ || handle.caller.layer !== snapshot.layer
912
+ || handle.caller.activationGeneration !== snapshot.instanceGeneration
913
+ ) throw new Error('behavior_control_handle_invalid');
914
+ this.controls.set(snapshot.activationId, handle);
915
+ runtime.instanceGeneration = snapshot.instanceGeneration;
916
+ } catch (error) {
917
+ this.diagnostic?.('behavior.activation.failed', {
918
+ behavior_id: snapshot.behaviorId,
919
+ activation_id: snapshot.activationId,
920
+ instance_generation: snapshot.instanceGeneration,
921
+ error_code: errorCode(error, 'BEHAVIOR_ACTIVATION_FAILED'),
922
+ }, 'error');
923
+ failures.push(...this.manager.finish(
924
+ snapshot.activationId,
925
+ 'failed',
926
+ errorCode(error, 'behavior_activation_failed'),
927
+ this.now(),
928
+ ));
929
+ }
930
+ }
931
+ for (const transition of transitions) {
932
+ if (
933
+ transition.type === 'suspended'
934
+ || transition.type === 'completed'
935
+ || transition.type === 'failed'
936
+ || transition.type === 'cancelled'
937
+ || transition.type === 'replaced'
938
+ ) {
939
+ this.controls.get(transition.activationId)?.release(`behavior_${transition.type}:${transition.reason}`);
940
+ this.controls.delete(transition.activationId);
941
+ const runtime = this.runtimes.get(transition.activationId);
942
+ await runtime?.runner?.stop('switched');
943
+ if (runtime) {
944
+ runtime.runner = undefined;
945
+ runtime.instanceGeneration = undefined;
946
+ }
947
+ if (transition.type !== 'suspended') this.runtimes.delete(transition.activationId);
948
+ }
949
+ }
950
+ if (failures.length > 0) await this.applyTransitions(failures);
951
+ }
952
+
953
+ private async ensureRuntime(
954
+ activation: Readonly<BehaviorActivationSnapshot>,
955
+ ): Promise<ActivationRuntime> {
956
+ let runtime = this.runtimes.get(activation.activationId);
957
+ if (!runtime) {
958
+ let prepared: PreparedClawclawBehavior;
959
+ if (
960
+ activation.source === 'idle'
961
+ && this.fallbackPrepared?.manifest.id === activation.behaviorId
962
+ ) {
963
+ prepared = this.fallbackPreparedUsed
964
+ ? Object.freeze({
965
+ ...this.fallbackPrepared,
966
+ module: this.fallbackPrepared.createModule(),
967
+ })
968
+ : this.fallbackPrepared;
969
+ this.fallbackPreparedUsed = true;
970
+ } else {
971
+ prepared = await this.catalog.prepare(activation.behaviorId, activation.input);
972
+ }
973
+ runtime = {
974
+ activationId: activation.activationId,
975
+ behaviorId: activation.behaviorId,
976
+ prepared,
977
+ committedActionDedupeKeys: new Map(),
978
+ };
979
+ this.runtimes.set(activation.activationId, runtime);
980
+ }
981
+ await runtime.runner?.stop('switched');
982
+ const prepared = runtime.instanceGeneration === undefined && activation.instanceGeneration === 1
983
+ ? runtime.prepared
984
+ : Object.freeze({
985
+ ...runtime.prepared,
986
+ module: runtime.prepared.createModule(),
987
+ });
988
+ runtime.runner = new ClawclawBehaviorRunner({
989
+ behaviorId: activation.behaviorId,
990
+ activationId: activation.activationId,
991
+ instanceGeneration: activation.instanceGeneration,
992
+ prepared,
993
+ diagnostic: this.diagnostic,
994
+ isActive: () => this.manager.isCurrent(
995
+ activation.activationId,
996
+ activation.instanceGeneration,
997
+ ),
998
+ });
999
+ runtime.instanceGeneration = activation.instanceGeneration;
1000
+ runtime.lastCommittedBackendTick = undefined;
1001
+ runtime.lastStatus = undefined;
1002
+ runtime.committedActionDedupeKeys.clear();
1003
+ return runtime;
1004
+ }
1005
+
1006
+ private async syncRoleFallback(
1007
+ frame: Readonly<BehaviorInput> | null,
1008
+ now: number,
1009
+ ): Promise<void> {
1010
+ const role = frame?.gameState.you?.role;
1011
+ if (this.manualFallbackOverride) return;
1012
+ if (typeof role !== 'string' || !role) return;
1013
+ const configured = this.fallbackBehaviors.get(role);
1014
+ const key = `${this.fallbackConfigGeneration}:${role}:${configured?.behaviorId ?? ''}`;
1015
+ if (this.appliedFallbackKey === key) return;
1016
+ this.appliedFallbackKey = key;
1017
+ if (!configured) {
1018
+ this.fallbackPrepared = undefined;
1019
+ this.fallbackPreparedUsed = false;
1020
+ await this.applyTransitions(this.manager.bindFallback(undefined, now));
1021
+ return;
1022
+ }
1023
+ try {
1024
+ const prepared = await this.catalog.prepare(configured.behaviorId, configured.input ?? {});
1025
+ this.fallbackPrepared = prepared;
1026
+ this.fallbackPreparedUsed = false;
1027
+ await this.applyTransitions(this.manager.bindFallback({
1028
+ behaviorId: configured.behaviorId,
1029
+ input: prepared.input,
1030
+ }, now));
1031
+ } catch (error) {
1032
+ this.fallbackPrepared = undefined;
1033
+ this.fallbackPreparedUsed = false;
1034
+ await this.applyTransitions(this.manager.bindFallback(undefined, now));
1035
+ this.diagnostic?.('behavior.fallback.invalid', {
1036
+ role,
1037
+ behavior_id: configured.behaviorId,
1038
+ error_code: errorCode(error, 'BEHAVIOR_FALLBACK_INVALID'),
1039
+ }, 'error');
1040
+ }
1041
+ }
1042
+
1043
+ /**
1044
+ * The backend still calls this display-only field a Strategy. Report the
1045
+ * persistent long/fallback Behavior, never a short or reflex overlay.
1046
+ */
1047
+ private backendStrategyDescriptor(): ClawclawResolvedResourceMetadata | undefined {
1048
+ const stack = this.manager.snapshot();
1049
+ const long = stack.long;
1050
+ const behaviorId = long?.behaviorId ?? stack.fallback?.behaviorId;
1051
+ if (!behaviorId) return undefined;
1052
+ const prepared = long
1053
+ ? this.runtimes.get(long.activationId)?.prepared
1054
+ : this.fallbackPrepared;
1055
+ if (!prepared || prepared.manifest.id !== behaviorId) return undefined;
1056
+ return resolveClawclawResourceMetadata({
1057
+ id: prepared.manifest.id,
1058
+ name: prepared.manifest.name,
1059
+ description: prepared.manifest.description,
1060
+ ...(prepared.manifest.localizations === undefined
1061
+ ? {}
1062
+ : { localizations: prepared.manifest.localizations }),
1063
+ }, BACKEND_STRATEGY_REPORT_LOCALE);
1064
+ }
1065
+
1066
+ private refreshBackendStrategyReport(
1067
+ input: RuntimeEpochPluginInput<Record<string, any>>,
1068
+ context: RuntimeEpochPluginContext<Record<string, any>>,
1069
+ ): void {
1070
+ const wasEligible = this.backendStrategyReportEligible;
1071
+ const state = input.epoch.state;
1072
+ this.backendStrategyReportContext = context;
1073
+ this.backendStrategyReportEligible = isClawclawRuntimeState(state)
1074
+ && state.connection === 'connected'
1075
+ && state.stage === 'game'
1076
+ && state.game_snapshot.status === 'fresh'
1077
+ && state.game_snapshot.state.phase === 'wandering';
1078
+
1079
+ const descriptor = this.backendStrategyDescriptor();
1080
+ const nextTarget = descriptor
1081
+ ? {
1082
+ ...descriptor,
1083
+ fingerprint: JSON.stringify([descriptor.id, descriptor.name, descriptor.description]),
1084
+ }
1085
+ : undefined;
1086
+ const targetChanged = nextTarget?.fingerprint !== this.backendStrategyReportTarget?.fingerprint;
1087
+ if (targetChanged) {
1088
+ this.backendStrategyReportTarget = nextTarget;
1089
+ // A prior target may still be in flight at the backend. Reconfirm even
1090
+ // when the selection later returns to an older fingerprint.
1091
+ this.backendStrategyReportAcknowledgedFingerprint = undefined;
1092
+ this.clearBackendStrategyReportTimer();
1093
+ }
1094
+
1095
+ const target = this.backendStrategyReportTarget;
1096
+ if (!target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
1097
+ this.clearBackendStrategyReportTimer();
1098
+ return;
1099
+ }
1100
+ if (targetChanged || (!wasEligible && this.backendStrategyReportEligible)) {
1101
+ this.scheduleBackendStrategyReport(0, true);
1102
+ }
1103
+ }
1104
+
1105
+ private clearBackendStrategyReportTimer(): void {
1106
+ if (!this.backendStrategyReportTimer) return;
1107
+ clearTimeout(this.backendStrategyReportTimer);
1108
+ this.backendStrategyReportTimer = undefined;
1109
+ }
1110
+
1111
+ private scheduleBackendStrategyReport(delayMs: number, replace = false): void {
1112
+ const target = this.backendStrategyReportTarget;
1113
+ if (
1114
+ !target
1115
+ || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint
1116
+ || this.backendStrategyReportInFlight
1117
+ ) return;
1118
+ if (this.backendStrategyReportTimer) {
1119
+ if (!replace) return;
1120
+ this.clearBackendStrategyReportTimer();
1121
+ }
1122
+ const lifecycleGeneration = this.backendStrategyReportLifecycleGeneration;
1123
+ this.backendStrategyReportTimer = setTimeout(() => {
1124
+ this.backendStrategyReportTimer = undefined;
1125
+ if (lifecycleGeneration !== this.backendStrategyReportLifecycleGeneration) return;
1126
+ this.startBackendStrategyReportAttempt();
1127
+ }, delayMs);
1128
+ this.backendStrategyReportTimer.unref?.();
1129
+ }
1130
+
1131
+ private startBackendStrategyReportAttempt(): void {
1132
+ const target = this.backendStrategyReportTarget;
1133
+ const context = this.backendStrategyReportContext;
1134
+ if (
1135
+ !target
1136
+ || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint
1137
+ || this.backendStrategyReportInFlight
1138
+ ) return;
1139
+ if (!this.backendStrategyReportEligible || !context || context.signal.aborted) {
1140
+ this.scheduleBackendStrategyReport(BACKEND_STRATEGY_REPORT_RETRY_MS);
1141
+ return;
1142
+ }
1143
+
1144
+ const attempt: BackendStrategyReportAttempt = {
1145
+ lifecycleGeneration: this.backendStrategyReportLifecycleGeneration,
1146
+ fingerprint: target.fingerprint,
1147
+ };
1148
+ this.backendStrategyReportInFlight = attempt;
1149
+ context.diagnostic('strategy.report.started', {
1150
+ strategy_id: target.id,
1151
+ }, 'debug');
1152
+
1153
+ let pending: Promise<unknown>;
1154
+ try {
1155
+ pending = context.capabilities.performAction(
1156
+ CLAWCLAW_ACTION_CAPABILITY,
1157
+ {
1158
+ route: 'game',
1159
+ action: {
1160
+ action: 'strategy',
1161
+ name: target.name,
1162
+ description: target.description,
1163
+ },
1164
+ },
1165
+ );
1166
+ } catch (error) {
1167
+ this.finishBackendStrategyReportAttempt(attempt, false, error);
1168
+ return;
1169
+ }
1170
+ void pending.then(
1171
+ result => this.finishBackendStrategyReportAttempt(
1172
+ attempt,
1173
+ isSuccessfulBackendStrategyReport(result),
1174
+ result,
1175
+ ),
1176
+ error => this.finishBackendStrategyReportAttempt(attempt, false, error),
1177
+ );
1178
+ }
1179
+
1180
+ private finishBackendStrategyReportAttempt(
1181
+ attempt: BackendStrategyReportAttempt,
1182
+ successful: boolean,
1183
+ result: unknown,
1184
+ ): void {
1185
+ if (
1186
+ attempt.lifecycleGeneration !== this.backendStrategyReportLifecycleGeneration
1187
+ || this.backendStrategyReportInFlight?.fingerprint !== attempt.fingerprint
1188
+ ) return;
1189
+ this.backendStrategyReportInFlight = undefined;
1190
+ const target = this.backendStrategyReportTarget;
1191
+ if (successful && target?.fingerprint === attempt.fingerprint) {
1192
+ this.backendStrategyReportAcknowledgedFingerprint = attempt.fingerprint;
1193
+ this.clearBackendStrategyReportTimer();
1194
+ this.backendStrategyReportContext?.diagnostic('strategy.report.completed', {
1195
+ strategy_id: target.id,
1196
+ }, 'info');
1197
+ return;
1198
+ }
1199
+
1200
+ if (target?.fingerprint === attempt.fingerprint) {
1201
+ this.backendStrategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
1202
+ strategy_id: target.id,
1203
+ retry_ms: BACKEND_STRATEGY_REPORT_RETRY_MS,
1204
+ error_code: errorCode(result, 'STRATEGY_REPORT_RESPONSE_INVALID'),
1205
+ }, 'warn');
1206
+ this.scheduleBackendStrategyReport(BACKEND_STRATEGY_REPORT_RETRY_MS);
1207
+ return;
1208
+ }
1209
+ if (
1210
+ target
1211
+ && this.backendStrategyReportAcknowledgedFingerprint !== target.fingerprint
1212
+ ) this.scheduleBackendStrategyReport(0);
1213
+ }
1214
+
1215
+ private resetBackendStrategyReporting(): void {
1216
+ this.backendStrategyReportLifecycleGeneration += 1;
1217
+ this.clearBackendStrategyReportTimer();
1218
+ this.backendStrategyReportTarget = undefined;
1219
+ this.backendStrategyReportAcknowledgedFingerprint = undefined;
1220
+ this.backendStrategyReportInFlight = undefined;
1221
+ this.backendStrategyReportContext = undefined;
1222
+ this.backendStrategyReportEligible = false;
1223
+ }
1224
+
1225
+ private output(
1226
+ consumeEventsThroughCommitSeq?: number,
1227
+ semanticStatus?: Readonly<BehaviorStatus>,
1228
+ decisionEvents: readonly RuntimeEventProposal[] = [],
1229
+ ): RuntimeEpochPluginResult {
1230
+ const lifecycle = this.pendingLifecycleEvents.splice(0);
1231
+ const trailingLifecycle = lifecycle.filter(event => (
1232
+ event.type === 'behavior.completed'
1233
+ || event.type === 'behavior.failed'
1234
+ || event.type === 'behavior.cancelled'
1235
+ ));
1236
+ const leadingLifecycle = lifecycle.filter(event => !trailingLifecycle.includes(event));
1237
+ const events = [...leadingLifecycle, ...decisionEvents, ...trailingLifecycle];
1238
+ const status = this.status();
1239
+ if (!status.running && events.length === 0 && semanticStatus === undefined) {
1240
+ return {
1241
+ outcome: 'noop',
1242
+ reason: 'behavior_inactive',
1243
+ ...(consumeEventsThroughCommitSeq === undefined
1244
+ ? {}
1245
+ : { consumeEventsThroughCommitSeq }),
1246
+ };
1247
+ }
1248
+ const current = status.current;
1249
+ const retainedStatus = semanticStatus
1250
+ ?? (current === undefined ? undefined : this.runtimes.get(current.activationId)?.lastStatus);
1251
+ const stateValue = {
1252
+ running: status.running,
1253
+ ...(current === undefined ? {} : {
1254
+ activation_id: current.activationId,
1255
+ behavior: current.behaviorId,
1256
+ layer: current.layer,
1257
+ source: current.source,
1258
+ instance_generation: current.instanceGeneration,
1259
+ }),
1260
+ ...(retainedStatus === undefined ? {} : { status: retainedStatus }),
1261
+ stack: status.stack,
1262
+ };
1263
+ return {
1264
+ outcome: 'processed',
1265
+ states: [{ topic: CLAWCLAW_BEHAVIOR_STATE_TOPIC, value: stateValue }],
1266
+ ...(events.length === 0 ? {} : { events }),
1267
+ ...(consumeEventsThroughCommitSeq === undefined
1268
+ ? {}
1269
+ : { consumeEventsThroughCommitSeq }),
1270
+ };
1271
+ }
1272
+
1273
+ private withDecisionTimeout<T>(
1274
+ operation: (signal: AbortSignal) => Promise<T>,
1275
+ signal: AbortSignal,
1276
+ activationId?: string,
1277
+ ): Promise<T> {
1278
+ if (signal.aborted) return Promise.reject(signal.reason);
1279
+ return new Promise<T>((resolve, reject) => {
1280
+ const controller = new AbortController();
1281
+ let settled = false;
1282
+ let timer: ReturnType<typeof setTimeout>;
1283
+ const onAbort = (): void => {
1284
+ const reason = signal.reason instanceof Error
1285
+ ? signal.reason
1286
+ : new Error('behavior_epoch_aborted');
1287
+ controller.abort(reason);
1288
+ complete(() => reject(reason));
1289
+ };
1290
+ const onInternalAbort = (): void => {
1291
+ const reason = controller.signal.reason instanceof Error
1292
+ ? controller.signal.reason
1293
+ : new Error('behavior_decision_aborted');
1294
+ complete(() => reject(reason));
1295
+ };
1296
+ const cleanup = (): void => {
1297
+ clearTimeout(timer);
1298
+ signal.removeEventListener('abort', onAbort);
1299
+ controller.signal.removeEventListener('abort', onInternalAbort);
1300
+ if (activationId) {
1301
+ const controllers = this.decisionControllers.get(activationId);
1302
+ controllers?.delete(controller);
1303
+ if (controllers?.size === 0) this.decisionControllers.delete(activationId);
1304
+ }
1305
+ };
1306
+ const complete = (callback: () => void): void => {
1307
+ if (settled) return;
1308
+ settled = true;
1309
+ cleanup();
1310
+ callback();
1311
+ };
1312
+ timer = setTimeout(() => {
1313
+ const timeout = new Error('behavior_decision_timeout');
1314
+ controller.abort(timeout);
1315
+ complete(() => reject(timeout));
1316
+ }, this.decisionTimeoutMs);
1317
+ timer.unref?.();
1318
+ controller.signal.addEventListener('abort', onInternalAbort, { once: true });
1319
+ if (activationId) {
1320
+ let controllers = this.decisionControllers.get(activationId);
1321
+ if (!controllers) {
1322
+ controllers = new Set();
1323
+ this.decisionControllers.set(activationId, controllers);
1324
+ }
1325
+ controllers.add(controller);
1326
+ }
1327
+ signal.addEventListener('abort', onAbort, { once: true });
1328
+ void operation(controller.signal).then(
1329
+ value => complete(() => resolve(value)),
1330
+ error => complete(() => reject(error)),
1331
+ ).catch(() => {});
1332
+ });
1333
+ }
1334
+
1335
+ private interruptDecisions(activationId: string, reason: string): void {
1336
+ const controllers = this.decisionControllers.get(activationId);
1337
+ if (!controllers) return;
1338
+ const error = new Error(reason);
1339
+ for (const controller of controllers) controller.abort(error);
1340
+ }
1341
+
1342
+ private enqueueControl<T>(operation: () => Promise<T>): Promise<T> {
1343
+ const pending = this.controlTail.then(operation, operation);
1344
+ this.controlTail = pending.then(() => undefined, () => undefined);
1345
+ return pending;
1346
+ }
1347
+ }