nova-personal-agent-server 0.4.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +12 -2
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +13 -6
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -0,0 +1,115 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ export const MAX_FINETUNE_HISTORY_TURNS = 6;
5
+ const LANGS = new Set(['zh', 'en']);
6
+ const CATEGORIES = new Set(['knowledge', 'emotion', 'persona', 'casual']);
7
+ const MEMORY_CATEGORIES = new Set(['knowledge', 'emotion', 'persona']);
8
+ const SYSTEM = {
9
+ memory: {
10
+ zh: '你是VoiceMem,一个有记忆的个人AI伴侣。用下面检索到的记忆和用户画像自然地回应,不要把记忆原样念给用户。',
11
+ en: 'You are VoiceMem, a personal AI companion with memory. Reply naturally using the retrieved memories and user profile below; do not recite them verbatim to the user.',
12
+ },
13
+ casual: {
14
+ zh: '你是VoiceMem,一个聪明有温度的AI伴侣。基于当下对话自然地回应。',
15
+ en: 'You are VoiceMem, a warm and thoughtful AI companion. Reply naturally based on the current conversation.',
16
+ },
17
+ };
18
+ export function systemPrompt(category, lang) {
19
+ if (!CATEGORIES.has(category) || !LANGS.has(lang))
20
+ throw new Error('Invalid fine-tune category/lang');
21
+ return SYSTEM[MEMORY_CATEGORIES.has(category) ? 'memory' : 'casual'][lang];
22
+ }
23
+ function record(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
24
+ function meta(value, row) {
25
+ // Upstream defaults a missing `meta` to {}, then still requires lang/category.
26
+ const raw = value ?? {};
27
+ if (!record(raw))
28
+ throw new Error(`FineTune row ${row} meta must be an object`);
29
+ if (!LANGS.has(raw.lang))
30
+ throw new Error(`FineTune row ${row} has invalid lang`);
31
+ if (!CATEGORIES.has(raw.category))
32
+ throw new Error(`FineTune row ${row} has invalid category`);
33
+ const session = raw.session_id, turn = raw.turn;
34
+ const sessionId = session === undefined ? undefined : (typeof session === 'string' && session.trim() ? session : invalidMeta(row, 'session_id'));
35
+ const turnNumber = turn === undefined ? undefined : (typeof turn === 'number' && Number.isSafeInteger(turn) && turn >= 1 ? turn : invalidMeta(row, 'turn'));
36
+ return { lang: raw.lang, category: raw.category, ...(sessionId === undefined ? {} : { sessionId }), ...(turnNumber === undefined ? {} : { turn: turnNumber }) };
37
+ }
38
+ function invalidMeta(row, field) { throw new Error(`FineTune row ${row} has invalid ${field}`); }
39
+ function messages(value, row, details) {
40
+ if (!Array.isArray(value) || !value.length)
41
+ throw new Error(`FineTune row ${row} messages must be a non-empty array`);
42
+ const parsed = value.map((item, index) => {
43
+ if (!record(item) || !['system', 'user', 'assistant'].includes(item.role) || typeof item.content !== 'string')
44
+ throw new Error(`FineTune row ${row} message ${index + 1} has invalid role or content`);
45
+ return { role: item.role, content: item.content };
46
+ });
47
+ if (parsed[0].role !== 'system')
48
+ throw new Error(`FineTune row ${row} first message must be system`);
49
+ if (parsed.at(-1).role !== 'assistant')
50
+ throw new Error(`FineTune row ${row} final message must be assistant`);
51
+ if (parsed.length % 2 !== 1)
52
+ throw new Error(`FineTune row ${row} system must be followed by user/assistant pairs`);
53
+ for (let index = 1; index < parsed.length; index++) {
54
+ const want = index % 2 === 1 ? 'user' : 'assistant';
55
+ if (parsed[index].role !== want)
56
+ throw new Error(`FineTune row ${row} message ${index + 1} must be ${want}`);
57
+ }
58
+ const historyTurns = (parsed.length - 3) / 2;
59
+ if (historyTurns > MAX_FINETUNE_HISTORY_TURNS)
60
+ throw new Error(`FineTune row ${row} history exceeds ${MAX_FINETUNE_HISTORY_TURNS} turns`);
61
+ if (parsed[0].content !== systemPrompt(details.category, details.lang))
62
+ throw new Error(`FineTune row ${row} system prompt does not match category/lang`);
63
+ return parsed;
64
+ }
65
+ /** Validates upstream JSONL before any future trainer or GPU job sees a row. */
66
+ export function parseFineTuneData(source) {
67
+ const examples = [];
68
+ for (const [index, raw] of source.split('\n').entries()) {
69
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
70
+ if (!line.trim())
71
+ continue;
72
+ let row;
73
+ try {
74
+ row = JSON.parse(line);
75
+ }
76
+ catch {
77
+ throw new Error(`FineTune JSONL line ${index + 1} is invalid`);
78
+ }
79
+ if (!record(row))
80
+ throw new Error(`FineTune JSONL line ${index + 1} must be an object`);
81
+ const details = meta(row.meta, index + 1), dialogue = messages(row.messages, index + 1, details);
82
+ examples.push({ messages: dialogue, meta: details, historyTurns: (dialogue.length - 3) / 2, prompt: dialogue.slice(0, -1), target: dialogue.at(-1), lastUser: dialogue.at(-2) });
83
+ }
84
+ return { examples };
85
+ }
86
+ export async function loadFineTuneData(path) { return parseFineTuneData(await readFile(path, 'utf8')); }
87
+ async function inspect() {
88
+ const args = process.argv.slice(2);
89
+ let path, inspectOnly = false;
90
+ for (let index = 0; index < args.length; index++) {
91
+ const arg = args[index];
92
+ if (arg === '--inspect')
93
+ inspectOnly = true;
94
+ else if (arg === '--data') {
95
+ path = args[++index];
96
+ if (!path)
97
+ throw new Error('Missing path after --data');
98
+ }
99
+ else
100
+ throw new Error(`Unknown argument ${arg}`);
101
+ }
102
+ if (!inspectOnly || !path)
103
+ throw new Error('Usage: finetune-data --data PATH --inspect');
104
+ const dataset = await loadFineTuneData(path);
105
+ const languages = { zh: 0, en: 0 }, categories = { knowledge: 0, emotion: 0, persona: 0, casual: 0 };
106
+ for (const example of dataset.examples) {
107
+ languages[example.meta.lang]++;
108
+ categories[example.meta.category]++;
109
+ }
110
+ const histories = dataset.examples.map(example => example.historyTurns);
111
+ console.log(JSON.stringify({ examples: dataset.examples.length, languages, categories, historyTurns: histories.length ? { min: Math.min(...histories), max: Math.max(...histories) } : null, sessions: dataset.examples.filter(example => example.meta.sessionId !== undefined).length, turns: dataset.examples.filter(example => example.meta.turn !== undefined).length }));
112
+ }
113
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))
114
+ void inspect().catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });
115
+ //# sourceMappingURL=finetune-data.js.map
@@ -0,0 +1,170 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { loadFineTuneData } from './finetune-data.js';
5
+ const BASE = 'Qwen/Qwen3.6-35B-A3B';
6
+ const TARGET_REGEX = '^(model\\.language_model(?=\\.).*\\.(shared_expert_gate|down_proj|out_proj|in_proj_a|in_proj_b|q_proj|in_proj_z|gate_proj|up_proj|in_proj_qkv|k_proj|v_proj|o_proj))$';
7
+ const TERMINATION_GRACE_MS = 5_000;
8
+ export async function planFineTune(options) {
9
+ const trainer = text(options.trainer, 'trainer'), model = text(options.model, 'model'), data = text(options.data, 'data'), output = text(options.output, 'output');
10
+ const rank = integer(options.rank ?? 32, 'rank'), alpha = integer(options.alpha ?? 64, 'alpha'), epochs = positive(options.epochs ?? 2, 'epochs');
11
+ const learningRate = positive(options.learningRate ?? 2e-4, 'learning rate'), maxLength = integer(options.maxLength ?? 2048, 'max length');
12
+ const targetRegex = options.targetRegex === undefined ? (model === BASE ? TARGET_REGEX : missingTargetRegex()) : text(options.targetRegex, 'target regex');
13
+ const dataset = await loadFineTuneData(data), warmupSteps = Math.max(1, pythonRound(dataset.examples.length * epochs / 16 * .03));
14
+ if (!dataset.examples.length)
15
+ throw new Error('Fine-tune dataset is empty');
16
+ const argv = [
17
+ 'sft', '--model', model, '--dataset', data, '--output_dir', output,
18
+ '--tuner_type', 'lora', '--lora_rank', String(rank), '--lora_alpha', String(alpha), '--lora_dropout', '0.05', '--lora_bias', 'none', '--target_regex', targetRegex,
19
+ ...((options.fourBit ?? true) ? ['--quant_bits', '4', '--quant_method', 'bnb'] : []),
20
+ '--torch_dtype', 'bfloat16', '--max_length', String(maxLength), '--loss_scale', 'last_round', '--num_train_epochs', String(epochs), '--learning_rate', String(learningRate),
21
+ '--lr_scheduler_type', 'cosine', '--warmup_steps', String(warmupSteps), '--per_device_train_batch_size', '8', '--gradient_accumulation_steps', '2', '--gradient_checkpointing', 'true',
22
+ '--weight_decay', '0.1', '--optim', 'adamw_torch_fused', '--seed', '42', '--split_dataset_ratio', '0.1',
23
+ ];
24
+ return { executable: trainer, argv, examples: dataset.examples.length, warmupSteps, lossScale: 'last_round' };
25
+ }
26
+ /** Runs only the reviewed command; no shell, output cleanup, GPU selection, or implicit checkpoint behavior. */
27
+ export async function runFineTune(command) {
28
+ if (process.platform === 'win32')
29
+ throw new Error('Fine-tune execution requires POSIX process-group supervision');
30
+ await new Promise((resolveRun, reject) => {
31
+ let settled = false;
32
+ let closeResult;
33
+ const child = spawn(command.executable, command.argv, { shell: false, stdio: 'inherit', detached: true }), groupId = child.pid;
34
+ let forcedKill, groupCheck;
35
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
36
+ const groupAlive = () => {
37
+ if (groupId === undefined)
38
+ return false;
39
+ try {
40
+ process.kill(-groupId, 0);
41
+ return true;
42
+ }
43
+ catch (error) {
44
+ if (error.code === 'ESRCH')
45
+ return false;
46
+ throw error;
47
+ }
48
+ };
49
+ const signalGroup = (signal) => {
50
+ if (groupId === undefined)
51
+ return;
52
+ try {
53
+ process.kill(-groupId, signal);
54
+ }
55
+ catch (error) {
56
+ if (error.code !== 'ESRCH')
57
+ throw error;
58
+ }
59
+ };
60
+ const finish = (callback) => {
61
+ if (!settled) {
62
+ settled = true;
63
+ for (const [signal, handler] of handlers)
64
+ process.off(signal, handler);
65
+ if (forcedKill !== undefined)
66
+ clearTimeout(forcedKill);
67
+ if (groupCheck !== undefined)
68
+ clearTimeout(groupCheck);
69
+ callback();
70
+ }
71
+ };
72
+ const settleClose = () => {
73
+ if (settled || closeResult === undefined)
74
+ return;
75
+ const result = closeResult;
76
+ try {
77
+ if (groupAlive()) {
78
+ groupCheck ??= setTimeout(() => { groupCheck = undefined; settleClose(); }, 25);
79
+ return;
80
+ }
81
+ }
82
+ catch (error) {
83
+ finish(() => reject(error));
84
+ return;
85
+ }
86
+ finish(() => {
87
+ if (result.signal)
88
+ reject(new Error(`Fine-tune trainer terminated by ${result.signal}`));
89
+ else if (result.code !== 0)
90
+ reject(new Error(`Fine-tune trainer exited with code ${result.code}`));
91
+ else
92
+ resolveRun();
93
+ });
94
+ };
95
+ const stop = (signal) => () => {
96
+ try {
97
+ signalGroup(signal);
98
+ forcedKill ??= setTimeout(() => { try {
99
+ if (groupAlive())
100
+ signalGroup('SIGKILL');
101
+ }
102
+ catch (error) {
103
+ finish(() => reject(error));
104
+ } }, TERMINATION_GRACE_MS);
105
+ }
106
+ catch (error) {
107
+ finish(() => reject(error));
108
+ }
109
+ };
110
+ const handlers = signals.map(signal => [signal, stop(signal)]);
111
+ for (const [signal, handler] of handlers)
112
+ process.on(signal, handler);
113
+ child.once('error', error => finish(() => reject(error)));
114
+ child.once('close', (code, signal) => { closeResult = { code, signal }; settleClose(); });
115
+ });
116
+ }
117
+ function text(value, label) {
118
+ if (typeof value !== 'string' || !value.trim() || value.includes('\0'))
119
+ throw new Error(`Invalid fine-tune ${label}`);
120
+ return value;
121
+ }
122
+ function integer(value, label) {
123
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
124
+ throw new Error(`Invalid fine-tune ${label}`);
125
+ return value;
126
+ }
127
+ function positive(value, label) {
128
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
129
+ throw new Error(`Invalid fine-tune ${label}`);
130
+ return value;
131
+ }
132
+ function pythonRound(value) {
133
+ const floor = Math.floor(value), fraction = value - floor;
134
+ return fraction < .5 ? floor : fraction > .5 ? floor + 1 : floor % 2 === 0 ? floor : floor + 1;
135
+ }
136
+ function missingTargetRegex() { throw new Error('A non-default model requires an explicit fine-tune target regex'); }
137
+ async function cli() {
138
+ const args = process.argv.slice(2), values = {}, allowed = new Set(['--trainer', '--model', '--data', '--output', '--rank', '--alpha', '--epochs', '--lr', '--max-len', '--target-regex']);
139
+ let run = false, fourBit = true;
140
+ for (let index = 0; index < args.length; index++) {
141
+ const arg = args[index];
142
+ if (arg === undefined)
143
+ break;
144
+ if (arg === '--run') {
145
+ run = true;
146
+ continue;
147
+ }
148
+ if (arg === '--no-4bit') {
149
+ fourBit = false;
150
+ continue;
151
+ }
152
+ if (!allowed.has(arg))
153
+ throw new Error(`Unknown argument ${arg}`);
154
+ const value = args[++index];
155
+ if (value === undefined)
156
+ throw new Error(`Missing value after ${arg}`);
157
+ values[arg] = value;
158
+ }
159
+ const command = await planFineTune({ trainer: values['--trainer'] ?? '', model: values['--model'] ?? '', data: values['--data'] ?? '', output: values['--output'] ?? '', fourBit,
160
+ ...(values['--rank'] === undefined ? {} : { rank: Number(values['--rank']) }), ...(values['--alpha'] === undefined ? {} : { alpha: Number(values['--alpha']) }),
161
+ ...(values['--epochs'] === undefined ? {} : { epochs: Number(values['--epochs']) }), ...(values['--lr'] === undefined ? {} : { learningRate: Number(values['--lr']) }),
162
+ ...(values['--max-len'] === undefined ? {} : { maxLength: Number(values['--max-len']) }), ...(values['--target-regex'] === undefined ? {} : { targetRegex: values['--target-regex'] }),
163
+ });
164
+ console.log(JSON.stringify({ ...command, mode: run ? 'run' : 'dry-run' }));
165
+ if (run)
166
+ await runFineTune(command);
167
+ }
168
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))
169
+ void cli().catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });
170
+ //# sourceMappingURL=finetune.js.map
@@ -0,0 +1,81 @@
1
+ // Nova SDK patch, Apache-2.0. This is a deliberately closed grammar, not a
2
+ // keyword classifier: the entire source must be an attributed standing claim.
3
+ export const REPLY_PREFERENCE_PROTOCOL = 'voicemem-0.0.1/grounded-reply-preferences-v1';
4
+ const dimensions = {
5
+ length: { brief: 'Prefers brief replies', detailed: 'Prefers detailed replies' },
6
+ directness: { direct: 'Prefers direct replies', indirect: 'Prefers indirect replies' },
7
+ };
8
+ const terms = new Map([
9
+ ['简洁', ['length', 'brief']], ['简短', ['length', 'brief']], ['精简', ['length', 'brief']],
10
+ ['详细', ['length', 'detailed']], ['详尽', ['length', 'detailed']],
11
+ ['直接', ['directness', 'direct']], ['委婉', ['directness', 'indirect']],
12
+ ['concise', ['length', 'brief']], ['brief', ['length', 'brief']], ['short', ['length', 'brief']],
13
+ ['detailed', ['length', 'detailed']], ['thorough', ['length', 'detailed']],
14
+ ['direct', ['directness', 'direct']], ['indirect', ['directness', 'indirect']],
15
+ ]);
16
+ export function groundedReplyPreferences(source) {
17
+ if (source.audioEvidence || (source.role ?? 'user') !== 'user') return [];
18
+ const text = source.text.trim();
19
+ // No arbitrary surrounding prose, quotations, negation, modality or third-party
20
+ // context is admitted. Optional tail must itself explicitly assert permanence.
21
+ const deniedZh = /^我(?:(?:一贯|一直|始终|通常))?(?:不喜欢|不偏好|不再喜欢|不再偏好)([\u4e00-\u9fff、和且及]+)的(?:回答|回复|答复)[。!.!]?$/u.exec(text);
22
+ const deniedEn = /^I (?:(?:always|consistently|generally) )?(?:do not|don't|no longer) (?:prefer|like) ([a-z ,]+) (?:answers|replies|responses)[.!]?$/iu.exec(text);
23
+ const polarity = deniedZh || deniedEn ? 'denied' : 'affirmed';
24
+ const zh = deniedZh ?? /^我(?:一贯|一直|始终|通常)(?:更)?(?:喜欢|偏好)([\u4e00-\u9fff、和且及]+)的(?:回答|回复|答复)(?:[,,](?:这是一项|这是我的)(?:长期沟通偏好|长期偏好))?[。!.!]?$/u.exec(text);
25
+ const en = deniedEn ?? /^I (?:always|consistently|generally) prefer ([a-z ,]+) (?:answers|replies|responses)(?:[,.] (?:this is a|this is my) (?:standing|long-term) (?:communication )?preference)?[.!]?$/iu.exec(text);
26
+ if (!zh && !en) return [];
27
+ const adjectives = zh ? zh[1].split(/[、和且及]/u).flatMap(part => {
28
+ // Chinese can concatenate adjectives without a conjunction. Consume every
29
+ // character; unknown material invalidates the whole assertion.
30
+ const result = [];
31
+ while (part) {
32
+ const term = [...terms.keys()].find(key => /[\u4e00-\u9fff]/u.test(key) && part.startsWith(key));
33
+ if (!term) return [''];
34
+ result.push(term); part = part.slice(term.length);
35
+ }
36
+ return result;
37
+ }) : en[1].toLowerCase().split(/\s*(?:,\s*(?:and\s+)?|\band\b)\s*/u);
38
+ if (!adjectives.length || adjectives.some(term => !terms.has(term))) return [];
39
+ const claims = new Map();
40
+ for (const term of adjectives) {
41
+ const [dimension, value] = terms.get(term);
42
+ if (claims.has(dimension) && claims.get(dimension) !== value) return [];
43
+ claims.set(dimension, value);
44
+ }
45
+ return [...claims].map(([dimension, value]) => ({
46
+ protocol: REPLY_PREFERENCE_PROTOCOL, dimension, value, polarity,
47
+ support: { text, start: source.text.indexOf(text), end: source.text.indexOf(text) + text.length },
48
+ }));
49
+ }
50
+ const attribute = claim => `reply_preference:v1:${claim.dimension}:${claim.value}:${claim.polarity}`;
51
+ const display = claim => claim.polarity === 'denied' ? `Rejects ${claim.dimension}=${claim.value} replies` : dimensions[claim.dimension][claim.value];
52
+ export function replyPreferenceTrait(claim, subject) {
53
+ return { text: display(claim), subject,
54
+ attribute: attribute(claim),
55
+ slots: ['表达风格'], entities: [], emotion: '', replyPreference: claim };
56
+ }
57
+ function supported(record, store) {
58
+ const claim = record.replyPreference;
59
+ if (!claim || claim.protocol !== REPLY_PREFERENCE_PROTOCOL || record.sourceRole === 'assistant' ||
60
+ record.subject !== record.userId || (record.attributedTo !== undefined && record.attributedTo !== record.userId) ||
61
+ !dimensions[claim.dimension]?.[claim.value] || !['affirmed', 'denied'].includes(claim.polarity) || record.attribute !== attribute(claim) ||
62
+ record.text !== display(claim) || !record.evidenceIds.length) return false;
63
+ return record.evidenceIds.every(id => {
64
+ const source = store.source(record.userId, record.scope, id);
65
+ return source?.state === 'learned' && (source.speaker ?? source.userId) === record.subject &&
66
+ groundedReplyPreferences(source).some(support => support.dimension === claim.dimension && support.value === claim.value && support.polarity === claim.polarity);
67
+ });
68
+ }
69
+ // Evaluate all active claims, before ranking, topK or the three-source floor.
70
+ // Even one authorized opposite observation withholds the entire dimension.
71
+ export function groundedStyleCandidates(items, store) {
72
+ const claims = items.filter(({record}) => record.kind === 'trait' && supported(record, store));
73
+ const conflicting = new Set();
74
+ for (const {record} of claims) for (const {record: other} of claims) {
75
+ if (record.userId === other.userId && record.scope === other.scope && record.subject === other.subject &&
76
+ record.replyPreference.dimension === other.replyPreference.dimension && (record.replyPreference.value !== other.replyPreference.value || record.replyPreference.polarity === 'denied' || other.replyPreference.polarity === 'denied'))
77
+ conflicting.add(record.replyPreference.dimension);
78
+ }
79
+ const allowed = new Set(claims.filter(({record}) => record.replyPreference.polarity === 'affirmed' && !conflicting.has(record.replyPreference.dimension) && new Set(record.evidenceIds).size >= 3).map(({record}) => record.id));
80
+ return items.filter(({record}) => record.kind !== 'trait' || allowed.has(record.id));
81
+ }
@@ -0,0 +1,22 @@
1
+ export * from './types.js';
2
+ export { REPLY_PREFERENCE_PROTOCOL } from './grounded-reply-preferences.js';
3
+ export * from './memory.js';
4
+ export { MemoryStore } from './store.js';
5
+ export * from './providers.js';
6
+ export * from './audio.js';
7
+ export * from './stream.js';
8
+ export * from './barge-in.js';
9
+ export * from './time.js';
10
+ export * from './routing.js';
11
+ export * from './realtime.js';
12
+ export * from './reply.js';
13
+ export * from './dashscope-tts.js';
14
+ export * from './dashscope-asr.js';
15
+ export * from './local-embedding.js';
16
+ export * from './local-speaker.js';
17
+ export * from './speaker-profiles.js';
18
+ export * from './speaker-bindings.js';
19
+ export * from './finetune-data.js';
20
+ export * from './finetune.js';
21
+ export * from './slots.js';
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,164 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { createLocalInferenceWorker, inferenceData, inferencePort } from './local-runtime.js';
4
+ const MODEL = 'Xenova/multilingual-e5-small';
5
+ // Official Hugging Face model API revision verified 2026-09-05.
6
+ const REVISION = '761b726dd34fb83930e26aab4e9ac3899aa1fa78';
7
+ function duration(value, fallback) {
8
+ const ms = value ?? fallback;
9
+ if (!Number.isInteger(ms) || ms < 1 || ms > 600000)
10
+ throw new Error('Invalid local embedding timeout');
11
+ return ms;
12
+ }
13
+ function bounded(promise, ms, signal) {
14
+ return new Promise((resolve, reject) => {
15
+ let settled = false;
16
+ const finish = (callback) => {
17
+ if (settled)
18
+ return;
19
+ settled = true;
20
+ clearTimeout(timer);
21
+ signal?.removeEventListener('abort', abort);
22
+ callback();
23
+ };
24
+ const abort = () => finish(() => reject(signal?.reason ?? new DOMException('Aborted', 'AbortError')));
25
+ const timer = ms === undefined ? undefined : setTimeout(() => finish(() => reject(new Error('Local embedding timeout'))), ms);
26
+ signal?.addEventListener('abort', abort, { once: true });
27
+ promise.then(value => finish(() => resolve(value)), error => finish(() => reject(error)));
28
+ if (signal?.aborted)
29
+ abort();
30
+ });
31
+ }
32
+ /** Native ONNX CPU inference in an owned Node process; q8 E5 embeddings use 512-token model truncation. */
33
+ export class LocalE5EmbeddingModel {
34
+ options;
35
+ model = `${MODEL}@${REVISION}:q8:mean-normalized:e5-prefix-v1`;
36
+ worker;
37
+ ready;
38
+ rejectReady;
39
+ active;
40
+ chain = Promise.resolve();
41
+ closed = false;
42
+ loadMs;
43
+ requestMs;
44
+ constructor(options = {}) {
45
+ this.options = options;
46
+ this.loadMs = duration(options.loadTimeoutMs, 120000);
47
+ this.requestMs = duration(options.timeoutMs, 30000);
48
+ }
49
+ embed(texts, signal, purpose = 'passage') {
50
+ if (this.closed)
51
+ return Promise.reject(new Error('Local embedding model closed'));
52
+ if (signal?.aborted)
53
+ return Promise.reject(signal.reason);
54
+ if (purpose !== 'query' && purpose !== 'passage')
55
+ return Promise.reject(new Error('Invalid embedding purpose'));
56
+ if (texts.length > 256 || texts.some(text => typeof text !== 'string' || !text.trim() || text.length > 40000))
57
+ return Promise.reject(new Error('Invalid local embedding input; use at most 256 nonempty texts of 40000 characters'));
58
+ if (!texts.length)
59
+ return Promise.resolve([]);
60
+ const prefixed = texts.map(text => `${purpose}: ${text}`);
61
+ const job = this.chain.catch(() => { }).then(async () => {
62
+ if (this.closed)
63
+ throw new Error('Local embedding model closed');
64
+ signal?.throwIfAborted();
65
+ try {
66
+ await bounded(this.load(), this.loadMs, signal);
67
+ signal?.throwIfAborted();
68
+ if (this.closed)
69
+ throw new Error('Local embedding model closed');
70
+ const result = new Promise((resolve, reject) => {
71
+ this.active = { resolve, reject };
72
+ this.worker.postMessage({ texts: prefixed });
73
+ });
74
+ const vectors = await bounded(result, this.requestMs, signal);
75
+ if (!Array.isArray(vectors) || vectors.length !== texts.length || vectors.some(row => !Array.isArray(row) || row.length !== 384 || row.some(n => typeof n !== 'number' || !Number.isFinite(n)) || !row.some(n => n !== 0)))
76
+ throw new Error('Invalid local embedding vector');
77
+ return vectors;
78
+ }
79
+ catch (error) {
80
+ await this.stop();
81
+ throw error;
82
+ }
83
+ finally {
84
+ this.active = undefined;
85
+ }
86
+ });
87
+ this.chain = job;
88
+ return bounded(job, undefined, signal);
89
+ }
90
+ load() {
91
+ if (this.ready)
92
+ return this.ready;
93
+ const worker = (this.options.workerFactory ?? createLocalInferenceWorker)(new URL(import.meta.url), {
94
+ workerData: { voicememE5: true, model: MODEL, revision: REVISION, cacheDir: this.options.cacheDir ?? join(homedir(), '.cache', 'voicemem'), localFilesOnly: this.options.localFilesOnly ?? false },
95
+ });
96
+ this.worker = worker;
97
+ this.ready = new Promise((resolve, reject) => {
98
+ this.rejectReady = reject;
99
+ const fail = (error) => {
100
+ if (this.worker !== worker)
101
+ return;
102
+ this.worker = undefined;
103
+ this.ready = undefined;
104
+ this.rejectReady = undefined;
105
+ reject(error);
106
+ this.active?.reject(error);
107
+ };
108
+ worker.on('message', (message) => {
109
+ if (this.worker !== worker)
110
+ return;
111
+ if (message.error) {
112
+ const error = new Error(message.error);
113
+ reject(error);
114
+ this.active?.reject(error);
115
+ }
116
+ else if (message.ready)
117
+ resolve();
118
+ else
119
+ this.active?.resolve(message.vectors);
120
+ });
121
+ worker.on('error', () => fail(new Error('Local embedding worker failed')));
122
+ worker.on('exit', () => fail(new Error('Local embedding worker exited')));
123
+ });
124
+ return this.ready;
125
+ }
126
+ async stop() {
127
+ const worker = this.worker;
128
+ this.worker = undefined;
129
+ this.ready = undefined;
130
+ const error = new Error('Local embedding worker stopped');
131
+ this.rejectReady?.(error);
132
+ this.rejectReady = undefined;
133
+ this.active?.reject(error);
134
+ if (worker)
135
+ await bounded(worker.terminate(), 5000);
136
+ }
137
+ async close() { this.closed = true; await this.stop(); await this.chain.catch(() => { }); }
138
+ }
139
+ if (inferenceData?.voicememE5 === true) {
140
+ try {
141
+ const { pipeline } = await import('@huggingface/transformers');
142
+ const extractor = await pipeline('feature-extraction', inferenceData.model, {
143
+ revision: inferenceData.revision, dtype: 'q8', device: 'cpu', cache_dir: inferenceData.cacheDir, local_files_only: inferenceData.localFilesOnly,
144
+ });
145
+ inferencePort.on('message', async (message) => {
146
+ try {
147
+ const vectors = [];
148
+ for (let index = 0; index < message.texts.length; index += 16) {
149
+ const output = await extractor(message.texts.slice(index, index + 16), { pooling: 'mean', normalize: true });
150
+ vectors.push(...output.tolist());
151
+ }
152
+ inferencePort.postMessage({ vectors });
153
+ }
154
+ catch {
155
+ inferencePort.postMessage({ error: 'Local embedding inference failed' });
156
+ }
157
+ });
158
+ inferencePort.postMessage({ ready: true });
159
+ }
160
+ catch {
161
+ inferencePort.postMessage({ error: 'Local embedding load failed; verify cached model files or download access' });
162
+ }
163
+ }
164
+ //# sourceMappingURL=local-embedding.js.map
@@ -0,0 +1,53 @@
1
+ import { fork } from 'node:child_process';
2
+ import { EventEmitter } from 'node:events';
3
+ import { isMainThread, parentPort, workerData } from 'node:worker_threads';
4
+ const childFlag = '--voicemem-local-inference';
5
+ const isChild = isMainThread && process.argv[2] === childFlag;
6
+ export const inferenceData = isChild ? JSON.parse(process.argv[3]) : workerData;
7
+ export const inferencePort = parentPort ?? (isChild ? {
8
+ on: (_event, listener) => process.on('message', listener),
9
+ postMessage: (message) => { if (process.connected)
10
+ process.send(message); },
11
+ } : null);
12
+ if (isChild)
13
+ process.on('disconnect', () => process.exit(0));
14
+ /** ONNX 1.21 cannot safely share addon state across worker lifetimes/isolate contexts.
15
+ * An owned Node process gives each model its own native runtime and bounded termination.
16
+ */
17
+ export class LocalInferenceProcess extends EventEmitter {
18
+ child;
19
+ exited;
20
+ stopped = false;
21
+ constructor(url, options) {
22
+ super();
23
+ this.child = fork(url, [childFlag, JSON.stringify(options.workerData)], {
24
+ serialization: 'advanced', execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
25
+ });
26
+ this.exited = new Promise(resolve => {
27
+ this.child.on('error', error => this.emit('error', error));
28
+ this.child.on('message', message => this.emit('message', message));
29
+ this.child.once('exit', code => {
30
+ this.stopped = true;
31
+ resolve(code ?? 1);
32
+ this.emit('exit', code ?? 1);
33
+ });
34
+ });
35
+ }
36
+ postMessage(message) {
37
+ if (this.stopped)
38
+ throw new Error('Local inference process stopped');
39
+ this.child.send(message, error => { if (error && !this.stopped)
40
+ this.emit('error', error); });
41
+ }
42
+ terminate() {
43
+ if (!this.stopped) {
44
+ this.stopped = true;
45
+ this.child.kill('SIGKILL');
46
+ }
47
+ return this.exited;
48
+ }
49
+ }
50
+ export function createLocalInferenceWorker(url, options) {
51
+ return new LocalInferenceProcess(url, options);
52
+ }
53
+ //# sourceMappingURL=local-runtime.js.map