@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,1343 @@
1
+ import { prepareNotificationContent } from "./notification-content.js";
2
+ import { preparePerceptionNotification } from "./report-content.js";
3
+ import { isNotificationTurn } from "../../notification-turn.js";
4
+ import { performance } from "node:perf_hooks";
5
+ import { isClawclawRuntimeState } from "../../runtime-state.js";
6
+ import {
7
+ PERCEPTION_PLUGIN_API_VERSION,
8
+ hasValidClawclawResourceLocalizations,
9
+ resolveClawclawResourceMetadata
10
+ } from "./contracts.js";
11
+ import { DEFAULT_PERCEPTION_MODULES } from "./official-module-ids.js";
12
+ import {
13
+ ImportedLocalPerceptionModuleRunner
14
+ } from "./module-runner.js";
15
+ import {
16
+ listClawclawPerceptionSources
17
+ } from "./perception-source.js";
18
+ import {
19
+ PerceptionAnalysisThreadPool,
20
+ perceptionAnalysisWorkerStartModuleId
21
+ } from "./perception-analysis-thread-pool.js";
22
+ import {
23
+ PerceptionModuleLoader
24
+ } from "./perception-module-loader.js";
25
+ import { PerceptionReducerThreadPool } from "./perception-reducer-thread-pool.js";
26
+ import {
27
+ CLAWCLAW_PERCEPTION_SPATIAL_API,
28
+ CLAWCLAW_PERCEPTION_SPATIAL_FACTS
29
+ } from "./spatial-facts.js";
30
+ import { ObservationFrameProjector } from "../../observation-frame-projector.js";
31
+ import { DEFAULT_PERCEPTION_MODULES as DEFAULT_PERCEPTION_MODULES2 } from "./official-module-ids.js";
32
+ const CLAWCLAW_PERCEPTION_PLUGIN_ID = "clawclaw.perception";
33
+ const DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES = 10;
34
+ const DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS = 3e4;
35
+ const PERCEPTION_MODULE_TIMING_WINDOW_MS = 1e4;
36
+ const PERCEPTION_ANALYSIS_WINDOW_FRAMES = 10;
37
+ function elapsedMs(startedAt) {
38
+ return Math.round(Math.max(0, performance.now() - startedAt) * 1e3) / 1e3;
39
+ }
40
+ function percentile95(values) {
41
+ if (values.length === 0) return 0;
42
+ const sorted = [...values].sort((left, right) => left - right);
43
+ return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)];
44
+ }
45
+ function roundedAverage(values) {
46
+ if (values.length === 0) return 0;
47
+ return Math.round(values.reduce((sum, value) => sum + value, 0) / values.length * 1e3) / 1e3;
48
+ }
49
+ const PERCEPTION_CHECKPOINT_SCHEMA = "clawclaw.perception-checkpoint.v1";
50
+ const PERCEPTION_COMPUTATION_SCHEMA = "clawclaw.perception-computation.v1";
51
+ const PERCEPTION_FAILURE_REPORT_WINDOW_MS = 3e4;
52
+ function nonEmpty(value) {
53
+ return typeof value === "string" && value.trim().length > 0;
54
+ }
55
+ function perceptionLifecycle(frame) {
56
+ const phase = frame.gameState.phase ?? "unknown";
57
+ return phase === "wandering" && frame.gameState.you?.is_alive === false ? "dead" : phase;
58
+ }
59
+ function hasValidPerceptionEventMetadata(manifest) {
60
+ if (manifest.wakeAgent !== void 0 && typeof manifest.wakeAgent !== "boolean") return false;
61
+ const metadata = manifest.eventMetadata;
62
+ if (metadata === void 0) return true;
63
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return false;
64
+ const entries = Object.entries(metadata);
65
+ return entries.length === manifest.produces.length && entries.every(([type, value]) => manifest.produces.includes(type) && !!value && typeof value === "object" && !Array.isArray(value) && nonEmpty(value.name) && nonEmpty(value.description) && hasValidClawclawResourceLocalizations(value.localizations));
66
+ }
67
+ function moduleClass(instance) {
68
+ return instance.constructor;
69
+ }
70
+ function perceptionFailureDetails(reason) {
71
+ const code = reason && typeof reason === "object" && typeof reason.code === "string" ? reason.code.trim() : "";
72
+ const message = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "";
73
+ const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1];
74
+ return {
75
+ errorCode: /^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code) ? code : prefix ?? "PERCEPTION_MODULE_FAILED",
76
+ messagePresent: message.length > 0,
77
+ ...message ? { messageLength: message.length } : {}
78
+ };
79
+ }
80
+ function perceptionManifest(instance) {
81
+ const ModuleClass = moduleClass(instance);
82
+ return validatePerceptionManifest(ModuleClass.manifest);
83
+ }
84
+ function validatePerceptionManifest(manifest) {
85
+ if (!manifest || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.id) || manifest.name !== void 0 && !nonEmpty(manifest.name) || !nonEmpty(manifest.description) || !hasValidClawclawResourceLocalizations(manifest.localizations) || !["others", "self_and_others", "visible_pairs", "corpses"].includes(manifest.subjectScope) || !Array.isArray(manifest.produces) || manifest.produces.length === 0 || manifest.produces.some((type) => !/^visual\.[a-z0-9_.-]+$/.test(type)) || new Set(manifest.produces).size !== manifest.produces.length || !hasValidPerceptionEventMetadata(manifest) || manifest.execution !== void 0 && manifest.execution !== "parallel_analysis" || manifest.boundaryBaseline !== void 0 && (manifest.execution !== "parallel_analysis" || manifest.boundaryBaseline !== "current_only")) {
86
+ throw new Error("Perception module manifest is invalid.");
87
+ }
88
+ return manifest;
89
+ }
90
+ function createModuleSlots(config, loader) {
91
+ const ids = [...new Set(config.modules ?? DEFAULT_PERCEPTION_MODULES)].sort();
92
+ const sources = new Map(
93
+ (config.moduleSources ?? listClawclawPerceptionSources(config.workspaceDir)).map((source) => [source.id, source])
94
+ );
95
+ const selected = ids.map((id) => {
96
+ const source = sources.get(id);
97
+ if (!source) throw new Error(`Unknown perception module '${id}'.`);
98
+ return source;
99
+ }).filter((source) => !source.reminder && !source.module);
100
+ const reducerPool = selected.length > 0 ? new PerceptionReducerThreadPool({
101
+ modules: selected.map((source) => loader.threadSpec(source)),
102
+ loader: loader.threadConfig(),
103
+ spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
104
+ diagnosticsEnabled: config.diagnosticsEnabled === true
105
+ }) : void 0;
106
+ return {
107
+ reducerPool,
108
+ modules: selected.map((source) => {
109
+ const runner = new ImportedLocalPerceptionModuleRunner(source, loader, reducerPool);
110
+ return {
111
+ manifest: validatePerceptionManifest(runner.manifest),
112
+ runner,
113
+ source,
114
+ analysisGeneration: 0,
115
+ analysisHistoryFloorFrameSeq: 0,
116
+ analysisBaselinePending: false,
117
+ reducerReplayFromFrameSeq: void 0
118
+ };
119
+ })
120
+ };
121
+ }
122
+ function proposals(value) {
123
+ return value ? value.map((proposal) => ({
124
+ ...proposal,
125
+ payload: { ...proposal.payload }
126
+ })) : [];
127
+ }
128
+ class ClawclawPerceptionPlugin {
129
+ agentNotificationProducer = true;
130
+ kind = "epoch";
131
+ id = CLAWCLAW_PERCEPTION_PLUGIN_ID;
132
+ version = String(PERCEPTION_PLUGIN_API_VERSION);
133
+ get catchUp() {
134
+ return this.maxBackfillVisualFrames === 1 && this.modules.some(({ runner }) => runner.execution === "parallel_analysis") ? "latest_only" : "every_epoch";
135
+ }
136
+ maxInFlight;
137
+ maxPendingEpochs = 10;
138
+ backlogPolicy = "finish_started";
139
+ // Includes bounded analysis queueing and ordered reducer roundtrips. A 1s
140
+ // framework default killed healthy Workers during CPU contention/recovery.
141
+ timeoutMs = 5e3;
142
+ recoveryTimeoutMs = DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS;
143
+ produces;
144
+ configuredModules;
145
+ reducerPool;
146
+ /** Modules that completed every startup stage for the current lifecycle. */
147
+ modules;
148
+ maxBackfillVisualFrames;
149
+ diagnosticsEnabled;
150
+ moduleLoader = new PerceptionModuleLoader();
151
+ analysisPool;
152
+ projector = new ObservationFrameProjector();
153
+ api = Object.freeze({
154
+ spatial: CLAWCLAW_PERCEPTION_SPATIAL_API
155
+ });
156
+ lifecyclePhase = null;
157
+ lastFrameSeq = 0;
158
+ lastFrameTimeMs = null;
159
+ lastVisualTick = null;
160
+ lastVisualFrame = null;
161
+ lastConnectionId = null;
162
+ analysisWindow = [];
163
+ /** Bounded projection cache shared by overlapping epoch analyses. */
164
+ projectedFrameCache = /* @__PURE__ */ new Map();
165
+ replayFromFrameSeq = null;
166
+ moduleFailureReports = /* @__PURE__ */ new Map();
167
+ disabledModuleIds = /* @__PURE__ */ new Set();
168
+ moduleTimingWindows = /* @__PURE__ */ new Map();
169
+ moduleTimingWindowStartedAt = performance.now();
170
+ frameTimingWindow = this.newFrameTimingWindow();
171
+ runnersStarted = false;
172
+ runnersStartTask;
173
+ runnersStartGeneration = 0;
174
+ runnersStopTask;
175
+ runnerLifecycleGeneration = 0;
176
+ constructor(config = {}) {
177
+ const maxBackfillVisualFrames = config.maxBackfillVisualFrames ?? DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES;
178
+ if (!Number.isInteger(maxBackfillVisualFrames) || maxBackfillVisualFrames <= 0 || maxBackfillVisualFrames > 10) {
179
+ throw new TypeError("maxBackfillVisualFrames must be an integer between 1 and 10.");
180
+ }
181
+ this.maxBackfillVisualFrames = maxBackfillVisualFrames;
182
+ this.diagnosticsEnabled = config.diagnosticsEnabled === true;
183
+ const configured = createModuleSlots(config, this.moduleLoader);
184
+ this.configuredModules = configured.modules;
185
+ this.reducerPool = configured.reducerPool;
186
+ this.modules = this.configuredModules;
187
+ this.maxInFlight = this.modules.some(({ runner }) => runner.execution === "parallel_analysis") ? maxBackfillVisualFrames : 1;
188
+ this.produces = {
189
+ events: [...new Set(this.modules.flatMap(({ manifest }) => [...manifest.produces]))]
190
+ };
191
+ }
192
+ async start(context) {
193
+ await this.startRunners(context.signal, context.diagnostic);
194
+ }
195
+ async recover(context) {
196
+ const completedThroughEpochSeq = context.progress().completedThroughEpochSeq;
197
+ if (completedThroughEpochSeq <= 0) return;
198
+ const latestCompletedFrame = context.stateHistory.queryStateFrames({
199
+ scope: context.scope,
200
+ toEpochSeq: completedThroughEpochSeq,
201
+ order: "desc",
202
+ limit: 1
203
+ }).frames[0];
204
+ if (!latestCompletedFrame) return;
205
+ const nextFrameSeq = latestCompletedFrame.frameSeq + 1;
206
+ this.resetProjection();
207
+ this.lastFrameSeq = latestCompletedFrame.frameSeq;
208
+ this.replayFromFrameSeq = nextFrameSeq;
209
+ for (const module of this.modules) {
210
+ if (module.runner.execution !== "parallel_analysis") continue;
211
+ this.advanceParallelGeneration(module, nextFrameSeq);
212
+ }
213
+ context.diagnostic("perception.recovery_history_skipped", {
214
+ completed_through_epoch_seq: completedThroughEpochSeq,
215
+ skipped_through_frame_seq: latestCompletedFrame.frameSeq,
216
+ resume_from_frame_seq: nextFrameSeq
217
+ });
218
+ }
219
+ async update(input, context) {
220
+ if (isNotificationTurn(input.epoch.state)) return { outcome: "noop", reason: "notification_only" };
221
+ if (input.epoch.state.cycle && !input.epoch.state.cycle.hasNewState && input.epoch.state.connection === "connected" && input.epoch.state.stage !== "ended") {
222
+ return { outcome: "noop", reason: "unchanged_observation" };
223
+ }
224
+ const updateStartedAt = performance.now();
225
+ const projectionStartedAt = performance.now();
226
+ const visual = this.projector.project(input.frame);
227
+ const projectionMs = elapsedMs(projectionStartedAt);
228
+ const historyStartedAt = performance.now();
229
+ const analysisInput = visual && this.shouldAnalyze(input.frame) ? this.analysisInputFromHistory(input.frame, visual, context) : null;
230
+ const historyPrepareMs = elapsedMs(historyStartedAt);
231
+ const prepared = await this.prepareFrame(input.frame, visual, context.signal, analysisInput);
232
+ const proposal = {
233
+ schema: PERCEPTION_COMPUTATION_SCHEMA,
234
+ visual: prepared.visual,
235
+ analyses: prepared.analyses,
236
+ timing: {
237
+ projectionMs,
238
+ historyPrepareMs,
239
+ ...prepared.analysisTiming,
240
+ updateTotalMs: elapsedMs(updateStartedAt)
241
+ }
242
+ };
243
+ return {
244
+ outcome: "processed",
245
+ reason: prepared.visual ? "visual_analyzed" : "state_classified",
246
+ proposal
247
+ };
248
+ }
249
+ async commit(input, computation, context) {
250
+ if (isNotificationTurn(input.epoch.state) || computation.reason === "unchanged_observation") return computation;
251
+ const proposal = this.computationProposal(computation.proposal);
252
+ const commitStartedAt = performance.now();
253
+ const previousFrameSeq = this.lastFrameSeq;
254
+ const inspected = await this.inspectPreparedFrame({
255
+ stored: input.frame,
256
+ visual: proposal.visual,
257
+ analyses: proposal.analyses,
258
+ analysisTiming: proposal.timing ?? this.emptyAnalysisTiming()
259
+ }, context.signal, context.diagnostic);
260
+ if (!input.epoch.state.cycle && input.frame.frameSeq > previousFrameSeq + 1) {
261
+ context.diagnostic("perception.catchup_frames_dropped", {
262
+ target_epoch_seq: input.epoch.epochSeq,
263
+ max_backfill_visual_frames: this.maxBackfillVisualFrames,
264
+ dropped_state_frame_count: input.frame.frameSeq - previousFrameSeq - 1,
265
+ dropped_from_frame_seq: previousFrameSeq + 1,
266
+ dropped_through_frame_seq: input.frame.frameSeq - 1,
267
+ retained_from_frame_seq: input.frame.frameSeq,
268
+ retained_through_frame_seq: input.frame.frameSeq
269
+ });
270
+ }
271
+ const checkpoint = this.checkpointValue();
272
+ const commitMs = elapsedMs(commitStartedAt);
273
+ if (proposal.timing) {
274
+ this.recordFrameTiming({
275
+ ...proposal.timing,
276
+ commitMs,
277
+ totalMs: proposal.timing.updateTotalMs + commitMs
278
+ }, context.diagnostic);
279
+ }
280
+ return inspected.visual || inspected.proposals.length > 0 ? {
281
+ outcome: "processed",
282
+ ...inspected.reason ? { reason: inspected.reason } : {},
283
+ events: inspected.proposals.map((event) => ({
284
+ ...event,
285
+ notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, input.currentState.state, "custom")
286
+ })),
287
+ checkpoint
288
+ } : { outcome: "noop", reason: inspected.reason ?? "not_visual_state", checkpoint };
289
+ }
290
+ /** Advances one frame; used by Runtime and deterministic offline replay. */
291
+ async inspectFrame(input, signal = new AbortController().signal, diagnostic) {
292
+ if (!this.runnersStarted) await this.startRunners(signal);
293
+ if (input.frameSeq <= this.lastFrameSeq) {
294
+ return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
295
+ }
296
+ const projected = this.projector.project(input);
297
+ return this.inspectPreparedFrame(
298
+ await this.prepareFrame(
299
+ input,
300
+ projected,
301
+ signal,
302
+ projected && this.shouldAnalyze(input) ? this.localAnalysisInput(input, projected) : null
303
+ ),
304
+ signal,
305
+ diagnostic
306
+ );
307
+ }
308
+ async inspectPreparedFrame(input, signal, diagnostic) {
309
+ if (input.stored.frameSeq <= this.lastFrameSeq) {
310
+ return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
311
+ }
312
+ const stateFrameGap = !input.stored.state.cycle && this.lastFrameSeq > 0 && input.stored.frameSeq > this.lastFrameSeq + 1;
313
+ this.lastFrameSeq = input.stored.frameSeq;
314
+ const runtimeState = input.stored.state;
315
+ if (isClawclawRuntimeState(runtimeState)) {
316
+ if (runtimeState.connection !== "connected") {
317
+ const events = await this.flushAndReset(
318
+ "trajectory_gap",
319
+ signal,
320
+ diagnostic,
321
+ input.stored.frameSeq + 1
322
+ );
323
+ return {
324
+ visual: null,
325
+ proposals: events,
326
+ moduleStates: this.moduleStateSnapshot(),
327
+ reason: runtimeState.connection
328
+ };
329
+ }
330
+ if (runtimeState.cause === "agent_events_query" && runtimeState.control?.type === "events_query") {
331
+ const events = await this.flushModules(
332
+ "events_requested",
333
+ "snapshot",
334
+ signal,
335
+ diagnostic
336
+ );
337
+ return {
338
+ visual: null,
339
+ proposals: events,
340
+ moduleStates: this.moduleStateSnapshot(),
341
+ reason: "events_requested"
342
+ };
343
+ }
344
+ if (runtimeState.stage === "ended") {
345
+ const events = await this.flushAndReset(
346
+ "segment_ending",
347
+ signal,
348
+ diagnostic,
349
+ input.stored.frameSeq + 1
350
+ );
351
+ return {
352
+ visual: null,
353
+ proposals: events,
354
+ moduleStates: this.moduleStateSnapshot(),
355
+ reason: "segment_ending"
356
+ };
357
+ }
358
+ if (runtimeState.game_snapshot.status !== "fresh" && runtimeState.game_snapshot.status !== "cached") {
359
+ return {
360
+ visual: null,
361
+ proposals: [],
362
+ moduleStates: this.moduleStateSnapshot(),
363
+ reason: `game_snapshot:${runtimeState.game_snapshot.status}`
364
+ };
365
+ }
366
+ }
367
+ const projected = input.visual;
368
+ if (!projected) {
369
+ return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
370
+ }
371
+ const previousVisualTick = this.lastVisualTick;
372
+ const projectedLifecycle = perceptionLifecycle(projected);
373
+ const phaseChanged = this.lifecyclePhase !== null && this.lifecyclePhase !== projectedLifecycle;
374
+ const tickDelta = previousVisualTick === null ? null : projected.tick - previousVisualTick;
375
+ const sameConnection = this.lastConnectionId === input.stored.connectionId;
376
+ const emitted = [];
377
+ if (previousVisualTick !== null && projected.tick > previousVisualTick + 1) {
378
+ diagnostic?.("runtime.plugin.coverage_gap", {
379
+ reason: "game_tick_gap",
380
+ previous_game_tick: previousVisualTick,
381
+ received_game_tick: projected.tick,
382
+ missing_from_game_tick: previousVisualTick + 1,
383
+ missing_to_game_tick: projected.tick - 1,
384
+ frame_seq: input.stored.frameSeq
385
+ });
386
+ }
387
+ const continuousFromPrevious = !stateFrameGap && !phaseChanged && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && sameConnection;
388
+ const frame = { ...projected, tickDelta, continuousFromPrevious };
389
+ const gap = this.lastVisualTick !== null && !phaseChanged && !continuousFromPrevious;
390
+ if (gap || phaseChanged) {
391
+ const kind = gap ? "trajectory_gap" : "phase_changed";
392
+ emitted.push(...await this.flushModules(kind, "close", signal, diagnostic, projected));
393
+ await this.resetModules(
394
+ kind,
395
+ signal,
396
+ diagnostic,
397
+ input.stored.frameSeq,
398
+ false
399
+ );
400
+ this.replayFromFrameSeq = input.stored.frameSeq;
401
+ }
402
+ if (this.replayFromFrameSeq === null) this.replayFromFrameSeq = input.stored.frameSeq;
403
+ emitted.push(...await this.deliverVisualFrame(
404
+ frame,
405
+ input.stored.connectionId,
406
+ input.analyses,
407
+ gap || phaseChanged,
408
+ signal,
409
+ diagnostic
410
+ ));
411
+ return { visual: frame, proposals: emitted, moduleStates: this.moduleStateSnapshot() };
412
+ }
413
+ async flushForEventsQuery(signal = new AbortController().signal) {
414
+ const events = await this.flushModules("events_requested", "snapshot", signal);
415
+ return events.length > 0 ? { outcome: "processed", reason: "events_requested", events } : { outcome: "noop", reason: "events_requested" };
416
+ }
417
+ async flush(reason, context) {
418
+ const events = await this.flushModules(reason, "close", context.signal, context.diagnostic);
419
+ if (events.length > 0) {
420
+ context.diagnostic("perception.lifecycle_output_uncommitted", {
421
+ event_count: events.length,
422
+ reason
423
+ });
424
+ }
425
+ await this.resetModules(
426
+ reason,
427
+ context.signal,
428
+ context.diagnostic,
429
+ this.lastFrameSeq + 1
430
+ );
431
+ this.flushModuleTimingWindows(context.diagnostic, true);
432
+ this.flushFrameTimingWindow(context.diagnostic, true);
433
+ }
434
+ stop(reason) {
435
+ if (this.runnersStopTask) return this.runnersStopTask;
436
+ this.runnerLifecycleGeneration += 1;
437
+ this.runnersStarted = false;
438
+ let task;
439
+ task = this.stopRunners(reason).finally(() => {
440
+ if (this.runnersStopTask === task) this.runnersStopTask = void 0;
441
+ });
442
+ this.runnersStopTask = task;
443
+ return task;
444
+ }
445
+ async stopRunners(reason) {
446
+ const analysisPool = this.analysisPool;
447
+ this.analysisPool = void 0;
448
+ await analysisPool?.stop();
449
+ await Promise.allSettled(this.configuredModules.map(({ runner }) => runner.stop(reason)));
450
+ await this.reducerPool?.stop();
451
+ await this.moduleLoader.stop();
452
+ this.modules = [];
453
+ this.moduleFailureReports.clear();
454
+ this.disabledModuleIds.clear();
455
+ this.moduleTimingWindows.clear();
456
+ this.moduleTimingWindowStartedAt = performance.now();
457
+ this.frameTimingWindow = this.newFrameTimingWindow();
458
+ this.resetProjection();
459
+ }
460
+ /** Starts the same module lifecycle without constructing a Runtime context. */
461
+ async startForReplay(signal = new AbortController().signal) {
462
+ await this.startRunners(signal);
463
+ }
464
+ async stopForReplay() {
465
+ await this.stop("shutdown");
466
+ }
467
+ moduleDescriptors() {
468
+ return this.modules.map(({ manifest }) => ({
469
+ ...manifest,
470
+ produces: [...manifest.produces],
471
+ pluginId: CLAWCLAW_PERCEPTION_PLUGIN_ID
472
+ }));
473
+ }
474
+ diagnosticSnapshot() {
475
+ const pool = this.analysisPool?.snapshot();
476
+ const reducerPool = this.reducerPool?.snapshot();
477
+ return Object.freeze({
478
+ configured_module_count: this.configuredModules.length,
479
+ active_module_count: this.modules.length,
480
+ active_module_ids: this.modules.map(({ manifest }) => manifest.id),
481
+ analysis_pool: pool ? {
482
+ state: pool.state,
483
+ min_worker_count: pool.minWorkers,
484
+ max_worker_count: pool.maxWorkers,
485
+ worker_count: pool.workerCount,
486
+ idle_worker_count: pool.idleWorkerCount,
487
+ busy_worker_count: pool.busyWorkerCount,
488
+ queued_batch_count: pool.queuedBatchCount,
489
+ queued_job_count: pool.queuedJobCount,
490
+ in_flight_batch_count: pool.inFlightBatchCount,
491
+ started_worker_count: pool.startedWorkerCount,
492
+ retired_worker_count: pool.retiredWorkerCount,
493
+ worker_heap_used_bytes: pool.workerHeapUsedBytes,
494
+ peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes
495
+ } : null,
496
+ reducer_pool: reducerPool ? {
497
+ state: reducerPool.state,
498
+ max_worker_count: reducerPool.maxWorkerCount,
499
+ worker_count: reducerPool.workerCount,
500
+ busy_worker_count: reducerPool.busyWorkerCount,
501
+ queued_request_count: reducerPool.queuedRequestCount,
502
+ in_flight_request_count: reducerPool.inFlightRequestCount,
503
+ active_module_count: reducerPool.activeModuleCount,
504
+ unavailable_module_ids: reducerPool.unavailableModuleIds,
505
+ restarted_worker_count: reducerPool.restartedWorkerCount,
506
+ worker_heap_used_bytes: reducerPool.workerHeapUsedBytes,
507
+ peak_worker_heap_used_bytes: reducerPool.peakWorkerHeapUsedBytes
508
+ } : null
509
+ });
510
+ }
511
+ localizedModuleDescriptors(locale) {
512
+ return this.modules.map(({ manifest, source }) => resolveClawclawResourceMetadata({
513
+ ...manifest,
514
+ display: source.display
515
+ }, locale));
516
+ }
517
+ localizedModuleDescriptorForEvent(type, locale) {
518
+ const module = this.modules.find(({ manifest }) => manifest.produces.includes(type));
519
+ if (!module) return void 0;
520
+ return {
521
+ ...resolveClawclawResourceMetadata({ ...module.manifest, display: module.source.display }, locale),
522
+ perceptionId: module.manifest.id
523
+ };
524
+ }
525
+ localizedEventDescriptors(locale) {
526
+ return this.modules.flatMap(({ manifest }) => manifest.produces.flatMap((type) => {
527
+ const metadata = manifest.eventMetadata?.[type];
528
+ if (!metadata) return [];
529
+ const localized = resolveClawclawResourceMetadata({ id: type, ...metadata }, locale);
530
+ return [{
531
+ type,
532
+ perceptionId: manifest.id,
533
+ name: localized.name,
534
+ description: localized.description
535
+ }];
536
+ }));
537
+ }
538
+ moduleStateSnapshot() {
539
+ return Object.fromEntries(this.modules.map(({ manifest, runner }) => [
540
+ manifest.id,
541
+ runner.debugSnapshot()
542
+ ]));
543
+ }
544
+ async deliverVisualFrame(frame, connectionId, analyses, discardParallelAnalysis, signal, diagnostic) {
545
+ this.lastFrameTimeMs = frame.timeMs;
546
+ this.lifecyclePhase = perceptionLifecycle(frame);
547
+ this.lastVisualTick = frame.tick;
548
+ this.lastVisualFrame = frame;
549
+ this.lastConnectionId = connectionId;
550
+ this.analysisWindow.push(frame);
551
+ if (this.analysisWindow.length > PERCEPTION_ANALYSIS_WINDOW_FRAMES) this.analysisWindow.shift();
552
+ return this.withOccurredAt(
553
+ await this.updateModules(
554
+ frame,
555
+ analyses,
556
+ discardParallelAnalysis,
557
+ signal,
558
+ diagnostic
559
+ ),
560
+ frame.timeMs
561
+ );
562
+ }
563
+ async updateModules(frame, analyses, discardParallelAnalysis, signal, diagnostic) {
564
+ const analysisByModule = new Map(analyses.map((entry) => [entry.moduleId, entry]));
565
+ this.recordAnalysisResults(analyses, diagnostic);
566
+ return this.collectModuleEvents(
567
+ "update",
568
+ async (module) => {
569
+ const { manifest, runner } = module;
570
+ if (runner.execution === "ordered_update") {
571
+ return runner.update(frame, this.api, signal);
572
+ }
573
+ if (!this.shouldRunParallelModuleForFrame(module, frame.frameSeq)) return [];
574
+ const analysis = analysisByModule.get(manifest.id);
575
+ if (discardParallelAnalysis) {
576
+ if (manifest.boundaryBaseline !== "current_only" || !analysis || analysis.outcome === "rejected" || analysis.generation + 1 !== module.analysisGeneration) {
577
+ module.analysisBaselinePending = true;
578
+ module.reducerReplayFromFrameSeq = null;
579
+ return [];
580
+ }
581
+ await runner.commit(frame, analysis.analysis, this.api, signal);
582
+ module.reducerReplayFromFrameSeq = frame.frameSeq;
583
+ module.analysisBaselinePending = false;
584
+ return [];
585
+ }
586
+ if (!analysis || analysis.outcome === "rejected") {
587
+ const failure = analysis?.outcome === "rejected" ? analysis.failure : void 0;
588
+ if (failure && this.analysisFailureDisablesModule(failure.errorCode) && !this.disabledModuleIds.has(manifest.id)) {
589
+ this.disabledModuleIds.add(manifest.id);
590
+ diagnostic?.("perception.module.disabled", {
591
+ module_id: manifest.id,
592
+ reason: failure.errorCode
593
+ }, "error");
594
+ }
595
+ await this.invalidateParallelModule(
596
+ module,
597
+ frame.frameSeq + 1,
598
+ signal
599
+ );
600
+ return [];
601
+ }
602
+ if (analysis.generation !== module.analysisGeneration) {
603
+ if (!module.analysisBaselinePending) {
604
+ module.analysisBaselinePending = true;
605
+ module.reducerReplayFromFrameSeq = null;
606
+ await runner.reset("trajectory_gap", signal);
607
+ }
608
+ return [];
609
+ }
610
+ const events = await runner.commit(frame, analysis.analysis, this.api, signal);
611
+ if (module.reducerReplayFromFrameSeq === null || module.reducerReplayFromFrameSeq === void 0 && module.analysisBaselinePending && module.analysisHistoryFloorFrameSeq > 0) module.reducerReplayFromFrameSeq = frame.frameSeq;
612
+ if (module.analysisBaselinePending) {
613
+ module.analysisBaselinePending = false;
614
+ return [];
615
+ }
616
+ return events;
617
+ },
618
+ diagnostic,
619
+ async (module) => {
620
+ if (module.runner.execution !== "parallel_analysis") return;
621
+ await this.invalidateParallelModule(
622
+ module,
623
+ frame.frameSeq + 1,
624
+ signal
625
+ );
626
+ }
627
+ );
628
+ }
629
+ async invalidateParallelModule(module, historyFloorFrameSeq, signal) {
630
+ this.advanceParallelGeneration(module, historyFloorFrameSeq);
631
+ await module.runner.reset("trajectory_gap", signal);
632
+ }
633
+ advanceParallelGeneration(module, historyFloorFrameSeq, baselinePending = true) {
634
+ module.analysisGeneration += 1;
635
+ module.analysisHistoryFloorFrameSeq = Math.max(
636
+ module.analysisHistoryFloorFrameSeq,
637
+ historyFloorFrameSeq
638
+ );
639
+ module.analysisBaselinePending = baselinePending;
640
+ module.reducerReplayFromFrameSeq = null;
641
+ }
642
+ async prepareFrame(stored, visual, signal, analysisInput = null) {
643
+ if (!visual || !this.shouldAnalyze(stored)) {
644
+ return { stored, visual, analyses: [], analysisTiming: this.emptyAnalysisTiming() };
645
+ }
646
+ const preparedVisual = analysisInput?.frame ?? visual;
647
+ const analyzerInput = analysisInput ?? this.localAnalysisInput(stored, visual);
648
+ const parallelModules = this.modules.filter((module) => module.runner.execution === "parallel_analysis" && this.shouldRunParallelModuleForFrame(module, stored.frameSeq));
649
+ if (parallelModules.length === 0) {
650
+ return {
651
+ stored,
652
+ visual: preparedVisual,
653
+ analyses: [],
654
+ analysisTiming: this.emptyAnalysisTiming()
655
+ };
656
+ }
657
+ const analysisPool = this.analysisPool;
658
+ if (!analysisPool) throw new Error("perception_analysis_pool_not_started");
659
+ const generations = new Map(parallelModules.map((module) => [
660
+ module.manifest.id,
661
+ module.analysisGeneration
662
+ ]));
663
+ const jobs = parallelModules.map((module) => ({
664
+ moduleId: module.manifest.id,
665
+ input: this.analysisInputForModule(analyzerInput, module)
666
+ }));
667
+ const startedAt = performance.now();
668
+ try {
669
+ signal.throwIfAborted();
670
+ const batch = await analysisPool.analyze(jobs, signal);
671
+ const analyses = batch.results.map((result) => result.outcome === "fulfilled" ? {
672
+ moduleId: result.moduleId,
673
+ generation: generations.get(result.moduleId),
674
+ outcome: "fulfilled",
675
+ durationMs: result.durationMs,
676
+ analysis: result.analysis
677
+ } : {
678
+ moduleId: result.moduleId,
679
+ generation: generations.get(result.moduleId),
680
+ outcome: "rejected",
681
+ durationMs: result.durationMs,
682
+ failure: result.failure
683
+ });
684
+ const moduleDurations = batch.results.map((result) => result.durationMs);
685
+ return {
686
+ stored,
687
+ visual: preparedVisual,
688
+ analyses,
689
+ analysisTiming: {
690
+ workerQueueMs: batch.queueDurationMs,
691
+ workerRoundtripMs: Math.max(0, batch.durationMs - batch.queueDurationMs),
692
+ moduleCpuSumMs: moduleDurations.reduce((sum, duration) => sum + duration, 0),
693
+ moduleCpuMaxMs: Math.max(0, ...moduleDurations),
694
+ workerCount: batch.workerCount
695
+ }
696
+ };
697
+ } catch (error) {
698
+ const failure = perceptionFailureDetails(error);
699
+ const durationMs = elapsedMs(startedAt);
700
+ return {
701
+ stored,
702
+ visual: preparedVisual,
703
+ analyses: parallelModules.map((module) => ({
704
+ moduleId: module.manifest.id,
705
+ generation: generations.get(module.manifest.id),
706
+ outcome: "rejected",
707
+ durationMs,
708
+ failure
709
+ })),
710
+ analysisTiming: {
711
+ workerQueueMs: 0,
712
+ workerRoundtripMs: durationMs,
713
+ moduleCpuSumMs: 0,
714
+ moduleCpuMaxMs: 0,
715
+ workerCount: analysisPool.snapshot().workerCount
716
+ }
717
+ };
718
+ }
719
+ }
720
+ emptyAnalysisTiming() {
721
+ return {
722
+ workerQueueMs: 0,
723
+ workerRoundtripMs: 0,
724
+ moduleCpuSumMs: 0,
725
+ moduleCpuMaxMs: 0,
726
+ workerCount: this.analysisPool?.snapshot().workerCount ?? 0
727
+ };
728
+ }
729
+ analysisInputForModule(input, module) {
730
+ const floor = module.analysisHistoryFloorFrameSeq;
731
+ if (floor <= 0) return input;
732
+ const history = input.history.filter((frame2) => frame2.frameSeq >= floor);
733
+ const previous = history.at(-1);
734
+ const keptImmediatePrevious = previous === input.history.at(-1);
735
+ const tickDelta = previous ? input.frame.tick - previous.tick : null;
736
+ const frame = {
737
+ ...input.frame,
738
+ tickDelta,
739
+ continuousFromPrevious: !!previous && keptImmediatePrevious && input.frame.continuousFromPrevious
740
+ };
741
+ return {
742
+ frame,
743
+ history,
744
+ gapBefore: input.gapBefore || history.length !== input.history.length || !frame.continuousFromPrevious
745
+ };
746
+ }
747
+ shouldRunParallelModuleForFrame(module, frameSeq) {
748
+ return !this.disabledModuleIds.has(module.manifest.id) && frameSeq >= module.analysisHistoryFloorFrameSeq;
749
+ }
750
+ analysisFailureDisablesModule(errorCode) {
751
+ return errorCode === "perception_analysis_worker_exited" || errorCode === "perception_analysis_worker_memory_invalid" || errorCode === "perception_analysis_output_too_large";
752
+ }
753
+ analysisInputFromHistory(stored, currentVisual, context) {
754
+ this.rememberProjectedFrame(stored, currentVisual);
755
+ const cached = (context.processingIntervalMs !== void 0 ? [] : [...this.projectedFrameCache.values()]).filter((value) => value.stored.frameSeq <= stored.frameSeq).sort((left, right) => left.stored.frameSeq - right.stored.frameSeq).slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1));
756
+ const cacheIsContinuous = cached.every((value, index) => index === 0 || value.stored.frameSeq === cached[index - 1].stored.frameSeq + 1);
757
+ if (cached.length > 1 && cacheIsContinuous && cached.at(-1)?.stored.frameSeq === stored.frameSeq) {
758
+ return this.enrichAnalysisInput(cached);
759
+ }
760
+ const projected = /* @__PURE__ */ new Map();
761
+ let beforeFrameSeq = stored.state.cycle?.stateFrameSeq ?? stored.frameSeq + 1;
762
+ while (projected.size < PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1 && beforeFrameSeq > 1) {
763
+ context.signal.throwIfAborted();
764
+ const page = context.stateHistory.queryStateFrames({
765
+ scope: context.scope,
766
+ beforeFrameSeq,
767
+ order: "desc",
768
+ limit: 32
769
+ });
770
+ if (page.frames.length === 0) break;
771
+ for (const candidate of page.frames) {
772
+ if (stored.state.cycle && candidate.state.cycle) continue;
773
+ if (candidate.frameSeq > stored.frameSeq) continue;
774
+ const visual = candidate.frameSeq === stored.frameSeq ? currentVisual : this.projector.project(candidate);
775
+ if (visual) {
776
+ projected.set(candidate.frameSeq, { stored: candidate, visual });
777
+ this.rememberProjectedFrame(candidate, visual);
778
+ }
779
+ if (projected.size >= PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1) break;
780
+ }
781
+ beforeFrameSeq = page.frames.at(-1).frameSeq;
782
+ if (!page.page.hasMore) break;
783
+ }
784
+ if (!projected.has(stored.frameSeq)) {
785
+ projected.set(stored.frameSeq, { stored, visual: currentVisual });
786
+ }
787
+ const values = [...projected.values()].sort((left, right) => left.stored.frameSeq - right.stored.frameSeq);
788
+ return this.enrichAnalysisInput(values);
789
+ }
790
+ enrichAnalysisInput(values) {
791
+ const enriched = [];
792
+ values.forEach((value, index) => {
793
+ const previous = index > 0 ? values[index - 1] : void 0;
794
+ const before = enriched.at(-1);
795
+ const tickDelta = before ? value.visual.tick - before.tick : null;
796
+ const continuousFromPrevious = !!before && perceptionLifecycle(before) === perceptionLifecycle(value.visual) && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && previous?.stored.connectionId === value.stored.connectionId;
797
+ enriched.push({ ...value.visual, tickDelta, continuousFromPrevious });
798
+ });
799
+ const bounded = enriched.slice(-PERCEPTION_ANALYSIS_WINDOW_FRAMES);
800
+ const frame = bounded.at(-1);
801
+ const history = bounded.slice(0, -1);
802
+ return {
803
+ frame,
804
+ history,
805
+ gapBefore: history.length > 0 && !frame.continuousFromPrevious
806
+ };
807
+ }
808
+ rememberProjectedFrame(stored, visual) {
809
+ this.projectedFrameCache.set(stored.frameSeq, { stored, visual });
810
+ const maximum = PERCEPTION_ANALYSIS_WINDOW_FRAMES + this.maxInFlight + 2;
811
+ while (this.projectedFrameCache.size > maximum) {
812
+ const oldest = Math.min(...this.projectedFrameCache.keys());
813
+ this.projectedFrameCache.delete(oldest);
814
+ }
815
+ }
816
+ localAnalysisInput(stored, visual) {
817
+ const history = this.analysisWindow.slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES - 1));
818
+ const previous = history.at(-1);
819
+ const tickDelta = previous ? visual.tick - previous.tick : null;
820
+ const frame = {
821
+ ...visual,
822
+ tickDelta,
823
+ continuousFromPrevious: !!previous && perceptionLifecycle(previous) === perceptionLifecycle(visual) && tickDelta !== null && tickDelta >= 0 && tickDelta <= 3 && this.lastConnectionId === stored.connectionId
824
+ };
825
+ return {
826
+ frame,
827
+ history,
828
+ gapBefore: history.length > 0 && !frame.continuousFromPrevious
829
+ };
830
+ }
831
+ shouldAnalyze(stored) {
832
+ const runtimeState = stored.state;
833
+ if (!isClawclawRuntimeState(runtimeState)) return true;
834
+ return runtimeState.connection === "connected" && runtimeState.stage !== "ended" && (runtimeState.game_snapshot.status === "fresh" || runtimeState.game_snapshot.status === "cached") && !(runtimeState.cause === "agent_events_query" && runtimeState.control?.type === "events_query");
835
+ }
836
+ computationProposal(value) {
837
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
838
+ throw new Error("perception_computation_missing");
839
+ }
840
+ const proposal = value;
841
+ if (proposal.schema !== PERCEPTION_COMPUTATION_SCHEMA || !Array.isArray(proposal.analyses) || proposal.visual !== null && typeof proposal.visual !== "object") throw new Error("perception_computation_invalid");
842
+ return proposal;
843
+ }
844
+ recordAnalysisResults(analyses, diagnostic) {
845
+ if (analyses.length === 0) return;
846
+ this.recordModuleTimings("analyze", analyses.map((entry) => ({
847
+ module_id: entry.moduleId,
848
+ duration_ms: entry.durationMs,
849
+ outcome: entry.outcome,
850
+ event_count: 0
851
+ })));
852
+ this.flushModuleTimingWindows(diagnostic);
853
+ for (const entry of analyses) {
854
+ if (entry.outcome !== "rejected" || !entry.failure) continue;
855
+ this.reportModuleFailure(entry.moduleId, "analyze", entry.failure, diagnostic);
856
+ }
857
+ }
858
+ async flushModules(kind, mode, signal, diagnostic, next) {
859
+ const boundary = Object.freeze({
860
+ kind,
861
+ mode,
862
+ through: this.lastVisualFrame,
863
+ ...next === void 0 ? {} : { next }
864
+ });
865
+ const output = await this.collectModuleEvents(
866
+ `flush:${kind}`,
867
+ ({ runner }) => runner.flush(boundary, this.api, signal),
868
+ diagnostic
869
+ );
870
+ return this.withOccurredAt(output, boundary.through?.timeMs ?? this.lastFrameTimeMs);
871
+ }
872
+ async flushAndReset(kind, signal, diagnostic, replayFromFrameSeq = null) {
873
+ const emitted = await this.flushModules(kind, "close", signal, diagnostic);
874
+ await this.resetModules(
875
+ kind,
876
+ signal,
877
+ diagnostic,
878
+ replayFromFrameSeq ?? this.lastFrameSeq + 1
879
+ );
880
+ this.lifecyclePhase = null;
881
+ this.lastFrameTimeMs = null;
882
+ this.lastVisualTick = null;
883
+ this.lastVisualFrame = null;
884
+ this.lastConnectionId = null;
885
+ this.analysisWindow.length = 0;
886
+ this.replayFromFrameSeq = replayFromFrameSeq;
887
+ return emitted;
888
+ }
889
+ async resetModules(reason, signal, diagnostic, parallelHistoryFloorFrameSeq, parallelBaselinePending = true) {
890
+ const modules = this.modules;
891
+ if (parallelHistoryFloorFrameSeq !== void 0) {
892
+ for (const module of modules) {
893
+ if (module.runner.execution !== "parallel_analysis") continue;
894
+ this.advanceParallelGeneration(
895
+ module,
896
+ parallelHistoryFloorFrameSeq,
897
+ parallelBaselinePending || module.manifest.boundaryBaseline !== "current_only"
898
+ );
899
+ }
900
+ }
901
+ const results = await Promise.allSettled(
902
+ modules.map(({ runner }) => runner.reset(reason, signal))
903
+ );
904
+ this.reportModuleFailures(`reset:${reason}`, modules, results, diagnostic);
905
+ }
906
+ async collectModuleEvents(operation, invoke, diagnostic, onRejected) {
907
+ const modules = this.modules;
908
+ const timings = new Array(modules.length);
909
+ const results = await Promise.allSettled(modules.map(async (module, index) => {
910
+ const startedAt = performance.now();
911
+ try {
912
+ const result = await invoke(module);
913
+ timings[index] = {
914
+ module_id: module.manifest.id,
915
+ duration_ms: elapsedMs(startedAt),
916
+ outcome: "fulfilled",
917
+ event_count: proposals(result).length
918
+ };
919
+ return result;
920
+ } catch (error) {
921
+ timings[index] = {
922
+ module_id: module.manifest.id,
923
+ duration_ms: elapsedMs(startedAt),
924
+ outcome: "rejected",
925
+ event_count: 0
926
+ };
927
+ throw error;
928
+ }
929
+ }));
930
+ this.reportModuleFailures(operation, modules, results, diagnostic);
931
+ if (onRejected) {
932
+ await Promise.allSettled(results.map((result, index) => result.status === "rejected" ? onRejected(modules[index], result.reason) : Promise.resolve()));
933
+ }
934
+ if (diagnostic) {
935
+ this.recordModuleTimings(operation, timings);
936
+ this.flushModuleTimingWindows(diagnostic);
937
+ }
938
+ return results.flatMap((result, index) => {
939
+ if (result.status !== "fulfilled") return [];
940
+ const module = modules[index];
941
+ const values = proposals(result.value);
942
+ return values.map((value) => ({
943
+ ...value,
944
+ ...module.source?.declaredId && module.source.declaredId !== module.manifest.id ? { dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` } : {},
945
+ notificationContent: preparePerceptionNotification(
946
+ value.type,
947
+ value.payload,
948
+ this.lastVisualFrame?.gameState ?? null,
949
+ module.manifest.id,
950
+ this.lastVisualTick
951
+ )
952
+ }));
953
+ });
954
+ }
955
+ recordModuleTimings(operation, timings) {
956
+ for (const timing of timings) {
957
+ const key = `${timing.module_id}\0${operation}`;
958
+ let window = this.moduleTimingWindows.get(key);
959
+ if (!window) {
960
+ window = {
961
+ moduleId: timing.module_id,
962
+ operation,
963
+ durationsMs: [],
964
+ eventCount: 0,
965
+ failureCount: 0
966
+ };
967
+ this.moduleTimingWindows.set(key, window);
968
+ }
969
+ window.durationsMs.push(timing.duration_ms);
970
+ window.eventCount += timing.event_count;
971
+ if (timing.outcome === "rejected") window.failureCount += 1;
972
+ }
973
+ }
974
+ newFrameTimingWindow() {
975
+ return {
976
+ startedAtMs: performance.now(),
977
+ projectionMs: [],
978
+ historyPrepareMs: [],
979
+ workerQueueMs: [],
980
+ workerRoundtripMs: [],
981
+ moduleCpuSumMs: [],
982
+ moduleCpuMaxMs: [],
983
+ updateTotalMs: [],
984
+ commitMs: [],
985
+ totalMs: [],
986
+ workerCountMax: 0
987
+ };
988
+ }
989
+ recordFrameTiming(sample, diagnostic) {
990
+ const window = this.frameTimingWindow;
991
+ window.projectionMs.push(sample.projectionMs);
992
+ window.historyPrepareMs.push(sample.historyPrepareMs);
993
+ window.workerQueueMs.push(sample.workerQueueMs);
994
+ window.workerRoundtripMs.push(sample.workerRoundtripMs);
995
+ window.moduleCpuSumMs.push(sample.moduleCpuSumMs);
996
+ window.moduleCpuMaxMs.push(sample.moduleCpuMaxMs);
997
+ window.updateTotalMs.push(sample.updateTotalMs);
998
+ window.commitMs.push(sample.commitMs);
999
+ window.totalMs.push(sample.totalMs);
1000
+ window.workerCountMax = Math.max(window.workerCountMax, sample.workerCount);
1001
+ this.flushFrameTimingWindow(diagnostic);
1002
+ }
1003
+ flushFrameTimingWindow(diagnostic, force = false) {
1004
+ const window = this.frameTimingWindow;
1005
+ if (!diagnostic || window.totalMs.length === 0) return;
1006
+ const windowMs = Math.max(0, performance.now() - window.startedAtMs);
1007
+ if (!force && windowMs < PERCEPTION_MODULE_TIMING_WINDOW_MS) return;
1008
+ diagnostic("perception.frame.timing_window", {
1009
+ window_ms: Math.round(windowMs),
1010
+ count: window.totalMs.length,
1011
+ projection_avg_ms: roundedAverage(window.projectionMs),
1012
+ projection_p95_ms: percentile95(window.projectionMs),
1013
+ history_prepare_avg_ms: roundedAverage(window.historyPrepareMs),
1014
+ history_prepare_p95_ms: percentile95(window.historyPrepareMs),
1015
+ worker_queue_avg_ms: roundedAverage(window.workerQueueMs),
1016
+ worker_queue_p95_ms: percentile95(window.workerQueueMs),
1017
+ worker_roundtrip_avg_ms: roundedAverage(window.workerRoundtripMs),
1018
+ worker_roundtrip_p95_ms: percentile95(window.workerRoundtripMs),
1019
+ module_cpu_sum_avg_ms: roundedAverage(window.moduleCpuSumMs),
1020
+ module_cpu_sum_p95_ms: percentile95(window.moduleCpuSumMs),
1021
+ module_cpu_max_p95_ms: percentile95(window.moduleCpuMaxMs),
1022
+ update_total_avg_ms: roundedAverage(window.updateTotalMs),
1023
+ update_total_p95_ms: percentile95(window.updateTotalMs),
1024
+ commit_avg_ms: roundedAverage(window.commitMs),
1025
+ commit_p95_ms: percentile95(window.commitMs),
1026
+ total_avg_ms: roundedAverage(window.totalMs),
1027
+ total_p95_ms: percentile95(window.totalMs),
1028
+ total_max_ms: Math.max(...window.totalMs),
1029
+ worker_count_max: window.workerCountMax
1030
+ });
1031
+ this.frameTimingWindow = this.newFrameTimingWindow();
1032
+ }
1033
+ flushModuleTimingWindows(diagnostic, force = false) {
1034
+ if (!diagnostic || this.moduleTimingWindows.size === 0) return;
1035
+ const now = performance.now();
1036
+ const windowMs = Math.max(0, now - this.moduleTimingWindowStartedAt);
1037
+ if (!force && windowMs < PERCEPTION_MODULE_TIMING_WINDOW_MS) return;
1038
+ for (const window of this.moduleTimingWindows.values()) {
1039
+ diagnostic("perception.module.timing_window", {
1040
+ module_id: window.moduleId,
1041
+ operation: window.operation,
1042
+ window_ms: Math.round(windowMs),
1043
+ count: window.durationsMs.length,
1044
+ average_duration_ms: roundedAverage(window.durationsMs),
1045
+ p95_duration_ms: percentile95(window.durationsMs),
1046
+ max_duration_ms: Math.max(...window.durationsMs),
1047
+ failure_count: window.failureCount,
1048
+ event_count: window.eventCount
1049
+ });
1050
+ }
1051
+ this.moduleTimingWindows.clear();
1052
+ this.moduleTimingWindowStartedAt = now;
1053
+ }
1054
+ reportModuleFailures(operation, modules, results, diagnostic) {
1055
+ results.forEach((result, index) => {
1056
+ if (result.status === "fulfilled" || !diagnostic) return;
1057
+ const moduleId = modules[index].manifest.id;
1058
+ this.reportModuleFailure(
1059
+ moduleId,
1060
+ operation,
1061
+ perceptionFailureDetails(result.reason),
1062
+ diagnostic
1063
+ );
1064
+ });
1065
+ }
1066
+ reportModuleFailure(moduleId, operation, details, diagnostic) {
1067
+ if (!diagnostic) return;
1068
+ const now = Date.now();
1069
+ const previous = this.moduleFailureReports.get(moduleId);
1070
+ const failureCount = (previous?.failureCount ?? 0) + 1;
1071
+ if (previous && now - previous.lastReportedAtMs < PERCEPTION_FAILURE_REPORT_WINDOW_MS) {
1072
+ this.moduleFailureReports.set(moduleId, {
1073
+ ...previous,
1074
+ failureCount,
1075
+ suppressedCount: previous.suppressedCount + 1
1076
+ });
1077
+ return;
1078
+ }
1079
+ diagnostic("perception.module.failed", {
1080
+ module_id: moduleId,
1081
+ operation,
1082
+ error_code: details.errorCode,
1083
+ error_message_present: details.messagePresent,
1084
+ error_message_length: details.messageLength,
1085
+ failure_count: failureCount,
1086
+ suppressed_failure_count: previous?.suppressedCount ?? 0
1087
+ }, "error");
1088
+ this.moduleFailureReports.set(moduleId, {
1089
+ lastReportedAtMs: now,
1090
+ failureCount,
1091
+ suppressedCount: 0
1092
+ });
1093
+ }
1094
+ startRunners(signal, diagnostic) {
1095
+ signal.throwIfAborted();
1096
+ if (this.runnersStarted) return Promise.resolve();
1097
+ if (this.runnersStopTask) {
1098
+ const pending = [this.runnersStopTask, this.runnersStartTask].filter(
1099
+ (task2) => !!task2
1100
+ );
1101
+ return Promise.allSettled(pending).then(() => {
1102
+ signal.throwIfAborted();
1103
+ return this.startRunners(signal, diagnostic);
1104
+ });
1105
+ }
1106
+ if (this.runnersStartTask) {
1107
+ if (this.runnersStartGeneration === this.runnerLifecycleGeneration) {
1108
+ return this.runnersStartTask;
1109
+ }
1110
+ return this.runnersStartTask.catch(() => {
1111
+ }).then(() => {
1112
+ signal.throwIfAborted();
1113
+ return this.startRunners(signal, diagnostic);
1114
+ });
1115
+ }
1116
+ const generation = ++this.runnerLifecycleGeneration;
1117
+ let task;
1118
+ task = this.startRunnersInternal(signal, diagnostic, generation).finally(() => {
1119
+ if (this.runnersStartTask === task) this.runnersStartTask = void 0;
1120
+ });
1121
+ this.runnersStartGeneration = generation;
1122
+ this.runnersStartTask = task;
1123
+ return task;
1124
+ }
1125
+ async startRunnersInternal(signal, diagnostic, generation) {
1126
+ let analysisPool;
1127
+ try {
1128
+ const candidates = this.configuredModules;
1129
+ this.disabledModuleIds.clear();
1130
+ for (const module of candidates) {
1131
+ module.analysisGeneration = 0;
1132
+ module.analysisHistoryFloorFrameSeq = 0;
1133
+ module.analysisBaselinePending = false;
1134
+ module.reducerReplayFromFrameSeq = void 0;
1135
+ }
1136
+ const startResults = await Promise.allSettled(candidates.map(({ runner }) => runner.start(
1137
+ CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
1138
+ this.api,
1139
+ signal,
1140
+ diagnostic
1141
+ )));
1142
+ this.assertRunnerLifecycle(generation, signal);
1143
+ const startedModules = candidates.filter((module, index) => {
1144
+ const result = startResults[index];
1145
+ if (result.status === "fulfilled") return true;
1146
+ this.reportModuleFailure(
1147
+ module.manifest.id,
1148
+ "start",
1149
+ perceptionFailureDetails(result.reason),
1150
+ diagnostic
1151
+ );
1152
+ return false;
1153
+ });
1154
+ await Promise.allSettled(candidates.flatMap((module, index) => startResults[index]?.status === "rejected" ? [module.runner.stop("shutdown")] : []));
1155
+ this.assertRunnerLifecycle(generation, signal);
1156
+ const parallelModules = startedModules.filter(({ runner }) => runner.execution === "parallel_analysis");
1157
+ const threadSpecResults = await Promise.allSettled(parallelModules.map((module) => Promise.resolve().then(() => this.moduleLoader.threadSpec(module.source))));
1158
+ this.assertRunnerLifecycle(generation, signal);
1159
+ let parallelCandidates = [];
1160
+ const threadSpecFailures = [];
1161
+ threadSpecResults.forEach((result, index) => {
1162
+ const module = parallelModules[index];
1163
+ if (result.status === "fulfilled") {
1164
+ parallelCandidates.push({ module, threadModule: result.value });
1165
+ return;
1166
+ }
1167
+ this.reportModuleFailure(
1168
+ module.manifest.id,
1169
+ "worker_start",
1170
+ perceptionFailureDetails(result.reason),
1171
+ diagnostic
1172
+ );
1173
+ threadSpecFailures.push(module);
1174
+ });
1175
+ await Promise.allSettled(threadSpecFailures.map(({ runner }) => runner.stop("shutdown")));
1176
+ this.assertRunnerLifecycle(generation, signal);
1177
+ let usedSingletonPreflight = false;
1178
+ while (parallelCandidates.length > 0) {
1179
+ const currentPool = new PerceptionAnalysisThreadPool({
1180
+ modules: parallelCandidates.map(({ threadModule }) => threadModule),
1181
+ loader: this.moduleLoader.threadConfig(),
1182
+ spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
1183
+ maxWorkers: Math.min(this.maxInFlight, Math.max(2, parallelCandidates.length)),
1184
+ maxPendingBatches: this.maxInFlight,
1185
+ fixedWorkers: true,
1186
+ diagnosticsEnabled: this.diagnosticsEnabled,
1187
+ diagnostic
1188
+ });
1189
+ analysisPool = currentPool;
1190
+ this.analysisPool = currentPool;
1191
+ try {
1192
+ await currentPool.start();
1193
+ this.assertRunnerLifecycle(generation, signal);
1194
+ break;
1195
+ } catch (error) {
1196
+ await currentPool.stop();
1197
+ if (this.analysisPool === currentPool) this.analysisPool = void 0;
1198
+ analysisPool = void 0;
1199
+ this.assertRunnerLifecycle(generation, signal);
1200
+ const failedModuleId = perceptionAnalysisWorkerStartModuleId(error);
1201
+ const failedIndex = failedModuleId ? parallelCandidates.findIndex(({ module }) => module.manifest.id === failedModuleId) : -1;
1202
+ if (failedIndex >= 0) {
1203
+ const [failed] = parallelCandidates.splice(failedIndex, 1);
1204
+ this.reportModuleFailure(
1205
+ failed.module.manifest.id,
1206
+ "worker_start",
1207
+ perceptionFailureDetails(error),
1208
+ diagnostic
1209
+ );
1210
+ await Promise.allSettled([failed.module.runner.stop("shutdown")]);
1211
+ continue;
1212
+ }
1213
+ if (!usedSingletonPreflight) {
1214
+ usedSingletonPreflight = true;
1215
+ parallelCandidates = await this.preflightParallelStartupCandidates(
1216
+ parallelCandidates,
1217
+ signal,
1218
+ diagnostic,
1219
+ generation
1220
+ );
1221
+ continue;
1222
+ }
1223
+ for (const candidate of parallelCandidates) {
1224
+ this.reportModuleFailure(
1225
+ candidate.module.manifest.id,
1226
+ "worker_start",
1227
+ perceptionFailureDetails(error),
1228
+ diagnostic
1229
+ );
1230
+ }
1231
+ await Promise.allSettled(parallelCandidates.map(({ module }) => module.runner.stop("shutdown")));
1232
+ parallelCandidates = [];
1233
+ }
1234
+ }
1235
+ const activeParallelIds = new Set(
1236
+ parallelCandidates.map(({ module }) => module.manifest.id)
1237
+ );
1238
+ const activeModules = startedModules.filter(({ manifest, runner }) => runner.execution === "ordered_update" || activeParallelIds.has(manifest.id));
1239
+ this.assertRunnerLifecycle(generation, signal);
1240
+ this.modules = activeModules;
1241
+ this.moduleTimingWindows.clear();
1242
+ this.moduleTimingWindowStartedAt = performance.now();
1243
+ await this.resetModules("replay", signal, diagnostic);
1244
+ this.assertRunnerLifecycle(generation, signal);
1245
+ this.resetProjection();
1246
+ this.runnersStarted = true;
1247
+ } catch (error) {
1248
+ await analysisPool?.stop();
1249
+ if (this.analysisPool === analysisPool) this.analysisPool = void 0;
1250
+ await Promise.allSettled(this.configuredModules.map(({ runner }) => runner.stop("shutdown")));
1251
+ await this.reducerPool?.stop();
1252
+ if (generation === this.runnerLifecycleGeneration) {
1253
+ await this.moduleLoader.stop();
1254
+ this.modules = [];
1255
+ this.runnersStarted = false;
1256
+ }
1257
+ throw error;
1258
+ }
1259
+ }
1260
+ async preflightParallelStartupCandidates(candidates, signal, diagnostic, generation) {
1261
+ const healthy = [];
1262
+ for (const candidate of candidates) {
1263
+ this.assertRunnerLifecycle(generation, signal);
1264
+ const pool = new PerceptionAnalysisThreadPool({
1265
+ modules: [candidate.threadModule],
1266
+ loader: this.moduleLoader.threadConfig(),
1267
+ spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS,
1268
+ maxWorkers: 1,
1269
+ diagnosticsEnabled: this.diagnosticsEnabled
1270
+ });
1271
+ this.analysisPool = pool;
1272
+ let failure;
1273
+ let failed = false;
1274
+ try {
1275
+ await pool.start();
1276
+ this.assertRunnerLifecycle(generation, signal);
1277
+ } catch (error) {
1278
+ failed = true;
1279
+ failure = error;
1280
+ } finally {
1281
+ await pool.stop().catch(() => {
1282
+ });
1283
+ if (this.analysisPool === pool) this.analysisPool = void 0;
1284
+ }
1285
+ this.assertRunnerLifecycle(generation, signal);
1286
+ if (!failed) {
1287
+ healthy.push(candidate);
1288
+ continue;
1289
+ }
1290
+ this.reportModuleFailure(
1291
+ candidate.module.manifest.id,
1292
+ "worker_start",
1293
+ perceptionFailureDetails(failure),
1294
+ diagnostic
1295
+ );
1296
+ await Promise.allSettled([candidate.module.runner.stop("shutdown")]);
1297
+ }
1298
+ return healthy;
1299
+ }
1300
+ assertRunnerLifecycle(generation, signal) {
1301
+ signal.throwIfAborted();
1302
+ if (generation !== this.runnerLifecycleGeneration) {
1303
+ throw new Error("perception_runners_start_cancelled");
1304
+ }
1305
+ }
1306
+ resetProjection() {
1307
+ this.projector.reset();
1308
+ this.lifecyclePhase = null;
1309
+ this.lastFrameSeq = 0;
1310
+ this.lastFrameTimeMs = null;
1311
+ this.lastVisualTick = null;
1312
+ this.lastVisualFrame = null;
1313
+ this.lastConnectionId = null;
1314
+ this.analysisWindow.length = 0;
1315
+ this.projectedFrameCache.clear();
1316
+ this.replayFromFrameSeq = null;
1317
+ }
1318
+ checkpointValue() {
1319
+ const parallelModuleHistoryFloors = Object.fromEntries(this.modules.flatMap((module) => module.runner.execution === "parallel_analysis" && module.analysisHistoryFloorFrameSeq > 0 ? [[module.manifest.id, module.analysisHistoryFloorFrameSeq]] : []));
1320
+ const parallelModuleReducerReplayStarts = Object.fromEntries(this.modules.flatMap((module) => module.runner.execution === "parallel_analysis" && module.reducerReplayFromFrameSeq !== void 0 ? [[module.manifest.id, module.reducerReplayFromFrameSeq]] : []));
1321
+ const parallelModuleBaselinePending = Object.fromEntries(this.modules.flatMap((module) => module.runner.execution === "parallel_analysis" && (module.analysisHistoryFloorFrameSeq > 0 || module.reducerReplayFromFrameSeq !== void 0) ? [[module.manifest.id, module.analysisBaselinePending]] : []));
1322
+ return {
1323
+ schema: PERCEPTION_CHECKPOINT_SCHEMA,
1324
+ replayFromFrameSeq: this.replayFromFrameSeq,
1325
+ ...Object.keys(parallelModuleHistoryFloors).length === 0 ? {} : { parallelModuleHistoryFloors },
1326
+ ...Object.keys(parallelModuleReducerReplayStarts).length === 0 ? {} : { parallelModuleReducerReplayStarts },
1327
+ ...Object.keys(parallelModuleBaselinePending).length === 0 ? {} : { parallelModuleBaselinePending }
1328
+ };
1329
+ }
1330
+ withOccurredAt(values, timeMs) {
1331
+ const occurredAt = timeMs !== null && Number.isFinite(timeMs) ? new Date(timeMs).toISOString() : void 0;
1332
+ return values.map((proposal) => proposal.occurredAt || !occurredAt ? proposal : { ...proposal, occurredAt });
1333
+ }
1334
+ }
1335
+ export {
1336
+ CLAWCLAW_PERCEPTION_PLUGIN_ID,
1337
+ ClawclawPerceptionPlugin,
1338
+ DEFAULT_MAX_PERCEPTION_BACKFILL_VISUAL_FRAMES,
1339
+ DEFAULT_PERCEPTION_MODULES2 as DEFAULT_PERCEPTION_MODULES,
1340
+ DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS,
1341
+ perceptionManifest,
1342
+ validatePerceptionManifest
1343
+ };