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

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,526 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { appendFileSync } from 'node:fs';
3
+ import { opendir, realpath } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { SensitivePathPolicy } from '../memory/sensitivity.js';
7
+ import { acceptanceManifest } from '../desktop/workbench-acceptance.js';
8
+ import { chunkKnowledgeText, fetchKnowledgeUrl, readKnowledgeFile, knowledgeExcerpt, KnowledgeDocumentFailure } from './documents.js';
9
+ import { KnowledgeStoreClientError } from './store-client.js';
10
+ import { withModelPurpose } from '../model/model-purpose.js';
11
+ const idSchema = z.string().regex(/^[a-zA-Z0-9_-]{1,80}$/u);
12
+ const ingestSchema = z.object({ kind: z.enum(['file', 'url', 'folder']), locator: z.string().min(1).max(4096), consent: z.literal(true) }).strict();
13
+ const failure = (code) => new Error(code);
14
+ /** Matches the provider's request batch, so each backfill upload is individually authorized. */
15
+ const EMBED_BATCH = 10;
16
+ function ingestionCode(cause, stage) {
17
+ if (cause instanceof KnowledgeStoreClientError && cause.code === 'STORE_CAPACITY')
18
+ return 'index_capacity';
19
+ if (cause instanceof KnowledgeDocumentFailure) {
20
+ if (['sensitive_content', 'path_denied'].includes(cause.code))
21
+ return 'screening_rejected';
22
+ if (['unsupported_mime', 'invalid_file', 'file_too_large', 'empty_text', 'invalid_text', 'parse_failed', 'parse_timeout'].includes(cause.code))
23
+ return 'unsupported_file';
24
+ if (cause.code === 'file_changed')
25
+ return 'file_changed';
26
+ if (cause.code === 'file_unavailable')
27
+ return 'file_unavailable';
28
+ }
29
+ if (cause instanceof Error && cause.message === 'knowledge_busy')
30
+ return 'knowledge_busy';
31
+ return stage === 'embedding' ? 'embedding_failed' : stage === 'evidence' || stage === 'store' ? 'store_failed' : 'ingest_failed';
32
+ }
33
+ /** Host-only mutations; all public model surfaces receive read-only evidence. */
34
+ export class KnowledgeService {
35
+ #store;
36
+ #embedding;
37
+ #stop = new AbortController();
38
+ #active;
39
+ #syncing = new Map();
40
+ #folderBusy = false;
41
+ #folderSignal;
42
+ #queries = 0;
43
+ #fts = false;
44
+ #ledger;
45
+ #binding;
46
+ #migrated = false;
47
+ #requireLedger;
48
+ #vectorQueue = new Map();
49
+ #vectorRetries = new Map();
50
+ #timings = new Map();
51
+ #vectorWork;
52
+ #vectorGate;
53
+ #resumeRequested = false;
54
+ constructor(options) {
55
+ this.#store = options.store;
56
+ this.#embedding = options.embedding;
57
+ this.#requireLedger = options.requireEvidenceLedger ?? false;
58
+ }
59
+ #assertLedger() { if (this.#requireLedger && (!this.#ledger || !this.#migrated))
60
+ throw failure('knowledge_unavailable'); }
61
+ async open() { this.#fts = (await this.#store.open()).fts; }
62
+ async close() {
63
+ this.#stop.abort();
64
+ this.#active?.abort.abort();
65
+ for (const active of this.#syncing.values())
66
+ active.abort.abort();
67
+ await Promise.allSettled([...this.#syncing.values()].map(active => active.done));
68
+ await this.#store.close();
69
+ }
70
+ purgeEvidence(ids) { return this.#store.purgeEvidence(ids); }
71
+ listSources() { return this.#store.listSources(); }
72
+ async getChunk(locator) {
73
+ this.#assertLedger();
74
+ const chunk = await this.#store.getChunk(locator);
75
+ const ledger = this.#ledger;
76
+ if (!ledger)
77
+ return chunk;
78
+ if (chunk.status !== 'ok' || !chunk.evidence_id)
79
+ return { status: chunk.status === 'stale' ? 'stale' : 'gone' };
80
+ const evidence = await ledger.read(chunk.evidence_id);
81
+ if (this.#ledger !== ledger || evidence?.evidence_id !== chunk.evidence_id)
82
+ return { status: 'gone' };
83
+ return { ...chunk, text: evidence.text };
84
+ }
85
+ /** Existing index chunks migrate offline; linked-but-deleted A evidence is never recreated. */
86
+ async bindEvidenceLedger(ledger) {
87
+ if (this.#binding)
88
+ await this.#binding;
89
+ this.#ledger = ledger;
90
+ // Reopened runtime resources keep canonical IDs; never import cached plaintext into a new binding.
91
+ if (this.#migrated)
92
+ return;
93
+ const work = this.#migrateEvidence(ledger);
94
+ this.#binding = work;
95
+ try {
96
+ await work;
97
+ this.#migrated = true;
98
+ }
99
+ finally {
100
+ if (this.#binding === work)
101
+ this.#binding = undefined;
102
+ }
103
+ if (this.#resumeRequested)
104
+ await this.resumeVectors();
105
+ }
106
+ /** The source owner decides, per backfill round, whether a knowledge source may still be embedded:
107
+ * null skips it now, an owner's signal cancels its in-flight uploads and its current grant replaces
108
+ * the one captured at queue time, undefined means no owner fences it. `queuedByOwner` says the owner
109
+ * queued this work itself with a lifecycle signal, before it could record the new source id. */
110
+ setVectorGate(gate) { this.#vectorGate = gate; }
111
+ /** Scans commit lexically first; the source owner resumes vectors a previous run or a pause left unfinished. */
112
+ async resumeVectors() {
113
+ // A ledger-backed service resumes only after its evidence migration settles.
114
+ if (!this.#migrated && (this.#requireLedger || this.#binding)) {
115
+ this.#resumeRequested = true;
116
+ return;
117
+ }
118
+ this.#resumeRequested = false;
119
+ for (const id of await this.#store.unembeddedSources(this.#embedding.id, this.#embedding.dims))
120
+ this.#queueVectors(id, undefined, undefined);
121
+ }
122
+ /** Resolves once scan-committed chunks have been embedded or skipped. */
123
+ async vectorsSettled() { while (this.#vectorWork)
124
+ await this.#vectorWork; }
125
+ #queueVectors(id, grant, signal) {
126
+ if (this.#stop.signal.aborted || signal?.aborted)
127
+ return;
128
+ this.#vectorQueue.set(id, { grant, signal });
129
+ this.#vectorWork ??= this.#drainVectors().finally(() => {
130
+ this.#vectorWork = undefined;
131
+ const next = this.#vectorQueue.entries().next().value;
132
+ if (next)
133
+ this.#queueVectors(next[0], next[1].grant, next[1].signal);
134
+ });
135
+ }
136
+ /** One source at a time, off the scan path; a failure is retried twice with a growing delay. */
137
+ async #drainVectors() {
138
+ for (const [id, { grant, signal }] of this.#vectorQueue) {
139
+ this.#vectorQueue.delete(id);
140
+ if (this.#stop.signal.aborted)
141
+ return;
142
+ try {
143
+ await this.#embedSource(id, grant, signal);
144
+ this.#vectorRetries.delete(id);
145
+ }
146
+ catch (cause) {
147
+ if (this.#stop.signal.aborted)
148
+ return;
149
+ const gate = this.#vectorGate?.(id, signal !== undefined);
150
+ if (gate === null || gate?.signal.aborted || signal?.aborted) {
151
+ this.#vectorRetries.delete(id);
152
+ continue;
153
+ }
154
+ const acceptance = acceptanceManifest();
155
+ if (acceptance)
156
+ appendFileSync(join(acceptance.outputDirectory, 'knowledge-errors.ndjson'), JSON.stringify({ stage: 'embedding_backfill', code: ingestionCode(cause, 'embedding'), error: cause instanceof Error ? `${cause.name}: ${cause.message}`.slice(0, 300) : typeof cause }) + '\n', { mode: 0o600 });
157
+ const attempt = (this.#vectorRetries.get(id) ?? 0) + 1;
158
+ if (attempt > 2) {
159
+ this.#vectorRetries.delete(id);
160
+ continue;
161
+ }
162
+ this.#vectorRetries.set(id, attempt);
163
+ setTimeout(() => this.#queueVectors(id, grant, signal), 60000 * attempt).unref();
164
+ }
165
+ }
166
+ }
167
+ async #embedSource(id, grant, owner) {
168
+ // One provider batch per round, so pause or revocation is observed before every upload.
169
+ for (let round = 0; round < 2000; round++) {
170
+ const gate = this.#vectorGate?.(id, owner !== undefined);
171
+ if (gate === null || gate?.signal.aborted || owner?.aborted)
172
+ return;
173
+ const current = gate ? gate.grant : grant;
174
+ const pending = await this.#store.unembeddedChunks(id, this.#embedding.id, this.#embedding.dims);
175
+ if (pending.fingerprint === null || pending.chunks.length === 0)
176
+ return;
177
+ const chunks = pending.chunks.slice(0, EMBED_BATCH);
178
+ const evidenceIds = chunks.map(chunk => chunk.evidence_id), ids = evidenceIds.filter((value) => value !== undefined);
179
+ const ledger = this.#ledger;
180
+ const fenced = () => { const now = this.#vectorGate?.(id, owner !== undefined); return now === null || !!now?.signal.aborted || !!gate?.signal.aborted || !!owner?.aborted || (gate !== undefined && now?.grant?.embedding_provider !== current?.embedding_provider); };
181
+ const allowed = async () => !fenced() && (ledger
182
+ ? evidenceIds.length > 0 && (await Promise.all(evidenceIds.map(async (value) => value ? await (ledger.canProcess?.(value, 'embedding') ?? Promise.resolve(false)) : false))).every(Boolean)
183
+ : current?.embedding_provider === this.#embedding.id);
184
+ const stamp = ledger ? await ledger.processingStamp?.(ids) ?? null : 'standalone';
185
+ if (stamp === null || !await allowed())
186
+ return;
187
+ const signal = AbortSignal.any([this.#stop.signal, ...(gate ? [gate.signal] : []), ...(owner ? [owner] : []), AbortSignal.timeout(60000)]);
188
+ const vectors = await withModelPurpose('embedding', () => this.#embedding.embed(chunks.map(chunk => chunk.text), signal));
189
+ signal.throwIfAborted();
190
+ if (vectors.length !== chunks.length)
191
+ throw failure('embedding_invalid_result');
192
+ if (!await allowed() || this.#ledger !== ledger || (ledger && stamp !== await ledger.processingStamp?.(ids)))
193
+ return;
194
+ // No await between this fence and enqueueing the fingerprint-checked write.
195
+ const written = await this.#store.setVectors({ source_id: id, fingerprint: pending.fingerprint, provider_id: this.#embedding.id, dims: this.#embedding.dims,
196
+ vectors: chunks.map((chunk, index) => ({ chunk_id: chunk.chunk_id, content_digest: chunk.content_digest, vector: [...vectors[index]] })) });
197
+ if (written === 0)
198
+ return;
199
+ }
200
+ }
201
+ async #migrateEvidence(ledger) {
202
+ for (const source of await this.#store.listSources()) {
203
+ for (let offset = 0; offset < 20000; offset += 100) {
204
+ this.#stop.signal.throwIfAborted();
205
+ const chunks = await this.#store.listChunks(source.id, offset);
206
+ const links = [];
207
+ for (const chunk of chunks) {
208
+ if (chunk.evidence_id)
209
+ continue;
210
+ const record = await ledger.record({ sourceId: `knowledge:${source.id}`, locator: `${chunk.locator}#chunk=${chunk.ordinal}`, text: chunk.text, observedAt: chunk.observed_at, kind: 'file', embeddingConsent: false });
211
+ links.push({ chunk_id: chunk.chunk_id, content_digest: chunk.content_digest, evidence_id: record.evidence_id });
212
+ }
213
+ if (links.length)
214
+ await this.#store.linkEvidence(links);
215
+ if (chunks.length < 100)
216
+ break;
217
+ }
218
+ }
219
+ }
220
+ async recall(query, k, signal) {
221
+ this.#assertLedger();
222
+ if (this.#queries >= 4)
223
+ throw failure('knowledge_busy');
224
+ const input = z.object({ query: z.string().trim().min(1).max(512), k: z.number().int().min(1).max(5) }).parse({ query, k });
225
+ const abort = AbortSignal.any([this.#stop.signal, ...(signal ? [signal] : []), AbortSignal.timeout(8000)]);
226
+ abort.throwIfAborted();
227
+ this.#queries++;
228
+ try {
229
+ if ((await this.#store.listSources()).length === 0)
230
+ return [];
231
+ const [vector] = await withModelPurpose('recall', () => this.#embedding.embed([input.query], abort));
232
+ abort.throwIfAborted();
233
+ if (vector === undefined)
234
+ throw failure('embedding_invalid_result');
235
+ const hits = await this.#store.recall(input.query, [...vector], this.#embedding.id, input.k);
236
+ abort.throwIfAborted();
237
+ if (!this.#ledger)
238
+ return hits;
239
+ const current = await Promise.all(hits.map(async (hit) => {
240
+ if (!hit.evidence_id)
241
+ return null;
242
+ const chunk = await this.getChunk(hit.locator);
243
+ abort.throwIfAborted();
244
+ return chunk.status === 'ok' && chunk.evidence_id === hit.evidence_id && typeof chunk.text === 'string' ? { ...hit, text: [...chunk.text].slice(0, 600).join('') } : null;
245
+ }));
246
+ return current.filter((hit) => hit !== null);
247
+ }
248
+ finally {
249
+ this.#queries--;
250
+ }
251
+ }
252
+ /** Directory-source admission retains its grant and cancellation through the actual file read. */
253
+ /** `vectorSignal` outlives the scan: the source owner aborts it when the source is paused, removed, or withdrawn. */
254
+ /** Cumulative ingest time per step, for acceptance counts. */
255
+ timings() {
256
+ const out = {};
257
+ for (const [key, row] of this.#timings) {
258
+ out[`${key}_ms`] = Math.round(row.ms);
259
+ out[`${key}_n`] = row.n;
260
+ }
261
+ return out;
262
+ }
263
+ async #timed(key, run) {
264
+ const at = performance.now();
265
+ try {
266
+ return await run();
267
+ }
268
+ finally {
269
+ const row = this.#timings.get(key) ?? { ms: 0, n: 0 };
270
+ row.ms += performance.now() - at;
271
+ row.n++;
272
+ this.#timings.set(key, row);
273
+ }
274
+ }
275
+ async syncFile(locator, root, signal, sourceId, processingConsent, vectorSignal) {
276
+ this.#assertLedger();
277
+ signal.throwIfAborted();
278
+ this.#stop.signal.throwIfAborted();
279
+ if (this.#active || this.#folderBusy)
280
+ throw failure('knowledge_busy');
281
+ while (this.#syncing.size >= 4 && !this.#stop.signal.aborted && !signal.aborted)
282
+ await Promise.race([...this.#syncing.values()].map(active => active.done));
283
+ signal.throwIfAborted();
284
+ this.#stop.signal.throwIfAborted();
285
+ if (this.#syncing.has(locator) || this.#active || this.#folderBusy)
286
+ throw failure('knowledge_busy');
287
+ if (sourceId !== undefined && !idSchema.safeParse(sourceId).success)
288
+ throw failure('invalid_request');
289
+ const active = { id: sourceId ?? randomUUID(), abort: new AbortController(), root, ...(processingConsent ? { processingConsent } : {}), processingAuthorized: false, deferVectors: true };
290
+ let release;
291
+ const slot = { ...active, previousId: sourceId, done: new Promise(resolve => { release = resolve; }) };
292
+ this.#syncing.set(locator, slot);
293
+ const cancel = () => active.abort.abort();
294
+ signal.addEventListener('abort', cancel, { once: true });
295
+ try {
296
+ const old = await this.#timed('ingest_lookup', () => this.#store.sourceByLocator(locator)) ?? undefined;
297
+ signal.throwIfAborted();
298
+ if (sourceId !== undefined && this.#ledger) {
299
+ if (old && old.id !== sourceId)
300
+ throw failure('source_changed');
301
+ // Build under a fresh ID. The old index stays queryable if reading,
302
+ // embedding, or the atomic replacement fails.
303
+ active.id = randomUUID();
304
+ slot.id = active.id;
305
+ }
306
+ else if (old !== undefined) {
307
+ active.id = old.id;
308
+ slot.id = active.id;
309
+ }
310
+ let excerpt = '';
311
+ const result = await this.#index('folder_child', locator, active, old, text => { excerpt = knowledgeExcerpt(text); });
312
+ if ('error' in result)
313
+ throw failure(result.error);
314
+ if (old && old.id !== active.id) {
315
+ await this.#ledger?.remove(`knowledge:${old.id}`);
316
+ }
317
+ this.#queueVectors(active.id, processingConsent, vectorSignal);
318
+ const evidence_ids = (await this.#timed('ingest_list_chunks', () => this.#store.listChunks(active.id, 0))).flatMap(chunk => chunk.evidence_id ? [chunk.evidence_id] : []).slice(0, 2);
319
+ return { id: active.id, excerpt, fingerprint: result.fingerprint, ...(evidence_ids.length ? { evidence_ids } : {}) };
320
+ }
321
+ catch (cause) {
322
+ signal.throwIfAborted();
323
+ const code = cause instanceof Error && /^(?:screening_rejected|unsupported_file|file_changed|file_unavailable|embedding_failed|store_failed|knowledge_busy|ingest_failed|index_capacity)$/u.test(cause.message)
324
+ ? cause.message : 'store_failed';
325
+ throw failure(code);
326
+ }
327
+ finally {
328
+ signal.removeEventListener('abort', cancel);
329
+ this.#syncing.delete(locator);
330
+ release();
331
+ }
332
+ }
333
+ async handle(method, params) {
334
+ this.#stop.signal.throwIfAborted();
335
+ if (method === 'knowledge.status') {
336
+ if (!z.object({}).strict().safeParse(params).success)
337
+ throw failure('invalid_request');
338
+ const sources = await this.#store.listSources(), jobs = await this.#store.listJobs();
339
+ return { fts: this.#fts, sources: sources.map(({ id, title, kind, bytes, updated_at, status }) => ({ id, title, kind, bytes, updated_at, status })), jobs };
340
+ }
341
+ if (method === 'knowledge.remove') {
342
+ this.#assertLedger();
343
+ const parsed = z.object({ id: idSchema }).strict().safeParse(params);
344
+ if (!parsed.success)
345
+ throw failure('invalid_request');
346
+ if (this.#active?.id === parsed.data.id)
347
+ this.#active.abort.abort();
348
+ const affected = [...this.#syncing.values()].filter(active => active.id === parsed.data.id || active.previousId === parsed.data.id);
349
+ for (const active of affected)
350
+ active.abort.abort();
351
+ await Promise.all(affected.map(active => active.done));
352
+ for (const id of new Set([parsed.data.id, ...affected.map(active => active.id)])) {
353
+ await this.#ledger?.remove(`knowledge:${id}`);
354
+ await this.#store.removeSource(id);
355
+ }
356
+ return { ok: true };
357
+ }
358
+ if (method === 'knowledge.reindex') {
359
+ this.#assertLedger();
360
+ const parsed = z.object({ id: idSchema, consent: z.literal(true) }).strict().safeParse(params);
361
+ if (!parsed.success)
362
+ throw failure('invalid_request');
363
+ if (this.#active || this.#folderBusy || this.#syncing.size)
364
+ return { error: 'knowledge_busy' };
365
+ // Claim the id before any asynchronous read, so remove can fence this reindex.
366
+ const active = { id: parsed.data.id, abort: new AbortController(), processingAuthorized: parsed.data.consent };
367
+ this.#active = active;
368
+ try {
369
+ const source = (await this.#store.listSources()).find(value => value.id === active.id);
370
+ if (source === undefined)
371
+ return { error: 'source_gone' };
372
+ return await this.#index(source.kind, source.locator, active, source);
373
+ }
374
+ finally {
375
+ if (this.#active === active)
376
+ this.#active = undefined;
377
+ }
378
+ }
379
+ if (method === 'knowledge.ingest') {
380
+ this.#assertLedger();
381
+ const parsed = ingestSchema.safeParse(params);
382
+ if (!parsed.success)
383
+ throw failure('invalid_request');
384
+ if (this.#active || this.#folderBusy || this.#syncing.size)
385
+ return { error: 'knowledge_busy' };
386
+ if (parsed.data.kind === 'folder')
387
+ return this.#folder(parsed.data.locator);
388
+ return this.#ingest(parsed.data.kind, parsed.data.locator);
389
+ }
390
+ throw failure('invalid_request');
391
+ }
392
+ async #ingest(kind, locator) {
393
+ const active = { id: randomUUID(), abort: new AbortController(), processingAuthorized: true };
394
+ this.#active = active;
395
+ try {
396
+ return await this.#index(kind, locator, active);
397
+ }
398
+ finally {
399
+ if (this.#active === active)
400
+ this.#active = undefined;
401
+ }
402
+ }
403
+ async #index(kind, locator, active, old, onIndexed) {
404
+ const signal = AbortSignal.any([active.abort.signal, this.#stop.signal,
405
+ ...(this.#folderSignal === undefined ? [] : [this.#folderSignal]), AbortSignal.timeout(120000)]);
406
+ const job = { id: randomUUID(), source_id: active.id, updated_at: Date.now(), error_code: null };
407
+ let stage = 'store';
408
+ let committed = false;
409
+ try {
410
+ signal.throwIfAborted();
411
+ await this.#timed('ingest_job', () => this.#store.recordJob({ ...job, state: 'running' }));
412
+ stage = 'read';
413
+ const document = await this.#timed('ingest_read', () => kind === 'url' ? fetchKnowledgeUrl(locator, signal) : readKnowledgeFile(locator, signal, active.root));
414
+ signal.throwIfAborted();
415
+ if (old === undefined && await this.#timed('ingest_lookup', () => this.#store.sourceByLocator(document.locator)))
416
+ throw failure('source_exists');
417
+ const chunks = chunkKnowledgeText(document.text);
418
+ const processingConsent = active.processingConsent ?? (active.processingAuthorized ? this.#ledger?.processingGrant?.(true) : undefined);
419
+ const evidenceIds = [];
420
+ stage = 'evidence';
421
+ const evidenceAt = performance.now();
422
+ // The grant belongs to the source, not the chunk: stating it once spares a read and write per chunk.
423
+ const inputs = chunks.map((chunk, ordinal) => ({ sourceId: `knowledge:${active.id}`, locator: `${document.locator}#chunk=${ordinal}`, text: chunk.text, observedAt: new Date().toISOString(), kind: 'file', embeddingConsent: active.processingAuthorized === true || Boolean(processingConsent?.embedding_provider), ...(processingConsent && ordinal === 0 ? { processingConsent } : {}) }));
424
+ const ledger = this.#ledger;
425
+ if (ledger?.recordBatch) {
426
+ // One ledger transaction per 256 chunks instead of two round trips per chunk.
427
+ for (let start = 0; start < inputs.length; start += 256) {
428
+ signal.throwIfAborted();
429
+ const part = inputs.slice(start, start + 256), saved = await ledger.recordBatch(part);
430
+ if (saved.length !== part.length)
431
+ throw failure('store_failed');
432
+ evidenceIds.push(...saved.map(row => row.evidence_id));
433
+ }
434
+ }
435
+ else
436
+ for (const input of inputs) {
437
+ signal.throwIfAborted();
438
+ const evidence = await ledger?.record(input);
439
+ evidenceIds.push(evidence?.evidence_id);
440
+ }
441
+ {
442
+ const row = this.#timings.get('ingest_evidence') ?? { ms: 0, n: 0 };
443
+ row.ms += performance.now() - evidenceAt;
444
+ row.n += chunks.length;
445
+ this.#timings.set('ingest_evidence', row);
446
+ }
447
+ signal.throwIfAborted();
448
+ const allowed = async () => { if (this.#ledger)
449
+ return evidenceIds.length > 0 && (await Promise.all(evidenceIds.map(async (id) => id ? await (this.#ledger?.canProcess?.(id, 'embedding') ?? Promise.resolve(false)) : false))).every(Boolean); return active.processingAuthorized === true || processingConsent?.embedding_provider === this.#embedding.id; };
450
+ const stamp = this.#ledger ? await this.#timed('ingest_stamp', async () => await this.#ledger?.processingStamp?.(evidenceIds.filter((id) => id !== undefined))) ?? null : 'standalone';
451
+ stage = 'embedding';
452
+ // Scan-time sources commit lexically now; #drainVectors embeds them off the scan path.
453
+ const vectors = !active.deferVectors && stamp !== null && await allowed() ? await withModelPurpose('embedding', () => this.#embedding.embed(chunks.map(chunk => chunk.text), signal)) : null;
454
+ signal.throwIfAborted();
455
+ if (vectors !== null && vectors.length !== chunks.length)
456
+ throw failure('embedding_invalid_result');
457
+ const keepVectors = vectors !== null && await allowed() && (!this.#ledger || stamp === await this.#ledger.processingStamp?.(evidenceIds.filter((id) => id !== undefined)));
458
+ const now = Date.now();
459
+ const title = [...document.title].slice(0, 256).join('');
460
+ // No await between this fence and enqueueing the atomic replacement. Remove enqueues after it.
461
+ stage = 'store';
462
+ await this.#timed('ingest_store', () => this.#store.replaceSource({
463
+ source: { id: active.id, title, kind, locator: document.locator, mime: document.mime,
464
+ fingerprint: document.fingerprint, bytes: document.bytes, created_at: old?.created_at ?? now, updated_at: now, status: 'ready' },
465
+ ...(old && old.id !== active.id ? { replaces_source_id: old.id } : {}),
466
+ provider_id: this.#embedding.id, dims: this.#embedding.dims,
467
+ // Plain text and extracted PDF/DOCX need not contain Markdown headings.
468
+ chunks: chunks.map((chunk, index) => ({ ...chunk,
469
+ ...(evidenceIds[index] === undefined ? {} : { evidence_id: evidenceIds[index] }),
470
+ heading_path: [...(chunk.heading_path || title)].slice(0, 256).join(''), vector: keepVectors && vectors ? [...vectors[index]] : null })),
471
+ }));
472
+ committed = true;
473
+ await this.#store.recordJob({ ...job, updated_at: Date.now(), state: 'complete' }).catch(() => undefined);
474
+ onIndexed?.(document.text);
475
+ return { ok: true, id: active.id, fingerprint: document.fingerprint };
476
+ }
477
+ catch (cause) {
478
+ const code = signal.aborted ? 'ingest_cancelled' : ingestionCode(cause, stage);
479
+ const acceptance = acceptanceManifest();
480
+ if (acceptance)
481
+ appendFileSync(join(acceptance.outputDirectory, 'knowledge-errors.ndjson'), JSON.stringify({ stage, code, error: cause instanceof Error ? `${cause.name}: ${cause.message}`.slice(0, 300) : typeof cause }) + '\n', { mode: 0o600 });
482
+ if (!committed && old?.id !== active.id)
483
+ await this.#ledger?.remove(`knowledge:${active.id}`).catch(() => undefined);
484
+ if (!this.#stop.signal.aborted)
485
+ await this.#store.recordJob({ ...job, updated_at: Date.now(), state: 'failed', error_code: code }).catch(() => undefined);
486
+ return { error: code, id: active.id };
487
+ }
488
+ }
489
+ async #folder(locator) {
490
+ this.#folderBusy = true;
491
+ this.#folderSignal = AbortSignal.any([this.#stop.signal, AbortSignal.timeout(120000)]);
492
+ const results = [];
493
+ try {
494
+ const policy = new SensitivePathPolicy();
495
+ if (!policy.allows(locator))
496
+ throw failure('invalid_request');
497
+ const root = await realpath(locator);
498
+ if (!policy.allows(root))
499
+ throw failure('invalid_request');
500
+ const directories = [{ path: root, depth: 0 }];
501
+ let visited = 0;
502
+ while (directories.length > 0 && results.length < 100 && visited < 1000) {
503
+ this.#folderSignal.throwIfAborted();
504
+ const directory = directories.pop();
505
+ for await (const entry of await opendir(directory.path)) {
506
+ visited++;
507
+ if (visited > 1000 || results.length >= 100)
508
+ break;
509
+ const path = join(directory.path, entry.name);
510
+ if (entry.name.startsWith('.') || !policy.allows(path) || entry.isSymbolicLink())
511
+ continue;
512
+ if (entry.isDirectory() && directory.depth < 16)
513
+ directories.push({ path, depth: directory.depth + 1 });
514
+ else if (entry.isFile())
515
+ results.push(await this.#ingest('folder_child', path));
516
+ }
517
+ }
518
+ return { results, limited: visited >= 1000 || results.length >= 100 };
519
+ }
520
+ finally {
521
+ this.#folderBusy = false;
522
+ this.#folderSignal = undefined;
523
+ }
524
+ }
525
+ }
526
+ //# sourceMappingURL=service.js.map