nova-personal-agent-server 0.4.1 → 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 +10 -0
  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 +11 -4
  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
@@ -3,6 +3,7 @@ import { z } from 'zod';
3
3
  import { BoundedJsonStore } from '../storage/bounded-json.js';
4
4
  import { taskDecisionSchema } from './task-loop.js';
5
5
  import { canonicalJson } from '../text/canonical-json.js';
6
+ import { planSchema } from './workbench-store.js';
6
7
  const eventSchema = z.object({
7
8
  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
9
  }).strict().refine(event => event.kind !== 'message' || event.sender !== undefined, 'message_sender_required');
@@ -11,7 +12,7 @@ export const taskTriggerSchema = z.object({ kind: z.literal('schedule'), schedul
11
12
  export const taskInputSchema = z.object({
12
13
  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
14
  }).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
+ export const internalTaskInputSchema = taskInputSchema.extend({ approved_plan: planSchema.optional(), 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
16
  const actorSchema = z.union([z.object({ kind: z.literal('nova') }).strict(), z.object({ kind: z.literal('user'), client_id: id }).strict()]);
16
17
  export const taskFenceSchema = z.object({
17
18
  task_id: id, control_revision: z.number().int().nonnegative(), goal_revision: z.number().int().nonnegative()
@@ -21,7 +22,7 @@ const controlChangeSchema = z.object({ fence: taskFenceSchema, actor: actorSchem
21
22
  const goalChangeSchema = z.object({
22
23
  fence: taskFenceSchema, actor: actorSchema, goal: goalSchema.shape.goal, acceptance: goalSchema.shape.acceptance
23
24
  }).strict();
24
- const recordSchema = taskInputSchema.extend({ trigger: taskTriggerSchema.optional(),
25
+ const recordSchema = taskInputSchema.extend({ approved_plan: planSchema.optional(), trigger: taskTriggerSchema.optional(),
25
26
  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
27
  }).strict();
27
28
  const evidenceSchema = z.object({
@@ -282,6 +283,7 @@ export class TaskService {
282
283
  return structuredClone(prior.result);
283
284
  }
284
285
  const task = {
286
+ ...(parsed.approved_plan ? { approved_plan: parsed.approved_plan } : {}),
285
287
  ...(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
288
  };
287
289
  next.tasks.push(task);
@@ -729,7 +731,14 @@ export class TaskService {
729
731
  task.phase = 'waiting';
730
732
  else if (task.phase === 'waiting')
731
733
  task.phase = task.work_ids.length ? 'verifying' : 'queued';
732
- });
734
+ }, { when: state => {
735
+ const task = state.tasks.find(task => task.id === taskId);
736
+ if (!task)
737
+ return false;
738
+ if (task.phase === 'completed' || task.phase === 'cancelled')
739
+ return true;
740
+ return task.waiting_reason === reason && (reason ? task.phase === 'waiting' : task.phase !== 'waiting');
741
+ }, value: undefined });
733
742
  }
734
743
  resourceState(taskId, reason) {
735
744
  return this.#mutate(next => {
@@ -900,8 +909,11 @@ export class TaskService {
900
909
  return false;
901
910
  });
902
911
  }
903
- #mutate(change) {
912
+ #mutate(change, unchanged) {
904
913
  const run = this.#tail.then(async () => {
914
+ // Test under the mutation queue so earlier transitions cannot be skipped.
915
+ if (unchanged?.when(this.#state))
916
+ return unchanged.value;
905
917
  const next = structuredClone(this.#state), result = await change(next);
906
918
  for (const taskId of this.#incompleteReplay)
907
919
  if (!next.replay_incomplete.includes(taskId))
@@ -0,0 +1,462 @@
1
+ import { selectTimelineInputs } from './timeline-inputs.js';
2
+ import { temporalSchema, resolvedTimeSchema, resolveTimelineTime, effectiveTimelineAnchor } from './timeline-time.js';
3
+ import { SensitiveContentPolicy } from '../memory/sensitivity.js';
4
+ import { createHash } from 'node:crypto';
5
+ import { z } from 'zod';
6
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
7
+ import { abortable } from '../core/camera-session.js';
8
+ import { sourceTagSchema } from '../memory/provenance.js';
9
+ import { clusterCards } from './timeline-cluster.js';
10
+ /** Shared by generation and publication so omitted identities cannot bypass revision checks. */
11
+ export function timelineRevisionId(priorId, refs, priorCards, infer) {
12
+ if (priorId && priorCards.some(card => card.id === priorId))
13
+ return priorId;
14
+ if (!infer)
15
+ return undefined;
16
+ const candidates = priorCards.filter(card => card.evidence_ids?.some(id => refs.includes(id)));
17
+ return candidates.length === 1 ? candidates[0].id : undefined;
18
+ }
19
+ /** How long a source recheck may run before the cards are shown as being checked. */
20
+ const CHECKING_GRACE_MS = 4000;
21
+ /** Scheduled synthesis is batched by events, not polled. */
22
+ const TIMELINE_BATCH_INPUTS = 20;
23
+ const TIMELINE_BATCH_SPACING_MS = 10 * 60_000;
24
+ const TIMELINE_DAY_SPACING_MS = 30 * 60_000;
25
+ const TIMELINE_IDLE_SPACING_MS = 4 * 3600_000;
26
+ const MESSAGE_KINDS = new Set(['im', 'mail', 'calendar']);
27
+ export const TIMELINE_MAX_REFS = 16;
28
+ const ref = z.string().min(1).max(600);
29
+ export const timelineReplySchema = z.object({ cards: z.array(z.object({
30
+ temporal: temporalSchema.default({ kind: 'unknown', dates: [] }),
31
+ kind: z.enum(['attention', 'deadline', 'progress', 'insight']).default('insight'), status_label: z.string().trim().max(18).default(''),
32
+ people: z.array(z.object({ name: z.string().trim().min(1).max(60), quote: z.string().min(1).max(600), ref }).strict()).max(8).default([]),
33
+ category: z.string().trim().min(1).max(40), title: z.string().trim().min(1).max(96), why_now: z.string().trim().min(1).max(160),
34
+ facts: z.array(z.object({ label: z.string().trim().max(32).default(''), tone: z.enum(['neutral', 'risk', 'warning', 'positive']).default('neutral'), text: z.string().trim().min(1).max(160), quote: z.string().min(1).max(600), ref }).strict()).min(1).max(3),
35
+ next_steps: z.array(z.object({ title: z.string().trim().min(1).max(40), detail: z.string().trim().min(1).max(100) }).strict()).max(3).default([]),
36
+ uncertainty: z.string().max(160), actions: z.array(z.object({ label: z.string().trim().min(1).max(40), kind: z.enum(['discuss', 'draft']) }).strict()).max(2), refs: z.array(ref).min(1).max(TIMELINE_MAX_REFS),
37
+ /** Set only when this output revises an already published card; the host then keeps that stable identity. */
38
+ prior_id: z.string().min(1).max(128).optional(),
39
+ }).strict()) }).strict();
40
+ /** Names are presentation hints, not inferred assignments or authority. */
41
+ export function groundedTimelinePeople(card, inputs) {
42
+ const cited = new Set([...card.refs, ...card.facts.map(fact => fact.ref)]), seen = new Set();
43
+ const prose = [card.title, ...card.facts.map(fact => fact.text)].join('\n');
44
+ return card.people.filter(person => {
45
+ const input = inputs.get(person.ref), namedAuthor = input?.author?.kind === 'person' && !input.author.is_user && input.author.name === person.name;
46
+ if (!cited.has(person.ref) || !input?.text.includes(person.quote) || !person.quote.includes(person.name) && !namedAuthor || !prose.includes(person.name) || seen.has(person.name))
47
+ return false;
48
+ seen.add(person.name);
49
+ return true;
50
+ });
51
+ }
52
+ const count = z.number().int().nonnegative();
53
+ export const timelineDiagnosticsSchema = z.object({
54
+ input_count: count, selected_inputs: count, screened_topics: count, composition_batches: count,
55
+ pending_batches: count.default(0),
56
+ failed_batches: z.array(z.object({ batch: count, reason: z.string() })).default([]),
57
+ stages: z.array(z.object({ batch: count, phase: z.enum(['compose', 'review']), received: count, accepted: count, dropped: z.record(z.string(), count) })),
58
+ host_received: count.default(0), published: count.default(0), host_dropped: z.record(z.string(), count).default({}),
59
+ // Incremental cache counters are part of the persisted shape; parse would strip them otherwise.
60
+ cache_reused_topics: count.default(0), cache_reused_inputs: count.default(0), cache_screened_inputs: count.default(0), cache_stage_hits: count.default(0), cache_stage_misses: count.default(0),
61
+ /** Topics whose inputs were all already published, so their existing cards stay the answer. */
62
+ cache_skipped_topics: count.default(0),
63
+ /** Repeated routine alerts folded into one batch entry, and revisions that ignored a new state change. */
64
+ duplicates_folded: count.default(0), cards_folded: count.default(0), stale_state_repairs: count.default(0), stale_state_dropped: count.default(0),
65
+ });
66
+ const cardSchema = timelineReplySchema.shape.cards.element.omit({ prior_id: true }).extend({ id: z.string(), version: z.string(), timezone: z.string().optional(), artifact_scope: z.string().optional(), evidence_basis: z.array(z.object({ id: ref, version: z.string() })).optional(), policy_revision: z.number().int().optional(), sources: z.array(sourceTagSchema), time: resolvedTimeSchema });
67
+ const failureSchema = z.object({ name: z.string(), code: z.string(), issues: z.array(z.object({ code: z.string(), path: z.array(z.union([z.string(), z.number()])), maximum: z.number().optional() })).optional() });
68
+ /** State v2 stores the last successful synthesis as a checkpoint: which inputs it covered and which generation it produced. */
69
+ const checkpointSchema = z.object({ last_success_at: z.string().nullable(), input_versions: z.array(z.object({ id: ref, version: z.string() })), generation: z.string() });
70
+ /** v1 states are migrated in place (checkpoint derived from key/basis/updated_at); running the migration again is a no-op. */
71
+ const migrateTimelineState = (raw) => {
72
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
73
+ return raw;
74
+ const state = raw, saved = state.checkpoint;
75
+ if (state.version === 2 && saved && typeof saved === 'object' && !Array.isArray(saved))
76
+ return raw;
77
+ if (state.version !== 1 && state.version !== 2 && state.version !== undefined)
78
+ return raw;
79
+ return { ...state, version: 2, checkpoint: { last_success_at: typeof state.updated_at === 'string' ? state.updated_at : null, input_versions: Array.isArray(state.basis) ? state.basis : [], generation: typeof state.key === 'string' ? state.key : '' } };
80
+ };
81
+ const stateSchema = z.preprocess(migrateTimelineState, z.object({ diagnostics: timelineDiagnosticsSchema.nullable().default(null), failure: failureSchema.nullable().default(null), version: z.literal(2), checkpoint: checkpointSchema, perspective_revision: z.number().int().default(0), key: z.string(), local_date: z.string(), timezone: z.string().nullable().default(null), basis: z.array(z.object({ id: ref, version: z.string() })), cards: z.array(cardSchema), updated_at: z.string().nullable(), last_attempt: z.number(), dismissed: z.array(z.string()).max(256) }));
82
+ const empty = () => ({ diagnostics: null, failure: null, version: 2, checkpoint: { last_success_at: null, input_versions: [], generation: '' }, perspective_revision: 1, key: '', local_date: '', timezone: null, basis: [], cards: [], updated_at: null, last_attempt: 0, dismissed: [] });
83
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
84
+ const scrubber = new SensitiveContentPolicy();
85
+ const sensitive = (text) => scrubber.scrub('timeline', text).kind !== 'clean';
86
+ /** Read-only derived attention cards. This owns no task execution or Life mutation authority. */
87
+ export class TimelineBrief {
88
+ generate;
89
+ changed;
90
+ #persisted = empty();
91
+ #loadFailed = false;
92
+ get loadFailed() { return this.#loadFailed; }
93
+ #access;
94
+ #cache;
95
+ #pendingValidation = false;
96
+ #epoch = 0;
97
+ #suspendedAt = 0;
98
+ #tail = Promise.resolve();
99
+ #defer = true;
100
+ #store;
101
+ #state = empty();
102
+ #inputs = [];
103
+ #date = '';
104
+ #timezone = 'UTC';
105
+ #status = 'idle';
106
+ #error = null;
107
+ #opened = false;
108
+ #timer;
109
+ #abort = new AbortController();
110
+ #run;
111
+ constructor(path, generate, changed, options) {
112
+ this.generate = generate;
113
+ this.changed = changed;
114
+ this.#store = new BoundedJsonStore(path, stateSchema);
115
+ this.#cache = options?.cache;
116
+ }
117
+ async open() {
118
+ this.#loadFailed = false;
119
+ try {
120
+ this.#state = await this.#store.read(empty());
121
+ if (this.#state.timezone)
122
+ for (const card of this.#state.cards)
123
+ card.timezone ??= this.#state.timezone;
124
+ }
125
+ catch (error) {
126
+ if (!(error instanceof z.ZodError) && !(error instanceof SyntaxError))
127
+ throw error;
128
+ this.#loadFailed = true;
129
+ this.#state = empty();
130
+ }
131
+ if (this.#dropDuplicates())
132
+ await this.#save();
133
+ // Older progress writes claimed the whole pool even when a batch failed or never finished.
134
+ if (this.#state.checkpoint.generation && this.#state.checkpoint.generation === this.#state.key && (this.#state.failure || this.#state.diagnostics?.failed_batches.length || this.#state.diagnostics?.pending_batches))
135
+ this.#state.checkpoint = { last_success_at: null, input_versions: [], generation: '' };
136
+ this.#persisted = structuredClone(this.#state);
137
+ this.#access = undefined;
138
+ this.#inputs = [];
139
+ this.#date = '';
140
+ this.#status = 'idle';
141
+ this.#defer = true;
142
+ this.#opened = true;
143
+ this.#abort = new AbortController();
144
+ }
145
+ startGeneration() { this.#defer = false; this.#schedule(); }
146
+ #save() { const state = structuredClone(this.#state); const run = this.#tail.then(async () => { await this.#store.write(state); this.#persisted = state; }); this.#tail = run.catch(() => undefined); return run; }
147
+ /** IDs only: each cached citation must be re-read under current source permissions. */
148
+ retainedEvidenceIds() { return [...new Set(this.#state.cards.filter(card => !this.#dismissed(card)).flatMap(card => card.refs))]; }
149
+ basis(id) { return structuredClone([...new Map(this.#visibleCards().filter(card => (!id || card.id === id) && this.#sourcesAvailable(card)).flatMap(card => (card.evidence_basis ?? this.#state.basis).filter(input => card.refs.includes(input.id))).map(input => [input.id, input])).values()]); }
150
+ async clear() { this.#epoch++; this.#abort.abort(); await this.#run; this.#abort = new AbortController(); this.#state = empty(); this.#inputs = []; await this.#save(); this.#loadFailed = false; this.changed(); }
151
+ /** Counts every event after which previously read inputs may no longer be authorized; a cached read is reusable only within one epoch. */
152
+ get epoch() { return this.#epoch; }
153
+ suspend() { this.#epoch++; if (!this.#pendingValidation)
154
+ this.#suspendedAt = Date.now(); this.#pendingValidation = true; this.changed(); }
155
+ /** A recheck that finishes within the grace window is invisible; only a slow one shows the checking state, so source events do not make cards and their buttons blink. */
156
+ #checking() { return this.#pendingValidation && Date.now() - this.#suspendedAt > CHECKING_GRACE_MS; }
157
+ invalidate() { this.#epoch++; this.update([], this.#date, this.#timezone, this.#access ? { ...this.#access, legacy_refs: [] } : { scope: 'local', allowed: true, legacy_refs: [] }); }
158
+ unavailable() { this.invalidate(); this.#status = 'failed'; this.#error = 'timeline_sources_unavailable'; this.changed(); }
159
+ #key() { return hash(['timeline-scope-v15', this.#date, this.#timezone, this.#inputs.map(({ id, version }) => ({ id, version }))]); }
160
+ #compatible(basis, date, timezone) {
161
+ if (date !== this.#date || timezone !== this.#timezone)
162
+ return false;
163
+ const versions = new Map(this.#inputs.map(input => [input.id, input.version]));
164
+ return basis.every(input => versions.get(input.id) === input.version);
165
+ }
166
+ setAccess(access) {
167
+ if (this.#access?.scope !== access.scope || !access.allowed) {
168
+ this.#epoch++;
169
+ this.#abort.abort();
170
+ this.#abort = new AbortController();
171
+ this.#inputs = [];
172
+ }
173
+ this.#access = { ...access, legacy_refs: [...access.legacy_refs] };
174
+ }
175
+ #dismissed(card, state = this.#state) { return state.dismissed.includes(`${card.artifact_scope ?? ''}:${card.id}`) || !card.artifact_scope && state.dismissed.includes(card.id); }
176
+ #sourcesAvailable(card, state = this.#state, duringRecheck = false) {
177
+ if (this.#pendingValidation && !duringRecheck)
178
+ return false;
179
+ const inputs = new Map(this.#inputs.map(input => [input.id, input])), basis = new Map((card.evidence_basis ?? state.basis).map(input => [input.id, input.version]));
180
+ // A message's version also covers permission bookkeeping (source fence, grant revision), which changes on pause, resume and rescan
181
+ // without the message changing; presence is the proof for messages. Files and memories keep the exact-version check.
182
+ return card.refs.every(ref => { const input = inputs.get(ref); return !!input && (MESSAGE_KINDS.has(input.kind) || input.version === basis.get(ref)); });
183
+ }
184
+ /** Cited message ids that are absent from the current inputs; the host asks the ledger which of them were really deleted. */
185
+ missingMessageRefs() {
186
+ const present = new Set(this.#inputs.map(input => input.id));
187
+ return [...new Set(this.#state.cards.flatMap(card => card.refs).filter(id => !present.has(id) && !id.startsWith('source:') && !id.startsWith('memory:')))];
188
+ }
189
+ /** Removes cards that cite a message that no longer exists. Cards whose source is merely paused or unauthorized stay. */
190
+ async retire(ids) {
191
+ if (!ids.size)
192
+ return 0;
193
+ const before = this.#state.cards.length;
194
+ this.#state.cards = this.#state.cards.filter(card => !card.refs.some(ref => ids.has(ref)));
195
+ const removed = before - this.#state.cards.length;
196
+ if (removed) {
197
+ await this.#save();
198
+ this.changed();
199
+ }
200
+ return removed;
201
+ }
202
+ /** Deletes cards that repeat a stronger card (same cited message, same matter). Cards that revise a published card are kept. */
203
+ #dropDuplicates() {
204
+ const byScope = new Map();
205
+ for (const card of this.#state.cards)
206
+ byScope.set(card.artifact_scope, [...(byScope.get(card.artifact_scope) ?? []), card]);
207
+ const drop = new Set();
208
+ for (const group of byScope.values())
209
+ for (const cluster of clusterCards(group))
210
+ for (const member of cluster.members)
211
+ drop.add(member);
212
+ if (!drop.size)
213
+ return 0;
214
+ const dropped = new Set([...drop].map(card => card.id));
215
+ this.#state.cards = this.#state.cards.filter(card => !drop.has(card));
216
+ this.#state.dismissed = this.#state.dismissed.filter(entry => ![...dropped].some(id => entry === id || entry.endsWith(':' + id)));
217
+ return drop.size;
218
+ }
219
+ #visibleCards(state = this.#state) {
220
+ if (!this.#access?.allowed)
221
+ return [];
222
+ return state.cards.filter(card => card.artifact_scope === this.#access.scope && !this.#dismissed(card, state));
223
+ }
224
+ #current(state = this.#state) { return this.#visibleCards(state).length > 0 || state.perspective_revision === 1 && !this.#pendingValidation && state.key === this.#key(); }
225
+ snapshot(persisted = false) {
226
+ const state = persisted ? this.#persisted : this.#state, counts = { messages: 0, files: 0, memories: 0 }, dates = [];
227
+ for (const input of this.#inputs) {
228
+ if (input.kind === 'file')
229
+ counts.files++;
230
+ else if (input.kind === 'memory')
231
+ counts.memories++;
232
+ else {
233
+ counts.messages++;
234
+ if (Number.isFinite(Date.parse(input.observed_at)))
235
+ dates.push(new Date(input.observed_at).toLocaleDateString('en-CA', { timeZone: this.#timezone }));
236
+ }
237
+ }
238
+ dates.sort();
239
+ // Persisted cards predate the effective-anchor rule; re-derive placement here so cached
240
+ // deadline/scheduled cards are not grouped after today without a regeneration.
241
+ const placed = (card) => card.time ? { ...card, time: { ...card.time, ...effectiveTimelineAnchor(card.time) } } : card;
242
+ const cards = structuredClone(this.#visibleCards(state).map(raw => placed(raw)).map(card => ({ ...card, sources_available: this.#sourcesAvailable(card, state, !this.#checking()), sources_checking: this.#checking(), historical: card.policy_revision !== 1 || !this.#sourcesAvailable(card, state, !this.#checking()) })));
243
+ const activeCount = cards.filter(card => card.sources_available).length;
244
+ return { generation_id: this.#current(state) ? state.key : null, diagnostics: this.#current(state) ? structuredClone(state.diagnostics) : null, available: !!this.generate, status: this.#status, error: this.#error, updated_at: this.#current(state) ? state.updated_at : null, input_count: this.#inputs.length, coverage: `本轮资料:${counts.messages} 条消息 · ${counts.files} 份文档 · ${counts.memories} 条个人记录${dates.length ? ';消息记录 ' + dates[0] + '—' + dates.at(-1) : ''}`, cards,
245
+ /** Active cards still have their original evidence; archived cards are retained history whose sources moved or were withdrawn. */
246
+ active_count: activeCount, archived_count: cards.length - activeCount,
247
+ /** Stable across batch-progress publishes, so an expanded page stays expanded while the same generation runs. */
248
+ pagination_key: state.key || this.#key(), checkpoint: { last_success_at: state.checkpoint.last_success_at, generation: state.checkpoint.generation } };
249
+ }
250
+ update(inputs, date, timezone, access = { scope: 'local', allowed: true, legacy_refs: inputs.map(input => input.id) }) {
251
+ this.setAccess(access);
252
+ const old = this.#key(), previous = this.#inputs, previousDate = this.#date, previousZone = this.#timezone, pending = this.#pendingValidation;
253
+ this.#pendingValidation = false;
254
+ const eligible = inputs.filter(input => input.text.trim() && !sensitive(input.text)), selected = selectTimelineInputs(eligible.filter(input => !input.history_only)), selectedIds = new Set(selected.map(input => input.id)), retained = new Set(this.retainedEvidenceIds());
255
+ this.#inputs = [...selected, ...eligible.filter(input => retained.has(input.id) && !selectedIds.has(input.id))];
256
+ this.#date = date;
257
+ this.#timezone = timezone;
258
+ if (old !== this.#key()) {
259
+ const additionsOnly = previous.length > 0 && this.#compatible(previous, previousDate, previousZone);
260
+ if (!additionsOnly) {
261
+ this.#abort.abort();
262
+ this.#abort = new AbortController();
263
+ }
264
+ this.#error = null;
265
+ this.#status = this.#run && additionsOnly ? 'working' : this.#current() ? 'ready' : this.#inputs.length ? 'queued' : 'idle';
266
+ this.changed();
267
+ }
268
+ else if (pending) {
269
+ if (this.#current())
270
+ this.#status = this.#run ? 'working' : 'ready';
271
+ this.changed();
272
+ }
273
+ // Bind legacy output only while every original reference can still prove its scope.
274
+ const safe = new Set(access.legacy_refs);
275
+ let migrated = false;
276
+ for (const card of this.#state.cards)
277
+ if (!card.artifact_scope && card.refs.every(id => safe.has(id)) && this.#sourcesAvailable(card)) {
278
+ if (this.#state.dismissed.includes(card.id))
279
+ this.#state.dismissed = this.#state.dismissed.map(id => id === card.id ? `${access.scope}:${id}` : id);
280
+ card.artifact_scope = access.scope;
281
+ card.evidence_basis = this.#state.basis.filter(input => card.refs.includes(input.id));
282
+ card.policy_revision = this.#state.perspective_revision;
283
+ migrated = true;
284
+ }
285
+ if (migrated) {
286
+ if (this.#visibleCards().length && !this.#run)
287
+ this.#status = 'ready';
288
+ void this.#save().catch(() => undefined);
289
+ this.changed();
290
+ }
291
+ this.#schedule();
292
+ }
293
+ #schedule() {
294
+ clearTimeout(this.#timer);
295
+ this.#timer = undefined;
296
+ if (!this.#access?.allowed || this.#pendingValidation || this.#defer || !this.#opened || !this.generate || this.#run || !this.#inputs.some(input => !input.history_only) || this.#key() === this.#state.checkpoint.generation && this.#state.perspective_revision === 1)
297
+ return;
298
+ const delay = this.#scheduleDelay();
299
+ if (delay === undefined)
300
+ return;
301
+ this.#timer = setTimeout(() => { this.#timer = undefined; void this.refresh({ force: false }); }, delay);
302
+ this.#timer.unref();
303
+ }
304
+ /**
305
+ * Event-batched, not polled. A first synthesis (or one from an older recipe) runs promptly; afterwards a batch of new messages runs
306
+ * at most every ten minutes, a new day or an edited file/memory within half an hour, and a trickle of fewer new messages only after
307
+ * hours. Version drift on a message that is already covered (pause, resume, rescan) teaches nothing, so it never triggers a run.
308
+ */
309
+ #scheduleDelay() {
310
+ const state = this.#state, now = Date.now();
311
+ if (state.perspective_revision !== 1 || !state.checkpoint.generation || !state.checkpoint.last_success_at)
312
+ return 1000;
313
+ const covered = new Map(state.checkpoint.input_versions.map(input => [input.id, input.version]));
314
+ const live = this.#inputs.filter(input => !input.history_only);
315
+ const added = live.filter(input => !covered.has(input.id)).length;
316
+ const editedStatic = live.some(input => covered.has(input.id) && covered.get(input.id) !== input.version && !MESSAGE_KINDS.has(input.kind));
317
+ const dayChanged = !!state.local_date && state.local_date !== this.#date;
318
+ const wait = (spacing) => Math.max(1000, state.last_attempt + spacing - now);
319
+ if (added >= TIMELINE_BATCH_INPUTS)
320
+ return wait(TIMELINE_BATCH_SPACING_MS);
321
+ // The inputs are exactly what was synthesized, yet the key moved: a new day, time zone or recipe.
322
+ const sameInputs = live.every(input => covered.get(input.id) === input.version);
323
+ if (dayChanged || editedStatic || sameInputs)
324
+ return wait(TIMELINE_DAY_SPACING_MS);
325
+ if (added > 0)
326
+ return wait(TIMELINE_IDLE_SPACING_MS);
327
+ return undefined;
328
+ }
329
+ /** A manual refresh may force a new synthesis even when the checkpoint already covers the same inputs; the scheduled path never does. */
330
+ async refresh(options = {}) {
331
+ if (this.#run)
332
+ return this.#run;
333
+ if (!this.#access?.allowed || this.#pendingValidation || !this.#opened || !this.generate || !this.#inputs.some(input => !input.history_only))
334
+ return;
335
+ clearTimeout(this.#timer);
336
+ this.#timer = undefined;
337
+ const key = this.#key(), force = options.force !== false;
338
+ // Nothing has changed since the last successful synthesis: the stored cards are already the answer, so no model call is spent.
339
+ if (!force && this.#state.perspective_revision === 1 && this.#state.checkpoint.generation === key) {
340
+ if (this.#current())
341
+ this.#status = 'ready';
342
+ return;
343
+ }
344
+ const checkpointVersions = new Map(this.#state.checkpoint.input_versions.map(({ id, version }) => [id, version]));
345
+ const inputs = structuredClone(selectTimelineInputs(this.#inputs.filter(input => !input.history_only)).map(source => { const input = { ...source }; delete input.account_scope; return input; }));
346
+ const newInputIds = inputs.filter(input => checkpointVersions.get(input.id) !== input.version).map(input => input.id);
347
+ const priorCards = this.#visibleCards().map(card => ({ id: card.id, title: card.title, category: card.category, why_now: card.why_now.slice(0, 120), anchor_date: card.time.anchor_date, evidence_ids: [...new Set(card.refs)].slice(0, TIMELINE_MAX_REFS) }));
348
+ const context = { local_date: this.#date, timezone: this.#timezone, ...(priorCards.length ? { prior_cards: priorCards } : {}), new_input_ids: newInputIds }, cancel = this.#abort.signal, timeout = AbortSignal.timeout(600000), signal = AbortSignal.any([cancel, timeout]);
349
+ this.#status = 'working';
350
+ this.#error = null;
351
+ this.changed();
352
+ const publish = async (generated, done) => {
353
+ if (signal.aborted || !this.#compatible(inputs, context.local_date, context.timezone) || !this.#opened)
354
+ return;
355
+ const result = timelineReplySchema.parse({ cards: generated.cards });
356
+ const diagnostics = timelineDiagnosticsSchema.parse(generated.diagnostics ?? { input_count: inputs.length, selected_inputs: inputs.length, screened_topics: 0, composition_batches: 1, stages: [] });
357
+ diagnostics.host_received = result.cards.length;
358
+ diagnostics.host_dropped = {};
359
+ const drop = (reason) => { diagnostics.host_dropped[reason] = (diagnostics.host_dropped[reason] ?? 0) + 1; return []; };
360
+ const byId = new Map(inputs.map(input => [input.id, input])), seen = new Set();
361
+ // A delta synthesis may revise an already published card; prior_id keeps that card's stable identity and history.
362
+ const revisionCards = priorCards;
363
+ const cards = result.cards.flatMap(raw => {
364
+ const card = { ...raw, people: groundedTimelinePeople(raw, byId) };
365
+ const priorId = card.prior_id;
366
+ delete card.prior_id;
367
+ const refs = [...new Set([...card.refs, ...card.facts.map(fact => fact.ref), ...card.temporal.dates.map(date => date.ref)])];
368
+ if (refs.length > TIMELINE_MAX_REFS)
369
+ return drop('reference_limit');
370
+ if (refs.some(id => !byId.has(id)))
371
+ return drop('unknown_reference');
372
+ if (card.facts.some(fact => !byId.get(fact.ref).text.includes(fact.quote)))
373
+ return drop('unsupported_quote');
374
+ if (sensitive(JSON.stringify(card)))
375
+ return drop('sensitive_content');
376
+ const time = resolveTimelineTime(card.temporal, refs.map(id => byId.get(id)), context);
377
+ if (!time)
378
+ return drop('invalid_time_or_background');
379
+ const recentSince = new Date(Date.parse(context.local_date + 'T00:00:00Z') - 14 * 86400000).toISOString().slice(0, 10);
380
+ if (time.anchor_date && time.anchor_date < recentSince && (!time.last_reported_on || time.last_reported_on < recentSince) && (!time.due_on || time.due_on < recentSince) && (!time.scheduled_on || time.scheduled_on < recentSince))
381
+ return drop('outside_window');
382
+ const newInputs = context.new_input_ids ?? [];
383
+ const stable = timelineRevisionId(priorId, refs, revisionCards, newInputs.length > 0);
384
+ // A revision has to be grounded in at least one new original: unchanged sources alone cannot
385
+ // justify rewriting a published conclusion, so the previous card is kept instead.
386
+ if (stable && !refs.some(id => newInputs.includes(id)))
387
+ return drop('unsupported_revision');
388
+ const id = stable ?? hash([card.title, refs.sort()]);
389
+ if (seen.has(id))
390
+ return drop('duplicate');
391
+ seen.add(id);
392
+ const sources = refs.flatMap(id => { const source = byId.get(id).source; return source ? [{ ...source, summary: card.facts.filter(fact => fact.ref === id).map(fact => fact.quote).join('\n').slice(0, 700) || source.summary }] : []; });
393
+ return [{ ...card, time, timezone: context.timezone, artifact_scope: this.#access.scope, evidence_basis: refs.map(id => ({ id, version: byId.get(id).version })), policy_revision: 1, refs, id, version: hash([card, refs.map(id => byId.get(id).version)]), sources }];
394
+ });
395
+ // A new synthesis updates matching cards; omission is not a withdrawal.
396
+ const merged = new Map(this.#state.cards.map(card => [`${card.artifact_scope ?? ''}:${card.id}`, card]));
397
+ for (const card of cards)
398
+ merged.set(`${card.artifact_scope}:${card.id}`, card);
399
+ const retainedCards = [...merged.values()], changed = hash(retainedCards) !== hash(this.#state.cards);
400
+ const basis = inputs.map(({ id, version }) => ({ id, version })), now = new Date().toISOString();
401
+ const completed = new Set(generated.completed_input_ids ?? (done && !diagnostics.failed_batches.length && !diagnostics.pending_batches ? inputs.map(input => input.id) : []));
402
+ const previous = new Map(this.#state.checkpoint.input_versions.map(input => [input.id, input.version]));
403
+ const covered = basis.filter(input => completed.has(input.id) || previous.get(input.id) === input.version);
404
+ const complete = done && !diagnostics.failed_batches.length && !diagnostics.pending_batches && covered.length === basis.length;
405
+ diagnostics.published = cards.length;
406
+ // updated_at only moves when a card actually changed; a no-op or empty refresh keeps the earlier briefing timestamp.
407
+ this.#state = { ...this.#state, perspective_revision: 1, diagnostics, failure: null, key, local_date: context.local_date, timezone: context.timezone, basis, cards: retainedCards, updated_at: changed ? now : this.#state.updated_at, checkpoint: { last_success_at: complete ? now : this.#state.checkpoint.last_success_at, input_versions: covered, generation: complete ? key : this.#state.checkpoint.generation } };
408
+ this.#dropDuplicates();
409
+ await this.#save();
410
+ this.#loadFailed = false;
411
+ if (done)
412
+ this.#status = 'ready';
413
+ this.changed();
414
+ };
415
+ const work = (async () => {
416
+ try {
417
+ this.#state.last_attempt = Date.now();
418
+ this.#state.failure = null;
419
+ await this.#save();
420
+ signal.throwIfAborted();
421
+ // Every refresh is cache-first, manual ones included; the generator re-authorizes through the host wrapper and only pays for changed input.
422
+ const generated = await abortable(this.generate(inputs, context, signal, result => publish(result, false), { ...(this.#cache ? { cache: this.#cache } : {}), scope: this.#access?.scope ?? 'local', force }), signal);
423
+ signal.throwIfAborted();
424
+ await publish(generated, true);
425
+ }
426
+ catch (error) {
427
+ if (!cancel.aborted) {
428
+ if (error instanceof Error && 'diagnostics' in error) {
429
+ const parsed = timelineDiagnosticsSchema.safeParse(error.diagnostics);
430
+ if (parsed.success)
431
+ this.#state.diagnostics = parsed.data;
432
+ }
433
+ this.#state.failure = { name: error instanceof Error ? error.name : 'unknown', code: error instanceof Error && ['invalid_timeline_evidence', 'invalid_timeline_selection', 'timeline_batches_failed', 'processing_consent_required'].includes(error.message) ? error.message : error instanceof Error && 'classification' in error && typeof error.classification === 'string' ? error.classification : 'unavailable', ...(error instanceof z.ZodError ? { issues: error.issues.map(issue => ({ code: issue.code, path: issue.path.map(part => typeof part === 'number' ? part : String(part)), ...('maximum' in issue && typeof issue.maximum === 'number' ? { maximum: issue.maximum } : {}) })) } : {}) };
434
+ await this.#save().catch(() => undefined);
435
+ }
436
+ if (cancel.aborted) {
437
+ this.#status = this.#inputs.length ? 'queued' : 'idle';
438
+ this.#error = null;
439
+ this.#state.last_attempt = 0;
440
+ }
441
+ else {
442
+ this.#status = 'failed';
443
+ this.#error = timeout.aborted ? 'timeline_generation_timeout' : 'timeline_generation_failed';
444
+ }
445
+ }
446
+ finally {
447
+ this.#run = undefined;
448
+ this.changed();
449
+ this.#schedule();
450
+ }
451
+ })();
452
+ this.#run = work;
453
+ await work;
454
+ }
455
+ async dismiss(id) { if (!this.snapshot().cards.some(card => card.id === id))
456
+ throw Error('stale_reference'); this.#state.dismissed = [...new Set([...this.#state.dismissed, `${this.#access.scope}:${id}`])].slice(-256); await this.#save(); this.#loadFailed = false; this.changed(); }
457
+ /** Looks the card up directly: a full snapshot() would also format a date for every input, which is the slow part with thousands of messages. */
458
+ discussion(id, version) { const card = this.#visibleCards().find(card => card.id === id && card.version === version); if (!card || !this.#sourcesAvailable(card) || card.policy_revision !== 1)
459
+ throw Error('stale_reference'); return { card: structuredClone({ ...card, sources_available: true, sources_checking: this.#checking(), historical: false }), evidence_refs: [...new Set(card.refs.flatMap(ref => { const input = this.#inputs.find(input => input.id === ref); return input.kind === 'file' ? [] : input.evidence_refs ?? [ref]; }))], originals: card.refs.map(ref => { const input = this.#inputs.find(input => input.id === ref); return { text: input.text, observed_at: input.observed_at, relation: input.relation, author: input.author }; }) }; }
460
+ async close() { this.#opened = false; clearTimeout(this.#timer); this.#timer = undefined; this.#abort.abort(); await this.#run; await this.#tail; }
461
+ }
462
+ //# sourceMappingURL=timeline-brief.js.map