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
package/README.md CHANGED
@@ -26,6 +26,16 @@ novapersonal-server --env-file "$HOME/.nova-remote/server.env" pair wss://your-h
26
26
 
27
27
  Scan the one-use QR with Nova on iPhone. SSH needs a TTY (`ssh -t`); Ctrl+C cancels the invitation without stopping the service. No desktop session or local microphone is required for remote phone audio.
28
28
 
29
+ ## Space Host
30
+
31
+ The same service can be a Space Host for the Nova phone Client. Set `NOVA_SPACE_HOST_CONFIG` to a config created with `nova-space-host init`, start the service, then pair from a second interactive terminal:
32
+
33
+ ```sh
34
+ nova-space-host pair --config /private/new-space/config.json
35
+ ```
36
+
37
+ `nova-space-host` (also `novapersonal-server space ...`) provides `init`, `resume`, `status`, `pair`, `devices` and `revoke`. See the [Space guide](https://github.com/deepnovacore/NovaPersonalAgent/blob/main/docs/en/space-host-client.md#headless-host-linuxmacos).
38
+
29
39
  ## Upgrading
30
40
 
31
41
  Install or update with `npm install --global nova-personal-agent-server@latest`, or pin `nova-personal-agent-server@0.4.0`. Stop the service and back up its data before upgrading; installing a different version changes the executable, not the persisted data.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import {main} from '../src/command.mjs'
3
+ try { process.exitCode = await main(['space', ...process.argv.slice(2)]) }
4
+ catch { console.error('[runtime-diagnostic] command_failed'); process.exitCode = 2 }
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, mkdirSync } from 'node:fs';
3
+ import { resolve, join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { RelayServer } from './server.js';
6
+ import { MEDIA_DEFAULTS } from './media.js';
7
+ export function loadDeploymentConfig(path) {
8
+ const config = JSON.parse(readFileSync(path, 'utf8'));
9
+ if (!config || typeof config.dataDirectory !== 'string' || typeof config.bootstrapTokenFile !== 'string')
10
+ throw new Error('dataDirectory and bootstrapTokenFile are required');
11
+ if (config.tlsCertificateFile && !config.tlsKeyFile || config.tlsKeyFile && !config.tlsCertificateFile)
12
+ throw new Error('TLS certificate and key must be configured together');
13
+ process.umask(0o077);
14
+ const directory = resolve(config.dataDirectory);
15
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
16
+ const bootstrapToken = readFileSync(config.bootstrapTokenFile, 'utf8').trim();
17
+ if (bootstrapToken.length < 24)
18
+ throw new Error('bootstrap token must contain at least 24 characters');
19
+ return { securityPath: join(directory, 'security.sqlite'), mailboxPath: join(directory, 'mailbox.sqlite'), bootstrapToken,
20
+ port: config.port ?? 8080, ...(config.bind === undefined ? {} : { bind: config.bind }),
21
+ ...(config.publicUrl === undefined ? {} : { publicUrl: config.publicUrl }),
22
+ ...(config.externalTls === undefined ? {} : { externalTls: config.externalTls }),
23
+ ...(config.trustedProxyAddresses === undefined ? {} : { trustedProxyAddresses: config.trustedProxyAddresses }),
24
+ ...(config.maxControlOperationsPerSpace === undefined ? {} : { maxControlOperationsPerSpace: config.maxControlOperationsPerSpace }),
25
+ ...(config.tlsCertificateFile && config.tlsKeyFile ? { tls: { cert: readFileSync(config.tlsCertificateFile), key: readFileSync(config.tlsKeyFile) } } : {}),
26
+ ...(config.maxBodyBytes === undefined ? {} : { maxBodyBytes: config.maxBodyBytes }),
27
+ ...(config.maxResponseBytes === undefined ? {} : { maxResponseBytes: config.maxResponseBytes }),
28
+ ...(config.maxConnections === undefined ? {} : { maxConnections: config.maxConnections }),
29
+ ...(config.maxConnectionsPerIp === undefined ? {} : { maxConnectionsPerIp: config.maxConnectionsPerIp }),
30
+ ...(config.requestsPerMinute === undefined ? {} : { requestsPerMinute: config.requestsPerMinute }),
31
+ ...(config.bootstrapPerMinute === undefined ? {} : { bootstrapPerMinute: config.bootstrapPerMinute }),
32
+ ...(config.globalRequestsPerMinute === undefined ? {} : { globalRequestsPerMinute: config.globalRequestsPerMinute }),
33
+ ...(config.globalBootstrapPerMinute === undefined ? {} : { globalBootstrapPerMinute: config.globalBootstrapPerMinute }),
34
+ ...(config.maxRateSources === undefined ? {} : { maxRateSources: config.maxRateSources }),
35
+ ...(config.media === undefined ? {} : { media: mediaConfig(config.media) }) };
36
+ }
37
+ function mediaConfig(value) {
38
+ if (!value || typeof value !== 'object' || Array.isArray(value))
39
+ throw new Error('media must be an object');
40
+ const { clock: _clock, ...rest } = value;
41
+ if (rest.enabled !== undefined && typeof rest.enabled !== 'boolean')
42
+ throw new Error('media.enabled must be a boolean');
43
+ for (const [key, option] of Object.entries(rest)) {
44
+ if (key === 'enabled')
45
+ continue;
46
+ if (!(key in MEDIA_DEFAULTS))
47
+ throw new Error(`unknown media option: ${key}`);
48
+ if (typeof option !== 'number' || !Number.isFinite(option) || option <= 0)
49
+ throw new Error(`media.${key} must be a positive number`);
50
+ }
51
+ return rest;
52
+ }
53
+ export async function main(args = process.argv.slice(2)) {
54
+ if (args.length !== 2 || args[0] !== '--config' || !args[1])
55
+ throw new Error('Usage: nova-relay --config /path/to/deployment.json');
56
+ const server = new RelayServer(loadDeploymentConfig(args[1]));
57
+ const address = await server.listen();
58
+ process.stdout.write(`Relay listening at ${address}\n`);
59
+ let closing = false;
60
+ const close = () => {
61
+ if (closing)
62
+ return;
63
+ closing = true;
64
+ void server.close().catch(() => { process.exitCode = 1; });
65
+ };
66
+ process.once('SIGINT', close);
67
+ process.once('SIGTERM', close);
68
+ }
69
+ if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
70
+ void main().catch(error => { process.stderr.write(`${error instanceof Error ? error.message : 'relay startup failed'}\n`); process.exitCode = 1; });
71
+ }
@@ -0,0 +1,340 @@
1
+ import { WebSocket } from 'ws';
2
+ /** Binary frames held until the first onFrame subscriber: the relay's control queue plus some audio. */
3
+ const MEDIA_PENDING_FRAMES = 32;
4
+ export class RelayClientError extends Error {
5
+ code;
6
+ status;
7
+ constructor(code, status) {
8
+ super(code);
9
+ this.code = code;
10
+ this.status = status;
11
+ this.name = 'RelayClientError';
12
+ }
13
+ }
14
+ /** Outbound SDK shared by Host and Client. It never decrypts business content or executes a model. */
15
+ export class RelayClient {
16
+ options;
17
+ base;
18
+ session;
19
+ loggingIn;
20
+ synchronizing;
21
+ stopped = true;
22
+ socket;
23
+ timer;
24
+ polling;
25
+ generation = 0;
26
+ constructor(options) {
27
+ this.options = options;
28
+ this.base = new URL(options.url);
29
+ if (this.base.username || this.base.password || this.base.search || this.base.hash ||
30
+ (this.base.protocol !== 'https:' && !(this.base.protocol === 'http:' &&
31
+ ['127.0.0.1', 'localhost', '[::1]', '::1'].includes(this.base.hostname))))
32
+ throw new RelayClientError('tls_required', 0);
33
+ if (this.base.pathname !== '/' && this.base.pathname !== '')
34
+ throw new RelayClientError('origin_url_required', 0);
35
+ for (const name of ['requestTimeoutMs', 'pollIntervalMs', 'reconnectMinMs', 'reconnectMaxMs']) {
36
+ if (options[name] !== undefined && (!Number.isSafeInteger(options[name]) || options[name] <= 0))
37
+ throw new RelayClientError('invalid_options', 0);
38
+ }
39
+ }
40
+ async login() {
41
+ if (this.loggingIn)
42
+ return this.loggingIn;
43
+ this.loggingIn = (async () => {
44
+ const challenge = await this.request('POST', '/v1/auth/challenge', { space: this.options.space, device: this.options.device }, false);
45
+ if (challenge.space !== this.options.space || challenge.device !== this.options.device ||
46
+ !Number.isSafeInteger(challenge.epoch) || challenge.epoch < 1 || !Number.isSafeInteger(challenge.expiresAt) ||
47
+ challenge.expiresAt <= Date.now())
48
+ throw new RelayClientError('invalid_challenge', 0);
49
+ const proof = await this.options.signChallenge(challenge);
50
+ const session = await this.request('POST', '/v1/auth/session', { challengeId: challenge.id, proof }, false);
51
+ if (session.selected_version !== 1)
52
+ throw new RelayClientError('unsupported_business_version', 0);
53
+ this.session = session;
54
+ })();
55
+ try {
56
+ await this.loggingIn;
57
+ }
58
+ finally {
59
+ this.loggingIn = undefined;
60
+ }
61
+ }
62
+ async authorized() {
63
+ if (!this.session || this.session.expiresAt <= Date.now() + 5000)
64
+ await this.login();
65
+ return this.session.token;
66
+ }
67
+ async request(method, path, body, auth = true) {
68
+ const headers = { 'accept': 'application/json' };
69
+ if (body !== undefined)
70
+ headers['content-type'] = 'application/json';
71
+ if (auth)
72
+ headers.authorization = `Bearer ${await this.authorized()}`;
73
+ const response = await fetch(new URL(path, this.base), { method, headers,
74
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(this.options.requestTimeoutMs ?? 10000), redirect: 'error' });
75
+ const value = await response.json();
76
+ if (!response.ok) {
77
+ const code = value && typeof value === 'object' && 'error' in value ? String(value.error) : 'relay_error';
78
+ if (response.status === 401)
79
+ this.session = undefined;
80
+ throw new RelayClientError(code, response.status);
81
+ }
82
+ return value;
83
+ }
84
+ send(envelope) { return this.request('POST', '/v1/mailbox', envelope); }
85
+ read(options = {}) {
86
+ const query = new URLSearchParams();
87
+ if (options.after !== undefined)
88
+ query.set('after', String(options.after));
89
+ if (options.limit !== undefined)
90
+ query.set('limit', String(options.limit));
91
+ return this.request('GET', `/v1/mailbox?${query}`);
92
+ }
93
+ async acknowledge(cursor) {
94
+ return (await this.request('POST', '/v1/mailbox/ack', { cursor })).ackCursor;
95
+ }
96
+ status() { return this.request('GET', '/v1/mailbox/status'); }
97
+ async presence(device) {
98
+ return (await this.request('GET', `/v1/presence?device=${encodeURIComponent(device)}`)).online;
99
+ }
100
+ async stream(envelope) { await this.request('POST', '/v1/stream', envelope); }
101
+ /** Media capability hint; null when the relay has no media route (older or media disabled). It never weakens crypto. */
102
+ async capabilities() {
103
+ try {
104
+ const value = await this.request('GET', '/v1/capabilities');
105
+ return { media: value.media && value.media.v === 1 && Array.isArray(value.media.codecs) ? value.media : null };
106
+ }
107
+ catch (error) {
108
+ if (error instanceof RelayClientError && error.status === 404)
109
+ return { media: null };
110
+ throw error;
111
+ }
112
+ }
113
+ /** Host only: reserve a media session for one Client device. */
114
+ reserveMedia(session, client, ttlMs) {
115
+ return this.request('POST', '/v1/media/sessions', { session, client, ...(ttlMs === undefined ? {} : { ttlMs }) });
116
+ }
117
+ /** Join a reserved media session. The bearer token is renewed in-band before it expires. */
118
+ async connectMedia(session) {
119
+ const token = await this.authorized();
120
+ const url = new URL('/v1/media', this.base);
121
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
122
+ const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-nova-media-session': session }, maxPayload: 8192,
123
+ handshakeTimeout: this.options.requestTimeoutMs ?? 10000, followRedirects: false, perMessageDeflate: false });
124
+ // One persistent handler from socket creation: a binary frame in the same chunk as `ready`
125
+ // (or before the first onFrame subscriber) is buffered, never lost.
126
+ const frames = [], closes = [], pending = [];
127
+ let ready = false, failure;
128
+ const opened = new Promise((resolve, reject) => {
129
+ ws.on('message', (data, isBinary) => {
130
+ const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
131
+ if (!ready) {
132
+ try {
133
+ const v = JSON.parse(bytes.toString());
134
+ if (!isBinary && v.type === 'ready') {
135
+ ready = true;
136
+ resolve();
137
+ return;
138
+ }
139
+ }
140
+ catch { /* rejected below */ }
141
+ reject(new RelayClientError('media_rejected', 0));
142
+ ws.terminate();
143
+ return;
144
+ }
145
+ if (!isBinary)
146
+ return;
147
+ const frame = new Uint8Array(bytes);
148
+ if (failure)
149
+ return;
150
+ if (frames.length) {
151
+ for (const f of frames)
152
+ f(frame);
153
+ return;
154
+ }
155
+ // Never evict silently (a dropped frame may be the peer's sealed ready): fail the leg explicitly.
156
+ if (pending.length >= MEDIA_PENDING_FRAMES) {
157
+ failure = 'media_overflow';
158
+ pending.length = 0;
159
+ ws.close(1008, failure);
160
+ return;
161
+ }
162
+ pending.push(frame);
163
+ });
164
+ ws.once('close', (code, reason) => reject(new RelayClientError(reason.toString() || 'media_rejected', code)));
165
+ ws.once('error', reject);
166
+ });
167
+ await opened;
168
+ let renewal, closed = false;
169
+ const schedule = () => {
170
+ if (closed)
171
+ return;
172
+ const expiresAt = this.session?.expiresAt ?? Date.now();
173
+ renewal = setTimeout(() => {
174
+ renewal = undefined;
175
+ void (async () => {
176
+ try {
177
+ await this.login();
178
+ // The socket may have closed while the login was in flight: no renew, no new timer.
179
+ if (closed || ws.readyState !== WebSocket.OPEN)
180
+ return;
181
+ ws.send(JSON.stringify({ type: 'renew', token: this.session.token }));
182
+ schedule();
183
+ }
184
+ catch {
185
+ if (!closed)
186
+ ws.close(1000, 'renewal_failed');
187
+ }
188
+ })();
189
+ }, Math.max(1000, expiresAt - Date.now() - 60_000));
190
+ renewal.unref?.();
191
+ };
192
+ const stop = () => { closed = true; if (renewal)
193
+ clearTimeout(renewal); renewal = undefined; };
194
+ schedule();
195
+ ws.on('close', (_code, reason) => { stop(); for (const c of closes)
196
+ c(failure ?? (reason.toString() || 'closed')); });
197
+ ws.on('error', () => ws.terminate());
198
+ return {
199
+ send: frame => new Promise((resolve, reject) => { if (ws.readyState !== WebSocket.OPEN) {
200
+ reject(new RelayClientError('media_closed', 0));
201
+ return;
202
+ } ws.send(frame, { binary: true }, e => e ? reject(e) : resolve()); }),
203
+ onFrame: listener => { frames.push(listener); for (const f of pending.splice(0))
204
+ listener(f); },
205
+ onClose: listener => { closes.push(listener); },
206
+ /** Pending renewal timer, for tests. */
207
+ get renewalPending() { return renewal !== undefined; },
208
+ close: () => { stop(); ws.close(1000, 'closed'); },
209
+ };
210
+ }
211
+ createInvitation(options = {}) { return this.request('POST', '/v1/pairing/invitations', options); }
212
+ pendingPairings() { return this.request('GET', '/v1/pairing/requests'); }
213
+ confirmPairing(requestId, opId) { return this.request('POST', '/v1/pairing/confirm', { requestId, opId }); }
214
+ devices() { return this.request('GET', '/v1/devices'); }
215
+ async revokeDevice(device, opId) {
216
+ try {
217
+ return await this.request('POST', '/v1/devices/revoke', { device, opId });
218
+ }
219
+ finally {
220
+ this.session = undefined;
221
+ }
222
+ }
223
+ requestPairing(body) { return this.request('POST', '/v1/pairing/requests', body, false); }
224
+ /** Bootstrap is an operator action. This method never persists the deployment secret. */
225
+ async createSpace(body, bootstrapToken) {
226
+ const response = await fetch(new URL('/v1/spaces', this.base), { method: 'POST', headers: { 'content-type': 'application/json',
227
+ 'x-relay-bootstrap-token': bootstrapToken }, body: JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(this.options.requestTimeoutMs ?? 10000) });
228
+ const value = await response.json();
229
+ if (!response.ok)
230
+ throw new RelayClientError(value && typeof value === 'object' && 'error' in value ? String(value.error) : 'relay_error', response.status);
231
+ return value;
232
+ }
233
+ /** Pulls from the durable cursor; never advances ACK before durable endpoint handling succeeds. */
234
+ async synchronize(subscription) {
235
+ if (this.synchronizing)
236
+ return this.synchronizing;
237
+ this.synchronizing = (async () => {
238
+ let after = await subscription.loadCursor?.();
239
+ for (;;) {
240
+ const page = await this.read(after === undefined ? {} : { after });
241
+ for (const message of page.messages)
242
+ await subscription.onMailbox(message.envelope, message.seq);
243
+ // `after` is always durable: loadCursor must return the last successfully saved cursor, and inside this loop it
244
+ // only advances after a save resolved. An idle poll returns an empty page at that cursor and needs neither a
245
+ // rewrite nor an ACK. A moved cursor (messages, or skipped expired rows) is saved first, so a failed save throws
246
+ // before any ACK. An ACK lost after a successful save is repaired from the ACK cursor the relay reports per page.
247
+ if (page.nextCursor !== after)
248
+ await subscription.saveCursor?.(page.nextCursor);
249
+ if (page.nextCursor > page.ackCursor)
250
+ await this.acknowledge(page.nextCursor);
251
+ after = page.nextCursor;
252
+ if (!page.hasMore)
253
+ return;
254
+ }
255
+ })();
256
+ try {
257
+ await this.synchronizing;
258
+ }
259
+ finally {
260
+ this.synchronizing = undefined;
261
+ }
262
+ }
263
+ /** Persistent outbound connection with bounded reconnect delay and durable HTTP catch-up. */
264
+ start(subscription) {
265
+ if (!this.stopped)
266
+ throw new RelayClientError('already_started', 0);
267
+ this.stopped = false;
268
+ const generation = ++this.generation;
269
+ let delay = this.options.reconnectMinMs ?? 250;
270
+ const report = (error) => { try {
271
+ subscription.onError?.(error);
272
+ }
273
+ catch { /* Consumer reporting cannot break retries. */ } };
274
+ const notify = (online) => { try {
275
+ subscription.onConnection?.(online);
276
+ }
277
+ catch (error) {
278
+ report(error);
279
+ } };
280
+ const sync = () => { void this.synchronize(subscription).catch(report); };
281
+ const connect = async () => {
282
+ if (this.stopped || generation !== this.generation)
283
+ return;
284
+ try {
285
+ const token = await this.authorized();
286
+ if (this.stopped || generation !== this.generation)
287
+ return;
288
+ const url = new URL('/v1/live', this.base);
289
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
290
+ const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}` }, maxPayload: 512 * 1024 + 256,
291
+ handshakeTimeout: this.options.requestTimeoutMs ?? 10000, followRedirects: false, perMessageDeflate: false });
292
+ this.socket = ws;
293
+ const retry = () => {
294
+ if (this.stopped || generation !== this.generation)
295
+ return;
296
+ notify(false);
297
+ this.timer = setTimeout(() => { void connect(); }, delay);
298
+ delay = Math.min(delay * 2, this.options.reconnectMaxMs ?? 30000);
299
+ };
300
+ ws.on('message', data => {
301
+ try {
302
+ const frame = JSON.parse(data.toString());
303
+ if (frame.type === 'ready') {
304
+ delay = this.options.reconnectMinMs ?? 250;
305
+ notify(true);
306
+ sync();
307
+ }
308
+ else if (frame.type === 'stream' && frame.envelope)
309
+ subscription.onStream?.(frame.envelope);
310
+ }
311
+ catch (error) {
312
+ report(error);
313
+ }
314
+ });
315
+ ws.on('error', report);
316
+ ws.once('close', retry);
317
+ }
318
+ catch (error) {
319
+ report(error);
320
+ if (!this.stopped && generation === this.generation) {
321
+ this.timer = setTimeout(() => { void connect(); }, delay);
322
+ delay = Math.min(delay * 2, this.options.reconnectMaxMs ?? 30000);
323
+ }
324
+ }
325
+ };
326
+ this.polling = setInterval(sync, this.options.pollIntervalMs ?? 1000);
327
+ void connect();
328
+ return () => this.stop();
329
+ }
330
+ stop() {
331
+ this.stopped = true;
332
+ ++this.generation;
333
+ if (this.timer)
334
+ clearTimeout(this.timer);
335
+ if (this.polling)
336
+ clearInterval(this.polling);
337
+ this.socket?.terminate();
338
+ this.socket = undefined;
339
+ }
340
+ }
@@ -0,0 +1,167 @@
1
+ /** Endpoint-only JOSE helpers. Relay uses public signature verification only. */
2
+ import { createPublicKey, createPrivateKey, generateKeyPairSync, randomBytes, randomUUID, verify, createHash } from 'node:crypto';
3
+ import { openSync, closeSync, writeFileSync, readFileSync, fsyncSync, renameSync, chmodSync, unlinkSync } from 'node:fs';
4
+ import { CompactEncrypt, compactDecrypt, CompactSign, importJWK } from 'jose';
5
+ import { assertId, RelayError } from './protocol.js';
6
+ export function generateContentKey() { return randomBytes(32); }
7
+ export async function generateDeviceIdentity() {
8
+ const signing = generateKeyPairSync('ed25519');
9
+ const agreement = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
10
+ return { device: randomUUID(), signingPublicKey: signing.publicKey.export({ format: 'jwk' }), signingPrivateKey: signing.privateKey.export({ format: 'jwk' }),
11
+ encryptionPublicKey: agreement.publicKey.export({ format: 'jwk' }), encryptionPrivateKey: agreement.privateKey.export({ format: 'jwk' }) };
12
+ }
13
+ function base64url(value, length) {
14
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value) || Buffer.from(value, 'base64url').length !== length || Buffer.from(value, 'base64url').toString('base64url') !== value)
15
+ throw new RelayError('invalid_public_key');
16
+ }
17
+ export function validatePublicKey(key, kind) {
18
+ if (!key || typeof key !== 'object' || key.d !== undefined)
19
+ throw new RelayError('invalid_public_key');
20
+ if (kind === 'signing') {
21
+ if (key.kty !== 'OKP' || key.crv !== 'Ed25519')
22
+ throw new RelayError('invalid_public_key');
23
+ base64url(key.x, 32);
24
+ }
25
+ else {
26
+ if (key.kty !== 'EC' || key.crv !== 'P-256')
27
+ throw new RelayError('invalid_public_key');
28
+ base64url(key.x, 32);
29
+ base64url(key.y, 32);
30
+ }
31
+ try {
32
+ createPublicKey({ key: key, format: 'jwk' });
33
+ }
34
+ catch {
35
+ throw new RelayError('invalid_public_key');
36
+ }
37
+ }
38
+ export function spaceId(key) {
39
+ validatePublicKey(key, 'signing');
40
+ return createHash('sha256').update(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x: key.x })).digest('base64url');
41
+ }
42
+ export function deviceFingerprint(signing, encryption) {
43
+ validatePublicKey(signing, 'signing');
44
+ validatePublicKey(encryption, 'encryption');
45
+ return createHash('sha256').update(JSON.stringify({ signing: { crv: 'Ed25519', kty: 'OKP', x: signing.x }, encryption: { crv: 'P-256', kty: 'EC', x: encryption.x, y: encryption.y } })).digest('base64url');
46
+ }
47
+ export async function signControl(payload, privateKey) {
48
+ return new CompactSign(Buffer.from(JSON.stringify(payload))).setProtectedHeader({ alg: 'EdDSA', typ: 'nova-control+jws' }).sign(await importJWK(privateKey, 'EdDSA'));
49
+ }
50
+ function verifyJws(compact, key, typ) {
51
+ try {
52
+ validatePublicKey(key, 'signing');
53
+ if (typeof compact !== 'string' || compact.length > 262_144)
54
+ throw 0;
55
+ const parts = compact.split('.');
56
+ if (parts.length !== 3 || parts.some(p => !/^[A-Za-z0-9_-]+$/.test(p)))
57
+ throw 0;
58
+ const [header, payload, signature] = parts;
59
+ for (const p of parts)
60
+ if (Buffer.from(p, 'base64url').toString('base64url') !== p)
61
+ throw 0;
62
+ const parsed = JSON.parse(Buffer.from(header, 'base64url').toString());
63
+ if (parsed.alg !== 'EdDSA' || parsed.typ !== typ || Object.keys(parsed).some(k => !['alg', 'typ'].includes(k)))
64
+ throw 0;
65
+ if (!verify(null, Buffer.from(`${header}.${payload}`), createPublicKey({ key: key, format: 'jwk' }), Buffer.from(signature, 'base64url')))
66
+ throw 0;
67
+ return Buffer.from(payload, 'base64url');
68
+ }
69
+ catch {
70
+ throw new RelayError('invalid_signature');
71
+ }
72
+ }
73
+ export function verifyControl(proof, key) {
74
+ try {
75
+ return JSON.parse(verifyJws(proof, key, 'nova-control+jws').toString());
76
+ }
77
+ catch {
78
+ throw new RelayError('invalid_signature');
79
+ }
80
+ }
81
+ export function envelopePayload(e) {
82
+ return JSON.stringify({ v: e.v, space: e.space, id: e.id, from: e.from, to: e.to, chan: e.chan, epoch: e.epoch, expiresAt: e.expiresAt, body: e.body });
83
+ }
84
+ export async function signEnvelope(e, privateKey) {
85
+ const compact = await new CompactSign(Buffer.from(envelopePayload(e))).setProtectedHeader({ alg: 'EdDSA', typ: 'nova-envelope+jws' }).sign(await importJWK(privateKey, 'EdDSA'));
86
+ return { ...e, sig: Buffer.from(compact).toString('base64') };
87
+ }
88
+ export function verifyEnvelope(e, key) {
89
+ try {
90
+ if (typeof e.sig !== 'string' || Buffer.from(e.sig, 'base64').toString('base64') !== e.sig)
91
+ throw 0;
92
+ if (verifyJws(Buffer.from(e.sig, 'base64').toString(), key, 'nova-envelope+jws').toString() !== envelopePayload(e))
93
+ throw 0;
94
+ }
95
+ catch {
96
+ throw new RelayError('invalid_signature');
97
+ }
98
+ }
99
+ function contentKey(key) { if (!(key instanceof Uint8Array) || key.length !== 32)
100
+ throw new RelayError('invalid_content_key'); }
101
+ export async function encryptBody(value, key) {
102
+ contentKey(key);
103
+ const jwe = await new CompactEncrypt(Buffer.from(JSON.stringify(value))).setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }).encrypt(key);
104
+ return Buffer.from(jwe).toString('base64');
105
+ }
106
+ export async function decryptBody(body, key) {
107
+ contentKey(key);
108
+ if (Buffer.from(body, 'base64').toString('base64') !== body)
109
+ throw new RelayError('invalid_encoding');
110
+ const result = await compactDecrypt(Buffer.from(body, 'base64').toString(), key, { keyManagementAlgorithms: ['dir'], contentEncryptionAlgorithms: ['A256GCM'] });
111
+ return JSON.parse(Buffer.from(result.plaintext).toString());
112
+ }
113
+ function validateDelivery(value) {
114
+ try {
115
+ if (value.v !== 1 || !Number.isSafeInteger(value.epoch) || value.epoch < 1)
116
+ throw 0;
117
+ assertId(value.space);
118
+ assertId(value.recipient);
119
+ base64url(value.key, 32);
120
+ }
121
+ catch {
122
+ throw new RelayError('invalid_key_delivery');
123
+ }
124
+ }
125
+ export async function wrapContentKey(payload, publicKey) {
126
+ validateDelivery(payload);
127
+ validatePublicKey(publicKey, 'encryption');
128
+ return new CompactEncrypt(Buffer.from(JSON.stringify(payload)))
129
+ .setProtectedHeader({ alg: 'ECDH-ES+A256KW', enc: 'A256GCM' }).encrypt(await importJWK(publicKey, 'ECDH-ES+A256KW'));
130
+ }
131
+ export async function unwrapContentKey(jwe, privateKey) {
132
+ const result = await compactDecrypt(jwe, await importJWK(privateKey, 'ECDH-ES+A256KW'), { keyManagementAlgorithms: ['ECDH-ES+A256KW'], contentEncryptionAlgorithms: ['A256GCM'] });
133
+ const value = JSON.parse(Buffer.from(result.plaintext).toString());
134
+ validateDelivery(value);
135
+ return value;
136
+ }
137
+ function validateIdentity(value) {
138
+ if (!value)
139
+ throw new RelayError('invalid_identity');
140
+ assertId(value.device);
141
+ validatePublicKey(value.signingPublicKey, 'signing');
142
+ validatePublicKey(value.encryptionPublicKey, 'encryption');
143
+ for (const [publicKey, privateKey] of [[value.signingPublicKey, value.signingPrivateKey], [value.encryptionPublicKey, value.encryptionPrivateKey]]) {
144
+ const derived = createPublicKey(createPrivateKey({ key: privateKey, format: 'jwk' })).export({ format: 'jwk' });
145
+ if (derived.x !== publicKey.x || derived.y !== publicKey.y)
146
+ throw new RelayError('invalid_identity');
147
+ }
148
+ }
149
+ export function saveDeviceIdentity(path, identity) {
150
+ validateIdentity(identity);
151
+ const temporary = `${path}.${randomUUID()}.tmp`;
152
+ const fd = openSync(temporary, 'wx', 0o600);
153
+ try {
154
+ writeFileSync(fd, JSON.stringify(identity));
155
+ fsyncSync(fd);
156
+ }
157
+ catch (error) {
158
+ unlinkSync(temporary);
159
+ throw error;
160
+ }
161
+ finally {
162
+ closeSync(fd);
163
+ }
164
+ renameSync(temporary, path);
165
+ chmodSync(path, 0o600);
166
+ }
167
+ export function loadDeviceIdentity(path) { const value = JSON.parse(readFileSync(path, 'utf8')); validateIdentity(value); return value; }