nova-personal-agent-server 0.4.0 → 1.0.2

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 (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +12 -2
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +13 -6
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -0,0 +1,558 @@
1
+ import { z } from 'zod';
2
+ import { TEMPORAL_RECIPE, temporalResultSchema, resolveWorkbenchGroups } from './workbench-temporal.js';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
5
+ import { sourceTagSchema } from '../memory/provenance.js';
6
+ import { automaticWorkbenchMatter, validWorkbenchMatter, workbenchBatches, workbenchCompositionSchema, workbenchExistingCandidates, workbenchHash, workbenchMatterSchema, workbenchRefSchema, workbenchSensitive } from './workbench-evidence.js';
7
+ const matterSchema = workbenchMatterSchema.extend({ id: z.string(), group: z.string(), observed_at: z.string().default('') });
8
+ const cardSchema = z.object({ scope: z.string().optional(), id: z.string(), candidate_id: z.string(), tab: z.enum(['ideas', 'goals']), title: z.string(), body: z.string(), why: z.string().nullable(), next: z.string().nullable(), refs: z.array(workbenchRefSchema), sources: z.array(sourceTagSchema), update: z.object({ id: z.string(), kind: z.literal('goal'), version: z.number(), status: z.string() }).optional() });
9
+ const cacheSchema = z.object({ key: z.string(), group: z.string(), basis: z.array(z.object({ id: z.string(), version: z.string() })), matters: z.array(matterSchema) });
10
+ const recordedSchema = z.object({ matter: matterSchema.pick({ id: true, kind: true, title: true, summary: true }), id: z.string(), version: z.number(), undone: z.boolean().default(false) });
11
+ /** Every idea ever generated stays readable, even after its cited sources changed or a later run produced none. */
12
+ const historySchema = cardSchema.pick({ id: true, tab: true, title: true, body: true, why: true, next: true, refs: true, sources: true }).extend({ generated_at: z.string(), imported: z.boolean().default(false), scope: z.string().optional() });
13
+ const legacyDismissedSchema = z.object({ tab: z.string(), refs: z.array(z.object({ entry_id: z.string(), version: z.union([z.string(), z.number()]) })) });
14
+ /** Todo generation is gone: a cache that still holds todo matters, todo cards or recorded todos is cleared, and the day is reopened for a fresh run. */
15
+ const dropTodoState = (raw) => {
16
+ if (!raw || typeof raw !== 'object')
17
+ return raw;
18
+ const state = raw, todo = (row) => row?.kind === 'todo';
19
+ const stale = (state.cards ?? []).some(card => card.tab === 'todos' || todo(card.update)) || (state.cache ?? []).some(entry => (entry.matters ?? []).some(todo)) || (state.recorded ?? []).some(row => todo(row.matter));
20
+ return stale ? { ...state, temporal: null, compositions: [], cache: [], cards: [], key: '', updated_at: null, automatic_day: '', recorded: (state.recorded ?? []).filter(row => !todo(row.matter)) } : raw;
21
+ };
22
+ export const dailyWorkbenchStateSchema = z.preprocess(dropTodoState, z.object({ version: z.literal(1), failure: z.string().nullable().default(null), temporal: z.object({ key: z.string(), source_key: z.string().default(''), result: temporalResultSchema }).nullable().default(null), legacy_imported: z.boolean().default(false), legacy_dismissed: z.array(legacyDismissedSchema).default([]), automatic_day: z.string(), key: z.string(), updated_at: z.string().nullable(), cache: z.array(cacheSchema), compositions: z.array(z.object({ key: z.string(), result: workbenchCompositionSchema })).default([]), cards: z.array(cardSchema), dismissed: z.array(z.string()), recorded: z.array(recordedSchema),
23
+ diagnostics: z.object({ inputs: z.number(), cache_hits: z.number(), extraction_calls: z.number(), composition_calls: z.number(), received: z.number(), rejected: z.number(), recorded: z.number() }), history: z.array(historySchema).max(200).default([]) }));
24
+ const diagnostics = () => ({ inputs: 0, cache_hits: 0, extraction_calls: 0, composition_calls: 0, received: 0, rejected: 0, recorded: 0 });
25
+ const empty = () => ({ version: 1, failure: null, temporal: null, legacy_imported: false, legacy_dismissed: [], automatic_day: '', key: '', updated_at: null, cache: [], compositions: [], cards: [], dismissed: [], recorded: [], diagnostics: diagnostics(), history: [] });
26
+ const RECIPE = 'workbench-daily-v1';
27
+ function invalidMatches(reason) {
28
+ throw Object.assign(Error('invalid_workbench_matches'), { classification: 'invalid_workbench_matches_' + reason });
29
+ }
30
+ function unresolvedWorkbenchReference(card) {
31
+ const references = (text) => text.match(/\b[me]\d+\b/gu) ?? [];
32
+ const quoted = new Set(card.refs.flatMap(ref => references(ref.quote)));
33
+ return references([card.title, card.body, card.why, card.next].join(' ')).some(id => !quoted.has(id));
34
+ }
35
+ /** One daily interpretation shared by three tabs; this service never dispatches agent tasks. */
36
+ export class DailyWorkbench {
37
+ options;
38
+ #store;
39
+ #state = empty();
40
+ #inputs = [];
41
+ #opened = false;
42
+ #defer = true;
43
+ #status = 'idle';
44
+ #error = null;
45
+ #abort = new AbortController();
46
+ #run;
47
+ #sync;
48
+ #tail = Promise.resolve();
49
+ #timer;
50
+ #pendingValidation = false;
51
+ #inputRevision = 0;
52
+ constructor(options) {
53
+ this.options = options;
54
+ this.#store = new BoundedJsonStore(options.path, dailyWorkbenchStateSchema, 16 * 1024 * 1024);
55
+ }
56
+ #validatedScope;
57
+ #scope() { return this.options.scope?.() ?? 'local'; }
58
+ retainedEvidenceIds() { return [...new Set([...this.#state.cards, ...this.#state.history].filter(card => !this.#state.dismissed.includes(card.id)).flatMap(card => card.refs.map(ref => ref.entry_id)))]; }
59
+ #now() { return this.options.now?.() ?? new Date(); }
60
+ #day() { return this.#now().toLocaleDateString('en-CA', { timeZone: this.options.timezone() }); }
61
+ #key(inputs = this.#inputs) { return workbenchHash([RECIPE, TEMPORAL_RECIPE, this.options.timezone(), inputs.map(({ id, version }) => [id, version]), this.#state.cache.flatMap(c => c.matters).filter(m => m.due).map(m => [m.id, m.due < this.#day()])]); }
62
+ async #save() { const state = structuredClone(this.#state); const run = this.#tail.then(() => this.#store.write(state)); this.#tail = run.catch(() => undefined); await run; }
63
+ /** Keeps generated ideas readable after their sources move or a later run produces none. */
64
+ #recordHistory(cards, generatedAt = this.#now().toISOString()) { const seen = new Set(this.#state.history.map(row => row.id)), added = cards.filter(card => card.tab === 'ideas' && !seen.has(card.id)).map(card => ({ id: card.id, tab: card.tab, title: card.title, body: card.body, why: card.why, next: card.next, refs: card.refs, sources: card.sources, generated_at: generatedAt, imported: false, ...(card.scope ? { scope: card.scope } : {}) })); if (added.length)
65
+ this.#state.history = [...this.#state.history, ...added].slice(-200); }
66
+ #publish(cards) { this.#recordHistory(this.#state.cards, this.#state.updated_at ?? this.#now().toISOString()); const scoped = cards.map(card => ({ ...card, scope: this.#scope() })); this.#recordHistory(scoped); this.#state.cards = scoped.filter((card, index) => Boolean(card.update) || cards.slice(0, index).filter(c => c.tab === card.tab && !c.update).length < 3); }
67
+ async open({ deferGeneration = false } = {}) {
68
+ this.#error = null;
69
+ try {
70
+ this.#state = await this.#store.read(empty());
71
+ }
72
+ catch (error) {
73
+ if (!(error instanceof z.ZodError || error instanceof SyntaxError))
74
+ throw error;
75
+ this.#state = empty();
76
+ this.#state.automatic_day = this.#day();
77
+ this.#error = 'cache_invalid';
78
+ }
79
+ if (!this.#error && !this.#state.legacy_imported) {
80
+ if (this.options.legacyPath)
81
+ try {
82
+ const old = z.object({ cards: z.array(legacyDismissedSchema.extend({ candidate_id: z.string().optional() }).passthrough()), dismissed: z.array(z.string()) }).parse(JSON.parse(await readFile(this.options.legacyPath, 'utf8')));
83
+ this.#state.legacy_dismissed = old.cards.filter(card => old.dismissed.includes(card.candidate_id ?? workbenchHash(card))).map(({ tab, refs }) => ({ tab, refs }));
84
+ }
85
+ catch (error) {
86
+ if (error.code !== 'ENOENT')
87
+ this.#error = 'cache_invalid';
88
+ }
89
+ if (!this.#error) {
90
+ this.#state.legacy_imported = true;
91
+ await this.#save();
92
+ }
93
+ }
94
+ this.#recordHistory(this.#state.cards, this.#state.updated_at ?? this.#now().toISOString());
95
+ await this.#save();
96
+ this.#validatedScope = undefined;
97
+ this.#opened = true;
98
+ this.#defer = deferGeneration;
99
+ this.#abort = new AbortController();
100
+ if (this.#error)
101
+ this.#status = 'failed';
102
+ }
103
+ startGeneration() { this.#defer = false; void this.sync().catch(() => undefined); }
104
+ suspend() { this.#pendingValidation = true; this.#inputRevision++; this.options.changed(); }
105
+ // Host document updates only wake the shared source read; there is no second file-only model path.
106
+ update(entries, digests) { void entries; void digests; void this.sync().catch(() => undefined); }
107
+ sync() {
108
+ // An incomplete startup projection is not a source withdrawal. Keep durable caches
109
+ // until the host can supply its full first snapshot; current cards still have no inputs.
110
+ if (this.#error === 'cache_invalid' || this.options.inputsReady?.() === false)
111
+ return Promise.resolve();
112
+ if (this.#sync)
113
+ return this.#sync;
114
+ const run = (async () => {
115
+ try {
116
+ let revision, inputs;
117
+ const scope = this.#scope();
118
+ do {
119
+ revision = this.#inputRevision;
120
+ inputs = await this.options.inputs();
121
+ } while (revision !== this.#inputRevision && this.#opened);
122
+ if (scope !== this.#scope())
123
+ return;
124
+ if (!this.#opened)
125
+ return;
126
+ const next = inputs.filter(input => input.text.trim() && !workbenchSensitive(input.text)).sort((a, b) => a.id.localeCompare(b.id));
127
+ // Only a withdrawn source invalidates an interpretation. A version bump is a message edit,
128
+ // a rescan or a pause: it must not cancel a run that is already paying for model calls.
129
+ if (this.#inputs.some(old => !next.some(input => input.id === old.id))) {
130
+ this.#abort.abort();
131
+ this.#abort = new AbortController();
132
+ }
133
+ this.#inputs = next;
134
+ this.#validatedScope = scope;
135
+ this.#pendingValidation = false;
136
+ if (this.#error === 'sources_unavailable')
137
+ this.#error = null;
138
+ const kept = this.#state.cache.filter(c => c.basis.every(ref => next.some(input => input.id === ref.id && input.version === ref.version)));
139
+ if (kept.length !== this.#state.cache.length) {
140
+ this.#state.cache = kept;
141
+ this.#state.compositions = [];
142
+ this.#recordHistory(this.#state.cards, this.#state.updated_at ?? this.#now().toISOString());
143
+ this.#state.cards = this.#state.cards.filter(card => this.#grounded(card.refs));
144
+ await this.#save();
145
+ }
146
+ let bound = false;
147
+ for (const row of this.#state.cards)
148
+ if (!row.scope && this.#grounded(row.refs)) {
149
+ row.scope = scope;
150
+ bound = true;
151
+ }
152
+ for (const row of this.#state.history)
153
+ if (!row.scope && row.refs.length && row.refs.every(ref => next.some(input => input.id === ref.entry_id))) {
154
+ row.scope = scope;
155
+ bound = true;
156
+ }
157
+ if (bound)
158
+ await this.#save();
159
+ this.options.changed();
160
+ this.#schedule();
161
+ }
162
+ catch {
163
+ this.#inputs = [];
164
+ this.#abort.abort();
165
+ this.#abort = new AbortController();
166
+ this.#status = 'failed';
167
+ this.#error = 'sources_unavailable';
168
+ this.options.changed();
169
+ }
170
+ })();
171
+ this.#sync = run;
172
+ void run.finally(() => { if (this.#sync === run)
173
+ this.#sync = undefined; });
174
+ return run;
175
+ }
176
+ #schedule() {
177
+ clearTimeout(this.#timer);
178
+ if (!this.#opened || this.#defer || this.#run || !this.#inputs.length || !this.options.ready() || this.#state.automatic_day >= this.#day() || this.#state.key === this.#key())
179
+ return;
180
+ this.#timer = setTimeout(() => { void this.refresh(true); }, 3000);
181
+ this.#timer.unref();
182
+ }
183
+ #grounded(refs) { return refs.every(ref => this.#inputs.some(input => input.id === ref.entry_id && input.version === String(ref.version))); }
184
+ sourcesForRefs(refs) { return refs.flatMap(ref => { const input = this.#inputs.find(input => input.id === ref.entry_id && input.version === String(ref.version)); return input?.source ? [input.source] : []; }); }
185
+ #temporalCurrent() { return this.#state.temporal?.source_key === workbenchHash(this.#inputs.map(i => [i.id, i.version])); }
186
+ snapshot() {
187
+ const life = this.options.life().snapshot();
188
+ const cards = this.#state.cards.filter(card => this.#validatedScope === this.#scope() && card.scope === this.#scope() && (card.tab === 'ideas' || this.#temporalCurrent()) && (!card.update || life.goals.some(row => row.id === card.update.id && row.version === card.update.version && row.status !== card.update.status)) && !this.#pendingValidation && !this.#state.dismissed.includes(card.id) && this.#grounded(card.refs) && !unresolvedWorkbenchReference(card)).map(card => ({ ...card, refs: card.refs.map(ref => ({ ...ref, label: ref.quote })) }));
189
+ const history = this.#ideaHistory(cards), count = this.#state.cache.flatMap(c => c.matters).filter(m => this.#grounded(m.refs)).length;
190
+ const reason = this.#error ? 'generation_failed' : !this.#inputs.length ? 'no_eligible_sources' : this.#state.updated_at ? this.#state.diagnostics.rejected && !count ? 'validation_filtered' : 'model_abstained' : null;
191
+ return { status: this.#status, candidate_count: count, recap: { text: null, projects: [] }, cards, empty_reason: cards.length ? null : reason,
192
+ idea_history: history, empty_reasons: Object.fromEntries(['ideas', 'goals'].map(tab => [tab, cards.some(c => c.tab === tab) || tab === 'ideas' && history.length ? null : reason])),
193
+ daily: true, automatic_available: this.#state.automatic_day < this.#day(), updated_at: this.#state.updated_at, error: this.#error, diagnostics: structuredClone(this.#state.diagnostics) };
194
+ }
195
+ /** Generated ideas that are no longer current cards stay listed, tagged when their sources moved. */
196
+ #ideaHistory(current) { if (this.#pendingValidation || this.#validatedScope !== this.#scope() || this.options.inputsReady?.() === false)
197
+ return []; const visible = new Set(current.filter(card => card.tab === 'ideas').map(card => card.id)); return this.#state.history.filter(row => row.tab === 'ideas' && row.scope === this.#scope() && row.refs.every(ref => this.#inputs.some(input => input.id === ref.entry_id)) && !visible.has(row.id) && !this.#state.dismissed.includes(row.id)).map(row => ({ ...row, source_changed: !this.#grounded(row.refs), refs: row.refs.map(ref => ({ ...ref, label: ref.quote })) })).reverse(); }
198
+ async dismiss(id) { if (!this.snapshot().cards.some(card => card.id === id) && !this.#state.history.some(row => row.id === id))
199
+ throw Error('card_not_found'); await this.#hide(id); }
200
+ async #hide(id) { this.#state.dismissed = [...new Set([...this.#state.dismissed, id])]; await this.#save(); this.options.changed(); }
201
+ #existing() { const life = this.options.life().snapshot(), saved = [...life.ideas, ...life.goals].map(row => ({ id: row.id, kind: row.kind, title: row.title, note: row.note, status: row.status, version: row.version })); return [...saved, ...this.#state.recorded.filter(r => r.undone && !saved.some(row => row.id === r.id)).map(r => ({ id: r.id, kind: 'goal', title: r.matter.title, note: r.matter.summary, status: 'cancelled', version: r.version }))]; }
202
+ #matterCurrent(matter) { return !this.#pendingValidation && this.#grounded(matter.refs) && validWorkbenchMatter(matter, this.#inputs); }
203
+ #composition(value) { const raw = workbenchCompositionSchema.extend({ suggestions: z.array(z.unknown()).max(9) }).parse(value); return { ...raw, suggestions: raw.suggestions.flatMap(item => { const parsed = workbenchCompositionSchema.shape.suggestions.element.safeParse(item); if (parsed.success)
204
+ return [parsed.data]; this.#state.diagnostics.rejected++; return []; }) }; }
205
+ /** `force` re-runs the shared pipeline for an explicit user retry even when today's automatic attempt is spent or the inputs are unchanged. */
206
+ async refresh(automatic = false, force = false) {
207
+ if (this.#run)
208
+ return this.#run;
209
+ const work = this.#refresh(automatic, force);
210
+ this.#run = work;
211
+ try {
212
+ await work;
213
+ }
214
+ finally {
215
+ this.#run = undefined;
216
+ this.options.changed();
217
+ }
218
+ }
219
+ async #refresh(automatic, force) {
220
+ await this.sync();
221
+ if (!this.#opened || this.#defer || !this.#inputs.length || !this.options.ready() || this.#error === 'sources_unavailable' || this.#error === 'cache_invalid')
222
+ return;
223
+ if (automatic && !force && this.#state.automatic_day >= this.#day())
224
+ return;
225
+ const key = this.#key();
226
+ if (!force && key === this.#state.key) {
227
+ this.#status = 'ready';
228
+ return;
229
+ }
230
+ clearTimeout(this.#timer);
231
+ this.#status = 'working';
232
+ this.#error = null;
233
+ this.#state.failure = null;
234
+ // A full run includes bounded extraction, global review and multiple sequential composition batches.
235
+ const cancel = this.#abort.signal, signal = AbortSignal.any([cancel, AbortSignal.timeout(1800000)]), inputs = structuredClone(this.#inputs), day = this.#day(), timezone = this.options.timezone(), scope = this.#scope(), spentDay = this.#state.automatic_day;
236
+ const guard = () => { signal.throwIfAborted(); if (!this.#opened)
237
+ throw Error('workbench_closed'); if (scope !== this.#scope())
238
+ throw Error('context_authorization_changed'); };
239
+ this.#state.diagnostics = { ...diagnostics(), inputs: inputs.length };
240
+ try {
241
+ if (automatic && !force) {
242
+ this.#state.automatic_day = day;
243
+ await this.#save();
244
+ }
245
+ const caches = [], batches = workbenchBatches(inputs), initialKeys = new Set(this.#state.cache.map(c => c.key));
246
+ for (const [index, batch] of batches.entries()) {
247
+ guard();
248
+ const cacheKey = workbenchHash([RECIPE, timezone, batch.inputs]), cached = this.#state.cache.find(c => c.key === cacheKey);
249
+ if (cached) {
250
+ caches.push(cached);
251
+ if (initialKeys.has(cacheKey))
252
+ this.#state.diagnostics.cache_hits++;
253
+ continue;
254
+ }
255
+ await this.sync();
256
+ guard();
257
+ const combined = [], batchInputs = [];
258
+ let chars = 0;
259
+ for (const next of batches.slice(index)) {
260
+ if (this.#state.cache.some(c => c.key === workbenchHash([RECIPE, timezone, next.inputs])))
261
+ continue;
262
+ const length = next.inputs.reduce((sum, input) => sum + input.text.length, 0);
263
+ if (combined.length && (batchInputs.length + next.inputs.length > 60 || chars + length > 24000))
264
+ break;
265
+ combined.push(next);
266
+ batchInputs.push(...next.inputs);
267
+ chars += length;
268
+ }
269
+ const previous = this.#state.cache.filter(c => combined.some(b => b.group === c.group)).flatMap(c => c.matters).filter(m => this.#grounded(m.refs)).slice(-8);
270
+ this.#state.diagnostics.extraction_calls++;
271
+ const result = z.object({ matters: z.array(z.unknown()).max(100) }).strict().parse(await this.options.generate({ phase: 'extract', inputs: batchInputs, previous, date: day, timezone }, signal));
272
+ guard();
273
+ this.#state.diagnostics.received += result.matters.length;
274
+ const matters = result.matters.flatMap(value => {
275
+ const parsed = workbenchMatterSchema.safeParse(value);
276
+ if (!parsed.success) {
277
+ this.#state.diagnostics.rejected++;
278
+ return [];
279
+ }
280
+ const raw = parsed.data;
281
+ if (!validWorkbenchMatter(raw, batchInputs)) {
282
+ this.#state.diagnostics.rejected++;
283
+ return [];
284
+ }
285
+ const m = raw.kind === 'goal' && raw.due ? { ...raw, summary: raw.summary.slice(0, 370) + ';目标日期:' + raw.due, due: null, due_quote: null } : raw;
286
+ return [{ ...m, id: workbenchHash([m.kind, m.refs[0].entry_id, m.refs[0].quote, m.title.normalize('NFKC').trim().toLowerCase()]), group: combined.find(b => b.inputs.some(input => input.id === m.refs[0].entry_id)).group, observed_at: inputs.filter(input => m.refs.some(ref => ref.entry_id === input.id)).map(input => input.observed_at).sort().at(-1) ?? '' }];
287
+ });
288
+ for (const part of combined) {
289
+ const partMatters = matters.filter(m => part.inputs.some(input => input.id === m.refs[0].entry_id));
290
+ const basis = batchInputs.filter(input => part.inputs.some(row => row.id === input.id) || partMatters.some(m => m.refs.some(ref => ref.entry_id === input.id))).map(({ id, version }) => ({ id, version }));
291
+ const entry = { key: workbenchHash([RECIPE, timezone, part.inputs]), group: part.group, basis, matters: partMatters };
292
+ this.#state.cache = [...this.#state.cache.filter(c => c.key !== entry.key), entry];
293
+ if (part === batch)
294
+ caches.push(entry);
295
+ }
296
+ await this.#save();
297
+ }
298
+ this.#state.cache = caches;
299
+ await this.#save();
300
+ const extracted = [...new Map(caches.flatMap(c => c.matters).map(m => [m.id, m])).values()];
301
+ const temporalKey = workbenchHash([TEMPORAL_RECIPE, timezone, day, extracted]);
302
+ let temporal = this.#state.temporal?.key === temporalKey ? this.#state.temporal.result : undefined;
303
+ if (!temporal) {
304
+ this.#state.diagnostics.composition_calls++;
305
+ temporal = temporalResultSchema.parse(await this.options.generate({ phase: 'reconcile', matters: extracted, inputs, date: day, timezone }, signal));
306
+ guard();
307
+ }
308
+ const resolved = resolveWorkbenchGroups(extracted, temporal);
309
+ this.#state.temporal = { key: temporalKey, source_key: workbenchHash(inputs.map(i => [i.id, i.version])), result: temporal };
310
+ await this.#save();
311
+ const groupFor = new Map(resolved.flatMap(g => g.members.map(m => [m.id, g]))), capturedGroups = new Set();
312
+ const matters = extracted.map(m => ({ ...m, state: groupFor.get(m.id).state }));
313
+ const cards = [], existing = this.#existing();
314
+ const groups = new Map(resolved.map(g => [g.id, matters.filter(m => groupFor.get(m.id).id === g.id)]));
315
+ const incomplete = new Set([...groups.values()].filter(group => group.length > 60 || JSON.stringify(group).length > 24000).flatMap(group => group.map(m => m.id)));
316
+ const packs = [];
317
+ let pack = [], size = 0;
318
+ for (const group of groups.values()) {
319
+ if (pack.length && (pack.length + group.length > 60 || size + JSON.stringify(group).length > 24000)) {
320
+ packs.push(pack);
321
+ pack = [];
322
+ size = 0;
323
+ }
324
+ for (const matter of group) {
325
+ const length = JSON.stringify(matter).length;
326
+ if (pack.length && (pack.length === 60 || size + length > 24000)) {
327
+ packs.push(pack);
328
+ pack = [];
329
+ size = 0;
330
+ }
331
+ pack.push(matter);
332
+ size += length;
333
+ }
334
+ }
335
+ if (pack.length)
336
+ packs.push(pack);
337
+ let batchFailure;
338
+ for (const batch of packs) {
339
+ try {
340
+ await this.sync();
341
+ guard();
342
+ const candidates = workbenchExistingCandidates(batch, existing), compositionKey = workbenchHash([RECIPE, TEMPORAL_RECIPE, temporalKey, timezone, batch, candidates, batch.filter(m => m.due).map(m => [m.id, m.due < day])]);
343
+ const cachedComposition = this.#state.compositions.find(c => c.key === compositionKey)?.result;
344
+ let result;
345
+ if (cachedComposition)
346
+ result = structuredClone(cachedComposition);
347
+ else {
348
+ this.#state.diagnostics.composition_calls++;
349
+ result = this.#composition(await this.options.generate({ phase: 'compose', matters: batch, existing: candidates, date: day, timezone }, signal));
350
+ guard();
351
+ }
352
+ const pending = batch.filter(m => m.kind !== 'topic'), ids = new Set();
353
+ // Topic rows cannot authorize writes; tolerate models returning these extra matches.
354
+ result.matches = result.matches.filter(match => !batch.some(m => m.kind === 'topic' && m.id === match.matter_id));
355
+ if (result.matches.length !== pending.length)
356
+ invalidMatches('count');
357
+ for (const match of result.matches) {
358
+ const matter = pending.find(m => m.id === match.matter_id);
359
+ if (!matter)
360
+ invalidMatches('unknown_matter');
361
+ if (ids.has(match.matter_id))
362
+ invalidMatches('duplicate_matter');
363
+ ids.add(match.matter_id);
364
+ if (match.target_id !== null && !candidates.some(c => c.id === match.target_id && c.kind === matter.kind))
365
+ invalidMatches('invalid_target');
366
+ if (match.same_as !== null && (!pending.some(m => m.id === match.same_as && m.kind === matter.kind) || match.same_as === matter.id || result.matches.some(other => other.matter_id === match.same_as && other.same_as !== null)))
367
+ invalidMatches('invalid_same_as');
368
+ }
369
+ this.#state.compositions = [...this.#state.compositions.filter(c => c.key !== compositionKey), { key: compositionKey, result }].slice(-256);
370
+ await this.#save();
371
+ result = structuredClone(result);
372
+ // A lexical shortlist cannot prove absence. Check the remaining compact records before any automatic add.
373
+ const unresolved = result.matches.filter(match => match.capture === 'record' && match.target_id === null && match.same_as === null && !incomplete.has(match.matter_id)).map(match => pending.find(m => m.id === match.matter_id)).filter(m => automaticWorkbenchMatter(m, this.#inputs));
374
+ const omitted = existing.filter(row => !candidates.some(c => c.id === row.id) && unresolved.some(m => m.kind === row.kind)).map(row => ({ ...row, note: row.note.slice(0, 300) }));
375
+ for (let offset = 0; offset < omitted.length && unresolved.length; offset += 40) {
376
+ await this.sync();
377
+ guard();
378
+ const shard = omitted.slice(offset, offset + 40), identityKey = workbenchHash([RECIPE, 'identity', unresolved, shard]);
379
+ let checked = this.#state.compositions.find(c => c.key === identityKey)?.result;
380
+ if (!checked) {
381
+ this.#state.diagnostics.composition_calls++;
382
+ checked = this.#composition(await this.options.generate({ phase: 'compose', identity_only: true, matters: unresolved, existing: shard, date: day, timezone }, signal));
383
+ guard();
384
+ }
385
+ if (checked.matches.length !== unresolved.length || new Set(checked.matches.map(m => m.matter_id)).size !== unresolved.length || checked.matches.some(m => !unresolved.some(item => item.id === m.matter_id) || m.target_id !== null && !shard.some(row => row.id === m.target_id && row.kind === unresolved.find(item => item.id === m.matter_id).kind)))
386
+ throw Error('invalid_workbench_matches');
387
+ this.#state.compositions = [...this.#state.compositions.filter(c => c.key !== identityKey), { key: identityKey, result: checked }].slice(-256);
388
+ await this.#save();
389
+ for (const match of checked.matches)
390
+ if (match.target_id !== null) {
391
+ result.matches.find(m => m.matter_id === match.matter_id).target_id = match.target_id;
392
+ unresolved.splice(unresolved.findIndex(m => m.id === match.matter_id), 1);
393
+ }
394
+ }
395
+ await this.sync();
396
+ guard();
397
+ for (const match of result.matches) {
398
+ guard();
399
+ const matter = pending.find(m => m.id === match.matter_id);
400
+ const temporalGroup = groupFor.get(matter.id);
401
+ const target = existing.find(row => row.id === match.target_id && row.kind === matter.kind);
402
+ const targetIds = new Set(result.matches.filter(m => m.target_id !== null && groupFor.get(m.matter_id)?.id === temporalGroup.id).map(m => m.target_id));
403
+ if (target && targetIds.size === 1 && matter.kind !== 'topic' && (matter.state === 'completed' || matter.state === 'cancelled') && !['done', 'completed', 'cancelled', 'archived'].includes(target.status) && !this.#state.recorded.some(r => r.id === target.id && r.undone)) {
404
+ const refs = [...new Map(temporalGroup.basis.flatMap(m => m.refs).map(ref => [ref.entry_id, ref])).values()];
405
+ if (refs.length <= 8 && refs.length && refs.every(ref => this.#grounded([ref]))) {
406
+ const status = matter.state === 'completed' ? 'completed' : 'archived';
407
+ const id = workbenchHash(['status-update', target.id, target.version, status, refs]);
408
+ if (!cards.some(card => card.id === id))
409
+ cards.push({ id, candidate_id: id, tab: 'goals', title: target.title.slice(0, 80), body: matter.state === 'completed' ? '后续资料显示这件事已完成,可以更新原记录。' : '后续资料显示这件事已取消,可以更新原记录。', why: null, next: null, refs, sources: this.sourcesForRefs(refs), update: { id: target.id, kind: matter.kind, version: target.version, status } });
410
+ }
411
+ }
412
+ if (match.capture !== 'record' || match.target_id !== null || match.same_as !== null || incomplete.has(matter.id) || capturedGroups.has(temporalGroup.id) || !automaticWorkbenchMatter(matter, this.#inputs) || !this.#matterCurrent(matter) || this.#state.recorded.some(r => r.matter.id === matter.id))
413
+ continue;
414
+ await this.sync();
415
+ guard();
416
+ if (!this.#matterCurrent(matter))
417
+ continue;
418
+ const life = this.options.life();
419
+ await life.refresh();
420
+ guard();
421
+ // A concurrent edit invalidates the identity decision, rather than silently using stale context.
422
+ if (workbenchHash(this.#existing()) !== workbenchHash(existing))
423
+ throw Error('workbench_records_changed');
424
+ const check = () => { guard(); if (!this.#matterCurrent(matter))
425
+ throw Error('candidate_stale_source'); };
426
+ const recovered = life.snapshot().goals.find(row => row.workbench_source?.candidate_id === matter.id);
427
+ const saved = recovered ?? await life.mutate({ op: 'from_workbench', kind: matter.kind, title: matter.title, note: matter.summary, due: null, success_criteria: '', automatic: true, source: { candidate_id: matter.id, refs: matter.refs }, proof: workbenchMatterSchema.parse(Object.fromEntries(Object.entries(matter).filter(([key]) => !['id', 'group', 'observed_at'].includes(key)))), evidence: this.#inputs.filter(input => matter.refs.some(ref => ref.entry_id === input.id)), sources: this.sourcesForRefs(matter.refs) }, 'workbench:' + matter.id, check);
428
+ this.#state.recorded.push({ matter: { id: matter.id, kind: matter.kind, title: matter.title, summary: matter.summary }, id: saved.id, version: saved.version, undone: false });
429
+ await this.#save();
430
+ this.#state.diagnostics.recorded++;
431
+ capturedGroups.add(temporalGroup.id);
432
+ existing.splice(0, existing.length, ...this.#existing());
433
+ // Persisting an inferred Life object may notify the host of a source change.
434
+ // Recheck it before judging subsequent records or suggestions from this batch.
435
+ if (this.#pendingValidation) {
436
+ await this.sync();
437
+ guard();
438
+ }
439
+ }
440
+ for (const suggestion of result.suggestions) {
441
+ const basis = suggestion.matter_ids.map(id => batch.find(m => m.id === id));
442
+ if (basis.some(m => !m || !this.#matterCurrent(m)) || workbenchSensitive(JSON.stringify(suggestion))) {
443
+ this.#state.diagnostics.rejected++;
444
+ continue;
445
+ }
446
+ if (suggestion.tab !== 'ideas' && basis.some(m => m.state !== 'open' || capturedGroups.has(groupFor.get(m.id).id) || this.#state.recorded.some(r => r.matter.id === m.id) || result.matches.some(match => match.matter_id === m.id && (match.target_id !== null || match.same_as !== null || match.capture !== 'suggest')))) {
447
+ this.#state.diagnostics.rejected++;
448
+ continue;
449
+ }
450
+ const refs = [...new Map(basis.flatMap(m => m.refs).map(ref => [ref.entry_id, ref])).values()];
451
+ if (refs.length > 8 || unresolvedWorkbenchReference({ ...suggestion, refs })) {
452
+ this.#state.diagnostics.rejected++;
453
+ continue;
454
+ }
455
+ if (this.#state.legacy_dismissed.some(old => old.tab === suggestion.tab && old.refs.every(ref => refs.some(current => current.entry_id === ref.entry_id))))
456
+ continue;
457
+ const id = workbenchHash([TEMPORAL_RECIPE, suggestion.tab, [...new Set(suggestion.matter_ids.map(id => groupFor.get(id).id))].sort()]);
458
+ if (cards.some(card => card.id === id))
459
+ continue;
460
+ cards.push({ id, candidate_id: id, tab: suggestion.tab, title: suggestion.title, body: suggestion.body, why: suggestion.why, next: suggestion.next, refs, sources: this.sourcesForRefs(refs) });
461
+ }
462
+ // Keep validated batches visible if a later model call fails.
463
+ this.#publish(cards);
464
+ await this.#save();
465
+ this.options.changed();
466
+ }
467
+ catch (error) {
468
+ signal.throwIfAborted();
469
+ if (error instanceof Error && error.message === 'workbench_records_changed')
470
+ throw error;
471
+ batchFailure = error;
472
+ }
473
+ }
474
+ if (batchFailure)
475
+ throw batchFailure instanceof Error ? batchFailure : Error('generation_failed');
476
+ guard();
477
+ this.#publish(cards);
478
+ this.#state.key = this.#key(inputs);
479
+ this.#state.updated_at = this.#now().toISOString();
480
+ await this.#save();
481
+ this.#status = 'ready';
482
+ }
483
+ catch (error) {
484
+ this.#status = 'failed';
485
+ this.#error = cancel.aborted ? 'sources_changed' : error instanceof Error && ['invalid_workbench_matches', 'workbench_records_changed'].includes(error.message) ? error.message : 'generation_failed';
486
+ if (cancel.aborted && automatic && !force)
487
+ this.#state.automatic_day = spentDay;
488
+ this.#state.failure = error instanceof z.ZodError ? error.issues.map(issue => issue.path.join('.') + ':' + issue.code).join(',').slice(0, 1000) : error instanceof Error && 'classification' in error && typeof error.classification === 'string' && /^[a-zA-Z0-9_]{1,80}$/u.test(error.classification) ? error.classification : error instanceof Error && error.name === 'TimeoutError' ? 'generation_timeout' : error instanceof Error && 'code' in error && typeof error.code === 'string' && /^[A-Z_]+$/u.test(error.code) ? error.code : error instanceof Error && /^[a-zA-Z0-9_.:-]{1,160}$/u.test(error.message) ? error.message : this.#error;
489
+ await this.#save().catch(() => undefined);
490
+ }
491
+ }
492
+ async #adoptHistory(id) {
493
+ await this.sync();
494
+ const life = this.options.life(), requestId = 'history-idea:' + workbenchHash([this.#scope(), id]);
495
+ await life.refresh();
496
+ const prior = life.receipt(requestId);
497
+ if (prior) {
498
+ await this.#hide(id);
499
+ return prior;
500
+ }
501
+ const row = this.snapshot().idea_history.find(row => row.id === id);
502
+ if (!row)
503
+ throw Error('card_not_found');
504
+ // Explicitly keeping an older interpretation creates a personal note, not a claim that
505
+ // its superseded evidence is still current. Its original citations stay in history.
506
+ const result = await life.mutate({ op: 'create', kind: 'idea', title: row.title.slice(0, 200), note: [row.body, row.next].filter(Boolean).join('\n').slice(0, 4000) }, requestId, () => { if (!this.snapshot().idea_history.some(row => row.id === id))
507
+ throw Error('candidate_stale_source'); });
508
+ await this.#hide(id);
509
+ return result;
510
+ }
511
+ async adopt(id) {
512
+ if (this.#state.history.some(row => row.id === id) && !this.snapshot().cards.some(card => card.id === id))
513
+ return this.#adoptHistory(id);
514
+ const original = this.#state.cards.find(c => c.id === id);
515
+ if (!original)
516
+ throw Error('card_not_found');
517
+ await this.sync();
518
+ await this.options.life().refresh();
519
+ const card = this.snapshot().cards.find(c => c.id === id);
520
+ if (!card)
521
+ throw Error(original.update ? 'version_conflict' : 'candidate_stale_source');
522
+ if (workbenchHash(card) !== workbenchHash({ ...original, refs: original.refs.map(ref => ({ ...ref, label: ref.quote })) }))
523
+ throw Error('candidate_stale_source');
524
+ if (!this.#grounded(card.refs) || card.tab !== 'ideas' && !this.#temporalCurrent())
525
+ throw Error('candidate_stale_source');
526
+ if (card.update) {
527
+ const update = card.update, life = this.options.life();
528
+ await life.refresh();
529
+ const result = await life.mutate({ op: 'update', kind: update.kind, id: update.id, expected_version: update.version, status: update.status }, 'workbench-update:' + card.id, () => { if (!this.#grounded(card.refs) || card.tab !== 'ideas' && !this.#temporalCurrent())
530
+ throw Error('candidate_stale_source'); });
531
+ await this.#hide(id);
532
+ return result;
533
+ }
534
+ const result = await this.options.life().mutate({ op: 'from_workbench', kind: card.tab === 'ideas' ? 'idea' : 'goal', title: card.title, note: [card.body, card.next].filter(Boolean).join('\n'), due: null, success_criteria: card.tab === 'goals' ? card.body : '', automatic: false, source: { candidate_id: card.id, refs: card.refs.map(({ entry_id, version, quote }) => ({ entry_id, version: String(version), quote })) }, sources: card.sources, evidence: this.#inputs.filter(input => card.refs.some(ref => ref.entry_id === input.id)) }, 'workbench-adopt:' + card.id, () => { if (!this.#grounded(card.refs) || card.tab !== 'ideas' && !this.#temporalCurrent())
535
+ throw Error('candidate_stale_source'); });
536
+ await this.#hide(id);
537
+ return result;
538
+ }
539
+ async undo(id) {
540
+ const record = this.#state.recorded.find(r => r.id === id);
541
+ if (!record)
542
+ throw Error('record_not_found');
543
+ const life = this.options.life();
544
+ await life.refresh();
545
+ const item = life.snapshot().goals.find(r => r.id === id);
546
+ if (item?.version !== 1)
547
+ throw Error('version_conflict');
548
+ // Persist suppression before removal so a crash cannot recreate an undone automatic record.
549
+ record.undone = true;
550
+ await this.#save();
551
+ await life.mutate({ op: 'undo_create', id, kind: record.matter.kind, expected_version: 1 }, 'workbench-undo:' + id);
552
+ this.options.changed();
553
+ }
554
+ sourceChanged(refs) { return !this.#grounded(refs); }
555
+ async clear() { await this.close(); this.#state = { ...empty(), legacy_imported: true, legacy_dismissed: this.#state.legacy_dismissed, dismissed: this.#state.dismissed, automatic_day: this.#state.automatic_day, recorded: this.#state.recorded }; this.#inputs = []; await this.#save(); this.#opened = true; this.#abort = new AbortController(); }
556
+ async close() { this.#opened = false; clearTimeout(this.#timer); this.#abort.abort(); await this.#run; await this.#sync; await this.#tail; }
557
+ }
558
+ //# sourceMappingURL=daily-workbench.js.map
@@ -0,0 +1,36 @@
1
+ /** Many-to-one pooling for source evidence: arrivals gather until the stream goes quiet or the cap passes. */
2
+ export class DiscoveryWindow {
3
+ #quietMs;
4
+ #maxMs;
5
+ #fire;
6
+ #now;
7
+ #timer;
8
+ #openedAt = 0;
9
+ constructor(options) {
10
+ this.#quietMs = options.quietMs;
11
+ this.#maxMs = options.maxMs;
12
+ this.#fire = options.fire;
13
+ this.#now = options.now ?? Date.now;
14
+ }
15
+ get pending() { return this.#timer !== undefined; }
16
+ /** New evidence arrived: fire after `quietMs` of silence, but never later than `maxMs` after the first arrival. */
17
+ touch() {
18
+ // No pooling: the caller owns the outcome, so a discovery failure reaches it as before.
19
+ if (this.#quietMs <= 0)
20
+ return this.#fire();
21
+ const now = this.#now();
22
+ if (this.#timer === undefined)
23
+ this.#openedAt = now;
24
+ else
25
+ clearTimeout(this.#timer);
26
+ const wait = Math.max(0, Math.min(this.#quietMs, this.#openedAt + this.#maxMs - now));
27
+ this.#timer = setTimeout(() => { this.#timer = undefined; void Promise.resolve(this.#fire()).catch(() => { }); }, wait);
28
+ this.#timer.unref();
29
+ }
30
+ cancel() {
31
+ if (this.#timer !== undefined)
32
+ clearTimeout(this.#timer);
33
+ this.#timer = undefined;
34
+ }
35
+ }
36
+ //# sourceMappingURL=discovery-window.js.map