@myclaw163/clawclaw-cli 0.6.112 → 0.7.5

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 (422) hide show
  1. package/QUICKSTART.md +46 -0
  2. package/QUICKSTART_HERMES.md +134 -0
  3. package/QUICKSTART_OPENCLAW.md +134 -0
  4. package/QUICKSTART_OTHER.md +134 -0
  5. package/README.md +23 -398
  6. package/bin/clawclaw-cli.mjs +9 -1
  7. package/docs/configuration.md +197 -0
  8. package/docs/runtime/README.md +52 -0
  9. package/docs/runtime/agent-notifications.md +55 -0
  10. package/docs/runtime/components-and-boundaries.md +213 -0
  11. package/docs/runtime/events-and-state.md +105 -0
  12. package/docs/runtime/owner-lifecycle-and-observability.md +69 -0
  13. package/docs/runtime/perception-replay.md +51 -0
  14. package/docs/runtime/short-commands-and-capabilities.md +55 -0
  15. package/docs/runtime/strategy-runtime.md +111 -0
  16. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +488 -0
  17. package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +395 -0
  18. package/package.json +26 -8
  19. package/scripts/check-skill-command-surface.mjs +16 -7
  20. package/scripts/compare-perception-replays.test.ts +188 -0
  21. package/scripts/compare-perception-replays.ts +589 -0
  22. package/scripts/generate-spatial-facts.py +246 -0
  23. package/scripts/package-readme.mjs +48 -0
  24. package/scripts/replay-perception.ts +347 -0
  25. package/scripts/sync-frontend-map.mjs +195 -0
  26. package/scripts/watch-perception-events.test.ts +43 -0
  27. package/scripts/watch-perception-events.ts +162 -0
  28. package/skills/clawclaw/SKILL.md +121 -65
  29. package/skills/clawclaw/references/CHATTERBOX.md +2 -4
  30. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  31. package/skills/clawclaw/references/COMMANDS.md +95 -61
  32. package/skills/clawclaw/references/GAME-MECHANICS.md +19 -9
  33. package/skills/clawclaw/references/HUB.md +5 -5
  34. package/skills/clawclaw/references/STRATEGIES.md +34 -17
  35. package/skills/clawclaw/references/STREAM.md +82 -46
  36. package/src/assets/clawclaw-map.json +1692 -0
  37. package/src/assets/clawclaw-spatial-facts.json +1291 -0
  38. package/src/assets/clawclaw-spatial-model.txt +142 -0
  39. package/src/cli.ts +21 -47
  40. package/src/commands/account.test.ts +229 -50
  41. package/src/commands/account.ts +456 -223
  42. package/src/commands/communication.test.ts +259 -0
  43. package/src/commands/communication.ts +391 -0
  44. package/src/commands/competition.test.ts +116 -0
  45. package/src/commands/competition.ts +50 -28
  46. package/src/commands/data.test.ts +57 -1
  47. package/src/commands/data.ts +79 -4
  48. package/src/commands/events-canonical-state.test.ts +187 -0
  49. package/src/commands/events.test.ts +50 -136
  50. package/src/commands/events.ts +175 -241
  51. package/src/commands/game/index.test.ts +510 -0
  52. package/src/commands/game/index.ts +556 -0
  53. package/src/commands/game-map.test.ts +48 -7
  54. package/src/commands/hub.test.ts +2 -23
  55. package/src/commands/hub.ts +4 -16
  56. package/src/commands/load.test.ts +10 -22
  57. package/src/commands/load.ts +15 -2
  58. package/src/commands/peek.ts +2 -3
  59. package/src/commands/perception.test.ts +46 -0
  60. package/src/commands/perception.ts +92 -0
  61. package/src/commands/setup/codex.ts +0 -1
  62. package/src/commands/strategy.test.ts +139 -102
  63. package/src/commands/strategy.ts +175 -103
  64. package/src/commands/upgrade.ts +0 -21
  65. package/src/lib/auth.test.ts +35 -0
  66. package/src/lib/auth.ts +45 -6
  67. package/src/lib/diagnostics-config.test.ts +59 -0
  68. package/src/lib/diagnostics-config.ts +76 -0
  69. package/src/lib/game-client.test.ts +166 -0
  70. package/src/lib/game-client.ts +316 -87
  71. package/src/lib/game-context.ts +33 -4
  72. package/src/lib/gameplay-config.test.ts +66 -0
  73. package/src/lib/gameplay-config.ts +151 -0
  74. package/src/lib/http-transport.test.ts +63 -0
  75. package/src/lib/http-transport.ts +76 -10
  76. package/src/lib/init-command.test.ts +25 -1
  77. package/src/lib/init-command.ts +66 -1
  78. package/src/lib/participation-leave.ts +78 -0
  79. package/src/lib/perception-config.test.ts +138 -0
  80. package/src/lib/perception-config.ts +101 -0
  81. package/src/lib/room.test.ts +14 -0
  82. package/src/lib/room.ts +28 -2
  83. package/src/lib/server-registry.test.ts +15 -5
  84. package/src/lib/server-registry.ts +9 -10
  85. package/src/lib/strategy-export.test.ts +123 -44
  86. package/src/lib/strategy-export.ts +110 -81
  87. package/src/lib/user-data.test.ts +2 -0
  88. package/src/lib/user-data.ts +17 -16
  89. package/src/pipeline/canonical-event-presentation.test.ts +196 -0
  90. package/src/pipeline/canonical-event-presentation.ts +71 -0
  91. package/src/pipeline/event-format.test.ts +357 -59
  92. package/src/pipeline/event-format.ts +365 -80
  93. package/src/pipeline/event-hints.test.ts +241 -0
  94. package/src/pipeline/event-hints.ts +202 -51
  95. package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
  96. package/src/pipeline/game-sync-event-normalization.ts +215 -0
  97. package/src/pipeline/player-projection.test.ts +164 -102
  98. package/src/pipeline/player-projection.ts +194 -235
  99. package/src/runtime/canonical-event-emitter.test.ts +70 -0
  100. package/src/runtime/canonical-event-emitter.ts +78 -0
  101. package/src/runtime/canonical-monitor.test.ts +575 -0
  102. package/src/runtime/canonical-monitor.ts +388 -0
  103. package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
  104. package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
  105. package/src/runtime/clawclaw/index.ts +4 -0
  106. package/src/runtime/clawclaw/notifications.test.ts +47 -0
  107. package/src/runtime/clawclaw/notifications.ts +65 -0
  108. package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
  109. package/src/runtime/clawclaw/owner.ts +945 -0
  110. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
  111. package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
  112. package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
  113. package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
  114. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
  115. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
  116. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
  117. package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
  118. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
  119. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
  120. package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
  121. package/src/runtime/clawclaw/plugins/index.ts +7 -0
  122. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  123. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
  124. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
  125. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
  126. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
  127. package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
  128. package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
  129. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
  130. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
  131. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
  132. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
  133. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
  134. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
  135. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
  136. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
  137. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
  138. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
  139. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
  140. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
  141. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
  142. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
  143. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
  144. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
  145. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
  146. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
  147. package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
  148. package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
  149. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
  150. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
  151. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
  152. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
  153. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
  154. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
  155. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
  156. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
  157. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
  158. package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
  159. package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
  160. package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
  161. package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
  162. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
  163. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
  164. package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
  165. package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
  166. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
  167. package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
  168. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
  169. package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
  170. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
  171. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
  172. package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
  173. package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
  174. package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
  175. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
  176. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
  177. package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
  178. package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
  179. package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
  180. package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
  181. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
  182. package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
  183. package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
  184. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
  185. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
  186. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
  187. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
  188. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
  189. package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
  190. package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
  191. package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
  192. package/src/runtime/clawclaw/runtime-state.ts +98 -0
  193. package/src/runtime/clawclaw/runtime.ts +133 -0
  194. package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
  195. package/src/runtime/clawclaw-event-catalog.ts +266 -0
  196. package/src/runtime/clawclaw-position.ts +4 -0
  197. package/src/runtime/clawclaw-room-state.ts +51 -0
  198. package/src/runtime/framework/action-diagnostics.test.ts +81 -0
  199. package/src/runtime/framework/action-diagnostics.ts +146 -0
  200. package/src/runtime/framework/capability-registry.test.ts +282 -0
  201. package/src/runtime/framework/capability-registry.ts +283 -0
  202. package/src/runtime/framework/contracts.ts +118 -0
  203. package/src/runtime/framework/control/control-scheduler.ts +1260 -0
  204. package/src/runtime/framework/control/domain-set.ts +81 -0
  205. package/src/runtime/framework/control/index.ts +3 -0
  206. package/src/runtime/framework/control/types.ts +184 -0
  207. package/src/runtime/framework/control-coordinator.test.ts +660 -0
  208. package/src/runtime/framework/control-coordinator.ts +11 -0
  209. package/src/runtime/framework/events/event-catalog.ts +74 -0
  210. package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
  211. package/src/runtime/framework/events/event-delivery-service.ts +198 -0
  212. package/src/runtime/framework/events/event-ingress.test.ts +178 -0
  213. package/src/runtime/framework/events/event-ingress.ts +97 -0
  214. package/src/runtime/framework/events/event-repository.ts +59 -0
  215. package/src/runtime/framework/events/index.ts +7 -0
  216. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
  217. package/src/runtime/framework/events/memory-event-repository.ts +928 -0
  218. package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
  219. package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
  220. package/src/runtime/framework/events/test-helpers.ts +78 -0
  221. package/src/runtime/framework/events/types.ts +286 -0
  222. package/src/runtime/framework/index.ts +7 -0
  223. package/src/runtime/framework/load-node-sqlite.ts +17 -0
  224. package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
  225. package/src/runtime/framework/mailbox/coalescer.ts +83 -0
  226. package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
  227. package/src/runtime/framework/mailbox/identity.test.ts +38 -0
  228. package/src/runtime/framework/mailbox/identity.ts +38 -0
  229. package/src/runtime/framework/mailbox/index.ts +7 -0
  230. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
  231. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
  232. package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
  233. package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
  234. package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
  235. package/src/runtime/framework/mailbox/types.ts +139 -0
  236. package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
  237. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
  238. package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
  239. package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
  240. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  241. package/src/runtime/framework/participation-manager.test.ts +108 -0
  242. package/src/runtime/framework/participation-manager.ts +244 -0
  243. package/src/runtime/framework/plugins/contracts.ts +382 -0
  244. package/src/runtime/framework/plugins/index.ts +4 -0
  245. package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
  246. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
  247. package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
  248. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
  249. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
  250. package/src/runtime/framework/runtime.ts +1756 -0
  251. package/src/runtime/framework/serial-task-queue.ts +14 -0
  252. package/src/runtime/framework/state/contracts.ts +49 -0
  253. package/src/runtime/framework/state/current-state-store.ts +184 -0
  254. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
  255. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
  256. package/src/runtime/framework/state/freshness.ts +72 -0
  257. package/src/runtime/framework/state/history/contracts.ts +150 -0
  258. package/src/runtime/framework/state/history/history-writer.ts +194 -0
  259. package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
  260. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
  261. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
  262. package/src/runtime/framework/state/history/state-history.test.ts +251 -0
  263. package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
  264. package/src/runtime/framework/state/index.ts +13 -0
  265. package/src/runtime/framework/state/state-core.test.ts +197 -0
  266. package/src/runtime/framework/state/state-ingress.ts +95 -0
  267. package/src/runtime/framework/state/state-provider.ts +62 -0
  268. package/src/runtime/framework/state/types.ts +155 -0
  269. package/src/runtime/game-sync-protocol.test.ts +123 -0
  270. package/src/runtime/game-sync-protocol.ts +261 -0
  271. package/src/runtime/mailbox-host-relay.test.ts +248 -0
  272. package/src/runtime/mailbox-host-relay.ts +300 -0
  273. package/src/runtime/observability/factory.ts +188 -0
  274. package/src/runtime/observability/index.ts +6 -0
  275. package/src/runtime/observability/observability.test.ts +561 -0
  276. package/src/runtime/observability/recorder.ts +209 -0
  277. package/src/runtime/observability/redaction.ts +154 -0
  278. package/src/runtime/observability/reporter.ts +154 -0
  279. package/src/runtime/observability/sinks.ts +135 -0
  280. package/src/runtime/observability/types.ts +92 -0
  281. package/src/runtime/owner-control.test.ts +153 -0
  282. package/src/runtime/owner-control.ts +206 -42
  283. package/src/runtime/parent-process-watch.test.ts +27 -0
  284. package/src/runtime/parent-process-watch.ts +51 -0
  285. package/src/runtime/pending-event-handoff.test.ts +29 -0
  286. package/src/runtime/pending-event-handoff.ts +61 -0
  287. package/src/runtime/raw-ws-log.test.ts +86 -17
  288. package/src/runtime/raw-ws-log.ts +230 -21
  289. package/src/runtime/runtime-logger.test.ts +58 -0
  290. package/src/runtime/runtime-logger.ts +10 -13
  291. package/src/runtime/runtime-persistence.test.ts +26 -0
  292. package/src/runtime/runtime.test.ts +1704 -0
  293. package/src/runtime/ws-client.test.ts +496 -103
  294. package/src/runtime/ws-client.ts +546 -166
  295. package/src/sdk/action.ts +3 -1
  296. package/src/sdk/index.ts +4 -19
  297. package/src/sdk/perception-plugin/index.test.ts +22 -0
  298. package/src/sdk/perception-plugin/index.ts +285 -0
  299. package/src/sdk/strategy-plugin/index.test.ts +952 -0
  300. package/src/sdk/strategy-plugin/index.ts +1324 -0
  301. package/src/sdk/types.ts +3 -1
  302. package/src/short-command/classifier.test.ts +107 -0
  303. package/src/short-command/classifier.ts +169 -0
  304. package/src/short-command/index.ts +7 -0
  305. package/src/short-command/presenter.test.ts +119 -0
  306. package/src/short-command/presenter.ts +308 -0
  307. package/src/short-command/process-io.ts +13 -0
  308. package/src/short-command/response-contract.ts +58 -0
  309. package/src/short-command/runner.test.ts +78 -0
  310. package/src/short-command/runner.ts +164 -0
  311. package/src/short-command/sensitive-data-filter.test.ts +56 -0
  312. package/src/short-command/sensitive-data-filter.ts +123 -0
  313. package/src/short-command/transport-response.test.ts +39 -0
  314. package/src/short-command/transport-response.ts +89 -0
  315. package/src/short-command/types.ts +92 -0
  316. package/src/strategies/avoid-lone.ts +18 -11
  317. package/src/strategies/avoid-players.ts +29 -13
  318. package/src/strategies/corpse-patrol.ts +29 -11
  319. package/src/strategies/crab-sabotage.ts +31 -18
  320. package/src/strategies/custom-module.test.ts +3 -5
  321. package/src/strategies/find-player.ts +34 -15
  322. package/src/strategies/game-utils.test.ts +42 -0
  323. package/src/strategies/game-utils.ts +143 -53
  324. package/src/strategies/goals/avoid-lone-top.ts +22 -1
  325. package/src/strategies/goals/avoid-players-top.test.ts +13 -0
  326. package/src/strategies/goals/avoid-players-top.ts +6 -5
  327. package/src/strategies/goals/corpse-patrol-top.ts +9 -2
  328. package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
  329. package/src/strategies/goals/crab-sabotage-top.ts +7 -1
  330. package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
  331. package/src/strategies/goals/find-player-top.ts +47 -3
  332. package/src/strategies/goals/flee-players-goal.ts +2 -0
  333. package/src/strategies/goals/follow-companion-goal.ts +27 -3
  334. package/src/strategies/goals/hide-top.ts +47 -5
  335. package/src/strategies/goals/keep-away-goal.ts +24 -2
  336. package/src/strategies/goals/kill-frenzy-top.ts +12 -2
  337. package/src/strategies/goals/kill-lone-top.test.ts +72 -0
  338. package/src/strategies/goals/kill-lone-top.ts +8 -6
  339. package/src/strategies/goals/kill-target-goal.ts +16 -7
  340. package/src/strategies/goals/kill-target-top.ts +16 -2
  341. package/src/strategies/goals/linger-corpse-goal.ts +11 -3
  342. package/src/strategies/goals/lone-kill-core.ts +4 -2
  343. package/src/strategies/goals/move-room-goal.ts +46 -4
  344. package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
  345. package/src/strategies/goals/normal-shrimp-top.ts +18 -18
  346. package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
  347. package/src/strategies/goals/paradise-fish-top.ts +16 -6
  348. package/src/strategies/goals/patrol-top.ts +14 -3
  349. package/src/strategies/goals/report-patrol-top.ts +14 -3
  350. package/src/strategies/goals/safe-task-goal.ts +32 -4
  351. package/src/strategies/goals/social-task-top.ts +39 -8
  352. package/src/strategies/goals/task-kill-report-top.ts +33 -10
  353. package/src/strategies/goals/task-only-top.test.ts +89 -0
  354. package/src/strategies/goals/task-only-top.ts +9 -2
  355. package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
  356. package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
  357. package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
  358. package/src/strategies/greeting.ts +10 -3
  359. package/src/strategies/hide-spots.ts +4 -0
  360. package/src/strategies/hide.ts +35 -20
  361. package/src/strategies/kill-frenzy.ts +18 -12
  362. package/src/strategies/kill-lone.ts +43 -12
  363. package/src/strategies/kill-target.ts +34 -17
  364. package/src/strategies/lone-kill-task.ts +31 -18
  365. package/src/strategies/move-room.ts +32 -15
  366. package/src/strategies/off-route-points.ts +12 -4
  367. package/src/strategies/paradise-fish.ts +49 -14
  368. package/src/strategies/pathfind/astar-path.test.ts +73 -0
  369. package/src/strategies/pathfind/astar-path.ts +196 -0
  370. package/src/strategies/pathfind/escape-planner.test.ts +27 -1
  371. package/src/strategies/pathfind/escape-planner.ts +108 -0
  372. package/src/strategies/patrol.ts +18 -11
  373. package/src/strategies/report-patrol.ts +18 -11
  374. package/src/strategies/shrimp-memory.ts +66 -14
  375. package/src/strategies/social-task.ts +49 -45
  376. package/src/strategies/task-kill-report.ts +34 -16
  377. package/src/strategies/task-only.test.ts +124 -0
  378. package/src/strategies/task-only.ts +20 -11
  379. package/src/strategies/task-report.ts +29 -11
  380. package/src/strategies/types.ts +29 -62
  381. package/src/strategies/warrior-memory.ts +44 -14
  382. package/scripts/check_monitor.test.mjs +0 -212
  383. package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
  384. package/src/assets/clawclaw-ascii-map.txt +0 -40
  385. package/src/commands/do.test.ts +0 -117
  386. package/src/commands/do.ts +0 -195
  387. package/src/commands/game-monitor-status.test.ts +0 -58
  388. package/src/commands/game-start-plan.test.ts +0 -356
  389. package/src/commands/game.ts +0 -2046
  390. package/src/commands/history-player.test.ts +0 -105
  391. package/src/commands/history.ts +0 -573
  392. package/src/commands/knowledge.test.ts +0 -13
  393. package/src/commands/knowledge.ts +0 -176
  394. package/src/commands/meeting-history.test.ts +0 -106
  395. package/src/commands/state.ts +0 -46
  396. package/src/commands/watch.test.ts +0 -1313
  397. package/src/commands/watch.ts +0 -824
  398. package/src/lib/knowledge-store.test.ts +0 -170
  399. package/src/lib/knowledge-store.ts +0 -369
  400. package/src/perception/player-history-store.test.ts +0 -177
  401. package/src/perception/player-history-store.ts +0 -262
  402. package/src/pipeline/event-store.test.ts +0 -28
  403. package/src/pipeline/event-store.ts +0 -193
  404. package/src/pipeline/pipeline.ts +0 -35
  405. package/src/runtime/event-daemon.test.ts +0 -268
  406. package/src/runtime/event-daemon.ts +0 -531
  407. package/src/runtime/room-lobby-runtime.test.ts +0 -95
  408. package/src/runtime/room-lobby-runtime.ts +0 -367
  409. package/src/strategies/avoid-players.knowledge.md +0 -19
  410. package/src/strategies/kill-lone.knowledge.md +0 -17
  411. package/src/strategies/knowledge-contract.ts +0 -85
  412. package/src/strategies/loader.test.ts +0 -710
  413. package/src/strategies/loader.ts +0 -183
  414. package/src/strategies/new-events-backfill.ts +0 -98
  415. package/src/strategies/paradise-fish.knowledge.md +0 -19
  416. package/src/strategies/scanner.ts +0 -238
  417. package/src/strategies/shrimp-memory.knowledge.md +0 -19
  418. package/src/strategies/social-task.test.ts +0 -28
  419. package/src/strategies/spawn.ts +0 -82
  420. package/src/strategies/strategy-loop.test.ts +0 -15
  421. package/src/strategies/strategy-loop.ts +0 -748
  422. package/src/strategies/warrior-memory.knowledge.md +0 -21
@@ -0,0 +1,2055 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { AuthProfile } from '../../../../lib/auth.js';
3
+ import {
4
+ apiErrorCode,
5
+ apiErrorMessage,
6
+ normalizeCompetitionStatusResponse,
7
+ serializeError,
8
+ } from '../../../../lib/competition.js';
9
+ import {
10
+ DEFAULT_MATCH_TIMEOUT_MS,
11
+ DEFAULT_WAITING_HEARTBEAT_MS,
12
+ } from '../../../../lib/match-state.js';
13
+ import {
14
+ businessFailureFromResult,
15
+ classifyLeaveQueueResult,
16
+ leaveFailureError,
17
+ } from '../../../../lib/participation-leave.js';
18
+ import {
19
+ isRoomMode,
20
+ isTrainingRoomMode,
21
+ queueMode,
22
+ queueRoomCode,
23
+ queueStatus,
24
+ unwrapData,
25
+ type RoomSnapshot,
26
+ } from '../../../../lib/room.js';
27
+ import type {
28
+ WsCloseInfo,
29
+ WsFrameMeta,
30
+ WsInputFrame,
31
+ WsRecoveryStartedInfo,
32
+ } from '../../../ws-client.js';
33
+ import {
34
+ type RuntimeInputAcceptance,
35
+ type RuntimeInputBatch,
36
+ type RuntimeSourceContext,
37
+ type RuntimeSourceEvent,
38
+ type RuntimeSourcePlugin,
39
+ type RuntimeSourceStopHandle,
40
+ } from '../../../framework/plugins/index.js';
41
+ import type { RuntimeScope } from '../../../framework/state/index.js';
42
+ import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
43
+ import { normalizeGameSyncEvent } from '../../../../pipeline/game-sync-event-normalization.js';
44
+ import {
45
+ projectClawclawRoomState,
46
+ } from '../../../clawclaw-room-state.js';
47
+ import {
48
+ clawclawStageFromGameEvents,
49
+ clawclawStageFromGameState,
50
+ isClawclawRuntimeState,
51
+ type ClawclawRuntimeCause,
52
+ type ClawclawRuntimeConnection,
53
+ type ClawclawRuntimeStage,
54
+ type ClawclawRuntimeState,
55
+ type ClawclawRuntimeTransport,
56
+ } from '../../runtime-state.js';
57
+ import {
58
+ ClawclawGameTransport,
59
+ type ClawclawGameTransportOutcome,
60
+ type ClawclawGameTransportOptions,
61
+ type ClawclawGameTransportPort,
62
+ type ClawclawGameTransportStopReason,
63
+ } from './game-transport.js';
64
+ import {
65
+ ClawclawRoomTransport,
66
+ type ClawclawRoomCloseDecision,
67
+ type ClawclawRoomCloseInfo,
68
+ type ClawclawRoomGameStarted,
69
+ type ClawclawRoomTransportOptions,
70
+ type ClawclawRoomTransportPort,
71
+ } from './room-transport.js';
72
+ import {
73
+ CLAWCLAW_GAME_WS_SOURCE,
74
+ CLAWCLAW_LOBBY_HTTP_SOURCE,
75
+ CLAWCLAW_LOCAL_CONTROL_SOURCE,
76
+ CLAWCLAW_ROOM_WS_SOURCE,
77
+ } from './source-transports.js';
78
+ import type {
79
+ ClawclawSourceClient,
80
+ ClawclawSourceCompletion,
81
+ ClawclawSourceControlIntent,
82
+ ClawclawSourceStartIntent,
83
+ ClawclawSourceTransportFactory,
84
+ } from './types.js';
85
+ import {
86
+ nextPlayerProjection,
87
+ type PlayersChangedPayload,
88
+ } from './player-change-tracker.js';
89
+
90
+ interface RoomFrameMeta {
91
+ connectionId: string;
92
+ receivedAt: string;
93
+ sourceSeq: number | string;
94
+ sourceEventId?: string;
95
+ replay?: boolean;
96
+ }
97
+
98
+ interface LifecycleContinue {
99
+ kind: 'continue';
100
+ queue?: Record<string, any>;
101
+ }
102
+
103
+ interface LifecycleComplete {
104
+ kind: 'complete';
105
+ completion: ClawclawSourceCompletion;
106
+ }
107
+
108
+ type LifecycleStep = LifecycleContinue | LifecycleComplete;
109
+
110
+ function competitionExitReason(code: string | undefined): string {
111
+ switch (code) {
112
+ case 'NO_ACTIVE_COMPETITION': return 'no_active_competition';
113
+ case 'COMPETITION_NOT_OPEN': return 'competition_not_open';
114
+ case 'ALREADY_IN_GAME': return 'already_in_game';
115
+ case 'INVALID_MODE': return 'invalid_mode';
116
+ default: return 'request_failed';
117
+ }
118
+ }
119
+
120
+ type GameAttachGate =
121
+ | { kind: 'attached' }
122
+ | { kind: 'outcome'; outcome: ClawclawGameTransportOutcome }
123
+ | { kind: 'timeout' };
124
+
125
+ type ReconciledTransport = 'game_ws' | 'room_ws';
126
+
127
+ interface SourceCoalescingBoundaryState {
128
+ connected: boolean;
129
+ ended: boolean;
130
+ actionAllowed: boolean;
131
+ }
132
+
133
+ function nextSourceCoalescingBoundaryState(
134
+ state: unknown,
135
+ previous?: SourceCoalescingBoundaryState,
136
+ ): SourceCoalescingBoundaryState | undefined {
137
+ if (!isClawclawRuntimeState(state)) return previous;
138
+ const connected = state.connection === 'connected';
139
+ const freshActionAllowed = state.game_snapshot.status === 'fresh'
140
+ && state.game_snapshot.state.phase === 'wandering'
141
+ && state.game_snapshot.state.you?.is_alive !== false;
142
+ const actionAllowed = connected
143
+ && state.stage === 'game'
144
+ && (state.game_snapshot.status === 'fresh'
145
+ ? freshActionAllowed
146
+ : previous?.actionAllowed === true);
147
+ return {
148
+ connected,
149
+ ended: state.stage === 'ended',
150
+ actionAllowed,
151
+ };
152
+ }
153
+
154
+ function crossesSourceCoalescingBoundary(
155
+ previous: SourceCoalescingBoundaryState | undefined,
156
+ next: SourceCoalescingBoundaryState | undefined,
157
+ ): boolean {
158
+ if (!previous || !next) return false;
159
+ return previous.connected !== next.connected
160
+ || (!previous.ended && next.ended)
161
+ || previous.actionAllowed !== next.actionAllowed;
162
+ }
163
+
164
+ export interface ClawclawSourcePluginOptions {
165
+ client: ClawclawSourceClient;
166
+ profile: Pick<AuthProfile, 'apiKey' | 'agentName'>;
167
+ initialIntent?: ClawclawSourceStartIntent;
168
+ /**
169
+ * Queue state already read by the Owner before Runtime construction. It is
170
+ * consumed exactly once so Runtime session recovery and Source startup use
171
+ * the same authoritative observation instead of racing two HTTP reads.
172
+ */
173
+ initialQueueState?: Record<string, any>;
174
+ pollIntervalMs?: number;
175
+ maxConsecutivePollFailures?: number;
176
+ roomReturnPollMs?: number;
177
+ matchWaitingIntervalMs?: number;
178
+ matchTimeoutMs?: number;
179
+ gameFirstStateTimeoutMs?: number;
180
+ roomAttachReconcileAfterMs?: number;
181
+ reconcileBaseDelayMs?: number;
182
+ reconcileMaxDelayMs?: number;
183
+ roomWebSocketFactory?: ClawclawRoomTransportOptions['webSocketFactory'];
184
+ transports?: Partial<ClawclawSourceTransportFactory>;
185
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
186
+ clock?: () => number;
187
+ }
188
+
189
+ function defaultSleep(ms: number, signal: AbortSignal): Promise<void> {
190
+ if (signal.aborted) return Promise.resolve();
191
+ return new Promise((resolve) => {
192
+ const timer = setTimeout(finish, ms);
193
+ const onAbort = (): void => finish();
194
+ function finish(): void {
195
+ clearTimeout(timer);
196
+ signal.removeEventListener('abort', onAbort);
197
+ resolve();
198
+ }
199
+ signal.addEventListener('abort', onAbort, { once: true });
200
+ });
201
+ }
202
+
203
+ export function normalizeClawclawQueueState(value: unknown): Record<string, any> {
204
+ const unwrapped = unwrapData(value);
205
+ return unwrapped && typeof unwrapped === 'object' && !Array.isArray(unwrapped)
206
+ ? structuredClone(unwrapped)
207
+ : {};
208
+ }
209
+
210
+ export function clawclawQueueGameId(value: unknown): string | undefined {
211
+ const data = normalizeClawclawQueueState(value);
212
+ return typeof data.game_id === 'string' && data.game_id.length > 0
213
+ ? data.game_id
214
+ : undefined;
215
+ }
216
+
217
+ function spectateUrl(value: unknown): string | undefined {
218
+ const data = normalizeClawclawQueueState(value);
219
+ const candidate = data.spectate_url ?? data.url;
220
+ return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined;
221
+ }
222
+
223
+ function normalizeBackendEvent(value: unknown): Record<string, any> {
224
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
225
+ throw new TypeError('ClawClaw backend Event must be an object.');
226
+ }
227
+ const raw = value as Record<string, any>;
228
+ if (typeof raw.type !== 'string' || raw.type.length === 0) {
229
+ throw new TypeError('ClawClaw backend Event requires type.');
230
+ }
231
+ const { type, data, ...rest } = raw;
232
+ return {
233
+ ...rest,
234
+ ...(data && typeof data === 'object' && !Array.isArray(data) ? data : {}),
235
+ type,
236
+ };
237
+ }
238
+
239
+ function eventSourceId(event: Record<string, any>): string | undefined {
240
+ const value = event.event_id ?? event.eventId;
241
+ return value === undefined ? undefined : String(value);
242
+ }
243
+
244
+ function eventSourceSequence(event: Record<string, any>): number | string | undefined {
245
+ return event.source_seq ?? event.sequence ?? event.seq;
246
+ }
247
+
248
+ function sameScope(left: RuntimeScope, right: RuntimeScope): boolean {
249
+ return left.adapterId === right.adapterId
250
+ && left.accountId === right.accountId
251
+ && left.sessionId === right.sessionId
252
+ && left.segmentId === right.segmentId;
253
+ }
254
+
255
+ function numericGameTick(value: unknown): number | undefined {
256
+ const tick = typeof value === 'number'
257
+ ? value
258
+ : typeof value === 'string' && value.trim() !== ''
259
+ ? Number(value)
260
+ : Number.NaN;
261
+ return Number.isFinite(tick) ? tick : undefined;
262
+ }
263
+
264
+ export function isActiveClawclawQueueStatus(status: string | undefined): boolean {
265
+ return status === 'queued'
266
+ || status === 'already_in_queue'
267
+ || status === 'allocating'
268
+ || status === 'in_room'
269
+ || status === 'allocated';
270
+ }
271
+
272
+ /**
273
+ * The only ClawClaw Source loaded by Runtime. It owns the complete external
274
+ * lifecycle and submits one complete InputBatch for every meaningful input.
275
+ */
276
+ export class ClawclawSourcePlugin
277
+ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
278
+ readonly kind = 'source' as const;
279
+ readonly id = 'clawclaw.source';
280
+ readonly version = '2';
281
+
282
+ private readonly client: ClawclawSourceClient;
283
+ private readonly profile: Pick<AuthProfile, 'apiKey' | 'agentName'>;
284
+ private readonly initialIntent: ClawclawSourceStartIntent;
285
+ private readonly pollIntervalMs: number;
286
+ private readonly maxConsecutivePollFailures: number;
287
+ private readonly roomReturnPollMs: number;
288
+ private readonly matchWaitingIntervalMs: number;
289
+ private readonly matchTimeoutMs: number;
290
+ private readonly gameFirstStateTimeoutMs: number;
291
+ private readonly roomAttachReconcileAfterMs: number;
292
+ private readonly reconcileBaseDelayMs: number;
293
+ private readonly reconcileMaxDelayMs: number;
294
+ private readonly roomWebSocketFactory?: ClawclawRoomTransportOptions['webSocketFactory'];
295
+ private readonly createGameTransport: (options: ClawclawGameTransportOptions) => ClawclawGameTransportPort;
296
+ private readonly createRoomTransport: (options: ClawclawRoomTransportOptions) => ClawclawRoomTransportPort;
297
+ private readonly sleep: (ms: number, signal: AbortSignal) => Promise<void>;
298
+ private readonly clock: () => number;
299
+ private initialQueueState?: Record<string, any>;
300
+ private readonly abortController = new AbortController();
301
+ private readonly sourceInstanceId = randomUUID();
302
+ private readonly gameConnectionsWithState = new Set<string>();
303
+ private readonly roomConnectionsWithSnapshot = new Set<string>();
304
+ private runtime: RuntimeSourceContext<Record<string, any>, Record<string, unknown>> | null = null;
305
+ private gameTransport?: ClawclawGameTransportPort;
306
+ private roomTransport?: ClawclawRoomTransportPort;
307
+ private activeGameConnectionId?: string;
308
+ private activeRoomConnectionId?: string;
309
+ private localSourceSeq = 0;
310
+ private currentStage: ClawclawRuntimeStage = 'matching';
311
+ private currentTransport: ClawclawRuntimeTransport = 'none';
312
+ private currentConnection: ClawclawRuntimeConnection = 'disconnected';
313
+ private participationMode?: string;
314
+ private currentQueue?: Record<string, any>;
315
+ private currentRoom?: Record<string, any>;
316
+ private trainingRoomControlOverlay: Record<string, any> = {};
317
+ private hasFreshGameSnapshot = false;
318
+ private latestFreshGameState?: Record<string, any>;
319
+ private latestFreshGameTick?: number;
320
+ private playerProjection: PlayerProjection[] = [];
321
+ private playerProjectionInitialized = false;
322
+ private matchStartedAtMs?: number;
323
+ private lastMatchWaitingAtMs?: number;
324
+ private matchTimedOut = false;
325
+ private started = false;
326
+ private finished = false;
327
+ private terminalStateSubmitted = false;
328
+ private leaveRequested = false;
329
+ private lifecyclePromise?: Promise<void>;
330
+ private controlTail: Promise<unknown> = Promise.resolve();
331
+ private inputTail: Promise<void> = Promise.resolve();
332
+ private sourceCoalescingBoundaryState?: SourceCoalescingBoundaryState;
333
+ private actionSafetyGeneration = 0;
334
+ private readonly reconcileAttempts: Record<ReconciledTransport, number> = {
335
+ game_ws: 0,
336
+ room_ws: 0,
337
+ };
338
+ private resolveCompletion!: (completion: ClawclawSourceCompletion) => void;
339
+ private readonly completionPromise: Promise<ClawclawSourceCompletion>;
340
+
341
+ constructor(options: ClawclawSourcePluginOptions) {
342
+ this.client = options.client;
343
+ this.profile = options.profile;
344
+ this.initialIntent = options.initialIntent ?? { kind: 'resume' };
345
+ this.initialQueueState = options.initialQueueState
346
+ ? normalizeClawclawQueueState(options.initialQueueState)
347
+ : undefined;
348
+ this.participationMode = this.initialIntent.kind === 'match'
349
+ ? this.initialIntent.mode ?? 'match'
350
+ : this.initialIntent.kind === 'create_room'
351
+ ? this.initialIntent.roomType ?? 'room'
352
+ : this.initialIntent.kind === 'join_room'
353
+ ? 'room'
354
+ : undefined;
355
+ this.pollIntervalMs = options.pollIntervalMs ?? 2_000;
356
+ this.maxConsecutivePollFailures = options.maxConsecutivePollFailures ?? 3;
357
+ this.roomReturnPollMs = options.roomReturnPollMs ?? 1_000;
358
+ this.matchWaitingIntervalMs = Math.max(
359
+ 1,
360
+ options.matchWaitingIntervalMs ?? DEFAULT_WAITING_HEARTBEAT_MS,
361
+ );
362
+ this.matchTimeoutMs = Math.max(1, options.matchTimeoutMs ?? DEFAULT_MATCH_TIMEOUT_MS);
363
+ this.gameFirstStateTimeoutMs = Math.max(1, options.gameFirstStateTimeoutMs ?? 30_000);
364
+ this.roomAttachReconcileAfterMs = Math.max(1, options.roomAttachReconcileAfterMs ?? 30_000);
365
+ this.reconcileBaseDelayMs = Math.max(0, options.reconcileBaseDelayMs ?? 2_000);
366
+ this.reconcileMaxDelayMs = Math.max(
367
+ this.reconcileBaseDelayMs,
368
+ options.reconcileMaxDelayMs ?? 30_000,
369
+ );
370
+ this.roomWebSocketFactory = options.roomWebSocketFactory;
371
+ this.createGameTransport = options.transports?.game
372
+ ?? ((transportOptions) => new ClawclawGameTransport(transportOptions));
373
+ this.createRoomTransport = options.transports?.room
374
+ ?? ((transportOptions) => new ClawclawRoomTransport(transportOptions));
375
+ this.sleep = options.sleep ?? defaultSleep;
376
+ this.clock = options.clock ?? Date.now;
377
+ this.completionPromise = new Promise((resolve) => { this.resolveCompletion = resolve; });
378
+ }
379
+
380
+ start(
381
+ runtime: RuntimeSourceContext<Record<string, any>, Record<string, unknown>>,
382
+ ): RuntimeSourceStopHandle {
383
+ if (this.started) throw new Error('ClawClaw Source is already started.');
384
+ this.started = true;
385
+ this.runtime = runtime;
386
+ this.lifecyclePromise = this.runLifecycle().then(
387
+ (completion) => this.completeLifecycle(completion),
388
+ (error) => this.completeLifecycle(
389
+ this.abortController.signal.aborted
390
+ ? { reason: 'stopped' }
391
+ : { reason: 'error', error },
392
+ ),
393
+ );
394
+ return {
395
+ stop: () => this.stop('shutdown'),
396
+ };
397
+ }
398
+
399
+ waitForCompletion(): Promise<ClawclawSourceCompletion> {
400
+ return this.completionPromise;
401
+ }
402
+
403
+ submitIntent(intent: ClawclawSourceControlIntent): Promise<Record<string, any> | void> {
404
+ if (!this.started || !this.runtime) throw new Error('ClawClaw Source is not started.');
405
+ const operation = this.controlTail.then(() => this.handleControlIntent(intent));
406
+ this.controlTail = operation.catch(() => {});
407
+ return operation;
408
+ }
409
+
410
+ /** Inserts an exact, non-coalescible boundary for an Agent Event query. */
411
+ async submitEventsQueryBoundary(
412
+ requestId: string,
413
+ ): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
414
+ if (!this.started || !this.runtime || this.finished) {
415
+ throw new Error('ClawClaw Source is not available for an Events query boundary.');
416
+ }
417
+ if (typeof requestId !== 'string' || !requestId.trim()) {
418
+ throw new TypeError('Events query requestId must not be empty.');
419
+ }
420
+ const sourceSeq = ++this.localSourceSeq;
421
+ const receivedAt = new Date().toISOString();
422
+ return this.enqueueInput(() => {
423
+ return {
424
+ scope: this.requireRuntime().currentSegment().scope,
425
+ sourceId: CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId,
426
+ connectionId: this.activeGameConnectionId ?? this.activeRoomConnectionId ?? 'events-query',
427
+ sourceKey: `events-query:${this.sourceInstanceId}:${requestId}`,
428
+ sourceSeq,
429
+ state: {
430
+ ...this.runtimeState('agent_events_query'),
431
+ control: { type: 'events_query', request_id: requestId },
432
+ },
433
+ events: [],
434
+ completeness: 'complete',
435
+ coalescing: 'forbidden',
436
+ receivedAt,
437
+ };
438
+ });
439
+ }
440
+
441
+ async stop(reason: 'shutdown' = 'shutdown'): Promise<void> {
442
+ if (this.finished) return;
443
+ if (!this.abortController.signal.aborted) {
444
+ try {
445
+ await this.submitControlState({ kind: 'stop' });
446
+ } catch {}
447
+ this.abortController.abort(new Error(reason));
448
+ }
449
+ await Promise.allSettled([
450
+ this.gameTransport?.stop('shutdown'),
451
+ this.roomTransport?.stop('shutdown'),
452
+ ].filter((value): value is Promise<void> => value !== undefined));
453
+ await this.controlTail.catch(() => {});
454
+ await this.lifecyclePromise;
455
+ await this.inputTail.catch(() => {});
456
+ }
457
+
458
+ private async runLifecycle(): Promise<ClawclawSourceCompletion> {
459
+ let queue: Record<string, any> | undefined = await this.applyInitialIntent();
460
+ while (!this.abortController.signal.aborted) {
461
+ if (!queue) queue = await this.readQueueWithRetry();
462
+ if (this.abortController.signal.aborted) break;
463
+ if (this.matchTimedOut) return { reason: 'match_timeout' };
464
+ const status = queueStatus(queue);
465
+
466
+ if (status === 'queued' || status === 'already_in_queue' || status === 'allocating') {
467
+ await this.sleep(this.pollIntervalMs, this.abortController.signal);
468
+ queue = undefined;
469
+ continue;
470
+ }
471
+ if (status === 'in_room') {
472
+ const step = await this.runRoom(queue);
473
+ if (step.kind === 'complete') return step.completion;
474
+ queue = step.queue;
475
+ continue;
476
+ }
477
+ if (status === 'allocated') {
478
+ const step = await this.runGame(queue);
479
+ if (step.kind === 'complete') return step.completion;
480
+ queue = step.queue;
481
+ continue;
482
+ }
483
+ if (status === 'not_in_queue') {
484
+ if (this.currentStage !== 'ended') {
485
+ this.currentStage = 'ended';
486
+ this.currentTransport = 'lobby_http';
487
+ this.currentConnection = 'connected';
488
+ await this.submitCurrentState('ending', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http');
489
+ }
490
+ return { reason: this.leaveRequested ? 'left' : 'not_participating' };
491
+ }
492
+
493
+ this.diagnostic('runtime.source.queue_status_unknown', { status }, 'warn');
494
+ await this.sleep(this.pollIntervalMs, this.abortController.signal);
495
+ queue = undefined;
496
+ }
497
+ return { reason: 'stopped' };
498
+ }
499
+
500
+ private async applyInitialIntent(): Promise<Record<string, any>> {
501
+ if (this.initialIntent.kind === 'resume') {
502
+ const queue = await this.readQueueRawWithRetry();
503
+ await this.acceptQueueState(queue, this.resumeLifecycleEvents(queue, 'resume'));
504
+ return queue;
505
+ }
506
+
507
+ if (this.initialIntent.kind === 'match') {
508
+ const existing = await this.readQueueRawWithRetry();
509
+ if (isActiveClawclawQueueStatus(queueStatus(existing))) {
510
+ await this.acceptQueueState(existing, this.resumeLifecycleEvents(existing, 'match'));
511
+ return existing;
512
+ }
513
+ this.requireInactiveParticipation(existing, 'start matchmaking');
514
+ let joined: Record<string, any>;
515
+ try {
516
+ joined = normalizeClawclawQueueState(await this.client.joinQueue({
517
+ gameType: 'clawclaw',
518
+ mode: this.initialIntent.mode ?? 'match',
519
+ agentType: this.initialIntent.agentType,
520
+ monitorStatus: this.initialIntent.monitorStatus,
521
+ llmModel: this.initialIntent.llmModel,
522
+ }));
523
+ } catch (error) {
524
+ try {
525
+ return await this.reconcileInitialRequest(
526
+ 'join_queue',
527
+ error,
528
+ (queue) => isActiveClawclawQueueStatus(queueStatus(queue)),
529
+ (queue) => [
530
+ this.sessionRecoveredEvent('join_queue', queue),
531
+ this.joinedEvent(queue, { recovered: true }),
532
+ ],
533
+ );
534
+ } catch (reconciledError) {
535
+ if (this.initialIntent.mode === 'competition') {
536
+ await this.submitCompetitionStartFailure(reconciledError);
537
+ }
538
+ throw reconciledError;
539
+ }
540
+ }
541
+ if (isActiveClawclawQueueStatus(queueStatus(joined))) {
542
+ await this.acceptQueueState(joined, [this.joinedEvent(joined)]);
543
+ return joined;
544
+ }
545
+ const reconciled = await this.readQueueRawWithRetry();
546
+ await this.acceptQueueState(reconciled, [this.joinedEvent({ ...joined, ...reconciled })]);
547
+ if (isActiveClawclawQueueStatus(queueStatus(reconciled))) return reconciled;
548
+ throw new Error('Match join completed without creating an active participation.');
549
+ }
550
+
551
+ if (this.initialIntent.kind === 'create_room') {
552
+ const existing = await this.readQueueRawWithRetry();
553
+ if (queueStatus(existing) === 'in_room') {
554
+ await this.acceptQueueState(existing, this.resumeLifecycleEvents(existing, 'create_room'));
555
+ return existing;
556
+ }
557
+ this.requireInactiveParticipation(existing, 'create a room');
558
+ let created: Record<string, any>;
559
+ try {
560
+ created = normalizeClawclawQueueState(
561
+ await this.client.createRoom({
562
+ roomType: this.initialIntent.roomType,
563
+ agentType: this.initialIntent.agentType,
564
+ monitorStatus: this.initialIntent.monitorStatus,
565
+ llmModel: this.initialIntent.llmModel,
566
+ }),
567
+ );
568
+ } catch (error) {
569
+ return this.reconcileInitialRequest(
570
+ 'create_room',
571
+ error,
572
+ (queue) => queueStatus(queue) === 'in_room',
573
+ (queue) => [
574
+ this.sessionRecoveredEvent('create_room', queue),
575
+ this.roomEntryEvent('room_created', queue, { recovered: true }),
576
+ ],
577
+ );
578
+ }
579
+ const queue = {
580
+ status: 'in_room',
581
+ mode: this.initialIntent.roomType ?? 'room',
582
+ ...created,
583
+ };
584
+ await this.acceptQueueState(queue, [this.roomEntryEvent('room_created', queue)]);
585
+ return queue;
586
+ }
587
+
588
+ const targetRoomCode = this.initialIntent.roomCode;
589
+ const existing = await this.readQueueRawWithRetry();
590
+ const existingStatus = queueStatus(existing);
591
+ const existingRoomCode = queueRoomCode(existing);
592
+ if (existingStatus === 'in_room' && existingRoomCode === targetRoomCode) {
593
+ await this.acceptQueueState(existing, this.resumeLifecycleEvents(existing, 'join_room'));
594
+ return existing;
595
+ }
596
+ if (existingStatus === 'in_room') {
597
+ if (!existingRoomCode) {
598
+ throw new Error('Cannot switch rooms because the current room identity is unavailable.');
599
+ }
600
+ await this.client.leaveRoom();
601
+ } else {
602
+ this.requireInactiveParticipation(existing, `join room ${targetRoomCode}`);
603
+ }
604
+
605
+ let joined: Record<string, any>;
606
+ try {
607
+ joined = normalizeClawclawQueueState(await this.client.joinRoom(targetRoomCode, {
608
+ agentType: this.initialIntent.agentType,
609
+ monitorStatus: this.initialIntent.monitorStatus,
610
+ llmModel: this.initialIntent.llmModel,
611
+ }));
612
+ } catch (error) {
613
+ return this.reconcileInitialRequest(
614
+ 'join_room',
615
+ error,
616
+ (queue) => (
617
+ queueStatus(queue) === 'in_room'
618
+ && queueRoomCode(queue) === targetRoomCode
619
+ ),
620
+ (queue) => [
621
+ this.sessionRecoveredEvent('join_room', queue),
622
+ this.roomEntryEvent('room_joined', queue, { recovered: true }),
623
+ ],
624
+ );
625
+ }
626
+ const queue = {
627
+ status: 'in_room',
628
+ mode: 'room',
629
+ room_code: targetRoomCode,
630
+ ...joined,
631
+ };
632
+ await this.acceptQueueState(queue, [this.roomEntryEvent('room_joined', queue)]);
633
+ return queue;
634
+ }
635
+
636
+ private requireInactiveParticipation(queue: Record<string, any>, operation: string): void {
637
+ const status = queueStatus(queue);
638
+ if (status === 'not_in_queue') return;
639
+ if (status === 'allocated' && isRoomMode(queueMode(queue))) {
640
+ throw new Error(`Cannot ${operation} while a room game is allocated.`);
641
+ }
642
+ if (isActiveClawclawQueueStatus(status)) {
643
+ throw new Error(`Cannot ${operation} while participation status is ${status}.`);
644
+ }
645
+ throw new Error(`Cannot ${operation} because participation status is unknown.`);
646
+ }
647
+
648
+ private async reconcileInitialRequest(
649
+ operation: string,
650
+ originalError: unknown,
651
+ accepted: (queue: Record<string, any>) => boolean,
652
+ lifecycleEvents: (queue: Record<string, any>) => Record<string, unknown>[],
653
+ ): Promise<Record<string, any>> {
654
+ this.diagnostic('runtime.source.initial_request_reconcile', {
655
+ operation,
656
+ error: originalError instanceof Error ? originalError.message : String(originalError),
657
+ }, 'warn');
658
+ let queue: Record<string, any>;
659
+ try {
660
+ queue = await this.readQueueRawWithRetry();
661
+ } catch (reconcileError) {
662
+ this.diagnostic('runtime.source.initial_request_reconcile_failed', {
663
+ operation,
664
+ error: reconcileError instanceof Error ? reconcileError.message : String(reconcileError),
665
+ }, 'warn');
666
+ throw originalError;
667
+ }
668
+ if (!accepted(queue)) throw originalError;
669
+ await this.acceptQueueState(queue, lifecycleEvents(queue));
670
+ this.diagnostic('runtime.source.initial_request_reconciled', {
671
+ operation,
672
+ status: queueStatus(queue),
673
+ room_code: queueRoomCode(queue),
674
+ game_id: clawclawQueueGameId(queue),
675
+ }, 'info');
676
+ return queue;
677
+ }
678
+
679
+ private async readQueueWithRetry(): Promise<Record<string, any>> {
680
+ const queue = await this.readQueueRawWithRetry();
681
+ await this.acceptQueueState(queue);
682
+ return queue;
683
+ }
684
+
685
+ private async readQueueRawWithRetry(): Promise<Record<string, any>> {
686
+ if (this.initialQueueState) {
687
+ const queue = this.initialQueueState;
688
+ this.initialQueueState = undefined;
689
+ return structuredClone(queue);
690
+ }
691
+ let failures = 0;
692
+ while (!this.abortController.signal.aborted) {
693
+ try {
694
+ return normalizeClawclawQueueState(await this.client.getQueueStatus('clawclaw'));
695
+ } catch (error) {
696
+ failures += 1;
697
+ this.currentTransport = 'lobby_http';
698
+ this.currentConnection = 'disconnected';
699
+ const message = error instanceof Error ? error.message : String(error);
700
+ await this.submitCurrentState(
701
+ 'transport_error',
702
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
703
+ 'lobby-http',
704
+ [{
705
+ type: 'poll_error',
706
+ message,
707
+ consecutive_failures: failures,
708
+ retrying: failures < this.maxConsecutivePollFailures,
709
+ }],
710
+ );
711
+ this.diagnostic('runtime.source.poll_failed', {
712
+ consecutive_failures: failures,
713
+ error: message,
714
+ }, 'warn');
715
+ if (failures >= this.maxConsecutivePollFailures) throw error;
716
+ await this.sleep(this.pollIntervalMs, this.abortController.signal);
717
+ }
718
+ }
719
+ throw this.abortController.signal.reason ?? new Error('ClawClaw Source stopped.');
720
+ }
721
+
722
+ private async acceptQueueState(
723
+ queue: Record<string, any>,
724
+ lifecycleEvents: readonly Record<string, unknown>[] = [],
725
+ ): Promise<void> {
726
+ const status = queueStatus(queue);
727
+ const mode = queueMode(queue);
728
+ const roomCode = queueRoomCode(queue);
729
+ const gameId = clawclawQueueGameId(queue);
730
+ const matching = status === 'queued' || status === 'already_in_queue' || status === 'allocating';
731
+ const genericRoomPoll = status === 'in_room' && mode === 'room';
732
+ if (mode && !(genericRoomPoll && isTrainingRoomMode(this.participationMode))) {
733
+ this.participationMode = mode;
734
+ this.requireRuntime().updateMode(mode);
735
+ }
736
+
737
+ if (matching) {
738
+ await this.ensureSegment('matching', mode);
739
+ this.currentStage = 'matching';
740
+ } else if (status === 'in_room') {
741
+ if (roomCode) this.requireRuntime().adoptResumeKey(roomCode);
742
+ await this.ensureSegment('room', roomCode);
743
+ this.currentStage = 'room';
744
+ } else if (status === 'allocated') {
745
+ if (gameId && !isRoomMode(mode)) this.requireRuntime().adoptResumeKey(gameId);
746
+ await this.ensureSegment('game', gameId);
747
+ this.currentStage = 'loading';
748
+ } else if (status === 'not_in_queue') {
749
+ this.currentStage = 'ended';
750
+ } else {
751
+ this.currentStage = 'matching';
752
+ }
753
+ this.currentTransport = 'lobby_http';
754
+ this.currentConnection = 'connected';
755
+ this.currentQueue = structuredClone(queue);
756
+ this.currentRoom = undefined;
757
+ this.hasFreshGameSnapshot = false;
758
+ const events = [...lifecycleEvents];
759
+ if (matching) {
760
+ events.push(...this.matchingLifecycleEvents(queue));
761
+ } else if (status === 'not_in_queue') {
762
+ events.push({
763
+ type: this.leaveRequested ? 'session_left' : 'not_in_queue',
764
+ queue: structuredClone(queue),
765
+ });
766
+ this.resetMatchingLifecycle();
767
+ } else if (status === 'in_room' || status === 'allocated') {
768
+ this.resetMatchingLifecycle();
769
+ }
770
+ await this.submitCurrentState(
771
+ status === 'not_in_queue' ? 'ending' : matching ? 'matching_poll' : 'reconcile',
772
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
773
+ 'lobby-http',
774
+ events,
775
+ );
776
+ }
777
+
778
+ private joinedEvent(
779
+ queue: Record<string, any>,
780
+ flags: Record<string, unknown> = {},
781
+ ): Record<string, unknown> {
782
+ const url = spectateUrl(queue);
783
+ return {
784
+ ...structuredClone(queue),
785
+ queue: structuredClone(queue),
786
+ ...(url ? { url } : {}),
787
+ ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}),
788
+ ...flags,
789
+ type: 'joined',
790
+ };
791
+ }
792
+
793
+ private roomEntryEvent(
794
+ type: 'room_created' | 'room_joined',
795
+ queue: Record<string, any>,
796
+ flags: Record<string, unknown> = {},
797
+ ): Record<string, unknown> {
798
+ const url = spectateUrl(queue);
799
+ return {
800
+ ...structuredClone(queue),
801
+ ...(url ? { spectate_url: url } : {}),
802
+ game_mode: queueMode(queue) ?? 'room',
803
+ ...flags,
804
+ type,
805
+ };
806
+ }
807
+
808
+ private sessionRecoveredEvent(
809
+ operation: string,
810
+ queue: Record<string, any>,
811
+ ): Record<string, unknown> {
812
+ return {
813
+ type: 'session_recovered',
814
+ operation,
815
+ initial_request_confirmation: 'missing_or_failed',
816
+ queue_reconciliation: 'active_participation_confirmed',
817
+ local_history_completeness: 'possibly_incomplete',
818
+ status: queueStatus(queue),
819
+ ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}),
820
+ ...(queueRoomCode(queue) ? { room_code: queueRoomCode(queue) } : {}),
821
+ ...(clawclawQueueGameId(queue) ? { game_id: clawclawQueueGameId(queue) } : {}),
822
+ };
823
+ }
824
+
825
+ private async submitCompetitionStartFailure(error: unknown): Promise<void> {
826
+ const code = apiErrorCode(error);
827
+ let competition: Record<string, any> = {
828
+ status: 'unavailable',
829
+ active: null,
830
+ is_open: null,
831
+ };
832
+ if (this.client.getCompetitionStatus) {
833
+ try {
834
+ competition = normalizeCompetitionStatusResponse(
835
+ await this.client.getCompetitionStatus(),
836
+ );
837
+ } catch (statusError) {
838
+ competition = {
839
+ ...competition,
840
+ error: serializeError(statusError),
841
+ };
842
+ }
843
+ }
844
+ const serialized = serializeError(error);
845
+ this.currentStage = 'ended';
846
+ this.currentTransport = 'lobby_http';
847
+ this.currentConnection = 'disconnected';
848
+ await this.submitCurrentState(
849
+ 'ending',
850
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
851
+ 'lobby-http',
852
+ [{
853
+ type: 'game_start_failed',
854
+ game_mode: 'competition',
855
+ exit_reason: competitionExitReason(code),
856
+ error: {
857
+ ...serialized,
858
+ code: code ?? 'REQUEST_FAILED',
859
+ message: apiErrorMessage(error),
860
+ },
861
+ competition,
862
+ }],
863
+ );
864
+ }
865
+
866
+ private resumeLifecycleEvents(
867
+ queue: Record<string, any>,
868
+ source: ClawclawSourceStartIntent['kind'],
869
+ ): Record<string, unknown>[] {
870
+ const status = queueStatus(queue);
871
+ if (!isActiveClawclawQueueStatus(status)) return [];
872
+ const resumed = {
873
+ type: 'session_resumed',
874
+ source,
875
+ status,
876
+ ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}),
877
+ ...(queueRoomCode(queue) ? { room_code: queueRoomCode(queue) } : {}),
878
+ ...(clawclawQueueGameId(queue) ? { game_id: clawclawQueueGameId(queue) } : {}),
879
+ };
880
+ const roomParticipation = status === 'in_room'
881
+ || (status === 'allocated' && isRoomMode(queueMode(queue)));
882
+ return [
883
+ resumed,
884
+ roomParticipation
885
+ ? this.roomEntryEvent('room_joined', queue, { resumed: true })
886
+ : this.joinedEvent(queue, { resumed: true }),
887
+ ];
888
+ }
889
+
890
+ private matchingLifecycleEvents(queue: Record<string, any>): Record<string, unknown>[] {
891
+ const now = this.clock();
892
+ const events: Record<string, unknown>[] = [];
893
+ if (this.matchStartedAtMs === undefined) {
894
+ this.matchStartedAtMs = now;
895
+ events.push({
896
+ type: 'match_start',
897
+ ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}),
898
+ });
899
+ }
900
+ const waitedSecs = Math.max(0, Math.floor((now - this.matchStartedAtMs) / 1_000));
901
+ if (
902
+ this.lastMatchWaitingAtMs === undefined
903
+ || now - this.lastMatchWaitingAtMs >= this.matchWaitingIntervalMs
904
+ ) {
905
+ this.lastMatchWaitingAtMs = now;
906
+ events.push({
907
+ type: 'match_waiting',
908
+ waited_secs: waitedSecs,
909
+ ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}),
910
+ });
911
+ }
912
+ if (!this.matchTimedOut && now - this.matchStartedAtMs >= this.matchTimeoutMs) {
913
+ this.matchTimedOut = true;
914
+ events.push({
915
+ type: 'match_timeout',
916
+ waited_secs: waitedSecs,
917
+ queue: structuredClone(queue),
918
+ ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}),
919
+ });
920
+ }
921
+ return events;
922
+ }
923
+
924
+ private resetMatchingLifecycle(): void {
925
+ this.matchStartedAtMs = undefined;
926
+ this.lastMatchWaitingAtMs = undefined;
927
+ this.matchTimedOut = false;
928
+ }
929
+
930
+ private async runRoom(queue: Record<string, any>): Promise<LifecycleStep> {
931
+ await this.stopGameTransport('manual');
932
+ const roomCode = queueRoomCode(queue);
933
+ if (roomCode) this.requireRuntime().adoptResumeKey(roomCode);
934
+ await this.ensureSegment('room', roomCode);
935
+ this.currentStage = 'room';
936
+ this.currentTransport = 'room_ws';
937
+ this.currentConnection = 'disconnected';
938
+ this.currentQueue = structuredClone(queue);
939
+ await this.submitCurrentState('reconcile', CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-pending');
940
+
941
+ const transport = this.createRoomTransport({
942
+ url: this.client.lobbyAgentWsUrl,
943
+ apiKey: this.profile.apiKey,
944
+ webSocketFactory: this.roomWebSocketFactory,
945
+ onOpened: async (connectionId, reconnected) => {
946
+ this.activeRoomConnectionId = connectionId;
947
+ this.requireRuntime().bindConnection(CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId);
948
+ this.currentTransport = 'room_ws';
949
+ this.currentConnection = 'connected';
950
+ await this.submitCurrentState(
951
+ 'control',
952
+ CLAWCLAW_ROOM_WS_SOURCE.sourceId,
953
+ connectionId,
954
+ [{ type: 'room_attached', reconnected }],
955
+ );
956
+ },
957
+ onLiveness: (connectionId, atMs) => {
958
+ this.requireRuntime().connectionLiveness(CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, atMs);
959
+ },
960
+ onConnectionChanged: async (connectionId, state) => {
961
+ this.requireRuntime().connectionChanged(
962
+ CLAWCLAW_ROOM_WS_SOURCE.sourceId,
963
+ connectionId,
964
+ state,
965
+ );
966
+ if (this.activeRoomConnectionId !== connectionId) return;
967
+ this.currentConnection = state;
968
+ await this.submitCurrentState('control', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId);
969
+ },
970
+ onClosed: (connectionId, info) => this.handleRoomClose(connectionId, info),
971
+ onFrame: (frame) => this.acceptRoomFrame(frame.snapshot, frame.type, frame.data, frame.meta, frame.terminalPhase),
972
+ onDiagnostic: (name, attributes) => this.diagnostic(name, attributes, 'warn'),
973
+ reconcileAfterMs: this.roomAttachReconcileAfterMs,
974
+ });
975
+ this.roomTransport = transport;
976
+ await transport.start();
977
+ const outcome = await transport.waitForOutcome();
978
+ await transport.flush();
979
+ if (this.roomTransport === transport) this.roomTransport = undefined;
980
+ this.activeRoomConnectionId = undefined;
981
+
982
+ if (outcome.reason === 'game_started') {
983
+ this.applyGameRoute(outcome.event);
984
+ const roomMode = isRoomMode(this.participationMode) ? this.participationMode : 'room';
985
+ return {
986
+ kind: 'continue',
987
+ queue: {
988
+ status: 'allocated',
989
+ mode: roomMode,
990
+ room_code: outcome.roomCode ?? roomCode,
991
+ ...outcome.event,
992
+ },
993
+ };
994
+ }
995
+ if (outcome.reason === 'self_left') return { kind: 'complete', completion: { reason: 'left' } };
996
+ if (outcome.reason === 'room_destroyed') {
997
+ return { kind: 'complete', completion: { reason: 'not_participating' } };
998
+ }
999
+ if (outcome.reason === 'replaced') return { kind: 'complete', completion: { reason: 'replaced' } };
1000
+ if (outcome.reason === 'shutdown' || outcome.reason === 'manual') {
1001
+ return { kind: 'complete', completion: { reason: 'stopped' } };
1002
+ }
1003
+ if (outcome.reason === 'fatal' || outcome.reason === 'error') {
1004
+ return { kind: 'complete', completion: { reason: 'error', error: outcome.error } };
1005
+ }
1006
+ await this.reconcileBackoff('room_ws', outcome.reason);
1007
+ return { kind: 'continue' };
1008
+ }
1009
+
1010
+ private async runGame(queue: Record<string, any>): Promise<LifecycleStep> {
1011
+ await this.stopRoomTransport('manual');
1012
+ this.applyGameRoute(normalizeClawclawQueueState(queue));
1013
+ const mode = queueMode(queue);
1014
+ if (mode) {
1015
+ this.participationMode = mode;
1016
+ this.requireRuntime().updateMode(mode);
1017
+ }
1018
+ const gameId = clawclawQueueGameId(queue);
1019
+ this.client.setExpectedGameSyncGameId(gameId);
1020
+ if (gameId && !isRoomMode(mode)) this.requireRuntime().adoptResumeKey(gameId);
1021
+ await this.ensureSegment('game', gameId);
1022
+ this.currentStage = 'loading';
1023
+ this.currentTransport = 'game_ws';
1024
+ this.currentConnection = 'disconnected';
1025
+ this.currentQueue = structuredClone(queue);
1026
+ this.currentRoom = undefined;
1027
+ this.hasFreshGameSnapshot = false;
1028
+ await this.submitCurrentState('reconcile', CLAWCLAW_GAME_WS_SOURCE.sourceId, 'game-pending');
1029
+
1030
+ const transport = this.createGameTransport({
1031
+ client: this.client,
1032
+ onFrame: (frame) => this.acceptGameFrame(frame),
1033
+ onConnectionOpened: async (connectionId, _reconnected) => {
1034
+ this.activeGameConnectionId = connectionId;
1035
+ this.requireRuntime().bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId);
1036
+ this.currentTransport = 'game_ws';
1037
+ // A physical socket is not action-ready until snapshot/resume finishes.
1038
+ this.currentConnection = 'reconnecting';
1039
+ await this.submitCurrentState(
1040
+ 'control',
1041
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1042
+ connectionId,
1043
+ [],
1044
+ );
1045
+ },
1046
+ onLiveness: (connectionId, atMs) => {
1047
+ this.requireRuntime().connectionLiveness(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, atMs);
1048
+ },
1049
+ onClose: (connectionId, info) => this.handleGameClose(connectionId, info),
1050
+ onConnectAttemptFailed: (error) => {
1051
+ this.diagnostic('runtime.source.connect_failed', {
1052
+ transport: 'game_ws',
1053
+ error: error instanceof Error ? error.message : String(error),
1054
+ }, 'warn');
1055
+ },
1056
+ onProtocolError: (info) => {
1057
+ this.diagnostic('runtime.input.rejected', {
1058
+ transport: 'game_ws',
1059
+ connection_id: info.connectionId,
1060
+ reason: info.reason,
1061
+ }, 'warn');
1062
+ },
1063
+ onRecoveryStarted: (info) => this.handleGameRecoveryStarted(info),
1064
+ });
1065
+ this.gameTransport = transport;
1066
+ await transport.start();
1067
+ const attachOutcome = await this.waitForGameAttach(transport);
1068
+ const outcome = attachOutcome ?? await transport.waitForOutcome();
1069
+ await transport.flush();
1070
+ if (this.gameTransport === transport) this.gameTransport = undefined;
1071
+ this.activeGameConnectionId = undefined;
1072
+
1073
+ const roomGame = isRoomMode(queueMode(queue));
1074
+ if (outcome.reason === 'game_over' || outcome.reason === 'user_left') {
1075
+ if (roomGame) return this.waitForRoomReturn(outcome.reason, queue);
1076
+ return {
1077
+ kind: 'complete',
1078
+ completion: { reason: outcome.reason === 'game_over' ? 'game_over' : 'left' },
1079
+ };
1080
+ }
1081
+ if (outcome.reason === 'replaced') {
1082
+ this.activeGameConnectionId = undefined;
1083
+ return { kind: 'complete', completion: { reason: 'replaced' } };
1084
+ }
1085
+ if (outcome.reason === 'shutdown' || outcome.reason === 'manual') {
1086
+ this.activeGameConnectionId = undefined;
1087
+ return { kind: 'complete', completion: { reason: 'stopped' } };
1088
+ }
1089
+ if (outcome.reason === 'error') {
1090
+ this.diagnostic('runtime.source.game_transport_failed', {
1091
+ error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
1092
+ }, 'warn');
1093
+ return {
1094
+ kind: 'complete',
1095
+ completion: {
1096
+ reason: 'error',
1097
+ error: outcome.error ?? new Error('GameSync transport failed.'),
1098
+ },
1099
+ };
1100
+ }
1101
+ await this.reconcileBackoff('game_ws', outcome.reason);
1102
+ return { kind: 'continue' };
1103
+ }
1104
+
1105
+ private async waitForGameAttach(
1106
+ transport: ClawclawGameTransportPort,
1107
+ ): Promise<ClawclawGameTransportOutcome | undefined> {
1108
+ const outcomePromise = transport.waitForOutcome();
1109
+ let timeout: ReturnType<typeof setTimeout> | undefined;
1110
+ const timeoutPromise = new Promise<GameAttachGate>((resolve) => {
1111
+ timeout = setTimeout(() => resolve({ kind: 'timeout' }), this.gameFirstStateTimeoutMs);
1112
+ timeout.unref?.();
1113
+ });
1114
+ const outcomeGate = outcomePromise.then<GameAttachGate>((outcome) => ({ kind: 'outcome', outcome }));
1115
+ const stateGate: Promise<GameAttachGate> = transport
1116
+ .waitForFirstState({ signal: this.abortController.signal })
1117
+ .then(
1118
+ () => ({ kind: 'attached' as const }),
1119
+ () => outcomeGate,
1120
+ );
1121
+ const gate = await Promise.race([stateGate, outcomeGate, timeoutPromise]);
1122
+ if (timeout) clearTimeout(timeout);
1123
+ if (gate.kind === 'attached') return undefined;
1124
+ if (gate.kind === 'outcome') return gate.outcome;
1125
+
1126
+ this.diagnostic('runtime.source.attach_timeout', {
1127
+ transport: 'game_ws',
1128
+ timeout_ms: this.gameFirstStateTimeoutMs,
1129
+ game_id: clawclawQueueGameId(this.currentQueue),
1130
+ }, 'warn');
1131
+ await this.submitCurrentState(
1132
+ 'transport_error',
1133
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1134
+ this.activeGameConnectionId ?? 'game-pending',
1135
+ [{
1136
+ type: 'game_start_failed',
1137
+ code: 'GAME_STATE_TIMEOUT',
1138
+ message: `Game stream did not provide its first State within ${this.gameFirstStateTimeoutMs}ms.`,
1139
+ timeout_ms: this.gameFirstStateTimeoutMs,
1140
+ ...(clawclawQueueGameId(this.currentQueue)
1141
+ ? { game_id: clawclawQueueGameId(this.currentQueue) }
1142
+ : {}),
1143
+ }],
1144
+ );
1145
+ await transport.stop('reconcile');
1146
+ return outcomePromise;
1147
+ }
1148
+
1149
+ private async waitForRoomReturn(
1150
+ endedReason: 'game_over' | 'user_left',
1151
+ previousQueue: Record<string, any>,
1152
+ ): Promise<LifecycleStep> {
1153
+ this.currentStage = 'settlement';
1154
+ this.currentTransport = 'lobby_http';
1155
+ this.currentConnection = 'connected';
1156
+ this.currentQueue = structuredClone(previousQueue);
1157
+ this.currentRoom = undefined;
1158
+ this.hasFreshGameSnapshot = false;
1159
+ await this.submitCurrentState(
1160
+ 'reconcile',
1161
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
1162
+ 'lobby-http',
1163
+ [{
1164
+ type: 'room_returning_to_lobby',
1165
+ reason: endedReason,
1166
+ ...(clawclawQueueGameId(previousQueue)
1167
+ ? { game_id: clawclawQueueGameId(previousQueue) }
1168
+ : {}),
1169
+ ...(queueRoomCode(previousQueue) ? { room_code: queueRoomCode(previousQueue) } : {}),
1170
+ }],
1171
+ );
1172
+
1173
+ while (!this.abortController.signal.aborted) {
1174
+ await this.sleep(this.roomReturnPollMs, this.abortController.signal);
1175
+ let queue: Record<string, any>;
1176
+ try {
1177
+ queue = await this.readQueueRawWithRetry();
1178
+ } catch (error) {
1179
+ const message = error instanceof Error ? error.message : String(error);
1180
+ await this.submitCurrentState(
1181
+ 'transport_error',
1182
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
1183
+ 'lobby-http',
1184
+ [{
1185
+ type: 'room_lobby_reconnect_failed',
1186
+ message,
1187
+ error: { message },
1188
+ }],
1189
+ );
1190
+ throw error;
1191
+ }
1192
+ if (queueStatus(queue) === 'in_room') {
1193
+ await this.acceptQueueState(queue);
1194
+ return { kind: 'continue', queue };
1195
+ }
1196
+ if (queueStatus(queue) !== 'allocated') {
1197
+ await this.acceptQueueState(queue, [{
1198
+ type: 'room_lobby_missing',
1199
+ queue: structuredClone(queue),
1200
+ }]);
1201
+ return { kind: 'complete', completion: { reason: 'not_participating' } };
1202
+ }
1203
+ this.currentStage = 'settlement';
1204
+ this.currentTransport = 'lobby_http';
1205
+ this.currentConnection = 'connected';
1206
+ this.currentQueue = structuredClone(queue);
1207
+ this.hasFreshGameSnapshot = false;
1208
+ await this.submitCurrentState(
1209
+ 'reconcile',
1210
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
1211
+ 'lobby-http',
1212
+ );
1213
+ this.diagnostic('runtime.source.room_return_pending', {
1214
+ game_id: clawclawQueueGameId(queue),
1215
+ });
1216
+ }
1217
+ throw this.abortController.signal.reason ?? new Error('ClawClaw Source stopped.');
1218
+ }
1219
+
1220
+ private async acceptGameFrame(frame: WsInputFrame): Promise<ClawclawGameTransportStopReason | void> {
1221
+ const segment = this.requireRuntime().currentSegment();
1222
+ if (
1223
+ frame.meta.origin === 'snapshot'
1224
+ && segment.kind === 'game'
1225
+ && segment.identity
1226
+ && segment.identity !== frame.meta.gameId
1227
+ ) {
1228
+ this.diagnostic('runtime.input.rejected', {
1229
+ transport: 'game_ws',
1230
+ reason: 'game_id_mismatch',
1231
+ expected_game_id: segment.identity,
1232
+ received_game_id: frame.meta.gameId,
1233
+ }, 'error');
1234
+ return 'error';
1235
+ }
1236
+ const gameState = frame.state;
1237
+ const tick = frame.meta.domainTick;
1238
+ let acceptedStage: ClawclawRuntimeStage | undefined;
1239
+ let acceptedPlayerProjection: PlayerProjection[] | undefined;
1240
+ const acceptance = await this.enqueueInputIf(() => {
1241
+ if (this.currentStage === 'ended') return null;
1242
+ const scope = this.requireConnectionScope(
1243
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1244
+ frame.meta.connectionId,
1245
+ );
1246
+ const backendEvents = this.sourceEvents(frame.events, frame.meta);
1247
+ const recoveryIdentity = `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:${frame.meta.connectionId}`;
1248
+ const recoveryEvents = frame.meta.origin === 'resume' || frame.meta.snapshotFallback
1249
+ ? this.localEvents([{
1250
+ type: 'game_stream_reconnected',
1251
+ recovery: frame.meta.origin,
1252
+ replayed_event_count: frame.events.length,
1253
+ }], `${recoveryIdentity}:recovered`, frame.meta.receivedAt)
1254
+ : [];
1255
+ const playerUpdate = nextPlayerProjection({
1256
+ previous: this.playerProjection,
1257
+ initialized: this.playerProjectionInitialized,
1258
+ summary: gameState,
1259
+ events: frame.events,
1260
+ selfName: this.profile.agentName,
1261
+ });
1262
+ const events = [
1263
+ ...backendEvents,
1264
+ ...recoveryEvents,
1265
+ ...(playerUpdate.payload
1266
+ ? [this.playersChangedEvent(
1267
+ playerUpdate.payload,
1268
+ frame.meta.receivedAt,
1269
+ `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1270
+ )]
1271
+ : []),
1272
+ ];
1273
+ acceptedPlayerProjection = playerUpdate.projection;
1274
+ this.currentTransport = 'game_ws';
1275
+ this.currentConnection = 'connected';
1276
+ acceptedStage = clawclawStageFromGameEvents(
1277
+ frame.events,
1278
+ clawclawStageFromGameState(gameState),
1279
+ );
1280
+ return {
1281
+ scope,
1282
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1283
+ connectionId: frame.meta.connectionId,
1284
+ // A resume barrier has no sequence of its own. In the valid zero-replay
1285
+ // case its to_seq equals the last update accepted before disconnect, so
1286
+ // include the new connection identity to avoid retry-conflicting with
1287
+ // that earlier runtime input while preserving the backend sequence.
1288
+ sourceKey: frame.meta.origin === 'resume'
1289
+ ? `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:resume:${frame.meta.connectionId}`
1290
+ : `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1291
+ sourceSeq: `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1292
+ domainTick: tick,
1293
+ state: this.gameRuntimeState(
1294
+ acceptedStage,
1295
+ acceptedStage === 'ended' ? 'ending' : 'game_snapshot',
1296
+ { status: 'fresh', state: structuredClone(gameState) },
1297
+ ),
1298
+ events,
1299
+ completeness: frame.meta.snapshotFallback ? 'best_effort' : 'complete',
1300
+ receivedAt: frame.meta.receivedAt,
1301
+ };
1302
+ }, () => {
1303
+ this.currentStage = acceptedStage!;
1304
+ this.currentQueue = undefined;
1305
+ this.currentRoom = undefined;
1306
+ this.resetReconcileBackoff('game_ws');
1307
+ this.hasFreshGameSnapshot = true;
1308
+ this.latestFreshGameState = structuredClone(gameState);
1309
+ this.latestFreshGameTick = tick;
1310
+ this.gameConnectionsWithState.add(frame.meta.connectionId);
1311
+ if (acceptedPlayerProjection) {
1312
+ this.playerProjection = acceptedPlayerProjection;
1313
+ this.playerProjectionInitialized = true;
1314
+ }
1315
+ });
1316
+ if (!acceptance) return;
1317
+ if (typeof frame.meta.sourceSeq !== 'number') {
1318
+ throw new TypeError('GameSync frame sourceSeq must be numeric.');
1319
+ }
1320
+ this.client.acknowledgeGameSync(
1321
+ frame.meta.ackToken,
1322
+ frame.meta.origin === 'snapshot' || frame.meta.origin === 'resume',
1323
+ );
1324
+ if (acceptedStage === 'ended') return 'game_over';
1325
+ }
1326
+
1327
+ private async handleGameRecoveryStarted(info: WsRecoveryStartedInfo): Promise<void> {
1328
+ if (this.activeGameConnectionId !== info.connectionId) return;
1329
+ this.requireRuntime().connectionChanged(
1330
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1331
+ info.connectionId,
1332
+ 'reconnecting',
1333
+ );
1334
+ this.currentTransport = 'game_ws';
1335
+ this.currentConnection = 'reconnecting';
1336
+ this.diagnostic('runtime.source.game_stream_recovery_started', {
1337
+ connection_id: info.connectionId,
1338
+ reason: info.reason,
1339
+ expected_seq: info.expectedSeq,
1340
+ received_seq: info.receivedSeq,
1341
+ }, 'warn');
1342
+ await this.submitCurrentState(
1343
+ 'transport_error',
1344
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1345
+ info.connectionId,
1346
+ );
1347
+ }
1348
+
1349
+ private async acceptRoomFrame(
1350
+ snapshot: RoomSnapshot | null,
1351
+ type: string,
1352
+ data: Record<string, any>,
1353
+ meta: RoomFrameMeta,
1354
+ terminalPhase?: 'room_left',
1355
+ ): Promise<void> {
1356
+ if (snapshot) {
1357
+ const roleConfig = Object.prototype.hasOwnProperty.call(snapshot, 'role_config')
1358
+ ? snapshot.role_config
1359
+ : this.trainingRoomControlOverlay.role_config;
1360
+ snapshot = type === 'room.snapshot'
1361
+ ? {
1362
+ ...this.trainingRoomControlOverlay,
1363
+ ...snapshot,
1364
+ ...(roleConfig !== undefined ? { role_config: roleConfig } : {}),
1365
+ }
1366
+ : { ...snapshot, ...this.trainingRoomControlOverlay };
1367
+ }
1368
+ const roomCode = snapshot?.room_code;
1369
+ if (roomCode) {
1370
+ this.requireRuntime().adoptResumeKey(roomCode);
1371
+ const current = this.requireRuntime().currentSegment();
1372
+ if (current.kind !== 'room' || current.identity !== roomCode) {
1373
+ await this.ensureSegment('room', roomCode);
1374
+ this.requireRuntime().rebindConnectionScope(
1375
+ CLAWCLAW_ROOM_WS_SOURCE.sourceId,
1376
+ meta.connectionId,
1377
+ );
1378
+ this.activeRoomConnectionId = meta.connectionId;
1379
+ }
1380
+ }
1381
+ const scope = this.requireConnectionScope(CLAWCLAW_ROOM_WS_SOURCE.sourceId, meta.connectionId);
1382
+ const hadSnapshot = this.roomConnectionsWithSnapshot.has(meta.connectionId);
1383
+ this.currentTransport = 'room_ws';
1384
+ this.currentConnection = 'connected';
1385
+ this.currentQueue = undefined;
1386
+ if (snapshot) {
1387
+ if (type === 'room.snapshot') this.resetReconcileBackoff('room_ws');
1388
+ const roomMode = isTrainingRoomMode(snapshot.room_type) ? snapshot.room_type : 'room';
1389
+ this.participationMode = roomMode;
1390
+ this.requireRuntime().updateMode(roomMode);
1391
+ this.currentRoom = projectClawclawRoomState(snapshot, {
1392
+ profileName: this.profile.agentName,
1393
+ receivedAt: meta.receivedAt,
1394
+ });
1395
+ } else if (terminalPhase === 'room_left') {
1396
+ this.currentRoom = undefined;
1397
+ this.trainingRoomControlOverlay = {};
1398
+ }
1399
+ if (terminalPhase === 'room_left') this.currentStage = 'ended';
1400
+ else if (type === 'room.game_started' || snapshot?.status === 'playing') this.currentStage = 'loading';
1401
+ else this.currentStage = 'room';
1402
+
1403
+ const rawEvents = type === 'room.snapshot' ? [] : [{ type, ...data }];
1404
+ await this.submit({
1405
+ scope,
1406
+ sourceId: CLAWCLAW_ROOM_WS_SOURCE.sourceId,
1407
+ connectionId: meta.connectionId,
1408
+ sourceKey: this.physicalSourceKey('room', meta),
1409
+ sourceSeq: `${meta.connectionId}:${String(meta.sourceSeq)}`,
1410
+ state: this.runtimeState(this.currentStage === 'ended' ? 'ending' : 'room_update'),
1411
+ events: this.sourceEvents(rawEvents, meta),
1412
+ completeness: meta.replay || !hadSnapshot ? 'best_effort' : 'complete',
1413
+ receivedAt: meta.receivedAt,
1414
+ });
1415
+ if (snapshot) this.roomConnectionsWithSnapshot.add(meta.connectionId);
1416
+ }
1417
+
1418
+ private async handleGameClose(
1419
+ connectionId: string,
1420
+ info: WsCloseInfo,
1421
+ ): Promise<ClawclawGameTransportStopReason | void> {
1422
+ const reason = (info.reason ?? '').trim().toLowerCase();
1423
+ const userLeft = (info.code === 1000 && reason === 'left game')
1424
+ || info.code === 4001;
1425
+ const connectionReplaced = info.code === 4002 && reason === 'game_sync_replaced';
1426
+ const fatalProtocolClose = info.code === 1002
1427
+ || info.code === 4003
1428
+ || (info.code === 4002 && !connectionReplaced);
1429
+ const nextConnection: ClawclawRuntimeConnection = (
1430
+ userLeft || connectionReplaced || fatalProtocolClose
1431
+ ) ? 'disconnected' : 'reconnecting';
1432
+ this.requireRuntime().connectionChanged(
1433
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1434
+ connectionId,
1435
+ nextConnection,
1436
+ );
1437
+ this.currentTransport = 'game_ws';
1438
+ this.currentConnection = nextConnection;
1439
+ if (userLeft) this.currentStage = 'ended';
1440
+ const connectionEvents = userLeft
1441
+ ? [{
1442
+ type: 'user_left_game',
1443
+ ...(this.participationMode ? { game_mode: this.participationMode } : {}),
1444
+ }]
1445
+ : connectionReplaced
1446
+ ? []
1447
+ : [{
1448
+ type: 'game_stream_disconnected',
1449
+ close_code: info.code,
1450
+ close_reason: info.reason,
1451
+ recoverable: !fatalProtocolClose,
1452
+ }];
1453
+ await this.submitCurrentState(
1454
+ userLeft ? 'ending' : 'transport_error',
1455
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1456
+ connectionId,
1457
+ connectionEvents,
1458
+ );
1459
+ if (userLeft) return 'user_left';
1460
+ // origin/dev uses 4000 when the routed GameServer no longer has an active
1461
+ // game for this player. Reconcile lobby participation instead of opening
1462
+ // the same terminal GameSync endpoint again.
1463
+ if (info.code === 4000 || info.code === 1000) return 'reconcile';
1464
+ if (connectionReplaced) return 'replaced';
1465
+ if (info.code === 4002) return 'error';
1466
+ if (info.code === 4003 || info.code === 1002) return 'error';
1467
+ this.diagnostic('runtime.source.input_gap', {
1468
+ transport: 'game_ws',
1469
+ connection_id: connectionId,
1470
+ close_code: info.code,
1471
+ close_reason: info.reason,
1472
+ recoverable: true,
1473
+ }, 'warn');
1474
+ }
1475
+
1476
+ private classifyRoomClose(code: number | undefined, reason: string): ClawclawRoomCloseDecision {
1477
+ if (code === 4005) return 'room_destroyed';
1478
+ if (code === 4002) return 'replaced';
1479
+ if (code === 4001) return 'fatal';
1480
+ if (code === 4003) return 'reconcile';
1481
+ if (/not in room|already left/i.test(reason)) return 'reconcile';
1482
+ return 'retry';
1483
+ }
1484
+
1485
+ private async handleRoomClose(
1486
+ connectionId: string,
1487
+ info: ClawclawRoomCloseInfo,
1488
+ ): Promise<ClawclawRoomCloseDecision> {
1489
+ const decision = this.classifyRoomClose(info.code, info.reason);
1490
+ if (decision === 'room_destroyed') {
1491
+ this.requireRuntime().connectionChanged(
1492
+ CLAWCLAW_ROOM_WS_SOURCE.sourceId,
1493
+ connectionId,
1494
+ 'disconnected',
1495
+ );
1496
+ this.currentTransport = 'room_ws';
1497
+ this.currentConnection = 'disconnected';
1498
+ this.currentStage = 'ended';
1499
+ this.currentQueue = undefined;
1500
+ this.currentRoom = undefined;
1501
+ await this.submitCurrentState(
1502
+ 'ending',
1503
+ CLAWCLAW_ROOM_WS_SOURCE.sourceId,
1504
+ connectionId,
1505
+ [{
1506
+ type: 'room_destroyed',
1507
+ close_code: info.code,
1508
+ reason: info.reason || 'room_destroyed',
1509
+ }],
1510
+ );
1511
+ return decision;
1512
+ }
1513
+ if (
1514
+ info.reason === 'heartbeat_timeout'
1515
+ && this.activeRoomConnectionId === connectionId
1516
+ ) {
1517
+ this.currentTransport = 'room_ws';
1518
+ this.currentConnection = 'reconnecting';
1519
+ await this.submitCurrentState(
1520
+ 'transport_error',
1521
+ CLAWCLAW_ROOM_WS_SOURCE.sourceId,
1522
+ connectionId,
1523
+ [{ type: 'room_ping_timeout', recoverable: true }],
1524
+ );
1525
+ }
1526
+ return decision;
1527
+ }
1528
+
1529
+ private async handleControlIntent(
1530
+ intent: ClawclawSourceControlIntent,
1531
+ ): Promise<Record<string, any> | void> {
1532
+ await this.submitControlState(intent);
1533
+ if (intent.kind === 'stop') {
1534
+ if (!this.abortController.signal.aborted) {
1535
+ this.abortController.abort(new Error('source_stop_intent'));
1536
+ }
1537
+ await Promise.allSettled([
1538
+ this.gameTransport?.stop('manual'),
1539
+ this.roomTransport?.stop('manual'),
1540
+ ].filter((value): value is Promise<void> => value !== undefined));
1541
+ return;
1542
+ }
1543
+ if (intent.kind === 'start_room') {
1544
+ if (this.currentStage !== 'room') throw new Error('start_room requires the room stage.');
1545
+ await this.client.startRoom();
1546
+ return;
1547
+ }
1548
+ if (intent.kind === 'training_mode') {
1549
+ this.requireTrainingRoomStage(intent.kind);
1550
+ const result = await this.client.setTrainingRoomMode(intent.roomType);
1551
+ const failure = businessFailureFromResult(result, 'Failed to change training mode.');
1552
+ if (failure) throw leaveFailureError(failure);
1553
+ await this.acceptTrainingRoomControlResult(result);
1554
+ return result;
1555
+ }
1556
+ if (intent.kind === 'training_role_lock') {
1557
+ this.requireTrainingRoomStage(intent.kind);
1558
+ const result = await this.client.setTrainingRoleLock(intent.characterId);
1559
+ const failure = businessFailureFromResult(result, 'Failed to lock the training role.');
1560
+ if (failure) throw leaveFailureError(failure);
1561
+ await this.acceptTrainingRoomControlResult(result);
1562
+ return result;
1563
+ }
1564
+ if (intent.kind === 'training_role_clear') {
1565
+ this.requireTrainingRoomStage(intent.kind);
1566
+ const result = await this.client.clearTrainingRoleLock();
1567
+ const failure = businessFailureFromResult(result, 'Failed to clear the training role lock.');
1568
+ if (failure) throw leaveFailureError(failure);
1569
+ await this.acceptTrainingRoomControlResult(result, { roleConfigCleared: true });
1570
+ return result;
1571
+ }
1572
+
1573
+ this.leaveRequested = true;
1574
+ try {
1575
+ if (
1576
+ this.currentTransport === 'game_ws'
1577
+ || this.currentStage === 'game'
1578
+ || this.currentStage === 'meeting'
1579
+ || this.currentStage === 'settlement'
1580
+ || this.currentStage === 'loading'
1581
+ ) {
1582
+ const result = await this.client.leaveGame();
1583
+ const failure = businessFailureFromResult(result, 'Failed to leave the active game.');
1584
+ if (failure) throw leaveFailureError(failure);
1585
+ } else if (this.currentStage === 'room') {
1586
+ const result = await this.client.leaveRoom();
1587
+ const failure = businessFailureFromResult(result, 'Failed to leave the room.');
1588
+ if (failure) throw leaveFailureError(failure);
1589
+ } else {
1590
+ const result = await this.client.leaveQueue('clawclaw');
1591
+ const outcome = classifyLeaveQueueResult(result);
1592
+ if (!outcome.remoteLeft) throw leaveFailureError(outcome.failure!);
1593
+ }
1594
+ } catch (error) {
1595
+ this.leaveRequested = false;
1596
+ const message = error instanceof Error ? error.message : String(error);
1597
+ await this.submitCurrentState(
1598
+ 'control',
1599
+ CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId,
1600
+ this.activeGameConnectionId ?? this.activeRoomConnectionId ?? 'local-control',
1601
+ [{
1602
+ type: 'quit_failed',
1603
+ error: { message },
1604
+ stage: this.currentStage,
1605
+ transport: this.currentTransport,
1606
+ }],
1607
+ );
1608
+ throw error;
1609
+ }
1610
+ }
1611
+
1612
+ private requireTrainingRoomStage(operation: string): void {
1613
+ const roomType = this.currentRoom?.room?.room_type;
1614
+ if (this.currentStage !== 'room' || !isTrainingRoomMode(roomType)) {
1615
+ throw new Error(`${operation} requires an active training room.`);
1616
+ }
1617
+ }
1618
+
1619
+ private async acceptTrainingRoomControlResult(
1620
+ result: Record<string, any>,
1621
+ options: { roleConfigCleared?: boolean } = {},
1622
+ ): Promise<void> {
1623
+ const update = unwrapData(result);
1624
+ if (!update || typeof update !== 'object' || Array.isArray(update)) return;
1625
+ const current = this.currentRoom?.room;
1626
+ const base = current && typeof current === 'object' && !Array.isArray(current)
1627
+ ? current as Record<string, any>
1628
+ : {};
1629
+ const {
1630
+ member_count: _memberCount,
1631
+ is_owner: _isOwner,
1632
+ ready_to_start: _readyToStart,
1633
+ role_lock_character_id: _roleLockCharacterId,
1634
+ ...baseSnapshot
1635
+ } = base;
1636
+ const snapshot: RoomSnapshot = {
1637
+ ...baseSnapshot,
1638
+ ...update,
1639
+ ...(options.roleConfigCleared ? { role_config: null } : {}),
1640
+ ...(baseSnapshot.my_seat !== undefined && update.my_seat === undefined
1641
+ ? { my_seat: baseSnapshot.my_seat }
1642
+ : {}),
1643
+ };
1644
+ if (options.roleConfigCleared) this.trainingRoomControlOverlay.role_config = null;
1645
+ for (const key of ['room_type', 'role_config'] as const) {
1646
+ if (Object.prototype.hasOwnProperty.call(update, key)) {
1647
+ this.trainingRoomControlOverlay[key] = update[key] === undefined
1648
+ ? undefined
1649
+ : structuredClone(update[key]);
1650
+ }
1651
+ }
1652
+ const roomMode = isTrainingRoomMode(snapshot.room_type) ? snapshot.room_type : undefined;
1653
+ if (roomMode) {
1654
+ this.participationMode = roomMode;
1655
+ this.requireRuntime().updateMode(roomMode);
1656
+ }
1657
+ this.currentQueue = undefined;
1658
+ this.currentRoom = projectClawclawRoomState(snapshot, {
1659
+ profileName: this.profile.agentName,
1660
+ receivedAt: new Date().toISOString(),
1661
+ });
1662
+ await this.submitCurrentState(
1663
+ 'control',
1664
+ CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId,
1665
+ this.activeRoomConnectionId ?? 'local-control',
1666
+ );
1667
+ }
1668
+
1669
+ private async reconcileBackoff(
1670
+ transport: ReconciledTransport,
1671
+ reason: string,
1672
+ ): Promise<void> {
1673
+ const attempt = this.reconcileAttempts[transport] + 1;
1674
+ this.reconcileAttempts[transport] = attempt;
1675
+ const exponent = Math.min(20, attempt - 1);
1676
+ const delayMs = Math.min(
1677
+ this.reconcileMaxDelayMs,
1678
+ this.reconcileBaseDelayMs * (2 ** exponent),
1679
+ );
1680
+ this.diagnostic('runtime.source.reconcile_backoff', {
1681
+ transport,
1682
+ reason,
1683
+ attempt,
1684
+ delay_ms: delayMs,
1685
+ queue_status: queueStatus(this.currentQueue),
1686
+ }, 'warn');
1687
+ if (delayMs > 0) await this.sleep(delayMs, this.abortController.signal);
1688
+ }
1689
+
1690
+ private resetReconcileBackoff(transport: ReconciledTransport): void {
1691
+ const attempts = this.reconcileAttempts[transport];
1692
+ if (attempts > 0) {
1693
+ this.diagnostic('runtime.source.reconcile_recovered', {
1694
+ transport,
1695
+ attempts,
1696
+ }, 'info');
1697
+ }
1698
+ this.reconcileAttempts[transport] = 0;
1699
+ }
1700
+
1701
+ private async submitControlState(intent: ClawclawSourceControlIntent): Promise<void> {
1702
+ if (!this.runtime || this.finished) return;
1703
+ if (intent.kind === 'stop') {
1704
+ this.currentStage = 'ended';
1705
+ this.currentConnection = 'disconnected';
1706
+ }
1707
+ const sourceSeq = ++this.localSourceSeq;
1708
+ const connectionId = this.activeGameConnectionId ?? this.activeRoomConnectionId ?? 'local-control';
1709
+ const eventValues = intent.kind === 'stop'
1710
+ ? [{ type: 'stop_requested' }]
1711
+ : intent.kind === 'leave'
1712
+ ? [{ type: 'quit_requested' }]
1713
+ : [];
1714
+ const receivedAt = new Date().toISOString();
1715
+ await this.submit({
1716
+ scope: this.runtime.currentSegment().scope,
1717
+ sourceId: CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId,
1718
+ connectionId,
1719
+ sourceKey: `control:${this.sourceInstanceId}:${sourceSeq}`,
1720
+ sourceSeq,
1721
+ state: {
1722
+ ...this.runtimeState(intent.kind === 'stop' ? 'ending' : 'control'),
1723
+ control: { type: intent.kind },
1724
+ },
1725
+ events: this.localEvents(eventValues, sourceSeq, receivedAt),
1726
+ completeness: 'complete',
1727
+ receivedAt,
1728
+ });
1729
+ }
1730
+
1731
+ private sourceEvents(
1732
+ values: readonly unknown[],
1733
+ meta: Pick<WsFrameMeta, 'receivedAt' | 'sourceEventId' | 'sourceSeq'> & { replayed?: boolean },
1734
+ ): RuntimeSourceEvent<Record<string, unknown>>[] {
1735
+ const events: RuntimeSourceEvent<Record<string, unknown>>[] = [];
1736
+ values.forEach((value, index) => {
1737
+ const normalized = normalizeGameSyncEvent(value);
1738
+ const sourceEventId = eventSourceId(value as Record<string, any>);
1739
+ const event = (
1740
+ (
1741
+ normalized.type === 'game_started'
1742
+ || normalized.type === 'game_over'
1743
+ || normalized.type === 'exile_game_over'
1744
+ )
1745
+ && normalized.game_mode == null
1746
+ && this.participationMode
1747
+ )
1748
+ ? { ...normalized, game_mode: this.participationMode }
1749
+ : normalized;
1750
+ const { type, ...payload } = event;
1751
+ const sequence = eventSourceSequence(event) ?? meta.sourceSeq;
1752
+ events.push({
1753
+ type,
1754
+ producer: 'backend_push',
1755
+ payload,
1756
+ sourceEventId: sourceEventId
1757
+ ?? (values.length === 1 ? meta.sourceEventId : undefined),
1758
+ sourceSeq: sequence === undefined
1759
+ ? undefined
1760
+ : values.length === 1 ? sequence : `${String(sequence)}:${index}`,
1761
+ receivedAt: meta.receivedAt,
1762
+ replayed: meta.replayed === true,
1763
+ });
1764
+ });
1765
+ return events;
1766
+ }
1767
+
1768
+ private applyGameRoute(value: Record<string, any> | ClawclawRoomGameStarted): void {
1769
+ const data = normalizeClawclawQueueState(value);
1770
+ if (typeof data.ws_url === 'string' && data.ws_url.length > 0) {
1771
+ this.client.setGameServerUrl(data.ws_url);
1772
+ }
1773
+ if (typeof data.game_server_name === 'string' && data.game_server_name.length > 0) {
1774
+ this.client.setRoomGameServer(data.game_server_name);
1775
+ }
1776
+ }
1777
+
1778
+ private async ensureSegment(kind: string, identity?: string): Promise<RuntimeScope> {
1779
+ const runtime = this.requireRuntime();
1780
+ const current = runtime.currentSegment();
1781
+ if (current.kind === kind && current.identity === identity) return current.scope;
1782
+ const next = await runtime.activateSegment(kind, identity);
1783
+ this.activeGameConnectionId = undefined;
1784
+ this.activeRoomConnectionId = undefined;
1785
+ this.gameConnectionsWithState.clear();
1786
+ this.roomConnectionsWithSnapshot.clear();
1787
+ this.hasFreshGameSnapshot = false;
1788
+ this.latestFreshGameState = undefined;
1789
+ this.latestFreshGameTick = undefined;
1790
+ this.playerProjection = [];
1791
+ this.playerProjectionInitialized = false;
1792
+ this.sourceCoalescingBoundaryState = undefined;
1793
+ this.actionSafetyGeneration = 0;
1794
+ return next;
1795
+ }
1796
+
1797
+ private requireConnectionScope(sourceId: string, connectionId: string): RuntimeScope {
1798
+ const runtime = this.requireRuntime();
1799
+ const scope = runtime.connectionScope(sourceId, connectionId);
1800
+ if (!scope || !runtime.isActiveConnection(sourceId, connectionId)) {
1801
+ throw new Error('stale_connection');
1802
+ }
1803
+ if (!sameScope(scope, runtime.currentSegment().scope)) throw new Error('stale_connection');
1804
+ return scope;
1805
+ }
1806
+
1807
+ private async submitCurrentState(
1808
+ cause: ClawclawRuntimeCause,
1809
+ sourceId: string,
1810
+ connectionId: string,
1811
+ eventValues: readonly Record<string, unknown>[] = [],
1812
+ ): Promise<void> {
1813
+ const sourceSeq = ++this.localSourceSeq;
1814
+ const receivedAt = new Date().toISOString();
1815
+ await this.submit({
1816
+ scope: this.requireRuntime().currentSegment().scope,
1817
+ sourceId,
1818
+ connectionId,
1819
+ sourceKey: `source-state:${this.sourceInstanceId}:${sourceSeq}`,
1820
+ sourceSeq,
1821
+ state: this.runtimeState(cause),
1822
+ events: this.localEvents(eventValues, sourceSeq, receivedAt),
1823
+ completeness: 'complete',
1824
+ receivedAt,
1825
+ });
1826
+ }
1827
+
1828
+ private localEvents(
1829
+ values: readonly Record<string, unknown>[],
1830
+ sourceSeq: number | string,
1831
+ receivedAt: string,
1832
+ ): RuntimeSourceEvent<Record<string, unknown>>[] {
1833
+ return values.map((value, index) => {
1834
+ const normalized = normalizeBackendEvent(value);
1835
+ const { type, ...payload } = normalized;
1836
+ const localSequence = `local:${this.sourceInstanceId}:${String(sourceSeq)}`;
1837
+ return {
1838
+ type,
1839
+ producer: 'local_synth',
1840
+ payload,
1841
+ sourceEventId: `${localSequence}:${index}`,
1842
+ sourceSeq: values.length === 1 ? localSequence : `${localSequence}:${index}`,
1843
+ receivedAt,
1844
+ };
1845
+ });
1846
+ }
1847
+
1848
+ private playersChangedEvent(
1849
+ payload: PlayersChangedPayload,
1850
+ receivedAt: string,
1851
+ sourceSeq: number | string,
1852
+ ): RuntimeSourceEvent<Record<string, unknown>> {
1853
+ return {
1854
+ type: 'players_changed',
1855
+ producer: 'local_synth',
1856
+ payload,
1857
+ sourceEventId: `local:${this.sourceInstanceId}:players-changed:${String(sourceSeq)}`,
1858
+ sourceSeq: `${String(sourceSeq)}:players-changed`,
1859
+ receivedAt,
1860
+ };
1861
+ }
1862
+
1863
+ private runtimeState(
1864
+ cause: ClawclawRuntimeCause,
1865
+ gameSnapshot?: ClawclawRuntimeState['game_snapshot'],
1866
+ ): ClawclawRuntimeState {
1867
+ return {
1868
+ schema: 'clawclaw.runtime-state.v1',
1869
+ stage: this.currentStage,
1870
+ transport: this.currentTransport,
1871
+ connection: this.currentConnection,
1872
+ cause,
1873
+ ...(this.currentQueue ? { queue: structuredClone(this.currentQueue) } : {}),
1874
+ ...(this.currentRoom ? { room: structuredClone(this.currentRoom) } : {}),
1875
+ game_snapshot: gameSnapshot
1876
+ ?? (this.hasFreshGameSnapshot ? { status: 'not_updated' } : { status: 'unavailable' }),
1877
+ };
1878
+ }
1879
+
1880
+ private gameRuntimeState(
1881
+ stage: ClawclawRuntimeStage,
1882
+ cause: ClawclawRuntimeCause,
1883
+ gameSnapshot: ClawclawRuntimeState['game_snapshot'],
1884
+ ): ClawclawRuntimeState {
1885
+ return {
1886
+ schema: 'clawclaw.runtime-state.v1',
1887
+ stage,
1888
+ transport: this.currentTransport,
1889
+ connection: this.currentConnection,
1890
+ cause,
1891
+ game_snapshot: gameSnapshot,
1892
+ };
1893
+ }
1894
+
1895
+ private physicalSourceKey(
1896
+ transport: 'game' | 'room',
1897
+ meta: Pick<WsFrameMeta, 'connectionId' | 'sourceEventId' | 'sourceSeq' | 'receivedAt'>,
1898
+ ): string {
1899
+ // A message sequence identifies the physical frame. Envelope Event IDs
1900
+ // are only a fallback because one backend Event can accompany multiple
1901
+ // distinct State frames on the same connection.
1902
+ const identity = meta.sourceSeq ?? meta.sourceEventId ?? `${meta.receivedAt}:${++this.localSourceSeq}`;
1903
+ return `${transport}:${meta.connectionId}:${String(identity)}`;
1904
+ }
1905
+
1906
+ private async submit(
1907
+ batch: RuntimeInputBatch<Record<string, any>, Record<string, unknown>>,
1908
+ afterAccepted?: (
1909
+ acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>,
1910
+ ) => void,
1911
+ ): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
1912
+ return this.enqueueInput(() => batch, afterAccepted);
1913
+ }
1914
+
1915
+ private async enqueueInput(
1916
+ createBatch: () => (
1917
+ RuntimeInputBatch<Record<string, any>, Record<string, unknown>>
1918
+ | Promise<RuntimeInputBatch<Record<string, any>, Record<string, unknown>>>
1919
+ ),
1920
+ afterAccepted?: (
1921
+ acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>,
1922
+ ) => void,
1923
+ ): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>> {
1924
+ const acceptance = await this.enqueueInputIf(createBatch, afterAccepted);
1925
+ if (!acceptance) throw new Error('Runtime Source input was unexpectedly skipped.');
1926
+ return acceptance;
1927
+ }
1928
+
1929
+ private async enqueueInputIf(
1930
+ createBatch: () => (
1931
+ RuntimeInputBatch<Record<string, any>, Record<string, unknown>>
1932
+ | null
1933
+ | Promise<RuntimeInputBatch<Record<string, any>, Record<string, unknown>> | null>
1934
+ ),
1935
+ afterAccepted?: (
1936
+ acceptance: RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>>,
1937
+ ) => void,
1938
+ ): Promise<RuntimeInputAcceptance<Record<string, any>, Record<string, unknown>> | null> {
1939
+ const operation = this.inputTail.then(async () => {
1940
+ const batch = await createBatch();
1941
+ if (!batch) return null;
1942
+ const nextBoundaryState = nextSourceCoalescingBoundaryState(
1943
+ batch.state,
1944
+ this.sourceCoalescingBoundaryState,
1945
+ );
1946
+ const crossedActionSafetyBoundary = crossesSourceCoalescingBoundary(
1947
+ this.sourceCoalescingBoundaryState,
1948
+ nextBoundaryState,
1949
+ );
1950
+ const actionSafetyGeneration = this.actionSafetyGeneration
1951
+ + (crossedActionSafetyBoundary ? 1 : 0);
1952
+ const acceptedBatch = {
1953
+ ...batch,
1954
+ state: isClawclawRuntimeState(batch.state)
1955
+ ? { ...batch.state, action_safety_generation: actionSafetyGeneration }
1956
+ : batch.state,
1957
+ ...(crossedActionSafetyBoundary ? { coalescing: 'forbidden' as const } : {}),
1958
+ };
1959
+ const acceptance = await this.requireRuntime().acceptInputBatch(acceptedBatch);
1960
+ this.sourceCoalescingBoundaryState = nextBoundaryState;
1961
+ this.actionSafetyGeneration = actionSafetyGeneration;
1962
+ if (acceptedBatch.state.stage === 'ended') {
1963
+ this.terminalStateSubmitted = true;
1964
+ }
1965
+ afterAccepted?.(acceptance);
1966
+ return acceptance;
1967
+ });
1968
+ this.inputTail = operation.then(() => undefined, () => undefined);
1969
+ return operation;
1970
+ }
1971
+
1972
+ private async stopGameTransport(reason: ClawclawGameTransportStopReason): Promise<void> {
1973
+ const transport = this.gameTransport;
1974
+ if (!transport) return;
1975
+ this.gameTransport = undefined;
1976
+ await transport.stop(reason);
1977
+ }
1978
+
1979
+ private async stopRoomTransport(reason: 'manual' | 'shutdown'): Promise<void> {
1980
+ const transport = this.roomTransport;
1981
+ if (!transport) return;
1982
+ this.roomTransport = undefined;
1983
+ await transport.stop(reason);
1984
+ }
1985
+
1986
+ private diagnostic(
1987
+ name: string,
1988
+ attributes: Readonly<Record<string, unknown>> = {},
1989
+ severity: 'debug' | 'info' | 'warn' | 'error' = 'debug',
1990
+ ): void {
1991
+ this.runtime?.diagnostic(name, attributes, severity);
1992
+ }
1993
+
1994
+ private requireRuntime(): RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1995
+ if (!this.runtime) throw new Error('ClawClaw Source is not started.');
1996
+ return this.runtime;
1997
+ }
1998
+
1999
+ private finish(completion: ClawclawSourceCompletion): void {
2000
+ if (this.finished) return;
2001
+ this.finished = true;
2002
+ this.resolveCompletion(completion);
2003
+ }
2004
+
2005
+ private async completeLifecycle(completion: ClawclawSourceCompletion): Promise<void> {
2006
+ if (completion.reason === 'error') {
2007
+ this.diagnostic('runtime.source.failed', {
2008
+ error: completion.error instanceof Error
2009
+ ? completion.error.message
2010
+ : String(completion.error ?? 'unknown source error'),
2011
+ }, 'error');
2012
+ }
2013
+ let finalCompletion = completion;
2014
+ if (!this.terminalStateSubmitted && this.runtime && !this.finished) {
2015
+ this.currentStage = 'ended';
2016
+ this.currentConnection = 'disconnected';
2017
+ const sourceSeq = ++this.localSourceSeq;
2018
+ const receivedAt = new Date().toISOString();
2019
+ const errorMessage = completion.error instanceof Error
2020
+ ? completion.error.message
2021
+ : String(completion.error ?? 'Unknown Source error.');
2022
+ try {
2023
+ await this.submit({
2024
+ scope: this.runtime.currentSegment().scope,
2025
+ sourceId: CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId,
2026
+ connectionId: 'source-lifecycle',
2027
+ sourceKey: `source-terminal:${this.sourceInstanceId}:${sourceSeq}`,
2028
+ sourceSeq,
2029
+ state: {
2030
+ ...this.runtimeState('ending'),
2031
+ control: { type: 'source_completed', reason: completion.reason },
2032
+ },
2033
+ events: completion.reason === 'error'
2034
+ ? this.localEvents([{
2035
+ type: 'error',
2036
+ code: 'SOURCE_FAILED',
2037
+ phase: 'runtime',
2038
+ message: errorMessage,
2039
+ ...(this.participationMode ? { game_mode: this.participationMode } : {}),
2040
+ }], sourceSeq, receivedAt)
2041
+ : [],
2042
+ completeness: 'complete',
2043
+ receivedAt,
2044
+ });
2045
+ } catch (error) {
2046
+ this.diagnostic('runtime.source.terminal_state_failed', {
2047
+ completion_reason: completion.reason,
2048
+ error: error instanceof Error ? error.message : String(error),
2049
+ }, 'error');
2050
+ finalCompletion = { reason: 'error', error };
2051
+ }
2052
+ }
2053
+ this.finish(finalCompletion);
2054
+ }
2055
+ }