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
@@ -0,0 +1,115 @@
1
+ import { createServer, createConnection } from 'node:net';
2
+ import { chmod, lstat, unlink } from 'node:fs/promises';
3
+ import { z } from 'zod';
4
+ export const SPACE_ADMIN_REQUEST_LIMIT = 16 * 1024;
5
+ const request = z.discriminatedUnion('method', [
6
+ z.object({ id: z.union([z.string().max(64), z.number().int()]), method: z.literal('status'), params: z.object({}).strict().optional() }).strict(),
7
+ z.object({ id: z.union([z.string().max(64), z.number().int()]), method: z.literal('invitation'), params: z.object({}).strict().optional() }).strict(),
8
+ z.object({ id: z.union([z.string().max(64), z.number().int()]), method: z.literal('pairings'), params: z.object({}).strict().optional() }).strict(),
9
+ z.object({ id: z.union([z.string().max(64), z.number().int()]), method: z.literal('confirm_pairing'), params: z.object({ id: z.string().min(1).max(256), fingerprint: z.string().min(1).max(512) }).strict() }).strict(),
10
+ z.object({ id: z.union([z.string().max(64), z.number().int()]), method: z.literal('revoke'), params: z.object({ device: z.string().min(1).max(256) }).strict() }).strict(),
11
+ ]);
12
+ export const adminSocketPath = (configPath) => configPath + '.admin.sock';
13
+ const connectable = (path) => new Promise(resolve => { const socket = createConnection(path); socket.once('connect', () => { socket.destroy(); resolve(true); }); socket.once('error', () => resolve(false)); });
14
+ async function dispatch(target, value) {
15
+ if (value.method === 'status')
16
+ return target.status();
17
+ if (value.method === 'invitation')
18
+ return target.invitation();
19
+ if (value.method === 'pairings')
20
+ return target.pairings();
21
+ if (value.method === 'confirm_pairing')
22
+ return target.confirmPairing(value.params.id, value.params.fingerprint);
23
+ return target.revoke(value.params.device);
24
+ }
25
+ function serve(target, socket) {
26
+ let buffer = '', chain = Promise.resolve();
27
+ const reject = (error) => { socket.end(JSON.stringify({ id: null, ok: false, error }) + '\n'); };
28
+ socket.setEncoding('utf8');
29
+ socket.on('error', () => socket.destroy());
30
+ socket.on('data', (chunk) => {
31
+ buffer += chunk;
32
+ for (let index = buffer.indexOf('\n'); index >= 0; index = buffer.indexOf('\n')) {
33
+ const line = buffer.slice(0, index);
34
+ buffer = buffer.slice(index + 1);
35
+ if (Buffer.byteLength(line) > SPACE_ADMIN_REQUEST_LIMIT)
36
+ return reject('request_too_large');
37
+ let parsed;
38
+ try {
39
+ parsed = request.parse(JSON.parse(line));
40
+ }
41
+ catch {
42
+ return reject('malformed_request');
43
+ }
44
+ chain = chain.then(async () => { let reply; try {
45
+ reply = { id: parsed.id, ok: true, data: await dispatch(target, parsed) ?? null };
46
+ }
47
+ catch (error) {
48
+ reply = { id: parsed.id, ok: false, error: error instanceof Error ? error.message.slice(0, 128) : 'request_failed' };
49
+ } if (!socket.destroyed)
50
+ socket.write(JSON.stringify(reply) + '\n'); });
51
+ }
52
+ if (Buffer.byteLength(buffer) > SPACE_ADMIN_REQUEST_LIMIT)
53
+ reject('request_too_large');
54
+ });
55
+ }
56
+ /** Returns undefined (after a diagnostic) when the socket cannot be offered; Host startup never fails because of it. */
57
+ export async function startSpaceAdminSocket(target, path, onDiagnostic) {
58
+ if (process.platform === 'win32')
59
+ return undefined;
60
+ if (Buffer.byteLength(path) > (process.platform === 'darwin' ? 103 : 107)) {
61
+ onDiagnostic?.('space_admin_socket_unavailable');
62
+ return undefined;
63
+ }
64
+ try {
65
+ const existing = await lstat(path).catch(error => { if (error.code === 'ENOENT')
66
+ return undefined; throw error; });
67
+ if (existing) {
68
+ if (!existing.isSocket() || await connectable(path))
69
+ throw Error('space_admin_socket_occupied');
70
+ await unlink(path);
71
+ }
72
+ const connections = new Set(), server = createServer(socket => { connections.add(socket); socket.once('close', () => connections.delete(socket)); serve(target, socket); });
73
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(path, () => { server.off('error', reject); resolve(); }); });
74
+ await chmod(path, 0o600);
75
+ return { close: async () => { for (const socket of connections)
76
+ socket.destroy(); await new Promise(resolve => server.close(() => resolve())); await unlink(path).catch(() => undefined); } };
77
+ }
78
+ catch {
79
+ onDiagnostic?.('space_admin_socket_unavailable');
80
+ return undefined;
81
+ }
82
+ }
83
+ /** One request/response round trip for the CLI. */
84
+ export function spaceAdminRequest(path, method, params, timeoutMs = 60000) {
85
+ return new Promise((resolve, reject) => {
86
+ const socket = createConnection(path);
87
+ let buffer = '';
88
+ const id = Math.floor(Math.random() * 2 ** 31);
89
+ const fail = (error) => { clearTimeout(timer); socket.destroy(); reject(error); }, timer = setTimeout(() => fail(Error('space_admin_timeout')), timeoutMs);
90
+ socket.setEncoding('utf8');
91
+ socket.once('connect', () => socket.write(JSON.stringify({ id, method, ...(params ? { params } : {}) }) + '\n'));
92
+ socket.on('error', error => fail(['ENOENT', 'ECONNREFUSED'].includes(error.code ?? '') ? Error('space_host_not_running') : error));
93
+ socket.on('close', () => fail(Error('space_admin_closed')));
94
+ socket.on('data', (chunk) => {
95
+ buffer += chunk;
96
+ const index = buffer.indexOf('\n');
97
+ if (index < 0)
98
+ return;
99
+ try {
100
+ const reply = z.object({ id: z.unknown(), ok: z.boolean(), data: z.unknown().optional(), error: z.string().optional() }).parse(JSON.parse(buffer.slice(0, index)));
101
+ clearTimeout(timer);
102
+ socket.removeAllListeners('close');
103
+ socket.destroy();
104
+ if (reply.ok)
105
+ resolve(reply.data);
106
+ else
107
+ reject(Error(reply.error ?? 'request_failed'));
108
+ }
109
+ catch (error) {
110
+ fail(error instanceof Error ? error : Error('space_admin_invalid_reply'));
111
+ }
112
+ });
113
+ });
114
+ }
115
+ //# sourceMappingURL=admin-socket.js.map
@@ -0,0 +1,44 @@
1
+ export class AudioOwnerArbiter {
2
+ #current = null;
3
+ #next = 0;
4
+ #tail = Promise.resolve();
5
+ #listeners = new Set();
6
+ get current() { return this.#current ? { owner: this.#current.owner, lease: this.#current.lease } : null; }
7
+ /** The device of the Space call that owns audio, if any. */
8
+ get spaceDevice() { const owner = this.#current?.owner; return owner?.startsWith('space:') ? owner.slice(6) : undefined; }
9
+ owns(lease) { return this.#current?.lease === lease; }
10
+ /** Synchronous claim; refuses with voice_active while another owner holds audio. Re-claiming one's own kind keeps the lease. */
11
+ claim(owner, preempt) {
12
+ if (this.#current) {
13
+ if (this.#current.owner === owner && !owner.startsWith('space:'))
14
+ return this.#current.lease;
15
+ throw Error('voice_active');
16
+ }
17
+ this.#current = { owner, lease: ++this.#next, ...(preempt ? { preempt } : {}) };
18
+ this.#notify();
19
+ return this.#current.lease;
20
+ }
21
+ release(lease) { if (this.#current?.lease !== lease)
22
+ return false; this.#current = null; this.#notify(); return true; }
23
+ /** Local desktop always takes over a Space call (approved decision 4). Other owners are left alone. */
24
+ async takeOver(reason = 'taken_over') {
25
+ const current = this.#current;
26
+ if (!current?.owner.startsWith('space:'))
27
+ return;
28
+ await current.preempt?.(reason);
29
+ // A preemption that failed to release must not leave the desktop locked out.
30
+ if (this.#current?.lease === current.lease) {
31
+ this.#current = null;
32
+ this.#notify();
33
+ }
34
+ }
35
+ serial(work) { const run = this.#tail.then(work); this.#tail = run.catch(() => { }); return run; }
36
+ subscribe(listener) { this.#listeners.add(listener); return () => this.#listeners.delete(listener); }
37
+ #notify() { for (const listener of this.#listeners) {
38
+ try {
39
+ listener();
40
+ }
41
+ catch { /* observers cannot break ownership */ }
42
+ } }
43
+ }
44
+ //# sourceMappingURL=audio-owner.js.map
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ import { constants } from 'node:fs';
3
+ import { open, mkdir, stat } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { createInterface } from 'node:readline/promises';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { initializeHostSpace, resumeHostSpaceRegistration } from './config.js';
9
+ import { adminSocketPath, spaceAdminRequest } from './admin-socket.js';
10
+ const usage = 'usage: nova-space-host init --config /new/space/config.json --data /new/space/personal.json --relay https://relay.example --bootstrap-file /private/operator-token\n nova-space-host resume --config /existing/space/config.json --bootstrap-file /private/operator-token\n nova-space-host status|devices --config /existing/space/config.json\n nova-space-host pair --config /existing/space/config.json [--timeout-seconds 300] [--yes-fingerprint FINGERPRINT]\n nova-space-host revoke --config /existing/space/config.json --device DEVICE_ID\nstatus, pair, devices and revoke talk to the running Host (novapersonal-server start, or the desktop) through <config>.admin.sock.';
11
+ export function parseSpaceInit(args) {
12
+ if (args[0] !== 'init' || args.length !== 9)
13
+ throw Error(usage);
14
+ const values = new Map();
15
+ for (let i = 1; i < args.length; i += 2) {
16
+ const key = args[i], value = args[i + 1];
17
+ if (!['--config', '--data', '--relay', '--bootstrap-file'].includes(key) || values.has(key) || !value)
18
+ throw Error(usage);
19
+ values.set(key, value);
20
+ }
21
+ const configPath = values.get('--config'), personalPath = values.get('--data'), bootstrapFile = values.get('--bootstrap-file'), relayUrl = values.get('--relay');
22
+ if (![configPath, personalPath, bootstrapFile].every(isAbsolute))
23
+ throw Error(usage);
24
+ if (new Set([resolve(configPath), resolve(personalPath), resolve(bootstrapFile)]).size !== 3)
25
+ throw Error('space_paths_must_be_distinct');
26
+ const url = new URL(relayUrl);
27
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
28
+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))))
29
+ throw Error('relay_tls_origin_required');
30
+ return { configPath, personalPath, relayUrl, bootstrapFile };
31
+ }
32
+ /** Host data stores refuse a group- or world-accessible parent at startup, so init rejects one before registering. */
33
+ export async function assertPrivateDirectory(path) {
34
+ if (process.platform === 'win32')
35
+ return;
36
+ const info = await stat(path);
37
+ if (!info.isDirectory() || (info.mode & 0o077) !== 0)
38
+ throw Error(`space_directory_must_be_private: ${path} (chmod 700)`);
39
+ }
40
+ export function parseSpaceResume(args) {
41
+ if (args[0] !== 'resume' || args.length !== 5)
42
+ throw Error(usage);
43
+ const values = new Map();
44
+ for (let i = 1; i < args.length; i += 2) {
45
+ const key = args[i], value = args[i + 1];
46
+ if (!['--config', '--bootstrap-file'].includes(key) || values.has(key) || !value)
47
+ throw Error(usage);
48
+ values.set(key, value);
49
+ }
50
+ const configPath = values.get('--config'), bootstrapFile = values.get('--bootstrap-file');
51
+ if (![configPath, bootstrapFile].every(isAbsolute))
52
+ throw Error(usage);
53
+ if (resolve(configPath) === resolve(bootstrapFile))
54
+ throw Error('space_paths_must_be_distinct');
55
+ return { configPath, bootstrapFile };
56
+ }
57
+ export function parseSpaceAdmin(args) {
58
+ const command = args[0];
59
+ if (command !== 'status' && command !== 'pair' && command !== 'devices' && command !== 'revoke')
60
+ throw Error(usage);
61
+ const allowed = ['--config', ...command === 'pair' ? ['--timeout-seconds', '--yes-fingerprint'] : [], ...command === 'revoke' ? ['--device'] : []];
62
+ const values = new Map();
63
+ if (args.length % 2 === 0)
64
+ throw Error(usage);
65
+ for (let i = 1; i < args.length; i += 2) {
66
+ const key = args[i], value = args[i + 1];
67
+ if (!allowed.includes(key) || values.has(key) || !value || value.startsWith('--'))
68
+ throw Error(usage);
69
+ values.set(key, value);
70
+ }
71
+ const configPath = values.get('--config');
72
+ if (!configPath || command === 'revoke' && !values.get('--device'))
73
+ throw Error(usage);
74
+ const seconds = values.has('--timeout-seconds') ? Number(values.get('--timeout-seconds')) : 300;
75
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600)
76
+ throw Error(usage);
77
+ return { command, configPath: resolve(configPath), timeoutSeconds: seconds, ...values.has('--device') ? { device: values.get('--device') } : {}, ...values.has('--yes-fingerprint') ? { yesFingerprint: values.get('--yes-fingerprint') } : {} };
78
+ }
79
+ /** Same bytes the desktop encodes: the invitation JSON without any rendered image. Compact renderer plus a four-module quiet zone. */
80
+ export async function renderInvitationQr(invitation) {
81
+ const value = JSON.stringify(invitation);
82
+ if (value.length > 8192)
83
+ throw Error('pairing_payload_too_large');
84
+ const name = 'qrcode', { default: QRCode } = await import(name), data = [{ data: value, mode: 'byte' }], options = { type: 'terminal', small: true, errorCorrectionLevel: 'M' };
85
+ const width = QRCode.create(data, options).modules.size + 8, white = '\x1b[47m', reset = '\x1b[0m', border = white + ' '.repeat(width) + reset + '\n';
86
+ const rows = (await QRCode.toString(data, options)).split('\n').slice(0, -1);
87
+ return border.repeat(2) + rows.map((row) => white + ' ' + row + white + ' ' + reset + '\n').join('') + border.repeat(2);
88
+ }
89
+ const pairingRows = (value) => Array.isArray(value) ? value : [];
90
+ export async function runSpacePair(options, io) {
91
+ const socket = adminSocketPath(options.configPath);
92
+ if (!io.interactive && !options.yesFingerprint)
93
+ throw Error('space_pair_requires_tty');
94
+ const invitation = await spaceAdminRequest(socket, 'invitation');
95
+ io.output.write('在手机 Nova 选择「连接 Host」→「扫描 Host 邀请码」,扫描下方二维码(一次性,Ctrl+C 取消):\n' + await renderInvitationQr(invitation) + '等待手机发起配对…\n');
96
+ const deadline = Date.now() + options.timeoutSeconds * 1000, skipped = new Set();
97
+ while (!io.signal.aborted) {
98
+ // Older abandoned requests stay pending until expiry; never let one block the intended phone.
99
+ const rows = pairingRows(await spaceAdminRequest(socket, 'pairings')).filter(row => !skipped.has(row.id));
100
+ const request = options.yesFingerprint !== undefined ? rows.find(row => row.fingerprint === options.yesFingerprint) : rows[0];
101
+ if (request) {
102
+ io.output.write(`收到配对请求:设备 ${request.device}\n指纹:${request.fingerprint}\n`);
103
+ if (options.yesFingerprint === undefined && !await io.confirm('确认该手机指纹与手机上显示一致?[y/N] ')) {
104
+ skipped.add(request.id);
105
+ io.output.write('已跳过该请求,继续等待…\n');
106
+ continue;
107
+ }
108
+ await spaceAdminRequest(socket, 'confirm_pairing', { id: request.id, fingerprint: request.fingerprint });
109
+ io.output.write(`已绑定设备 ${request.device}\n`);
110
+ return 0;
111
+ }
112
+ if (Date.now() >= deadline) {
113
+ io.output.write(options.yesFingerprint !== undefined && skipped.size + rows.length > 0 ? '没有指纹与 --yes-fingerprint 一致的请求,未绑定。\n' : '等待配对超时,请重新运行 pair。\n');
114
+ return 1;
115
+ }
116
+ await delay(io.pollMs ?? 2000, undefined, { signal: io.signal }).catch(() => undefined);
117
+ }
118
+ io.output.write('已取消配对。\n');
119
+ return 1;
120
+ }
121
+ async function adminMain(args) {
122
+ const options = parseSpaceAdmin(args), socket = adminSocketPath(options.configPath);
123
+ if (options.command === 'pair') {
124
+ const stop = new AbortController(), cancel = () => stop.abort(), signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
125
+ for (const name of signals)
126
+ process.on(name, cancel);
127
+ const interactive = !!process.stdin.isTTY && !!process.stdout.isTTY;
128
+ try {
129
+ return await runSpacePair(options, { output: process.stdout, interactive, signal: stop.signal, confirm: async (question) => { const rl = createInterface({ input: process.stdin, output: process.stdout }); const abort = () => rl.close(); stop.signal.addEventListener('abort', abort, { once: true }); try {
130
+ return /^y(es)?$/i.test((await rl.question(question)).trim());
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ finally {
136
+ stop.signal.removeEventListener('abort', abort);
137
+ rl.close();
138
+ } } });
139
+ }
140
+ finally {
141
+ for (const name of signals)
142
+ process.off(name, cancel);
143
+ }
144
+ }
145
+ const status = await spaceAdminRequest(socket, options.command === 'revoke' ? 'revoke' : 'status', options.command === 'revoke' ? { device: options.device } : undefined);
146
+ if (options.command === 'devices')
147
+ process.stdout.write(status.clients.length ? status.clients.join('\n') + '\n' : '尚未配对任何手机。\n');
148
+ else
149
+ process.stdout.write(`Space ${status.space}\nRelay ${status.relay_url}\nEpoch ${status.epoch}\nDevices ${status.clients.length}${status.pairing_pending ? '\nPairing pending' : ''}${status.revocation_pending ? '\nRevocation pending' : ''}\n`);
150
+ return 0;
151
+ }
152
+ export async function main(args) {
153
+ if (['status', 'pair', 'devices', 'revoke'].includes(args[0] ?? ''))
154
+ return adminMain(args);
155
+ if (args.length === 1 && args[0] === '--help') {
156
+ process.stdout.write(usage + '\nHost loss means Space loss. A new mode always requires a new Space.\n');
157
+ return 0;
158
+ }
159
+ const options = args[0] === 'resume' ? { mode: 'resume', ...parseSpaceResume(args) } : { mode: 'init', ...parseSpaceInit(args) };
160
+ const file = await open(options.bootstrapFile, constants.O_RDONLY | constants.O_NOFOLLOW);
161
+ let bootstrapToken;
162
+ try {
163
+ const stat = await file.stat();
164
+ if (!stat.isFile() || stat.size > 4096 || process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
165
+ throw Error('bootstrap_file_must_be_private');
166
+ bootstrapToken = (await file.readFile('utf8')).trim();
167
+ if (bootstrapToken.length < 32)
168
+ throw Error('bootstrap_token_too_short');
169
+ }
170
+ finally {
171
+ await file.close();
172
+ }
173
+ let result;
174
+ if (options.mode === 'init') {
175
+ await mkdir(dirname(options.configPath), { recursive: true, mode: 0o700 });
176
+ await mkdir(dirname(options.personalPath), { recursive: true, mode: 0o700 });
177
+ for (const directory of new Set([dirname(options.configPath), dirname(options.personalPath)]))
178
+ await assertPrivateDirectory(directory);
179
+ result = await initializeHostSpace({ ...options, bootstrapToken });
180
+ }
181
+ else
182
+ result = await resumeHostSpaceRegistration({ ...options, bootstrapToken });
183
+ process.stdout.write(`Registered Host Space ${result.space}\nSet NOVA_SPACE_HOST_CONFIG=${result.configPath} for the Host.\nDesktop: open Settings > Connections > Space and pair a phone.\nHeadless: run novapersonal-server start, then nova-space-host pair --config ${result.configPath}\n`);
184
+ return 0;
185
+ }
186
+ if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
187
+ try {
188
+ process.exitCode = await main(process.argv.slice(2));
189
+ }
190
+ catch (error) {
191
+ process.stderr.write(`nova-space-host: ${error instanceof Error ? error.message : 'initialization_failed'}\n`);
192
+ process.exitCode = 1;
193
+ }
194
+ }
195
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,247 @@
1
+ import { loadSettings } from '../config/config.js';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, basename, isAbsolute, resolve } from 'node:path';
4
+ import { readdir, lstat } from 'node:fs/promises';
5
+ import { canonicalJson } from '../text/canonical-json.js';
6
+ import { SpacePushDelivery } from './push.js';
7
+ import { DurableKeyDelivery } from './key-delivery.js';
8
+ import { z } from 'zod';
9
+ import { constants, openSync, readFileSync, fstatSync, closeSync, existsSync } from 'node:fs';
10
+ import { open } from 'node:fs/promises';
11
+ import { randomBytes, randomUUID, createHash } from 'node:crypto';
12
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
13
+ import { SpaceHost } from './service.js';
14
+ import { SpaceVoiceController } from './voice.js';
15
+ import { adminSocketPath, startSpaceAdminSocket } from './admin-socket.js';
16
+ import { HostSecretStore, spaceSecretsPath } from './host-admin.js';
17
+ import { HostModelRoutesStore } from './model-settings.js';
18
+ export { readHostModelRoutes, seedHostModelRoutes } from './model-settings.js';
19
+ import { createRelaySpaceTransport } from './relay-transport.js';
20
+ const jwk = z.record(z.string(), z.unknown());
21
+ const identity = z.object({ device: z.string(), signingPublicKey: jwk, signingPrivateKey: jwk, encryptionPublicKey: jwk, encryptionPrivateKey: jwk });
22
+ const member = z.object({ selected_version: z.literal(1), device: z.string(), signingPublicKey: jwk, encryptionPublicKey: jwk });
23
+ export const hostSpaceConfigSchema = z.object({ v: z.union([z.literal(1), z.literal(2)]), mode: z.literal('host'), space: z.string(), personal_path: z.string(), data_mode: z.enum(['isolated', 'existing']).optional(), relay_url: z.string().url(), epoch: z.number().int().positive(), identity, content_key: z.string().regex(/^[A-Za-z0-9_-]{43}$/), members: z.array(member).max(64), pending_pairing: z.object({ request_id: z.string(), op_id: z.string(), member, fingerprint: z.string() }).optional(), revoked_members: z.array(member).max(1024).optional(), pending_revoke: z.object({ device: z.string(), op_id: z.string(), new_content_key: z.string() }).optional(), push_gateway_url: z.string().url().optional(), owner_device: z.string().optional(), voice_policy: z.enum(['off', 'owner', 'members']).optional() }).refine(config => config.v === 1 || config.data_mode === 'existing', { message: 'space_config_mode_invalid', path: ['data_mode'] });
24
+ async function modules() { const cryptoPackage = '@nova-personal-agent/relay/crypto', clientPackage = '@nova-personal-agent/relay/client'; const crypto = await import(cryptoPackage), client = await import(clientPackage); return { crypto: crypto, RelayClient: client.RelayClient }; }
25
+ function client(config, sdk) { return new sdk.RelayClient({ url: config.relay_url, space: config.space, device: config.identity.device, signChallenge: challenge => sdk.crypto.signControl({ v: 1, purpose: 'relay-login', challengeId: challenge.id, nonce: challenge.nonce, space: challenge.space, device: challenge.device, epoch: challenge.epoch, expiresAt: challenge.expiresAt }, config.identity.signingPrivateKey) }); }
26
+ /** A new Space gets a new identity and its own PersonalAgentHost data path. Never migrate an existing Space. */
27
+ export async function initializeHostSpace(options) {
28
+ if (!isAbsolute(options.personalPath) || !isAbsolute(options.configPath))
29
+ throw Error('space_paths_must_be_absolute');
30
+ const siblings = await readdir(dirname(options.personalPath)).catch(error => { if (error.code === 'ENOENT')
31
+ return []; throw error; });
32
+ if (siblings.some(name => name === basename(options.personalPath) || name.startsWith(basename(options.personalPath) + '.')))
33
+ throw Error('space_personal_path_exists');
34
+ if (existsSync(options.personalPath))
35
+ throw Error('space_personal_path_exists');
36
+ return createHostSpace(options, 'isolated');
37
+ }
38
+ /** Attach only the trusted desktop's current personal store; no original file is rewritten. */
39
+ export async function attachExistingHostSpace(options) {
40
+ if (!isAbsolute(options.personalPath) || !isAbsolute(options.configPath))
41
+ throw Error('space_paths_must_be_absolute');
42
+ const info = await lstat(options.personalPath).catch(error => { if (error.code === 'ENOENT')
43
+ throw Error('space_existing_data_unavailable'); throw error; });
44
+ if (!info.isFile())
45
+ throw Error('space_existing_data_invalid');
46
+ return createHostSpace(options, 'existing');
47
+ }
48
+ export function existingHostPersonalPath(environment) { const settings = loadSettings(environment, false), path = settings.blackboard_path.replace(/^~(?=\/)/u, homedir()); if (!isAbsolute(path))
49
+ throw Error('space_existing_data_unavailable'); return resolve(path) + '.personal.json'; }
50
+ async function createHostSpace(options, dataMode) {
51
+ const sdk = await modules(), keys = await sdk.crypto.generateDeviceIdentity(), space = sdk.crypto.spaceId(keys.signingPublicKey);
52
+ const config = { v: dataMode === 'existing' ? 2 : 1, mode: 'host', space, personal_path: options.personalPath, data_mode: dataMode, relay_url: options.relayUrl, epoch: 1, identity: keys, content_key: randomBytes(32).toString('base64url'), members: [] };
53
+ // Exclusive destination prevents accidental in-place identity or mode replacement.
54
+ const file = await open(options.configPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
55
+ await file.close();
56
+ await new BoundedJsonStore(options.configPath, hostSpaceConfigSchema).write(config);
57
+ await resumeHostSpaceRegistration({ configPath: options.configPath, bootstrapToken: options.bootstrapToken });
58
+ return { space, configPath: options.configPath };
59
+ }
60
+ /** Local-only pairing manager. Public keys are pinned on explicit fingerprint confirmation. */
61
+ export class SpaceHostController {
62
+ path;
63
+ config;
64
+ host;
65
+ sdk;
66
+ environment;
67
+ service;
68
+ models;
69
+ secrets;
70
+ #client;
71
+ #store;
72
+ #keys;
73
+ #opened = false;
74
+ #admin;
75
+ #management = Promise.resolve();
76
+ #retry;
77
+ #voiceController;
78
+ constructor(path, config, host, sdk, environment = process.env) {
79
+ this.path = path;
80
+ this.config = config;
81
+ this.host = host;
82
+ this.sdk = sdk;
83
+ this.environment = environment;
84
+ this.secrets = new HostSecretStore(spaceSecretsPath(path));
85
+ this.models = new HostModelRoutesStore(path, environment, { credentialConfigured: name => !!this.secrets.value(name)?.trim() });
86
+ this.#client = client(config, sdk);
87
+ this.#store = new BoundedJsonStore(path, hostSpaceConfigSchema);
88
+ this.#keys = new DurableKeyDelivery({ path: path + '.keys.json', create: (epoch, device) => this.#createKey(epoch, device), send: async (envelope) => { await this.#client.send(envelope); } });
89
+ }
90
+ async #service() { const transport = await createRelaySpaceTransport({ path: this.path + '.envelopes.' + this.config.epoch + '.json', space: this.config.space, epoch: this.config.epoch, identity: this.config.identity, members: Object.fromEntries(this.config.members.map(member => [member.device, member.signingPublicKey])), historicalMembers: Object.fromEntries((this.config.revoked_members ?? []).map(member => [member.device, member.signingPublicKey])), contentKey: Buffer.from(this.config.content_key, 'base64url'), client: this.#client, crypto: this.sdk.crypto, beforeSend: device => this.#keys.deliver(this.config.epoch, device), onError: () => this.host.options.onDiagnostic?.('space_relay_unavailable') }); const voice = this.#voice(transport); return new SpaceHost({ ...(voice ? { voice } : {}), path: this.path + '.journal.json', space: this.config.space, host: this.host, transport, owner: () => this.config.owner_device, revokeDevice: device => this.revoke(device), secrets: this.secrets, models: this.models, environment: this.environment, ...(this.config.push_gateway_url ? { push: new SpacePushDelivery({ path: this.path + '.push.json', gatewayUrl: this.config.push_gateway_url }) } : {}), onError: () => this.host.options.onDiagnostic?.('space_relay_unavailable') }); }
91
+ /** Space voice is wired only on a voice-capable desktop Host whose relay SDK has media support (docs/design/space-voice.md). */
92
+ #voice(transport) {
93
+ const port = this.host.spaceVoicePort(), sdk = this.#client;
94
+ if (!port || !sdk.capabilities || !sdk.reserveMedia || !sdk.connectMedia)
95
+ return undefined;
96
+ const controller = new SpaceVoiceController({ space: this.config.space, epoch: this.config.epoch, hostDevice: this.config.identity.device, contentKey: Buffer.from(this.config.content_key, 'base64url'),
97
+ policy: () => this.config.voice_policy ?? 'owner', owner: () => this.config.owner_device, host: port,
98
+ member: device => this.config.members.some(member => member.device === device) && !(this.config.revoked_members ?? []).some(member => member.device === device),
99
+ media: { capabilities: () => sdk.capabilities(), reserve: (session, client, ttl) => sdk.reserveMedia(session, client, ttl), connect: session => sdk.connectMedia(session) },
100
+ notify: (to, body) => transport.stream(to, { v: 1, ...body }, 'voice-' + randomUUID()),
101
+ onAvailabilityChanged: () => { void this.service?.publishSnapshot().catch(() => { }); },
102
+ onError: () => this.host.options.onDiagnostic?.('space_voice_failed') });
103
+ this.host.setSpaceVoiceSink(controller.sink);
104
+ this.#voiceController = controller;
105
+ void controller.refreshCapability();
106
+ return controller;
107
+ }
108
+ #manage(work) { const run = this.#management.then(work); this.#management = run.catch(() => { }); return run; }
109
+ async #activate() { if (this.service)
110
+ return; this.service = await this.#service(); await this.service.open(); await this.host.notifications.bind({ id: 'space-relay', provider: 'space-relay', user_scope: this.host.options.userScope, generation: this.config.epoch, identity: this.config.space, status: 'ready' }); if (!this.host.notifications.configured || this.host.notifications.snapshot().primary_binding_id === 'space-relay')
111
+ await this.host.configureNotifications('space-relay'); }
112
+ async open() { if (this.#opened)
113
+ return; if (this.config.data_mode === 'existing' && this.config.v === 1) {
114
+ await this.#store.write({ ...this.config, v: 2 });
115
+ this.config.v = 2;
116
+ } this.#opened = true; await this.#keys.open(); if (this.config.pending_revoke) {
117
+ await this.#manage(() => this.#completeRevoke()).catch(() => this.host.options.onDiagnostic?.('space_revocation_pending'));
118
+ }
119
+ else
120
+ await this.#activate(); if (this.config.pending_pairing)
121
+ await this.#manage(() => this.#completePairing()).catch(() => this.host.options.onDiagnostic?.('space_pairing_pending')); this.#retry = setInterval(() => { /* Throttled inside: re-probes relay media at most every 30 s while unavailable. */ void this.#voiceController?.refreshIfUnavailable(); void this.#manage(async () => { if (this.config.pending_revoke)
122
+ await this.#completeRevoke(); if (this.config.pending_pairing)
123
+ await this.#completePairing(); if (!this.service)
124
+ await this.#activate(); await this.service.dispatchNotifications(); await this.service.flush(); await this.#deliverKeys(); }).catch(() => this.host.options.onDiagnostic?.('space_relay_pending')); }, 5000); this.#retry.unref(); await this.#deliverKeys().catch(() => this.host.options.onDiagnostic?.('space_key_delivery_pending')); this.#admin = await startSpaceAdminSocket(this, adminSocketPath(this.path), code => this.host.options.onDiagnostic?.(code)); }
125
+ modelsStatus() { return this.models.view(); }
126
+ async configureModels(params, opId) { const result = await this.models.configure(params, opId); this.host.connectionChanged(); return result; }
127
+ status() { return { mode: 'host', space: this.config.space, epoch: this.config.epoch, clients: this.config.members.map(member => member.device), relay_url: this.config.relay_url, pairing_pending: !!this.config.pending_pairing, revocation_pending: !!this.config.pending_revoke }; }
128
+ /**
129
+ * Relay transport, TLS and DNS failures surface as raw `fetch failed`/`TypeError` text.
130
+ * Only closed snake_case codes may cross to a client, so anything else becomes a stable code.
131
+ */
132
+ async #relay(call) {
133
+ try {
134
+ return await call();
135
+ }
136
+ catch (error) {
137
+ if (error instanceof z.ZodError)
138
+ throw Object.assign(Error('relay_response_invalid'), { cause: error });
139
+ if (error instanceof Error && !/^[a-z_]{1,64}$/u.test(error.message))
140
+ throw Object.assign(Error('relay_unreachable'), { cause: error });
141
+ throw error;
142
+ }
143
+ }
144
+ async #pendingPairings() { return z.array(member.extend({ id: z.string(), space: z.string(), expiresAt: z.number() })).parse(await this.#relay(() => this.#client.pendingPairings())); }
145
+ async invitation() { return { ...await this.#relay(() => this.#client.createInvitation()), space: this.config.space, host: this.config.identity.device, hostSigningPublicKey: this.config.identity.signingPublicKey, relay: this.config.relay_url, business_versions: [1] }; }
146
+ async pairings() { const pending = await this.#pendingPairings(); return pending.map(row => ({ ...row, fingerprint: this.sdk.crypto.deviceFingerprint(row.signingPublicKey, row.encryptionPublicKey) })); }
147
+ async confirmPairing(id, fingerprint) { return this.#manage(async () => { if (this.config.pending_revoke)
148
+ throw Error('revocation_pending'); if (this.config.pending_pairing) {
149
+ if (this.config.pending_pairing.request_id !== id || this.config.pending_pairing.fingerprint !== fingerprint)
150
+ throw Error('pairing_pending');
151
+ }
152
+ else {
153
+ const pending = await this.#pendingPairings(), request = pending.find(row => row.id === id);
154
+ if (!request || request.expiresAt <= Date.now())
155
+ throw Error('pairing_request_expired');
156
+ if (request.space !== this.config.space || this.sdk.crypto.deviceFingerprint(request.signingPublicKey, request.encryptionPublicKey) !== fingerprint)
157
+ throw Error('pairing_fingerprint_mismatch');
158
+ this.config.pending_pairing = { request_id: id, op_id: randomUUID(), member: member.parse(request), fingerprint };
159
+ await this.#store.write(this.config);
160
+ } return this.#completePairing(); }); }
161
+ // Only a fresh Host promotes the first phone. After the owner is revoked, or on a Host that already has members but no owner, admin intents stay unassigned until the operator clears the pairing.
162
+ async #completePairing() { const pending = this.config.pending_pairing; if (!pending)
163
+ return; const value = member.parse(await this.#client.confirmPairing(pending.request_id, pending.op_id)); if (value.device !== pending.member.device || canonicalJson(value.signingPublicKey) !== canonicalJson(pending.member.signingPublicKey) || canonicalJson(value.encryptionPublicKey) !== canonicalJson(pending.member.encryptionPublicKey) || this.sdk.crypto.deviceFingerprint(value.signingPublicKey, value.encryptionPublicKey) !== pending.fingerprint)
164
+ throw Error('pairing_key_mismatch'); const promote = !this.config.owner_device && this.config.members.length === 0; if (!this.config.members.some(row => row.device === value.device))
165
+ this.config.members.push(value); if (promote)
166
+ this.config.owner_device = value.device; delete this.config.pending_pairing; await this.#store.write(this.config); await this.#restart(); await this.#keys.deliver(this.config.epoch, value.device); return { device: value.device }; }
167
+ async revoke(device) { return this.#manage(async () => { if (this.config.pending_revoke) {
168
+ if (this.config.pending_revoke.device !== device)
169
+ throw Error('revocation_pending');
170
+ }
171
+ else {
172
+ if (this.config.pending_pairing)
173
+ throw Error('pairing_pending');
174
+ if (!this.config.members.some(row => row.device === device))
175
+ throw Error('client_not_paired');
176
+ this.config.pending_revoke = { device, op_id: randomUUID(), new_content_key: randomBytes(32).toString('base64url') };
177
+ await this.#store.write(this.config);
178
+ await this.service?.close('epoch_rotated');
179
+ this.service = undefined;
180
+ } await this.#completeRevoke(); return this.status(); }); }
181
+ async #completeRevoke() {
182
+ const pending = this.config.pending_revoke;
183
+ if (!pending)
184
+ return;
185
+ const value = z.object({ epoch: z.number().int().positive() }).parse(await this.#client.revokeDevice(pending.device, pending.op_id)); // The relay rotates by exactly one epoch per revocation (a replayed receipt repeats that epoch). Any other value is refused and the revocation stays pending.
186
+ if (value.epoch !== this.config.epoch + 1)
187
+ throw Error('invalid_rotation_epoch');
188
+ this.config.revoked_members = [...(this.config.revoked_members ?? []), ...this.config.members.filter(row => row.device === pending.device)];
189
+ this.config.members = this.config.members.filter(row => row.device !== pending.device);
190
+ if (this.config.owner_device === pending.device)
191
+ delete this.config.owner_device;
192
+ this.config.epoch = value.epoch;
193
+ this.config.content_key = pending.new_content_key;
194
+ delete this.config.pending_revoke;
195
+ await this.#store.write(this.config);
196
+ await this.#restart();
197
+ await this.#deliverKeys();
198
+ }
199
+ async #restart() { await this.service?.close(); this.#client = client(this.config, this.sdk); this.service = undefined; await this.#activate(); }
200
+ async #createKey(epoch, device) { const recipient = this.config.members.find(row => row.device === device); if (!recipient || epoch !== this.config.epoch)
201
+ throw Error('key_recipient_not_paired'); const wrapped = await this.sdk.crypto.wrapContentKey({ v: 1, space: this.config.space, epoch, recipient: recipient.device, key: this.config.content_key }, recipient.encryptionPublicKey); const id = 'key-' + createHash('sha256').update(JSON.stringify([epoch, recipient.device])).digest('hex'); const envelope = await this.sdk.crypto.signEnvelope({ v: 1, space: this.config.space, id, from: this.config.identity.device, to: recipient.device, chan: 'mailbox', epoch, expiresAt: null, body: Buffer.from(wrapped).toString('base64') }, this.config.identity.signingPrivateKey); return { ...envelope }; }
202
+ async #deliverKeys() { if (this.config.pending_revoke)
203
+ return; for (const member of this.config.members)
204
+ await this.#keys.deliver(this.config.epoch, member.device); }
205
+ async close() { this.#opened = false; await this.#admin?.close(); this.#admin = undefined; if (this.#retry)
206
+ clearInterval(this.#retry); await this.#management; await this.service?.close(); }
207
+ }
208
+ export async function loadSpaceHostController(host, path, environment = process.env) { const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW); let config; try {
209
+ const stat = await file.stat();
210
+ if (stat.size > 1024 * 1024)
211
+ throw Error('space_config_capacity');
212
+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
213
+ throw Error('space_config_permissions');
214
+ config = hostSpaceConfigSchema.parse(JSON.parse(await file.readFile('utf8')));
215
+ }
216
+ finally {
217
+ await file.close();
218
+ } ; if (config.personal_path !== host.path)
219
+ throw Error('space_personal_path_mismatch'); const sdk = await modules(); if (sdk.crypto.spaceId(config.identity.signingPublicKey) !== config.space)
220
+ throw Error('space_identity_mismatch'); return new SpaceHostController(path, config, host, sdk, environment); }
221
+ export function readHostSpaceConfig(path) { const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); try {
222
+ const stat = fstatSync(fd);
223
+ if (stat.size > 1024 * 1024)
224
+ throw Error('space_config_capacity');
225
+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
226
+ throw Error('space_config_permissions');
227
+ return hostSpaceConfigSchema.parse(JSON.parse(readFileSync(fd, 'utf8')));
228
+ }
229
+ finally {
230
+ closeSync(fd);
231
+ } }
232
+ export function scopeHostSpaceSettings(settings, config) { if (config.data_mode === 'existing') {
233
+ if (config.personal_path !== resolve(settings.blackboard_path.replace(/^~(?=\/)/u, homedir())) + '.personal.json')
234
+ throw Error('space_existing_data_mismatch');
235
+ return settings;
236
+ } return { ...settings, blackboard_path: config.personal_path + '.blackboard.sqlite', blackboard_owner_id: config.space, knowledge_path: config.personal_path + '.knowledge.sqlite', memory_path: config.personal_path + '.legacy-memory.sqlite', memory_user_id: config.space, workspace_graph_path: config.personal_path + '.memory.sqlite', memory_connection: settings.memory_connection === 'disabled' ? 'disabled' : 'local', memory_url: '', memory_token: null }; }
237
+ export async function resumeHostSpaceRegistration(options) { const config = readHostSpaceConfig(options.configPath), sdk = await modules(); if (sdk.crypto.spaceId(config.identity.signingPublicKey) !== config.space)
238
+ throw Error('space_identity_mismatch'); const host = { device: config.identity.device, signingPublicKey: config.identity.signingPublicKey, encryptionPublicKey: config.identity.encryptionPublicKey }, proof = await sdk.crypto.signControl({ v: 1, purpose: 'space-create', space: config.space, host }, config.identity.signingPrivateKey), connection = client(config, sdk); try {
239
+ await connection.createSpace({ space: config.space, host, proof }, options.bootstrapToken);
240
+ }
241
+ catch (error) {
242
+ if (!(error instanceof Error) || error.message !== 'space_exists')
243
+ throw error;
244
+ await connection.login();
245
+ } return { space: config.space, configPath: options.configPath }; }
246
+ export { createExperienceHost } from "../experience/host.js";
247
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,12 @@
1
+ import { spaceSourceInputSchema } from '../memory-substrate/space-source-input.js';
2
+ /** The sender comes from authenticated transport, never from a client-supplied field. */
3
+ export async function applySpaceSourceInput(memory, scope, input) {
4
+ const result = spaceSourceInputSchema.safeParse(input);
5
+ if (!result.success)
6
+ throw Error('invalid_source_input');
7
+ const parsed = result.data;
8
+ if (!memory.receiveSpaceSourceInput)
9
+ throw Error('source_backend_unavailable');
10
+ return memory.receiveSpaceSourceInput(scope, parsed);
11
+ }
12
+ //# sourceMappingURL=context-input.js.map
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ const id = z.string().min(1).max(128);
3
+ export const intentSchema = z.object({ v: z.literal(1), type: z.literal('intent'), op_id: id, kind: z.enum(['life.mutate', 'snapshot.request', 'chat.send', 'chat.cancel', 'card.dismiss', 'mobile.result', 'push.register', 'push.unregister', 'source.input', 'settings.patch', 'secret.put', 'secret.clear', 'connector.feishu', 'device.revoke', 'approval.resolve', 'voice.start', 'voice.stop']), input: z.record(z.string(), z.unknown()), created_at: z.number().int().nonnegative(), expires_at: z.number().int().optional(), base_version: z.number().int().nonnegative().optional(), temp_id: id.optional(), depends_on: z.array(id).max(64).optional() });
4
+ export const approvalResolveSchema = z.object({ conversation_id: id, approval_id: id, approved: z.boolean(), scope: z.enum(['once', 'session']).optional() }).strict();
5
+ export const mobileActionSchema = z.discriminatedUnion('tool', [
6
+ z.object({ tool: z.literal('calendar.read'), args: z.object({ start: z.string().datetime(), end: z.string().datetime() }).strict() }),
7
+ z.object({ tool: z.literal('reminder.create'), args: z.object({ title: z.string().min(1).max(200), due: z.string().datetime() }).strict() }),
8
+ z.object({ tool: z.literal('camera.capture'), args: z.object({ prompt: z.string().max(500) }).strict() }),
9
+ ]);
10
+ //# sourceMappingURL=contracts.js.map