@myclaw163/clawclaw-cli 0.10.11 → 0.10.13

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