@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,1257 @@
1
+ import { startupMark, startupSpan, startupTraceEnabled, timeStartup } from "../../../bin/startup-trace.mjs";
2
+ import { BUILTIN_PERCEPTION_NAMES } from "./plugins/system-perception/system-perceptions.js";
3
+ import { BUILTIN_PERCEPTION_PREFIX } from "./notification-policy.js";
4
+ import { isClawclawAgentNotification } from "./notification-policy.js";
5
+ import { createClawclawProcessingCadence } from "./runtime-cadence.js";
6
+ import { readRuntimeCycleIntervalMs } from "../../lib/runtime-cadence-config.js";
7
+ import { randomUUID } from "node:crypto";
8
+ import { BehaviorReflexControl } from "./behavior-reflex-control.js";
9
+ import { DeferredMeetingShortStrategy } from "./behavior-start-control.js";
10
+ import { normalizeBehaviorInput } from "./behavior-input-fields.js";
11
+ import { acquireOwnerLock } from "./owner-lock.js";
12
+ import { createStartingOwnerControl } from "./starting-owner-control.js";
13
+ import { acquireOwnerLock as acquireOwnerLock2 } from "./owner-lock.js";
14
+ import {
15
+ chmodSync,
16
+ readFileSync,
17
+ renameSync,
18
+ unlinkSync,
19
+ writeFileSync
20
+ } from "node:fs";
21
+ import { getHeapStatistics } from "node:v8";
22
+ import { RuntimeProcessTimingSampler } from "../observability/process-timing.js";
23
+ import { GameClient } from "../../lib/game-client.js";
24
+ import { isTrainingRole } from "../../lib/training-role.js";
25
+ import { getProfileRuntimeStateDir, getWorkspaceDir } from "../../lib/init-command.js";
26
+ import { readWorkspacePerceptionConfig } from "../../lib/perception-config.js";
27
+ import {
28
+ CLAWCLAW_ROLE_IDS,
29
+ readGameplayConfig
30
+ } from "../../lib/gameplay-config.js";
31
+ import { toTriggerRegistrationOverrides } from "../../lib/trigger-config.js";
32
+ import {
33
+ isRoomMode,
34
+ isTrainingRoomMode,
35
+ queueMode,
36
+ queueRoomCode,
37
+ queueStatus
38
+ } from "../../lib/room.js";
39
+ import { isMailboxRepository } from "../framework/mailbox/index.js";
40
+ import {
41
+ MailboxRelayBroker,
42
+ runStdoutMailboxRelay
43
+ } from "../mailbox-host-relay.js";
44
+ import {
45
+ HostMonitorWriteGate
46
+ } from "../host-monitor-rate-gate.js";
47
+ import {
48
+ gameStartRuntimePath,
49
+ startOwnerControlServer
50
+ } from "../owner-control.js";
51
+ import {
52
+ createOwnerTelemetryRecorder,
53
+ observabilityRetention,
54
+ resolveOwnerObservabilityLevel
55
+ } from "../observability/index.js";
56
+ import {
57
+ watchParentProcess
58
+ } from "../parent-process-watch.js";
59
+ import { ownerRawWsLogPath } from "../raw-ws-log.js";
60
+ import {
61
+ presentCanonicalEventForCclEvents,
62
+ presentCanonicalEventForDesktop
63
+ } from "../../pipeline/canonical-event-presentation.js";
64
+ import { compactStateForEvents } from "../../pipeline/event-format.js";
65
+ import { createClawclawRuntime } from "./runtime.js";
66
+ import { assembleClawclawPlugins } from "./plugins/assembly.js";
67
+ import {
68
+ ClawclawBehaviorCatalog,
69
+ createClawclawBehaviorControlDriver
70
+ } from "./plugins/behavior/index.js";
71
+ import {
72
+ ClawclawMailboxService,
73
+ CompositeClawclawMailboxDriver,
74
+ ClaudeChannelMailboxAdapter,
75
+ ClaudeChannelSocketSink,
76
+ DesktopEventSocketSink,
77
+ GameSyncPerceptionReportAdapter,
78
+ GameSyncRuntimeReportAdapter,
79
+ AgentMailboxCoordinator,
80
+ clawclawEventRequiresDetails,
81
+ MailboxEventBatchPump,
82
+ CCL_EVENTS_MAILBOX_CONSUMER_ID,
83
+ DESKTOP_IPC_MAILBOX_CONSUMER_ID,
84
+ MONITOR_MAILBOX_CONSUMER_ID
85
+ } from "./plugins/mailbox/index.js";
86
+ import { BEHAVIOR_PLUGIN_API_VERSION, resolveClawclawResourceMetadata } from "../../sdk/behavior-plugin/index.js";
87
+ import { TRIGGER_PLUGIN_API_VERSION } from "../../sdk/trigger-plugin/index.js";
88
+ import {
89
+ readLocalAgentWorkspaceSnapshot,
90
+ resolveLocalAgentWorkspaceSnapshot
91
+ } from "../../lib/agent-workspace-sync.js";
92
+ import { filterInactiveAgentWorkspaceSnapshot } from "../../lib/capability-cloud-presence.js";
93
+ import {
94
+ listAgentWorkspaceBehaviorSources,
95
+ listAgentWorkspacePerceptionSources,
96
+ mergeAgentWorkspaceBehaviorSources,
97
+ mergeAgentWorkspacePerceptionSources
98
+ } from "../../lib/agent-workspace-runtime.js";
99
+ import { listClawclawTriggerSources } from "./plugins/trigger/trigger-source.js";
100
+ import {
101
+ clawclawQueueGameId,
102
+ ClawclawSourcePlugin,
103
+ normalizeClawclawQueueState
104
+ } from "./plugins/source/index.js";
105
+ import { discoverLocalCapabilities } from "../../lib/capability-discovery.js";
106
+ import {
107
+ ensureAccountUserDataLayout,
108
+ getUserDataAccountTriggersDir
109
+ } from "../../lib/user-data.js";
110
+ const FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS = 5e3;
111
+ function ownerAgentEventPresenter(delivery, desktopHost) {
112
+ return delivery === "desktop_ipc" || desktopHost ? presentCanonicalEventForDesktop : presentCanonicalEventForCclEvents;
113
+ }
114
+ function channelOwnerDeliveryPolicy(channelDelivery, localStopRequested = false) {
115
+ const enabled = channelDelivery === true;
116
+ return {
117
+ enabled,
118
+ drainOnNaturalCompletion: enabled && !localStopRequested
119
+ };
120
+ }
121
+ async function performOwnerAgentAction(runtime, capability, action, expectedScope) {
122
+ return runtime.performAction(
123
+ capability,
124
+ action,
125
+ expectedScope,
126
+ { kind: "agent" }
127
+ );
128
+ }
129
+ function deriveClawclawOwnerRuntimeStart(queueValue, intent) {
130
+ const initialQueueState = normalizeClawclawQueueState(queueValue);
131
+ const status = queueStatus(initialQueueState);
132
+ const mode = queueMode(initialQueueState);
133
+ const roomCode = queueRoomCode(initialQueueState);
134
+ const gameId = clawclawQueueGameId(initialQueueState);
135
+ if (status === "in_room") {
136
+ const switchingRooms = intent.kind === "join_room" && intent.roomCode !== roomCode;
137
+ if (!switchingRooms && roomCode) {
138
+ return {
139
+ initialQueueState,
140
+ initialSegment: { kind: "room", identity: roomCode },
141
+ mode: mode ?? "room",
142
+ resume: true,
143
+ resumeKey: roomCode
144
+ };
145
+ }
146
+ }
147
+ if (status === "allocated" && gameId) {
148
+ return {
149
+ initialQueueState,
150
+ initialSegment: { kind: "game", identity: gameId },
151
+ ...mode ? { mode } : {},
152
+ // Match sessions use game_id as their session key. Room sessions keep
153
+ // room_code as the session key, but can still match the current game
154
+ // segment by game_id when /queue/status omits room_code during play.
155
+ resume: true,
156
+ ...isRoomMode(mode) ? roomCode ? { resumeKey: roomCode } : {} : { resumeKey: gameId }
157
+ };
158
+ }
159
+ if ((status === "queued" || status === "already_in_queue" || status === "allocating") && mode) {
160
+ return {
161
+ initialQueueState,
162
+ initialSegment: { kind: "matching", identity: mode },
163
+ mode,
164
+ resume: true
165
+ };
166
+ }
167
+ return {
168
+ initialQueueState,
169
+ initialSegment: { kind: "bootstrap" },
170
+ resume: false
171
+ };
172
+ }
173
+ const MAILBOX_DRAIN_TIMEOUT_MS = 2e3;
174
+ const DESKTOP_RESOURCE_LOCALE = "zh-CN";
175
+ const EVENTS_QUERY_BARRIER_TIMEOUT_MS = 1e4;
176
+ const LOCAL_STOP_FORCE_EXIT_MS = 1e4;
177
+ function roleFallbackBehaviors(config, catalog, warning = () => {
178
+ }) {
179
+ const loadable = new Set(catalog.list().filter((entry) => entry.loadable).map((entry) => entry.id));
180
+ const result = {};
181
+ for (const role of CLAWCLAW_ROLE_IDS) {
182
+ const behaviorId = config.fallback_behaviors[role];
183
+ if (behaviorId === null) continue;
184
+ if (!loadable.has(behaviorId)) {
185
+ warning("behavior_fallback_unavailable", { role, behavior_id: behaviorId });
186
+ continue;
187
+ }
188
+ result[role] = { behaviorId, input: {} };
189
+ }
190
+ return Object.freeze(result);
191
+ }
192
+ function triggerRegistrations(sources, config, catalog, warning = () => {
193
+ }) {
194
+ const loadableBehaviors = new Set(
195
+ catalog.list().filter((entry) => entry.loadable).map((entry) => entry.id)
196
+ );
197
+ const overrides = new Map(
198
+ toTriggerRegistrationOverrides(config.triggers).map((override) => [override.id, override])
199
+ );
200
+ const disabledTriggers = new Set(config.disabled_triggers);
201
+ const sourceIds = new Set(sources.map((source) => source.id));
202
+ for (const id of overrides.keys()) {
203
+ if (!sourceIds.has(id)) warning("trigger_source_unavailable", { trigger_id: id });
204
+ }
205
+ return Object.freeze(sources.map((source) => {
206
+ const override = overrides.get(source.id);
207
+ const behavior = override?.behavior ?? source.manifest.defaultBehavior;
208
+ const requestedEnabled = !disabledTriggers.has(source.id);
209
+ const enabled = requestedEnabled && source.apiVersion === TRIGGER_PLUGIN_API_VERSION && loadableBehaviors.has(behavior);
210
+ if (requestedEnabled && !enabled) {
211
+ warning("trigger_binding_unavailable", {
212
+ trigger_id: source.id,
213
+ behavior_id: behavior,
214
+ api_version: source.apiVersion
215
+ });
216
+ }
217
+ return Object.freeze({
218
+ source,
219
+ enabled,
220
+ ...override?.input === void 0 ? {} : { input: override.input },
221
+ ...override?.behavior === void 0 ? {} : { behavior: override.behavior },
222
+ ...override?.behaviorInput === void 0 ? {} : { behaviorInput: override.behaviorInput },
223
+ ...override?.reflexPriority === void 0 ? {} : { reflexPriority: override.reflexPriority },
224
+ ...override?.cooldownMs === void 0 ? {} : { cooldownMs: override.cooldownMs },
225
+ ...override?.rearm === void 0 ? {} : { rearm: override.rearm },
226
+ ...override?.maxRuntimeMs === void 0 ? {} : { maxRuntimeMs: override.maxRuntimeMs }
227
+ });
228
+ }));
229
+ }
230
+ function eventsQueryId(value) {
231
+ if (typeof value === "string" && /^[A-Za-z0-9_.:-]{1,120}$/.test(value)) return value;
232
+ return randomUUID();
233
+ }
234
+ function boundedTiming(value) {
235
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 36e5 ? Math.round(value) : void 0;
236
+ }
237
+ function ownerExpectedScope(value) {
238
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
239
+ const source = value;
240
+ if (typeof source.sessionId !== "string" || typeof source.segmentId !== "string") return void 0;
241
+ return { sessionId: source.sessionId, segmentId: source.segmentId };
242
+ }
243
+ function ownerScopeIsCurrent(runtime, expected) {
244
+ const actual = runtime.publicScope();
245
+ return actual.sessionId === expected.sessionId && actual.segmentId === expected.segmentId;
246
+ }
247
+ function readyRoleForScope(runtime, expected) {
248
+ const ready = runtime.readReadyView(0, 1);
249
+ if (ready.scope.sessionId !== expected.sessionId || ready.scope.segmentId !== expected.segmentId) return void 0;
250
+ const state = ready.state.state;
251
+ if (!state || typeof state !== "object" || Array.isArray(state)) return void 0;
252
+ const you = state.you;
253
+ if (!you || typeof you !== "object" || Array.isArray(you)) return void 0;
254
+ const role = you.role;
255
+ return typeof role === "string" ? role : void 0;
256
+ }
257
+ function eventsOutputCount(output) {
258
+ if (Array.isArray(output.events)) return output.events.length;
259
+ return output.found === true && output.event && typeof output.event === "object" ? 1 : 0;
260
+ }
261
+ async function waitWithin(promise, timeoutMs, error) {
262
+ let timer;
263
+ try {
264
+ return await Promise.race([
265
+ promise,
266
+ new Promise((_resolve, reject) => {
267
+ timer = setTimeout(() => reject(new Error(error)), timeoutMs);
268
+ timer.unref?.();
269
+ })
270
+ ]);
271
+ } finally {
272
+ if (timer) clearTimeout(timer);
273
+ }
274
+ }
275
+ async function waitForMailboxDrain(broker, timeoutMs = MAILBOX_DRAIN_TIMEOUT_MS) {
276
+ const deadline = Date.now() + timeoutMs;
277
+ while (broker.hasPendingCurrent()) {
278
+ if (Date.now() >= deadline) return false;
279
+ await new Promise((resolve) => setTimeout(resolve, 25));
280
+ }
281
+ return true;
282
+ }
283
+ function publishOwnerRuntimePointer(stateDir, control, instanceId) {
284
+ const path = gameStartRuntimePath(stateDir);
285
+ const tempPath = `${path}.${process.pid}.tmp`;
286
+ const value = {
287
+ schema: "clawclaw.owner.v1",
288
+ owner_pid: process.pid,
289
+ ...instanceId ? { instance_id: instanceId } : {},
290
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
291
+ control: control.control,
292
+ control_token: control.token,
293
+ relay_token: control.relayToken
294
+ };
295
+ writeFileSync(tempPath, JSON.stringify(value), { encoding: "utf8", mode: 384 });
296
+ try {
297
+ chmodSync(tempPath, 384);
298
+ } catch {
299
+ }
300
+ try {
301
+ renameSync(tempPath, path);
302
+ } catch (error) {
303
+ try {
304
+ unlinkSync(path);
305
+ renameSync(tempPath, path);
306
+ } catch {
307
+ try {
308
+ unlinkSync(tempPath);
309
+ } catch {
310
+ }
311
+ throw error;
312
+ }
313
+ }
314
+ try {
315
+ chmodSync(path, 384);
316
+ } catch {
317
+ }
318
+ let released = false;
319
+ return {
320
+ release: () => {
321
+ if (released) return;
322
+ released = true;
323
+ try {
324
+ const current = JSON.parse(readFileSync(path, "utf8"));
325
+ if (current.owner_pid === process.pid && current.control?.path === control.control.path) {
326
+ unlinkSync(path);
327
+ }
328
+ } catch {
329
+ }
330
+ try {
331
+ unlinkSync(tempPath);
332
+ } catch {
333
+ }
334
+ }
335
+ };
336
+ }
337
+ async function runClawclawOwner(options) {
338
+ let lock;
339
+ let telemetry;
340
+ let ingressRawLog;
341
+ let closeGameSyncTransports;
342
+ let runtime;
343
+ let source;
344
+ let mailbox;
345
+ let mailboxService;
346
+ let cclEventsMailbox;
347
+ let desktopMailbox;
348
+ let desktopEventPump;
349
+ let channelAdapter;
350
+ let channelEventPump;
351
+ let mailboxBroker;
352
+ let ownerControl;
353
+ let runtimePointer;
354
+ let startingControl;
355
+ let relayAlive = false;
356
+ let relayAbort;
357
+ let relayPromise;
358
+ let parentWatch;
359
+ let diagnosticSampleTimer;
360
+ let processTimingSampler;
361
+ let localStopRequested = false;
362
+ let forceExitTimer;
363
+ const channelPolicy = channelOwnerDeliveryPolicy(options.channelDelivery);
364
+ const requestLocalStop = () => {
365
+ if (localStopRequested) return;
366
+ localStopRequested = true;
367
+ try {
368
+ lock?.setPhase("stopping");
369
+ } catch {
370
+ }
371
+ forceExitTimer = setTimeout(() => process.exit(1), LOCAL_STOP_FORCE_EXIT_MS);
372
+ forceExitTimer.unref?.();
373
+ void source?.submitIntent({ kind: "stop" }).catch(() => {
374
+ });
375
+ };
376
+ const onSignal = () => requestLocalStop();
377
+ startupMark("owner.entry");
378
+ try {
379
+ lock = await timeStartup("owner.lock", () => acquireOwnerLock(options.profile, {
380
+ force: options.forceExistingRuntime === true
381
+ }));
382
+ const controlDone = startupSpan("owner.control");
383
+ startingControl = createStartingOwnerControl(lock.instanceId, requestLocalStop);
384
+ ownerControl = await startOwnerControlServer(
385
+ getProfileRuntimeStateDir(options.profile),
386
+ startingControl.handle,
387
+ { get observability() {
388
+ return telemetry;
389
+ } }
390
+ );
391
+ runtimePointer = publishOwnerRuntimePointer(
392
+ getProfileRuntimeStateDir(options.profile),
393
+ ownerControl,
394
+ lock.instanceId
395
+ );
396
+ parentWatch = watchParentProcess(() => {
397
+ runtime?.diagnostic("runtime.owner.parent_exited", {
398
+ parent_pid: parentWatch?.parentPid ?? process.ppid
399
+ }, "warn");
400
+ requestLocalStop();
401
+ });
402
+ process.on("SIGINT", onSignal);
403
+ process.on("SIGTERM", onSignal);
404
+ telemetry = createOwnerTelemetryRecorder(options.profile);
405
+ telemetry.log("info", "owner.control.started", { transport: ownerControl.control.kind }, {
406
+ component: "runtime.owner_control"
407
+ });
408
+ controlDone?.();
409
+ const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === "full";
410
+ if (fullDiagnosticsEnabled) {
411
+ const retention = observabilityRetention();
412
+ ingressRawLog = { path: ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)), options: retention };
413
+ telemetry.log("info", "runtime.raw_ws.capture_started", {
414
+ max_file_bytes: retention.maxFileBytes,
415
+ retained_files: retention.retainedFiles
416
+ }, { component: "runtime.transport" });
417
+ }
418
+ const client = new GameClient({
419
+ lobbyUrl: options.profile.serverUrl,
420
+ apiKey: options.profile.apiKey,
421
+ agentName: options.profile.agentName,
422
+ enableWs: true,
423
+ gameSyncIngress: {
424
+ rawLog: ingressRawLog,
425
+ diagnostic: (name, attributes, severity = "debug") => telemetry?.log(severity, name, attributes, {
426
+ component: "runtime.transport",
427
+ scope: runtime?.publicScope()
428
+ })
429
+ }
430
+ });
431
+ closeGameSyncTransports = () => client.closeGameSyncTransports();
432
+ void client.lobbyHostContext;
433
+ const initialQueue = options.resolveStartupIntent ? { value: await timeStartup("owner.initial_queue_status", () => client.getQueueStatus("clawclaw")) } : void 0;
434
+ const resolveIntent = options.resolveStartupIntent;
435
+ const intent = resolveIntent && initialQueue ? await timeStartup("owner.resolve_participation", () => resolveIntent(client, initialQueue.value)) : options.intent;
436
+ const assemblyDone = startupSpan("owner.resource_assembly");
437
+ const workspaceDir = getWorkspaceDir();
438
+ ensureAccountUserDataLayout(workspaceDir, options.profile);
439
+ const perceptionConfig = readWorkspacePerceptionConfig();
440
+ const gameplayConfig = readGameplayConfig(workspaceDir, options.profile);
441
+ const storedAgentWorkspace = readLocalAgentWorkspaceSnapshot(workspaceDir, options.profile);
442
+ const agentWorkspace = filterInactiveAgentWorkspaceSnapshot(
443
+ workspaceDir,
444
+ options.profile,
445
+ storedAgentWorkspace ? resolveLocalAgentWorkspaceSnapshot(workspaceDir, options.profile, storedAgentWorkspace) : void 0
446
+ );
447
+ const configurationWarning = (code, details) => {
448
+ telemetry?.log("warn", `runtime.configuration.${code}`, details, {
449
+ component: "runtime.behavior"
450
+ });
451
+ };
452
+ const disabledBehaviors = new Set(gameplayConfig.disabled_behaviors);
453
+ const discoveredLocalCapabilities = discoverLocalCapabilities(workspaceDir, options.profile);
454
+ const agentBehaviorSources = agentWorkspace ? listAgentWorkspaceBehaviorSources(workspaceDir, options.profile, agentWorkspace) : [];
455
+ const behaviorSources = mergeAgentWorkspaceBehaviorSources(
456
+ discoveredLocalCapabilities.behaviors.filter(({ source: source2, entry }) => entry.selection === "equipped" && !disabledBehaviors.has(source2.id) && !agentWorkspace?.items.strategy.some((item) => item.resourceId === entry.hub?.resourceId)).map(({ source: source2 }) => source2),
457
+ agentBehaviorSources,
458
+ disabledBehaviors
459
+ );
460
+ const behaviorSourceById = new Map(behaviorSources.map((source2) => [source2.id, source2]));
461
+ const behaviorCatalog = new ClawclawBehaviorCatalog(behaviorSources);
462
+ const behaviorEventTypes = [...new Set(
463
+ behaviorCatalog.list().filter((entry) => entry.loadable && entry.apiVersion === BEHAVIOR_PLUGIN_API_VERSION).flatMap((entry) => entry.produces ?? [])
464
+ )];
465
+ const fallbackBehaviors = roleFallbackBehaviors(
466
+ gameplayConfig,
467
+ behaviorCatalog,
468
+ configurationWarning
469
+ );
470
+ const triggerSources = listClawclawTriggerSources(
471
+ getUserDataAccountTriggersDir(workspaceDir, options.profile)
472
+ );
473
+ const legacyTriggers = triggerRegistrations(
474
+ triggerSources,
475
+ gameplayConfig,
476
+ behaviorCatalog,
477
+ configurationWarning
478
+ );
479
+ const triggers = legacyTriggers;
480
+ const disabledPerceptions = new Set(gameplayConfig.disabled_perception_modules);
481
+ const agentPerceptionSources = agentWorkspace ? listAgentWorkspacePerceptionSources(workspaceDir, options.profile, agentWorkspace) : [];
482
+ const localPerceptionSources = discoveredLocalCapabilities.perceptions.filter(({ source: source2, entry }) => entry.selection === "equipped" && !disabledPerceptions.has(source2.id) && !agentWorkspace?.items.perception.some((item) => item.resourceId === entry.hub?.resourceId)).map(({ source: source2 }) => source2);
483
+ const perceptionSources = mergeAgentWorkspacePerceptionSources(
484
+ localPerceptionSources,
485
+ agentPerceptionSources,
486
+ disabledPerceptions
487
+ );
488
+ const perceptionModules = [
489
+ ...localPerceptionSources.map(({ id }) => id),
490
+ ...agentPerceptionSources.map(({ id }) => id)
491
+ ].filter((id, index, values) => values.indexOf(id) === index);
492
+ const assembly = assembleClawclawPlugins(client, {
493
+ epochPlugins: options.epochPlugins,
494
+ perception: {
495
+ ...perceptionConfig.perception,
496
+ modules: perceptionModules,
497
+ moduleSources: perceptionSources,
498
+ diagnosticsEnabled: fullDiagnosticsEnabled
499
+ },
500
+ behaviorCatalog,
501
+ behaviorDiagnosticsEnabled: fullDiagnosticsEnabled,
502
+ triggerDiagnosticsEnabled: fullDiagnosticsEnabled,
503
+ fallbackBehaviors,
504
+ behaviorEventTypes,
505
+ triggers
506
+ });
507
+ await assembly.behavior.setIdleMs(gameplayConfig.idle_ms);
508
+ const epochPlugins = assembly.plugins;
509
+ mailbox = assembly.mailbox;
510
+ assemblyDone?.();
511
+ const runtimeStart = deriveClawclawOwnerRuntimeStart(
512
+ initialQueue ? initialQueue.value : await timeStartup("owner.initial_queue_status", () => client.getQueueStatus("clawclaw")),
513
+ intent
514
+ );
515
+ const reflexControl = new BehaviorReflexControl(
516
+ assembly.modules,
517
+ assembly.behavior,
518
+ behaviorCatalog,
519
+ () => runtime.publicScope()
520
+ );
521
+ const runtimeDone = startupSpan("owner.runtime_init");
522
+ runtime = createClawclawRuntime(options.profile, {
523
+ processingCadence: createClawclawProcessingCadence(readRuntimeCycleIntervalMs()),
524
+ initialSegment: runtimeStart.initialSegment,
525
+ mode: runtimeStart.mode,
526
+ resume: runtimeStart.resume,
527
+ resumeKey: runtimeStart.resumeKey,
528
+ observability: telemetry,
529
+ runtimeEpochPlugins: epochPlugins,
530
+ visualEventDelivery: perceptionConfig.events.delivery,
531
+ visualEventTypes: assembly.perception.produces.events,
532
+ behaviorEventTypes: assembly.behavior.produces?.events ?? [],
533
+ perceptionEventTypes: assembly.modules?.produces.events
534
+ });
535
+ runtimeDone?.();
536
+ const deferredShort = new DeferredMeetingShortStrategy(runtime, assembly.behavior, (request) => {
537
+ const source2 = behaviorSourceById.get(request.behavior);
538
+ if (!source2) return void 0;
539
+ normalizeBehaviorInput(request.input, source2.inputs, { allowedKeys: ["timeout_ms", "duration_ms"] });
540
+ return resolveClawclawResourceMetadata(source2, "zh-CN");
541
+ });
542
+ assembly.behavior.attachDeferredShortControl(deferredShort);
543
+ if (fullDiagnosticsEnabled) {
544
+ processTimingSampler = new RuntimeProcessTimingSampler();
545
+ const sample = () => {
546
+ try {
547
+ const memory = process.memoryUsage();
548
+ const heap = getHeapStatistics();
549
+ const behaviorStatus = assembly.behavior.status();
550
+ const effectiveBehaviorId = behaviorStatus.current?.behaviorId ?? behaviorStatus.stack.long?.behaviorId ?? behaviorStatus.stack.fallback?.behaviorId;
551
+ const effectiveBehavior = effectiveBehaviorId ? behaviorSourceById.get(effectiveBehaviorId) : void 0;
552
+ telemetry?.log("debug", "runtime.diagnostics.sample", {
553
+ sample_interval_ms: FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS,
554
+ node_version: process.version,
555
+ process_platform: process.platform,
556
+ process_arch: process.arch,
557
+ process_uptime_seconds: Math.round(process.uptime()),
558
+ process_timing: processTimingSampler?.sample(),
559
+ process_memory: {
560
+ rss_bytes: memory.rss,
561
+ heap_total_bytes: memory.heapTotal,
562
+ heap_used_bytes: memory.heapUsed,
563
+ external_bytes: memory.external,
564
+ array_buffers_bytes: memory.arrayBuffers,
565
+ heap_size_limit_bytes: heap.heap_size_limit
566
+ },
567
+ scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
568
+ retained_records: runtime?.runtimeRetainedRecordCounts(),
569
+ persistence: runtime?.runtimePersistenceDiagnostics(),
570
+ detail_capture: telemetry?.detailStats(),
571
+ behavior: {
572
+ ...assembly.behavior.diagnosticSnapshot(),
573
+ effective_source: effectiveBehavior ? {
574
+ id: effectiveBehavior.id,
575
+ execution: effectiveBehavior.execution,
576
+ every_ticks: effectiveBehavior.everyTicks,
577
+ source: effectiveBehavior.management.source,
578
+ managed_by: effectiveBehavior.management.managedBy,
579
+ resource_id: effectiveBehavior.management.resourceId ?? null,
580
+ version_id: effectiveBehavior.management.versionId ?? null,
581
+ resolution: effectiveBehavior.management.resolution ?? null,
582
+ file: effectiveBehavior.sourcePath.split(/[\\/]/).at(-1) ?? null
583
+ } : null
584
+ },
585
+ perception: assembly.perception.diagnosticSnapshot(),
586
+ trigger: assembly.trigger.diagnosticSnapshot()
587
+ }, {
588
+ component: "runtime.diagnostics",
589
+ scope: runtime?.publicScope()
590
+ });
591
+ } catch {
592
+ }
593
+ };
594
+ sample();
595
+ diagnosticSampleTimer = setInterval(sample, FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS);
596
+ diagnosticSampleTimer.unref?.();
597
+ }
598
+ if (!isMailboxRepository(runtime.repository)) {
599
+ throw new Error("The configured Runtime repository does not support durable Mailbox delivery.");
600
+ }
601
+ const mailboxRepository = runtime.repository;
602
+ const perceptionSourceById = new Map(perceptionSources.map((source2) => [source2.id, source2]));
603
+ const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
604
+ producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...assembly.modules ? [assembly.modules.id] : []],
605
+ descriptor: (id) => {
606
+ const source2 = perceptionSourceById.get(id);
607
+ return source2 ? { ...resolveClawclawResourceMetadata({ ...source2.manifest, display: source2.display }, client.gameSyncLocale), perceptionId: id } : void 0;
608
+ },
609
+ send: (reports) => client.reportGameSyncPerceptions(reports),
610
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
611
+ });
612
+ const runtimeReportAdapter = new GameSyncRuntimeReportAdapter({
613
+ snapshot: (ready) => {
614
+ const view = runtime.readReadyView(0, 1);
615
+ if (view.epochSeq !== ready.epochSeq || view.scope.segmentId !== ready.scope.segmentId) return null;
616
+ const state = view.state.state;
617
+ const status = view.state.stateStatus;
618
+ if (!state?.game_id || status.connectionState !== "connected" || !status.connectionId || status.terminal || state.phase === "game_over" || state.phase === "settling") return null;
619
+ const locale = client.gameSyncLocale;
620
+ return { gameId: String(state.game_id), connectionId: status.connectionId, resources: {
621
+ perceivers: [
622
+ ...assembly.perception.localizedModuleDescriptors(locale),
623
+ ...assembly.reminders.localizedModuleDescriptors(locale),
624
+ ...assembly.modules?.localizedModuleDescriptors(locale) ?? []
625
+ ].sort((a, b) => a.id.localeCompare(b.id)),
626
+ strategies: behaviorCatalog.list().filter((entry) => entry.loadable).map((entry) => resolveClawclawResourceMetadata(behaviorSourceById.get(entry.id), locale)).sort((a, b) => a.id.localeCompare(b.id))
627
+ } };
628
+ },
629
+ send: (report, gameId, connectionId) => client.reportGameSyncRuntime(report, gameId, connectionId),
630
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
631
+ });
632
+ cclEventsMailbox = new AgentMailboxCoordinator({
633
+ repository: mailboxRepository,
634
+ readyView: () => runtime.readReadyView(0, 1),
635
+ presentEvent: ownerAgentEventPresenter("ccl_events", !!options.desktopEvents),
636
+ compactState: compactStateForEvents,
637
+ admitEvent: isClawclawAgentNotification,
638
+ eventFilter: clawclawEventRequiresDetails,
639
+ delegatedMonitorConsumerId: MONITOR_MAILBOX_CONSUMER_ID,
640
+ consumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID,
641
+ adapter: {
642
+ id: "clawclaw.mailbox.adapter.ccl-events",
643
+ acknowledgement: "explicit",
644
+ consumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID
645
+ },
646
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
647
+ });
648
+ mailboxService = new ClawclawMailboxService({
649
+ notificationOnly: true,
650
+ repository: mailboxRepository,
651
+ readyView: () => runtime.readReadyView(0, 1),
652
+ agentMailbox: cclEventsMailbox,
653
+ consumerId: MONITOR_MAILBOX_CONSUMER_ID,
654
+ delegatedDetailsConsumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID,
655
+ monitorEnabled: !!options.notificationHost,
656
+ diagnostic: (name, attributes, severity) => runtime?.diagnostic(name, attributes, severity)
657
+ });
658
+ const mailboxDrivers = [
659
+ runtimeReportAdapter,
660
+ perceptionReportAdapter,
661
+ mailboxService,
662
+ cclEventsMailbox
663
+ ];
664
+ if (options.desktopEvents) {
665
+ desktopMailbox = new AgentMailboxCoordinator({
666
+ admitEvent: isClawclawAgentNotification,
667
+ repository: mailboxRepository,
668
+ readyView: () => runtime.readReadyView(0, 1),
669
+ presentEvent: ownerAgentEventPresenter("desktop_ipc", true),
670
+ compactState: () => null,
671
+ consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID,
672
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
673
+ });
674
+ const desktopSink = new DesktopEventSocketSink({
675
+ ...options.desktopEvents,
676
+ activeResources: () => ({
677
+ locale: DESKTOP_RESOURCE_LOCALE,
678
+ strategy: (() => {
679
+ const stack = assembly.behavior.status().stack;
680
+ const behaviorId = stack.long?.behaviorId ?? stack.fallback?.behaviorId;
681
+ const source2 = behaviorId ? behaviorSourceById.get(behaviorId) : void 0;
682
+ return source2 ? resolveClawclawResourceMetadata(source2, DESKTOP_RESOURCE_LOCALE) : null;
683
+ })(),
684
+ perceptions: [
685
+ ...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
686
+ ...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
687
+ ...assembly.modules?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? []
688
+ ]
689
+ }),
690
+ eventDescriptors: () => assembly.perception.localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE).map((descriptor) => ({
691
+ type: descriptor.type,
692
+ perception_id: descriptor.perceptionId,
693
+ name: descriptor.name,
694
+ description: descriptor.description
695
+ })),
696
+ onConnected: () => desktopEventPump?.retryNow(),
697
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
698
+ });
699
+ desktopEventPump = new MailboxEventBatchPump({
700
+ adapter: {
701
+ id: "clawclaw.mailbox.adapter.desktop-ipc",
702
+ acknowledgement: "explicit",
703
+ consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID
704
+ },
705
+ source: {
706
+ prepare: () => {
707
+ const result = desktopMailbox.prepareEvents({
708
+ deliveryVia: "desktop_ipc",
709
+ ownerIdPrefix: "desktop_ipc"
710
+ });
711
+ if (startupTraceEnabled() && result.deliveryToken && result.batch.events.some((event) => {
712
+ const type = typeof event === "string" ? event.split(" | ", 1)[0].trim() : event.type;
713
+ return type === "joined" || type === "match_start";
714
+ })) startupMark("match.mailbox_prepared");
715
+ return result;
716
+ },
717
+ renew: (deliveryToken) => desktopMailbox.renew(deliveryToken),
718
+ ack: (deliveryToken, level) => desktopMailbox.ack(deliveryToken, level),
719
+ release: (deliveryToken) => desktopMailbox.release(deliveryToken)
720
+ },
721
+ sink: desktopSink,
722
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
723
+ });
724
+ mailboxDrivers.push(desktopMailbox, desktopEventPump);
725
+ desktopSink.start();
726
+ }
727
+ assembly.behavior.attachDriver(createClawclawBehaviorControlDriver(runtime));
728
+ if (channelPolicy.enabled) {
729
+ channelAdapter = new ClaudeChannelMailboxAdapter({
730
+ notificationOnly: true,
731
+ repository: mailboxRepository,
732
+ readyView: () => runtime.readReadyView(0, 1),
733
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
734
+ });
735
+ const channelSink = new ClaudeChannelSocketSink({
736
+ onConnected: () => channelEventPump?.retryNow(),
737
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
738
+ });
739
+ channelEventPump = new MailboxEventBatchPump({
740
+ source: {
741
+ prepare: () => channelAdapter.prepare(),
742
+ renew: (deliveryToken) => channelAdapter.renew(deliveryToken),
743
+ ack: (deliveryToken, level) => channelAdapter.ack(deliveryToken, level),
744
+ release: (deliveryToken) => channelAdapter.release(deliveryToken)
745
+ },
746
+ sink: channelSink,
747
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes)
748
+ });
749
+ mailboxDrivers.push(channelAdapter, channelEventPump);
750
+ channelSink.start();
751
+ }
752
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver(mailboxDrivers));
753
+ const ownerSource = new ClawclawSourcePlugin({
754
+ client,
755
+ profile: options.profile,
756
+ initialIntent: intent,
757
+ initialQueueState: runtimeStart.initialQueueState
758
+ });
759
+ source = ownerSource;
760
+ let eventsQueryBarrier;
761
+ let eventsQuerySequence = 0;
762
+ const preparedEventsQueryTraces = /* @__PURE__ */ new Map();
763
+ const readyViewAfterEventsQueryBoundary = (queryId, querySeq) => {
764
+ if (eventsQueryBarrier) return eventsQueryBarrier;
765
+ const requestId = queryId;
766
+ const startedAt = Date.now();
767
+ const operation = (async () => {
768
+ let epochSeq;
769
+ try {
770
+ const acceptance = await ownerSource.submitEventsQueryBoundary(requestId);
771
+ const acceptedAt = Date.now();
772
+ epochSeq = acceptance.epoch.epochSeq;
773
+ runtime.diagnostic("runtime.events_query.boundary_accepted", {
774
+ query_seq: querySeq,
775
+ epoch_seq: epochSeq,
776
+ source_boundary_ms: acceptedAt - startedAt
777
+ });
778
+ const ready = await waitWithin(
779
+ runtime.waitForEpochReadyView(epochSeq),
780
+ EVENTS_QUERY_BARRIER_TIMEOUT_MS,
781
+ "events_query_barrier_timeout"
782
+ );
783
+ runtime.diagnostic("runtime.events_query.boundary_ready", {
784
+ query_seq: querySeq,
785
+ epoch_seq: ready.epochSeq,
786
+ event_watermark: ready.eventWatermark,
787
+ source_boundary_ms: acceptedAt - startedAt,
788
+ plugin_ready_ms: Date.now() - acceptedAt,
789
+ duration_ms: Date.now() - startedAt
790
+ });
791
+ return {
792
+ ready,
793
+ querySeq,
794
+ sourceBoundaryMs: acceptedAt - startedAt,
795
+ pluginReadyMs: Date.now() - acceptedAt,
796
+ totalMs: Date.now() - startedAt
797
+ };
798
+ } catch (error) {
799
+ runtime.diagnostic("runtime.events_query.boundary_failed", {
800
+ query_seq: querySeq,
801
+ ...epochSeq === void 0 ? {} : { epoch_seq: epochSeq },
802
+ duration_ms: Date.now() - startedAt,
803
+ error: error instanceof Error ? error.message : String(error)
804
+ }, "warn");
805
+ throw error;
806
+ }
807
+ })();
808
+ eventsQueryBarrier = operation.finally(() => {
809
+ eventsQueryBarrier = void 0;
810
+ });
811
+ return eventsQueryBarrier;
812
+ };
813
+ if (options.notificationHost) {
814
+ mailboxBroker = new MailboxRelayBroker(
815
+ mailboxRepository,
816
+ "short",
817
+ MONITOR_MAILBOX_CONSUMER_ID
818
+ );
819
+ relayAbort = new AbortController();
820
+ relayAlive = true;
821
+ const monitorRateGate = new HostMonitorWriteGate();
822
+ relayPromise = runStdoutMailboxRelay({
823
+ request: async (type, payload) => {
824
+ if (type === "mailbox_claim") mailboxService?.prepareMonitor();
825
+ return mailboxBroker?.handle({ type, ...payload }) ?? null;
826
+ },
827
+ emit: (payload) => options.notificationHost.emit(payload),
828
+ compose: (payloads) => mailboxService.composeMonitor(payloads),
829
+ rateGate: monitorRateGate,
830
+ isOwnerAlive: () => relayAlive,
831
+ mode: "short",
832
+ signal: relayAbort.signal
833
+ }).catch((error) => {
834
+ runtime?.diagnostic("runtime.mailbox.host_relay_failed", {
835
+ error: error instanceof Error ? error.message : String(error)
836
+ }, "error");
837
+ });
838
+ }
839
+ startingControl.setHandler(async (request, context) => {
840
+ if (context.principal === "host_relay") {
841
+ if (request.type === "mailbox_claim") mailboxService?.prepareMonitor();
842
+ return mailboxBroker?.handle(request) ?? { ok: false, error: "mailbox_monitor_unavailable" };
843
+ }
844
+ if (context.principal !== "master") return { ok: false, error: "owner_request_not_supported" };
845
+ if (request.type === "mailbox_claim" || request.type === "mailbox_ack" || request.type === "mailbox_nack") {
846
+ if (request.type === "mailbox_claim") mailboxService?.prepareMonitor();
847
+ return mailboxBroker?.handle(request) ?? { ok: false, error: "mailbox_monitor_unavailable" };
848
+ }
849
+ if (request.type === "mailbox_events_prepare") {
850
+ const ownerStartedAtMs = Date.now();
851
+ const queryId = eventsQueryId(request.query_id);
852
+ const querySeq = ++eventsQuerySequence;
853
+ const eventType = typeof request.event_type === "string" ? request.event_type : void 0;
854
+ const mode = request.mode === "backlog" ? "backlog" : "current";
855
+ const queryKind = eventType ? "latest_by_type" : mode === "backlog" ? "unread_backlog" : "unread_current";
856
+ let stage = "query_boundary";
857
+ try {
858
+ const boundary = !eventType && mode === "current" ? await readyViewAfterEventsQueryBoundary(queryId, querySeq) : void 0;
859
+ const mailboxStartedAtMs = Date.now();
860
+ stage = "mailbox_prepare";
861
+ const prepared = await mailboxService.prepareEventsWhenAvailable({
862
+ ...eventType ? { eventType } : {},
863
+ mode
864
+ }, boundary?.ready);
865
+ const ownerPreparedAtMs = Date.now();
866
+ for (const [token, trace] of preparedEventsQueryTraces) {
867
+ if (ownerPreparedAtMs - trace.ownerPreparedAtMs > 6e4) {
868
+ preparedEventsQueryTraces.delete(token);
869
+ }
870
+ }
871
+ if (prepared.deliveryToken) {
872
+ preparedEventsQueryTraces.set(prepared.deliveryToken, {
873
+ querySeq,
874
+ ownerStartedAtMs,
875
+ ownerPreparedAtMs
876
+ });
877
+ }
878
+ const state = prepared.output.state;
879
+ const stateRecord = state && typeof state === "object" ? state : void 0;
880
+ runtime.diagnostic("runtime.events_query.prepared", {
881
+ query_seq: querySeq,
882
+ query_kind: queryKind,
883
+ ...eventType ? { event_type: eventType } : {},
884
+ boundary_used: !!boundary,
885
+ ...boundary ? {
886
+ boundary_query_seq: boundary.querySeq,
887
+ boundary_shared: boundary.querySeq !== querySeq,
888
+ source_boundary_ms: boundary.sourceBoundaryMs,
889
+ plugin_ready_ms: boundary.pluginReadyMs,
890
+ boundary_total_ms: boundary.totalMs,
891
+ ready_epoch_seq: boundary.ready.epochSeq,
892
+ event_watermark: boundary.ready.eventWatermark
893
+ } : {},
894
+ mailbox_prepare_ms: ownerPreparedAtMs - mailboxStartedAtMs,
895
+ owner_total_ms: ownerPreparedAtMs - ownerStartedAtMs,
896
+ event_count: eventsOutputCount(prepared.output),
897
+ delivery_token_present: !!prepared.deliveryToken,
898
+ ...typeof stateRecord?.phase === "string" ? { phase: stateRecord.phase } : {},
899
+ ...typeof stateRecord?.tick === "number" ? { tick: stateRecord.tick } : {}
900
+ }, "info");
901
+ return {
902
+ ok: true,
903
+ type: "mailbox_events_prepare",
904
+ query_id: queryId,
905
+ output: prepared.output,
906
+ ...prepared.deliveryToken ? { delivery_token: prepared.deliveryToken } : {}
907
+ };
908
+ } catch (error) {
909
+ runtime.diagnostic("runtime.events_query.prepare_failed", {
910
+ query_seq: querySeq,
911
+ query_kind: queryKind,
912
+ ...eventType ? { event_type: eventType } : {},
913
+ stage,
914
+ duration_ms: Date.now() - ownerStartedAtMs,
915
+ error: error instanceof Error ? error.message : String(error)
916
+ }, "warn");
917
+ throw error;
918
+ }
919
+ }
920
+ if (request.type === "mailbox_events_ack") {
921
+ const ackStartedAtMs = Date.now();
922
+ const token = typeof request.delivery_token === "string" ? request.delivery_token : "";
923
+ const trace = preparedEventsQueryTraces.get(token);
924
+ preparedEventsQueryTraces.delete(token);
925
+ const accepted = mailboxService.ackEvents(token);
926
+ runtime.diagnostic("runtime.events_query.client_completed", {
927
+ ...trace ? { query_seq: trace.querySeq } : {},
928
+ accepted,
929
+ ...trace ? {
930
+ prepared_to_ack_ms: ackStartedAtMs - trace.ownerPreparedAtMs,
931
+ owner_observed_total_ms: Date.now() - trace.ownerStartedAtMs
932
+ } : {},
933
+ ...boundedTiming(request.client_elapsed_ms) === void 0 ? {} : {
934
+ client_elapsed_before_ack_ms: boundedTiming(request.client_elapsed_ms)
935
+ },
936
+ ...boundedTiming(request.prepare_rpc_ms) === void 0 ? {} : {
937
+ prepare_rpc_ms: boundedTiming(request.prepare_rpc_ms)
938
+ },
939
+ ...boundedTiming(request.stdout_write_ms) === void 0 ? {} : {
940
+ stdout_write_ms: boundedTiming(request.stdout_write_ms)
941
+ },
942
+ ...boundedTiming(request.output_characters) === void 0 ? {} : {
943
+ output_characters: boundedTiming(request.output_characters)
944
+ },
945
+ ...boundedTiming(request.output_bytes) === void 0 ? {} : {
946
+ output_bytes: boundedTiming(request.output_bytes)
947
+ },
948
+ ack_processing_ms: Date.now() - ackStartedAtMs
949
+ }, accepted ? "info" : "warn");
950
+ return accepted ? { ok: true, type: "mailbox_events_ack" } : { ok: false, error: "mailbox_delivery_not_found" };
951
+ }
952
+ if (request.type === "mailbox_events_release") {
953
+ const releaseStartedAtMs = Date.now();
954
+ const token = typeof request.delivery_token === "string" ? request.delivery_token : "";
955
+ const trace = preparedEventsQueryTraces.get(token);
956
+ preparedEventsQueryTraces.delete(token);
957
+ const released = mailboxService.releaseEvents(token);
958
+ runtime.diagnostic("runtime.events_query.client_aborted", {
959
+ ...trace ? { query_seq: trace.querySeq } : {},
960
+ released,
961
+ outcome: typeof request.outcome === "string" ? request.outcome : "released",
962
+ ...trace ? {
963
+ prepared_to_release_ms: releaseStartedAtMs - trace.ownerPreparedAtMs,
964
+ owner_observed_total_ms: Date.now() - trace.ownerStartedAtMs
965
+ } : {},
966
+ ...boundedTiming(request.client_elapsed_ms) === void 0 ? {} : {
967
+ client_elapsed_before_release_ms: boundedTiming(request.client_elapsed_ms)
968
+ },
969
+ ...boundedTiming(request.prepare_rpc_ms) === void 0 ? {} : {
970
+ prepare_rpc_ms: boundedTiming(request.prepare_rpc_ms)
971
+ },
972
+ release_processing_ms: Date.now() - releaseStartedAtMs
973
+ }, "warn");
974
+ return released ? { ok: true, type: "mailbox_events_release" } : { ok: false, error: "mailbox_delivery_not_found" };
975
+ }
976
+ if (request.type === "snapshot") {
977
+ const ready = runtime.readReadyView(0, 1);
978
+ return {
979
+ ok: true,
980
+ type: "snapshot",
981
+ scope: ready.scope,
982
+ state: ready.state.state,
983
+ summary: ready.state.state,
984
+ state_status: ready.state.stateStatus,
985
+ ready: {
986
+ epoch_seq: ready.epochSeq,
987
+ frame_seq: ready.frameSeq,
988
+ event_commit_seq: ready.eventWatermark
989
+ }
990
+ };
991
+ }
992
+ if (request.type === "action") {
993
+ const capability = typeof request.capability === "string" ? request.capability : "";
994
+ const expected = request.expected_scope;
995
+ if (!capability || !expected || typeof expected.sessionId !== "string" || typeof expected.segmentId !== "string") return { ok: false, error: "invalid_action_request" };
996
+ const result = await performOwnerAgentAction(
997
+ runtime,
998
+ capability,
999
+ request.action,
1000
+ { sessionId: expected.sessionId, segmentId: expected.segmentId }
1001
+ );
1002
+ return { ok: true, type: "action", result };
1003
+ }
1004
+ if (request.type === "perception_status") {
1005
+ return { ok: true, type: request.type, status: [...Object.entries(BUILTIN_PERCEPTION_NAMES).map(([id, name]) => ({
1006
+ id: `${BUILTIN_PERCEPTION_PREFIX}${id}`,
1007
+ name,
1008
+ mandatory: true,
1009
+ configurable: false,
1010
+ outcome: runtime.readReadyView().pluginOutcomes[`${BUILTIN_PERCEPTION_PREFIX}${id}`]?.outcome
1011
+ })).filter((item) => !request.perception || item.id === request.perception), ...assembly.modules?.status(request.perception) ?? []] };
1012
+ }
1013
+ if (request.type === "perception_update") {
1014
+ const expected = ownerExpectedScope(request.expected_scope);
1015
+ if (!expected || !request.input || typeof request.input !== "object" || Array.isArray(request.input) || typeof request.perception !== "string") return { ok: false, type: request.type, error: "invalid_perception_control_request" };
1016
+ if (runtime.currentSegment().kind !== "game") return { ok: false, type: request.type, error: "no_active_game" };
1017
+ if (!ownerScopeIsCurrent(runtime, expected)) return { ok: false, type: request.type, error: "stale_runtime_scope" };
1018
+ try {
1019
+ if (request.perception.startsWith(BUILTIN_PERCEPTION_PREFIX)) throw Error("builtin_perception_readonly");
1020
+ if (!assembly.modules) throw Error("perception_not_found");
1021
+ const result = assembly.modules.configure(request.perception, request.input, () => ownerScopeIsCurrent(runtime, expected));
1022
+ return { ok: true, type: request.type, result };
1023
+ } catch (error) {
1024
+ return { ok: false, type: request.type, error: error instanceof Error ? error.message : "perception_control_failed" };
1025
+ }
1026
+ }
1027
+ if (request.type === "behavior_watch" || request.type === "behavior_unwatch" || request.type === "behavior_update") {
1028
+ if (runtime.currentSegment().kind !== "game") {
1029
+ return { ok: false, type: request.type, error: "no_active_game" };
1030
+ }
1031
+ const expected = ownerExpectedScope(request.expected_scope);
1032
+ const behavior = typeof request.behavior === "string" ? request.behavior.trim() : "";
1033
+ const activationId = typeof request.activation_id === "string" ? request.activation_id.trim() : "";
1034
+ const patch = request.type === "behavior_unwatch" ? {} : request.input;
1035
+ if (!expected || !patch || typeof patch !== "object" || Array.isArray(patch) || (request.type === "behavior_update" ? Boolean(behavior) === Boolean(activationId) : !behavior || !!activationId)) {
1036
+ return { ok: false, type: request.type, error: "invalid_behavior_control_request" };
1037
+ }
1038
+ if (!ownerScopeIsCurrent(runtime, expected)) return { ok: false, type: request.type, error: "stale_runtime_scope" };
1039
+ try {
1040
+ if (activationId) {
1041
+ const activation = await assembly.behavior.updateInput(
1042
+ activationId,
1043
+ patch,
1044
+ () => ownerScopeIsCurrent(runtime, expected)
1045
+ );
1046
+ return { ok: true, type: request.type, updated: true, activation };
1047
+ }
1048
+ const operation = request.type === "behavior_watch" ? "enable" : request.type === "behavior_unwatch" ? "disable" : "update";
1049
+ const result = await reflexControl.apply(operation, behavior, patch, expected);
1050
+ return { ok: true, type: request.type, result };
1051
+ } catch (error) {
1052
+ return { ok: false, type: request.type, error: error instanceof Error ? error.message : "behavior_control_failed" };
1053
+ }
1054
+ }
1055
+ if (request.type === "behavior_start") {
1056
+ const expected = ownerExpectedScope(request.expected_scope);
1057
+ const behavior = typeof request.behavior === "string" ? request.behavior.trim() : "";
1058
+ const layer = request.layer === "long" || request.layer === "short" ? request.layer : void 0;
1059
+ const behaviorInput = request.input;
1060
+ const maxRuntimeMs = request.max_runtime_ms;
1061
+ if (!expected || !behavior || !layer || !behaviorInput || typeof behaviorInput !== "object" || Array.isArray(behaviorInput) || maxRuntimeMs !== void 0 && (!Number.isSafeInteger(maxRuntimeMs) || maxRuntimeMs <= 0 || maxRuntimeMs > 12e4)) return { ok: false, type: "behavior_start", error: "invalid_behavior_start_request" };
1062
+ return deferredShort.start({
1063
+ expectedScope: expected,
1064
+ behavior,
1065
+ layer,
1066
+ input: behaviorInput,
1067
+ ...maxRuntimeMs === void 0 ? {} : { maxRuntimeMs }
1068
+ });
1069
+ }
1070
+ if (request.type === "behavior_status") {
1071
+ const id = typeof request.behavior === "string" ? request.behavior : void 0;
1072
+ const pending = deferredShort.status(id);
1073
+ return { ok: true, type: "behavior_status", status: {
1074
+ ...reflexControl.view(id),
1075
+ ...pending ? { pending_short: pending } : {}
1076
+ } };
1077
+ }
1078
+ if (request.type === "behavior_cancel") {
1079
+ const expected = ownerExpectedScope(request.expected_scope);
1080
+ if (!expected) return { ok: false, type: "behavior_cancel", error: "invalid_behavior_cancel_request" };
1081
+ if (!ownerScopeIsCurrent(runtime, expected)) {
1082
+ return { ok: false, type: "behavior_cancel", error: "stale_runtime_scope" };
1083
+ }
1084
+ const requestedId = typeof request.activation_id === "string" ? request.activation_id.trim() : assembly.behavior.status().current?.activationId ?? deferredShort.status()?.request_id;
1085
+ if (requestedId && deferredShort.cancel(requestedId)) {
1086
+ return { ok: true, type: "behavior_cancel", cancelled: true, request_id: requestedId };
1087
+ }
1088
+ if (!requestedId) {
1089
+ return { ok: true, type: "behavior_cancel", cancelled: false };
1090
+ }
1091
+ const stack = assembly.behavior.status().stack;
1092
+ const known = [stack.long, stack.short, stack.reflex].some((activation) => activation?.activationId === requestedId);
1093
+ if (!known) {
1094
+ return { ok: true, type: "behavior_cancel", cancelled: false, activation_id: requestedId };
1095
+ }
1096
+ await assembly.behavior.cancel(requestedId, "cancelled_by_agent");
1097
+ return { ok: true, type: "behavior_cancel", cancelled: true, activation_id: requestedId };
1098
+ }
1099
+ if (request.type === "behavior_fallback") {
1100
+ const expected = ownerExpectedScope(request.expected_scope);
1101
+ const role = typeof request.role === "string" ? request.role : "";
1102
+ if (!expected || !CLAWCLAW_ROLE_IDS.includes(role) || request.action !== "set" && request.action !== "clear") return { ok: false, type: "behavior_fallback", error: "invalid_behavior_fallback_request" };
1103
+ if (!ownerScopeIsCurrent(runtime, expected)) {
1104
+ return { ok: false, type: "behavior_fallback", error: "stale_runtime_scope" };
1105
+ }
1106
+ const latest = readGameplayConfig(workspaceDir, options.profile);
1107
+ const currentRole = readyRoleForScope(runtime, expected);
1108
+ if (currentRole === role) {
1109
+ await assembly.behavior.noteAgentActivity();
1110
+ }
1111
+ await assembly.behavior.configureFallbackBehaviors(roleFallbackBehaviors(
1112
+ latest,
1113
+ behaviorCatalog,
1114
+ configurationWarning
1115
+ ), currentRole);
1116
+ return {
1117
+ ok: true,
1118
+ type: "behavior_fallback",
1119
+ role,
1120
+ fallback: latest.fallback_behaviors[role]
1121
+ };
1122
+ }
1123
+ if (request.type === "behavior_idle") {
1124
+ const expected = ownerExpectedScope(request.expected_scope);
1125
+ if (!expected || !Number.isSafeInteger(request.idle_ms) || request.idle_ms < 0 || request.idle_ms > 6e4) return { ok: false, type: "behavior_idle", error: "invalid_behavior_idle_request" };
1126
+ if (!ownerScopeIsCurrent(runtime, expected)) {
1127
+ return { ok: false, type: "behavior_idle", error: "stale_runtime_scope" };
1128
+ }
1129
+ const latest = readGameplayConfig(workspaceDir, options.profile);
1130
+ await assembly.behavior.setIdleMs(latest.idle_ms);
1131
+ return { ok: true, type: "behavior_idle", idle_ms: latest.idle_ms };
1132
+ }
1133
+ if (request.type === "trigger_configure") {
1134
+ const expected = ownerExpectedScope(request.expected_scope);
1135
+ if (!expected || typeof request.trigger !== "string" || !request.trigger.trim()) {
1136
+ return { ok: false, type: "trigger_configure", error: "invalid_trigger_configure_request" };
1137
+ }
1138
+ if (!ownerScopeIsCurrent(runtime, expected)) {
1139
+ return { ok: false, type: "trigger_configure", error: "stale_runtime_scope" };
1140
+ }
1141
+ const latest = readGameplayConfig(workspaceDir, options.profile);
1142
+ const currentTriggerSources = listClawclawTriggerSources(
1143
+ getUserDataAccountTriggersDir(workspaceDir, options.profile)
1144
+ );
1145
+ if (!currentTriggerSources.some((source2) => source2.id === request.trigger)) {
1146
+ return { ok: false, type: "trigger_configure", error: "trigger_source_unavailable" };
1147
+ }
1148
+ assembly.trigger.configure(triggerRegistrations(
1149
+ currentTriggerSources,
1150
+ latest,
1151
+ behaviorCatalog,
1152
+ configurationWarning
1153
+ ));
1154
+ return {
1155
+ ok: true,
1156
+ type: "trigger_configure",
1157
+ trigger: request.trigger,
1158
+ config: latest.triggers[request.trigger] ?? null
1159
+ };
1160
+ }
1161
+ if (request.type === "quit" || request.type === "leave") {
1162
+ await ownerSource.submitIntent({ kind: "leave" });
1163
+ return { ok: true, type: request.type };
1164
+ }
1165
+ if (request.type === "training_mode") {
1166
+ if (!isTrainingRoomMode(request.room_type)) {
1167
+ return { ok: false, type: request.type, error: "invalid_training_room_type" };
1168
+ }
1169
+ const result = await ownerSource.submitIntent({
1170
+ kind: "training_mode",
1171
+ roomType: request.room_type
1172
+ });
1173
+ return { ok: true, type: request.type, result };
1174
+ }
1175
+ if (request.type === "training_role_lock") {
1176
+ if (!isTrainingRole(request.role)) {
1177
+ return { ok: false, type: request.type, error: "invalid_training_role", roles: [...CLAWCLAW_ROLE_IDS] };
1178
+ }
1179
+ const result = await ownerSource.submitIntent({
1180
+ kind: "training_role_lock",
1181
+ role: request.role
1182
+ });
1183
+ return { ok: true, type: request.type, role: request.role, result };
1184
+ }
1185
+ if (request.type === "training_role_clear") {
1186
+ const result = await ownerSource.submitIntent({ kind: "training_role_clear" });
1187
+ return { ok: true, type: request.type, role: null, result };
1188
+ }
1189
+ return { ok: false, error: "owner_request_not_supported" };
1190
+ });
1191
+ if (localStopRequested) return { reason: "stopped" };
1192
+ startupMark("owner.source_start");
1193
+ const startingRuntime = runtime;
1194
+ await timeStartup("owner.runtime_start", () => startingRuntime.start());
1195
+ await timeStartup("owner.source_attach", () => startingRuntime.startSourcePlugin(ownerSource));
1196
+ await desktopEventPump?.flush();
1197
+ await channelEventPump?.flush();
1198
+ if (localStopRequested) await ownerSource.submitIntent({ kind: "stop" });
1199
+ if (!localStopRequested) lock.setPhase("ready");
1200
+ options.notificationHost?.markMailboxReady();
1201
+ const completion = await source.waitForCompletion();
1202
+ await runtime.flush();
1203
+ await mailboxService.flush();
1204
+ await cclEventsMailbox.flush();
1205
+ await desktopMailbox?.flush();
1206
+ await desktopEventPump?.drain();
1207
+ if (channelOwnerDeliveryPolicy(options.channelDelivery, localStopRequested).drainOnNaturalCompletion) {
1208
+ await channelAdapter.flush();
1209
+ await channelEventPump.drain();
1210
+ runtime.diagnostic("runtime.channel.shutdown_drained", {
1211
+ bounded_by: "current_delivery_attempt"
1212
+ });
1213
+ }
1214
+ if (mailboxBroker && !await waitForMailboxDrain(mailboxBroker)) {
1215
+ runtime.diagnostic("runtime.shutdown.mailbox_drain_incomplete", {
1216
+ timeout_ms: MAILBOX_DRAIN_TIMEOUT_MS
1217
+ }, "warn");
1218
+ }
1219
+ return completion;
1220
+ } finally {
1221
+ if (diagnosticSampleTimer) clearInterval(diagnosticSampleTimer);
1222
+ processTimingSampler?.stop();
1223
+ process.off("SIGINT", onSignal);
1224
+ process.off("SIGTERM", onSignal);
1225
+ if (forceExitTimer) clearTimeout(forceExitTimer);
1226
+ parentWatch?.stop();
1227
+ relayAlive = false;
1228
+ relayAbort?.abort(new Error("owner_stopping"));
1229
+ await relayPromise;
1230
+ try {
1231
+ try {
1232
+ await ownerControl?.close();
1233
+ } finally {
1234
+ runtimePointer?.release();
1235
+ await runtime?.close();
1236
+ }
1237
+ } finally {
1238
+ try {
1239
+ await closeGameSyncTransports?.();
1240
+ await telemetry?.closeWithin(2e3).catch(() => false);
1241
+ } finally {
1242
+ lock?.release();
1243
+ }
1244
+ }
1245
+ }
1246
+ }
1247
+ export {
1248
+ acquireOwnerLock2 as acquireOwnerLock,
1249
+ channelOwnerDeliveryPolicy,
1250
+ deriveClawclawOwnerRuntimeStart,
1251
+ ownerAgentEventPresenter,
1252
+ performOwnerAgentAction,
1253
+ publishOwnerRuntimePointer,
1254
+ roleFallbackBehaviors,
1255
+ runClawclawOwner,
1256
+ triggerRegistrations
1257
+ };