nova-personal-agent-server 0.4.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +10 -0
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +11 -4
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -0,0 +1,764 @@
1
+ /**
2
+ * Dependency-free data-root resolution and the explicit `~/.nova-audio-agent` -> `~/.nova-personal-agent` move.
3
+ * check-capabilities.mjs emits this file into the standalone CLI and the desktop main process, so every entry point
4
+ * resolves the same root by the same rules.
5
+ *
6
+ * Resolution everywhere: an explicit path (environment or a user setting) is honoured as-is; otherwise the new root
7
+ * once the move is done or when there is no legacy data; otherwise the legacy root (a real directory, or a link the
8
+ * user created). Nothing moves on startup: existing users keep working from the legacy root until they run
9
+ * `npa migrate-data` with Nova closed. A pending move journal blocks every writer until that command finishes or
10
+ * rolls it back. A fresh install never creates the legacy root.
11
+ */
12
+ import * as nodeFs from 'node:fs';
13
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
14
+ export const DATA_ROOT_NAME = '.nova-personal-agent';
15
+ // Compatibility: the retired product identity. Used only for detection, the explicit move and the compatibility link.
16
+ export const LEGACY_DATA_ROOT_NAME = '.nova-audio-agent';
17
+ export const DATA_ROOT_TILDE = `~/${DATA_ROOT_NAME}`;
18
+ export const LEGACY_DATA_ROOT_TILDE = `~/${LEGACY_DATA_ROOT_NAME}`;
19
+ /** Written into the new root last, once every entry has moved and the compatibility link is verified. */
20
+ export const DATA_ROOT_MARKER = '.data-root-migrated.json';
21
+ /** Written into the new root before the first rename; while it exists no process may write either root. */
22
+ export const DATA_ROOT_JOURNAL = '.data-root-migration.journal.json';
23
+ /** Exclusive migrator lock, in the home directory (outside both roots), held for the whole move. */
24
+ export const MIGRATION_LOCK_NAME = '.nova-personal-agent.migration.lock';
25
+ const EMPTY_SUFFIX = '.migrating-empty';
26
+ /** A journal from an interrupted move exists: no process may read or write either root until it is finished. */
27
+ export class DataRootMigrationPendingError extends Error {
28
+ journal;
29
+ lock;
30
+ code = 'data_root_migration_pending';
31
+ constructor(journal, lock) {
32
+ super(lock === undefined
33
+ ? `Nova data migration is incomplete (${journal}). Quit Nova and run \`npa migrate-data\` to finish or roll it back.`
34
+ : `Nova data migration is running or was interrupted (${lock}). Wait for \`npa migrate-data\` to finish; if none is running, run it again.`);
35
+ this.journal = journal;
36
+ this.lock = lock;
37
+ }
38
+ }
39
+ export function dataRootPaths(home) {
40
+ const root = join(home, DATA_ROOT_NAME);
41
+ return { root, legacyRoot: join(home, LEGACY_DATA_ROOT_NAME), journal: join(root, DATA_ROOT_JOURNAL), marker: join(root, DATA_ROOT_MARKER), lock: join(home, MIGRATION_LOCK_NAME) };
42
+ }
43
+ function lstatOrNull(fs, path) {
44
+ try {
45
+ return fs.lstatSync(path);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ function realpathOrNull(fs, path) {
52
+ try {
53
+ return fs.realpathSync(path);
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ function exists(fs, path) {
60
+ return lstatOrNull(fs, path) !== null;
61
+ }
62
+ /**
63
+ * The new root once migrated or when no legacy data exists; the legacy root while it is a real directory or a link
64
+ * the user created (relocated data is resolved through it, never treated as a fresh install).
65
+ * Throws while a move journal is pending.
66
+ */
67
+ export function resolveDataRoot(home, fs = nodeFs) {
68
+ const { root, legacyRoot, journal, marker, lock } = dataRootPaths(home);
69
+ // A journal or a held migrator lock always wins, even over the marker: the move is in progress.
70
+ if (exists(fs, journal))
71
+ throw new DataRootMigrationPendingError(journal);
72
+ if (exists(fs, lock))
73
+ throw new DataRootMigrationPendingError(journal, lock);
74
+ if (fs.existsSync(marker))
75
+ return linkedToRoot(fs, legacyRoot, root) ? { root, legacy: false } : { root, legacy: false, linkBroken: true };
76
+ const legacy = lstatOrNull(fs, legacyRoot);
77
+ if (legacy !== null && (legacy.isDirectory() || legacy.isSymbolicLink()))
78
+ return { root: legacyRoot, legacy: true };
79
+ return { root, legacy: false };
80
+ }
81
+ /** Refuses (throws DataRootMigrationPendingError) before a writer creates anything while a journal is pending. */
82
+ export function assertNoPendingDataRootMigration(home, fs = nodeFs) {
83
+ resolveDataRoot(home, fs);
84
+ }
85
+ /** The home directory a configuration environment names; undefined keeps the static defaults. */
86
+ export function environmentHome(environment, platform = process.platform) {
87
+ const value = platform === 'win32' ? environment.USERPROFILE ?? environment.HOME : environment.HOME;
88
+ return value?.trim() ? value : undefined;
89
+ }
90
+ export function legacyDataRootActive(home, fs = nodeFs) {
91
+ return home !== undefined && resolveDataRoot(home, fs).legacy;
92
+ }
93
+ /** Moves a default `~/.nova-personal-agent/...` onto the legacy root while that root is still active. */
94
+ export function rebaseDataRootDefault(path, legacy) {
95
+ if (!legacy)
96
+ return path;
97
+ if (path === DATA_ROOT_TILDE || path.startsWith(`${DATA_ROOT_TILDE}/`))
98
+ return LEGACY_DATA_ROOT_TILDE + path.slice(DATA_ROOT_TILDE.length);
99
+ return path;
100
+ }
101
+ /**
102
+ * Once migrated, an explicit path under the legacy root (absolute or `~/.nova-audio-agent/...`) is mapped onto the
103
+ * new root, so a missing or broken compatibility link can never make it open a second, separate database.
104
+ */
105
+ export function mapLegacyDataPath(path, home, fs = nodeFs) {
106
+ if (home === undefined || typeof path !== 'string' || path === '')
107
+ return path;
108
+ const { root, legacyRoot } = dataRootPaths(home);
109
+ if (resolveDataRoot(home, fs).legacy)
110
+ return path;
111
+ if (path === LEGACY_DATA_ROOT_TILDE || path.startsWith(`${LEGACY_DATA_ROOT_TILDE}/`))
112
+ return DATA_ROOT_TILDE + path.slice(LEGACY_DATA_ROOT_TILDE.length);
113
+ const inside = relative(legacyRoot, path);
114
+ if (isAbsolute(path) && (inside === '' || (inside !== '..' && !inside.startsWith(`..${sep}`) && !isAbsolute(inside))))
115
+ return join(root, inside);
116
+ return path;
117
+ }
118
+ /** A default data path under whichever root is active for `home`. */
119
+ export function defaultDataPath(relativePath, home, fs = nodeFs) {
120
+ return rebaseDataRootDefault(relativePath === '' ? DATA_ROOT_TILDE : `${DATA_ROOT_TILDE}/${relativePath}`, legacyDataRootActive(home, fs));
121
+ }
122
+ /** `<db>`, `<db>-wal`, `<db>-shm`, `<db>-journal` and the `<db>.memory/` repository form one indivisible unit. */
123
+ export function sqliteGroup(name) {
124
+ return /^(.+\.(?:sqlite|sqlite3|db))(?:-wal|-shm|-journal|\.memory)?$/iu.exec(name)?.[1] ?? null;
125
+ }
126
+ /** Group identity compared case-insensitively: conservative on case-insensitive volumes (macOS, Windows). */
127
+ function groupKey(name) {
128
+ return sqliteGroup(name)?.toLowerCase() ?? null;
129
+ }
130
+ function sameBytes(fs, left, right) {
131
+ const a = fs.statSync(left), b = fs.statSync(right);
132
+ if (a.size !== b.size)
133
+ return false;
134
+ const first = fs.openSync(left, 'r'), second = fs.openSync(right, 'r');
135
+ try {
136
+ const x = Buffer.alloc(65_536), y = Buffer.alloc(65_536);
137
+ for (;;) {
138
+ const read = fs.readSync(first, x, 0, x.length, null);
139
+ const other = fs.readSync(second, y, 0, y.length, null);
140
+ if (read !== other)
141
+ return false;
142
+ if (read === 0)
143
+ return true;
144
+ if (!x.subarray(0, read).equals(y.subarray(0, read)))
145
+ return false;
146
+ }
147
+ }
148
+ finally {
149
+ fs.closeSync(first);
150
+ fs.closeSync(second);
151
+ }
152
+ }
153
+ function emptyDirectory(fs, path, stats) {
154
+ return stats?.isDirectory() === true && fs.readdirSync(path).length === 0;
155
+ }
156
+ /** Release downloads the CLI can fetch again; a duplicate is set aside under a `.legacy-<ts>` name, never merged. */
157
+ function cacheLeaf(relativePath) {
158
+ const parts = relativePath.split(sep);
159
+ return parts[0] === 'cli' && parts[1] === 'releases' && parts.length >= 4;
160
+ }
161
+ /**
162
+ * Plans renames only; nothing on disk changes. Directories present on both sides are merged entry by entry.
163
+ * A database group moves only whole: its main file must exist in the legacy root and no member may exist in the
164
+ * new root. Identical or empty non-database leftovers in the new root are set aside, never deleted.
165
+ */
166
+ export function planDataRootMigration(fs, from, to, stamp) {
167
+ const ops = [], conflicts = [], taken = new Set();
168
+ const aside = (target, label) => {
169
+ for (let index = 0;; index += 1) {
170
+ const candidate = `${target}.${label}-${stamp}${index === 0 ? '' : `-${index}`}`;
171
+ if (!taken.has(candidate) && lstatOrNull(fs, candidate) === null) {
172
+ taken.add(candidate);
173
+ return candidate;
174
+ }
175
+ }
176
+ };
177
+ const visit = (source, target) => {
178
+ const names = fs.readdirSync(source).sort();
179
+ const targetNames = lstatOrNull(fs, target)?.isDirectory() === true ? fs.readdirSync(target) : [];
180
+ const groups = new Set();
181
+ for (const name of names) {
182
+ const sourcePath = join(source, name), targetPath = join(target, name);
183
+ const group = groupKey(name);
184
+ if (group !== null) {
185
+ if (groups.has(group))
186
+ continue;
187
+ groups.add(group);
188
+ const members = names.filter(member => groupKey(member) === group);
189
+ const existing = targetNames.filter(candidate => groupKey(candidate) === group);
190
+ if (existing.length > 0) {
191
+ conflicts.push(...existing.sort().map(candidate => ({ path: join(target, candidate), reason: 'sqlite_both' })));
192
+ continue;
193
+ }
194
+ if (!members.some(member => member.toLowerCase() === group)) {
195
+ conflicts.push({ path: join(source, sqliteGroup(name) ?? name), reason: 'sqlite_partial' });
196
+ continue;
197
+ }
198
+ for (const member of members)
199
+ ops.push({ kind: 'move', from: join(source, member), to: join(target, member) });
200
+ continue;
201
+ }
202
+ const existing = lstatOrNull(fs, targetPath);
203
+ if (existing === null) {
204
+ ops.push({ kind: 'move', from: sourcePath, to: targetPath });
205
+ continue;
206
+ }
207
+ if (cacheLeaf(relative(to, targetPath))) {
208
+ ops.push({ kind: 'move', from: sourcePath, to: aside(targetPath, 'legacy') });
209
+ continue;
210
+ }
211
+ const current = fs.lstatSync(sourcePath);
212
+ if (current.isDirectory() && existing.isDirectory()) {
213
+ visit(sourcePath, targetPath);
214
+ ops.push({ kind: 'rmdir', path: sourcePath });
215
+ continue;
216
+ }
217
+ if (emptyDirectory(fs, targetPath, existing) || (current.isFile() && existing.isFile() && sameBytes(fs, sourcePath, targetPath))) {
218
+ ops.push({ kind: 'backup', from: targetPath, to: aside(targetPath, 'conflict') }, { kind: 'move', from: sourcePath, to: targetPath });
219
+ continue;
220
+ }
221
+ conflicts.push({ path: targetPath, reason: 'differs' });
222
+ }
223
+ };
224
+ visit(from, to);
225
+ return { ops, conflicts };
226
+ }
227
+ function applied(fs, op) {
228
+ if (op.kind === 'rmdir')
229
+ return !exists(fs, op.path);
230
+ return !exists(fs, op.from) && exists(fs, op.to);
231
+ }
232
+ class NoClobberError extends Error {
233
+ path;
234
+ counterpart;
235
+ code = 'EEXIST';
236
+ constructor(path, counterpart) {
237
+ super(`refusing to overwrite ${path}`);
238
+ this.path = path;
239
+ this.counterpart = counterpart;
240
+ }
241
+ }
242
+ /** Never renames onto an existing path; the migrator lock and the stopped-Nova checks exclude racing writers. */
243
+ function renameNoClobber(fs, from, to) {
244
+ if (exists(fs, to))
245
+ throw new NoClobberError(to);
246
+ fs.renameSync(from, to);
247
+ }
248
+ /** Rolls forward from whatever the disk says is already applied; a destination this step did not create stops it. */
249
+ export function applyDataRootOps(fs, ops) {
250
+ for (const op of ops) {
251
+ if (applied(fs, op))
252
+ continue;
253
+ if (op.kind === 'rmdir')
254
+ fs.rmdirSync(op.path);
255
+ else
256
+ renameNoClobber(fs, op.from, op.to);
257
+ }
258
+ }
259
+ /**
260
+ * Undoes applied operations newest first, restoring the legacy root exactly. Stops (NoClobberError) instead of
261
+ * renaming onto an existing path, or when an operation's source and destination are both present or both missing.
262
+ */
263
+ export function revertDataRootOps(fs, ops) {
264
+ for (const op of [...ops].reverse()) {
265
+ if (op.kind === 'rmdir') {
266
+ if (!exists(fs, op.path))
267
+ fs.mkdirSync(op.path, { mode: 0o700 });
268
+ continue;
269
+ }
270
+ const source = exists(fs, op.from), target = exists(fs, op.to);
271
+ if (source && !target)
272
+ continue;
273
+ if (!source && target) {
274
+ renameNoClobber(fs, op.to, op.from);
275
+ continue;
276
+ }
277
+ // Both present is expected only for a move whose destination still holds the copy its backup has not set aside.
278
+ const awaitingBackup = source && ops.some(other => other.kind === 'backup' && other.from === op.to && exists(fs, other.from) && !exists(fs, other.to));
279
+ if (!awaitingBackup)
280
+ throw new NoClobberError(op.from, op.to);
281
+ }
282
+ }
283
+ /**
284
+ * Paths that block a resumed move: a destination of an unapplied move that already exists (and is not waiting for
285
+ * its backup), or any member of an unapplied database's group in the new root that the journal did not put there.
286
+ */
287
+ function resumeConflicts(fs, ops) {
288
+ const targets = new Set(ops.flatMap(op => op.kind === 'rmdir' ? [] : [op.to]));
289
+ const conflicts = new Set();
290
+ for (const op of ops) {
291
+ if (op.kind !== 'move' || applied(fs, op) || !exists(fs, op.from))
292
+ continue;
293
+ const awaitingBackup = ops.some(other => other.kind === 'backup' && other.from === op.to && exists(fs, other.from) && !exists(fs, other.to));
294
+ if (exists(fs, op.to) && !awaitingBackup)
295
+ conflicts.add(op.to);
296
+ const key = groupKey(basename(op.to));
297
+ if (key === null)
298
+ continue;
299
+ let names = [];
300
+ try {
301
+ names = fs.readdirSync(dirname(op.to));
302
+ }
303
+ catch {
304
+ continue;
305
+ }
306
+ for (const name of names) {
307
+ const path = join(dirname(op.to), name);
308
+ if (groupKey(name) === key && !targets.has(path))
309
+ conflicts.add(path);
310
+ }
311
+ }
312
+ return [...conflicts].sort();
313
+ }
314
+ /** Operations whose effect is still on disk; empty exactly when the legacy layout is fully restored. */
315
+ function stillApplied(fs, ops) {
316
+ return ops.filter(op => op.kind === 'rmdir' ? !exists(fs, op.path) : !exists(fs, op.from));
317
+ }
318
+ function writeAtomic(fs, path, value) {
319
+ const temporary = `${path}.${process.pid}.tmp`;
320
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 1)}\n`, { mode: 0o600 });
321
+ fs.renameSync(temporary, path);
322
+ }
323
+ function readJournal(fs, path, root, legacyRoot) {
324
+ const record = JSON.parse(fs.readFileSync(path, 'utf8'));
325
+ if (record.version !== 1 || record.root !== root || record.legacyRoot !== legacyRoot || !Array.isArray(record.ops)) {
326
+ throw new Error('data_root_journal_invalid');
327
+ }
328
+ return record.ops;
329
+ }
330
+ function linkType(platform) {
331
+ return platform === 'win32' ? 'junction' : 'dir';
332
+ }
333
+ function removeLink(fs, path) {
334
+ try {
335
+ fs.unlinkSync(path);
336
+ }
337
+ catch {
338
+ fs.rmdirSync(path);
339
+ }
340
+ }
341
+ function linkSupported(fs, root, platform) {
342
+ const probe = join(root, `.compat-link-probe-${process.pid}`);
343
+ try {
344
+ fs.symlinkSync(root, probe, linkType(platform));
345
+ const ok = realpathOrNull(fs, probe) === realpathOrNull(fs, root);
346
+ removeLink(fs, probe);
347
+ return ok;
348
+ }
349
+ catch {
350
+ return false;
351
+ }
352
+ }
353
+ function linkedToRoot(fs, legacyRoot, root) {
354
+ return lstatOrNull(fs, legacyRoot)?.isSymbolicLink() === true && realpathOrNull(fs, legacyRoot) === realpathOrNull(fs, root);
355
+ }
356
+ /** Whether the rename phase is over: the legacy root was swapped aside or already replaced by our link. */
357
+ function inLinkPhase(fs, legacyRoot, root) {
358
+ return exists(fs, legacyRoot + EMPTY_SUFFIX) || linkedToRoot(fs, legacyRoot, root);
359
+ }
360
+ /**
361
+ * Replaces the emptied legacy root with the compatibility link: rename it aside, create the link at the old path,
362
+ * verify it resolves to the new root, then remove the empty directory. Resumable from every intermediate state.
363
+ */
364
+ function swapInLink(fs, legacyRoot, root, platform) {
365
+ const aside = legacyRoot + EMPTY_SUFFIX;
366
+ const current = lstatOrNull(fs, legacyRoot);
367
+ if (current !== null && !current.isSymbolicLink()) {
368
+ if (!current.isDirectory() || fs.readdirSync(legacyRoot).length > 0)
369
+ throw Object.assign(new Error('legacy root changed during migration'), { code: 'changed' });
370
+ if (exists(fs, aside))
371
+ fs.rmdirSync(aside);
372
+ fs.renameSync(legacyRoot, aside);
373
+ }
374
+ if (!exists(fs, legacyRoot))
375
+ fs.symlinkSync(root, legacyRoot, linkType(platform));
376
+ if (!linkedToRoot(fs, legacyRoot, root))
377
+ throw Object.assign(new Error('compatibility link does not resolve to the new root'), { code: 'link_unsupported' });
378
+ if (exists(fs, aside))
379
+ fs.rmdirSync(aside);
380
+ }
381
+ /** Undoes swapInLink: removes our link and restores the (empty) legacy directory, never touching foreign data. */
382
+ function unswapLink(fs, legacyRoot, root) {
383
+ const aside = legacyRoot + EMPTY_SUFFIX;
384
+ if (linkedToRoot(fs, legacyRoot, root))
385
+ removeLink(fs, legacyRoot);
386
+ if (exists(fs, aside))
387
+ renameNoClobber(fs, aside, legacyRoot);
388
+ else if (!exists(fs, legacyRoot))
389
+ fs.mkdirSync(legacyRoot, { mode: 0o700 });
390
+ }
391
+ function describeOp(op) {
392
+ return op.kind === 'rmdir' ? `recreate the directory ${op.path}` : `move ${op.to} back to ${op.from}`;
393
+ }
394
+ function sameVolume(fs, root, legacyRoot, home) {
395
+ const target = lstatOrNull(fs, root) === null ? home : root;
396
+ return fs.statSync(target).dev === fs.statSync(legacyRoot).dev;
397
+ }
398
+ /** The move `migrateDataRoot` would make, without changing anything (the `--dry-run` view). */
399
+ export function inspectDataRootMigration(options) {
400
+ const fs = options.fs ?? nodeFs;
401
+ const { root, legacyRoot, journal, marker } = dataRootPaths(options.home);
402
+ const result = (status, ops = [], conflicts = []) => ({ status, root, legacyRoot, ops, conflicts });
403
+ if (exists(fs, journal))
404
+ return result('pending', readJournal(fs, journal, root, legacyRoot));
405
+ if (fs.existsSync(marker))
406
+ return result(linkedToRoot(fs, legacyRoot, root) ? 'done' : 'link_broken');
407
+ const legacy = lstatOrNull(fs, legacyRoot);
408
+ if (legacy === null || (!legacy.isDirectory() && !legacy.isSymbolicLink()))
409
+ return result('fresh');
410
+ if (legacy.isSymbolicLink())
411
+ return result('foreign_link');
412
+ if (lstatOrNull(fs, root)?.isSymbolicLink() === true)
413
+ return result('root_link');
414
+ if (!sameVolume(fs, root, legacyRoot, options.home))
415
+ return result('cross_device');
416
+ const stamp = (options.now?.() ?? new Date()).toISOString().replace(/[:.]/gu, '-');
417
+ const planned = planDataRootMigration(fs, legacyRoot, root, stamp);
418
+ return result(planned.conflicts.length > 0 ? 'conflict' : 'ready', planned.ops, planned.conflicts);
419
+ }
420
+ /**
421
+ * The explicit, idempotent move of the legacy data root into the new root by same-volume, no-clobber renames.
422
+ * Called only by `npa migrate-data` while holding the migrator lock with Nova stopped. Never copies, never
423
+ * overwrites, refuses on any conflict before the first rename, and removes the journal only once every step is
424
+ * either committed or exactly reverted; otherwise the journal stays and blocks every writer.
425
+ */
426
+ export function migrateDataRoot(options) {
427
+ const fs = options.fs ?? nodeFs;
428
+ const platform = options.platform ?? process.platform;
429
+ const log = options.log ?? (() => undefined);
430
+ const { root, legacyRoot, journal: journalPath, marker } = dataRootPaths(options.home);
431
+ const skipped = (reason, detail, recovery) => {
432
+ log(`data-root: migration not done (${reason})${detail?.length ? `: ${detail.join(', ')}` : ''}`);
433
+ const pending = exists(fs, journalPath);
434
+ return { status: 'skipped', root: pending ? root : legacyRoot, reason, pending,
435
+ ...(detail === undefined ? {} : { detail }), ...(recovery === undefined ? {} : { recovery }) };
436
+ };
437
+ // The journal always wins over the marker.
438
+ const pending = exists(fs, journalPath);
439
+ if (!pending && fs.existsSync(marker))
440
+ return { status: 'done', root };
441
+ const legacy = lstatOrNull(fs, legacyRoot);
442
+ if (!pending) {
443
+ if (legacy === null || (!legacy.isDirectory() && !legacy.isSymbolicLink()))
444
+ return { status: 'fresh', root };
445
+ if (legacy.isSymbolicLink())
446
+ return skipped('foreign_link');
447
+ // A linked new root would make the planner look at the link, not the directory it names: refuse.
448
+ if (lstatOrNull(fs, root)?.isSymbolicLink() === true)
449
+ return skipped('root_link');
450
+ }
451
+ if (options.locksHeld?.() === true)
452
+ return skipped('locked');
453
+ let ops;
454
+ try {
455
+ if (pending) {
456
+ ops = readJournal(fs, journalPath, root, legacyRoot);
457
+ log(`data-root: resuming interrupted migration (${ops.length} operations)`);
458
+ }
459
+ else {
460
+ if (!sameVolume(fs, root, legacyRoot, options.home))
461
+ return skipped('cross_device');
462
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
463
+ if (!linkSupported(fs, root, platform))
464
+ return skipped('link_unsupported');
465
+ const stamp = (options.now?.() ?? new Date()).toISOString().replace(/[:.]/gu, '-');
466
+ const plan = planDataRootMigration(fs, legacyRoot, root, stamp);
467
+ if (plan.conflicts.length > 0)
468
+ return skipped('conflict', plan.conflicts.map(conflict => conflict.path));
469
+ ops = plan.ops;
470
+ // Publish the journal first (from now on Nova refuses to start), then make the final check.
471
+ writeAtomic(fs, journalPath, { version: 1, createdAt: new Date().toISOString(), root, legacyRoot, ops });
472
+ if (options.locksHeld?.() === true) {
473
+ fs.unlinkSync(journalPath);
474
+ return skipped('locked');
475
+ }
476
+ }
477
+ }
478
+ catch (error) {
479
+ log(`data-root: planning failed: ${error.message}`);
480
+ return skipped('failed');
481
+ }
482
+ const rollback = (reason, error, conflicts = []) => {
483
+ log(`data-root: migration failed (${error.code ?? error.message}); rolling back`);
484
+ let failure = null;
485
+ try {
486
+ unswapLink(fs, legacyRoot, root);
487
+ revertDataRootOps(fs, ops);
488
+ }
489
+ catch (rollbackError) {
490
+ failure = rollbackError;
491
+ }
492
+ const remaining = stillApplied(fs, ops);
493
+ if (conflicts.length === 0 && failure === null && remaining.length === 0 && !exists(fs, legacyRoot + EMPTY_SUFFIX) && lstatOrNull(fs, legacyRoot)?.isDirectory() === true) {
494
+ fs.unlinkSync(journalPath);
495
+ return skipped(reason);
496
+ }
497
+ // Keep the journal: it blocks every writer until the half state is resolved.
498
+ const blocked = failure instanceof NoClobberError ? [failure.counterpart === undefined
499
+ ? `${failure.path} already exists, so undoing the move would overwrite it: compare it with the moved copy and move the one that is not yours out of the way`
500
+ : `cannot move ${failure.counterpart} back to ${failure.path}: ${exists(fs, failure.path) ? 'both exist' : 'neither exists'}; compare both locations and move the copy that is not yours out of the way`] : failure === null ? [] : [`rollback stopped: ${failure.message}`];
501
+ const strays = conflicts.map(path => `${path} appeared after the migration started; move it out of the way (it is not part of the move)`);
502
+ return skipped(reason, conflicts.length > 0 ? conflicts : undefined, [...strays, ...blocked, ...remaining.reverse().map(describeOp),
503
+ `then run \`npa migrate-data\` again, which finishes or rolls back from ${journalPath}`]);
504
+ };
505
+ if (pending && !inLinkPhase(fs, legacyRoot, root)) {
506
+ // Something may have written into the new root since the journal was published: re-check before moving.
507
+ const conflicts = resumeConflicts(fs, ops);
508
+ if (conflicts.length > 0)
509
+ return rollback('conflict', new Error('conflict on resume'), conflicts);
510
+ }
511
+ try {
512
+ if (!inLinkPhase(fs, legacyRoot, root))
513
+ applyDataRootOps(fs, ops);
514
+ swapInLink(fs, legacyRoot, root, platform);
515
+ }
516
+ catch (error) {
517
+ const code = error.code;
518
+ const reason = code === 'EXDEV' ? 'cross_device' : code === 'EEXIST' ? 'conflict'
519
+ : code === 'changed' ? 'changed' : code === 'link_unsupported' ? 'link_unsupported' : 'failed';
520
+ return rollback(reason, error);
521
+ }
522
+ try {
523
+ options.beforeCommit?.();
524
+ }
525
+ catch (error) {
526
+ // Everything has moved and the link works; the journal stays so a rerun finishes the rewrites and the marker.
527
+ return skipped('failed', undefined, [`updating saved paths failed (${error.message})`, `run \`npa migrate-data\` again to finish from ${journalPath}`]);
528
+ }
529
+ const backups = ops.filter(op => op.kind === 'backup').map(op => op.to);
530
+ const moved = ops.filter(op => op.kind === 'move').length;
531
+ writeAtomic(fs, marker, { version: 1, migratedAt: new Date().toISOString(), from: legacyRoot, moved, backups });
532
+ fs.unlinkSync(journalPath);
533
+ log(`data-root: moved ${moved} entries into ${root}`);
534
+ return { status: 'migrated', root, moved, backups };
535
+ }
536
+ function processAlive(pid) {
537
+ if (!Number.isSafeInteger(pid) || pid <= 0)
538
+ return false;
539
+ try {
540
+ process.kill(pid, 0);
541
+ return true;
542
+ }
543
+ catch (error) {
544
+ return error.code === 'EPERM';
545
+ }
546
+ }
547
+ /** Whether an Electron instance still owns a profile directory (Chromium's SingletonLock, or Windows' lockfile). */
548
+ export function electronProfileInUse(directory, options = {}) {
549
+ const fs = options.fs ?? nodeFs;
550
+ if ((options.platform ?? process.platform) === 'win32') {
551
+ const lock = join(directory, 'lockfile');
552
+ if (!fs.existsSync(lock))
553
+ return false;
554
+ try {
555
+ fs.closeSync(fs.openSync(lock, 'r+'));
556
+ return false;
557
+ }
558
+ catch (error) {
559
+ return error.code !== 'ENOENT';
560
+ }
561
+ }
562
+ let target;
563
+ try {
564
+ // A symlink to "<hostname>-<pid>".
565
+ target = fs.readlinkSync(join(directory, 'SingletonLock'));
566
+ }
567
+ catch (error) {
568
+ const code = error.code;
569
+ return code !== 'ENOENT' && code !== 'ENOTDIR';
570
+ }
571
+ const pid = Number(target.slice(target.lastIndexOf('-') + 1));
572
+ return !Number.isSafeInteger(pid) || (pid !== process.pid && processAlive(pid));
573
+ }
574
+ /**
575
+ * The exclusive migrator lock. The owner record is written to a private temporary file first and then hard-linked
576
+ * into place, so the lock path never exists empty or half written; link() fails when it exists. An existing lock is
577
+ * never taken over automatically: returns null and the caller asks the user to remove it once no migration runs.
578
+ */
579
+ export function acquireMigrationLock(path, fs = nodeFs) {
580
+ const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
581
+ const temporary = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
582
+ fs.writeFileSync(temporary, JSON.stringify({ pid: process.pid, token, createdAt: new Date().toISOString() }), { mode: 0o600, flag: 'wx' });
583
+ try {
584
+ try {
585
+ fs.linkSync(temporary, path);
586
+ }
587
+ catch (error) {
588
+ if (error.code === 'EEXIST')
589
+ return null;
590
+ throw error;
591
+ }
592
+ let released = false;
593
+ return {
594
+ release() {
595
+ if (released)
596
+ return;
597
+ released = true;
598
+ try {
599
+ if (JSON.parse(fs.readFileSync(path, 'utf8')).token === token)
600
+ fs.unlinkSync(path);
601
+ }
602
+ catch { /* already gone */ }
603
+ },
604
+ };
605
+ }
606
+ finally {
607
+ try {
608
+ fs.unlinkSync(temporary);
609
+ }
610
+ catch { /* already gone */ }
611
+ }
612
+ }
613
+ /** The pid recorded in an existing migrator lock, or null when it is missing, empty or unreadable. */
614
+ export function migrationLockOwner(path, fs = nodeFs) {
615
+ try {
616
+ const pid = JSON.parse(fs.readFileSync(path, 'utf8')).pid;
617
+ return Number.isSafeInteger(pid) ? pid : null;
618
+ }
619
+ catch {
620
+ return null;
621
+ }
622
+ }
623
+ /**
624
+ * Restores the compatibility link after a completed move when the legacy path is missing or an empty directory.
625
+ * Anything else at the legacy path (a file, data, or a link elsewhere) is left alone and reported.
626
+ */
627
+ export function repairCompatibilityLink(home, options = {}) {
628
+ const fs = options.fs ?? nodeFs;
629
+ const { root, legacyRoot } = dataRootPaths(home);
630
+ if (linkedToRoot(fs, legacyRoot, root))
631
+ return 'ok';
632
+ const current = lstatOrNull(fs, legacyRoot);
633
+ if (current !== null && !(current.isDirectory() && !current.isSymbolicLink() && fs.readdirSync(legacyRoot).length === 0))
634
+ return 'blocked';
635
+ if (current !== null)
636
+ fs.rmdirSync(legacyRoot);
637
+ fs.symlinkSync(root, legacyRoot, linkType(options.platform ?? process.platform));
638
+ return linkedToRoot(fs, legacyRoot, root) ? 'repaired' : 'blocked';
639
+ }
640
+ /** Whether another process has a natively locked file open (codex project locks), probed without native code. */
641
+ export function nativeLockHeld(path, options = {}) {
642
+ const fs = options.fs ?? nodeFs, platform = options.platform ?? process.platform;
643
+ if (platform === 'win32') {
644
+ // LockFileEx ranges refuse reads from other handles.
645
+ let descriptor = null;
646
+ try {
647
+ descriptor = fs.openSync(path, 'r');
648
+ fs.readSync(descriptor, Buffer.alloc(1), 0, 1, 0);
649
+ return false;
650
+ }
651
+ catch (error) {
652
+ return error.code !== 'ENOENT';
653
+ }
654
+ finally {
655
+ if (descriptor !== null)
656
+ fs.closeSync(descriptor);
657
+ }
658
+ }
659
+ const childProcess = process.getBuiltinModule('node:child_process');
660
+ const result = childProcess?.spawnSync('lsof', ['-t', '--', path], { encoding: 'utf8', timeout: 10_000 });
661
+ if (result !== undefined && result.error === undefined && (result.status === 0 || result.status === 1)) {
662
+ return result.stdout.split(/\s+/u).some(pid => pid !== '' && Number(pid) !== process.pid);
663
+ }
664
+ if (platform === 'linux') {
665
+ const target = realpathOrNull(fs, path);
666
+ let pids = [];
667
+ try {
668
+ pids = fs.readdirSync('/proc').filter(name => /^\d+$/u.test(name) && Number(name) !== process.pid);
669
+ }
670
+ catch {
671
+ return true;
672
+ }
673
+ for (const pid of pids) {
674
+ let descriptors = [];
675
+ try {
676
+ descriptors = fs.readdirSync(`/proc/${pid}/fd`);
677
+ }
678
+ catch {
679
+ continue;
680
+ }
681
+ for (const descriptor of descriptors) {
682
+ try {
683
+ if (fs.readlinkSync(`/proc/${pid}/fd/${descriptor}`) === target)
684
+ return true;
685
+ }
686
+ catch { /* closed meanwhile */ }
687
+ }
688
+ }
689
+ return false;
690
+ }
691
+ // Cannot prove the lock is free.
692
+ return true;
693
+ }
694
+ function sqliteLockHeld(path) {
695
+ const sqlite = process.getBuiltinModule('node:sqlite');
696
+ if (sqlite === undefined)
697
+ return true;
698
+ let database = null;
699
+ try {
700
+ database = new sqlite.DatabaseSync(path);
701
+ database.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE');
702
+ database.exec('ROLLBACK');
703
+ return false;
704
+ }
705
+ catch {
706
+ return true;
707
+ }
708
+ finally {
709
+ database?.close();
710
+ }
711
+ }
712
+ function pidLockHeld(fs, path, directory) {
713
+ try {
714
+ const owner = JSON.parse(fs.readFileSync(directory ? join(path, 'owner.json') : path, 'utf8'));
715
+ const pid = owner.pid ?? owner.owner?.pid;
716
+ return pid === undefined ? null : processAlive(pid);
717
+ }
718
+ catch {
719
+ return null;
720
+ }
721
+ }
722
+ /**
723
+ * Every writer lock the runtime, CLI and desktop take inside a data root, at any depth and in every subdirectory
724
+ * (links are not followed): `*.owner.sqlite` ownership databases, pid-owned `*.lock` files (memory repository
725
+ * `<ledger>.memory/.nova-memory.lock`) and lock directories (CLI release installs), and natively locked `*.lock`
726
+ * files (codex project store). An unreadable directory or lock counts as held.
727
+ */
728
+ export function dataRootLocksHeld(root, options = {}) {
729
+ const fs = options.fs ?? nodeFs;
730
+ const platform = options.platform ?? process.platform;
731
+ const native = options.nativeLockHeld ?? (path => nativeLockHeld(path, { fs, platform }));
732
+ const visit = (directory, top) => {
733
+ let entries;
734
+ try {
735
+ entries = fs.readdirSync(directory, { withFileTypes: true });
736
+ }
737
+ catch (error) {
738
+ return !(top && error.code === 'ENOENT');
739
+ }
740
+ for (const entry of entries) {
741
+ const path = join(directory, entry.name);
742
+ if (entry.name.endsWith('.owner.sqlite') && entry.isFile() && sqliteLockHeld(path))
743
+ return true;
744
+ if (entry.name.endsWith('.lock')) {
745
+ if (entry.isDirectory()) {
746
+ if (pidLockHeld(fs, path, true) !== false)
747
+ return true;
748
+ continue;
749
+ }
750
+ if (entry.isFile()) {
751
+ const owned = pidLockHeld(fs, path, false);
752
+ if (owned === true || (owned === null && native(path)))
753
+ return true;
754
+ continue;
755
+ }
756
+ }
757
+ if (entry.isDirectory() && visit(path, false))
758
+ return true;
759
+ }
760
+ return false;
761
+ };
762
+ return visit(root, true);
763
+ }
764
+ //# sourceMappingURL=data-root.js.map