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,841 @@
1
+ import { chatFailure } from '../personal-agent/chat-failure.js';
2
+ import { notificationSchema } from '../notifications/contracts.js';
3
+ import { applySpaceSourceInput } from './context-input.js';
4
+ import { constants } from 'node:fs';
5
+ import { link, mkdir, open as openFile, rm } from 'node:fs/promises';
6
+ import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto';
7
+ import { dirname } from 'node:path';
8
+ import { z } from 'zod';
9
+ import { loadWindowsSpaceSecretKey } from './windows-secret-key.js';
10
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
11
+ import { canonicalJson } from '../text/canonical-json.js';
12
+ import { displaySnapshot, displayText, pendingApprovals, visibleChatRequests } from './projection.js';
13
+ import { connectorFeishuSchema, credentialsView, feishuMethod, feishuView, secretClearSchema, secretPutSchema, settingsPatchSchema, settingsView } from './host-admin.js';
14
+ import { APPROVAL_TTL_SECONDS } from '../core/approval-port.js';
15
+ import { approvalResolveSchema, intentSchema, mobileActionSchema } from './contracts.js';
16
+ import { voiceStopSchema } from './voice.js';
17
+ const record = z.record(z.string(), z.unknown());
18
+ const entry = z.object({ hash: z.string(), tag: z.string().optional(), intent: intentSchema, sender: z.string(), receipt: record.nullable(), chat_status: z.enum(['admitted', 'completed']).optional(), final: record.optional(), notification_pending: z.boolean().optional(), recorded_at: z.number().int().nonnegative().optional(), revoke_started: z.boolean().optional() });
19
+ /** The journal stays readable by binaries from before receipt pruning: version 1, and only fields their non-strict schema tolerates. */
20
+ const journalSchema = z.object({ version: z.literal(1), space: z.string(), cursor: z.number().int().nonnegative(), projection_revision: z.number().int().nonnegative().default(0), ops: z.record(z.string(), entry), remaps: z.record(z.string(), z.record(z.string(), z.string())), outbox: z.array(z.object({ id: z.string(), to: z.string(), body: record })), push_outbox: z.array(z.object({ to: z.string(), id: z.string(), title: z.string(), body: z.string(), expires_at: z.number().int().optional(), notification: notificationSchema.optional() })).default([]), actions: z.record(z.string(), z.object({ device: z.string(), body: record, result: record.nullable() })) });
21
+ /**
22
+ * Replay protection for pruned ops lives in a sidecar next to the journal (see `#prune`). An older binary never reads it, so a
23
+ * downgrade only loses that protection and never refuses or rewrites the journal; a missing sidecar starts empty.
24
+ */
25
+ const replaySchema = z.object({ version: z.literal(1), space: z.string(), replay_floor: z.record(z.string(), z.number().int().nonnegative()), pruned_receipts: z.record(z.string(), z.object({ accepted: z.boolean(), hash: z.string(), tag: z.string().optional(), sender: z.string(), created_at: z.number().int().nonnegative() })) });
26
+ /** Settled receipts kept for idempotent replay before the oldest are pruned (see `#prune`). */
27
+ const RETAINED_RECEIPTS = 1024;
28
+ /** Serialized bytes of retained ops, well below the 32 MiB journal limit: large receipts are pruned by size as well as by count. */
29
+ const OPS_BYTE_BUDGET = 12 * 1024 * 1024;
30
+ /**
31
+ * Unsettled ops one sender may hold; past it that sender's new ops are refused, other senders are unaffected.
32
+ * Known limit (pre-existing): the backlog summed over all senders is not bounded against the 32 MiB journal store.
33
+ */
34
+ const LIVE_OPS_PER_SENDER = 1024;
35
+ /** Pruned op outcomes remembered for late `depends_on` lookups and changed-body detection. */
36
+ const PRUNED_TOMBSTONES = 4096;
37
+ /**
38
+ * Accepted ops created after the Host clock keep their tombstones past PRUNED_TOMBSTONES until that time arrives, because the
39
+ * clamped floor does not cover them yet. receive() refuses a sender's new future-dated op (`future_capacity`) once it holds this
40
+ * many such ops or tombstones, which bounds the protected set without ever evicting one early.
41
+ */
42
+ const FUTURE_TOMBSTONES_PER_SENDER = 1024;
43
+ /** A dependent whose dependency is unknown to the Host (never seen, not tombstoned) fails after waiting this long on the Host clock. */
44
+ const DEPENDENCY_WAIT_MS = 7 * 86_400_000;
45
+ /** An intent created further ahead of the Host clock is refused; the refusal is an ordinary settled, prunable op. */
46
+ const CLOCK_SKEW_MS = 86_400_000;
47
+ /** An op no replay or later op can still change: it has a final receipt, its chat is finished and its notification is published. */
48
+ const settled = (op) => op.receipt !== null && op.receipt.status !== 'pending' && op.chat_status !== 'admitted' && !op.notification_pending;
49
+ const ADMIN_KINDS = new Set(['settings.patch', 'secret.put', 'secret.clear', 'connector.feishu', 'device.revoke', 'approval.resolve']);
50
+ /** Kinds whose journaled intent is redacted; an HMAC tag over the full intent lets replays detect a changed value without storing it. */
51
+ const SECRET_KINDS = new Set(['secret.put', 'secret.clear', 'source.input', 'push.register']);
52
+ const fingerprint = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
53
+ /** Key-file failures carry their code as a property too, so startup diagnostics do not have to parse the message. */
54
+ const keyError = (code) => Object.assign(Error(code), { code });
55
+ export class SpaceHost {
56
+ options;
57
+ #store;
58
+ #state;
59
+ #raw = new Map();
60
+ #tail = Promise.resolve();
61
+ #stop;
62
+ #unsubscribe;
63
+ #chats = new Map();
64
+ #feishuPolls = new Map();
65
+ #flush;
66
+ #opened = false;
67
+ #snapshotTimer;
68
+ #snapshotHashes = new Map();
69
+ #secretKey;
70
+ #approvalDeadlines = new Map();
71
+ #approvalTimer;
72
+ /** `feishuPollMs` is the interval between Feishu app-setup status polls and `feishuSetupTimeoutMs` bounds them to the connector's 300s config operation, so a link that appears late still reaches the phone. */
73
+ constructor(options) {
74
+ this.options = options;
75
+ this.#store = new BoundedJsonStore(options.path, journalSchema, 32 * 1024 * 1024);
76
+ this.#replayStore = new BoundedJsonStore(options.path + '.replay.json', replaySchema, 8 * 1024 * 1024);
77
+ this.#replay = { version: 1, space: options.space, replay_floor: {}, pruned_receipts: {} };
78
+ this.#state = { version: 1, space: options.space, cursor: 0, projection_revision: 0, ops: {}, remaps: {}, outbox: [], push_outbox: [], actions: {} };
79
+ }
80
+ #now() { return this.options.now?.() ?? Date.now(); }
81
+ #serial(work) { const run = this.#tail.then(work); this.#tail = run.catch(() => { }); return run; }
82
+ #replayStore;
83
+ #replay;
84
+ #replayDirty = false;
85
+ #loaded = false;
86
+ /** The sidecar is written first: a crash between the writes leaves tombstones for ops the journal still holds, which is harmless because a retained op is always looked up first. */
87
+ async #save() { this.#prune(); if (this.#replayDirty) {
88
+ await this.#replayStore.write(this.#replay);
89
+ this.#replayDirty = false;
90
+ } await this.#store.write(this.#state); }
91
+ #opBytes = new WeakMap();
92
+ /** Ops are replaced, never mutated in place, when their receipt changes, so the cached size of an op object stays exact. */
93
+ #sizeOf(op) { let bytes = this.#opBytes.get(op); if (bytes === undefined) {
94
+ bytes = Buffer.byteLength(JSON.stringify(op));
95
+ this.#opBytes.set(op, bytes);
96
+ } return bytes; }
97
+ /**
98
+ * Bounded receipt retention. Idempotent replay needs the receipt of an op its client may still resend, but keeping every receipt
99
+ * eventually fills the journal. Settled ops (refusals included) are pruned oldest arrival first while more than `retainedReceipts`
100
+ * remain or their serialized size exceeds OPS_BYTE_BUDGET. An op is kept while anything can still need it: it is unsettled, an
101
+ * unsettled op depends on it, or the snapshot chat window still shows its turn.
102
+ *
103
+ * Replay safety: a pruned op leaves a tombstone in the replay sidecar (outcome, redacted body hash, HMAC tag over the full intent of redacted kinds) and
104
+ * lifts its sender's floor to its `created_at`, clamped to the Host clock. receive() answers an unknown op whose key is tombstoned,
105
+ * or whose `created_at` is at or below the floor, without running it: `op_id_conflict` for a changed intent under a tombstoned op
106
+ * id, `op_expired` otherwise. The floor only compares one device's clock with itself; the clamp keeps a future-dated record from
107
+ * locking that device out after its clock is corrected.
108
+ *
109
+ * Known tradeoffs:
110
+ * - Beyond the tombstone window, an op id reused with a changed intent and a `created_at` above the floor is a new op. Clients never
111
+ * reuse op ids, and a resend carries its original `created_at`, which the floor rejects; the exception is a future-dated op whose
112
+ * floor contribution was clamped, which after leaving the tombstone window is judged afresh.
113
+ * - An op refused as clock_skew can run if it is redelivered after its time arrives and its tombstone has left the window. Accepted:
114
+ * it never ran, and its client already saw the rejection and dropped it.
115
+ * - A downgraded binary ignores the replay sidecar, so ops pruned before the downgrade lose replay protection while it runs. It also
116
+ * strips `revoke_started`, so after a re-upgrade a revocation that completed while its receipt was pending stays pending until
117
+ * its client resends it.
118
+ * - A first delivery that arrives after newer ops of the same device were pruned is refused as `op_expired`, for example an op held
119
+ * back by its client while more than `retainedReceipts` newer ops settled. It fails visibly and never runs twice.
120
+ * - A chat turn that leaves the snapshot window can be pruned; if the window later shows it again, it appears without its turn id.
121
+ * Pre-existing limits, not addressed here: `remaps` and completed mobile `actions` still grow without bound; a version_conflict
122
+ * receipt carries a full snapshot in one message and can exceed the relay message limit; the Flutter controller does not enqueue a
123
+ * new snapshot.request after a terminal rejection of its pending one.
124
+ */
125
+ #prune() {
126
+ const now = this.#now(), ops = this.#state.ops, tombstones = this.#replay.pruned_receipts, limit = this.options.retainedReceipts ?? RETAINED_RECEIPTS;
127
+ const known = (sender, dep) => { const depKey = this.#key(sender, dep); return depKey in ops || depKey in tombstones; };
128
+ for (const [key, op] of Object.entries(ops)) {
129
+ if (op.receipt?.status !== 'pending' || op.receipt.error !== 'dependency_pending')
130
+ continue;
131
+ // A dependent cannot wait forever: past its own deadline it expires, and on a dependency the Host never saw it fails after DEPENDENCY_WAIT_MS. Its client gets the stored rejection on its next resend.
132
+ const recorded = op.recorded_at ?? now, error = op.intent.expires_at !== undefined && op.intent.expires_at <= now ? 'expired' : recorded + DEPENDENCY_WAIT_MS <= now && (op.intent.depends_on ?? []).some(dep => !known(op.sender, dep)) ? 'dependency_failed' : undefined;
133
+ if (error)
134
+ ops[key] = { ...op, receipt: { v: 1, type: 'receipt', op_id: op.intent.op_id, status: 'rejected', error } };
135
+ else if (op.recorded_at === undefined)
136
+ ops[key] = { ...op, recorded_at: now };
137
+ }
138
+ const keys = Object.keys(ops), needed = new Set();
139
+ let count = keys.length, bytes = 0;
140
+ for (const op of Object.values(ops)) {
141
+ bytes += this.#sizeOf(op);
142
+ if (!settled(op))
143
+ for (const dep of op.intent.depends_on ?? [])
144
+ needed.add(this.#key(op.sender, dep));
145
+ }
146
+ if (count > limit || bytes > OPS_BYTE_BUDGET) {
147
+ const visible = visibleChatRequests(this.options.host);
148
+ // Object key order is first-arrival order: #record reassigns an existing key in place.
149
+ for (const key of keys) {
150
+ if (count <= limit && bytes <= OPS_BYTE_BUDGET)
151
+ break;
152
+ const op = ops[key];
153
+ if (!settled(op) || needed.has(key) || visible.has('space:' + key))
154
+ continue;
155
+ delete ops[key];
156
+ this.#raw.delete(key);
157
+ count--;
158
+ bytes -= this.#sizeOf(op);
159
+ this.#replay.replay_floor[op.sender] = Math.max(this.#replay.replay_floor[op.sender] ?? 0, Math.min(op.intent.created_at, now));
160
+ delete tombstones[key];
161
+ tombstones[key] = { accepted: op.receipt.status === 'accepted', hash: op.hash, ...(op.tag ? { tag: op.tag } : {}), sender: op.sender, created_at: op.intent.created_at };
162
+ this.#replayDirty = true;
163
+ }
164
+ }
165
+ // The oldest tombstones leave first, except one a pending dependent still waits on and an accepted one whose op was created after
166
+ // the Host clock (bounded at admission, see FUTURE_TOMBSTONES_PER_SENDER). An evicted tombstone raises its sender's floor to its
167
+ // created_at, clamped to the Host clock, so a tombstone that waited for its time is still covered once it leaves.
168
+ let extra = Object.keys(tombstones).length - PRUNED_TOMBSTONES;
169
+ if (extra > 0)
170
+ for (const [key, tombstone] of Object.entries(tombstones)) {
171
+ if (extra <= 0)
172
+ break;
173
+ if (needed.has(key) || tombstone.accepted && tombstone.created_at > now)
174
+ continue;
175
+ this.#replay.replay_floor[tombstone.sender] = Math.max(this.#replay.replay_floor[tombstone.sender] ?? 0, Math.min(tombstone.created_at, now));
176
+ delete tombstones[key];
177
+ extra--;
178
+ this.#replayDirty = true;
179
+ }
180
+ }
181
+ /** Accepted or still running ops of a sender created after the Host clock, retained or tombstoned. */
182
+ #futureOps(sender, now) { let count = 0; for (const op of Object.values(this.#state.ops))
183
+ if (op.sender === sender && op.intent.created_at > now && op.receipt?.status !== 'rejected')
184
+ count++; for (const tombstone of Object.values(this.#replay.pruned_receipts))
185
+ if (tombstone.sender === sender && tombstone.accepted && tombstone.created_at > now)
186
+ count++; return count; }
187
+ /** The outcome of a dependency, from its retained op or its tombstone. */
188
+ #dependency(sender, dep) { const depKey = this.#key(sender, dep), pruned = this.#replay.pruned_receipts[depKey]; return this.#state.ops[depKey]?.receipt ?? (pruned === undefined ? undefined : { status: pruned.accepted ? 'accepted' : 'rejected' }); }
189
+ // A persisted hash must not be an offline guess oracle for a stored secret: the idempotency hash covers the redacted form only. A conflicting value under the same op id is detected from `#raw` within one process and from the persisted HMAC tag across restarts. The tag key lives in a private sibling file, never in the journal.
190
+ #journalIntent(intent) { if (intent.kind === 'source.input')
191
+ return { ...intent, input: {} }; if (intent.kind === 'secret.put' || intent.kind === 'secret.clear')
192
+ return { ...intent, input: { name: intent.input.name } }; if (intent.kind === 'push.register') {
193
+ const { credential: _credential, ...rest } = intent.input;
194
+ return { ...intent, input: rest };
195
+ } return intent; }
196
+ /** The journal is a portable backup; its secret tags are useless without this separate 0600 key. */
197
+ async #loadSecretKey() {
198
+ const cached = this.#secretKey;
199
+ if (cached)
200
+ return cached;
201
+ const path = this.options.path + '.key';
202
+ if (process.platform === 'win32')
203
+ return this.#secretKey = await loadWindowsSpaceSecretKey(path);
204
+ // Only a missing key is created. A damaged key fails closed and is never deleted or replaced: it may be the last copy that can still authenticate existing tags, and a starter that recovers "late" must not remove the complete key another starter just published.
205
+ const existing = await this.#readSecretKey(path).catch((error) => { if (error.code === 'ENOENT')
206
+ return undefined; throw error; });
207
+ if (existing !== undefined)
208
+ return this.#secretKey = existing;
209
+ return this.#publishSecretKey(path);
210
+ }
211
+ /** Publish only a complete key: write and fsync a private temp file, then link it into place without replacing a key another starter already published. */
212
+ async #publishSecretKey(path) {
213
+ const key = randomBytes(32).toString('hex'), temp = path + '.' + randomUUID() + '.tmp';
214
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
215
+ let publishing = false;
216
+ try {
217
+ const file = await openFile(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
218
+ try {
219
+ await file.writeFile(key);
220
+ await file.sync();
221
+ }
222
+ finally {
223
+ await file.close();
224
+ }
225
+ publishing = true;
226
+ await link(temp, path);
227
+ // Node cannot fsync directories on Windows; the key itself was synced before it was linked.
228
+ if (process.platform !== 'win32') {
229
+ const dir = await openFile(dirname(path), constants.O_RDONLY);
230
+ try {
231
+ await dir.sync();
232
+ }
233
+ finally {
234
+ await dir.close();
235
+ }
236
+ }
237
+ }
238
+ catch (error) {
239
+ // A starter that lost the race adopts the winner's complete key below instead of trusting its own.
240
+ if (!publishing || error.code !== 'EEXIST')
241
+ throw error;
242
+ }
243
+ finally {
244
+ await rm(temp, { force: true }).catch(() => { });
245
+ }
246
+ return this.#secretKey = await this.#readSecretKey(path);
247
+ }
248
+ /** Read the tag key through a handle: a symlinked or group-readable key file must never supply the tag key. */
249
+ async #readSecretKey(path) {
250
+ const opened = await openFile(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch((error) => {
251
+ // O_NOFOLLOW reports a symlinked key as ELOOP instead of following it to a file someone else controls.
252
+ if (error.code === 'ELOOP')
253
+ throw keyError('space_secret_key_symlink');
254
+ throw error;
255
+ });
256
+ try {
257
+ const stats = await opened.stat();
258
+ if (!stats.isFile())
259
+ throw keyError('space_secret_key_invalid');
260
+ // Another account could read a 0644 key and forge the tags that guard secret replays.
261
+ if ((stats.mode & 0o077) !== 0)
262
+ throw keyError('space_secret_key_permissions');
263
+ if (stats.size === 0)
264
+ throw keyError('space_secret_key_empty');
265
+ if (stats.size !== 64)
266
+ throw keyError('space_secret_key_invalid');
267
+ const { buffer, bytesRead } = await opened.read(Buffer.alloc(64), 0, 64, 0), text = buffer.toString('utf8', 0, bytesRead);
268
+ if (!/^[a-f0-9]{64}$/u.test(text))
269
+ throw keyError('space_secret_key_invalid');
270
+ return text;
271
+ }
272
+ finally {
273
+ await opened.close();
274
+ }
275
+ }
276
+ #secretTag(key, raw) { return createHmac('sha256', this.#secretKey).update(key + '\n' + raw).digest('hex'); }
277
+ #owner() { return this.options.owner?.(); }
278
+ #hostAdmin(sender) { return this.#owner() === sender; }
279
+ #requireChat(id) { const row = this.options.host.conversationSnapshot(0).items.find(row => row.id === id); if (!row)
280
+ throw Error('conversation_not_found'); if (!['chat', 'topic'].includes(row.kind) || (row.mode ?? 'chat') !== 'chat')
281
+ throw Error('conversation_read_only'); }
282
+ #key(sender, op) { return fingerprint([sender, op]); }
283
+ async open() {
284
+ if (this.#opened)
285
+ return;
286
+ // Both files are validated before either replaces the initial state; until then close() saves nothing, so a refused or unreadable file is never overwritten.
287
+ const read = async (store, fallback) => { try {
288
+ return await store.read(fallback);
289
+ }
290
+ catch (error) {
291
+ if (error.code !== 'ENOENT')
292
+ throw error;
293
+ return fallback;
294
+ } };
295
+ const state = await read(this.#store, this.#state), replay = await read(this.#replayStore, this.#replay);
296
+ if (state.space !== this.options.space || replay.space !== this.options.space)
297
+ throw Error('space_scope_mismatch');
298
+ this.#state = state;
299
+ this.#replay = replay;
300
+ this.#loaded = true;
301
+ // A crash between the sidecar and journal writes can leave an op both retained and tombstoned; the tombstone is the later state, so the op was settled and pruned. Dropping it makes a retry answer op_expired instead of running it again.
302
+ for (const [key, op] of Object.entries(this.#state.ops))
303
+ if (this.#replay.pruned_receipts[key]?.hash === op.hash)
304
+ delete this.#state.ops[key];
305
+ await this.#loadSecretKey();
306
+ await this.options.secrets?.open();
307
+ await this.options.push?.open();
308
+ await this.options.push?.prune(this.options.transport.clients());
309
+ this.#opened = true;
310
+ const clients = new Set(this.options.transport.clients());
311
+ this.#state.outbox = this.#state.outbox.filter(row => clients.has(row.to));
312
+ this.#state.push_outbox = this.#state.push_outbox.filter(row => clients.has(row.to));
313
+ await this.#save();
314
+ await this.options.transport.recoverPending?.(this.#state.outbox.map(row => row.id));
315
+ // An admitted chat is never submitted to the model a second time after a crash.
316
+ for (const [key, op] of Object.entries(this.#state.ops))
317
+ if (op.chat_status === 'admitted') {
318
+ const saved = this.options.host.spaceChatResult('space:' + key, displayText(op.intent.input.conversation_id, 'chat:main'));
319
+ await this.#finishChat(key, saved ?? { text: '', status: 'interrupted', message_id: 'turn-' + fingerprint(key) });
320
+ }
321
+ // An authorized revocation stays pending because revoking restarts the Host. Only an op marked when the authorized branch started
322
+ // the revoke is settled, once its device has left the membership; its accepted receipt gets its own queue id after the pending one.
323
+ for (const op of Object.values(this.#state.ops))
324
+ if (op.intent.kind === 'device.revoke' && op.revoke_started && op.receipt?.status === 'pending' && !clients.has(String(op.intent.input.device))) {
325
+ const key = this.#key(op.sender, op.intent.op_id);
326
+ if (clients.has(op.sender))
327
+ await this.#record(op.sender, op.intent, op.hash, { status: 'accepted' }, 'receipt-' + key + '-settled');
328
+ else {
329
+ this.#state.ops[key] = { ...op, receipt: { v: 1, type: 'receipt', op_id: op.intent.op_id, status: 'accepted' } };
330
+ await this.#save();
331
+ }
332
+ }
333
+ this.#unsubscribe = this.options.host.subscribe(() => this.#scheduleSnapshot());
334
+ this.#stop = await this.options.transport.start((from, body) => this.receive(from, body), { load: () => this.#state.cursor, save: n => this.#serial(async () => { if (!this.#opened)
335
+ throw Error('space_host_closed'); if (this.#state.cursor === n)
336
+ return; const durable = this.#state.cursor; this.#state.cursor = n; try {
337
+ await this.#save();
338
+ }
339
+ catch (error) {
340
+ this.#state.cursor = durable;
341
+ throw error;
342
+ } }) });
343
+ // Delivering queued messages needs the relay, which can be unreachable (for example a stopped tailnet) and then waits out one network
344
+ // timeout per queued message. Startup must not wait for that: the Host is usable locally, and the queue is retried in the background.
345
+ this.initialDelivery = (async () => { try {
346
+ await this.publishSnapshot();
347
+ await this.dispatchNotifications();
348
+ await this.flush();
349
+ }
350
+ catch {
351
+ this.options.onError?.(undefined);
352
+ } })();
353
+ }
354
+ /** The first delivery pass after open(), which runs in the background; tests and shutdown can wait for it. */
355
+ initialDelivery = Promise.resolve();
356
+ #scheduleSnapshot() { if (!this.#opened || this.#snapshotTimer)
357
+ return; this.#snapshotTimer = setTimeout(() => { this.#snapshotTimer = undefined; if (!this.#opened)
358
+ return; void this.#publishSnapshot(undefined, true).catch(error => this.options.onError?.(error)); }, 100); this.#snapshotTimer.unref(); }
359
+ /**
360
+ * The executor clock is monotonic seconds; a phone needs a wall-clock deadline. Each approval keeps the deadline first derived
361
+ * for its executor expiry, so repeated projections hash the same until the head is re-armed or leaves.
362
+ */
363
+ #approvalDeadline(id, raw, now) { if (raw === null) {
364
+ this.#approvalDeadlines.delete(id);
365
+ return null;
366
+ } const old = this.#approvalDeadlines.get(id); if (old?.raw === raw)
367
+ return old.at; const at = Math.round(now + Math.max(0, Math.min(APPROVAL_TTL_SECONDS, raw - performance.now() / 1000)) * 1000); this.#approvalDeadlines.set(id, { raw, at }); return at; }
368
+ /** Current resolvable approvals; arms one timer so an expiry the executor has not yet reported still drops the card. */
369
+ #approvals() {
370
+ const now = this.#now(), rows = pendingApprovals(this.options.host, (id, raw) => this.#approvalDeadline(id, raw, now), now), live = new Set(rows.map(row => row.id));
371
+ for (const id of [...this.#approvalDeadlines.keys()])
372
+ if (!live.has(id))
373
+ this.#approvalDeadlines.delete(id);
374
+ const next = Math.min(...rows.flatMap(row => row.expires_at === null ? [] : [row.expires_at]));
375
+ if (this.#approvalTimer) {
376
+ clearTimeout(this.#approvalTimer);
377
+ this.#approvalTimer = undefined;
378
+ }
379
+ if (this.#opened && Number.isFinite(next)) {
380
+ this.#approvalTimer = setTimeout(() => { this.#approvalTimer = undefined; this.#scheduleSnapshot(); }, Math.max(0, next - now) + 50);
381
+ this.#approvalTimer.unref();
382
+ }
383
+ return rows;
384
+ }
385
+ snapshot(to) { const owner = to !== undefined && this.#hostAdmin(to), turns = new Map(Object.entries(this.#state.ops).filter(([, op]) => op.intent.kind === 'chat.send').map(([key, op]) => ['space:' + key, op.intent.op_id])); return { ...displaySnapshot(this.options.host, turns, owner ? this.#approvals() : []), revision: ++this.#state.projection_revision, owner, ...(this.options.voice && to !== undefined ? { host_capabilities: this.options.voice.available(to) ? ['voice.v1'] : [] } : {}), ...(owner ? { host_settings: { devices: this.options.transport.clients(), ...settingsView(this.options.host), ...(this.options.models ? { models: this.options.models.view() } : {}) }, host_credentials: credentialsView(this.options.secrets, this.options.environment ?? process.env), host_feishu: this.#feishuProjection() } : {}) }; }
386
+ #setupUrl;
387
+ #feishuProjection() { const raw = this.options.host.snapshot().feishu, view = feishuView(raw); return this.#setupUrl && view.app_setup?.state === 'waiting' ? { ...view, app_setup: { ...view.app_setup, verification_url: this.#setupUrl } } : view; }
388
+ async publishSnapshot(to) { await this.#publishSnapshot(to); }
389
+ async #publishSnapshot(to, onlyChanged = false) { await this.#serial(async () => { for (const device of to ? [to] : this.options.transport.clients())
390
+ this.#queueSnapshot(device, this.snapshot(device), 'snapshot-' + randomUUID(), onlyChanged); await this.#save(); await this.options.transport.recoverPending?.(this.#state.outbox.map(row => row.id)); }); await this.flush(); }
391
+ #queueSnapshot(to, snapshot, id, onlyChanged = false) {
392
+ const { revision: _revision, ...projection } = snapshot, hash = fingerprint(projection);
393
+ if (onlyChanged && this.#snapshotHashes.get(to) === hash)
394
+ return;
395
+ // A newer full projection supersedes queued snapshot chunks, never receipts or actions.
396
+ this.#state.outbox = this.#state.outbox.filter(row => row.to !== to || !['snapshot', 'snapshot.chunk'].includes(String(row.body.type)));
397
+ this.#enqueue(to, { v: 1, type: 'snapshot', snapshot }, id);
398
+ this.#snapshotHashes.set(to, hash);
399
+ }
400
+ #enqueue(to, body, id) { if (body.type === 'snapshot') {
401
+ const data = JSON.stringify(body.snapshot);
402
+ if (Buffer.byteLength(data) > 48 * 1024) {
403
+ if (Buffer.byteLength(data) > 16 * 1024 * 1024)
404
+ throw Error('snapshot_capacity');
405
+ const chunks = [];
406
+ let text = '', bytes = 0;
407
+ for (const char of data) {
408
+ const size = Buffer.byteLength(char);
409
+ if (bytes + size > 48 * 1024) {
410
+ chunks.push(text);
411
+ text = '';
412
+ bytes = 0;
413
+ }
414
+ text += char;
415
+ bytes += size;
416
+ }
417
+ if (text)
418
+ chunks.push(text);
419
+ if (chunks.length > 512)
420
+ throw Error('snapshot_capacity');
421
+ for (const [index, data] of chunks.entries())
422
+ this.#enqueue(to, { v: 1, type: 'snapshot.chunk', snapshot_id: id, index, total: chunks.length, data }, id + '-' + index);
423
+ return;
424
+ }
425
+ } if (this.#state.outbox.some(row => row.id === id && row.to === to))
426
+ return; if (this.#state.outbox.length >= 4096)
427
+ throw Error('space_outbox_capacity'); this.#state.outbox.push({ to, body: structuredClone(body), id }); }
428
+ async receive(sender, raw) {
429
+ if (!this.#opened)
430
+ throw Error('space_host_closed');
431
+ const exact = raw;
432
+ let voiceCall, voiceAccept;
433
+ if (!this.options.transport.clients().includes(sender))
434
+ throw Error('sender_not_paired');
435
+ const parsed = intentSchema.safeParse(raw);
436
+ if (!parsed.success) {
437
+ this.options.onError?.(Error('invalid_business_intent'));
438
+ return;
439
+ }
440
+ const intent = parsed.data;
441
+ const key = this.#key(sender, intent.op_id);
442
+ let startChat = false, pollSetup = false;
443
+ let revokeTarget;
444
+ await this.#serial(async () => {
445
+ const old = this.#state.ops[key], raw = fingerprint(intent), hash = fingerprint(this.#journalIntent(intent)), tag = SECRET_KINDS.has(intent.kind) ? this.#secretTag(key, raw) : undefined;
446
+ if (old) {
447
+ // A record written before tags existed keeps the legacy in-memory comparison; its raw fingerprint must never be compared against an HMAC tag.
448
+ const seen = old.tag ?? this.#raw.get(key), next = old.tag === undefined ? raw : tag;
449
+ if (old.hash !== hash || (seen !== undefined && seen !== next)) {
450
+ this.#enqueue(sender, { v: 1, type: 'receipt', op_id: intent.op_id, status: 'rejected', error: 'op_id_conflict' }, 'conflict-' + randomUUID());
451
+ await this.#save();
452
+ return;
453
+ }
454
+ if (old.receipt && old.receipt.status !== 'pending') {
455
+ // A stored conflict receipt omits its snapshot to keep the journal small; a replay carries the current one.
456
+ this.#enqueue(sender, old.receipt.status === 'conflict' ? { ...old.receipt, snapshot: this.snapshot(sender) } : old.receipt, 'receipt-' + key);
457
+ await this.#save();
458
+ return;
459
+ }
460
+ }
461
+ else {
462
+ // An unknown op that may be a pruned one is answered without journaling it (see #prune): the answer depends only on the op and on
463
+ // tombstones and the replay floor, which never move back. Its queue id is deterministic so repeated replays dedupe in the outbox.
464
+ const refuse = async (error) => { this.#enqueue(sender, { v: 1, type: 'receipt', op_id: intent.op_id, status: 'rejected', error }, 'refused-' + key + '-' + error); await this.#save(); };
465
+ const tombstone = this.#replay.pruned_receipts[key], floor = this.#replay.replay_floor[sender];
466
+ if (tombstone) {
467
+ await refuse(tombstone.hash !== hash || (tombstone.tag !== undefined && tombstone.tag !== tag) ? 'op_id_conflict' : 'op_expired');
468
+ return;
469
+ }
470
+ if (floor !== undefined && intent.created_at <= floor) {
471
+ await refuse('op_expired');
472
+ return;
473
+ }
474
+ this.#raw.set(key, raw);
475
+ // Other refusals are journaled as settled ops, so a redelivery can never run an intent that was already refused; pruning bounds them.
476
+ const now = this.#now(), live = Object.values(this.#state.ops).filter(op => op.sender === sender && !settled(op));
477
+ // A parent that a pending op waits on is admitted past the limit, but only if it can run now, so the exception cannot chain.
478
+ const releases = live.some(op => op.intent.depends_on?.includes(intent.op_id)) && (intent.depends_on ?? []).every(dep => { const prior = this.#dependency(sender, dep); return prior !== undefined && prior.status !== 'pending'; });
479
+ const refusal = intent.created_at > now + CLOCK_SKEW_MS ? 'clock_skew' : intent.created_at > now && this.#futureOps(sender, now) >= FUTURE_TOMBSTONES_PER_SENDER ? 'future_capacity' : intent.expires_at !== undefined && intent.expires_at <= now ? 'expired' : live.length >= LIVE_OPS_PER_SENDER && !releases ? 'space_receipt_capacity' : undefined;
480
+ if (refusal) {
481
+ await this.#record(sender, intent, hash, { status: 'rejected', error: refusal });
482
+ return;
483
+ }
484
+ }
485
+ // A pending op re-evaluated after its deadline settles as expired instead of waiting on its dependencies again.
486
+ if (old && intent.expires_at !== undefined && intent.expires_at <= this.#now()) {
487
+ await this.#record(sender, intent, hash, { status: 'rejected', error: 'expired' });
488
+ return;
489
+ }
490
+ for (const dep of intent.depends_on ?? []) {
491
+ const prior = this.#dependency(sender, dep);
492
+ if (!prior || prior.status === 'pending') {
493
+ await this.#record(sender, intent, hash, { status: 'pending', error: 'dependency_pending' });
494
+ return;
495
+ }
496
+ if (prior.status !== 'accepted') {
497
+ await this.#record(sender, intent, hash, { status: 'rejected', error: 'dependency_failed' });
498
+ return;
499
+ }
500
+ }
501
+ if (!old) {
502
+ this.#state.ops[key] = { hash, ...(tag ? { tag } : {}), intent: this.#journalIntent(intent), sender, receipt: null, recorded_at: this.#now() };
503
+ await this.#save();
504
+ }
505
+ let authorityCommitted = false;
506
+ try {
507
+ if (ADMIN_KINDS.has(intent.kind) && !this.#hostAdmin(sender))
508
+ throw Error(this.#owner() === undefined ? 'owner_unassigned' : 'owner_required');
509
+ if (intent.kind === 'life.mutate') {
510
+ const input = structuredClone(intent.input), maps = this.#state.remaps[sender] ?? {};
511
+ for (const field of ['id', 'goal_id', 'idea_id'])
512
+ if (typeof input[field] === 'string' && Object.hasOwn(maps, input[field]))
513
+ input[field] = maps[input[field]];
514
+ if (input.op !== 'create') {
515
+ if (intent.base_version === undefined)
516
+ throw Error('base_version_required');
517
+ input.expected_version = intent.base_version;
518
+ }
519
+ const requestId = 'space:' + key;
520
+ const result = await this.options.host.life.mutate(input, requestId);
521
+ authorityCommitted = true;
522
+ if (intent.temp_id)
523
+ (this.#state.remaps[sender] ??= {})[intent.temp_id] = result.id;
524
+ await this.#record(sender, intent, hash, { status: 'accepted', result, ...(intent.temp_id ? { id_map: { [intent.temp_id]: result.id } } : {}) });
525
+ }
526
+ else if (intent.kind === 'snapshot.request') {
527
+ await this.#record(sender, intent, hash, { status: 'accepted' });
528
+ }
529
+ else if (intent.kind === 'card.dismiss') {
530
+ const p = z.object({ id: z.string(), kind: z.enum(['feed', 'timeline']) }).parse(intent.input);
531
+ if (p.kind === 'feed')
532
+ await this.options.host.action({ id: p.id, action: 'dismiss' });
533
+ else
534
+ await this.options.host.timeline.dismiss(p.id);
535
+ await this.#record(sender, intent, hash, { status: 'accepted' });
536
+ }
537
+ else if (intent.kind === 'chat.send') {
538
+ z.object({ conversation_id: z.string().max(128).default('chat:main'), text: z.string().min(1).max(16000) }).parse(intent.input);
539
+ if (intent.expires_at === undefined || intent.expires_at - this.#now() > 60000)
540
+ throw Error('chat_deadline_required');
541
+ this.#requireChat(displayText(intent.input.conversation_id, 'chat:main'));
542
+ if (Object.entries(this.#state.ops).some(([other, value]) => other !== key && value.chat_status === 'admitted' && displayText(value.intent.input.conversation_id, 'chat:main') === displayText(intent.input.conversation_id, 'chat:main')))
543
+ throw Error('conversation_busy');
544
+ this.#state.ops[key].chat_status = 'admitted';
545
+ await this.#record(sender, intent, hash, { status: 'accepted', turn_id: intent.op_id });
546
+ startChat = true;
547
+ }
548
+ else if (intent.kind === 'chat.cancel') {
549
+ const p = z.object({ op_id: z.string() }).parse(intent.input), target = this.#state.ops[this.#key(sender, p.op_id)];
550
+ if (target?.intent.kind !== 'chat.send')
551
+ throw Error('chat_not_found');
552
+ if (target.chat_status === 'admitted')
553
+ await this.options.host.cancelSpaceChat(displayText(target.intent.input.conversation_id, 'chat:main'));
554
+ await this.#record(sender, intent, hash, { status: 'accepted' });
555
+ }
556
+ else if (intent.kind === 'source.input') {
557
+ const memory = this.options.host.options.memory();
558
+ if (!memory)
559
+ throw Error('source_backend_unavailable');
560
+ const result = await applySpaceSourceInput(memory, { space: this.options.space, sender, opId: intent.op_id }, intent.input);
561
+ authorityCommitted = true;
562
+ await this.options.host.sourceProcessingAgent.reload();
563
+ this.options.host.connectionChanged();
564
+ await this.#record(sender, intent, hash, { status: 'accepted', result });
565
+ }
566
+ else if (intent.kind === 'push.register') {
567
+ if (!this.options.push)
568
+ throw Error('push_unconfigured');
569
+ const message = await this.options.push.register(sender, intent.input);
570
+ this.#enqueue(sender, { ...message }, 'push-key-' + key);
571
+ await this.#record(sender, intent, hash, { status: 'accepted' });
572
+ }
573
+ else if (intent.kind === 'push.unregister') {
574
+ await this.options.push?.revoke(sender);
575
+ await this.#record(sender, intent, hash, { status: 'accepted' });
576
+ }
577
+ // Identity edits carry one field; merging at execution keeps queued offline edits from reverting each other.
578
+ // soul.set reports a version mismatch as 'stale'; the Client offers a retry only for conflict receipts.
579
+ else if (intent.kind === 'settings.patch') {
580
+ const p = settingsPatchSchema.parse(intent.input);
581
+ if (p.method === 'models.configure') {
582
+ if (!this.options.models)
583
+ throw Error('models_unconfigured');
584
+ const result = await this.options.models.configure(p.params, 'space:' + key);
585
+ authorityCommitted = true;
586
+ await this.#record(sender, intent, hash, { status: 'accepted', ...result });
587
+ }
588
+ else {
589
+ const params = p.method === 'identity.configure' ? { ...this.options.host.identity(), ...p.params } : p.params, result = await this.options.host.command({ type: 'personal.command', request_id: 'space:' + key, method: p.method, params }, { client_id: 'space:' + sender });
590
+ if (!result.ok)
591
+ throw Error(result.error === 'stale' ? 'version_conflict' : result.error ?? 'unavailable');
592
+ authorityCommitted = true;
593
+ await this.#record(sender, intent, hash, { status: 'accepted' });
594
+ }
595
+ }
596
+ else if (intent.kind === 'approval.resolve') {
597
+ const p = approvalResolveSchema.parse(intent.input);
598
+ if (p.scope === 'session')
599
+ throw Error('scope_unsupported');
600
+ const raw = (this.options.host.snapshot().pending_approvals ?? []).find(row => row.approval_id === p.approval_id && row.conversation_id === p.conversation_id);
601
+ if (raw && !this.#approvals().some(row => row.id === p.approval_id))
602
+ throw Error('approval_expired'); /* No pending-state pre-check otherwise: a redelivery after the Host decided but before this receipt was saved must reach the Host's own idempotent receipt for the same client and request id; an id the Host does not own comes back as approval_not_owned. */
603
+ const result = await this.options.host.command({ type: 'personal.command', request_id: 'space:' + key, method: 'conversations.approve', params: { id: p.conversation_id, approval_id: p.approval_id, approved: p.approved } }, { client_id: 'space:' + sender });
604
+ if (!result.ok)
605
+ throw Error(result.error === 'approval_not_owned' ? 'approval_not_found' : result.error ?? 'unavailable');
606
+ authorityCommitted = true;
607
+ await this.#record(sender, intent, hash, { status: 'accepted' });
608
+ }
609
+ else if (intent.kind === 'secret.put' || intent.kind === 'secret.clear') {
610
+ if (!this.options.secrets)
611
+ throw Error('secrets_unconfigured');
612
+ const env = this.options.environment ?? process.env, p = intent.kind === 'secret.put' ? secretPutSchema.parse(intent.input) : secretClearSchema.parse(intent.input);
613
+ const value = p.value;
614
+ if (value !== undefined)
615
+ await this.options.secrets.put(p.name, value);
616
+ else
617
+ await this.options.secrets.clear(p.name);
618
+ authorityCommitted = true;
619
+ await this.#record(sender, intent, hash, { status: 'accepted', applies: 'restart', shadowed_by_environment: !!env[p.name]?.trim() });
620
+ }
621
+ else if (intent.kind === 'device.revoke') {
622
+ const p = z.object({ device: z.string().min(1).max(256) }).strict().parse(intent.input);
623
+ if (p.device === sender)
624
+ throw Error('cannot_revoke_self');
625
+ if (!this.options.revokeDevice)
626
+ throw Error('device_revoke_unavailable');
627
+ if (this.options.transport.clients().includes(p.device)) {
628
+ this.#state.ops[key] = { ...this.#state.ops[key], revoke_started: true };
629
+ await this.#record(sender, intent, hash, { status: 'pending' });
630
+ revokeTarget = p.device;
631
+ }
632
+ else
633
+ await this.#record(sender, intent, hash, { status: 'accepted' });
634
+ }
635
+ else if (intent.kind === 'connector.feishu') {
636
+ const p = connectorFeishuSchema.parse(intent.input), result = await this.options.host.command({ type: 'personal.command', request_id: 'space:' + key, method: feishuMethod(p.action), params: {} }, { client_id: 'space:' + sender });
637
+ if (!result.ok)
638
+ throw Error(result.error ?? 'unavailable');
639
+ authorityCommitted = true;
640
+ const view = feishuView(result.data);
641
+ this.#setupUrl = view.app_setup?.verification_url;
642
+ pollSetup = view.app_setup?.state === 'waiting' && !this.#setupUrl;
643
+ await this.#record(sender, intent, hash, { status: 'accepted', result: view });
644
+ }
645
+ else if (intent.kind === 'voice.start') {
646
+ // Stream-only (relay-transport) and journaled by (sender, op_id): a replay returns this same receipt, never a second call.
647
+ if (!this.options.voice)
648
+ throw Error('voice_unavailable');
649
+ const started = await this.options.voice.begin(sender, exact, this.#now());
650
+ // The owner lease is held from here: any failure before the accept is durable releases it.
651
+ try {
652
+ await started.call.prepare();
653
+ await this.#record(sender, intent, hash, { status: 'accepted', voice: started.accept });
654
+ }
655
+ catch (error) {
656
+ await started.call.end(started.call.endReason.value ?? 'host_error');
657
+ throw error;
658
+ }
659
+ voiceCall = started.call;
660
+ voiceAccept = started.accept;
661
+ }
662
+ else if (intent.kind === 'voice.stop') {
663
+ const p = voiceStopSchema.parse(intent.input);
664
+ await this.options.voice?.stop(sender, p.op_id);
665
+ await this.#record(sender, intent, hash, { status: 'accepted' });
666
+ }
667
+ else if (intent.kind === 'mobile.result') {
668
+ const p = z.object({ action_id: z.string(), status: z.enum(['completed', 'denied', 'failed', 'unknown']), result: record.optional(), error: z.string().max(500).optional() }).parse(intent.input), action = this.#state.actions[p.action_id];
669
+ if (action?.device !== sender)
670
+ throw Error('action_not_found');
671
+ if (action.result && fingerprint(action.result) !== fingerprint(p))
672
+ throw Error('action_result_conflict');
673
+ action.result = p;
674
+ await this.#record(sender, intent, hash, { status: 'accepted' });
675
+ }
676
+ }
677
+ catch (error) {
678
+ if (authorityCommitted)
679
+ throw error;
680
+ const code = error instanceof Error ? error.message : 'invalid_intent';
681
+ await this.#record(sender, intent, hash, { status: code === 'version_conflict' ? 'conflict' : 'rejected', error: code.slice(0, 128), ...(code === 'version_conflict' ? { snapshot: this.snapshot(sender) } : {}) });
682
+ }
683
+ });
684
+ if (pollSetup)
685
+ this.#startFeishuPoll(sender);
686
+ if (voiceCall && voiceAccept) {
687
+ void this.options.transport.stream(sender, { v: 1, ...voiceAccept }, 'voice-accept-' + key).catch(() => { });
688
+ }
689
+ if (startChat) {
690
+ const run = this.#runChat(key);
691
+ this.#chats.set(key, run);
692
+ void run.catch(error => this.options.onError?.(error)).finally(() => this.#chats.delete(key));
693
+ }
694
+ await this.flush();
695
+ if (revokeTarget)
696
+ await this.options.revokeDevice(revokeTarget);
697
+ }
698
+ /** One cancellable task per owner: a repeated app.start replaces nothing and must not add another polling chain. */
699
+ #startFeishuPoll(owner) {
700
+ if (!this.#opened || this.#feishuPolls.has(owner))
701
+ return;
702
+ const abort = new AbortController();
703
+ const task = this.#pollFeishuSetup(owner, abort.signal).catch(error => { if (!abort.signal.aborted && this.#opened)
704
+ this.options.onError?.(error); }).finally(() => { if (this.#feishuPolls.get(owner)?.abort === abort)
705
+ this.#feishuPolls.delete(owner); });
706
+ this.#feishuPolls.set(owner, { abort, task });
707
+ }
708
+ #sleep(ms, signal) {
709
+ return new Promise(resolve => {
710
+ if (signal.aborted)
711
+ return resolve();
712
+ const wake = () => { clearTimeout(timer); resolve(); };
713
+ const timer = setTimeout(() => { signal.removeEventListener('abort', wake); resolve(); }, ms);
714
+ timer.unref();
715
+ signal.addEventListener('abort', wake, { once: true });
716
+ });
717
+ }
718
+ /** The setup link appears only after lark-cli starts; the connector strips it from published snapshots, so fetch it once for the owner. The connector allows 300s for the config operation, so poll while it is still waiting; a status call that fails transiently is retried instead of dropping the link. */
719
+ async #pollFeishuSetup(owner, signal) {
720
+ const deadline = Date.now() + (this.options.feishuSetupTimeoutMs ?? 300_000);
721
+ let failures = 0;
722
+ while (this.#opened && !signal.aborted && Date.now() < deadline) {
723
+ await this.#sleep(this.options.feishuPollMs ?? 1000, signal);
724
+ // Every await can outlive close: re-check before touching the host or publishing.
725
+ if (!this.#opened || signal.aborted)
726
+ return;
727
+ const result = await this.options.host.command({ type: 'personal.command', request_id: 'space-feishu-setup-' + randomUUID(), method: 'feishu.app.status', params: {} }, { client_id: 'space:' + owner }).catch(() => undefined);
728
+ if (!this.#opened || signal.aborted)
729
+ return;
730
+ if (!result?.ok) {
731
+ if (++failures >= 3)
732
+ return;
733
+ continue;
734
+ }
735
+ failures = 0;
736
+ const view = feishuView(result.data), url = view.app_setup?.verification_url;
737
+ if (view.app_setup?.state !== 'waiting')
738
+ return;
739
+ if (url) {
740
+ this.#setupUrl = url;
741
+ if (this.#hostAdmin(owner) && this.#opened && !signal.aborted)
742
+ await this.publishSnapshot(owner);
743
+ return;
744
+ }
745
+ }
746
+ }
747
+ async #record(sender, intent, hash, value, id) {
748
+ const receipt = { v: 1, type: 'receipt', op_id: intent.op_id, ...value };
749
+ const key = this.#key(sender, intent.op_id), tag = SECRET_KINDS.has(intent.kind) ? this.#secretTag(key, fingerprint(intent)) : undefined, projection = value.status === 'accepted' && ['life.mutate', 'card.dismiss', 'source.input', 'snapshot.request', 'settings.patch', 'secret.put', 'secret.clear', 'connector.feishu', 'approval.resolve'].includes(intent.kind) ? this.snapshot(sender) : undefined;
750
+ this.#enqueue(sender, receipt, id ?? 'receipt-' + key);
751
+ if (projection)
752
+ this.#queueSnapshot(sender, projection, 'snapshot-' + key);
753
+ // Every path that records a secret op stores its salted tag, including the early pending and dependency records, so a retry stays idempotent across a restart.
754
+ const { snapshot: _snapshot, ...stored } = receipt;
755
+ this.#state.ops[key] = { ...this.#state.ops[key], hash, ...(tag ? { tag } : {}), intent: this.#journalIntent(intent), sender, receipt: stored, recorded_at: this.#state.ops[key]?.recorded_at ?? this.#now() };
756
+ await this.#save();
757
+ if (projection)
758
+ await this.options.transport.recoverPending?.(this.#state.outbox.map(row => row.id));
759
+ }
760
+ async #runChat(key) {
761
+ const op = this.#state.ops[key];
762
+ const conversation = displayText(op.intent.input.conversation_id, 'chat:main');
763
+ let sequence = 0;
764
+ const unsubscribe = this.options.host.subscribeSpaceFrames(frame => { if (frame.conversation_id !== conversation || typeof frame.text !== 'string' || frame.role !== 'assistant')
765
+ return; void this.options.transport.stream(op.sender, { v: 1, type: 'chat.delta', op_id: op.intent.op_id, conversation_id: conversation, text: typeof frame.full_text === 'string' ? frame.full_text : frame.text, sequence: ++sequence }, 'delta-' + randomUUID()).catch(() => { }); });
766
+ try {
767
+ this.#requireChat(conversation);
768
+ await this.options.host.submitConversationText(conversation, String(op.intent.input.text), 'space:' + key);
769
+ await this.options.host.waitConversation(conversation);
770
+ await this.#serial(() => this.#finishChat(key, this.options.host.spaceChatResult('space:' + key, conversation) ?? { text: '', status: 'failed', message_id: 'turn-' + key }));
771
+ }
772
+ catch (error) {
773
+ await this.#serial(() => this.#finishChat(key, { text: '', status: 'failed', message_id: 'turn-' + key, error: chatFailure(error) }));
774
+ }
775
+ finally {
776
+ unsubscribe();
777
+ }
778
+ await this.dispatchNotifications();
779
+ await this.flush();
780
+ }
781
+ async #finishChat(key, result) { const op = { ...this.#state.ops[key], chat_status: 'completed', final: result, ...(result.status === 'completed' && result.text ? { notification_pending: true } : {}) }; this.#state.ops[key] = op; this.#enqueue(op.sender, { v: 1, type: 'chat.final', op_id: op.intent.op_id, conversation_id: displayText(op.intent.input.conversation_id, 'chat:main'), ...result }, 'final-' + key); await this.#save(); }
782
+ async dispatchNotifications() { for (const [key, op] of Object.entries(this.#state.ops)) {
783
+ if (!op.notification_pending || !op.final)
784
+ continue;
785
+ const now = this.#now();
786
+ await this.options.host.publishNotification({ event_key: 'space-chat:' + key, revision: '1', occurrence: 'initial', kind: 'alert', title: 'Nova', body: String(op.final.text), source: { type: 'space_chat', id: key }, created_at: now, expires_at: null, not_before: 0, priority: 100, coalesce_key: null, feedback: [] });
787
+ await this.#serial(async () => { const current = this.#state.ops[key]; if (current)
788
+ this.#state.ops[key] = { ...current, notification_pending: false }; await this.#save(); });
789
+ } }
790
+ async waitForChats() { await Promise.all([...this.#chats.values()]); }
791
+ async notify(notification, id, validity) { await this.#serial(async () => { for (const to of this.options.transport.clients()) {
792
+ this.#enqueue(to, { v: 1, type: 'notification', ...notification, id }, 'notification-' + fingerprint([id, to]));
793
+ if (this.options.push && !this.#state.push_outbox.some(row => row.id === id && row.to === to))
794
+ this.#state.push_outbox.push({ to, id, title: displayText(notification.title), body: displayText(notification.body), expires_at: Math.min(typeof notification.expires_at === 'number' ? notification.expires_at : Infinity, (typeof notification.created_at === 'number' ? notification.created_at : this.#now()) + 86400000), ...(validity ? { notification: structuredClone(validity) } : {}) });
795
+ } await this.#save(); }); await this.flush(); }
796
+ async #flushPush() {
797
+ if (!this.options.push)
798
+ return;
799
+ for (const next of [...this.#state.push_outbox]) {
800
+ // Legacy pending rows have no validity deadline. Do not extend an unknown-age notification on upgrade.
801
+ const expired = next.expires_at === undefined || next.expires_at <= this.#now();
802
+ const validity = expired ? 'invalid' : next.notification ? await this.options.host.notificationValidity(next.notification) : 'valid';
803
+ if (validity === 'defer')
804
+ continue;
805
+ if (validity === 'valid' && next.expires_at !== undefined)
806
+ await this.options.push.send(next.to, { id: next.id, title: next.title, body: next.body, expires_at: next.expires_at });
807
+ await this.#serial(async () => { this.#state.push_outbox = this.#state.push_outbox.filter(row => row.id !== next.id || row.to !== next.to); await this.#save(); });
808
+ }
809
+ }
810
+ async requestMobileAction(device, action, ttlMs = 60000, providedId) { if (!this.options.transport.clients().includes(device))
811
+ throw Error('client_not_paired'); if (ttlMs <= 0 || ttlMs > 60000)
812
+ throw Error('invalid_action_deadline'); const parsed = mobileActionSchema.parse(action), action_id = providedId ?? randomUUID(), body = { v: 1, type: 'mobile.action', action_id, ...parsed, expires_at: this.#now() + ttlMs }; await this.#serial(async () => { const prior = this.#state.actions[action_id]; if (prior) {
813
+ if (prior.device !== device || fingerprint({ tool: prior.body.tool, args: prior.body.args }) !== fingerprint(parsed))
814
+ throw Error('action_id_conflict');
815
+ return;
816
+ } this.#state.actions[action_id] = { device, body, result: null }; this.#enqueue(device, body, 'action-' + action_id); await this.#save(); }); await this.flush(); return { action_id }; }
817
+ mobileResult(actionId) { return structuredClone(this.#state.actions[actionId]?.result ?? null); }
818
+ flush() { const pass = (this.#flush ?? Promise.resolve()).then(() => this.#drainOutbox()); this.#flush = pass.then(() => { }, () => { }); return pass; }
819
+ /** One bounded pass over the rows queued when it runs: a steady stream of unrelated snapshots must not keep a caller's own receipt pending behind a chase that only ends once the Host goes quiet. */
820
+ async #drainOutbox() { if (!this.#opened)
821
+ return; for (const next of [...this.#state.outbox]) {
822
+ try {
823
+ await this.options.transport.send(next.to, next.body, next.id);
824
+ }
825
+ catch (error) {
826
+ this.options.onError?.(error);
827
+ continue;
828
+ }
829
+ await this.#serial(async () => { this.#state.outbox = this.#state.outbox.filter(row => row.id !== next.id || row.to !== next.to); await this.#save(); });
830
+ await this.options.transport.settle?.(next.id);
831
+ } await this.#flushPush(); }
832
+ async close(reason = 'host_closed') { this.#opened = false; await this.options.voice?.closeAll(reason).catch(error => this.options.onError?.(error)); if (this.#approvalTimer)
833
+ clearTimeout(this.#approvalTimer); this.#approvalTimer = undefined; if (this.#snapshotTimer)
834
+ clearTimeout(this.#snapshotTimer); this.#snapshotTimer = undefined; const polls = [...this.#feishuPolls.values()]; for (const poll of polls)
835
+ poll.abort.abort(); await Promise.all(polls.map(poll => poll.task.catch(() => undefined))); for (const op of Object.values(this.#state.ops))
836
+ if (op.chat_status === 'admitted')
837
+ await this.options.host.cancelSpaceChat(displayText(op.intent.input.conversation_id, 'chat:main')); await this.waitForChats(); if (this.#snapshotTimer)
838
+ clearTimeout(this.#snapshotTimer); this.#snapshotTimer = undefined; this.#unsubscribe?.(); await this.#stop?.(); await this.#flush; if (this.#loaded)
839
+ await this.#serial(() => this.#save()); await this.#tail; }
840
+ }
841
+ //# sourceMappingURL=service.js.map