nova-personal-agent-server 0.0.0-stage → 0.4.1

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 (345) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/bin/novapersonal-server.mjs +4 -0
  4. package/package.json +61 -4
  5. package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
  6. package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
  7. package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
  8. package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
  9. package/resources/native/codex-sandbox-probe +0 -0
  10. package/resources/native/project-native/nova_project_native.node +0 -0
  11. package/resources/native-resources-v1.json +1 -0
  12. package/runtime/dist/eval/demos.js +156 -0
  13. package/runtime/dist/eval/fixture-host.js +385 -0
  14. package/runtime/dist/eval/fixtures.js +319 -0
  15. package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
  16. package/runtime/dist/eval/scorecard.js +285 -0
  17. package/runtime/dist/eval/sim.js +43 -0
  18. package/runtime/dist/src/cascaded-text-provider.js +31 -0
  19. package/runtime/dist/src/cli.js +96 -0
  20. package/runtime/dist/src/composition/assembly.js +352 -0
  21. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
  22. package/runtime/dist/src/composition/production-composition.js +389 -0
  23. package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
  24. package/runtime/dist/src/config/capability-registry.js +315 -0
  25. package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
  26. package/runtime/dist/src/config/coding-backends.js +8 -0
  27. package/runtime/dist/src/config/coding-profiles.js +98 -0
  28. package/runtime/dist/src/config/config.js +857 -0
  29. package/runtime/dist/src/config/diagnostics.js +139 -0
  30. package/runtime/dist/src/config/environment-contract.js +202 -0
  31. package/runtime/dist/src/config/self-hosted.js +23 -0
  32. package/runtime/dist/src/connectors/composio/client.js +195 -0
  33. package/runtime/dist/src/connectors/composio/google.js +208 -0
  34. package/runtime/dist/src/connectors/composio/index.js +334 -0
  35. package/runtime/dist/src/connectors/feishu/cli.js +220 -0
  36. package/runtime/dist/src/connectors/feishu/index.js +980 -0
  37. package/runtime/dist/src/connectors/macos/calendar.js +35 -0
  38. package/runtime/dist/src/connectors/macos/mail.js +32 -0
  39. package/runtime/dist/src/connectors/macos/reader.js +62 -0
  40. package/runtime/dist/src/conversation-voice-provider.js +41 -0
  41. package/runtime/dist/src/core/approval-port.js +9 -0
  42. package/runtime/dist/src/core/approval.js +1328 -0
  43. package/runtime/dist/src/core/calls.js +35 -0
  44. package/runtime/dist/src/core/camera-session.js +32 -0
  45. package/runtime/dist/src/core/causal-runtime.js +650 -0
  46. package/runtime/dist/src/core/clock.js +139 -0
  47. package/runtime/dist/src/core/context-view.js +156 -0
  48. package/runtime/dist/src/core/effects.js +62 -0
  49. package/runtime/dist/src/core/events.js +217 -0
  50. package/runtime/dist/src/core/executor-diagnostic.js +9 -0
  51. package/runtime/dist/src/core/ids.js +32 -0
  52. package/runtime/dist/src/core/media-store.js +104 -0
  53. package/runtime/dist/src/core/memory.js +296 -0
  54. package/runtime/dist/src/core/pending-decision.js +64 -0
  55. package/runtime/dist/src/core/ports.js +125 -0
  56. package/runtime/dist/src/core/runtime.js +1459 -0
  57. package/runtime/dist/src/core/schedule-tools.js +15 -0
  58. package/runtime/dist/src/core/sims.js +186 -0
  59. package/runtime/dist/src/core/slots.js +97 -0
  60. package/runtime/dist/src/core/source-processing-instructions.js +3 -0
  61. package/runtime/dist/src/core/source-processing-tools.js +12 -0
  62. package/runtime/dist/src/core/suggestions.js +143 -0
  63. package/runtime/dist/src/core/task-tools.js +22 -0
  64. package/runtime/dist/src/core/tool-schema.js +212 -0
  65. package/runtime/dist/src/core/trace.js +34 -0
  66. package/runtime/dist/src/core/work-tools.js +94 -0
  67. package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
  68. package/runtime/dist/src/desktop/desktop-camera.js +281 -0
  69. package/runtime/dist/src/desktop/desktop-control.js +140 -0
  70. package/runtime/dist/src/desktop/desktop-progress.js +162 -0
  71. package/runtime/dist/src/desktop/desktop-session.js +2106 -0
  72. package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
  73. package/runtime/dist/src/desktop/desktop-wire.js +605 -0
  74. package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
  75. package/runtime/dist/src/desktop/startup-error.js +18 -0
  76. package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
  77. package/runtime/dist/src/desktop-entry.js +106 -0
  78. package/runtime/dist/src/desktop.js +1092 -0
  79. package/runtime/dist/src/executors/acp/backends.js +105 -0
  80. package/runtime/dist/src/executors/acp/mcp.js +81 -0
  81. package/runtime/dist/src/executors/acp/preflight.js +14 -0
  82. package/runtime/dist/src/executors/acp/process-owner.js +112 -0
  83. package/runtime/dist/src/executors/acp/transport.js +760 -0
  84. package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
  85. package/runtime/dist/src/executors/agent-controller.js +244 -0
  86. package/runtime/dist/src/executors/autoglm.js +376 -0
  87. package/runtime/dist/src/executors/browser-device.js +102 -0
  88. package/runtime/dist/src/executors/browser.js +61 -0
  89. package/runtime/dist/src/executors/camera.js +101 -0
  90. package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
  91. package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
  92. package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
  93. package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
  94. package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
  95. package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
  96. package/runtime/dist/src/executors/codex/common.js +655 -0
  97. package/runtime/dist/src/executors/codex/contract.js +581 -0
  98. package/runtime/dist/src/executors/codex/controller.js +141 -0
  99. package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
  100. package/runtime/dist/src/executors/codex/factory.js +463 -0
  101. package/runtime/dist/src/executors/codex/host-config.js +238 -0
  102. package/runtime/dist/src/executors/codex/host.js +17 -0
  103. package/runtime/dist/src/executors/codex/index.js +19 -0
  104. package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
  105. package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
  106. package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
  107. package/runtime/dist/src/executors/codex/process-owner.js +398 -0
  108. package/runtime/dist/src/executors/codex/production-host.js +887 -0
  109. package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
  110. package/runtime/dist/src/executors/codex/protocol.js +581 -0
  111. package/runtime/dist/src/executors/codex/safe-json.js +87 -0
  112. package/runtime/dist/src/executors/codex/session-title.js +61 -0
  113. package/runtime/dist/src/executors/codex/shared-home.js +29 -0
  114. package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
  115. package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
  116. package/runtime/dist/src/executors/codex/version.js +38 -0
  117. package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
  118. package/runtime/dist/src/executors/coding/intake-model.js +103 -0
  119. package/runtime/dist/src/executors/coding/intake.js +824 -0
  120. package/runtime/dist/src/executors/coding/json-completion.js +14 -0
  121. package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
  122. package/runtime/dist/src/executors/coding/work-order.js +50 -0
  123. package/runtime/dist/src/executors/coding-executor.js +23 -0
  124. package/runtime/dist/src/executors/computer-backend.js +188 -0
  125. package/runtime/dist/src/executors/computer-device.js +187 -0
  126. package/runtime/dist/src/executors/computer-worker.js +125 -0
  127. package/runtime/dist/src/executors/computer.js +100 -0
  128. package/runtime/dist/src/executors/device-lock.js +127 -0
  129. package/runtime/dist/src/executors/frame-source.js +29 -0
  130. package/runtime/dist/src/executors/gui-evidence.js +30 -0
  131. package/runtime/dist/src/executors/gui-execution.js +237 -0
  132. package/runtime/dist/src/executors/gui-runner.js +88 -0
  133. package/runtime/dist/src/executors/host-executor-capability.js +12 -0
  134. package/runtime/dist/src/executors/index.js +13 -0
  135. package/runtime/dist/src/executors/mcp-client.js +198 -0
  136. package/runtime/dist/src/executors/mcp.js +210 -0
  137. package/runtime/dist/src/executors/mobile-android.js +180 -0
  138. package/runtime/dist/src/executors/mobile-ios.js +303 -0
  139. package/runtime/dist/src/executors/mobile.js +78 -0
  140. package/runtime/dist/src/executors/search-mcp.js +146 -0
  141. package/runtime/dist/src/executors/search.js +524 -0
  142. package/runtime/dist/src/executors/task-resources.js +38 -0
  143. package/runtime/dist/src/executors/vision/assess.js +296 -0
  144. package/runtime/dist/src/executors/vision/controller-core.js +373 -0
  145. package/runtime/dist/src/executors/vision/controller.js +164 -0
  146. package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
  147. package/runtime/dist/src/executors/vision.js +5 -0
  148. package/runtime/dist/src/executors/watcher.js +718 -0
  149. package/runtime/dist/src/http/bounded-response.js +37 -0
  150. package/runtime/dist/src/index.js +56 -0
  151. package/runtime/dist/src/knowledge/assembly.js +60 -0
  152. package/runtime/dist/src/knowledge/documents.js +520 -0
  153. package/runtime/dist/src/knowledge/embeddings.js +201 -0
  154. package/runtime/dist/src/knowledge/mcp.js +218 -0
  155. package/runtime/dist/src/knowledge/parse-worker.js +122 -0
  156. package/runtime/dist/src/knowledge/references.js +51 -0
  157. package/runtime/dist/src/knowledge/service.js +526 -0
  158. package/runtime/dist/src/knowledge/store-client.js +185 -0
  159. package/runtime/dist/src/knowledge/store-worker.js +843 -0
  160. package/runtime/dist/src/knowledge/types.js +2 -0
  161. package/runtime/dist/src/mcp/http-server.js +177 -0
  162. package/runtime/dist/src/mem0/resource.js +35 -0
  163. package/runtime/dist/src/mem0/store-worker.js +330 -0
  164. package/runtime/dist/src/memory/blackboard-session.js +205 -0
  165. package/runtime/dist/src/memory/blackboard-store.js +194 -0
  166. package/runtime/dist/src/memory/blackboard-worker.js +369 -0
  167. package/runtime/dist/src/memory/entry.js +39 -0
  168. package/runtime/dist/src/memory/factory.js +20 -0
  169. package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
  170. package/runtime/dist/src/memory/personal-memory.js +10 -0
  171. package/runtime/dist/src/memory/prerecall.js +20 -0
  172. package/runtime/dist/src/memory/provenance.js +17 -0
  173. package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
  174. package/runtime/dist/src/memory/retrieval.js +235 -0
  175. package/runtime/dist/src/memory/sensitivity.js +261 -0
  176. package/runtime/dist/src/memory-ledger/models.js +98 -0
  177. package/runtime/dist/src/memory-ledger/store-client.js +210 -0
  178. package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
  179. package/runtime/dist/src/memory-ledger/store.js +597 -0
  180. package/runtime/dist/src/memory-substrate/candidates.js +16 -0
  181. package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
  182. package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
  183. package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
  184. package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
  185. package/runtime/dist/src/memory-substrate/migration.js +87 -0
  186. package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
  187. package/runtime/dist/src/memory-substrate/purge.js +398 -0
  188. package/runtime/dist/src/memory-substrate/resolution.js +32 -0
  189. package/runtime/dist/src/memory-substrate/resource.js +867 -0
  190. package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
  191. package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
  192. package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
  193. package/runtime/dist/src/memory-substrate/source-state.js +93 -0
  194. package/runtime/dist/src/memory-substrate/store.js +534 -0
  195. package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
  196. package/runtime/dist/src/memory-substrate/workspace.js +21 -0
  197. package/runtime/dist/src/model/jev-client.js +25 -0
  198. package/runtime/dist/src/model/model-adapters.js +64 -0
  199. package/runtime/dist/src/model/model-gateway.js +399 -0
  200. package/runtime/dist/src/model/model-lane.js +34 -0
  201. package/runtime/dist/src/model/model-purpose.js +5 -0
  202. package/runtime/dist/src/model/personal-writer.js +361 -0
  203. package/runtime/dist/src/model/proactivity.js +72 -0
  204. package/runtime/dist/src/model/prompting.js +279 -0
  205. package/runtime/dist/src/model/task-verifier.js +217 -0
  206. package/runtime/dist/src/model/vision-capability.js +10 -0
  207. package/runtime/dist/src/news/feeds.js +114 -0
  208. package/runtime/dist/src/news/jev-ranking.js +25 -0
  209. package/runtime/dist/src/news/ranking.js +26 -0
  210. package/runtime/dist/src/news/service.js +262 -0
  211. package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
  212. package/runtime/dist/src/notifications/adapters/nova.js +15 -0
  213. package/runtime/dist/src/notifications/content.js +15 -0
  214. package/runtime/dist/src/notifications/contracts.js +9 -0
  215. package/runtime/dist/src/notifications/feed.js +8 -0
  216. package/runtime/dist/src/notifications/service.js +412 -0
  217. package/runtime/dist/src/notifications/store.js +4 -0
  218. package/runtime/dist/src/personal-agent/app-context.js +113 -0
  219. package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
  220. package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
  221. package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
  222. package/runtime/dist/src/personal-agent/contracts.js +32 -0
  223. package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
  224. package/runtime/dist/src/personal-agent/conversations.js +187 -0
  225. package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2403 -0
  227. package/runtime/dist/src/personal-agent/intake-task.js +37 -0
  228. package/runtime/dist/src/personal-agent/life.js +260 -0
  229. package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
  230. package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
  231. package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
  232. package/runtime/dist/src/personal-agent/project-digests.js +242 -0
  233. package/runtime/dist/src/personal-agent/sampling.js +20 -0
  234. package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
  235. package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
  236. package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
  237. package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
  238. package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
  239. package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
  240. package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
  241. package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
  242. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
  243. package/runtime/dist/src/personal-agent/source-priority.js +142 -0
  244. package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
  245. package/runtime/dist/src/personal-agent/source-walk.js +25 -0
  246. package/runtime/dist/src/personal-agent/sources.js +1484 -0
  247. package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
  248. package/runtime/dist/src/personal-agent/store.js +146 -0
  249. package/runtime/dist/src/personal-agent/task-loop.js +163 -0
  250. package/runtime/dist/src/personal-agent/tasks.js +920 -0
  251. package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
  252. package/runtime/dist/src/personal-agent/understanding.js +160 -0
  253. package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
  254. package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
  255. package/runtime/dist/src/projects/host-paths.js +133 -0
  256. package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
  257. package/runtime/dist/src/projects/project-confirmation.js +486 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +284 -0
  259. package/runtime/dist/src/projects/project-node-files.js +169 -0
  260. package/runtime/dist/src/projects/project-root-file.js +16 -0
  261. package/runtime/dist/src/projects/project-state.js +504 -0
  262. package/runtime/dist/src/projects/project-store-files.js +1271 -0
  263. package/runtime/dist/src/projects/project-store.js +1345 -0
  264. package/runtime/dist/src/realtime/aoq.js +141 -0
  265. package/runtime/dist/src/realtime/bridge.js +652 -0
  266. package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
  267. package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
  268. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
  269. package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
  270. package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
  271. package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
  272. package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
  273. package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
  274. package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
  275. package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
  276. package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
  277. package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
  278. package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
  279. package/runtime/dist/src/realtime/dictation.js +28 -0
  280. package/runtime/dist/src/realtime/evidence.js +276 -0
  281. package/runtime/dist/src/realtime/floor.js +43 -0
  282. package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
  283. package/runtime/dist/src/realtime/gemini.js +517 -0
  284. package/runtime/dist/src/realtime/history.js +122 -0
  285. package/runtime/dist/src/realtime/host-delivery.js +1711 -0
  286. package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
  287. package/runtime/dist/src/realtime/memory-board.js +105 -0
  288. package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
  289. package/runtime/dist/src/realtime/playback.js +242 -0
  290. package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
  291. package/runtime/dist/src/realtime/prompt-language.js +17 -0
  292. package/runtime/dist/src/realtime/protocol.js +428 -0
  293. package/runtime/dist/src/realtime/provider-projection.js +526 -0
  294. package/runtime/dist/src/realtime/provider-session.js +491 -0
  295. package/runtime/dist/src/realtime/qwen-transport.js +144 -0
  296. package/runtime/dist/src/realtime/qwen.js +1377 -0
  297. package/runtime/dist/src/realtime/recall.js +341 -0
  298. package/runtime/dist/src/realtime/service-ports.js +8 -0
  299. package/runtime/dist/src/realtime/service-state.js +259 -0
  300. package/runtime/dist/src/realtime/service.js +1726 -0
  301. package/runtime/dist/src/realtime/session-state.js +684 -0
  302. package/runtime/dist/src/realtime/session.js +1976 -0
  303. package/runtime/dist/src/realtime/speech-prep.js +63 -0
  304. package/runtime/dist/src/realtime/streaming-speech.js +120 -0
  305. package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
  306. package/runtime/dist/src/realtime/telemetry.js +144 -0
  307. package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
  308. package/runtime/dist/src/realtime/transport.js +8 -0
  309. package/runtime/dist/src/realtime/usage.js +55 -0
  310. package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
  311. package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
  312. package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
  313. package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
  314. package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
  315. package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
  316. package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
  317. package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
  318. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
  319. package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
  320. package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
  321. package/runtime/dist/src/server/aoq-chat-server.js +497 -0
  322. package/runtime/dist/src/server/client-pairing.js +192 -0
  323. package/runtime/dist/src/server/client-protocol.js +87 -0
  324. package/runtime/dist/src/server/client-server.js +312 -0
  325. package/runtime/dist/src/server/server-config.js +72 -0
  326. package/runtime/dist/src/server-entry.js +135 -0
  327. package/runtime/dist/src/storage/bounded-json.js +63 -0
  328. package/runtime/dist/src/storage/native-file-lock.js +8 -0
  329. package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
  330. package/runtime/dist/src/storage/private-database.js +120 -0
  331. package/runtime/dist/src/text/canonical-json.js +60 -0
  332. package/runtime/dist/src/text/python-number.js +18 -0
  333. package/runtime/dist/src/text/python-text.js +92 -0
  334. package/runtime/dist/src/text/unicode-casefold.js +29 -0
  335. package/runtime/dist/src/text/unicode-normalize.js +138 -0
  336. package/runtime/dist/src/text/unicode-tables.js +210 -0
  337. package/runtime/dist/src/understanding/candidates.js +77 -0
  338. package/runtime/dist/src/understanding/fixture.js +7 -0
  339. package/runtime/dist/src/understanding/jev.js +20 -0
  340. package/runtime/dist/src/understanding/pipeline.js +38 -0
  341. package/runtime/dist/src/voicemem/store-client.js +476 -0
  342. package/runtime/dist/src/voicemem/store-worker.js +380 -0
  343. package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
  344. package/runtime/scripts/pair-device.mjs +109 -0
  345. package/src/command.mjs +48 -0
@@ -0,0 +1,843 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, lstatSync } from 'node:fs';
3
+ import { isMainThread, parentPort, workerData } from 'node:worker_threads';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { SensitiveContentPolicy, SensitivePathPolicy } from '../memory/sensitivity.js';
6
+ import { preparePrivateDatabasePath, PrivateDatabaseError } from '../storage/private-database.js';
7
+ const MAX_SOURCE_BYTES = 10 * 1024 * 1024;
8
+ const MAX_CHUNKS = 20_000;
9
+ const DEFAULT_MAX_SOURCES = 100;
10
+ const MAX_JOBS = 256;
11
+ const RRF_K = 60;
12
+ class StoreError extends Error {
13
+ code;
14
+ constructor(code) {
15
+ super(code);
16
+ this.code = code;
17
+ }
18
+ }
19
+ if (isMainThread || parentPort === null)
20
+ throw new Error('knowledge store worker cannot run on the main thread');
21
+ const port = parentPort;
22
+ const data = parseWorkerData(workerData);
23
+ const paths = new SensitivePathPolicy();
24
+ const content = new SensitiveContentPolicy();
25
+ let database;
26
+ let ftsAvailable = false;
27
+ port.on('message', message => {
28
+ const request = parseRequest(message);
29
+ if (request === undefined) {
30
+ port.postMessage({ kind: 'protocol_error' });
31
+ return;
32
+ }
33
+ try {
34
+ const result = execute(request);
35
+ if (request.operation === 'close') {
36
+ port.close();
37
+ return;
38
+ }
39
+ port.postMessage({ kind: 'response', request_id: request.request_id, ok: true, result });
40
+ }
41
+ catch (error) {
42
+ if (request.operation === 'close') {
43
+ port.close();
44
+ return;
45
+ }
46
+ port.postMessage({ kind: 'response', request_id: request.request_id, ok: false, error_code: codeFor(error) });
47
+ }
48
+ });
49
+ function execute(request) {
50
+ switch (request.operation) {
51
+ case 'open': return open();
52
+ case 'close': return close();
53
+ case 'list_sources': return listSources();
54
+ case 'source_by_locator': {
55
+ const locator = boundedString(request.locator, 4096);
56
+ const row = db().prepare('SELECT * FROM sources WHERE locator=? ORDER BY updated_at DESC,id ASC LIMIT 1').get(locator);
57
+ return row ? sourceFrom(row) : null;
58
+ }
59
+ case 'list_chunks': return listChunks(request.source_id, request.offset);
60
+ case 'link_evidence': return linkEvidence(request.links);
61
+ case 'replace_source': return replaceSource(request.input);
62
+ case 'purge_evidence': return purgeEvidence(request.ids);
63
+ case 'remove_source': return removeSource(request.id);
64
+ case 'recall': return recall(request.query, request.vector, request.provider_id, request.k);
65
+ case 'unembedded_sources': return unembeddedSources(request.provider_id, request.dims);
66
+ case 'unembedded_chunks': return unembeddedChunks(request.source_id, request.provider_id, request.dims);
67
+ case 'set_vectors': return setVectors(request.input);
68
+ case 'get_chunk': return getChunk(request.locator);
69
+ case 'record_job': return recordJob(request.input);
70
+ case 'list_jobs': return listJobs();
71
+ default: throw new StoreError('STORE_INVALID_INPUT');
72
+ }
73
+ }
74
+ function open() {
75
+ if (database !== undefined)
76
+ throw new StoreError('STORE_ALREADY_OPEN');
77
+ ftsAvailable = false;
78
+ let opened;
79
+ try {
80
+ const path = preparePrivateDatabasePath(data.path);
81
+ opened = new DatabaseSync(path, { allowExtension: false, enableForeignKeyConstraints: true });
82
+ opened.exec('PRAGMA busy_timeout=1000; PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL');
83
+ opened.exec(`
84
+ CREATE TABLE IF NOT EXISTS sources (
85
+ id TEXT PRIMARY KEY, title TEXT NOT NULL, kind TEXT NOT NULL, locator TEXT NOT NULL,
86
+ mime TEXT NOT NULL, fingerprint TEXT NOT NULL, bytes INTEGER NOT NULL,
87
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, status TEXT NOT NULL
88
+ );
89
+ CREATE INDEX IF NOT EXISTS sources_locator ON sources(locator);
90
+ CREATE TABLE IF NOT EXISTS chunks (
91
+ id TEXT PRIMARY KEY, source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
92
+ heading_path TEXT NOT NULL, text TEXT NOT NULL, token_estimate INTEGER NOT NULL,
93
+ ordinal INTEGER NOT NULL, content_digest TEXT NOT NULL, legacy_digest TEXT
94
+ );
95
+ CREATE TABLE IF NOT EXISTS embeddings (
96
+ chunk_id TEXT PRIMARY KEY REFERENCES chunks(id) ON DELETE CASCADE,
97
+ provider_id TEXT NOT NULL, dims INTEGER NOT NULL, vector BLOB NOT NULL
98
+ );
99
+ CREATE TABLE IF NOT EXISTS jobs (
100
+ id TEXT PRIMARY KEY, source_id TEXT NOT NULL, state TEXT NOT NULL,
101
+ error_code TEXT, updated_at INTEGER NOT NULL
102
+ );
103
+ CREATE TABLE IF NOT EXISTS evidence_links (
104
+ chunk_id TEXT PRIMARY KEY REFERENCES chunks(id) ON DELETE CASCADE,
105
+ evidence_id TEXT NOT NULL
106
+ );
107
+ CREATE TABLE IF NOT EXISTS knowledge_suppressed (hash TEXT PRIMARY KEY);
108
+ CREATE TABLE IF NOT EXISTS knowledge_metadata (key TEXT PRIMARY KEY, value INTEGER NOT NULL);
109
+ INSERT OR IGNORE INTO knowledge_metadata(key, value) VALUES ('fts_dirty', 1);
110
+ CREATE INDEX IF NOT EXISTS chunks_source_idx ON chunks(source_id);
111
+ CREATE INDEX IF NOT EXISTS embeddings_model_idx ON embeddings(provider_id, dims);
112
+ CREATE INDEX IF NOT EXISTS jobs_updated_idx ON jobs(updated_at DESC, id DESC);
113
+ `);
114
+ migrateChunkDigests(opened);
115
+ ftsAvailable = enableFts(opened);
116
+ secureSidecar(path, '-wal');
117
+ secureSidecar(path, '-shm');
118
+ database = opened;
119
+ opened = undefined;
120
+ return { fts: ftsAvailable };
121
+ }
122
+ catch (error) {
123
+ try {
124
+ opened?.close();
125
+ }
126
+ catch { /* stable error only */ }
127
+ database = undefined;
128
+ ftsAvailable = false;
129
+ if (error instanceof StoreError)
130
+ throw error;
131
+ if (error instanceof PrivateDatabaseError)
132
+ throw new StoreError(error.code);
133
+ throw new StoreError('STORE_WRITE_FAILED');
134
+ }
135
+ }
136
+ /** Upgrade the original identity-tag schema without replacing rows or losing citations. */
137
+ function migrateChunkDigests(opened) {
138
+ if (opened.prepare('PRAGMA table_info(chunks)').all().some(row => row.name === 'content_digest'))
139
+ return;
140
+ try {
141
+ opened.exec(`BEGIN IMMEDIATE;
142
+ ALTER TABLE chunks ADD COLUMN ordinal INTEGER NOT NULL DEFAULT 0;
143
+ ALTER TABLE chunks ADD COLUMN content_digest TEXT NOT NULL DEFAULT '';
144
+ ALTER TABLE chunks ADD COLUMN legacy_digest TEXT;
145
+ `);
146
+ const rows = opened.prepare(`SELECT c.id, c.source_id, c.heading_path, c.text, s.title
147
+ FROM chunks c JOIN sources s ON s.id = c.source_id ORDER BY c.source_id, c.rowid`).all();
148
+ const update = opened.prepare('UPDATE chunks SET ordinal = ?, content_digest = ?, legacy_digest = ? WHERE id = ?');
149
+ let sourceId = '', ordinal = 0;
150
+ for (const row of rows) {
151
+ const source = textValue(row, 'source_id'), id = textValue(row, 'id');
152
+ if (source !== sourceId) {
153
+ sourceId = source;
154
+ ordinal = 0;
155
+ }
156
+ update.run(ordinal++, contentDigest(textValue(row, 'title'), textValue(row, 'heading_path'), textValue(row, 'text')), locatorDigest(source, id), id);
157
+ }
158
+ opened.exec('COMMIT');
159
+ }
160
+ catch (error) {
161
+ try {
162
+ opened.exec('ROLLBACK');
163
+ }
164
+ catch { /* no active transaction */ }
165
+ throw error;
166
+ }
167
+ }
168
+ function close() {
169
+ if (database === undefined)
170
+ return null;
171
+ const opened = database;
172
+ database = undefined;
173
+ try {
174
+ opened.close();
175
+ return null;
176
+ }
177
+ catch {
178
+ throw new StoreError('STORE_WRITE_FAILED');
179
+ }
180
+ }
181
+ function enableFts(opened) {
182
+ if (data.forceLexical || !supportsFts5(opened))
183
+ return false;
184
+ try {
185
+ opened.exec('BEGIN IMMEDIATE');
186
+ const exists = opened.prepare("SELECT 1 FROM sqlite_master WHERE name = 'chunks_fts'").get() !== undefined;
187
+ const dirty = opened.prepare("SELECT value FROM knowledge_metadata WHERE key = 'fts_dirty'").get()?.value !== 0;
188
+ opened.exec(`
189
+ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
190
+ chunk_id UNINDEXED, source_id UNINDEXED, text, heading_path
191
+ );
192
+ `);
193
+ if (!exists || dirty)
194
+ opened.exec(`
195
+ DELETE FROM chunks_fts;
196
+ INSERT INTO chunks_fts(chunk_id, source_id, text, heading_path)
197
+ SELECT id, source_id, text, heading_path FROM chunks;
198
+ UPDATE knowledge_metadata SET value = 0 WHERE key = 'fts_dirty';
199
+ `);
200
+ opened.exec('COMMIT');
201
+ return true;
202
+ }
203
+ catch {
204
+ try {
205
+ opened.exec('ROLLBACK');
206
+ }
207
+ catch { /* no active transaction */ }
208
+ return false;
209
+ }
210
+ }
211
+ function supportsFts5(opened) {
212
+ try {
213
+ opened.prepare('SELECT fts5(?) AS available').get('knowledge');
214
+ return true;
215
+ }
216
+ catch {
217
+ return false;
218
+ }
219
+ }
220
+ function listSources() {
221
+ return db().prepare(`
222
+ SELECT id, title, kind, locator, mime, fingerprint, bytes, created_at, updated_at, status
223
+ FROM sources ORDER BY updated_at DESC, id ASC
224
+ `).all().map(row => sourceFrom(row));
225
+ }
226
+ function listChunks(sourceValue, offsetValue) {
227
+ const sourceId = boundedString(sourceValue, 200), offset = nonnegativeInteger(offsetValue, MAX_CHUNKS);
228
+ return db().prepare(`SELECT c.id, c.source_id, c.text, c.ordinal, c.content_digest, s.locator, s.updated_at, l.evidence_id
229
+ FROM chunks c JOIN sources s ON s.id = c.source_id LEFT JOIN evidence_links l ON l.chunk_id = c.id
230
+ WHERE c.source_id = ? ORDER BY c.ordinal, c.id LIMIT 100 OFFSET ?`).all(sourceId, offset).map(value => {
231
+ const row = value;
232
+ return { chunk_id: textValue(row, 'id'), source_id: sourceId, text: textValue(row, 'text'), ordinal: numberValue(row, 'ordinal'),
233
+ locator: textValue(row, 'locator'), observed_at: new Date(numberValue(row, 'updated_at')).toISOString(), content_digest: textValue(row, 'content_digest'),
234
+ ...(typeof row.evidence_id === 'string' ? { evidence_id: row.evidence_id } : {}) };
235
+ });
236
+ }
237
+ function linkEvidence(value) {
238
+ if (!Array.isArray(value) || value.length > 100)
239
+ throw new StoreError('STORE_INVALID_INPUT');
240
+ const links = value.map(item => {
241
+ if (!isRecord(item))
242
+ throw new StoreError('STORE_INVALID_INPUT');
243
+ return { chunk_id: boundedString(item.chunk_id, 200), content_digest: boundedString(item.content_digest, 200), evidence_id: boundedString(item.evidence_id, 600) };
244
+ });
245
+ const opened = db();
246
+ try {
247
+ opened.exec('BEGIN IMMEDIATE');
248
+ for (const link of links) {
249
+ if (!opened.prepare('SELECT 1 FROM chunks WHERE id = ? AND content_digest = ?').get(link.chunk_id, link.content_digest))
250
+ throw new StoreError('STORE_WRITE_FAILED');
251
+ opened.prepare('INSERT INTO evidence_links(chunk_id,evidence_id) VALUES (?,?) ON CONFLICT(chunk_id) DO UPDATE SET evidence_id=excluded.evidence_id').run(link.chunk_id, link.evidence_id);
252
+ }
253
+ opened.exec('COMMIT');
254
+ return null;
255
+ }
256
+ catch (error) {
257
+ try {
258
+ opened.exec('ROLLBACK');
259
+ }
260
+ catch { /* no active transaction */ }
261
+ throw error;
262
+ }
263
+ }
264
+ /** Chunks without a vector from this provider, so a scan can commit lexically and embed later. */
265
+ function unembeddedSources(providerValue, dimsValue) {
266
+ const providerId = boundedString(providerValue, 160), dims = positiveInteger(dimsValue, 4096);
267
+ return db().prepare(`SELECT DISTINCT c.source_id FROM chunks c LEFT JOIN embeddings e ON e.chunk_id = c.id AND e.provider_id = ? AND e.dims = ?
268
+ WHERE e.chunk_id IS NULL LIMIT 1000`).all(providerId, dims).map(row => textValue(row, 'source_id'));
269
+ }
270
+ function unembeddedChunks(sourceValue, providerValue, dimsValue) {
271
+ const sourceId = boundedString(sourceValue, 200), providerId = boundedString(providerValue, 160), dims = positiveInteger(dimsValue, 4096);
272
+ const opened = db(), source = opened.prepare('SELECT fingerprint FROM sources WHERE id = ?').get(sourceId);
273
+ if (source === undefined)
274
+ return { fingerprint: null, chunks: [] };
275
+ const chunks = opened.prepare(`SELECT c.id, c.content_digest, c.text, l.evidence_id FROM chunks c
276
+ LEFT JOIN embeddings e ON e.chunk_id = c.id AND e.provider_id = ? AND e.dims = ? LEFT JOIN evidence_links l ON l.chunk_id = c.id
277
+ WHERE c.source_id = ? AND e.chunk_id IS NULL ORDER BY c.ordinal, c.id LIMIT 100`).all(providerId, dims, sourceId).map(row => ({
278
+ chunk_id: textValue(row, 'id'), content_digest: textValue(row, 'content_digest'), text: textValue(row, 'text'),
279
+ ...(typeof row.evidence_id === 'string' ? { evidence_id: row.evidence_id } : {})
280
+ }));
281
+ return { fingerprint: textValue(source, 'fingerprint'), chunks };
282
+ }
283
+ /** Writes only while the source fingerprint and each chunk digest still match what was embedded. */
284
+ function setVectors(value) {
285
+ if (!isRecord(value) || !Array.isArray(value.vectors) || value.vectors.length > 100)
286
+ throw new StoreError('STORE_INVALID_INPUT');
287
+ const sourceId = boundedString(value.source_id, 200), fingerprint = boundedString(value.fingerprint, 200);
288
+ const providerId = boundedString(value.provider_id, 160), dims = positiveInteger(value.dims, 4096);
289
+ const vectors = value.vectors.map(item => {
290
+ if (!isRecord(item))
291
+ throw new StoreError('STORE_INVALID_INPUT');
292
+ const vector = numericVector(item.vector);
293
+ if (vector.length !== dims)
294
+ throw new StoreError('STORE_INVALID_INPUT');
295
+ return { chunk_id: boundedString(item.chunk_id, 200), content_digest: boundedString(item.content_digest, 200), vector };
296
+ });
297
+ const opened = db();
298
+ try {
299
+ opened.exec('BEGIN IMMEDIATE');
300
+ let written = 0;
301
+ if (opened.prepare('SELECT 1 FROM sources WHERE id = ? AND fingerprint = ?').get(sourceId, fingerprint)) {
302
+ const matches = opened.prepare('SELECT 1 FROM chunks WHERE id = ? AND source_id = ? AND content_digest = ?');
303
+ const write = opened.prepare('INSERT INTO embeddings(chunk_id, provider_id, dims, vector) VALUES (?, ?, ?, ?) ON CONFLICT(chunk_id) DO UPDATE SET provider_id = excluded.provider_id, dims = excluded.dims, vector = excluded.vector');
304
+ for (const item of vectors)
305
+ if (matches.get(item.chunk_id, sourceId, item.content_digest)) {
306
+ write.run(item.chunk_id, providerId, dims, vectorBlob(item.vector));
307
+ written++;
308
+ }
309
+ }
310
+ opened.exec('COMMIT');
311
+ return written;
312
+ }
313
+ catch (error) {
314
+ try {
315
+ opened.exec('ROLLBACK');
316
+ }
317
+ catch { /* no active transaction */ }
318
+ if (error instanceof StoreError)
319
+ throw error;
320
+ throw new StoreError('STORE_WRITE_FAILED');
321
+ }
322
+ }
323
+ function evidenceLink(chunkId) {
324
+ const row = db().prepare('SELECT evidence_id FROM evidence_links WHERE chunk_id = ?').get(chunkId);
325
+ return typeof row?.evidence_id === 'string' ? { evidence_id: row.evidence_id } : {};
326
+ }
327
+ function replaceSource(value) {
328
+ const input = parseReplaceInput(value);
329
+ const opened = db();
330
+ try {
331
+ opened.exec('BEGIN IMMEDIATE');
332
+ const retiredId = input.replaces_source_id && input.replaces_source_id !== input.source.id ? input.replaces_source_id : undefined;
333
+ const retiring = retiredId ? opened.prepare('SELECT locator FROM sources WHERE id = ?').get(retiredId) : undefined;
334
+ if (retiredId && retiring?.locator !== input.source.locator)
335
+ throw new StoreError('STORE_INVALID_INPUT');
336
+ const sourceExists = opened.prepare('SELECT 1 AS present FROM sources WHERE id = ?').get(input.source.id);
337
+ const sourceCount = numberValue(opened.prepare('SELECT COUNT(*) AS count FROM sources').get(), 'count');
338
+ if (sourceCount - Number(!!retiredId) + Number(sourceExists === undefined) > data.maxSources)
339
+ throw new StoreError('STORE_CAPACITY');
340
+ const oldCount = numberValue(opened.prepare('SELECT COUNT(*) AS count FROM chunks WHERE source_id = ?').get(input.source.id), 'count')
341
+ + (retiredId ? numberValue(opened.prepare('SELECT COUNT(*) AS count FROM chunks WHERE source_id = ?').get(retiredId), 'count') : 0);
342
+ const totalCount = numberValue(opened.prepare('SELECT COUNT(*) AS count FROM chunks').get(), 'count');
343
+ if (totalCount - oldCount + input.chunks.length > MAX_CHUNKS)
344
+ throw new StoreError('STORE_CAPACITY');
345
+ const previous = new Map(opened.prepare('SELECT id, ordinal, content_digest, legacy_digest FROM chunks WHERE source_id = ? ORDER BY ordinal').all(input.source.id).map(row => [numberValue(row, 'ordinal'), row]));
346
+ if (ftsAvailable)
347
+ opened.prepare('DELETE FROM chunks_fts WHERE source_id = ?').run(input.source.id);
348
+ else
349
+ opened.exec("UPDATE knowledge_metadata SET value = 1 WHERE key = 'fts_dirty'");
350
+ if (retiredId) {
351
+ if (ftsAvailable)
352
+ opened.prepare('DELETE FROM chunks_fts WHERE source_id = ?').run(retiredId);
353
+ opened.prepare('DELETE FROM sources WHERE id = ?').run(retiredId);
354
+ }
355
+ opened.prepare('DELETE FROM sources WHERE id = ?').run(input.source.id);
356
+ opened.prepare(`
357
+ INSERT INTO sources(id, title, kind, locator, mime, fingerprint, bytes, created_at, updated_at, status)
358
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
359
+ `).run(input.source.id, input.source.title, input.source.kind, input.source.locator, input.source.mime, input.source.fingerprint, input.source.bytes, input.source.created_at, input.source.updated_at, input.source.status);
360
+ const chunkStatement = opened.prepare(`
361
+ INSERT INTO chunks(id, source_id, heading_path, text, token_estimate, ordinal, content_digest, legacy_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
362
+ `);
363
+ const embeddingStatement = opened.prepare(`
364
+ INSERT INTO embeddings(chunk_id, provider_id, dims, vector) VALUES (?, ?, ?, ?)
365
+ `);
366
+ const ftsStatement = ftsAvailable ? opened.prepare(`
367
+ INSERT INTO chunks_fts(chunk_id, source_id, text, heading_path) VALUES (?, ?, ?, ?)
368
+ `) : undefined;
369
+ // ponytail: ordinal correspondence; use semantic matching only if stable section tracking is required.
370
+ for (const [ordinal, chunk] of input.chunks.entries()) {
371
+ if ((chunk.evidence_id && opened.prepare('SELECT 1 FROM knowledge_suppressed WHERE hash=?').get(purgeHash(chunk.evidence_id))) || opened.prepare('SELECT 1 FROM knowledge_suppressed WHERE hash=?').get(purgeHash(input.source.id + '\0' + chunk.text)))
372
+ continue;
373
+ const old = previous.get(ordinal);
374
+ const id = old === undefined ? randomUUID() : textValue(old, 'id');
375
+ const digest = contentDigest(input.source.title, chunk.heading_path, chunk.text);
376
+ const legacy = old?.content_digest === digest ? old.legacy_digest ?? null : null;
377
+ chunkStatement.run(id, input.source.id, chunk.heading_path, chunk.text, chunk.token_estimate, ordinal, digest, legacy);
378
+ if (chunk.evidence_id)
379
+ opened.prepare('INSERT INTO evidence_links(chunk_id,evidence_id) VALUES (?,?)').run(id, chunk.evidence_id);
380
+ if (chunk.vector !== null)
381
+ embeddingStatement.run(id, input.provider_id, input.dims, vectorBlob(chunk.vector));
382
+ ftsStatement?.run(id, input.source.id, chunk.text, chunk.heading_path);
383
+ }
384
+ opened.exec('COMMIT');
385
+ return null;
386
+ }
387
+ catch (error) {
388
+ try {
389
+ opened.exec('ROLLBACK');
390
+ }
391
+ catch { /* no active transaction */ }
392
+ if (error instanceof StoreError)
393
+ throw error;
394
+ throw new StoreError('STORE_WRITE_FAILED');
395
+ }
396
+ }
397
+ function purgeHash(value) { return createHash('sha256').update(value).digest('hex'); }
398
+ /** Persist the fence and remove all managed copies atomically; every retry compacts again. */
399
+ function purgeEvidence(value) {
400
+ if (!Array.isArray(value) || value.length > 4096)
401
+ throw new StoreError('STORE_INVALID_INPUT');
402
+ const ids = [...new Set(value.map(id => boundedString(id, 600)))], opened = db();
403
+ opened.exec('PRAGMA secure_delete=ON; BEGIN IMMEDIATE');
404
+ try {
405
+ for (const id of ids) {
406
+ opened.prepare('INSERT OR IGNORE INTO knowledge_suppressed VALUES(?)').run(purgeHash(id));
407
+ const chunks = opened.prepare('SELECT c.id,c.source_id,c.text FROM chunks c JOIN evidence_links e ON e.chunk_id=c.id WHERE e.evidence_id=?').all(id);
408
+ for (const chunk of chunks) {
409
+ opened.prepare('INSERT OR IGNORE INTO knowledge_suppressed VALUES(?)').run(purgeHash(String(chunk.source_id) + '\0' + String(chunk.text)));
410
+ // Even a lexical-only worker must clean an existing FTS copy created by a prior runtime.
411
+ if (opened.prepare("SELECT 1 FROM sqlite_master WHERE name='chunks_fts'").get())
412
+ opened.prepare('DELETE FROM chunks_fts WHERE chunk_id=?').run(String(chunk.id));
413
+ opened.prepare('DELETE FROM chunks WHERE id=?').run(String(chunk.id));
414
+ }
415
+ }
416
+ opened.exec('COMMIT');
417
+ }
418
+ catch (error) {
419
+ try {
420
+ opened.exec('ROLLBACK');
421
+ }
422
+ catch { /* preserve failure */ }
423
+ throw error;
424
+ }
425
+ // FTS internal segments retain deleted tokens until merged; rebuild contains only surviving chunks.
426
+ if (opened.prepare("SELECT 1 FROM sqlite_master WHERE name='chunks_fts'").get()) {
427
+ opened.exec("DROP TABLE chunks_fts; CREATE VIRTUAL TABLE chunks_fts USING fts5(chunk_id UNINDEXED,source_id UNINDEXED,text,heading_path); INSERT INTO chunks_fts(chunk_id,source_id,text,heading_path) SELECT id,source_id,text,heading_path FROM chunks");
428
+ }
429
+ const checkpoint = opened.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
430
+ if (checkpoint && Number(checkpoint.busy) > 0)
431
+ throw new StoreError('STORE_WRITE_FAILED');
432
+ opened.exec('VACUUM');
433
+ const after = opened.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
434
+ if (after && Number(after.busy) > 0)
435
+ throw new StoreError('STORE_WRITE_FAILED');
436
+ return null;
437
+ }
438
+ function removeSource(value) {
439
+ const id = boundedString(value, 200);
440
+ const opened = db();
441
+ try {
442
+ opened.exec('BEGIN IMMEDIATE');
443
+ if (ftsAvailable)
444
+ opened.prepare('DELETE FROM chunks_fts WHERE source_id = ?').run(id);
445
+ else
446
+ opened.exec("UPDATE knowledge_metadata SET value = 1 WHERE key = 'fts_dirty'");
447
+ opened.prepare('DELETE FROM sources WHERE id = ?').run(id);
448
+ opened.exec('COMMIT');
449
+ return null;
450
+ }
451
+ catch {
452
+ try {
453
+ opened.exec('ROLLBACK');
454
+ }
455
+ catch { /* no active transaction */ }
456
+ throw new StoreError('STORE_WRITE_FAILED');
457
+ }
458
+ }
459
+ function recall(queryValue, vectorValue, providerValue, kValue) {
460
+ const query = boundedString(queryValue, 512);
461
+ const vector = numericVector(vectorValue);
462
+ const providerId = boundedString(providerValue, 160);
463
+ const k = positiveInteger(kValue, 5);
464
+ if (k > 5 || vector.length > 4096)
465
+ throw new StoreError('STORE_INVALID_INPUT');
466
+ const opened = db();
467
+ const dims = vector.length;
468
+ const candidates = new Map();
469
+ const vectors = opened.prepare(`
470
+ SELECT c.id, c.source_id, c.content_digest, s.title, c.heading_path, c.text, e.vector
471
+ FROM chunks c JOIN sources s ON s.id = c.source_id JOIN embeddings e ON e.chunk_id = c.id
472
+ WHERE e.provider_id = ? AND e.dims = ?
473
+ `).all(providerId, dims);
474
+ const scored = vectors.map(row => ({ row, score: cosine(vector, blobVector(row.vector ?? null, dims)) }))
475
+ .sort((left, right) => right.score - left.score || textValue(left.row, 'source_id').localeCompare(textValue(right.row, 'source_id')) || textValue(left.row, 'id').localeCompare(textValue(right.row, 'id')))
476
+ .slice(0, 50);
477
+ for (const [index, candidate] of scored.entries()) {
478
+ candidates.set(textValue(candidate.row, 'id'), { row: candidate.row, vectorRank: index + 1 });
479
+ }
480
+ for (const [index, row] of lexicalCandidates(opened, query).entries()) {
481
+ const id = textValue(row, 'id');
482
+ candidates.set(id, { ...candidates.get(id), row, lexicalRank: index + 1 });
483
+ }
484
+ if (candidates.size === 0)
485
+ return [];
486
+ return [...candidates.values()]
487
+ .map(ranks => {
488
+ const { row } = ranks;
489
+ const score = (ranks.vectorRank === undefined ? 0 : 1 / (RRF_K + ranks.vectorRank))
490
+ + (ranks.lexicalRank === undefined ? 0 : 1 / (RRF_K + ranks.lexicalRank));
491
+ return hitFrom(row, score);
492
+ })
493
+ .sort((left, right) => right.score - left.score || left.source_id.localeCompare(right.source_id) || left.locator.localeCompare(right.locator))
494
+ .slice(0, k);
495
+ }
496
+ function getChunk(value) {
497
+ const parsed = parseLocator(boundedString(value, 600));
498
+ if (parsed === undefined)
499
+ return { status: 'gone' };
500
+ const row = db().prepare(`
501
+ SELECT c.id, c.source_id, c.content_digest, c.legacy_digest, c.heading_path, c.text, s.title
502
+ FROM chunks c JOIN sources s ON s.id = c.source_id WHERE c.id = ? AND c.source_id = ?
503
+ `).get(parsed.chunkId, parsed.sourceId);
504
+ if (row === undefined)
505
+ return { status: 'gone' };
506
+ return {
507
+ ...evidenceLink(textValue(row, 'id')),
508
+ status: textValue(row, 'content_digest').slice(0, 12) === parsed.digest || row.legacy_digest === parsed.digest ? 'ok' : 'stale', text: redactOutput(textValue(row, 'text')), title: redactOutput(textValue(row, 'title')),
509
+ heading_path: redactOutput(textValue(row, 'heading_path')), source_id: textValue(row, 'source_id'),
510
+ };
511
+ }
512
+ function recordJob(value) {
513
+ const job = parseJob(value);
514
+ const opened = db();
515
+ try {
516
+ opened.exec('BEGIN IMMEDIATE');
517
+ opened.prepare(`
518
+ INSERT INTO jobs(id, source_id, state, error_code, updated_at) VALUES (?, ?, ?, ?, ?)
519
+ ON CONFLICT(id) DO UPDATE SET source_id = excluded.source_id, state = excluded.state,
520
+ error_code = excluded.error_code, updated_at = excluded.updated_at
521
+ `).run(job.id, job.source_id, job.state, job.error_code, job.updated_at);
522
+ opened.prepare(`
523
+ DELETE FROM jobs WHERE id IN (
524
+ SELECT id FROM jobs ORDER BY updated_at DESC, id ASC LIMIT -1 OFFSET ?
525
+ )
526
+ `).run(MAX_JOBS);
527
+ opened.exec('COMMIT');
528
+ return null;
529
+ }
530
+ catch {
531
+ try {
532
+ opened.exec('ROLLBACK');
533
+ }
534
+ catch { /* no active transaction */ }
535
+ throw new StoreError('STORE_WRITE_FAILED');
536
+ }
537
+ }
538
+ function listJobs() {
539
+ return db().prepare(`SELECT id, source_id, state, error_code, updated_at FROM jobs ORDER BY updated_at DESC, id ASC`).all()
540
+ .map(row => jobFrom(row));
541
+ }
542
+ function parseReplaceInput(value) {
543
+ if (!isRecord(value) || !isRecord(value.source) || !Array.isArray(value.chunks))
544
+ throw new StoreError('STORE_INVALID_INPUT');
545
+ const source = parseSource(value.source);
546
+ const providerId = screenContent(boundedString(value.provider_id, 160));
547
+ const dims = positiveInteger(value.dims, 4096);
548
+ const chunks = value.chunks.map(parseChunk);
549
+ for (const chunk of chunks)
550
+ if (chunk.vector !== null && chunk.vector.length !== dims)
551
+ throw new StoreError('STORE_INVALID_INPUT');
552
+ const replacesSourceId = value.replaces_source_id === undefined ? undefined : boundedString(value.replaces_source_id, 200);
553
+ return { source, chunks, provider_id: providerId, dims, ...(replacesSourceId ? { replaces_source_id: replacesSourceId } : {}) };
554
+ }
555
+ function parseSource(value) {
556
+ const kind = value.kind;
557
+ if (kind !== 'file' && kind !== 'url' && kind !== 'folder_child')
558
+ throw new StoreError('STORE_INVALID_INPUT');
559
+ const locator = boundedString(value.locator, 4096);
560
+ if (kind === 'file' || kind === 'folder_child') {
561
+ if (!paths.allows(locator))
562
+ throw new StoreError('STORE_SENSITIVE_PATH_DENIED');
563
+ }
564
+ else {
565
+ try {
566
+ new URL(locator);
567
+ }
568
+ catch {
569
+ throw new StoreError('STORE_INVALID_INPUT');
570
+ }
571
+ }
572
+ return {
573
+ id: screenContent(boundedString(value.id, 200)), title: screenContent(boundedString(value.title, 512)),
574
+ kind, locator: screenContent(locator), mime: screenContent(boundedString(value.mime, 200)),
575
+ fingerprint: screenContent(boundedString(value.fingerprint, 200)), bytes: nonnegativeInteger(value.bytes, MAX_SOURCE_BYTES),
576
+ created_at: nonnegativeInteger(value.created_at, Number.MAX_SAFE_INTEGER),
577
+ updated_at: nonnegativeInteger(value.updated_at, Number.MAX_SAFE_INTEGER),
578
+ status: value.status === 'ready' || value.status === 'failed' ? value.status : invalid(),
579
+ };
580
+ }
581
+ function parseChunk(value) {
582
+ if (!isRecord(value))
583
+ throw new StoreError('STORE_INVALID_INPUT');
584
+ return {
585
+ heading_path: screenContent(boundedString(value.heading_path, 1024)),
586
+ ...(value.evidence_id === undefined ? {} : { evidence_id: boundedString(value.evidence_id, 600) }),
587
+ text: screenContent(boundedCodePoints(value.text, 3200)),
588
+ token_estimate: nonnegativeInteger(value.token_estimate, 1_000_000),
589
+ vector: value.vector === null ? null : numericVector(value.vector),
590
+ };
591
+ }
592
+ function parseJob(value) {
593
+ if (!isRecord(value))
594
+ throw new StoreError('STORE_INVALID_INPUT');
595
+ const state = value.state;
596
+ if (state !== 'running' && state !== 'complete' && state !== 'failed')
597
+ throw new StoreError('STORE_INVALID_INPUT');
598
+ const error = value.error_code;
599
+ if (error !== null && typeof error !== 'string')
600
+ throw new StoreError('STORE_INVALID_INPUT');
601
+ return {
602
+ id: screenContent(boundedString(value.id, 200)), source_id: screenContent(boundedString(value.source_id, 200)),
603
+ state, error_code: error === null ? null : screenContent(boundedString(error, 200)),
604
+ updated_at: nonnegativeInteger(value.updated_at, Number.MAX_SAFE_INTEGER),
605
+ };
606
+ }
607
+ function sourceFrom(row) {
608
+ const kind = textValue(row, 'kind');
609
+ const status = textValue(row, 'status');
610
+ if ((kind !== 'file' && kind !== 'url' && kind !== 'folder_child') || (status !== 'ready' && status !== 'failed'))
611
+ throw new StoreError('STORE_READ_FAILED');
612
+ return {
613
+ id: textValue(row, 'id'), title: redactOutput(textValue(row, 'title')), kind, locator: textValue(row, 'locator'),
614
+ mime: textValue(row, 'mime'), fingerprint: textValue(row, 'fingerprint'), bytes: numberValue(row, 'bytes'),
615
+ created_at: numberValue(row, 'created_at'), updated_at: numberValue(row, 'updated_at'), status,
616
+ };
617
+ }
618
+ function jobFrom(row) {
619
+ const state = textValue(row, 'state');
620
+ if (state !== 'running' && state !== 'complete' && state !== 'failed')
621
+ throw new StoreError('STORE_READ_FAILED');
622
+ const error = row.error_code;
623
+ if (error !== null && typeof error !== 'string')
624
+ throw new StoreError('STORE_READ_FAILED');
625
+ return { id: textValue(row, 'id'), source_id: textValue(row, 'source_id'), state, error_code: error, updated_at: numberValue(row, 'updated_at') };
626
+ }
627
+ function hitFrom(row, score) {
628
+ const sourceId = textValue(row, 'source_id');
629
+ const id = textValue(row, 'id');
630
+ return {
631
+ ...evidenceLink(id),
632
+ locator: `knowledge://${sourceId}/${id}?d=${textValue(row, 'content_digest').slice(0, 12)}`,
633
+ source_id: sourceId, title: redactOutput(textValue(row, 'title')), heading_path: redactOutput(textValue(row, 'heading_path')),
634
+ text: redactOutput(truncateCodePoints(textValue(row, 'text'), 600)), score,
635
+ };
636
+ }
637
+ function db() {
638
+ if (database === undefined)
639
+ throw new StoreError('STORE_CLOSED');
640
+ return database;
641
+ }
642
+ function parseWorkerData(value) {
643
+ if (!isRecord(value) || typeof value.path !== 'string')
644
+ throw new Error('invalid knowledge worker data');
645
+ const maxSources = value.maxSources === undefined ? DEFAULT_MAX_SOURCES : positiveInteger(value.maxSources, MAX_CHUNKS);
646
+ if (value.forceLexical !== undefined && typeof value.forceLexical !== 'boolean')
647
+ throw new Error('invalid knowledge worker data');
648
+ return { path: value.path, maxSources, forceLexical: value.forceLexical === true };
649
+ }
650
+ function parseRequest(value) {
651
+ if (!isRecord(value) || value.kind !== 'request' || !positiveInteger(value.request_id, Number.MAX_SAFE_INTEGER) || typeof value.operation !== 'string')
652
+ return undefined;
653
+ return value;
654
+ }
655
+ function codeFor(error) {
656
+ return error instanceof StoreError ? error.code : 'STORE_WRITE_FAILED';
657
+ }
658
+ function screenContent(value) {
659
+ if (content.scrub('knowledge', value).kind !== 'clean')
660
+ throw new StoreError('STORE_SENSITIVE_CONTENT_REJECTED');
661
+ if (paths.scrubText('knowledge', value).kind !== 'clean')
662
+ throw new StoreError('STORE_SENSITIVE_PATH_DENIED');
663
+ return value;
664
+ }
665
+ function boundedString(value, max) {
666
+ if (typeof value !== 'string' || value.length === 0 || value.length > max)
667
+ throw new StoreError('STORE_INVALID_INPUT');
668
+ return value;
669
+ }
670
+ function boundedCodePoints(value, max) {
671
+ const text = boundedString(value, max * 2);
672
+ if ([...text].length > max)
673
+ throw new StoreError('STORE_INVALID_INPUT');
674
+ return text;
675
+ }
676
+ function nonnegativeInteger(value, max) {
677
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > max)
678
+ throw new StoreError('STORE_INVALID_INPUT');
679
+ return value;
680
+ }
681
+ function positiveInteger(value, max) {
682
+ const integer = nonnegativeInteger(value, max);
683
+ if (integer === 0)
684
+ throw new StoreError('STORE_INVALID_INPUT');
685
+ return integer;
686
+ }
687
+ function numericVector(value) {
688
+ if (!Array.isArray(value) || value.length === 0 || value.length > 4096)
689
+ throw new StoreError('STORE_INVALID_INPUT');
690
+ const vector = value.map(item => {
691
+ if (typeof item !== 'number' || !Number.isFinite(item))
692
+ throw new StoreError('STORE_INVALID_INPUT');
693
+ const float = Math.fround(item);
694
+ if (!Number.isFinite(float))
695
+ throw new StoreError('STORE_INVALID_INPUT');
696
+ return float;
697
+ });
698
+ if (!vector.some(item => item !== 0))
699
+ throw new StoreError('STORE_INVALID_INPUT');
700
+ return vector;
701
+ }
702
+ function vectorBlob(vector) {
703
+ const blob = Buffer.allocUnsafe(vector.length * 4);
704
+ vector.forEach((value, index) => blob.writeFloatLE(value, index * 4));
705
+ return blob;
706
+ }
707
+ function blobVector(value, dims) {
708
+ if (!(value instanceof Uint8Array) || value.byteLength !== dims * 4)
709
+ throw new StoreError('STORE_READ_FAILED');
710
+ const blob = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
711
+ const vector = Array.from({ length: dims }, (_item, index) => blob.readFloatLE(index * 4));
712
+ if (!vector.every(Number.isFinite))
713
+ throw new StoreError('STORE_READ_FAILED');
714
+ return vector;
715
+ }
716
+ function cosine(left, right) {
717
+ let dot = 0;
718
+ let leftNorm = 0;
719
+ let rightNorm = 0;
720
+ for (let index = 0; index < left.length; index += 1) {
721
+ const a = left[index];
722
+ const b = right[index];
723
+ dot += a * b;
724
+ leftNorm += a * a;
725
+ rightNorm += b * b;
726
+ }
727
+ return leftNorm === 0 || rightNorm === 0 ? -1 : dot / Math.sqrt(leftNorm * rightNorm);
728
+ }
729
+ function safeFtsQuery(query) {
730
+ return lexicalTerms(query).map(token => `"${token.replaceAll('"', '""')}"`).join(' ');
731
+ }
732
+ function lexicalTerms(query) {
733
+ return [...new Set(query.match(/[\p{L}\p{N}_]+/gu) ?? [])].slice(0, 24);
734
+ }
735
+ function lexicalCandidates(opened, query) {
736
+ const terms = lexicalTerms(query);
737
+ if (terms.length === 0)
738
+ return [];
739
+ if (ftsAvailable) {
740
+ return opened.prepare(`
741
+ SELECT c.id, c.source_id, c.content_digest, s.title, c.heading_path, c.text
742
+ FROM chunks_fts f JOIN chunks c ON c.id = f.chunk_id JOIN sources s ON s.id = c.source_id
743
+ WHERE chunks_fts MATCH ?
744
+ ORDER BY bm25(chunks_fts), f.chunk_id ASC LIMIT 50
745
+ `).all(safeFtsQuery(query));
746
+ }
747
+ const clauses = terms.map(() => '(c.text LIKE ? ESCAPE \'\\\' OR c.heading_path LIKE ? ESCAPE \'\\\')').join(' AND ');
748
+ const values = terms.flatMap(term => {
749
+ const pattern = `%${term.replace(/[\\%_]/gu, character => `\\${character}`)}%`;
750
+ return [pattern, pattern];
751
+ });
752
+ return opened.prepare(`
753
+ SELECT c.id, c.source_id, c.content_digest, s.title, c.heading_path, c.text
754
+ FROM chunks c JOIN sources s ON s.id = c.source_id
755
+ WHERE ${clauses}
756
+ ORDER BY c.source_id ASC, c.id ASC LIMIT 50
757
+ `).all(...values);
758
+ }
759
+ function contentDigest(title, heading, text) {
760
+ return createHash('sha256').update(JSON.stringify([title, heading, text])).digest('hex');
761
+ }
762
+ function locatorDigest(sourceId, chunkId) {
763
+ return createHash('sha256').update(`${sourceId}:${chunkId}`).digest('hex').slice(0, 12);
764
+ }
765
+ function parseLocator(locator) {
766
+ try {
767
+ const url = new URL(locator);
768
+ const chunkId = url.pathname.slice(1);
769
+ const digest = url.searchParams.get('d');
770
+ if (url.protocol !== 'knowledge:' || url.username !== '' || url.password !== '' || url.port !== '' || !url.hostname || !chunkId || digest === null)
771
+ return undefined;
772
+ return { sourceId: url.hostname, chunkId, digest };
773
+ }
774
+ catch {
775
+ return undefined;
776
+ }
777
+ }
778
+ function textValue(row, key) {
779
+ const value = row[key];
780
+ if (typeof value !== 'string')
781
+ throw new StoreError('STORE_READ_FAILED');
782
+ return value;
783
+ }
784
+ function numberValue(row, key) {
785
+ const value = row[key];
786
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
787
+ throw new StoreError('STORE_READ_FAILED');
788
+ return value;
789
+ }
790
+ function truncateCodePoints(value, max) {
791
+ return [...value].slice(0, max).join('');
792
+ }
793
+ function secureSidecar(databasePath, suffix) {
794
+ const path = `${databasePath}${suffix}`;
795
+ try {
796
+ const info = lstatSync(path);
797
+ if (info.isSymbolicLink() || !info.isFile() || !ownedByCurrentUser(info.uid))
798
+ throw new StoreError('STORE_WRITE_FAILED');
799
+ // SQLite creates these with the process umask; they live in the already-admitted private parent.
800
+ // Tightening their mode prevents a later reopen from leaving document bytes world-readable.
801
+ chmodSync(path, 0o600);
802
+ }
803
+ catch (error) {
804
+ if (error.code !== 'ENOENT')
805
+ throw error;
806
+ }
807
+ }
808
+ function ownedByCurrentUser(uid) {
809
+ return process.platform === 'win32' || typeof process.getuid !== 'function' || uid === process.getuid();
810
+ }
811
+ function redactOutput(value) {
812
+ let result = '';
813
+ let offset = 0;
814
+ for (const match of value.matchAll(/https?:\/\/[^\s<>"'`()\[\]{},;!?]+/giu)) {
815
+ const index = match.index;
816
+ if (index === undefined)
817
+ continue;
818
+ result += redactPathSpans(value.slice(offset, index));
819
+ const token = match[0];
820
+ result += safeOutputUrl(token) ? token : redactPathSpans(token);
821
+ offset = index + token.length;
822
+ }
823
+ return result + redactPathSpans(value.slice(offset));
824
+ }
825
+ function safeOutputUrl(value) {
826
+ try {
827
+ const url = new URL(value);
828
+ return (url.protocol === 'http:' || url.protocol === 'https:')
829
+ && url.username === '' && url.password === ''
830
+ && content.scrub('knowledge-output-url', value).kind === 'clean';
831
+ }
832
+ catch {
833
+ return false;
834
+ }
835
+ }
836
+ function redactPathSpans(value) {
837
+ return value.replace(/(?:\\\\[^\s<>"'`()\[\]{},;!?]+|[A-Za-z]:[\\/][^\s<>"'`()\[\]{},;!?]+|\/(?!\/)[^\s<>"'`()\[\]{},;!?]+)/gu, '[path]');
838
+ }
839
+ function isRecord(value) {
840
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
841
+ }
842
+ function invalid() { throw new StoreError('STORE_INVALID_INPUT'); }
843
+ //# sourceMappingURL=store-worker.js.map