@dikolab/kbdb 0.1.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 (308) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +270 -0
  3. package/dist/chunk-QCCN7OZH.mjs +82 -0
  4. package/dist/chunk-QCCN7OZH.mjs.map +7 -0
  5. package/dist/cli.cjs +3598 -0
  6. package/dist/cli.cjs.map +7 -0
  7. package/dist/cli.mjs +3537 -0
  8. package/dist/cli.mjs.map +7 -0
  9. package/dist/kbdb-worker.cjs +1659 -0
  10. package/dist/kbdb-worker.cjs.map +7 -0
  11. package/dist/mod.cjs +538 -0
  12. package/dist/mod.cjs.map +7 -0
  13. package/dist/mod.d.ts +3 -0
  14. package/dist/mod.mjs +507 -0
  15. package/dist/mod.mjs.map +7 -0
  16. package/dist/src/cli.d.ts +1 -0
  17. package/dist/src/shared/cli/constants/defaults.constant.d.ts +11 -0
  18. package/dist/src/shared/cli/constants/help-text.constant.d.ts +2 -0
  19. package/dist/src/shared/cli/functions/dispatch-command.function.d.ts +37 -0
  20. package/dist/src/shared/cli/functions/ensure-db.function.d.ts +11 -0
  21. package/dist/src/shared/cli/functions/error-to-message.function.d.ts +7 -0
  22. package/dist/src/shared/cli/functions/find-db.function.d.ts +13 -0
  23. package/dist/src/shared/cli/functions/format-output.function.d.ts +15 -0
  24. package/dist/src/shared/cli/functions/generate-help.function.d.ts +31 -0
  25. package/dist/src/shared/cli/functions/is-stdin-tty.function.d.ts +7 -0
  26. package/dist/src/shared/cli/functions/parse-args.function.d.ts +25 -0
  27. package/dist/src/shared/cli/functions/prompt-user.function.d.ts +13 -0
  28. package/dist/src/shared/cli/functions/run-agent-create.function.d.ts +58 -0
  29. package/dist/src/shared/cli/functions/run-agent-delete.function.d.ts +32 -0
  30. package/dist/src/shared/cli/functions/run-agent-get.function.d.ts +46 -0
  31. package/dist/src/shared/cli/functions/run-agent-list.function.d.ts +45 -0
  32. package/dist/src/shared/cli/functions/run-check.function.d.ts +64 -0
  33. package/dist/src/shared/cli/functions/run-cli.function.d.ts +39 -0
  34. package/dist/src/shared/cli/functions/run-content.function.d.ts +40 -0
  35. package/dist/src/shared/cli/functions/run-db-init.function.d.ts +23 -0
  36. package/dist/src/shared/cli/functions/run-db-migrate.function.d.ts +32 -0
  37. package/dist/src/shared/cli/functions/run-gc.function.d.ts +38 -0
  38. package/dist/src/shared/cli/functions/run-init.function.d.ts +27 -0
  39. package/dist/src/shared/cli/functions/run-learn.function.d.ts +46 -0
  40. package/dist/src/shared/cli/functions/run-migrate.function.d.ts +57 -0
  41. package/dist/src/shared/cli/functions/run-rebuild.function.d.ts +40 -0
  42. package/dist/src/shared/cli/functions/run-search.function.d.ts +39 -0
  43. package/dist/src/shared/cli/functions/run-skill-delete.function.d.ts +30 -0
  44. package/dist/src/shared/cli/functions/run-skill-get.function.d.ts +49 -0
  45. package/dist/src/shared/cli/functions/run-skill-learn.function.d.ts +36 -0
  46. package/dist/src/shared/cli/functions/run-skill-list.function.d.ts +43 -0
  47. package/dist/src/shared/cli/functions/run-status.function.d.ts +22 -0
  48. package/dist/src/shared/cli/functions/run-unlearn.function.d.ts +45 -0
  49. package/dist/src/shared/cli/index.d.ts +35 -0
  50. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +53 -0
  51. package/dist/src/shared/cli/typings/command-result.model.d.ts +15 -0
  52. package/dist/src/shared/cli/typings/learn-result.model.d.ts +11 -0
  53. package/dist/src/shared/cli/typings/search-display.model.d.ts +17 -0
  54. package/dist/src/shared/dir-resolver/functions/resolve-base-dir.function.d.ts +3 -0
  55. package/dist/src/shared/dir-resolver/functions/resolve-wasm-dir.function.d.ts +1 -0
  56. package/dist/src/shared/dir-resolver/functions/resolve-worker-script.function.d.ts +2 -0
  57. package/dist/src/shared/dir-resolver/index.d.ts +4 -0
  58. package/dist/src/shared/dir-resolver/typings/base-dir.interface.d.ts +4 -0
  59. package/dist/src/shared/hash/functions/compute-sha256.d.ts +10 -0
  60. package/dist/src/shared/hash/index.d.ts +1 -0
  61. package/dist/src/shared/mcp/classes/mcp-server.class.d.ts +55 -0
  62. package/dist/src/shared/mcp/constants/mcp-error-codes.constant.d.ts +26 -0
  63. package/dist/src/shared/mcp/functions/create-mcp-server.function.d.ts +11 -0
  64. package/dist/src/shared/mcp/functions/create-prompt-definitions.function.d.ts +41 -0
  65. package/dist/src/shared/mcp/functions/create-resource-templates.function.d.ts +7 -0
  66. package/dist/src/shared/mcp/functions/create-tool-definitions.function.d.ts +7 -0
  67. package/dist/src/shared/mcp/functions/extract-skill-arguments.function.d.ts +13 -0
  68. package/dist/src/shared/mcp/functions/handle-agent-create.function.d.ts +29 -0
  69. package/dist/src/shared/mcp/functions/handle-agent-delete.function.d.ts +28 -0
  70. package/dist/src/shared/mcp/functions/handle-agent-get.function.d.ts +29 -0
  71. package/dist/src/shared/mcp/functions/handle-agent-list.function.d.ts +31 -0
  72. package/dist/src/shared/mcp/functions/handle-completion.function.d.ts +58 -0
  73. package/dist/src/shared/mcp/functions/handle-prompt-get.function.d.ts +23 -0
  74. package/dist/src/shared/mcp/functions/handle-resource-read.function.d.ts +26 -0
  75. package/dist/src/shared/mcp/functions/handle-roots-list.function.d.ts +21 -0
  76. package/dist/src/shared/mcp/functions/handle-tool-call.function.d.ts +26 -0
  77. package/dist/src/shared/mcp/functions/parse-skill-content.function.d.ts +15 -0
  78. package/dist/src/shared/mcp/functions/serialize-skill-content.function.d.ts +9 -0
  79. package/dist/src/shared/mcp/functions/should-emit-log.function.d.ts +20 -0
  80. package/dist/src/shared/mcp/index.d.ts +9 -0
  81. package/dist/src/shared/mcp/typings/agent-types.interface.d.ts +38 -0
  82. package/dist/src/shared/mcp/typings/log-types.interface.d.ts +17 -0
  83. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +217 -0
  84. package/dist/src/shared/mcp/typings/mcp-types.interface.d.ts +149 -0
  85. package/dist/src/shared/mcp/typings/prompt-types.interface.d.ts +37 -0
  86. package/dist/src/shared/mcp/typings/remove-section-result.model.d.ts +10 -0
  87. package/dist/src/shared/mcp/typings/sampling-types.interface.d.ts +46 -0
  88. package/dist/src/shared/mcp/typings/skill-types.interface.d.ts +28 -0
  89. package/dist/src/shared/mod.d.ts +1 -0
  90. package/dist/src/shared/platform/functions/get-ipc-path.function.d.ts +11 -0
  91. package/dist/src/shared/platform/functions/get-tmpdir.function.d.ts +4 -0
  92. package/dist/src/shared/platform/functions/is-process-alive.function.d.ts +10 -0
  93. package/dist/src/shared/platform/index.d.ts +3 -0
  94. package/dist/src/shared/runtime/functions/detect-runtime.d.ts +8 -0
  95. package/dist/src/shared/runtime/functions/get-args.d.ts +7 -0
  96. package/dist/src/shared/runtime/index.d.ts +3 -0
  97. package/dist/src/shared/runtime/typings/runtime.d.ts +2 -0
  98. package/dist/src/shared/version/constants/version.constant.d.ts +2 -0
  99. package/dist/src/shared/version/index.d.ts +1 -0
  100. package/dist/src/shared/wasm-codec/functions/decode-compose-output.function.d.ts +5 -0
  101. package/dist/src/shared/wasm-codec/functions/decode-document-manifest-list.function.d.ts +14 -0
  102. package/dist/src/shared/wasm-codec/functions/decode-document-manifest.function.d.ts +40 -0
  103. package/dist/src/shared/wasm-codec/functions/decode-f32.function.d.ts +2 -0
  104. package/dist/src/shared/wasm-codec/functions/decode-key-value-text.function.d.ts +1 -0
  105. package/dist/src/shared/wasm-codec/functions/decode-remove-flag.function.d.ts +1 -0
  106. package/dist/src/shared/wasm-codec/functions/decode-scored-results.function.d.ts +10 -0
  107. package/dist/src/shared/wasm-codec/functions/decode-section-record-list.function.d.ts +13 -0
  108. package/dist/src/shared/wasm-codec/functions/decode-section-records.function.d.ts +50 -0
  109. package/dist/src/shared/wasm-codec/functions/decode-string.function.d.ts +5 -0
  110. package/dist/src/shared/wasm-codec/functions/decode-u32.function.d.ts +2 -0
  111. package/dist/src/shared/wasm-codec/functions/decode-u64.function.d.ts +2 -0
  112. package/dist/src/shared/wasm-codec/functions/encode-add-section-params.function.d.ts +10 -0
  113. package/dist/src/shared/wasm-codec/functions/encode-group-params.function.d.ts +10 -0
  114. package/dist/src/shared/wasm-codec/functions/encode-identifier-list.function.d.ts +1 -0
  115. package/dist/src/shared/wasm-codec/functions/encode-kbid-list.function.d.ts +1 -0
  116. package/dist/src/shared/wasm-codec/functions/encode-option-string.function.d.ts +1 -0
  117. package/dist/src/shared/wasm-codec/functions/encode-search-params.function.d.ts +1 -0
  118. package/dist/src/shared/wasm-codec/functions/encode-section-type.function.d.ts +1 -0
  119. package/dist/src/shared/wasm-codec/functions/encode-string.function.d.ts +1 -0
  120. package/dist/src/shared/wasm-codec/functions/encode-type-filter-param.function.d.ts +11 -0
  121. package/dist/src/shared/wasm-codec/functions/encode-u32.function.d.ts +1 -0
  122. package/dist/src/shared/wasm-codec/functions/encode-update-section-params.function.d.ts +2 -0
  123. package/dist/src/shared/wasm-codec/index.d.ts +29 -0
  124. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +230 -0
  125. package/dist/src/shared/worker-client/functions/compute-context-id.function.d.ts +11 -0
  126. package/dist/src/shared/worker-client/functions/create-worker-client.function.d.ts +18 -0
  127. package/dist/src/shared/worker-client/functions/discover-daemon.function.d.ts +14 -0
  128. package/dist/src/shared/worker-client/functions/resolve-db-path.function.d.ts +11 -0
  129. package/dist/src/shared/worker-client/functions/spawn-daemon.function.d.ts +11 -0
  130. package/dist/src/shared/worker-client/functions/wait-for-daemon.function.d.ts +13 -0
  131. package/dist/src/shared/worker-client/index.d.ts +22 -0
  132. package/dist/src/shared/worker-client/typings/add-section-result.model.d.ts +22 -0
  133. package/dist/src/shared/worker-client/typings/content-result.model.d.ts +12 -0
  134. package/dist/src/shared/worker-client/typings/daemon-info.model.d.ts +7 -0
  135. package/dist/src/shared/worker-client/typings/gc-result.model.d.ts +12 -0
  136. package/dist/src/shared/worker-client/typings/integrity-check-result.model.d.ts +36 -0
  137. package/dist/src/shared/worker-client/typings/migrate-result.model.d.ts +11 -0
  138. package/dist/src/shared/worker-client/typings/rebuild-result.model.d.ts +12 -0
  139. package/dist/src/shared/worker-client/typings/remove-section-result.model.d.ts +7 -0
  140. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +12 -0
  141. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +14 -0
  142. package/dist/src/shared/worker-client/typings/section.model.d.ts +26 -0
  143. package/dist/src/shared/worker-client/typings/status-result.model.d.ts +14 -0
  144. package/dist/src/shared/worker-client/typings/version-status.model.d.ts +24 -0
  145. package/dist/src/shared/worker-client/typings/worker-client-error.interface.d.ts +8 -0
  146. package/dist/src/shared/worker-client/typings/worker-client-options.interface.d.ts +30 -0
  147. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +147 -0
  148. package/dist/src/shared/worker-daemon/constants/daemon-defaults.constant.d.ts +24 -0
  149. package/dist/src/shared/worker-daemon/functions/create-host-imports.function.d.ts +68 -0
  150. package/dist/src/shared/worker-daemon/functions/create-ipc-server.function.d.ts +18 -0
  151. package/dist/src/shared/worker-daemon/functions/load-wasm-modules.function.d.ts +19 -0
  152. package/dist/src/shared/worker-daemon/functions/read-config.function.d.ts +12 -0
  153. package/dist/src/shared/worker-daemon/functions/run-worker.function.d.ts +26 -0
  154. package/dist/src/shared/worker-daemon/functions/start-daemon.function.d.ts +13 -0
  155. package/dist/src/shared/worker-daemon/index.d.ts +9 -0
  156. package/dist/src/shared/worker-daemon/typings/daemon-config.interface.d.ts +13 -0
  157. package/dist/src/shared/worker-daemon/typings/ipc-handler.interface.d.ts +36 -0
  158. package/dist/src/shared/worker-daemon/typings/wasm-modules.interface.d.ts +7 -0
  159. package/dist/src/worker.d.ts +1 -0
  160. package/dist/vitest.config.d.ts +2 -0
  161. package/dist/worker.mjs +1615 -0
  162. package/dist/worker.mjs.map +7 -0
  163. package/mod.ts +17 -0
  164. package/package.json +85 -0
  165. package/src/cli.ts +62 -0
  166. package/src/shared/cli/constants/defaults.constant.ts +19 -0
  167. package/src/shared/cli/constants/help-text.constant.ts +4 -0
  168. package/src/shared/cli/functions/dispatch-command.function.ts +338 -0
  169. package/src/shared/cli/functions/ensure-db.function.ts +21 -0
  170. package/src/shared/cli/functions/error-to-message.function.ts +9 -0
  171. package/src/shared/cli/functions/find-db.function.ts +20 -0
  172. package/src/shared/cli/functions/format-output.function.ts +64 -0
  173. package/src/shared/cli/functions/generate-help.function.ts +599 -0
  174. package/src/shared/cli/functions/is-stdin-tty.function.ts +12 -0
  175. package/src/shared/cli/functions/parse-args.function.ts +133 -0
  176. package/src/shared/cli/functions/prompt-user.function.ts +36 -0
  177. package/src/shared/cli/functions/run-agent-create.function.ts +114 -0
  178. package/src/shared/cli/functions/run-agent-delete.function.ts +47 -0
  179. package/src/shared/cli/functions/run-agent-get.function.ts +166 -0
  180. package/src/shared/cli/functions/run-agent-list.function.ts +58 -0
  181. package/src/shared/cli/functions/run-check.function.ts +78 -0
  182. package/src/shared/cli/functions/run-cli.function.ts +299 -0
  183. package/src/shared/cli/functions/run-content.function.ts +47 -0
  184. package/src/shared/cli/functions/run-db-init.function.ts +44 -0
  185. package/src/shared/cli/functions/run-db-migrate.function.ts +40 -0
  186. package/src/shared/cli/functions/run-gc.function.ts +45 -0
  187. package/src/shared/cli/functions/run-init.function.ts +91 -0
  188. package/src/shared/cli/functions/run-learn.function.ts +171 -0
  189. package/src/shared/cli/functions/run-migrate.function.ts +85 -0
  190. package/src/shared/cli/functions/run-rebuild.function.ts +47 -0
  191. package/src/shared/cli/functions/run-search.function.ts +62 -0
  192. package/src/shared/cli/functions/run-skill-delete.function.ts +47 -0
  193. package/src/shared/cli/functions/run-skill-get.function.ts +90 -0
  194. package/src/shared/cli/functions/run-skill-learn.function.ts +70 -0
  195. package/src/shared/cli/functions/run-skill-list.function.ts +74 -0
  196. package/src/shared/cli/functions/run-status.function.ts +29 -0
  197. package/src/shared/cli/functions/run-unlearn.function.ts +58 -0
  198. package/src/shared/cli/index.ts +48 -0
  199. package/src/shared/cli/typings/cli-options.interface.ts +55 -0
  200. package/src/shared/cli/typings/command-result.model.ts +15 -0
  201. package/src/shared/cli/typings/learn-result.model.ts +11 -0
  202. package/src/shared/cli/typings/search-display.model.ts +17 -0
  203. package/src/shared/dir-resolver/functions/resolve-base-dir.function.ts +25 -0
  204. package/src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts +5 -0
  205. package/src/shared/dir-resolver/functions/resolve-worker-script.function.ts +13 -0
  206. package/src/shared/dir-resolver/index.ts +7 -0
  207. package/src/shared/dir-resolver/typings/base-dir.interface.ts +4 -0
  208. package/src/shared/hash/functions/compute-sha256.ts +17 -0
  209. package/src/shared/hash/index.ts +1 -0
  210. package/src/shared/mcp/classes/mcp-server.class.ts +448 -0
  211. package/src/shared/mcp/constants/mcp-error-codes.constant.ts +30 -0
  212. package/src/shared/mcp/functions/create-mcp-server.function.ts +14 -0
  213. package/src/shared/mcp/functions/create-prompt-definitions.function.ts +102 -0
  214. package/src/shared/mcp/functions/create-resource-templates.function.ts +23 -0
  215. package/src/shared/mcp/functions/create-tool-definitions.function.ts +401 -0
  216. package/src/shared/mcp/functions/extract-skill-arguments.function.ts +27 -0
  217. package/src/shared/mcp/functions/handle-agent-create.function.ts +116 -0
  218. package/src/shared/mcp/functions/handle-agent-delete.function.ts +50 -0
  219. package/src/shared/mcp/functions/handle-agent-get.function.ts +160 -0
  220. package/src/shared/mcp/functions/handle-agent-list.function.ts +50 -0
  221. package/src/shared/mcp/functions/handle-completion.function.ts +114 -0
  222. package/src/shared/mcp/functions/handle-prompt-get.function.ts +214 -0
  223. package/src/shared/mcp/functions/handle-resource-read.function.ts +56 -0
  224. package/src/shared/mcp/functions/handle-roots-list.function.ts +29 -0
  225. package/src/shared/mcp/functions/handle-tool-call.function.ts +464 -0
  226. package/src/shared/mcp/functions/parse-skill-content.function.ts +38 -0
  227. package/src/shared/mcp/functions/serialize-skill-content.function.ts +12 -0
  228. package/src/shared/mcp/functions/should-emit-log.function.ts +38 -0
  229. package/src/shared/mcp/index.ts +28 -0
  230. package/src/shared/mcp/typings/agent-types.interface.ts +39 -0
  231. package/src/shared/mcp/typings/log-types.interface.ts +26 -0
  232. package/src/shared/mcp/typings/mcp-client.interface.ts +252 -0
  233. package/src/shared/mcp/typings/mcp-types.interface.ts +158 -0
  234. package/src/shared/mcp/typings/prompt-types.interface.ts +39 -0
  235. package/src/shared/mcp/typings/remove-section-result.model.ts +10 -0
  236. package/src/shared/mcp/typings/sampling-types.interface.ts +48 -0
  237. package/src/shared/mcp/typings/skill-types.interface.ts +29 -0
  238. package/src/shared/mod.ts +1 -0
  239. package/src/shared/platform/functions/get-ipc-path.function.ts +19 -0
  240. package/src/shared/platform/functions/get-tmpdir.function.ts +8 -0
  241. package/src/shared/platform/functions/is-process-alive.function.ts +17 -0
  242. package/src/shared/platform/index.ts +3 -0
  243. package/src/shared/runtime/functions/detect-runtime.ts +14 -0
  244. package/src/shared/runtime/functions/get-args.ts +16 -0
  245. package/src/shared/runtime/index.ts +3 -0
  246. package/src/shared/runtime/typings/runtime.ts +2 -0
  247. package/src/shared/version/constants/version.constant.ts +2 -0
  248. package/src/shared/version/index.ts +1 -0
  249. package/src/shared/wasm-codec/functions/decode-compose-output.function.ts +16 -0
  250. package/src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts +70 -0
  251. package/src/shared/wasm-codec/functions/decode-document-manifest.function.ts +87 -0
  252. package/src/shared/wasm-codec/functions/decode-f32.function.ts +16 -0
  253. package/src/shared/wasm-codec/functions/decode-key-value-text.function.ts +15 -0
  254. package/src/shared/wasm-codec/functions/decode-remove-flag.function.ts +3 -0
  255. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +54 -0
  256. package/src/shared/wasm-codec/functions/decode-section-record-list.function.ts +20 -0
  257. package/src/shared/wasm-codec/functions/decode-section-records.function.ts +162 -0
  258. package/src/shared/wasm-codec/functions/decode-string.function.ts +22 -0
  259. package/src/shared/wasm-codec/functions/decode-u32.function.ts +16 -0
  260. package/src/shared/wasm-codec/functions/decode-u64.function.ts +16 -0
  261. package/src/shared/wasm-codec/functions/encode-add-section-params.function.ts +34 -0
  262. package/src/shared/wasm-codec/functions/encode-group-params.function.ts +28 -0
  263. package/src/shared/wasm-codec/functions/encode-identifier-list.function.ts +17 -0
  264. package/src/shared/wasm-codec/functions/encode-kbid-list.function.ts +17 -0
  265. package/src/shared/wasm-codec/functions/encode-option-string.function.ts +14 -0
  266. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +9 -0
  267. package/src/shared/wasm-codec/functions/encode-section-type.function.ts +18 -0
  268. package/src/shared/wasm-codec/functions/encode-string.function.ts +9 -0
  269. package/src/shared/wasm-codec/functions/encode-type-filter-param.function.ts +13 -0
  270. package/src/shared/wasm-codec/functions/encode-u32.function.ts +5 -0
  271. package/src/shared/wasm-codec/functions/encode-update-section-params.function.ts +16 -0
  272. package/src/shared/wasm-codec/index.ts +36 -0
  273. package/src/shared/worker-client/classes/worker-client.class.ts +427 -0
  274. package/src/shared/worker-client/functions/compute-context-id.function.ts +18 -0
  275. package/src/shared/worker-client/functions/create-worker-client.function.ts +70 -0
  276. package/src/shared/worker-client/functions/discover-daemon.function.ts +47 -0
  277. package/src/shared/worker-client/functions/resolve-db-path.function.ts +21 -0
  278. package/src/shared/worker-client/functions/spawn-daemon.function.ts +35 -0
  279. package/src/shared/worker-client/functions/wait-for-daemon.function.ts +34 -0
  280. package/src/shared/worker-client/index.ts +31 -0
  281. package/src/shared/worker-client/typings/add-section-result.model.ts +22 -0
  282. package/src/shared/worker-client/typings/content-result.model.ts +12 -0
  283. package/src/shared/worker-client/typings/daemon-info.model.ts +7 -0
  284. package/src/shared/worker-client/typings/gc-result.model.ts +12 -0
  285. package/src/shared/worker-client/typings/integrity-check-result.model.ts +43 -0
  286. package/src/shared/worker-client/typings/migrate-result.model.ts +11 -0
  287. package/src/shared/worker-client/typings/rebuild-result.model.ts +12 -0
  288. package/src/shared/worker-client/typings/remove-section-result.model.ts +7 -0
  289. package/src/shared/worker-client/typings/search-params.model.ts +12 -0
  290. package/src/shared/worker-client/typings/search-result.model.ts +14 -0
  291. package/src/shared/worker-client/typings/section.model.ts +27 -0
  292. package/src/shared/worker-client/typings/status-result.model.ts +14 -0
  293. package/src/shared/worker-client/typings/version-status.model.ts +28 -0
  294. package/src/shared/worker-client/typings/worker-client-error.interface.ts +8 -0
  295. package/src/shared/worker-client/typings/worker-client-options.interface.ts +30 -0
  296. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +1001 -0
  297. package/src/shared/worker-daemon/constants/daemon-defaults.constant.ts +29 -0
  298. package/src/shared/worker-daemon/functions/create-host-imports.function.ts +312 -0
  299. package/src/shared/worker-daemon/functions/create-ipc-server.function.ts +83 -0
  300. package/src/shared/worker-daemon/functions/load-wasm-modules.function.ts +98 -0
  301. package/src/shared/worker-daemon/functions/read-config.function.ts +83 -0
  302. package/src/shared/worker-daemon/functions/run-worker.function.ts +57 -0
  303. package/src/shared/worker-daemon/functions/start-daemon.function.ts +74 -0
  304. package/src/shared/worker-daemon/index.ts +16 -0
  305. package/src/shared/worker-daemon/typings/daemon-config.interface.ts +13 -0
  306. package/src/shared/worker-daemon/typings/ipc-handler.interface.ts +39 -0
  307. package/src/shared/worker-daemon/typings/wasm-modules.interface.ts +7 -0
  308. package/src/worker.ts +34 -0
@@ -0,0 +1,16 @@
1
+ import { encodeString } from './encode-string.function.ts';
2
+ import { encodeAddSectionParams } from './encode-add-section-params.function.ts';
3
+
4
+ import type { AddSectionInput } from './encode-add-section-params.function.ts';
5
+
6
+ export function encodeUpdateSectionParams(
7
+ oldKbid: string,
8
+ params: AddSectionInput,
9
+ ): Uint8Array {
10
+ const kbidBytes = encodeString(oldKbid);
11
+ const paramBytes = encodeAddSectionParams(params);
12
+ const result = new Uint8Array(kbidBytes.length + paramBytes.length);
13
+ result.set(kbidBytes, 0);
14
+ result.set(paramBytes, kbidBytes.length);
15
+ return result;
16
+ }
@@ -0,0 +1,36 @@
1
+ export { encodeString } from './functions/encode-string.function.ts';
2
+ export { encodeU32 } from './functions/encode-u32.function.ts';
3
+ export { encodeOptionString } from './functions/encode-option-string.function.ts';
4
+ export { encodeSectionType } from './functions/encode-section-type.function.ts';
5
+ export { encodeAddSectionParams } from './functions/encode-add-section-params.function.ts';
6
+ export { encodeUpdateSectionParams } from './functions/encode-update-section-params.function.ts';
7
+ export { encodeKbidList } from './functions/encode-kbid-list.function.ts';
8
+ export { encodeGroupParams } from './functions/encode-group-params.function.ts';
9
+ export { encodeIdentifierList } from './functions/encode-identifier-list.function.ts';
10
+ export { encodeSearchParams } from './functions/encode-search-params.function.ts';
11
+ export { encodeTypeFilterParam } from './functions/encode-type-filter-param.function.ts';
12
+ export { decodeString } from './functions/decode-string.function.ts';
13
+ export { decodeU32 } from './functions/decode-u32.function.ts';
14
+ export { decodeF32 } from './functions/decode-f32.function.ts';
15
+ export { decodeU64 } from './functions/decode-u64.function.ts';
16
+ export { decodeScoredResults } from './functions/decode-scored-results.function.ts';
17
+ export { decodeSectionRecords } from './functions/decode-section-records.function.ts';
18
+ export { decodeSectionRecordList } from './functions/decode-section-record-list.function.ts';
19
+ export { decodeDocumentManifest } from './functions/decode-document-manifest.function.ts';
20
+ export { decodeDocumentManifestList } from './functions/decode-document-manifest-list.function.ts';
21
+ export { decodeComposeOutput } from './functions/decode-compose-output.function.ts';
22
+ export { decodeKeyValueText } from './functions/decode-key-value-text.function.ts';
23
+ export { decodeRemoveFlag } from './functions/decode-remove-flag.function.ts';
24
+
25
+ export type { DecodeResult } from './functions/decode-string.function.ts';
26
+ export type { AddSectionInput } from './functions/encode-add-section-params.function.ts';
27
+ export type {
28
+ ScoredResult,
29
+ TermMatch,
30
+ } from './functions/decode-scored-results.function.ts';
31
+ export type { SectionRecord } from './functions/decode-section-records.function.ts';
32
+ export type {
33
+ DocumentManifest,
34
+ DocumentSection,
35
+ } from './functions/decode-document-manifest.function.ts';
36
+ export type { ComposeOutput } from './functions/decode-compose-output.function.ts';
@@ -0,0 +1,427 @@
1
+ import { connect } from 'node:net';
2
+ import type { Socket } from 'node:net';
3
+ import type { SearchParams } from '../typings/search-params.model.ts';
4
+ import type { SearchResult } from '../typings/search-result.model.ts';
5
+ import type {
6
+ AddSectionParams,
7
+ Section,
8
+ } from '../typings/section.model.ts';
9
+ import type { StatusResult } from '../typings/status-result.model.ts';
10
+ import type { AddSectionResult } from '../typings/add-section-result.model.ts';
11
+ import type { RemoveSectionResult } from '../typings/remove-section-result.model.ts';
12
+ import type { ContentResult } from '../typings/content-result.model.ts';
13
+ import type { IntegrityCheckResult } from '../typings/integrity-check-result.model.ts';
14
+ import type { GcResult } from '../typings/gc-result.model.ts';
15
+ import type { RebuildResult } from '../typings/rebuild-result.model.ts';
16
+ import type { MigrateResult } from '../typings/migrate-result.model.ts';
17
+ import type { VersionStatus } from '../typings/version-status.model.ts';
18
+ import type { SectionRecord } from '../../wasm-codec/functions/decode-section-records.function.ts';
19
+ import type { DocumentManifest } from '../../wasm-codec/functions/decode-document-manifest.function.ts';
20
+
21
+ /** Pending JSON-RPC call awaiting a response from the daemon. */
22
+ interface PendingCall {
23
+ resolve: (v: unknown) => void;
24
+ reject: (e: Error) => void;
25
+ }
26
+
27
+ /** Shape of a JSON-RPC 2.0 error object from the daemon. */
28
+ interface JsonRpcError {
29
+ readonly code: number;
30
+ readonly message: string;
31
+ }
32
+
33
+ /** Shape of a JSON-RPC 2.0 response from the daemon. */
34
+ interface JsonRpcResponse {
35
+ readonly id: number;
36
+ readonly result?: unknown;
37
+ readonly error?: JsonRpcError;
38
+ }
39
+
40
+ /**
41
+ * IPC client that communicates with the worker daemon over a Unix
42
+ * domain socket (or Windows named pipe) using JSON-RPC 2.0 with
43
+ * newline-delimited message framing.
44
+ *
45
+ * Call `connect()` before any other method and `disconnect()` when
46
+ * done to release the underlying socket.
47
+ */
48
+ export class WorkerClient {
49
+ /** Underlying socket; `null` when not connected. */
50
+ private socket: Socket | null = null;
51
+
52
+ /** Monotonically increasing request ID counter. */
53
+ private nextId = 1;
54
+
55
+ /** Map of outstanding request IDs to their resolve/reject pairs. */
56
+ private readonly pending = new Map<number, PendingCall>();
57
+
58
+ /** Partial line buffer for split TCP/IPC frames. */
59
+ private buffer = '';
60
+
61
+ /**
62
+ * @param socketPath - absolute path to the daemon's IPC socket
63
+ * (or Windows named pipe path)
64
+ * @param contextId - 16-character context identifier sent as
65
+ * `ctx` in every JSON-RPC request
66
+ */
67
+ constructor(
68
+ private readonly socketPath: string,
69
+ private readonly contextId: string,
70
+ ) {}
71
+
72
+ /**
73
+ * Establishes the IPC connection to the worker daemon.
74
+ *
75
+ * @throws {Error} if the connection cannot be established
76
+ */
77
+ async connect(): Promise<void> {
78
+ return new Promise<void>((resolve, reject) => {
79
+ this.socket = connect(this.socketPath, () => {
80
+ resolve();
81
+ });
82
+ this.socket.on('error', (err: Error) => {
83
+ reject(err);
84
+ });
85
+ this.socket.on('data', (chunk: Buffer) => {
86
+ this.handleData(chunk.toString());
87
+ });
88
+ });
89
+ }
90
+
91
+ /** Destroys the IPC socket and clears the connection state. */
92
+ disconnect(): void {
93
+ if (this.socket) {
94
+ this.socket.destroy();
95
+ this.socket = null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Searches the knowledge base.
101
+ *
102
+ * @param params - query parameters including the search string
103
+ * @returns ranked list of matching sections
104
+ */
105
+ async search(params: SearchParams): Promise<SearchResult[]> {
106
+ return this.call('search', params) as Promise<SearchResult[]>;
107
+ }
108
+
109
+ /**
110
+ * Adds a new section to the knowledge base.
111
+ *
112
+ * @param params - section content and metadata
113
+ * @returns the result including the assigned knowledge-base
114
+ * identifier and indexing statistics
115
+ */
116
+ async addSection(
117
+ params: AddSectionParams,
118
+ ): Promise<AddSectionResult> {
119
+ return this.call(
120
+ 'addSection',
121
+ params,
122
+ ) as Promise<AddSectionResult>;
123
+ }
124
+
125
+ /**
126
+ * Replaces an existing section's content and metadata.
127
+ *
128
+ * @param kbid - identifier of the section to update
129
+ * @param params - new content and metadata
130
+ * @returns the knowledge-base identifier of the updated section
131
+ */
132
+ async updateSection(
133
+ kbid: string,
134
+ params: AddSectionParams,
135
+ ): Promise<string> {
136
+ return this.call('updateSection', {
137
+ kbid,
138
+ ...params,
139
+ }) as Promise<string>;
140
+ }
141
+
142
+ /**
143
+ * Removes a section from the knowledge base.
144
+ *
145
+ * @param kbid - identifier of the section to remove
146
+ * @returns removal result with `removed` flag and elapsed time
147
+ */
148
+ async removeSection(kbid: string): Promise<RemoveSectionResult> {
149
+ return this.call('removeSection', {
150
+ kbid,
151
+ }) as Promise<RemoveSectionResult>;
152
+ }
153
+
154
+ /**
155
+ * Retrieves multiple sections by their identifiers.
156
+ *
157
+ * @param kbids - list of knowledge-base identifiers to fetch
158
+ * @returns sections in the order their IDs were requested
159
+ */
160
+ async readSections(kbids: string[]): Promise<Section[]> {
161
+ return this.call('readSections', {
162
+ kbids,
163
+ }) as Promise<Section[]>;
164
+ }
165
+
166
+ /**
167
+ * Groups a set of sections under a named document.
168
+ *
169
+ * @param title - human-readable document title
170
+ * @param kbids - identifiers of the sections to group
171
+ * @param docType - application-level document type tag; omit or
172
+ * pass an empty string for untagged documents
173
+ * @returns the assigned document identifier
174
+ */
175
+ async groupSections(
176
+ title: string,
177
+ kbids: string[],
178
+ docType?: string,
179
+ ): Promise<string> {
180
+ const result = (await this.call('groupSections', {
181
+ title,
182
+ kbids,
183
+ docType: docType ?? '',
184
+ })) as { docid: string } | string;
185
+ return typeof result === 'string' ? result : result.docid;
186
+ }
187
+
188
+ /**
189
+ * Removes the document grouping for the given document.
190
+ *
191
+ * The sections themselves are not deleted; only the grouping
192
+ * record is removed.
193
+ *
194
+ * @param docid - identifier of the document grouping to remove
195
+ */
196
+ async removeGrouping(docid: string): Promise<void> {
197
+ await this.call('removeGrouping', { docid });
198
+ }
199
+
200
+ /**
201
+ * Retrieves a full document record including its sections.
202
+ *
203
+ * @param docid - identifier of the document to retrieve
204
+ * @returns the document record as returned by the daemon
205
+ */
206
+ async retrieveDocument(docid: string): Promise<unknown> {
207
+ return this.call('retrieveDocument', { docid });
208
+ }
209
+
210
+ /**
211
+ * Composes a rendered Markdown document from one or more kbid
212
+ * or docid identifiers.
213
+ *
214
+ * @param ids - list of kbid or docid identifiers (may be mixed)
215
+ * @returns composed Markdown result with character count
216
+ */
217
+ async content(ids: string[]): Promise<ContentResult> {
218
+ return this.call('content', { ids }) as Promise<ContentResult>;
219
+ }
220
+
221
+ /**
222
+ * Runs an integrity check on the knowledge-base database.
223
+ *
224
+ * @returns a report of all issues found; `ok` is `true` when
225
+ * no errors were detected
226
+ */
227
+ async integrityCheck(): Promise<IntegrityCheckResult> {
228
+ return this.call(
229
+ 'integrityCheck',
230
+ {},
231
+ ) as Promise<IntegrityCheckResult>;
232
+ }
233
+
234
+ /**
235
+ * Removes unreferenced sections from the database.
236
+ *
237
+ * @returns a report of sections removed and bytes freed
238
+ */
239
+ async gc(): Promise<GcResult> {
240
+ return this.call('gc', {}) as Promise<GcResult>;
241
+ }
242
+
243
+ /**
244
+ * Reconstructs all index files from section files and document
245
+ * manifests on disk. Text and code sections are re-tokenized;
246
+ * image sections are skipped.
247
+ *
248
+ * @returns a report of sections and terms re-indexed
249
+ */
250
+ async rebuildIndexes(): Promise<RebuildResult> {
251
+ return this.call('rebuildIndexes', {}) as Promise<RebuildResult>;
252
+ }
253
+
254
+ /**
255
+ * Invalidates the in-memory cache entry for a single section.
256
+ *
257
+ * @param kbid - identifier of the section to evict from cache
258
+ */
259
+ async invalidate(kbid: string): Promise<void> {
260
+ await this.call('invalidate', { kbid });
261
+ }
262
+
263
+ /** Clears all entries from the daemon's in-memory cache. */
264
+ async invalidateAll(): Promise<void> {
265
+ await this.call('invalidateAll', {});
266
+ }
267
+
268
+ /**
269
+ * Retrieves diagnostic status information from the daemon.
270
+ *
271
+ * @returns current initialization state and cache statistics
272
+ */
273
+ async status(): Promise<StatusResult> {
274
+ return this.call('status', {}) as Promise<StatusResult>;
275
+ }
276
+
277
+ /**
278
+ * Returns database metadata and status from the daemon,
279
+ * including document count, section count, index size, and
280
+ * cache statistics.
281
+ *
282
+ * @returns database metadata from the daemon's cached state
283
+ */
284
+ async dbStatus(): Promise<StatusResult> {
285
+ return this.call('dbStatus', {}) as Promise<StatusResult>;
286
+ }
287
+
288
+ /**
289
+ * Initialises a new `.kbdb` database directory at the given path
290
+ * by sending an init request to the worker daemon.
291
+ *
292
+ * The daemon creates all required subdirectories and seed files via
293
+ * the `worker_init_directory` WASM export.
294
+ *
295
+ * @param targetPath - absolute path to the directory that will
296
+ * contain the new `.kbdb` database
297
+ * @throws {Error} if the `.kbdb` directory already exists or the
298
+ * daemon cannot create the layout
299
+ */
300
+ async initDirectory(targetPath: string): Promise<void> {
301
+ await this.call('initDirectory', { targetPath });
302
+ }
303
+
304
+ /**
305
+ * Runs all pending database migrations for the `.kbdb` directory
306
+ * at the given path.
307
+ *
308
+ * Delegates to the `worker_migrate` WASM export on the daemon.
309
+ * Each migration step updates `catalog.toml` on success, so
310
+ * retrying after a partial failure is safe.
311
+ *
312
+ * @param targetPath - absolute path to the `.kbdb` database root
313
+ * @returns migration report with old version, new version, and
314
+ * number of migration steps applied
315
+ */
316
+ async migrateDatabase(targetPath: string): Promise<MigrateResult> {
317
+ return this.call('migrateDatabase', {
318
+ targetPath,
319
+ }) as Promise<MigrateResult>;
320
+ }
321
+
322
+ /**
323
+ * Checks the format version of the `.kbdb` database at the given
324
+ * path against the version required by the current WASM engine.
325
+ *
326
+ * This is a read-only operation: it reads `catalog.toml` and
327
+ * returns the compatibility status without making any changes.
328
+ *
329
+ * @param targetPath - absolute path to the `.kbdb` database root
330
+ * @returns version compatibility report
331
+ */
332
+ async checkVersion(targetPath: string): Promise<VersionStatus> {
333
+ return this.call('checkVersion', {
334
+ targetPath,
335
+ }) as Promise<VersionStatus>;
336
+ }
337
+
338
+ /**
339
+ * Retrieves all sections whose type name matches the given string.
340
+ *
341
+ * @param sectionType - the application-level type name to filter by
342
+ * @returns all section records with a matching type name
343
+ */
344
+ async listByType(sectionType: string): Promise<SectionRecord[]> {
345
+ return this.call('listByType', {
346
+ sectionType,
347
+ }) as Promise<SectionRecord[]>;
348
+ }
349
+
350
+ /**
351
+ * Retrieves all documents whose type name matches the given string.
352
+ *
353
+ * @param docType - the application-level document type to filter by
354
+ * @returns all document manifests with a matching type name
355
+ */
356
+ async listDocumentsByType(
357
+ docType: string,
358
+ ): Promise<DocumentManifest[]> {
359
+ return this.call('listDocumentsByType', {
360
+ docType,
361
+ }) as Promise<DocumentManifest[]>;
362
+ }
363
+
364
+ /**
365
+ * Sends a JSON-RPC 2.0 request and awaits the response.
366
+ *
367
+ * @param method - the RPC method name
368
+ * @param params - parameters to include in the request
369
+ * @throws {Error} if not connected
370
+ * @throws {Error} when the daemon returns an error response
371
+ */
372
+ private async call(
373
+ method: string,
374
+ params: unknown,
375
+ ): Promise<unknown> {
376
+ const socket = this.socket;
377
+ if (!socket) {
378
+ throw new Error('not connected');
379
+ }
380
+
381
+ const id = this.nextId++;
382
+ const request = {
383
+ jsonrpc: '2.0',
384
+ id,
385
+ method,
386
+ params: { ctx: this.contextId, ...(params as object) },
387
+ };
388
+
389
+ return new Promise<unknown>((resolve, reject) => {
390
+ this.pending.set(id, { resolve, reject });
391
+ socket.write(JSON.stringify(request) + '\n');
392
+ });
393
+ }
394
+
395
+ /**
396
+ * Processes incoming data from the socket, splitting on newlines
397
+ * and dispatching complete JSON-RPC response objects.
398
+ *
399
+ * @param data - raw string chunk received from the socket
400
+ */
401
+ private handleData(data: string): void {
402
+ this.buffer += data;
403
+ const lines = this.buffer.split('\n');
404
+ this.buffer = lines.pop() ?? '';
405
+
406
+ for (const line of lines) {
407
+ if (!line.trim()) continue;
408
+ try {
409
+ const response = JSON.parse(line) as JsonRpcResponse;
410
+ const pending = this.pending.get(response.id);
411
+ if (pending) {
412
+ this.pending.delete(response.id);
413
+ if (response.error) {
414
+ const err = new Error(response.error.message);
415
+ (err as unknown as Record<string, unknown>).code =
416
+ response.error.code;
417
+ pending.reject(err);
418
+ } else {
419
+ pending.resolve(response.result);
420
+ }
421
+ }
422
+ } catch {
423
+ // Ignore unparseable lines
424
+ }
425
+ }
426
+ }
427
+ }
@@ -0,0 +1,18 @@
1
+ import { computeSha256 } from '../../hash/functions/compute-sha256.ts';
2
+
3
+ /**
4
+ * Computes a short context identifier for an absolute path.
5
+ *
6
+ * Hashes the path with SHA-256 and returns the first 16 hex
7
+ * characters. The result is stable for the same input and unique
8
+ * enough to avoid accidental collisions across typical path sets.
9
+ *
10
+ * @param absolutePath - the absolute filesystem path to identify
11
+ * @returns a 16-character lowercase hex string
12
+ */
13
+ export async function computeContextId(
14
+ absolutePath: string,
15
+ ): Promise<string> {
16
+ const hash = await computeSha256(absolutePath);
17
+ return hash.slice(0, 16);
18
+ }
@@ -0,0 +1,70 @@
1
+ import { existsSync, readFileSync, unlinkSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { WorkerClient } from '../classes/worker-client.class.ts';
5
+ import { resolveDbPath } from './resolve-db-path.function.ts';
6
+ import { computeContextId } from './compute-context-id.function.ts';
7
+ import { discoverDaemon } from './discover-daemon.function.ts';
8
+ import { spawnDaemon } from './spawn-daemon.function.ts';
9
+ import { waitForDaemon } from './wait-for-daemon.function.ts';
10
+ import { detectRuntime } from '../../runtime/functions/detect-runtime.ts';
11
+ import { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';
12
+ import type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';
13
+
14
+ /**
15
+ * Creates and connects a `WorkerClient` to the worker daemon.
16
+ *
17
+ * Resolves the context path, derives a stable context identifier,
18
+ * and checks whether a daemon is already running. If no daemon is
19
+ * found and `autoSpawn` is not `false`, a new daemon process is
20
+ * spawned and the factory waits for its PID file to appear before
21
+ * connecting.
22
+ *
23
+ * @param options - optional configuration for path resolution,
24
+ * auto-spawn behaviour, and connection timeout
25
+ * @returns a connected `WorkerClient` ready to send requests
26
+ * @throws {Error} if the `.kbdb` directory cannot be found
27
+ * @throws {Error} if the socket connection cannot be established
28
+ */
29
+ export async function createWorkerClient(
30
+ options?: WorkerClientOptions,
31
+ ): Promise<WorkerClient> {
32
+ const dbPath =
33
+ options?.contextPath ?? resolveDbPath(options?.dbPath);
34
+ const contextId = await computeContextId(dbPath);
35
+ const socketPath = getIpcPath(contextId);
36
+
37
+ let daemon = discoverDaemon(contextId);
38
+
39
+ if (!daemon && options?.autoSpawn !== false) {
40
+ const runtime = detectRuntime();
41
+ spawnDaemon(dbPath, runtime, options?.workerScript);
42
+ await waitForDaemon(contextId, options?.connectTimeoutMs);
43
+ daemon = discoverDaemon(contextId);
44
+ }
45
+
46
+ if (!daemon) {
47
+ throw new Error(
48
+ `kbdb worker daemon did not start: ${readCrashReason(contextId)}`,
49
+ );
50
+ }
51
+
52
+ const client = new WorkerClient(socketPath, contextId);
53
+ await client.connect();
54
+ return client;
55
+ }
56
+
57
+ function readCrashReason(contextId: string): string {
58
+ const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);
59
+ if (!existsSync(crashPath)) {
60
+ return 'daemon failed to start (no details available)';
61
+ }
62
+ try {
63
+ const raw = readFileSync(crashPath, 'utf-8');
64
+ const crash = JSON.parse(raw) as { error?: string };
65
+ unlinkSync(crashPath);
66
+ return crash.error ?? 'unknown error (crash log empty)';
67
+ } catch {
68
+ return 'daemon failed to start (crash log unreadable)';
69
+ }
70
+ }
@@ -0,0 +1,47 @@
1
+ import { existsSync, readFileSync, unlinkSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { isProcessAlive } from '../../platform/functions/is-process-alive.function.ts';
5
+ import type { DaemonInfo } from '../typings/daemon-info.model.ts';
6
+
7
+ export type { DaemonInfo };
8
+
9
+ /**
10
+ * Discovers a running worker daemon for the given context.
11
+ *
12
+ * Reads the PID file at `<tmpdir>/kbdb-<contextId>.pid`. If the
13
+ * file exists and the process is alive, returns its PID and the
14
+ * expected socket path. If the file is stale (process dead or PID
15
+ * unparseable), removes the PID file and returns `null`.
16
+ *
17
+ * @param contextId - the 16-character context identifier
18
+ * @returns daemon location info, or `null` if no live daemon found
19
+ */
20
+ export function discoverDaemon(contextId: string): DaemonInfo | null {
21
+ const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);
22
+
23
+ if (!existsSync(pidPath)) return null;
24
+
25
+ const pidStr = readFileSync(pidPath, 'utf-8').trim();
26
+ const pid = parseInt(pidStr, 10);
27
+
28
+ if (isNaN(pid) || !isProcessAlive(pid)) {
29
+ try {
30
+ unlinkSync(pidPath);
31
+ } catch {
32
+ // Stale PID file removal is best-effort
33
+ }
34
+ return null;
35
+ }
36
+
37
+ const socketPath = join(tmpdir(), `kbdb-${contextId}.sock`);
38
+
39
+ const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);
40
+ try {
41
+ unlinkSync(crashPath);
42
+ } catch {
43
+ // stale crash file removal is best-effort
44
+ }
45
+
46
+ return { pid, socketPath };
47
+ }
@@ -0,0 +1,21 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+
4
+ /**
5
+ * Resolves the absolute path to the `.kbdb` database directory.
6
+ *
7
+ * Searches for a `.kbdb` sub-directory inside `targetDir`. When
8
+ * `targetDir` is omitted, `process.cwd()` is used as the base.
9
+ *
10
+ * @param targetDir - directory to search in; defaults to cwd
11
+ * @throws {Error} if no `.kbdb` directory exists at the resolved
12
+ * path
13
+ */
14
+ export function resolveDbPath(targetDir?: string): string {
15
+ const base = targetDir ? resolve(targetDir) : process.cwd();
16
+ const dbPath = join(base, '.kbdb');
17
+ if (!existsSync(dbPath)) {
18
+ throw new Error(`database not found: ${dbPath}`);
19
+ }
20
+ return dbPath;
21
+ }
@@ -0,0 +1,35 @@
1
+ import { spawn } from 'node:child_process';
2
+ import type { Runtime } from '../../runtime/typings/runtime.ts';
3
+
4
+ /**
5
+ * Spawns a detached worker daemon process for the given context.
6
+ *
7
+ * @param contextPath - absolute path to the context directory the
8
+ * daemon should serve
9
+ * @param runtime - the current JavaScript runtime environment
10
+ * @param workerScript - absolute path to the worker daemon script,
11
+ * resolved at the entry point by `resolveWorkerScript`
12
+ */
13
+ export function spawnDaemon(
14
+ contextPath: string,
15
+ runtime: Runtime,
16
+ workerScript?: string,
17
+ ): void {
18
+ if (!workerScript) {
19
+ throw new Error(
20
+ 'workerScript must be provided' + ' (resolve at entry point)',
21
+ );
22
+ }
23
+ const execPath = runtime === 'deno' ? 'deno' : process.execPath;
24
+
25
+ const args =
26
+ runtime === 'deno'
27
+ ? ['run', '--allow-all', workerScript, contextPath]
28
+ : [workerScript, contextPath];
29
+
30
+ const child = spawn(execPath, args, {
31
+ detached: true,
32
+ stdio: 'ignore',
33
+ });
34
+ child.unref();
35
+ }