@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,684 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { DetailCapture } from "../../../observability/detail-capture.js";
3
+ import { performance } from "node:perf_hooks";
4
+ import { Worker } from "node:worker_threads";
5
+ const WORKER_BOOTSTRAP_URL = new URL(
6
+ "../../../framework/modules/runtime-module-worker-bootstrap.mjs",
7
+ import.meta.url
8
+ );
9
+ const WORKER_HOST_URL = new URL("./perception-analysis-thread-worker.ts", import.meta.url).href;
10
+ const DEFAULT_WORKERS = 10;
11
+ const DEFAULT_WARM_WORKERS = 2;
12
+ const MAX_WORKERS = 10;
13
+ const START_TIMEOUT_MS = 2e4;
14
+ const REPLACEMENT_RETRY_BASE_MS = 50;
15
+ const REPLACEMENT_RETRY_MAX_MS = 2e3;
16
+ const PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS = 3e4;
17
+ function perceptionAnalysisWorkerStartModuleId(error) {
18
+ if (!error || typeof error !== "object") return void 0;
19
+ const moduleId = error.moduleId;
20
+ return typeof moduleId === "string" && moduleId ? moduleId : void 0;
21
+ }
22
+ function roundedElapsed(startedAt) {
23
+ return Math.round(Math.max(0, performance.now() - startedAt) * 1e3) / 1e3;
24
+ }
25
+ function asError(value, fallback) {
26
+ return value instanceof Error ? value : new Error(typeof value === "string" ? value : fallback);
27
+ }
28
+ function abortError(signal) {
29
+ return asError(signal.reason, "perception_analysis_aborted");
30
+ }
31
+ function moduleFailure(error) {
32
+ const message = error instanceof Error ? error.message : String(error);
33
+ const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1];
34
+ return {
35
+ errorCode: prefix ?? "PERCEPTION_MODULE_FAILED",
36
+ messagePresent: message.length > 0,
37
+ ...message ? { messageLength: message.length } : {}
38
+ };
39
+ }
40
+ class PerceptionAnalysisThreadPool {
41
+ constructor(options) {
42
+ this.options = options;
43
+ const maxWorkers = options.maxWorkers ?? DEFAULT_WORKERS;
44
+ if (!Number.isInteger(maxWorkers) || maxWorkers <= 0 || maxWorkers > MAX_WORKERS) {
45
+ throw new TypeError(`maxWorkers must be between 1 and ${MAX_WORKERS}.`);
46
+ }
47
+ this.maxWorkers = maxWorkers;
48
+ this.maxPendingBatches = options.maxPendingBatches ?? maxWorkers;
49
+ if (!Number.isInteger(this.maxPendingBatches) || this.maxPendingBatches < 1 || this.maxPendingBatches > MAX_WORKERS) {
50
+ throw new Error("perception_pending_batch_limit_invalid");
51
+ }
52
+ this.minWorkers = options.fixedWorkers ? maxWorkers : Math.min(DEFAULT_WARM_WORKERS, maxWorkers);
53
+ this.maxOldGenerationSizeMb = Math.max(16, Math.min(
54
+ 256,
55
+ Math.floor(options.maxOldGenerationSizeMb ?? 64)
56
+ ));
57
+ const ids = options.modules.map(({ moduleId }) => moduleId);
58
+ if (new Set(ids).size !== ids.length) throw new Error("perception_thread_module_duplicate");
59
+ }
60
+ options;
61
+ poolId = randomUUID();
62
+ minWorkers;
63
+ maxWorkers;
64
+ maxPendingBatches;
65
+ maxOldGenerationSizeMb;
66
+ state = "new";
67
+ slots = /* @__PURE__ */ new Set();
68
+ queue = [];
69
+ inFlight = /* @__PURE__ */ new Set();
70
+ spawnTasks = /* @__PURE__ */ new Set();
71
+ startTask;
72
+ stopTask;
73
+ replacementTask;
74
+ replacementDelay;
75
+ idleShrinkTimer;
76
+ replacementFailureCount = 0;
77
+ nextSlotId = 1;
78
+ startedWorkerCount = 0;
79
+ retiredWorkerCount = 0;
80
+ peakWorkerHeapUsedBytes = 0;
81
+ start() {
82
+ if (this.state === "running") return Promise.resolve();
83
+ if (this.state === "starting") return this.startTask;
84
+ if (this.state === "stopping" || this.state === "stopped") {
85
+ return Promise.reject(new Error("perception_analysis_pool_stopped"));
86
+ }
87
+ this.state = "starting";
88
+ const startedAt = performance.now();
89
+ this.startTask = this.startInternal().then(() => {
90
+ if (this.state !== "starting") throw new Error("perception_analysis_pool_stopped");
91
+ this.state = "running";
92
+ this.emitDiagnostic("perception.analysis_pool.started", {
93
+ worker_count: this.slots.size,
94
+ min_worker_count: this.minWorkers,
95
+ max_worker_count: this.maxWorkers,
96
+ started_worker_count: this.startedWorkerCount,
97
+ retired_worker_count: this.retiredWorkerCount,
98
+ module_count: this.options.modules.length,
99
+ duration_ms: roundedElapsed(startedAt),
100
+ worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
101
+ startup_worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
102
+ peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes
103
+ }, "info");
104
+ }).catch(async (error) => {
105
+ if (this.state === "starting") this.state = "stopped";
106
+ await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, "start_failed")));
107
+ throw error;
108
+ });
109
+ return this.startTask;
110
+ }
111
+ async analyze(jobs, signal) {
112
+ const capture = this.detailCapture ??= new DetailCapture(
113
+ "perception_io",
114
+ (name, attributes, severity) => this.emitDiagnostic(name, attributes, severity)
115
+ );
116
+ if (!capture.enabled) return this.analyzeInternal(jobs, signal);
117
+ const requestId = randomUUID();
118
+ for (const job of jobs) capture.emit("input", () => ({
119
+ invocation_id: `${requestId}:${job.moduleId}`,
120
+ module_id: job.moduleId,
121
+ operation: "analyze",
122
+ tick: job.input.frame.tick,
123
+ frame_seq: job.input.frame.frameSeq,
124
+ game_id: job.input.frame.gameState.game_id,
125
+ input: job.input,
126
+ stage: "requested"
127
+ }));
128
+ try {
129
+ return await this.analyzeInternal(jobs, signal, requestId);
130
+ } catch (error) {
131
+ for (const job of jobs) capture.emit(signal.aborted ? "cancelled" : "failed", () => ({
132
+ invocation_id: `${requestId}:${job.moduleId}`,
133
+ module_id: job.moduleId,
134
+ operation: "analyze",
135
+ cancelled: signal.aborted,
136
+ tick: job.input.frame.tick,
137
+ frame_seq: job.input.frame.frameSeq,
138
+ stage: "batch_discarded",
139
+ error: error instanceof Error ? error.message : String(error)
140
+ }));
141
+ throw error;
142
+ }
143
+ }
144
+ detailCapture;
145
+ async analyzeInternal(jobs, signal, captureRequestId) {
146
+ signal.throwIfAborted();
147
+ await this.start();
148
+ signal.throwIfAborted();
149
+ if (this.state !== "running") throw new Error("perception_analysis_pool_not_running");
150
+ if (jobs.length === 0) {
151
+ return {
152
+ results: [],
153
+ queueDurationMs: 0,
154
+ durationMs: 0,
155
+ workerCount: this.slots.size,
156
+ workerHeapUsedBytes: 0,
157
+ workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes()
158
+ };
159
+ }
160
+ if (this.inFlight.size >= this.maxPendingBatches) {
161
+ throw new Error("perception_analysis_window_full");
162
+ }
163
+ const configured = new Set(this.options.modules.map(({ moduleId }) => moduleId));
164
+ const ids = jobs.map(({ moduleId }) => moduleId);
165
+ if (new Set(ids).size !== ids.length || ids.some((id) => !configured.has(id))) {
166
+ throw new Error("perception_analysis_jobs_invalid");
167
+ }
168
+ return new Promise((resolve, reject) => {
169
+ const pending = {
170
+ captureRequestId,
171
+ requestId: randomUUID(),
172
+ jobs,
173
+ signal,
174
+ enqueuedAt: performance.now(),
175
+ resolve,
176
+ reject,
177
+ results: new Array(jobs.length),
178
+ remaining: jobs.length,
179
+ peakWorkerHeapUsedBytes: 0,
180
+ settled: false,
181
+ onAbort: () => this.abortBatch(pending)
182
+ };
183
+ signal.addEventListener("abort", pending.onAbort, { once: true });
184
+ this.inFlight.add(pending);
185
+ this.queue.push(...jobs.map((job, index) => ({
186
+ requestId: `${pending.requestId}:${index}`,
187
+ batch: pending,
188
+ index,
189
+ job
190
+ })));
191
+ this.pump();
192
+ });
193
+ }
194
+ stop() {
195
+ if (this.state === "stopped") return Promise.resolve();
196
+ if (this.state === "stopping") return this.stopTask ?? Promise.resolve();
197
+ if (this.state === "new") {
198
+ this.state = "stopped";
199
+ return Promise.resolve();
200
+ }
201
+ this.state = "stopping";
202
+ const task = this.stopInternal().finally(() => {
203
+ this.state = "stopped";
204
+ if (this.stopTask === task) this.stopTask = void 0;
205
+ });
206
+ this.stopTask = task;
207
+ return task;
208
+ }
209
+ async stopInternal() {
210
+ this.cancelReplacementDelay();
211
+ this.cancelIdleShrink();
212
+ const error = new Error("perception_analysis_pool_stopped");
213
+ for (const batch of [...this.inFlight]) this.rejectBatch(batch, error);
214
+ await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, "shutdown")));
215
+ await Promise.allSettled([...this.spawnTasks]);
216
+ await this.startTask?.catch(() => {
217
+ });
218
+ await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, "shutdown")));
219
+ this.emitDiagnostic("perception.analysis_pool.stopped", {
220
+ worker_count: this.slots.size,
221
+ min_worker_count: this.minWorkers,
222
+ max_worker_count: this.maxWorkers,
223
+ started_worker_count: this.startedWorkerCount,
224
+ retired_worker_count: this.retiredWorkerCount,
225
+ worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
226
+ peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes
227
+ }, "info");
228
+ }
229
+ snapshot() {
230
+ const values = [...this.slots];
231
+ return {
232
+ state: this.state,
233
+ minWorkers: this.minWorkers,
234
+ maxWorkers: this.maxWorkers,
235
+ workerCount: values.length,
236
+ idleWorkerCount: values.filter(({ state }) => state === "idle").length,
237
+ busyWorkerCount: values.filter(({ state }) => state === "busy").length,
238
+ queuedBatchCount: new Set(this.queue.map(({ batch }) => batch.requestId)).size,
239
+ queuedJobCount: this.queue.length,
240
+ inFlightBatchCount: this.inFlight.size,
241
+ startedWorkerCount: this.startedWorkerCount,
242
+ retiredWorkerCount: this.retiredWorkerCount,
243
+ startupWorkerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
244
+ workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
245
+ peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes
246
+ };
247
+ }
248
+ async startInternal() {
249
+ await Promise.all(Array.from(
250
+ { length: this.minWorkers },
251
+ () => this.spawnSlot("prewarm")
252
+ ));
253
+ }
254
+ async spawnSlot(trigger) {
255
+ const worker = new Worker(WORKER_BOOTSTRAP_URL, {
256
+ execArgv: [],
257
+ resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb },
258
+ stderr: true,
259
+ stdout: true,
260
+ workerData: {
261
+ runtimeModuleBootstrap: {
262
+ hostUrl: WORKER_HOST_URL,
263
+ hooksUrl: this.options.loader.hooksUrl,
264
+ sdkAliases: this.options.loader.sdkAliases,
265
+ esmModuleRoots: [...new Set(this.options.modules.map((module) => new URL(".", module.sourceUrl).href))]
266
+ },
267
+ poolId: this.poolId,
268
+ spatialFacts: this.options.spatialFacts,
269
+ modules: this.options.modules,
270
+ diagnosticsEnabled: this.options.diagnosticsEnabled === true
271
+ }
272
+ });
273
+ const slot = { id: this.nextSlotId++, worker, state: "starting" };
274
+ this.slots.add(slot);
275
+ worker.stdout?.on("data", (chunk) => this.emitDiagnostic(
276
+ "perception.analysis_worker.stdout",
277
+ { bytes: chunk.length, slot_id: slot.id }
278
+ ));
279
+ worker.stderr?.on("data", (chunk) => this.emitDiagnostic(
280
+ "perception.analysis_worker.stderr",
281
+ { bytes: chunk.length, slot_id: slot.id }
282
+ ));
283
+ worker.on("message", (message) => this.handleMessage(slot, message));
284
+ worker.once("error", (error) => this.failSlot(slot, error));
285
+ worker.once("exit", (code) => {
286
+ if (slot.state !== "retiring") {
287
+ this.failSlot(slot, new Error(`perception_analysis_worker_exited:${code}`));
288
+ }
289
+ });
290
+ let timer;
291
+ try {
292
+ await new Promise((resolve, reject) => {
293
+ slot.readyResolve = resolve;
294
+ slot.readyReject = reject;
295
+ timer = setTimeout(() => reject(new Error("perception_analysis_worker_start_timeout")), START_TIMEOUT_MS);
296
+ timer.unref?.();
297
+ });
298
+ if (this.state !== "starting" && this.state !== "running") {
299
+ throw new Error("perception_analysis_pool_stopped");
300
+ }
301
+ slot.state = "idle";
302
+ slot.idleSince = performance.now();
303
+ this.startedWorkerCount += 1;
304
+ this.peakWorkerHeapUsedBytes = Math.max(
305
+ this.peakWorkerHeapUsedBytes,
306
+ this.currentWorkerHeapUsedBytes()
307
+ );
308
+ this.emitDiagnostic("perception.analysis_worker.started", {
309
+ slot_id: slot.id,
310
+ worker_count: this.readyWorkerCount(),
311
+ min_worker_count: this.minWorkers,
312
+ max_worker_count: this.maxWorkers,
313
+ trigger,
314
+ worker_heap_used_bytes: slot.readyHeapUsedBytes ?? 0
315
+ }, "info");
316
+ } catch (error) {
317
+ await this.retireSlot(slot, "start_failed");
318
+ throw error;
319
+ } finally {
320
+ if (timer) clearTimeout(timer);
321
+ slot.readyResolve = void 0;
322
+ slot.readyReject = void 0;
323
+ }
324
+ }
325
+ pump() {
326
+ if (this.state !== "running") return;
327
+ while (this.queue.length > 0) {
328
+ const slot = [...this.slots].find((candidate) => candidate.state === "idle");
329
+ if (!slot) break;
330
+ const moduleJob = this.queue.shift();
331
+ const { batch } = moduleJob;
332
+ if (batch.settled || batch.signal.aborted) {
333
+ if (!batch.settled) this.rejectBatch(batch, abortError(batch.signal));
334
+ continue;
335
+ }
336
+ slot.state = "busy";
337
+ slot.idleSince = void 0;
338
+ slot.current = moduleJob;
339
+ moduleJob.slot = slot;
340
+ moduleJob.assignedAt = performance.now();
341
+ batch.firstAssignedAt ??= moduleJob.assignedAt;
342
+ try {
343
+ slot.worker.postMessage({
344
+ type: "analyze",
345
+ poolId: this.poolId,
346
+ requestId: moduleJob.requestId,
347
+ jobs: [moduleJob.job]
348
+ });
349
+ } catch (error) {
350
+ this.failModuleJob(moduleJob, asError(error, "perception_analysis_submit_failed"));
351
+ slot.current = void 0;
352
+ void this.retireSlot(slot, "submit_failed");
353
+ }
354
+ }
355
+ this.rebalanceCapacity();
356
+ }
357
+ handleMessage(slot, value) {
358
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
359
+ this.failSlot(slot, new Error("perception_analysis_protocol_invalid"));
360
+ return;
361
+ }
362
+ const message = value;
363
+ if (message.poolId !== this.poolId) {
364
+ this.failSlot(slot, new Error("perception_analysis_pool_mismatch"));
365
+ return;
366
+ }
367
+ if (message.type === "ready") {
368
+ if (slot.state !== "starting") {
369
+ this.failSlot(slot, new Error("perception_analysis_ready_unexpected"));
370
+ return;
371
+ }
372
+ if (this.options.diagnosticsEnabled === true && (!Number.isFinite(message.heapUsedBytes) || Number(message.heapUsedBytes) < 0)) {
373
+ this.failSlot(slot, new Error("perception_analysis_worker_memory_invalid"));
374
+ return;
375
+ }
376
+ if (typeof message.heapUsedBytes === "number") {
377
+ slot.readyHeapUsedBytes = message.heapUsedBytes;
378
+ }
379
+ slot.readyResolve?.();
380
+ return;
381
+ }
382
+ if (message.type === "error") {
383
+ if (typeof message.heapUsedBytes === "number" && Number.isFinite(message.heapUsedBytes)) {
384
+ slot.readyHeapUsedBytes = Math.max(0, message.heapUsedBytes);
385
+ this.peakWorkerHeapUsedBytes = Math.max(
386
+ this.peakWorkerHeapUsedBytes,
387
+ this.currentWorkerHeapUsedBytes()
388
+ );
389
+ }
390
+ const error = new Error(typeof message.code === "string" ? message.code : "perception_analysis_worker_failed");
391
+ const moduleId = typeof message.moduleId === "string" && this.options.modules.some((module) => module.moduleId === message.moduleId) ? message.moduleId : void 0;
392
+ if (slot.state === "starting") {
393
+ if (moduleId) Object.defineProperty(error, "moduleId", { value: moduleId, enumerable: true });
394
+ this.failSlot(slot, error);
395
+ return;
396
+ }
397
+ if (slot.current && (!message.requestId || message.requestId === slot.current.requestId)) {
398
+ const moduleJob2 = slot.current;
399
+ slot.current = void 0;
400
+ this.failModuleJob(moduleJob2, error);
401
+ }
402
+ void this.retireSlot(slot, "worker_error");
403
+ return;
404
+ }
405
+ if (message.type !== "analysis" || !Array.isArray(message.results)) {
406
+ this.failSlot(slot, new Error("perception_analysis_protocol_invalid"));
407
+ return;
408
+ }
409
+ if (this.options.diagnosticsEnabled === true && (!Number.isFinite(message.heapUsedBytes) || Number(message.heapUsedBytes) < 0)) {
410
+ this.failSlot(slot, new Error("perception_analysis_worker_memory_invalid"));
411
+ return;
412
+ }
413
+ const moduleJob = slot.current;
414
+ if (!moduleJob || message.requestId !== moduleJob.requestId) {
415
+ this.failSlot(slot, new Error("perception_analysis_request_mismatch"));
416
+ return;
417
+ }
418
+ const { batch } = moduleJob;
419
+ const result = message.results[0];
420
+ if (message.results.length !== 1 || result?.moduleId !== moduleJob.job.moduleId) {
421
+ slot.current = void 0;
422
+ this.failModuleJob(moduleJob, new Error("perception_analysis_results_invalid"));
423
+ void this.retireSlot(slot, "invalid_results");
424
+ return;
425
+ }
426
+ slot.current = void 0;
427
+ slot.state = "idle";
428
+ slot.idleSince = performance.now();
429
+ if (typeof message.heapUsedBytes === "number") slot.readyHeapUsedBytes = message.heapUsedBytes;
430
+ this.peakWorkerHeapUsedBytes = Math.max(
431
+ this.peakWorkerHeapUsedBytes,
432
+ this.currentWorkerHeapUsedBytes()
433
+ );
434
+ moduleJob.slot = void 0;
435
+ this.captureModuleResult(moduleJob, result);
436
+ if (!batch.settled) {
437
+ batch.results[moduleJob.index] = result;
438
+ batch.remaining -= 1;
439
+ batch.peakWorkerHeapUsedBytes = Math.max(
440
+ batch.peakWorkerHeapUsedBytes,
441
+ message.heapUsedBytes ?? 0
442
+ );
443
+ if (batch.remaining === 0) this.resolveBatch(batch);
444
+ }
445
+ this.pump();
446
+ }
447
+ abortBatch(batch) {
448
+ if (batch.settled) return;
449
+ const slots = [...this.slots].filter(({ current }) => current?.batch === batch);
450
+ this.rejectBatch(batch, abortError(batch.signal));
451
+ for (const slot of slots) void this.retireSlot(slot, "analysis_aborted");
452
+ this.pump();
453
+ }
454
+ resolveBatch(batch) {
455
+ if (batch.settled) return;
456
+ batch.settled = true;
457
+ batch.signal.removeEventListener("abort", batch.onAbort);
458
+ this.inFlight.delete(batch);
459
+ const results = batch.results.filter((result) => !!result);
460
+ if (results.length !== batch.jobs.length) {
461
+ batch.reject(new Error("perception_analysis_results_incomplete"));
462
+ return;
463
+ }
464
+ batch.resolve({
465
+ results,
466
+ queueDurationMs: Math.round(Math.max(
467
+ 0,
468
+ (batch.firstAssignedAt ?? performance.now()) - batch.enqueuedAt
469
+ ) * 1e3) / 1e3,
470
+ durationMs: roundedElapsed(batch.enqueuedAt),
471
+ workerCount: this.slots.size,
472
+ workerHeapUsedBytes: batch.peakWorkerHeapUsedBytes,
473
+ workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes()
474
+ });
475
+ }
476
+ rejectBatch(batch, error) {
477
+ if (batch.settled) return;
478
+ batch.settled = true;
479
+ batch.signal.removeEventListener("abort", batch.onAbort);
480
+ this.inFlight.delete(batch);
481
+ for (let index = this.queue.length - 1; index >= 0; index -= 1) {
482
+ if (this.queue[index].batch === batch) this.queue.splice(index, 1);
483
+ }
484
+ batch.reject(error);
485
+ }
486
+ failModuleJob(moduleJob, error) {
487
+ const { batch } = moduleJob;
488
+ moduleJob.slot = void 0;
489
+ if (batch.settled || batch.results[moduleJob.index]) return;
490
+ batch.results[moduleJob.index] = {
491
+ moduleId: moduleJob.job.moduleId,
492
+ durationMs: roundedElapsed(moduleJob.assignedAt ?? batch.enqueuedAt),
493
+ outcome: "rejected",
494
+ failure: moduleFailure(error)
495
+ };
496
+ this.captureModuleResult(moduleJob, batch.results[moduleJob.index]);
497
+ batch.remaining -= 1;
498
+ if (batch.remaining === 0) this.resolveBatch(batch);
499
+ }
500
+ captureModuleResult(job, result) {
501
+ if (!job.batch.captureRequestId) return;
502
+ this.detailCapture?.emit("output", () => ({
503
+ invocation_id: `${job.batch.captureRequestId}:${job.job.moduleId}`,
504
+ worker_request_id: job.requestId,
505
+ module_id: job.job.moduleId,
506
+ operation: "analyze",
507
+ tick: job.job.input.frame.tick,
508
+ frame_seq: job.job.input.frame.frameSeq,
509
+ game_id: job.job.input.frame.gameState.game_id,
510
+ outcome: result.outcome,
511
+ stage: job.batch.settled ? "late_result" : "analysis_only_not_committed",
512
+ output: result
513
+ }));
514
+ }
515
+ failSlot(slot, error) {
516
+ slot.readyReject?.(error);
517
+ if (slot.current) {
518
+ const moduleJob = slot.current;
519
+ slot.current = void 0;
520
+ this.failModuleJob(moduleJob, error);
521
+ }
522
+ void this.retireSlot(slot, "failed");
523
+ }
524
+ retireSlot(slot, reason) {
525
+ if (slot.retirement) return slot.retirement;
526
+ slot.state = "retiring";
527
+ if (slot.current) {
528
+ const moduleJob = slot.current;
529
+ slot.current = void 0;
530
+ this.failModuleJob(moduleJob, new Error(`perception_analysis_worker_retired:${reason}`));
531
+ }
532
+ const retirement = Promise.resolve().then(() => slot.worker.terminate()).catch(() => -1).then(() => {
533
+ this.slots.delete(slot);
534
+ this.retiredWorkerCount += 1;
535
+ this.emitDiagnostic("perception.analysis_worker.retired", {
536
+ slot_id: slot.id,
537
+ reason,
538
+ worker_count: this.slots.size,
539
+ min_worker_count: this.minWorkers,
540
+ max_worker_count: this.maxWorkers
541
+ }, reason === "idle" ? "info" : "debug");
542
+ if (this.state === "running") {
543
+ this.pump();
544
+ }
545
+ });
546
+ slot.retirement = retirement;
547
+ slot.readyReject?.(new Error(`perception_analysis_worker_retired:${reason}`));
548
+ if (this.state === "running") this.pump();
549
+ return retirement;
550
+ }
551
+ scheduleReplacement() {
552
+ if (this.state !== "running" || this.activeWorkerCount() >= this.desiredWorkerCount()) return;
553
+ if (this.replacementTask) return;
554
+ const delayMs = this.replacementRetryDelayMs();
555
+ let trigger = this.activeWorkerCount() < this.minWorkers ? "replacement" : "pressure";
556
+ let task;
557
+ task = this.waitForReplacementDelay(delayMs).then(async () => {
558
+ if (this.state !== "running" || this.activeWorkerCount() >= this.desiredWorkerCount()) return;
559
+ trigger = this.activeWorkerCount() < this.minWorkers ? "replacement" : "pressure";
560
+ await this.spawnSlot(trigger);
561
+ this.replacementFailureCount = 0;
562
+ this.pump();
563
+ }).catch((error) => {
564
+ if (this.state !== "running") return;
565
+ this.replacementFailureCount += 1;
566
+ this.emitDiagnostic("perception.analysis_worker.replacement_failed", {
567
+ error_code: error instanceof Error ? error.message.split(":", 1)[0] : "perception_analysis_worker_start_failed",
568
+ consecutive_failures: this.replacementFailureCount,
569
+ retry_delay_ms: this.replacementRetryDelayMs(),
570
+ worker_count: this.activeWorkerCount(),
571
+ queued_batch_count: new Set(this.queue.map(({ batch }) => batch.requestId)).size,
572
+ queued_job_count: this.queue.length,
573
+ trigger
574
+ }, "error");
575
+ }).finally(() => {
576
+ this.spawnTasks.delete(task);
577
+ if (this.replacementTask === task) this.replacementTask = void 0;
578
+ this.pump();
579
+ });
580
+ this.replacementTask = task;
581
+ this.spawnTasks.add(task);
582
+ }
583
+ replacementRetryDelayMs() {
584
+ if (this.replacementFailureCount <= 0) return 0;
585
+ const exponent = Math.min(8, this.replacementFailureCount - 1);
586
+ return Math.min(REPLACEMENT_RETRY_MAX_MS, REPLACEMENT_RETRY_BASE_MS * 2 ** exponent);
587
+ }
588
+ waitForReplacementDelay(delayMs) {
589
+ if (delayMs <= 0) return Promise.resolve();
590
+ return new Promise((resolve) => {
591
+ let settled = false;
592
+ let timer;
593
+ const finish = () => {
594
+ if (settled) return;
595
+ settled = true;
596
+ clearTimeout(timer);
597
+ if (this.replacementDelay?.timer === timer) this.replacementDelay = void 0;
598
+ resolve();
599
+ };
600
+ timer = setTimeout(finish, delayMs);
601
+ this.replacementDelay = { timer, resolve: finish };
602
+ });
603
+ }
604
+ cancelReplacementDelay() {
605
+ const delay = this.replacementDelay;
606
+ this.replacementDelay = void 0;
607
+ delay?.resolve();
608
+ }
609
+ desiredWorkerCount() {
610
+ const busyWorkerCount = [...this.slots].filter(({ state }) => state === "busy").length;
611
+ return Math.max(
612
+ this.minWorkers,
613
+ Math.min(this.maxWorkers, this.queue.length + busyWorkerCount)
614
+ );
615
+ }
616
+ rebalanceCapacity() {
617
+ if (this.state !== "running") return;
618
+ if (this.queue.length > 0 || this.activeWorkerCount() < this.minWorkers) {
619
+ this.scheduleReplacement();
620
+ }
621
+ this.scheduleIdleShrink();
622
+ }
623
+ scheduleIdleShrink() {
624
+ if (this.state !== "running" || this.idleShrinkTimer) return;
625
+ const delayMs = this.nextIdleShrinkDelayMs();
626
+ if (delayMs === void 0) return;
627
+ const timer = setTimeout(() => {
628
+ if (this.idleShrinkTimer === timer) this.idleShrinkTimer = void 0;
629
+ this.shrinkIdleWorkers();
630
+ this.scheduleIdleShrink();
631
+ }, delayMs);
632
+ timer.unref?.();
633
+ this.idleShrinkTimer = timer;
634
+ }
635
+ nextIdleShrinkDelayMs() {
636
+ const excess = this.activeWorkerCount() - this.desiredWorkerCount();
637
+ if (excess <= 0) return void 0;
638
+ const oldestIdleSince = [...this.slots].reduce((oldest, slot) => {
639
+ if (slot.state !== "idle" || slot.idleSince === void 0) return oldest;
640
+ return oldest === void 0 ? slot.idleSince : Math.min(oldest, slot.idleSince);
641
+ }, void 0);
642
+ if (oldestIdleSince === void 0) return void 0;
643
+ return Math.max(
644
+ 0,
645
+ Math.ceil(oldestIdleSince + PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS - performance.now())
646
+ );
647
+ }
648
+ cancelIdleShrink() {
649
+ if (!this.idleShrinkTimer) return;
650
+ clearTimeout(this.idleShrinkTimer);
651
+ this.idleShrinkTimer = void 0;
652
+ }
653
+ shrinkIdleWorkers() {
654
+ if (this.state !== "running") return;
655
+ const excess = this.activeWorkerCount() - this.desiredWorkerCount();
656
+ if (excess <= 0) return;
657
+ const cutoff = performance.now() - PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS;
658
+ const idle = [...this.slots].filter((slot) => slot.state === "idle" && slot.idleSince !== void 0 && slot.idleSince <= cutoff).sort((left, right) => left.idleSince - right.idleSince).slice(0, excess);
659
+ for (const slot of idle) void this.retireSlot(slot, "idle");
660
+ }
661
+ activeWorkerCount() {
662
+ return [...this.slots].filter(({ state }) => state !== "retiring").length;
663
+ }
664
+ currentWorkerHeapUsedBytes() {
665
+ return [...this.slots].reduce(
666
+ (sum, slot) => sum + (slot.state === "retiring" ? 0 : slot.readyHeapUsedBytes ?? 0),
667
+ 0
668
+ );
669
+ }
670
+ readyWorkerCount() {
671
+ return [...this.slots].filter(({ state }) => state === "idle" || state === "busy").length;
672
+ }
673
+ emitDiagnostic(name, attributes, severity = "debug") {
674
+ try {
675
+ this.options.diagnostic?.(name, attributes, severity);
676
+ } catch {
677
+ }
678
+ }
679
+ }
680
+ export {
681
+ PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS,
682
+ PerceptionAnalysisThreadPool,
683
+ perceptionAnalysisWorkerStartModuleId
684
+ };