nova-personal-agent-server 0.0.0-stage → 0.4.1

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 (345) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/bin/novapersonal-server.mjs +4 -0
  4. package/package.json +61 -4
  5. package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
  6. package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
  7. package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
  8. package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
  9. package/resources/native/codex-sandbox-probe +0 -0
  10. package/resources/native/project-native/nova_project_native.node +0 -0
  11. package/resources/native-resources-v1.json +1 -0
  12. package/runtime/dist/eval/demos.js +156 -0
  13. package/runtime/dist/eval/fixture-host.js +385 -0
  14. package/runtime/dist/eval/fixtures.js +319 -0
  15. package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
  16. package/runtime/dist/eval/scorecard.js +285 -0
  17. package/runtime/dist/eval/sim.js +43 -0
  18. package/runtime/dist/src/cascaded-text-provider.js +31 -0
  19. package/runtime/dist/src/cli.js +96 -0
  20. package/runtime/dist/src/composition/assembly.js +352 -0
  21. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
  22. package/runtime/dist/src/composition/production-composition.js +389 -0
  23. package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
  24. package/runtime/dist/src/config/capability-registry.js +315 -0
  25. package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
  26. package/runtime/dist/src/config/coding-backends.js +8 -0
  27. package/runtime/dist/src/config/coding-profiles.js +98 -0
  28. package/runtime/dist/src/config/config.js +857 -0
  29. package/runtime/dist/src/config/diagnostics.js +139 -0
  30. package/runtime/dist/src/config/environment-contract.js +202 -0
  31. package/runtime/dist/src/config/self-hosted.js +23 -0
  32. package/runtime/dist/src/connectors/composio/client.js +195 -0
  33. package/runtime/dist/src/connectors/composio/google.js +208 -0
  34. package/runtime/dist/src/connectors/composio/index.js +334 -0
  35. package/runtime/dist/src/connectors/feishu/cli.js +220 -0
  36. package/runtime/dist/src/connectors/feishu/index.js +980 -0
  37. package/runtime/dist/src/connectors/macos/calendar.js +35 -0
  38. package/runtime/dist/src/connectors/macos/mail.js +32 -0
  39. package/runtime/dist/src/connectors/macos/reader.js +62 -0
  40. package/runtime/dist/src/conversation-voice-provider.js +41 -0
  41. package/runtime/dist/src/core/approval-port.js +9 -0
  42. package/runtime/dist/src/core/approval.js +1328 -0
  43. package/runtime/dist/src/core/calls.js +35 -0
  44. package/runtime/dist/src/core/camera-session.js +32 -0
  45. package/runtime/dist/src/core/causal-runtime.js +650 -0
  46. package/runtime/dist/src/core/clock.js +139 -0
  47. package/runtime/dist/src/core/context-view.js +156 -0
  48. package/runtime/dist/src/core/effects.js +62 -0
  49. package/runtime/dist/src/core/events.js +217 -0
  50. package/runtime/dist/src/core/executor-diagnostic.js +9 -0
  51. package/runtime/dist/src/core/ids.js +32 -0
  52. package/runtime/dist/src/core/media-store.js +104 -0
  53. package/runtime/dist/src/core/memory.js +296 -0
  54. package/runtime/dist/src/core/pending-decision.js +64 -0
  55. package/runtime/dist/src/core/ports.js +125 -0
  56. package/runtime/dist/src/core/runtime.js +1459 -0
  57. package/runtime/dist/src/core/schedule-tools.js +15 -0
  58. package/runtime/dist/src/core/sims.js +186 -0
  59. package/runtime/dist/src/core/slots.js +97 -0
  60. package/runtime/dist/src/core/source-processing-instructions.js +3 -0
  61. package/runtime/dist/src/core/source-processing-tools.js +12 -0
  62. package/runtime/dist/src/core/suggestions.js +143 -0
  63. package/runtime/dist/src/core/task-tools.js +22 -0
  64. package/runtime/dist/src/core/tool-schema.js +212 -0
  65. package/runtime/dist/src/core/trace.js +34 -0
  66. package/runtime/dist/src/core/work-tools.js +94 -0
  67. package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
  68. package/runtime/dist/src/desktop/desktop-camera.js +281 -0
  69. package/runtime/dist/src/desktop/desktop-control.js +140 -0
  70. package/runtime/dist/src/desktop/desktop-progress.js +162 -0
  71. package/runtime/dist/src/desktop/desktop-session.js +2106 -0
  72. package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
  73. package/runtime/dist/src/desktop/desktop-wire.js +605 -0
  74. package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
  75. package/runtime/dist/src/desktop/startup-error.js +18 -0
  76. package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
  77. package/runtime/dist/src/desktop-entry.js +106 -0
  78. package/runtime/dist/src/desktop.js +1092 -0
  79. package/runtime/dist/src/executors/acp/backends.js +105 -0
  80. package/runtime/dist/src/executors/acp/mcp.js +81 -0
  81. package/runtime/dist/src/executors/acp/preflight.js +14 -0
  82. package/runtime/dist/src/executors/acp/process-owner.js +112 -0
  83. package/runtime/dist/src/executors/acp/transport.js +760 -0
  84. package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
  85. package/runtime/dist/src/executors/agent-controller.js +244 -0
  86. package/runtime/dist/src/executors/autoglm.js +376 -0
  87. package/runtime/dist/src/executors/browser-device.js +102 -0
  88. package/runtime/dist/src/executors/browser.js +61 -0
  89. package/runtime/dist/src/executors/camera.js +101 -0
  90. package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
  91. package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
  92. package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
  93. package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
  94. package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
  95. package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
  96. package/runtime/dist/src/executors/codex/common.js +655 -0
  97. package/runtime/dist/src/executors/codex/contract.js +581 -0
  98. package/runtime/dist/src/executors/codex/controller.js +141 -0
  99. package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
  100. package/runtime/dist/src/executors/codex/factory.js +463 -0
  101. package/runtime/dist/src/executors/codex/host-config.js +238 -0
  102. package/runtime/dist/src/executors/codex/host.js +17 -0
  103. package/runtime/dist/src/executors/codex/index.js +19 -0
  104. package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
  105. package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
  106. package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
  107. package/runtime/dist/src/executors/codex/process-owner.js +398 -0
  108. package/runtime/dist/src/executors/codex/production-host.js +887 -0
  109. package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
  110. package/runtime/dist/src/executors/codex/protocol.js +581 -0
  111. package/runtime/dist/src/executors/codex/safe-json.js +87 -0
  112. package/runtime/dist/src/executors/codex/session-title.js +61 -0
  113. package/runtime/dist/src/executors/codex/shared-home.js +29 -0
  114. package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
  115. package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
  116. package/runtime/dist/src/executors/codex/version.js +38 -0
  117. package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
  118. package/runtime/dist/src/executors/coding/intake-model.js +103 -0
  119. package/runtime/dist/src/executors/coding/intake.js +824 -0
  120. package/runtime/dist/src/executors/coding/json-completion.js +14 -0
  121. package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
  122. package/runtime/dist/src/executors/coding/work-order.js +50 -0
  123. package/runtime/dist/src/executors/coding-executor.js +23 -0
  124. package/runtime/dist/src/executors/computer-backend.js +188 -0
  125. package/runtime/dist/src/executors/computer-device.js +187 -0
  126. package/runtime/dist/src/executors/computer-worker.js +125 -0
  127. package/runtime/dist/src/executors/computer.js +100 -0
  128. package/runtime/dist/src/executors/device-lock.js +127 -0
  129. package/runtime/dist/src/executors/frame-source.js +29 -0
  130. package/runtime/dist/src/executors/gui-evidence.js +30 -0
  131. package/runtime/dist/src/executors/gui-execution.js +237 -0
  132. package/runtime/dist/src/executors/gui-runner.js +88 -0
  133. package/runtime/dist/src/executors/host-executor-capability.js +12 -0
  134. package/runtime/dist/src/executors/index.js +13 -0
  135. package/runtime/dist/src/executors/mcp-client.js +198 -0
  136. package/runtime/dist/src/executors/mcp.js +210 -0
  137. package/runtime/dist/src/executors/mobile-android.js +180 -0
  138. package/runtime/dist/src/executors/mobile-ios.js +303 -0
  139. package/runtime/dist/src/executors/mobile.js +78 -0
  140. package/runtime/dist/src/executors/search-mcp.js +146 -0
  141. package/runtime/dist/src/executors/search.js +524 -0
  142. package/runtime/dist/src/executors/task-resources.js +38 -0
  143. package/runtime/dist/src/executors/vision/assess.js +296 -0
  144. package/runtime/dist/src/executors/vision/controller-core.js +373 -0
  145. package/runtime/dist/src/executors/vision/controller.js +164 -0
  146. package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
  147. package/runtime/dist/src/executors/vision.js +5 -0
  148. package/runtime/dist/src/executors/watcher.js +718 -0
  149. package/runtime/dist/src/http/bounded-response.js +37 -0
  150. package/runtime/dist/src/index.js +56 -0
  151. package/runtime/dist/src/knowledge/assembly.js +60 -0
  152. package/runtime/dist/src/knowledge/documents.js +520 -0
  153. package/runtime/dist/src/knowledge/embeddings.js +201 -0
  154. package/runtime/dist/src/knowledge/mcp.js +218 -0
  155. package/runtime/dist/src/knowledge/parse-worker.js +122 -0
  156. package/runtime/dist/src/knowledge/references.js +51 -0
  157. package/runtime/dist/src/knowledge/service.js +526 -0
  158. package/runtime/dist/src/knowledge/store-client.js +185 -0
  159. package/runtime/dist/src/knowledge/store-worker.js +843 -0
  160. package/runtime/dist/src/knowledge/types.js +2 -0
  161. package/runtime/dist/src/mcp/http-server.js +177 -0
  162. package/runtime/dist/src/mem0/resource.js +35 -0
  163. package/runtime/dist/src/mem0/store-worker.js +330 -0
  164. package/runtime/dist/src/memory/blackboard-session.js +205 -0
  165. package/runtime/dist/src/memory/blackboard-store.js +194 -0
  166. package/runtime/dist/src/memory/blackboard-worker.js +369 -0
  167. package/runtime/dist/src/memory/entry.js +39 -0
  168. package/runtime/dist/src/memory/factory.js +20 -0
  169. package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
  170. package/runtime/dist/src/memory/personal-memory.js +10 -0
  171. package/runtime/dist/src/memory/prerecall.js +20 -0
  172. package/runtime/dist/src/memory/provenance.js +17 -0
  173. package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
  174. package/runtime/dist/src/memory/retrieval.js +235 -0
  175. package/runtime/dist/src/memory/sensitivity.js +261 -0
  176. package/runtime/dist/src/memory-ledger/models.js +98 -0
  177. package/runtime/dist/src/memory-ledger/store-client.js +210 -0
  178. package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
  179. package/runtime/dist/src/memory-ledger/store.js +597 -0
  180. package/runtime/dist/src/memory-substrate/candidates.js +16 -0
  181. package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
  182. package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
  183. package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
  184. package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
  185. package/runtime/dist/src/memory-substrate/migration.js +87 -0
  186. package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
  187. package/runtime/dist/src/memory-substrate/purge.js +398 -0
  188. package/runtime/dist/src/memory-substrate/resolution.js +32 -0
  189. package/runtime/dist/src/memory-substrate/resource.js +867 -0
  190. package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
  191. package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
  192. package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
  193. package/runtime/dist/src/memory-substrate/source-state.js +93 -0
  194. package/runtime/dist/src/memory-substrate/store.js +534 -0
  195. package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
  196. package/runtime/dist/src/memory-substrate/workspace.js +21 -0
  197. package/runtime/dist/src/model/jev-client.js +25 -0
  198. package/runtime/dist/src/model/model-adapters.js +64 -0
  199. package/runtime/dist/src/model/model-gateway.js +399 -0
  200. package/runtime/dist/src/model/model-lane.js +34 -0
  201. package/runtime/dist/src/model/model-purpose.js +5 -0
  202. package/runtime/dist/src/model/personal-writer.js +361 -0
  203. package/runtime/dist/src/model/proactivity.js +72 -0
  204. package/runtime/dist/src/model/prompting.js +279 -0
  205. package/runtime/dist/src/model/task-verifier.js +217 -0
  206. package/runtime/dist/src/model/vision-capability.js +10 -0
  207. package/runtime/dist/src/news/feeds.js +114 -0
  208. package/runtime/dist/src/news/jev-ranking.js +25 -0
  209. package/runtime/dist/src/news/ranking.js +26 -0
  210. package/runtime/dist/src/news/service.js +262 -0
  211. package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
  212. package/runtime/dist/src/notifications/adapters/nova.js +15 -0
  213. package/runtime/dist/src/notifications/content.js +15 -0
  214. package/runtime/dist/src/notifications/contracts.js +9 -0
  215. package/runtime/dist/src/notifications/feed.js +8 -0
  216. package/runtime/dist/src/notifications/service.js +412 -0
  217. package/runtime/dist/src/notifications/store.js +4 -0
  218. package/runtime/dist/src/personal-agent/app-context.js +113 -0
  219. package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
  220. package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
  221. package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
  222. package/runtime/dist/src/personal-agent/contracts.js +32 -0
  223. package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
  224. package/runtime/dist/src/personal-agent/conversations.js +187 -0
  225. package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2403 -0
  227. package/runtime/dist/src/personal-agent/intake-task.js +37 -0
  228. package/runtime/dist/src/personal-agent/life.js +260 -0
  229. package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
  230. package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
  231. package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
  232. package/runtime/dist/src/personal-agent/project-digests.js +242 -0
  233. package/runtime/dist/src/personal-agent/sampling.js +20 -0
  234. package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
  235. package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
  236. package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
  237. package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
  238. package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
  239. package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
  240. package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
  241. package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
  242. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
  243. package/runtime/dist/src/personal-agent/source-priority.js +142 -0
  244. package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
  245. package/runtime/dist/src/personal-agent/source-walk.js +25 -0
  246. package/runtime/dist/src/personal-agent/sources.js +1484 -0
  247. package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
  248. package/runtime/dist/src/personal-agent/store.js +146 -0
  249. package/runtime/dist/src/personal-agent/task-loop.js +163 -0
  250. package/runtime/dist/src/personal-agent/tasks.js +920 -0
  251. package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
  252. package/runtime/dist/src/personal-agent/understanding.js +160 -0
  253. package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
  254. package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
  255. package/runtime/dist/src/projects/host-paths.js +133 -0
  256. package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
  257. package/runtime/dist/src/projects/project-confirmation.js +486 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +284 -0
  259. package/runtime/dist/src/projects/project-node-files.js +169 -0
  260. package/runtime/dist/src/projects/project-root-file.js +16 -0
  261. package/runtime/dist/src/projects/project-state.js +504 -0
  262. package/runtime/dist/src/projects/project-store-files.js +1271 -0
  263. package/runtime/dist/src/projects/project-store.js +1345 -0
  264. package/runtime/dist/src/realtime/aoq.js +141 -0
  265. package/runtime/dist/src/realtime/bridge.js +652 -0
  266. package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
  267. package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
  268. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
  269. package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
  270. package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
  271. package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
  272. package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
  273. package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
  274. package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
  275. package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
  276. package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
  277. package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
  278. package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
  279. package/runtime/dist/src/realtime/dictation.js +28 -0
  280. package/runtime/dist/src/realtime/evidence.js +276 -0
  281. package/runtime/dist/src/realtime/floor.js +43 -0
  282. package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
  283. package/runtime/dist/src/realtime/gemini.js +517 -0
  284. package/runtime/dist/src/realtime/history.js +122 -0
  285. package/runtime/dist/src/realtime/host-delivery.js +1711 -0
  286. package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
  287. package/runtime/dist/src/realtime/memory-board.js +105 -0
  288. package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
  289. package/runtime/dist/src/realtime/playback.js +242 -0
  290. package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
  291. package/runtime/dist/src/realtime/prompt-language.js +17 -0
  292. package/runtime/dist/src/realtime/protocol.js +428 -0
  293. package/runtime/dist/src/realtime/provider-projection.js +526 -0
  294. package/runtime/dist/src/realtime/provider-session.js +491 -0
  295. package/runtime/dist/src/realtime/qwen-transport.js +144 -0
  296. package/runtime/dist/src/realtime/qwen.js +1377 -0
  297. package/runtime/dist/src/realtime/recall.js +341 -0
  298. package/runtime/dist/src/realtime/service-ports.js +8 -0
  299. package/runtime/dist/src/realtime/service-state.js +259 -0
  300. package/runtime/dist/src/realtime/service.js +1726 -0
  301. package/runtime/dist/src/realtime/session-state.js +684 -0
  302. package/runtime/dist/src/realtime/session.js +1976 -0
  303. package/runtime/dist/src/realtime/speech-prep.js +63 -0
  304. package/runtime/dist/src/realtime/streaming-speech.js +120 -0
  305. package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
  306. package/runtime/dist/src/realtime/telemetry.js +144 -0
  307. package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
  308. package/runtime/dist/src/realtime/transport.js +8 -0
  309. package/runtime/dist/src/realtime/usage.js +55 -0
  310. package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
  311. package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
  312. package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
  313. package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
  314. package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
  315. package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
  316. package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
  317. package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
  318. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
  319. package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
  320. package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
  321. package/runtime/dist/src/server/aoq-chat-server.js +497 -0
  322. package/runtime/dist/src/server/client-pairing.js +192 -0
  323. package/runtime/dist/src/server/client-protocol.js +87 -0
  324. package/runtime/dist/src/server/client-server.js +312 -0
  325. package/runtime/dist/src/server/server-config.js +72 -0
  326. package/runtime/dist/src/server-entry.js +135 -0
  327. package/runtime/dist/src/storage/bounded-json.js +63 -0
  328. package/runtime/dist/src/storage/native-file-lock.js +8 -0
  329. package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
  330. package/runtime/dist/src/storage/private-database.js +120 -0
  331. package/runtime/dist/src/text/canonical-json.js +60 -0
  332. package/runtime/dist/src/text/python-number.js +18 -0
  333. package/runtime/dist/src/text/python-text.js +92 -0
  334. package/runtime/dist/src/text/unicode-casefold.js +29 -0
  335. package/runtime/dist/src/text/unicode-normalize.js +138 -0
  336. package/runtime/dist/src/text/unicode-tables.js +210 -0
  337. package/runtime/dist/src/understanding/candidates.js +77 -0
  338. package/runtime/dist/src/understanding/fixture.js +7 -0
  339. package/runtime/dist/src/understanding/jev.js +20 -0
  340. package/runtime/dist/src/understanding/pipeline.js +38 -0
  341. package/runtime/dist/src/voicemem/store-client.js +476 -0
  342. package/runtime/dist/src/voicemem/store-worker.js +380 -0
  343. package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
  344. package/runtime/scripts/pair-device.mjs +109 -0
  345. package/src/command.mjs +48 -0
@@ -0,0 +1,920 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
4
+ import { taskDecisionSchema } from './task-loop.js';
5
+ import { canonicalJson } from '../text/canonical-json.js';
6
+ const eventSchema = z.object({
7
+ thread_id: z.string().min(1).max(512).optional(), turn_id: z.string().min(1).max(512).optional(), item_id: z.string().min(1).max(512).optional(), stage: z.enum(['started', 'completed']).optional(), seq: z.number().int().positive(), task_id: z.string().min(1).max(512), work_id: z.string().min(1).max(512).optional(), session_id: z.string().min(1).max(512).optional(), kind: z.enum(['message', 'tool', 'artifact', 'control', 'verification', 'status']), sender: z.enum(['nova', 'user-to-executor', 'executor']).optional(), text: z.string().max(16000), refs: z.array(z.string().min(1).max(512)).max(128), text_truncated: z.boolean().optional()
8
+ }).strict().refine(event => event.kind !== 'message' || event.sender !== undefined, 'message_sender_required');
9
+ const id = z.string().trim().min(1).max(512);
10
+ export const taskTriggerSchema = z.object({ kind: z.literal('schedule'), schedule_id: id, run_id: id, definition_revision: z.number().int().positive(), definition_hash: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
11
+ export const taskInputSchema = z.object({
12
+ execution_route: id.optional(), conversation_generation: z.number().int().nonnegative().optional(), conversation_id: id, goal: z.string().trim().min(1).max(16000), acceptance: z.array(z.string().trim().min(1).max(2000)).max(64), origin_ref: id, todo_ref: z.object({ id, version: z.number().int().nonnegative() }).strict().optional()
13
+ }).strict();
14
+ export const internalTaskInputSchema = taskInputSchema.extend({ trigger: taskTriggerSchema.optional() }).strict().refine(input => !input.trigger || (input.origin_ref === 'schedule-run:' + input.trigger.run_id && input.conversation_id === 'schedule:' + input.trigger.schedule_id && input.conversation_generation === 0), 'invalid_schedule_origin');
15
+ const actorSchema = z.union([z.object({ kind: z.literal('nova') }).strict(), z.object({ kind: z.literal('user'), client_id: id }).strict()]);
16
+ export const taskFenceSchema = z.object({
17
+ task_id: id, control_revision: z.number().int().nonnegative(), goal_revision: z.number().int().nonnegative()
18
+ }).strict();
19
+ const goalSchema = taskInputSchema.pick({ goal: true, acceptance: true });
20
+ const controlChangeSchema = z.object({ fence: taskFenceSchema, actor: actorSchema, nextActor: actorSchema }).strict();
21
+ const goalChangeSchema = z.object({
22
+ fence: taskFenceSchema, actor: actorSchema, goal: goalSchema.shape.goal, acceptance: goalSchema.shape.acceptance
23
+ }).strict();
24
+ const recordSchema = taskInputSchema.extend({ trigger: taskTriggerSchema.optional(),
25
+ reconciled_inputs: z.array(id).default([]), pending_delivery: id.optional(), original_goal: z.string().optional(), execution_route: z.string().optional(), id, phase: z.enum(['queued', 'running', 'verifying', 'waiting', 'completed', 'cancelled']), controller: actorSchema, control_revision: z.number().int().nonnegative(), goal_revision: z.number().int().nonnegative(), corrections: z.number().int().nonnegative(), work_ids: z.array(id), session_ids: z.array(id), works: z.array(z.object({ work_id: id, executor: id, session_id: id.optional(), target: id.optional() }).strict()).default([]), primary_session_id: id.optional(), evidence_refs: z.array(id), criteria_evidence: z.array(z.object({ index: z.number().int().nonnegative(), evidence_refs: z.array(id) }).strict()).optional(), artifact_refs: z.array(id).default([]), waiting_reason: z.string().trim().min(1).max(4000).nullable(), todo_sync: z.enum(['none', 'pending', 'synced', 'conflict'])
26
+ }).strict();
27
+ const evidenceSchema = z.object({
28
+ observations: z.array(eventSchema).max(32).default([]), observations_truncated: z.boolean().default(false), ref: id, task_id: id, goal_revision: z.number().int().nonnegative(), kind: z.enum(['work', 'delivery', 'input', 'context']), work_id: id.optional(), outcome: z.string(), content: z.string().max(131072), refs: z.array(id).max(128)
29
+ }).strict();
30
+ const pendingSchema = z.object({
31
+ id, task_id: id, fence: taskFenceSchema, instruction: z.string().max(16000), write_started: z.boolean().optional(), status: z.enum(['pending', 'accepted', 'failed', 'unknown'])
32
+ }).strict();
33
+ const stateSchema = z.object({
34
+ run_receipts: z.record(z.string(), z.object({ hash: z.string(), task_id: id }).strict()).default({}),
35
+ instruction_work_ids: z.array(id).default([]), outcomes: z.array(evidenceSchema).default([]), work_fences: z.record(z.string(), taskFenceSchema).default({}), pending_effects: z.record(z.string(), pendingSchema).default({}), replay_incomplete: z.array(id).default([]), events: z.array(eventSchema).default([]), event_keys: z.record(z.string(), z.object({ seq: z.number().int().positive(), hash: z.string(), task_id: id.optional() }).strict()).default({}), event_seq: z.number().int().nonnegative().default(0), truncated: z.record(z.string(), z.number().int().nonnegative()).default({}), effects: z.record(z.string(), z.object({
36
+ hash: z.string(), status: z.enum(['accepted', 'failed', 'unknown']), task_id: id.optional(), session_id: id.optional(), fence: taskFenceSchema.optional(), actor: actorSchema.optional(), text: z.string().max(16000).optional()
37
+ }).strict()).default({}), tasks: z.array(recordSchema), receipts: z.record(z.string(), z.object({ hash: z.string(), task_id: id, result: recordSchema.optional() }).strict()), handbacks: z.record(z.string(), z.object({ hash: z.string(), command: z.string().max(16384).optional(), result: z.array(recordSchema).optional() }).strict()).default({})
38
+ }).strict();
39
+ const RETAINED_FINISHED_TASKS = 200, RETAINED_HANDBACKS = 256, RETAINED_TOMBSTONES = 20000, PRUNE_ABOVE_BYTES = 12 * 1024 * 1024, PRUNE_TO_BYTES = 8 * 1024 * 1024;
40
+ const empty = () => ({
41
+ run_receipts: {},
42
+ instruction_work_ids: [], outcomes: [], work_fences: {}, pending_effects: {}, replay_incomplete: [], events: [], event_keys: {}, event_seq: 0, truncated: {}, tasks: [], receipts: {}, handbacks: {}, effects: {}
43
+ });
44
+ const hash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
45
+ const sameGoal = (task, goal, acceptance) => task.goal === goal && task.acceptance.length === acceptance.length && task.acceptance.every((criterion, index) => criterion === acceptance[index]);
46
+ const grants = new WeakMap();
47
+ export function taskGrantService(context) {
48
+ const grant = grants.get(context);
49
+ if (!grant)
50
+ throw Error('invalid_continuation');
51
+ grant.tasks.assertExecutionAllowed(context.fence.task_id, grant.actor);
52
+ grant.tasks.assertWritable(context.fence, grant.actor);
53
+ if (grant.tasks.get(context.fence.task_id).origin_ref !== context.origin_ref)
54
+ throw Error('invalid_origin_ref');
55
+ return grant.tasks;
56
+ }
57
+ export class TaskService {
58
+ path;
59
+ changed;
60
+ admitExecution;
61
+ #grants = new WeakSet();
62
+ #incompleteReplay = new Set();
63
+ continuationContext(fence) { return this.instructionContext(fence, { kind: 'nova' }); }
64
+ instructionContext(fence, actor) {
65
+ fence = Object.freeze(taskFenceSchema.parse(fence));
66
+ actor = Object.freeze(actorSchema.parse(actor));
67
+ this.assertExecutionAllowed(fence.task_id, actor);
68
+ this.assertWritable(fence, actor);
69
+ const context = Object.freeze({
70
+ fence, origin_ref: this.get(fence.task_id).origin_ref, stillWanted: () => {
71
+ try {
72
+ this.assertExecutionAllowed(fence.task_id, actor);
73
+ this.assertWritable(fence, actor);
74
+ return true;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ });
81
+ this.#grants.add(context);
82
+ grants.set(context, { tasks: this, actor: structuredClone(actor) });
83
+ return context;
84
+ }
85
+ validateContinuation(context) {
86
+ if (!this.#grants.has(context))
87
+ throw Error('invalid_continuation');
88
+ this.assertExecutionAllowed(context.fence.task_id, { kind: 'nova' });
89
+ this.assertWritable(context.fence, { kind: 'nova' });
90
+ if (context.origin_ref !== this.get(context.fence.task_id).origin_ref)
91
+ throw Error('invalid_origin_ref');
92
+ }
93
+ assertWritable(fence, actor) {
94
+ this.assertCurrent(fence, actor);
95
+ const task = this.get(fence.task_id);
96
+ if (task.phase === 'completed' || task.phase === 'cancelled')
97
+ throw Error('task_terminal');
98
+ }
99
+ #store;
100
+ #state = empty();
101
+ #tail = Promise.resolve();
102
+ constructor(path, changed = () => { }, admitExecution = () => { }) {
103
+ this.path = path;
104
+ this.changed = changed;
105
+ this.admitExecution = admitExecution;
106
+ this.#store = new BoundedJsonStore(path, stateSchema, 16 * 1024 * 1024);
107
+ }
108
+ async open() {
109
+ try {
110
+ this.#state = await this.#store.read(empty());
111
+ for (const task of this.#state.tasks)
112
+ task.original_goal ??= Object.values(this.#state.receipts).find(receipt => receipt.task_id === task.id && receipt.result?.goal_revision === 0)?.result?.goal ?? (task.goal_revision === 0 ? task.goal : 'Original goal unavailable');
113
+ }
114
+ catch (error) {
115
+ if (error.code !== 'ENOENT')
116
+ throw error;
117
+ }
118
+ if (Object.values(this.#state.pending_effects).some(effect => effect.status === 'pending') || this.#state.tasks.some(task => task.work_ids.some(work => !this.#state.work_fences[work])))
119
+ await this.#mutate(next => {
120
+ for (const effect of Object.values(next.pending_effects))
121
+ if (effect.status === 'pending')
122
+ effect.status = effect.write_started === false ? 'failed' : 'unknown';
123
+ for (const task of next.tasks)
124
+ if (task.work_ids.some(work => !next.work_fences[work]) && task.phase !== 'completed' && task.phase !== 'cancelled') {
125
+ task.phase = 'waiting';
126
+ task.waiting_reason = 'work_fence_unavailable';
127
+ }
128
+ });
129
+ }
130
+ cancel(requestId, fence, actor) {
131
+ return this.#change(requestId, { fence: taskFenceSchema.parse(fence), actor: actorSchema.parse(actor), operation: 'cancel' }, task => {
132
+ if (task.phase === 'completed')
133
+ throw Error('task_terminal');
134
+ task.phase = 'cancelled';
135
+ task.waiting_reason = this.hasUnresolvedExecution(task.id) ? 'cancellation_pending' : null;
136
+ }, task => this.#assertDecider(task, fence, actor, false));
137
+ }
138
+ #liveInputs = new Set();
139
+ #liveDeliveries = new Set();
140
+ async input(requestId, fence, actor, sessionId, text, send) {
141
+ const request = id.parse(requestId), session = id.parse(sessionId), instruction = z.string().trim().min(1).max(16000).parse(text), body = hash({ fence, actor, session, instruction });
142
+ const prior = await this.#mutate(next => {
143
+ const receipt = next.effects[request];
144
+ if (receipt) {
145
+ if (receipt.hash !== body)
146
+ throw Error('request_conflict');
147
+ return receipt.status;
148
+ }
149
+ this.assertExecutionAllowed(fence.task_id);
150
+ this.assertWritable(fence, actor);
151
+ if (!this.get(fence.task_id).session_ids.includes(session))
152
+ throw Error('session_not_found');
153
+ next.effects[request] = {
154
+ hash: body, status: 'unknown', task_id: fence.task_id, session_id: session, fence: { ...fence }, actor: { ...actor }, text: instruction
155
+ };
156
+ next.events.push({
157
+ seq: ++next.event_seq, task_id: fence.task_id, session_id: session, kind: 'message', sender: actor.kind === 'user' ? 'user-to-executor' : 'nova', text: instruction, refs: []
158
+ });
159
+ return null;
160
+ });
161
+ if (prior)
162
+ return prior;
163
+ let status = 'unknown';
164
+ let grant;
165
+ try {
166
+ grant = this.instructionContext(fence, actor);
167
+ }
168
+ catch {
169
+ status = 'failed';
170
+ }
171
+ this.#liveInputs.add(request);
172
+ try {
173
+ if (grant)
174
+ try {
175
+ status = await send(grant);
176
+ }
177
+ catch {
178
+ status = 'unknown';
179
+ }
180
+ await this.#mutate(next => {
181
+ next.effects[request] = { ...next.effects[request], hash: body, status };
182
+ next.events.push({
183
+ seq: ++next.event_seq, task_id: fence.task_id, session_id: session, kind: 'control', text: 'Input delivery: ' + status, refs: []
184
+ });
185
+ // A handback can land while the send is in flight; the executor still got the message, so say so in the activity feed.
186
+ const now = next.tasks.find(task => task.id === fence.task_id);
187
+ if (status === 'accepted' && now && now.control_revision !== fence.control_revision)
188
+ next.events.push({
189
+ seq: ++next.event_seq, task_id: fence.task_id, session_id: session, kind: 'control', text: JSON.stringify({ operation: 'input_before_handback', control_revision: now.control_revision }), refs: []
190
+ });
191
+ });
192
+ return status;
193
+ }
194
+ finally {
195
+ this.#liveInputs.delete(request);
196
+ }
197
+ }
198
+ async close() { await this.#tail; }
199
+ get(taskId) {
200
+ const task = this.#state.tasks.find(item => item.id === id.parse(taskId));
201
+ if (!task)
202
+ throw Error('task_not_found');
203
+ return structuredClone(task);
204
+ }
205
+ appendEvent(event, sourceKey) {
206
+ const key = hash({ task: event.task_id, source: z.string().min(1).max(2048).parse(sourceKey) }), text = event.text.slice(0, 16000);
207
+ const parsed = eventSchema.parse({ ...event, text, ...(event.text.length > 16000 ? { text_truncated: true } : {}), seq: 1 });
208
+ return this.#mutate(next => {
209
+ const task = next.tasks.find(task => task.id === parsed.task_id);
210
+ if (!task)
211
+ throw Error('task_not_found');
212
+ if (parsed.work_id && !task.work_ids.includes(parsed.work_id))
213
+ throw Error('work_not_found');
214
+ if (parsed.session_id && !task.session_ids.includes(parsed.session_id))
215
+ throw Error('session_not_found');
216
+ const body = hash(parsed), prior = next.event_keys[key];
217
+ if (prior) {
218
+ if (prior.hash !== body)
219
+ throw Error('event_conflict');
220
+ return { ...parsed, seq: prior.seq };
221
+ }
222
+ const item = { ...parsed, seq: ++next.event_seq };
223
+ next.events.push(item);
224
+ next.event_keys[key] = { seq: item.seq, hash: body, task_id: parsed.task_id };
225
+ for (const ref of item.refs)
226
+ if (!task.artifact_refs.includes(ref))
227
+ task.artifact_refs.push(ref);
228
+ return structuredClone(item);
229
+ });
230
+ }
231
+ markReplayIncomplete(taskId) {
232
+ this.get(taskId);
233
+ this.#incompleteReplay.add(taskId);
234
+ try {
235
+ this.changed();
236
+ }
237
+ catch { /* notification failure cannot change executor outcome */ }
238
+ }
239
+ events(taskId, after) {
240
+ this.get(taskId);
241
+ z.number().int().nonnegative().parse(after);
242
+ const items = this.#state.events.filter(event => event.task_id === taskId && event.seq > after).slice(0, 100);
243
+ return {
244
+ incomplete: this.#incompleteReplay.has(taskId) || this.#state.replay_incomplete.includes(taskId), items: structuredClone(items), next: items.at(-1)?.seq ?? after, truncated: (this.#state.truncated[taskId] ?? 0) > after
245
+ };
246
+ }
247
+ inputReceipts(taskId) {
248
+ return Object.entries(this.#state.effects).filter(([, receipt]) => receipt.task_id === taskId).map(([request_id, receipt]) => ({ request_id, ...structuredClone(receipt) }));
249
+ }
250
+ list() { return structuredClone(this.#state.tasks); }
251
+ findByRun(runId) {
252
+ const receipt = this.#state.run_receipts[id.parse(runId)];
253
+ if (!receipt)
254
+ return null;
255
+ const task = this.#state.tasks.find(item => item.id === receipt.task_id);
256
+ if (!task)
257
+ throw Error('task_retired');
258
+ return structuredClone(task);
259
+ }
260
+ delegate(requestId, input) {
261
+ const request = id.parse(requestId), parsed = internalTaskInputSchema.parse(input), payload = hash(parsed);
262
+ return this.#mutate(next => {
263
+ if (parsed.trigger) {
264
+ const prior = next.run_receipts[parsed.trigger.run_id];
265
+ if (prior) {
266
+ if (prior.hash !== payload)
267
+ throw Error('run_conflict');
268
+ const task = next.tasks.find(item => item.id === prior.task_id);
269
+ if (!task)
270
+ throw Error('task_retired');
271
+ return structuredClone(task);
272
+ }
273
+ if (Object.keys(next.run_receipts).length >= RETAINED_TOMBSTONES)
274
+ throw Error('task_capacity');
275
+ }
276
+ const prior = next.receipts[request];
277
+ if (prior) {
278
+ if (prior.hash !== payload)
279
+ throw Error('request_conflict');
280
+ if (!prior.result)
281
+ throw Error('task_retired');
282
+ return structuredClone(prior.result);
283
+ }
284
+ const task = {
285
+ ...(parsed.trigger ? { trigger: parsed.trigger } : {}), reconciled_inputs: [], works: [], ...(parsed.execution_route ? { execution_route: parsed.execution_route } : {}), original_goal: parsed.goal, ...(parsed.conversation_generation === undefined ? {} : { conversation_generation: parsed.conversation_generation }), conversation_id: parsed.conversation_id, goal: parsed.goal, acceptance: parsed.acceptance, origin_ref: parsed.origin_ref, ...(parsed.todo_ref ? { todo_ref: parsed.todo_ref } : {}), id: randomUUID(), phase: 'queued', controller: { kind: 'nova' }, control_revision: 0, goal_revision: 0, corrections: 0, work_ids: [], session_ids: [], evidence_refs: [], artifact_refs: [], waiting_reason: null, todo_sync: 'none'
286
+ };
287
+ next.tasks.push(task);
288
+ next.receipts[request] = { hash: payload, task_id: task.id, result: structuredClone(task) };
289
+ if (parsed.trigger)
290
+ next.run_receipts[parsed.trigger.run_id] = { hash: payload, task_id: task.id };
291
+ return structuredClone(task);
292
+ });
293
+ }
294
+ control(requestId, fence, actor, nextActor) {
295
+ const parsed = controlChangeSchema.parse({ fence, actor, nextActor });
296
+ return this.#change(requestId, parsed, task => { task.controller = parsed.nextActor; task.control_revision++; });
297
+ }
298
+ returnFromUserOrigin(requestId, fence, provenance, stillWanted) {
299
+ const request = id.parse(requestId), parsed = {
300
+ fence: taskFenceSchema.parse(fence), provenance: z.object({ conversation_id: id, conversation_generation: z.number().int().nonnegative(), origin_ref: id }).strict().parse(provenance), operation: 'user_origin_return'
301
+ }, body = hash(parsed);
302
+ return this.#mutate(next => {
303
+ const prior = next.receipts[request];
304
+ if (prior) {
305
+ if (prior.hash !== body)
306
+ throw Error('request_conflict');
307
+ if (!prior.result)
308
+ throw Error('task_retired');
309
+ return structuredClone(prior.result);
310
+ }
311
+ if (!stillWanted())
312
+ throw Error('superseded');
313
+ const task = next.tasks.find(task => task.id === parsed.fence.task_id);
314
+ if (!task)
315
+ throw Error('task_not_found');
316
+ this.#assertFence(task, parsed.fence);
317
+ if (task.conversation_id !== parsed.provenance.conversation_id)
318
+ throw Error('task_not_owned');
319
+ task.controller = { kind: 'nova' };
320
+ task.control_revision++;
321
+ next.events.push({ seq: ++next.event_seq, task_id: task.id, kind: 'control', text: 'Control returned to Nova', refs: [] });
322
+ const result = structuredClone(task);
323
+ next.receipts[request] = { hash: body, task_id: task.id, result };
324
+ return result;
325
+ });
326
+ }
327
+ reservePresentationRequest(requestId, clientId, command) {
328
+ const request = id.parse(requestId), body = hash({ client: id.parse(clientId) }), identity = z.string().min(1).max(16384).parse(command);
329
+ return this.#mutate(next => {
330
+ const prior = next.handbacks[request];
331
+ if (prior) {
332
+ if (prior.hash !== body || prior.command !== identity)
333
+ throw Error('request_conflict');
334
+ return;
335
+ }
336
+ next.handbacks[request] = { hash: body, command: identity };
337
+ });
338
+ }
339
+ returnClientTasks(requestId, clientId) {
340
+ const request = id.parse(requestId), client = id.parse(clientId), body = hash({ client });
341
+ return this.#mutate(next => {
342
+ const prior = next.handbacks[request];
343
+ if (prior) {
344
+ if (prior.hash !== body)
345
+ throw Error('request_conflict');
346
+ if (prior.result)
347
+ return structuredClone(prior.result);
348
+ }
349
+ const result = next.tasks.filter(task => task.controller.kind === 'user' && task.controller.client_id === client);
350
+ for (const task of result) {
351
+ task.controller = { kind: 'nova' };
352
+ task.control_revision++;
353
+ next.events.push({ seq: ++next.event_seq, task_id: task.id, kind: 'control', text: 'Control returned to Nova', refs: [] });
354
+ }
355
+ next.handbacks[request] = { ...prior, hash: body, result: structuredClone(result) };
356
+ return structuredClone(result);
357
+ });
358
+ }
359
+ controlClient(requestId, fence, clientId, action) {
360
+ const parsed = {
361
+ fence: taskFenceSchema.parse(fence), actor: actorSchema.parse({ kind: 'user', client_id: clientId }), action: z.enum(['takeover', 'return']).parse(action)
362
+ };
363
+ return this.#change(requestId, parsed, task => {
364
+ task.controller = parsed.action === 'takeover' ? parsed.actor : { kind: 'nova' };
365
+ task.control_revision++;
366
+ }, task => {
367
+ this.#assertFence(task, parsed.fence);
368
+ if (parsed.action === 'takeover' && task.controller.kind === 'user' && task.controller.client_id !== clientId)
369
+ throw Error('not_controller');
370
+ });
371
+ }
372
+ assertCurrent(fence, actor) {
373
+ const parsed = taskFenceSchema.parse(fence), task = this.#state.tasks.find(item => item.id === parsed.task_id);
374
+ if (!task)
375
+ throw Error('task_not_found');
376
+ this.#assert(task, parsed, actorSchema.parse(actor));
377
+ }
378
+ bindWork(fence, workId, sessionId, primary = true, targetId) {
379
+ const parsed = taskFenceSchema.parse(fence), work = id.parse(workId), session = sessionId === undefined ? undefined : id.parse(sessionId);
380
+ return this.#mutate(next => {
381
+ const task = next.tasks.find(item => item.id === parsed.task_id);
382
+ if (!task)
383
+ throw Error('task_not_found');
384
+ this.#assertFence(task, parsed);
385
+ if (task.phase === 'completed' || task.phase === 'cancelled')
386
+ throw Error('task_terminal');
387
+ const active = (item) => item.phase !== 'completed' && item.phase !== 'cancelled';
388
+ if (next.tasks.some(item => item.id !== task.id && active(item) && item.work_ids.includes(work)))
389
+ throw Error('work_active');
390
+ if (session)
391
+ for (const previous of next.tasks.filter(item => item.id !== task.id && item.session_ids.includes(session))) {
392
+ // An unfinished task keeps its session even between works, so its corrections continue where they started.
393
+ if (active(previous) || this.hasUnresolvedExecution(previous.id))
394
+ throw Error('session_active');
395
+ previous.session_ids = previous.session_ids.filter(id => id !== session);
396
+ if (previous.primary_session_id === session)
397
+ delete previous.primary_session_id;
398
+ }
399
+ if (task.phase === 'queued' || task.phase === 'waiting') {
400
+ task.phase = 'running';
401
+ task.waiting_reason = null;
402
+ }
403
+ if (!primary && !next.instruction_work_ids.includes(work))
404
+ next.instruction_work_ids.push(work);
405
+ next.work_fences[work] ??= parsed;
406
+ if (!task.work_ids.includes(work))
407
+ task.work_ids.push(work);
408
+ if (session && !task.session_ids.includes(session))
409
+ task.session_ids.push(session);
410
+ // Each work runs on exactly one executor session; the first bound session is where continuations go by default.
411
+ const entry = task.works.find(item => item.work_id === work) ?? (task.works.push({ work_id: work, executor: task.execution_route ?? 'unknown' }), task.works.at(-1));
412
+ if (targetId !== undefined) {
413
+ const target = id.parse(targetId);
414
+ if (entry.target && entry.target !== target)
415
+ throw Error('work_target_conflict');
416
+ entry.target = target;
417
+ }
418
+ if (session) {
419
+ if (entry.session_id && entry.session_id !== session)
420
+ throw Error('work_session_conflict');
421
+ entry.session_id = session;
422
+ if (!task.primary_session_id || !task.session_ids.includes(task.primary_session_id))
423
+ task.primary_session_id = session;
424
+ }
425
+ });
426
+ }
427
+ reviseGoal(requestId, fence, actor, goal, acceptance) {
428
+ const parsed = goalChangeSchema.parse({ fence, actor, goal, acceptance });
429
+ return this.#change(requestId, parsed, task => {
430
+ if (task.phase === 'completed' || task.phase === 'cancelled')
431
+ throw Error('task_terminal');
432
+ if (!sameGoal(task, parsed.goal, parsed.acceptance)) {
433
+ task.goal = parsed.goal;
434
+ task.acceptance = parsed.acceptance;
435
+ task.goal_revision++;
436
+ }
437
+ });
438
+ }
439
+ setRoute(fence, route) {
440
+ return this.#mutate(next => {
441
+ this.assertWritable(fence, { kind: 'nova' });
442
+ next.tasks.find(task => task.id === fence.task_id).execution_route = id.parse(route);
443
+ });
444
+ }
445
+ evidence(taskId) {
446
+ this.get(taskId);
447
+ return structuredClone(this.#state.outcomes.filter(item => item.task_id === taskId));
448
+ }
449
+ recordContextEvidence(fence, readId, content, refs) {
450
+ const ref = 'task-context:' + id.parse(readId), parsed = evidenceSchema.parse({ ref, task_id: fence.task_id, goal_revision: fence.goal_revision, kind: 'context', outcome: 'observed', content, refs });
451
+ return this.#mutate(next => {
452
+ this.assertWritable(fence, { kind: 'nova' });
453
+ this.assertExecutionAllowed(fence.task_id, { kind: 'nova' });
454
+ const prior = next.outcomes.find(item => item.ref === ref);
455
+ if (prior) {
456
+ if (hash(prior) !== hash(parsed))
457
+ throw Error('context_evidence_conflict');
458
+ return ref;
459
+ }
460
+ next.outcomes.push(parsed);
461
+ const task = next.tasks.find(item => item.id === fence.task_id);
462
+ if (!task.evidence_refs.includes(ref))
463
+ task.evidence_refs.push(ref);
464
+ return ref;
465
+ });
466
+ }
467
+ assertExecutionAllowed(taskId, actor) {
468
+ this.get(taskId);
469
+ this.admitExecution(taskId);
470
+ if (this.hasUnknownWork(taskId))
471
+ throw Error('task_effect_unknown');
472
+ if (actor?.kind === 'nova' && this.pendingUserInputs(taskId).length)
473
+ throw Error('task_input_reconciliation_required');
474
+ }
475
+ hasUnknownWork(taskId) {
476
+ return this.#state.outcomes.some(item => item.task_id === taskId && item.work_id && !['ok', 'failed', 'refused', 'cancelled'].includes(item.outcome));
477
+ }
478
+ acceptedUserInputs(taskId) {
479
+ return this.inputReceipts(taskId).filter(receipt => receipt.status === 'accepted' && receipt.actor?.kind === 'user');
480
+ }
481
+ pendingUserInputs(taskId) {
482
+ const task = this.get(taskId);
483
+ return this.acceptedUserInputs(taskId).filter(receipt => !task.reconciled_inputs?.includes(receipt.request_id));
484
+ }
485
+ hasUnresolvedExecution(taskId) {
486
+ const task = this.get(taskId);
487
+ return !!task.pending_delivery || this.pendingEffect(taskId) !== null || this.inputReceipts(taskId).some(receipt => receipt.status === 'unknown') || task.work_ids.some(work => !this.#state.outcomes.some(item => item.task_id === taskId && item.work_id === work && ['ok', 'failed', 'refused', 'cancelled'].includes(item.outcome)));
488
+ }
489
+ activeWork(taskId) {
490
+ return this.get(taskId).work_ids.filter(work => !this.#state.outcomes.some(item => item.task_id === taskId && item.work_id === work));
491
+ }
492
+ pendingEffect(taskId) {
493
+ return structuredClone(Object.values(this.#state.pending_effects).find(item => item.task_id === taskId && (item.status === 'pending' || item.status === 'unknown')) ?? null);
494
+ }
495
+ async recordWorkOutcome(workId, outcome, content, refs = []) {
496
+ return this.#mutate(next => {
497
+ const task = next.tasks.find(task => task.work_ids.includes(workId));
498
+ if (!task)
499
+ return null;
500
+ const ref = 'task-work:' + workId, prior = next.outcomes.find(item => item.ref === ref);
501
+ if (prior)
502
+ return ref;
503
+ const workFence = next.work_fences[workId];
504
+ if (!workFence)
505
+ throw Error('work_fence_unavailable');
506
+ const observed = next.events.filter(event => event.work_id === workId && event.task_id === task.id && event.kind === 'tool' && event.stage === 'completed');
507
+ let bytes = 0;
508
+ const observations = observed.slice(-32).reverse().filter(event => { bytes += Buffer.byteLength(JSON.stringify(event)); return bytes <= 65536; }).reverse();
509
+ next.outcomes.push(evidenceSchema.parse({
510
+ observations, observations_truncated: observations.length < observed.length || observations.some(event => event.text_truncated) || !!next.truncated[task.id] || this.#incompleteReplay.has(task.id) || next.replay_incomplete.includes(task.id), ref, task_id: task.id, goal_revision: workFence.goal_revision, kind: next.instruction_work_ids.includes(workId) ? 'input' : 'work', work_id: workId, outcome, content: JSON.stringify(content).slice(0, 131072), refs
511
+ }));
512
+ return ref;
513
+ });
514
+ }
515
+ recordDelivery(fence, deliveryId, text, outcome = 'delivered') {
516
+ return this.#mutate(next => {
517
+ this.assertWritable(fence, { kind: 'nova' });
518
+ const task = next.tasks.find(task => task.id === fence.task_id);
519
+ task.execution_route ??= 'nova';
520
+ const ref = 'task-delivery:' + id.parse(deliveryId);
521
+ const prior = next.outcomes.find(item => item.ref === ref);
522
+ if (prior) {
523
+ if (prior.task_id !== fence.task_id || prior.content !== text)
524
+ throw Error('evidence_conflict');
525
+ return;
526
+ }
527
+ next.outcomes.push(evidenceSchema.parse({
528
+ ref, task_id: fence.task_id, goal_revision: fence.goal_revision, kind: 'delivery', outcome, content: text, refs: []
529
+ }));
530
+ });
531
+ }
532
+ continue(requestId, fence, actor) {
533
+ return this.#change(requestId, { fence, actor, operation: 'continue' }, task => {
534
+ if (task.phase === 'cancelled' || task.phase === 'completed')
535
+ throw Error('task_terminal');
536
+ this.assertExecutionAllowed(task.id);
537
+ task.controller = { kind: 'nova' };
538
+ task.corrections = 0;
539
+ task.waiting_reason = null;
540
+ task.phase = task.work_ids.length ? 'verifying' : 'queued';
541
+ task.control_revision++;
542
+ }, task => this.#assertDecider(task, fence, actor, true));
543
+ }
544
+ /** A user attests what happened to execution whose outcome Nova could not observe, so a waiting task can move on. */
545
+ reconcile(requestId, fence, actor, resolution) {
546
+ const parsed = {
547
+ fence: taskFenceSchema.parse(fence), actor: actorSchema.parse(actor), operation: 'reconcile', resolution: z.enum(['done', 'not_run']).parse(resolution)
548
+ };
549
+ return this.#change(requestId, parsed, (task, next) => {
550
+ // Only durably uncertain execution is the user's to settle; a reserved or in-flight effect or send still reports its own result.
551
+ if (task.pending_delivery && this.#liveDeliveries.has(task.pending_delivery) || Object.values(next.pending_effects).some(effect => effect.task_id === task.id && effect.status === 'pending') || [...this.#liveInputs].some(request => next.effects[request]?.task_id === task.id))
552
+ throw Error('execution_in_flight');
553
+ const done = parsed.resolution === 'done';
554
+ let changed = false;
555
+ if (task.pending_delivery && task.waiting_reason === 'task_delivery_uncertain') {
556
+ delete task.pending_delivery;
557
+ changed = true;
558
+ }
559
+ for (const item of next.outcomes)
560
+ if (item.task_id === task.id && item.work_id && !['ok', 'failed', 'refused', 'cancelled'].includes(item.outcome)) {
561
+ item.outcome = done ? 'ok' : 'cancelled';
562
+ changed = true;
563
+ }
564
+ for (const effect of Object.values(next.pending_effects))
565
+ if (effect.task_id === task.id && effect.status === 'unknown') {
566
+ effect.status = done ? 'accepted' : 'failed';
567
+ changed = true;
568
+ // A confirmed step becomes evidence, so the loop verifies it instead of dispatching it again.
569
+ if (done)
570
+ next.outcomes.push({
571
+ observations: [], observations_truncated: false, ref: 'task-attested:' + effect.id, task_id: task.id, goal_revision: task.goal_revision, kind: 'work', outcome: 'ok', content: 'The user checked and confirmed this step ran, although Nova did not observe its result: ' + effect.instruction.slice(0, 4000), refs: []
572
+ });
573
+ }
574
+ for (const receipt of Object.values(next.effects))
575
+ if (receipt.task_id === task.id && receipt.status === 'unknown') {
576
+ receipt.status = done ? 'accepted' : 'failed';
577
+ changed = true;
578
+ }
579
+ if (!changed)
580
+ throw Error('nothing_to_reconcile');
581
+ task.waiting_reason = 'user_reconciled';
582
+ task.control_revision++;
583
+ }, task => {
584
+ this.#assertDecider(task, parsed.fence, parsed.actor, true);
585
+ if (parsed.actor.kind !== 'user')
586
+ throw Error('not_controller');
587
+ });
588
+ }
589
+ needsReconcile(taskId) {
590
+ const task = this.get(taskId);
591
+ return task.phase === 'waiting' && (Boolean(task.pending_delivery && !this.#liveDeliveries.has(task.pending_delivery) && task.waiting_reason === 'task_delivery_uncertain') || this.hasUnknownWork(taskId) || this.pendingEffect(taskId) !== null || this.inputReceipts(taskId).some(receipt => receipt.status === 'unknown'));
592
+ }
593
+ wait(fence, reason, diag) {
594
+ return this.applyDecision(fence, { kind: 'wait', reason, evidence_refs: [] }, diag);
595
+ }
596
+ applyDecision(fence, raw, diag, revalidate) {
597
+ let decision = taskDecisionSchema.parse(raw);
598
+ return this.#mutate(async (next) => {
599
+ if (decision.kind !== 'wait' && revalidate && !await revalidate())
600
+ decision = { kind: 'wait', reason: 'context_authorization_changed', evidence_refs: [] };
601
+ this.assertWritable(fence, { kind: 'nova' });
602
+ const task = next.tasks.find(task => task.id === fence.task_id);
603
+ if (decision.kind !== 'wait' && this.hasUnknownWork(task.id))
604
+ throw Error('task_effect_unknown');
605
+ if (task.pending_delivery && decision.kind !== 'wait')
606
+ throw Error('task_delivery_pending');
607
+ if (this.activeWork(task.id).length)
608
+ throw Error('task_work_active');
609
+ if (decision.kind === 'reconcile') {
610
+ const pending = this.pendingUserInputs(task.id).map(receipt => receipt.request_id);
611
+ if (!pending.length || hash(pending) !== hash(decision.input_refs))
612
+ throw Error('task_input_reconciliation_stale');
613
+ if (this.pendingEffect(task.id) || this.inputReceipts(task.id).some(receipt => receipt.status === 'unknown'))
614
+ throw Error('task_effect_unknown');
615
+ task.reconciled_inputs.push(...pending);
616
+ task.control_revision++;
617
+ if (decision.goal_change && !sameGoal(task, decision.goal_change.goal, decision.goal_change.acceptance)) {
618
+ task.goal = decision.goal_change.goal;
619
+ task.acceptance = decision.goal_change.acceptance;
620
+ task.goal_revision++;
621
+ }
622
+ task.phase = 'verifying';
623
+ task.waiting_reason = null;
624
+ next.events.push({ seq: ++next.event_seq, task_id: task.id, kind: 'control', text: JSON.stringify(decision), refs: [] });
625
+ return structuredClone(task);
626
+ }
627
+ if (decision.kind !== 'wait' && this.pendingUserInputs(task.id).length)
628
+ throw Error('task_input_reconciliation_required');
629
+ const evidence = this.evidence(task.id).filter(item => item.goal_revision === task.goal_revision && item.kind !== 'input');
630
+ if (decision.evidence_refs.some(ref => !evidence.some(item => item.ref === ref)))
631
+ throw Error('invalid_evidence');
632
+ if (decision.kind === 'complete' && !decision.evidence_refs.length)
633
+ throw Error('missing_evidence');
634
+ if (decision.kind !== 'wait' && (this.pendingEffect(task.id) || this.inputReceipts(task.id).some(receipt => receipt.status === 'unknown')))
635
+ throw Error('task_effect_unknown');
636
+ if (decision.kind === 'complete' && decision.criteria) {
637
+ if (decision.criteria.some(item => item.index >= task.acceptance.length || item.evidence_refs.some(ref => !evidence.some(entry => entry.ref === ref))))
638
+ throw Error('invalid_evidence');
639
+ }
640
+ task.evidence_refs = decision.evidence_refs;
641
+ if (decision.kind === 'complete' && decision.criteria)
642
+ task.criteria_evidence = decision.criteria.map(item => ({ index: item.index, evidence_refs: [...item.evidence_refs] }));
643
+ if (decision.kind === 'complete') {
644
+ task.phase = 'completed';
645
+ task.waiting_reason = null;
646
+ task.todo_sync = task.todo_ref ? 'pending' : 'none';
647
+ }
648
+ else if (decision.kind === 'wait') {
649
+ task.phase = 'waiting';
650
+ task.waiting_reason = decision.reason;
651
+ }
652
+ else if (task.corrections >= 3) {
653
+ task.phase = 'waiting';
654
+ task.waiting_reason = 'correction_limit';
655
+ }
656
+ else {
657
+ task.corrections++;
658
+ task.phase = 'queued';
659
+ task.waiting_reason = null;
660
+ const effectId = task.id + ':' + task.control_revision + ':' + task.goal_revision + ':' + task.corrections;
661
+ next.pending_effects[effectId] = {
662
+ id: effectId, task_id: task.id, fence, instruction: decision.instruction, status: 'pending', write_started: false
663
+ };
664
+ }
665
+ const stage = typeof diag?.stage === 'string' && /^[a-z_]{1,64}$/.test(diag.stage) ? diag.stage : undefined;
666
+ const code = typeof diag?.code === 'string' && /^[a-z_]{1,64}$/.test(diag.code) ? diag.code : undefined;
667
+ next.events.push({
668
+ seq: ++next.event_seq, task_id: task.id, kind: 'verification',
669
+ text: JSON.stringify(stage || code ? { ...decision, ...(stage ? { stage } : {}), ...(code ? { code } : {}) } : decision),
670
+ refs: decision.evidence_refs
671
+ });
672
+ return structuredClone(task);
673
+ });
674
+ }
675
+ beginDelivery(fence, deliveryId) {
676
+ return this.#mutate(next => {
677
+ this.assertWritable(fence, { kind: 'nova' });
678
+ const task = next.tasks.find(task => task.id === fence.task_id);
679
+ if (task.pending_delivery)
680
+ throw Error('task_delivery_pending');
681
+ task.pending_delivery = id.parse(deliveryId);
682
+ this.#liveDeliveries.add(deliveryId);
683
+ });
684
+ }
685
+ finishDelivery(taskId, deliveryId) {
686
+ return this.#mutate(next => {
687
+ const task = next.tasks.find(task => task.id === taskId);
688
+ if (task?.pending_delivery === deliveryId)
689
+ delete task.pending_delivery;
690
+ this.#liveDeliveries.delete(deliveryId);
691
+ });
692
+ }
693
+ reserveInitial(fence) {
694
+ return this.#mutate(next => {
695
+ this.assertWritable(fence, { kind: 'nova' });
696
+ if (this.hasUnknownWork(fence.task_id) || this.pendingEffect(fence.task_id) || this.inputReceipts(fence.task_id).some(receipt => receipt.status === 'unknown'))
697
+ throw Error('task_effect_unknown');
698
+ if (this.pendingUserInputs(fence.task_id).length)
699
+ throw Error('task_input_reconciliation_required');
700
+ const task = next.tasks.find(task => task.id === fence.task_id), prefix = task.id + ':initial:' + task.control_revision + ':' + task.goal_revision, prior = Object.values(next.pending_effects).filter(effect => effect.id === prefix || effect.id.startsWith(prefix + ':'));
701
+ if (prior.some(effect => effect.status !== 'failed'))
702
+ throw Error('task_initial_pending');
703
+ const effectId = prefix + ':' + prior.length;
704
+ next.pending_effects[effectId] = { id: effectId, task_id: task.id, fence, instruction: task.goal, status: 'pending', write_started: false };
705
+ return effectId;
706
+ });
707
+ }
708
+ markEffectDispatching(effectId) {
709
+ return this.#mutate(next => {
710
+ const effect = next.pending_effects[effectId];
711
+ if (effect?.status !== 'pending')
712
+ throw Error('effect_not_pending');
713
+ this.assertWritable(effect.fence, { kind: 'nova' });
714
+ this.assertExecutionAllowed(effect.task_id);
715
+ if (this.pendingUserInputs(effect.task_id).length)
716
+ throw Error('task_input_reconciliation_required');
717
+ effect.write_started = true;
718
+ });
719
+ }
720
+ recoveryWait(taskId, reason) {
721
+ return this.#mutate(next => {
722
+ const task = next.tasks.find(task => task.id === taskId);
723
+ if (!task)
724
+ throw Error('task_not_found');
725
+ if (task.phase === 'completed' || task.phase === 'cancelled')
726
+ return;
727
+ task.waiting_reason = reason;
728
+ if (reason)
729
+ task.phase = 'waiting';
730
+ else if (task.phase === 'waiting')
731
+ task.phase = task.work_ids.length ? 'verifying' : 'queued';
732
+ });
733
+ }
734
+ resourceState(taskId, reason) {
735
+ return this.#mutate(next => {
736
+ const task = next.tasks.find(task => task.id === taskId);
737
+ if (!task || task.phase === 'completed' || task.phase === 'cancelled')
738
+ return;
739
+ task.waiting_reason = reason;
740
+ task.phase = reason ? 'waiting' : 'running';
741
+ });
742
+ }
743
+ settleEffect(effectId, status) {
744
+ return this.#mutate(next => {
745
+ const effect = next.pending_effects[effectId];
746
+ if (!effect)
747
+ throw Error('effect_not_found');
748
+ if (effect.status === 'pending')
749
+ effect.status = status;
750
+ });
751
+ }
752
+ markTodoSync(taskId, goalRevision, status) {
753
+ return this.#mutate(next => {
754
+ const task = next.tasks.find(task => task.id === taskId);
755
+ if (task?.phase !== 'completed' || task.goal_revision !== goalRevision)
756
+ throw Error('stale_task');
757
+ task.todo_sync = status;
758
+ });
759
+ }
760
+ #change(requestId, parsed, change, authorize) {
761
+ const request = id.parse(requestId), body = hash(parsed);
762
+ return this.#mutate(next => {
763
+ const prior = next.receipts[request];
764
+ if (prior) {
765
+ if (prior.hash !== body)
766
+ throw Error('request_conflict');
767
+ if (!prior.result)
768
+ throw Error('task_retired');
769
+ return structuredClone(prior.result);
770
+ }
771
+ const task = next.tasks.find(item => item.id === parsed.fence.task_id);
772
+ if (!task)
773
+ throw Error('task_not_found');
774
+ if (authorize)
775
+ authorize(task);
776
+ else
777
+ this.#assert(task, parsed.fence, parsed.actor);
778
+ change(task, next);
779
+ next.events.push({
780
+ seq: ++next.event_seq, task_id: task.id, kind: 'control', text: JSON.stringify({
781
+ operation: parsed.operation ?? parsed.action ?? ('nextActor' in parsed ? 'controller_changed' : 'goal_revised'), ...(parsed.resolution ? { resolution: parsed.resolution } : {}), controller: task.controller, control_revision: task.control_revision, goal_revision: task.goal_revision
782
+ }), refs: []
783
+ });
784
+ const result = structuredClone(task);
785
+ next.receipts[request] = { hash: body, task_id: task.id, result };
786
+ return result;
787
+ });
788
+ }
789
+ /** The controller may always decide; a user may also stop, or unblock a waiting task, while Nova holds control. */
790
+ #assertDecider(task, fence, actor, waitingOnly) {
791
+ this.#assertFence(task, fence);
792
+ if (JSON.stringify(task.controller) === JSON.stringify(actor))
793
+ return;
794
+ if (actor.kind === 'user' && task.controller.kind === 'nova' && (!waitingOnly || task.phase === 'waiting'))
795
+ return;
796
+ throw Error('not_controller');
797
+ }
798
+ #assert(task, fence, actor) {
799
+ this.#assertFence(task, fence);
800
+ if (JSON.stringify(task.controller) !== JSON.stringify(actor))
801
+ throw Error('not_controller');
802
+ }
803
+ #assertFence(task, fence) {
804
+ if (task.control_revision !== fence.control_revision || task.goal_revision !== fence.goal_revision)
805
+ throw Error('stale_task');
806
+ }
807
+ /**
808
+ * Finished tasks beyond the newest RETAINED_FINISHED_TASKS leave the store with everything keyed to them, and so do the oldest
809
+ * ones while the store is above PRUNE_ABOVE_BYTES, down to PRUNE_TO_BYTES; unresolved ones stay.
810
+ */
811
+ #pruneRetired(next) {
812
+ const unresolved = (taskId) => Object.values(next.pending_effects).some(effect => effect.task_id === taskId && (effect.status === 'pending' || effect.status === 'unknown')) || Object.values(next.effects).some(effect => effect.task_id === taskId && effect.status === 'unknown');
813
+ const finished = next.tasks.filter(task => (task.phase === 'completed' || task.phase === 'cancelled') && !task.pending_delivery && !task.waiting_reason && !unresolved(task.id));
814
+ const last = new Map();
815
+ for (const event of next.events)
816
+ last.set(event.task_id, event.seq);
817
+ const oldest = finished.map((task, order) => ({ id: task.id, rank: last.get(task.id) ?? order })).sort((a, b) => a.rank - b.rank).map(task => task.id);
818
+ const retired = new Set(oldest.slice(0, Math.max(0, oldest.length - RETAINED_FINISHED_TASKS)));
819
+ let size = Buffer.byteLength(JSON.stringify(next));
820
+ if (size > PRUNE_ABOVE_BYTES) {
821
+ // Large results can fill the store long before the count cap, so retire by footprint too.
822
+ const footprint = new Map(oldest.map(taskId => [taskId, 0]));
823
+ const add = (taskId, value) => { if (taskId && footprint.has(taskId))
824
+ footprint.set(taskId, footprint.get(taskId) + Buffer.byteLength(JSON.stringify(value ?? null))); };
825
+ for (const task of next.tasks)
826
+ add(task.id, task);
827
+ for (const event of next.events)
828
+ add(event.task_id, event);
829
+ for (const outcome of next.outcomes)
830
+ add(outcome.task_id, outcome);
831
+ for (const receipt of Object.values(next.receipts))
832
+ add(receipt.task_id, receipt.result);
833
+ for (const effect of Object.values(next.effects))
834
+ add(effect.task_id, effect);
835
+ for (const taskId of retired)
836
+ size -= footprint.get(taskId);
837
+ for (const taskId of oldest) {
838
+ if (size <= PRUNE_TO_BYTES)
839
+ break;
840
+ if (!retired.has(taskId)) {
841
+ retired.add(taskId);
842
+ size -= footprint.get(taskId);
843
+ }
844
+ }
845
+ }
846
+ if (retired.size) {
847
+ const works = new Set(next.tasks.filter(task => retired.has(task.id)).flatMap(task => task.work_ids));
848
+ next.tasks = next.tasks.filter(task => !retired.has(task.id));
849
+ next.events = next.events.filter(event => !retired.has(event.task_id));
850
+ next.outcomes = next.outcomes.filter(outcome => !retired.has(outcome.task_id));
851
+ next.instruction_work_ids = next.instruction_work_ids.filter(work => !works.has(work));
852
+ next.replay_incomplete = next.replay_incomplete.filter(taskId => !retired.has(taskId));
853
+ // A retired task's receipts become tombstones, so replaying its request cannot start the work again.
854
+ for (const value of Object.values(next.receipts))
855
+ if (retired.has(value.task_id))
856
+ delete value.result;
857
+ for (const [key, value] of Object.entries(next.effects))
858
+ if (value.task_id && retired.has(value.task_id))
859
+ delete next.effects[key];
860
+ for (const [key, value] of Object.entries(next.pending_effects))
861
+ if (retired.has(value.task_id))
862
+ delete next.pending_effects[key];
863
+ for (const [key, value] of Object.entries(next.work_fences))
864
+ if (retired.has(value.task_id) || works.has(key))
865
+ delete next.work_fences[key];
866
+ for (const [key, value] of Object.entries(next.event_keys))
867
+ if (value.task_id && retired.has(value.task_id))
868
+ delete next.event_keys[key];
869
+ for (const taskId of retired)
870
+ delete next.truncated[taskId];
871
+ }
872
+ const tombstones = Object.entries(next.receipts).filter(([, receipt]) => !receipt.result).map(([key]) => key);
873
+ for (const key of tombstones.slice(0, Math.max(0, tombstones.length - RETAINED_TOMBSTONES)))
874
+ delete next.receipts[key];
875
+ const handbacks = Object.keys(next.handbacks);
876
+ for (const key of handbacks.slice(0, Math.max(0, handbacks.length - RETAINED_HANDBACKS)))
877
+ delete next.handbacks[key];
878
+ }
879
+ #pruneDisplay(next) {
880
+ // ponytail: bounded linear retention; move display history to indexed storage if task volume grows.
881
+ const counts = new Map(), bytes = new Map();
882
+ let total = 0;
883
+ const eligible = (event) => event.kind !== 'control' && event.kind !== 'verification';
884
+ for (const event of next.events)
885
+ if (eligible(event)) {
886
+ const size = Buffer.byteLength(JSON.stringify(event));
887
+ counts.set(event.task_id, (counts.get(event.task_id) ?? 0) + 1);
888
+ bytes.set(event.task_id, (bytes.get(event.task_id) ?? 0) + size);
889
+ total += size;
890
+ }
891
+ const budget = Math.max(0, Math.min(4 * 1024 * 1024, 16 * 1024 * 1024 - Buffer.byteLength(JSON.stringify(next)) + total - 4096));
892
+ next.events = next.events.filter(event => {
893
+ if (!eligible(event) || ((counts.get(event.task_id) ?? 0) <= 1000 && (bytes.get(event.task_id) ?? 0) <= 1024 * 1024 && total <= budget))
894
+ return true;
895
+ const size = Buffer.byteLength(JSON.stringify(event));
896
+ counts.set(event.task_id, counts.get(event.task_id) - 1);
897
+ bytes.set(event.task_id, bytes.get(event.task_id) - size);
898
+ total -= size;
899
+ next.truncated[event.task_id] = Math.max(next.truncated[event.task_id] ?? 0, event.seq);
900
+ return false;
901
+ });
902
+ }
903
+ #mutate(change) {
904
+ const run = this.#tail.then(async () => {
905
+ const next = structuredClone(this.#state), result = await change(next);
906
+ for (const taskId of this.#incompleteReplay)
907
+ if (!next.replay_incomplete.includes(taskId))
908
+ next.replay_incomplete.push(taskId);
909
+ this.#pruneRetired(next);
910
+ this.#pruneDisplay(next);
911
+ await this.#store.write(next);
912
+ this.#state = next;
913
+ this.changed();
914
+ return result;
915
+ });
916
+ this.#tail = run.catch(() => { });
917
+ return run;
918
+ }
919
+ }
920
+ //# sourceMappingURL=tasks.js.map