@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
package/dist/cli.cjs ADDED
@@ -0,0 +1,3598 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/shared/runtime/functions/detect-runtime.ts
5
+ function detectRuntime() {
6
+ if (typeof globalThis !== "undefined" && "Deno" in globalThis) {
7
+ return "deno";
8
+ }
9
+ return "node";
10
+ }
11
+
12
+ // src/shared/runtime/functions/get-args.ts
13
+ function getArgs() {
14
+ if (detectRuntime() === "deno") {
15
+ const g = globalThis;
16
+ const deno = g["Deno"];
17
+ return deno?.args ?? [];
18
+ }
19
+ return process.argv.slice(2);
20
+ }
21
+
22
+ // src/shared/dir-resolver/functions/resolve-base-dir.function.ts
23
+ var import_node_path = require("node:path");
24
+ var import_node_url = require("node:url");
25
+ function resolveScriptDir(entryUrl, entryDirname) {
26
+ if (entryDirname) return entryDirname;
27
+ if (entryUrl.startsWith("file:"))
28
+ return (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(entryUrl));
29
+ return (0, import_node_path.dirname)(entryUrl);
30
+ }
31
+ function resolveBaseDir(entryUrl, entryDirname) {
32
+ const scriptDir = typeof __dirname !== "undefined" ? __dirname : resolveScriptDir(entryUrl, entryDirname);
33
+ return { scriptDir, cwd: process.cwd() };
34
+ }
35
+
36
+ // src/shared/dir-resolver/functions/resolve-worker-script.function.ts
37
+ var import_node_path2 = require("node:path");
38
+ function resolveWorkerScript(scriptDir, runtime2) {
39
+ if (runtime2 === "deno") {
40
+ return (0, import_node_path2.join)(scriptDir, "worker.ts");
41
+ }
42
+ return (0, import_node_path2.join)(scriptDir, "kbdb-worker.cjs");
43
+ }
44
+
45
+ // src/shared/cli/constants/defaults.constant.ts
46
+ var DEFAULT_LIMIT = 20;
47
+ var DEFAULT_FORMAT = "json";
48
+ var DEFAULT_MODE = "sections";
49
+ var SUPPORTED_EXTENSIONS = [
50
+ ".md",
51
+ ".txt",
52
+ ".rst",
53
+ ".adoc"
54
+ ];
55
+
56
+ // src/shared/cli/functions/parse-args.function.ts
57
+ function parseArgs(argv) {
58
+ const options = {
59
+ command: "",
60
+ format: DEFAULT_FORMAT,
61
+ mode: DEFAULT_MODE,
62
+ limit: DEFAULT_LIMIT,
63
+ args: []
64
+ };
65
+ let i = 0;
66
+ while (i < argv.length) {
67
+ const arg = argv[i];
68
+ switch (arg) {
69
+ case "--help":
70
+ case "-h":
71
+ if (options.command) {
72
+ options.args.unshift(options.command);
73
+ options.command = "help";
74
+ } else {
75
+ options.command = "help";
76
+ }
77
+ return options;
78
+ case "--version":
79
+ case "-v":
80
+ options.command = "version";
81
+ return options;
82
+ case "--init":
83
+ console.error(
84
+ 'warning: --init is deprecated, use "kbdb db init"'
85
+ );
86
+ options.command = "init";
87
+ break;
88
+ case "--migrate":
89
+ console.error(
90
+ 'warning: --migrate is deprecated, use "kbdb db migrate"'
91
+ );
92
+ options.command = "migrate";
93
+ break;
94
+ case "--db":
95
+ options.dbPath = argv[++i];
96
+ break;
97
+ case "--format":
98
+ case "-f":
99
+ options.format = argv[++i] ?? DEFAULT_FORMAT;
100
+ break;
101
+ case "--mode":
102
+ case "-m":
103
+ options.mode = argv[++i] ?? DEFAULT_MODE;
104
+ break;
105
+ case "--limit":
106
+ case "-l":
107
+ options.limit = parseInt(argv[++i] ?? "", 10) || DEFAULT_LIMIT;
108
+ break;
109
+ case "--title":
110
+ options.title = argv[++i];
111
+ break;
112
+ case "--description":
113
+ options.description = argv[++i];
114
+ break;
115
+ case "--docid":
116
+ options.docid = argv[++i];
117
+ break;
118
+ case "--name":
119
+ options.name = argv[++i];
120
+ break;
121
+ case "--persona":
122
+ options.persona = argv[++i];
123
+ break;
124
+ case "--body":
125
+ options.body = argv[++i];
126
+ break;
127
+ case "--skills":
128
+ options.skills = (argv[++i] ?? "").split(",");
129
+ break;
130
+ case "--content":
131
+ case "-c":
132
+ options.content = true;
133
+ break;
134
+ default:
135
+ if (!options.command) {
136
+ options.command = arg;
137
+ } else if (!options.args.length && (options.command === "db" || options.command === "skill" || options.command === "agent")) {
138
+ options.command = `${options.command}-${arg}`;
139
+ } else {
140
+ options.args.push(arg);
141
+ }
142
+ }
143
+ i++;
144
+ }
145
+ return options;
146
+ }
147
+
148
+ // src/shared/cli/functions/format-output.function.ts
149
+ function formatOutput(results, format) {
150
+ switch (format) {
151
+ case "json":
152
+ return JSON.stringify(results, null, 2);
153
+ case "text":
154
+ return formatText(results);
155
+ case "mcp":
156
+ return formatMcp(results);
157
+ }
158
+ }
159
+ function formatText(results) {
160
+ if (results.length === 0) return "No results found.";
161
+ return results.map(
162
+ (r, i) => `${String(i + 1)}. [${r.kbid}] (score: ${r.score.toFixed(4)})
163
+ ${r.preview}
164
+ matches: ${r.matches.map((m) => m.term).join(", ")}`
165
+ ).join("\n\n");
166
+ }
167
+ function formatMcp(results) {
168
+ return JSON.stringify({
169
+ type: "text",
170
+ text: results.map(
171
+ (r) => `[${r.kbid}] score=${r.score.toFixed(4)} \u2014 ${r.preview}`
172
+ ).join("\n")
173
+ });
174
+ }
175
+
176
+ // src/shared/cli/functions/run-search.function.ts
177
+ async function runSearch(client, options) {
178
+ const query = options.args.join(" ").trim();
179
+ if (!query) return [];
180
+ const results = await client.search({
181
+ query,
182
+ mode: options.mode,
183
+ limit: options.limit
184
+ });
185
+ return results.map((r) => ({
186
+ kbid: r.kbid,
187
+ score: r.score,
188
+ preview: "",
189
+ matches: r.matches
190
+ }));
191
+ }
192
+
193
+ // src/shared/cli/functions/run-learn.function.ts
194
+ var import_node_fs = require("node:fs");
195
+ var import_node_path3 = require("node:path");
196
+ async function runLearn(client, options, io) {
197
+ const results = [];
198
+ let stdinConsumed = false;
199
+ const readStdin = io?.readStdin ?? readProcessStdin;
200
+ for (const target of options.args) {
201
+ if (target === "-") {
202
+ if (stdinConsumed) continue;
203
+ stdinConsumed = true;
204
+ const content = await readStdin();
205
+ const result = await client.addSection({
206
+ sectionType: "text",
207
+ content,
208
+ title: options.title,
209
+ description: options.description,
210
+ docid: options.docid
211
+ });
212
+ results.push({
213
+ kbid: result.kbid,
214
+ path: "-",
215
+ size: content.length,
216
+ skipped: false
217
+ });
218
+ continue;
219
+ }
220
+ const files = collectFiles(target);
221
+ for (const file of files) {
222
+ const content = (0, import_node_fs.readFileSync)(file, "utf-8");
223
+ const result = await client.addSection({
224
+ sectionType: "text",
225
+ content,
226
+ title: options.title,
227
+ docid: options.docid
228
+ });
229
+ results.push({
230
+ kbid: result.kbid,
231
+ path: file,
232
+ size: content.length,
233
+ skipped: false
234
+ });
235
+ }
236
+ }
237
+ return results;
238
+ }
239
+ function readProcessStdin() {
240
+ return new Promise((resolve4) => {
241
+ const chunks = [];
242
+ process.stdin.on("data", (chunk) => {
243
+ chunks.push(chunk);
244
+ });
245
+ process.stdin.on("end", () => {
246
+ resolve4(Buffer.concat(chunks).toString("utf-8"));
247
+ });
248
+ process.stdin.resume();
249
+ });
250
+ }
251
+ function collectFiles(target) {
252
+ try {
253
+ const stat = (0, import_node_fs.statSync)(target);
254
+ if (stat.isFile()) {
255
+ return isSupportedFile(target) ? [target] : [];
256
+ }
257
+ if (stat.isDirectory()) {
258
+ return scanDirectory(target);
259
+ }
260
+ } catch {
261
+ }
262
+ return [];
263
+ }
264
+ function scanDirectory(dir) {
265
+ const files = [];
266
+ for (const entry of (0, import_node_fs.readdirSync)(dir)) {
267
+ if (entry.startsWith(".")) continue;
268
+ const full = (0, import_node_path3.join)(dir, entry);
269
+ try {
270
+ const stat = (0, import_node_fs.statSync)(full);
271
+ if (stat.isDirectory()) {
272
+ files.push(...scanDirectory(full));
273
+ } else if (isSupportedFile(full)) {
274
+ files.push(full);
275
+ }
276
+ } catch {
277
+ }
278
+ }
279
+ return files;
280
+ }
281
+ function isSupportedFile(path) {
282
+ if ((0, import_node_path3.basename)(path).startsWith(".")) return false;
283
+ const ext = (0, import_node_path3.extname)(path).toLowerCase();
284
+ return SUPPORTED_EXTENSIONS.includes(ext);
285
+ }
286
+
287
+ // src/shared/cli/functions/run-unlearn.function.ts
288
+ async function runUnlearn(client, options) {
289
+ const results = [];
290
+ for (const kbid of options.args) {
291
+ const result = await client.removeSection(kbid);
292
+ results.push({ kbid, removed: result.removed });
293
+ }
294
+ return results;
295
+ }
296
+
297
+ // src/shared/cli/functions/run-content.function.ts
298
+ async function runContent(client, options) {
299
+ return client.content(options.args);
300
+ }
301
+
302
+ // src/shared/cli/functions/run-check.function.ts
303
+ async function runCheck(client, _options) {
304
+ return client.integrityCheck();
305
+ }
306
+
307
+ // src/shared/cli/functions/run-gc.function.ts
308
+ async function runGc(client, _options) {
309
+ return client.gc();
310
+ }
311
+
312
+ // src/shared/cli/functions/run-rebuild.function.ts
313
+ async function runRebuild(client, _options) {
314
+ return client.rebuildIndexes();
315
+ }
316
+
317
+ // src/shared/cli/functions/find-db.function.ts
318
+ var import_node_fs2 = require("node:fs");
319
+ var import_node_path4 = require("node:path");
320
+ function findDb(dbPath) {
321
+ const base = dbPath ? (0, import_node_path4.resolve)(dbPath) : process.cwd();
322
+ const kbdbDir = (0, import_node_path4.join)(base, ".kbdb");
323
+ return (0, import_node_fs2.existsSync)(kbdbDir) ? kbdbDir : null;
324
+ }
325
+
326
+ // src/shared/cli/functions/run-init.function.ts
327
+ var import_node_fs3 = require("node:fs");
328
+ var import_node_path5 = require("node:path");
329
+ var DB_FORMAT_VERSION = 1;
330
+ var CATALOG_TOML = `version = ${DB_FORMAT_VERSION.toString()}
331
+ section_count = 0
332
+ document_count = 0
333
+ created_at = 0
334
+ updated_at = 0
335
+ checksum = ""
336
+ `;
337
+ var WORKER_TOML = "# kbdb worker configuration\n";
338
+ var GITIGNORE = [
339
+ "# kbdb binary indexes (auto-generated)",
340
+ "corpus.bin",
341
+ "inverted.idx",
342
+ "positional.idx",
343
+ ""
344
+ ].join("\n");
345
+ function createScaffold(dbDir) {
346
+ (0, import_node_fs3.mkdirSync)(dbDir, { recursive: true });
347
+ (0, import_node_fs3.mkdirSync)((0, import_node_path5.join)(dbDir, "sections"));
348
+ (0, import_node_fs3.mkdirSync)((0, import_node_path5.join)(dbDir, "documents"));
349
+ (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(dbDir, "catalog.toml"), CATALOG_TOML);
350
+ (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(dbDir, "corpus.bin"), "");
351
+ (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(dbDir, "inverted.idx"), "");
352
+ (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(dbDir, "positional.idx"), "");
353
+ (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(dbDir, "worker.toml"), WORKER_TOML);
354
+ (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(dbDir, ".gitignore"), GITIGNORE);
355
+ }
356
+ function runInit(options) {
357
+ const basePath = options.dbPath ? (0, import_node_path5.resolve)(options.dbPath) : process.cwd();
358
+ const dbDir = (0, import_node_path5.join)(basePath, ".kbdb");
359
+ try {
360
+ if ((0, import_node_fs3.existsSync)(dbDir)) {
361
+ return {
362
+ ok: false,
363
+ targetPath: dbDir,
364
+ errorMessage: `database directory already exists: ${dbDir}`
365
+ };
366
+ }
367
+ createScaffold(dbDir);
368
+ return { ok: true, targetPath: dbDir };
369
+ } catch (err) {
370
+ const errorMessage = err instanceof Error ? err.message : String(err);
371
+ return { ok: false, targetPath: dbDir, errorMessage };
372
+ }
373
+ }
374
+
375
+ // src/shared/cli/functions/error-to-message.function.ts
376
+ function errorToMessage(err) {
377
+ return err instanceof Error ? err.message : String(err);
378
+ }
379
+
380
+ // src/shared/cli/functions/is-stdin-tty.function.ts
381
+ function isStdinTty(stdin = process.stdin) {
382
+ return stdin.isTTY ?? false;
383
+ }
384
+
385
+ // src/shared/cli/functions/prompt-user.function.ts
386
+ var import_node_readline = require("node:readline");
387
+ async function promptUser(question, io) {
388
+ const ask = io?.ask ?? askReadline;
389
+ const answer = await ask(question);
390
+ return answer.trim();
391
+ }
392
+ function askReadline(question) {
393
+ return new Promise((resolve4) => {
394
+ const rl = (0, import_node_readline.createInterface)({
395
+ input: process.stdin,
396
+ output: process.stdout
397
+ });
398
+ rl.question(question, (answer) => {
399
+ rl.close();
400
+ resolve4(answer);
401
+ });
402
+ });
403
+ }
404
+
405
+ // src/shared/cli/functions/run-status.function.ts
406
+ async function runStatus(client, _options) {
407
+ return client.dbStatus();
408
+ }
409
+
410
+ // src/shared/cli/functions/run-db-init.function.ts
411
+ function runDbInit(options, runInitFn) {
412
+ const result = runInitFn(options);
413
+ if (result.ok) {
414
+ return {
415
+ output: JSON.stringify(
416
+ { path: result.targetPath, created: true },
417
+ null,
418
+ 2
419
+ ),
420
+ exitCode: 0
421
+ };
422
+ }
423
+ return {
424
+ error: result.errorMessage ?? "init failed",
425
+ exitCode: 1
426
+ };
427
+ }
428
+
429
+ // src/shared/cli/functions/run-db-migrate.function.ts
430
+ async function runDbMigrate(client, options) {
431
+ const dbPath = options.dbPath ?? process.cwd();
432
+ return client.migrateDatabase(dbPath);
433
+ }
434
+
435
+ // src/shared/mcp/functions/extract-skill-arguments.function.ts
436
+ function extractSkillArguments(body) {
437
+ const seen = /* @__PURE__ */ new Set();
438
+ const args = [];
439
+ const re = /\{\{(\w+)\}\}/g;
440
+ let match;
441
+ while ((match = re.exec(body)) !== null) {
442
+ const name = match[1];
443
+ if (!seen.has(name)) {
444
+ seen.add(name);
445
+ args.push({ name, required: true });
446
+ }
447
+ }
448
+ return args;
449
+ }
450
+
451
+ // src/shared/mcp/functions/serialize-skill-content.function.ts
452
+ function serializeSkillContent(skill) {
453
+ return JSON.stringify(skill);
454
+ }
455
+
456
+ // src/shared/cli/functions/run-skill-learn.function.ts
457
+ async function runSkillLearn(client, options) {
458
+ const name = options.name;
459
+ if (!name) {
460
+ return { error: "--name is required", exitCode: 1 };
461
+ }
462
+ const body = options.body;
463
+ if (!body) {
464
+ return { error: "--body is required", exitCode: 1 };
465
+ }
466
+ const args = extractSkillArguments(body);
467
+ const skill = {
468
+ name,
469
+ description: options.description,
470
+ arguments: args.length > 0 ? args : void 0,
471
+ body
472
+ };
473
+ const json = serializeSkillContent(skill);
474
+ const result = await client.addSection({
475
+ sectionType: "skill",
476
+ content: json,
477
+ title: name,
478
+ description: options.description
479
+ });
480
+ return {
481
+ output: JSON.stringify(result, null, 2),
482
+ exitCode: 0
483
+ };
484
+ }
485
+
486
+ // src/shared/cli/functions/run-skill-list.function.ts
487
+ async function runSkillList(client, _options) {
488
+ const records = await client.listByType("skill");
489
+ const items = records.map((r) => {
490
+ let argumentCount = 0;
491
+ try {
492
+ const parsed = JSON.parse(r.content);
493
+ if (Array.isArray(parsed["arguments"])) {
494
+ argumentCount = parsed["arguments"].length;
495
+ }
496
+ } catch {
497
+ }
498
+ return {
499
+ kbid: r.kbid,
500
+ name: r.title,
501
+ description: r.description,
502
+ argumentCount
503
+ };
504
+ });
505
+ return {
506
+ output: JSON.stringify(items, null, 2),
507
+ exitCode: 0
508
+ };
509
+ }
510
+
511
+ // src/shared/mcp/functions/parse-skill-content.function.ts
512
+ function parseSkillContent(json) {
513
+ const raw = JSON.parse(json);
514
+ if (typeof raw["name"] !== "string" || !raw["name"]) {
515
+ throw new Error("skill name is required");
516
+ }
517
+ if (typeof raw["body"] !== "string") {
518
+ throw new Error("skill body is required");
519
+ }
520
+ return {
521
+ name: raw["name"],
522
+ description: typeof raw["description"] === "string" ? raw["description"] : void 0,
523
+ arguments: Array.isArray(raw["arguments"]) ? raw["arguments"] : void 0,
524
+ body: raw["body"]
525
+ };
526
+ }
527
+
528
+ // src/shared/cli/functions/run-skill-get.function.ts
529
+ async function runSkillGet(client, options) {
530
+ const identifier = options.args[0] ?? options.name;
531
+ if (!identifier) {
532
+ return {
533
+ error: "skill name or kbid required",
534
+ exitCode: 1
535
+ };
536
+ }
537
+ let content;
538
+ if (/^[0-9a-f]{16,}$/i.test(identifier)) {
539
+ const sections = await client.readSections([identifier]);
540
+ if (sections.length > 0) {
541
+ content = sections[0]?.content;
542
+ }
543
+ }
544
+ if (content === void 0) {
545
+ const records = await client.listByType("skill");
546
+ const match = records.filter((r) => r.title === identifier).pop();
547
+ if (match) {
548
+ content = match.content;
549
+ }
550
+ }
551
+ if (content === void 0) {
552
+ return {
553
+ error: `skill not found: ${identifier}`,
554
+ exitCode: 1
555
+ };
556
+ }
557
+ const skill = parseSkillContent(content);
558
+ return {
559
+ output: JSON.stringify(skill, null, 2),
560
+ exitCode: 0
561
+ };
562
+ }
563
+
564
+ // src/shared/cli/functions/run-skill-delete.function.ts
565
+ async function runSkillDelete(client, options) {
566
+ const kbid = options.args[0];
567
+ if (!kbid) {
568
+ return { error: "kbid is required", exitCode: 1 };
569
+ }
570
+ const result = await client.removeSection(kbid);
571
+ return {
572
+ output: JSON.stringify(
573
+ { kbid, removed: result.removed },
574
+ null,
575
+ 2
576
+ ),
577
+ exitCode: 0
578
+ };
579
+ }
580
+
581
+ // src/shared/cli/functions/run-agent-create.function.ts
582
+ async function runAgentCreate(client, options) {
583
+ const name = options.name;
584
+ if (!name) {
585
+ return { error: "--name is required", exitCode: 1 };
586
+ }
587
+ const persona = options.persona;
588
+ if (!persona) {
589
+ return { error: "--persona is required", exitCode: 1 };
590
+ }
591
+ const skills = options.skills ?? [];
592
+ if (skills.length > 0) {
593
+ const sections = await client.readSections(skills);
594
+ const found = new Set(sections.map((s) => s.kbid));
595
+ const missing = skills.filter((k) => !found.has(k));
596
+ if (missing.length > 0) {
597
+ return {
598
+ error: `skill not found: ${missing.join(", ")}`,
599
+ exitCode: 1
600
+ };
601
+ }
602
+ }
603
+ const metadata = JSON.stringify({
604
+ name,
605
+ description: options.description ?? "",
606
+ persona
607
+ });
608
+ const metaResult = await client.addSection({
609
+ sectionType: "text",
610
+ content: metadata,
611
+ title: name,
612
+ description: options.description
613
+ });
614
+ const allKbids = [metaResult.kbid, ...skills];
615
+ const docid = await client.groupSections(name, allKbids, "agent");
616
+ return {
617
+ output: JSON.stringify(
618
+ { docid, name, skillCount: skills.length },
619
+ null,
620
+ 2
621
+ ),
622
+ exitCode: 0
623
+ };
624
+ }
625
+
626
+ // src/shared/cli/functions/run-agent-list.function.ts
627
+ async function runAgentList(client, _options) {
628
+ const docs = await client.listDocumentsByType("agent");
629
+ const items = docs.map((d) => ({
630
+ docid: d.docid,
631
+ name: d.title,
632
+ skillCount: Math.max(0, d.sections.length - 1)
633
+ }));
634
+ return {
635
+ output: JSON.stringify(items, null, 2),
636
+ exitCode: 0
637
+ };
638
+ }
639
+
640
+ // src/shared/cli/functions/run-agent-get.function.ts
641
+ async function readAgentMeta(client, metaKbid, fallbackName) {
642
+ const sections = await client.readSections([metaKbid]);
643
+ const first = sections.at(0);
644
+ if (!first) {
645
+ return { name: fallbackName, description: "", persona: "" };
646
+ }
647
+ try {
648
+ const meta = JSON.parse(first.content);
649
+ return {
650
+ name: typeof meta["name"] === "string" ? meta["name"] : fallbackName,
651
+ description: typeof meta["description"] === "string" ? meta["description"] : "",
652
+ persona: typeof meta["persona"] === "string" ? meta["persona"] : ""
653
+ };
654
+ } catch {
655
+ return { name: fallbackName, description: "", persona: "" };
656
+ }
657
+ }
658
+ async function resolveSkills(client, skillRefs) {
659
+ if (skillRefs.length === 0) {
660
+ return [];
661
+ }
662
+ const kbids = skillRefs.map((r) => r.kbid);
663
+ const sections = await client.readSections(kbids);
664
+ const sectionMap = new Map(sections.map((s) => [s.kbid, s]));
665
+ return skillRefs.map((ref) => {
666
+ const sec = sectionMap.get(ref.kbid);
667
+ if (!sec) {
668
+ return { kbid: ref.kbid, name: null, position: ref.position };
669
+ }
670
+ try {
671
+ const parsed = JSON.parse(sec.content);
672
+ const skillName = typeof parsed["name"] === "string" ? parsed["name"] : null;
673
+ return {
674
+ kbid: ref.kbid,
675
+ name: skillName,
676
+ position: ref.position
677
+ };
678
+ } catch {
679
+ return { kbid: ref.kbid, name: null, position: ref.position };
680
+ }
681
+ });
682
+ }
683
+ async function runAgentGet(client, options) {
684
+ const docid = options.args[0];
685
+ if (!docid) {
686
+ return { error: "docid is required", exitCode: 1 };
687
+ }
688
+ const doc = await client.retrieveDocument(docid);
689
+ const metaKbid = doc.sections[0]?.kbid;
690
+ const skillRefs = doc.sections.slice(1);
691
+ const { name, description, persona } = metaKbid ? await readAgentMeta(client, metaKbid, doc.title) : { name: doc.title, description: "", persona: "" };
692
+ const skills = await resolveSkills(client, skillRefs);
693
+ return {
694
+ output: JSON.stringify(
695
+ { docid, name, description, persona, skills },
696
+ null,
697
+ 2
698
+ ),
699
+ exitCode: 0
700
+ };
701
+ }
702
+
703
+ // src/shared/cli/functions/run-agent-delete.function.ts
704
+ async function runAgentDelete(client, options) {
705
+ const docid = options.args[0];
706
+ if (!docid) {
707
+ return { error: "docid is required", exitCode: 1 };
708
+ }
709
+ await client.removeGrouping(docid);
710
+ return {
711
+ output: JSON.stringify({ docid, removed: true }, null, 2),
712
+ exitCode: 0
713
+ };
714
+ }
715
+
716
+ // src/shared/cli/functions/dispatch-command.function.ts
717
+ async function dispatchCommand(client, options, io) {
718
+ switch (options.command) {
719
+ case "learn":
720
+ return handleLearn(client, options, io);
721
+ case "unlearn":
722
+ return handleUnlearn(client, options);
723
+ case "search":
724
+ return handleSearch(client, options);
725
+ case "content":
726
+ return handleContent(client, options);
727
+ case "check":
728
+ return handleCheck(client, options);
729
+ case "gc":
730
+ return handleGc(client, options);
731
+ case "rebuild":
732
+ return handleRebuild(client, options);
733
+ case "status":
734
+ return handleStatus(client, options);
735
+ case "db-init":
736
+ return handleDbInit(options);
737
+ case "db-migrate":
738
+ return handleDbMigrate(client, options);
739
+ case "skill-learn": {
740
+ const result = await runSkillLearn(client, options);
741
+ return result;
742
+ }
743
+ case "skill-list": {
744
+ const result = await runSkillList(client, options);
745
+ return result;
746
+ }
747
+ case "skill-get": {
748
+ const result = await runSkillGet(client, options);
749
+ return result;
750
+ }
751
+ case "skill-delete": {
752
+ const result = await runSkillDelete(client, options);
753
+ return result;
754
+ }
755
+ case "agent-create": {
756
+ const result = await runAgentCreate(client, options);
757
+ return result;
758
+ }
759
+ case "agent-list": {
760
+ const result = await runAgentList(client, options);
761
+ return result;
762
+ }
763
+ case "agent-get": {
764
+ const result = await runAgentGet(client, options);
765
+ return result;
766
+ }
767
+ case "agent-delete": {
768
+ const result = await runAgentDelete(client, options);
769
+ return result;
770
+ }
771
+ default:
772
+ return {
773
+ error: `unknown command: ${options.command}`,
774
+ exitCode: 1
775
+ };
776
+ }
777
+ }
778
+ async function handleLearn(client, options, io) {
779
+ try {
780
+ const results = await runLearn(client, options, io);
781
+ return {
782
+ output: JSON.stringify(results, null, 2),
783
+ exitCode: 0
784
+ };
785
+ } catch (err) {
786
+ return {
787
+ error: `learn failed: ${errorToMessage(err)}`,
788
+ exitCode: 1
789
+ };
790
+ }
791
+ }
792
+ async function handleUnlearn(client, options) {
793
+ try {
794
+ const results = await runUnlearn(client, options);
795
+ return {
796
+ output: JSON.stringify(results, null, 2),
797
+ exitCode: 0
798
+ };
799
+ } catch (err) {
800
+ return {
801
+ error: `unlearn failed: ${errorToMessage(err)}`,
802
+ exitCode: 1
803
+ };
804
+ }
805
+ }
806
+ async function handleSearch(client, options) {
807
+ try {
808
+ const results = await runSearch(client, options);
809
+ if (options.content) {
810
+ await hydrateSearchPreviews(client, results);
811
+ }
812
+ return {
813
+ output: formatOutput(results, options.format),
814
+ exitCode: 0
815
+ };
816
+ } catch (err) {
817
+ return {
818
+ error: `search failed: ${errorToMessage(err)}`,
819
+ exitCode: 1
820
+ };
821
+ }
822
+ }
823
+ async function handleContent(client, options) {
824
+ try {
825
+ const result = await runContent(client, options);
826
+ return {
827
+ output: JSON.stringify(result, null, 2),
828
+ exitCode: 0
829
+ };
830
+ } catch (err) {
831
+ return {
832
+ error: `content failed: ${errorToMessage(err)}`,
833
+ exitCode: 1
834
+ };
835
+ }
836
+ }
837
+ async function handleCheck(client, options) {
838
+ try {
839
+ const result = await runCheck(client, options);
840
+ return {
841
+ output: JSON.stringify(result, null, 2),
842
+ exitCode: result.ok ? 0 : 1
843
+ };
844
+ } catch (err) {
845
+ return {
846
+ error: `check failed: ${errorToMessage(err)}`,
847
+ exitCode: 1
848
+ };
849
+ }
850
+ }
851
+ async function handleGc(client, options) {
852
+ try {
853
+ const result = await runGc(client, options);
854
+ return {
855
+ output: JSON.stringify(result, null, 2),
856
+ exitCode: 0
857
+ };
858
+ } catch (err) {
859
+ return {
860
+ error: `gc failed: ${errorToMessage(err)}`,
861
+ exitCode: 1
862
+ };
863
+ }
864
+ }
865
+ async function handleRebuild(client, options) {
866
+ try {
867
+ const result = await runRebuild(client, options);
868
+ return {
869
+ output: JSON.stringify(result, null, 2),
870
+ exitCode: 0
871
+ };
872
+ } catch (err) {
873
+ return {
874
+ error: `rebuild failed: ${errorToMessage(err)}`,
875
+ exitCode: 1
876
+ };
877
+ }
878
+ }
879
+ async function handleStatus(client, options) {
880
+ try {
881
+ const result = await runStatus(client, options);
882
+ return {
883
+ output: JSON.stringify(result, null, 2),
884
+ exitCode: 0
885
+ };
886
+ } catch (err) {
887
+ return {
888
+ error: `status failed: ${errorToMessage(err)}`,
889
+ exitCode: 1
890
+ };
891
+ }
892
+ }
893
+ function handleDbInit(options) {
894
+ return runDbInit(options, runInit);
895
+ }
896
+ async function handleDbMigrate(client, options) {
897
+ try {
898
+ const result = await runDbMigrate(client, options);
899
+ return {
900
+ output: JSON.stringify(result, null, 2),
901
+ exitCode: 0
902
+ };
903
+ } catch (err) {
904
+ return {
905
+ error: `db-migrate failed: ${errorToMessage(err)}`,
906
+ exitCode: 1
907
+ };
908
+ }
909
+ }
910
+ async function hydrateSearchPreviews(client, results) {
911
+ await Promise.all(
912
+ results.map(async (result) => {
913
+ try {
914
+ const contentResult = await client.content([result.kbid]);
915
+ result.preview = contentResult.data;
916
+ } catch {
917
+ }
918
+ })
919
+ );
920
+ }
921
+
922
+ // src/shared/version/constants/version.constant.ts
923
+ var VERSION = "0.1.0";
924
+
925
+ // src/shared/cli/functions/generate-help.function.ts
926
+ var KNOWN_COMMANDS = /* @__PURE__ */ new Set([
927
+ "learn",
928
+ "unlearn",
929
+ "search",
930
+ "content",
931
+ "check",
932
+ "gc",
933
+ "rebuild",
934
+ "status",
935
+ "mcp",
936
+ "db",
937
+ "skill",
938
+ "agent"
939
+ ]);
940
+ var GROUP_SUBCOMMANDS = {
941
+ db: [
942
+ ["init", "Initialise a new .kbdb directory"],
943
+ ["migrate", "Migrate database to current format"]
944
+ ],
945
+ skill: [
946
+ ["learn", "Create a new skill definition"],
947
+ ["list", "List all skills"],
948
+ ["get", "Retrieve a skill by name or kbid"],
949
+ ["delete", "Remove a skill"]
950
+ ],
951
+ agent: [
952
+ ["create", "Create an agent with skill refs"],
953
+ ["list", "List all agents"],
954
+ ["get", "Retrieve an agent by docid"],
955
+ ["delete", "Remove an agent"]
956
+ ]
957
+ };
958
+ function isKnownCommand(cmd) {
959
+ if (KNOWN_COMMANDS.has(cmd)) {
960
+ return true;
961
+ }
962
+ const dashIdx = cmd.indexOf("-");
963
+ if (dashIdx < 0) {
964
+ return false;
965
+ }
966
+ const group = cmd.slice(0, dashIdx);
967
+ return group in GROUP_SUBCOMMANDS;
968
+ }
969
+ function generateHelp(command, subcommand) {
970
+ if (!command) {
971
+ return generateGlobalHelp();
972
+ }
973
+ if (!subcommand && command.includes("-")) {
974
+ const dashIdx = command.indexOf("-");
975
+ const group = command.slice(0, dashIdx);
976
+ const sub = command.slice(dashIdx + 1);
977
+ if (group in GROUP_SUBCOMMANDS) {
978
+ return generateSubcommandHelp(group, sub);
979
+ }
980
+ }
981
+ if (subcommand) {
982
+ return generateSubcommandHelp(command, subcommand);
983
+ }
984
+ return generateCommandHelp(command);
985
+ }
986
+ function generateGlobalHelp() {
987
+ return `kbdb v${VERSION} - File-based knowledge base database for AI agents
988
+
989
+ Usage: kbdb [options]
990
+ kbdb <command> [options] ...[parameters]
991
+ kbdb <command> <subcommand> [options] ...[params]
992
+
993
+ Knowledge Base:
994
+ learn Import content from files/stdin
995
+ unlearn Remove sections by kbid
996
+ search Query the knowledge base
997
+ content Compose rendered content from ids
998
+
999
+ Database:
1000
+ db init Initialise a new .kbdb directory
1001
+ db migrate Migrate database to current format
1002
+
1003
+ Maintenance:
1004
+ check Verify knowledge base integrity
1005
+ gc Garbage collect unreferenced
1006
+ sections
1007
+ rebuild Reconstruct all index files
1008
+ status Show database status
1009
+
1010
+ Skills:
1011
+ skill learn Create a new skill definition
1012
+ skill list List all skills
1013
+ skill get Retrieve a skill by name or kbid
1014
+ skill delete Remove a skill
1015
+
1016
+ Agents:
1017
+ agent create Create an agent with skill refs
1018
+ agent list List all agents
1019
+ agent get Retrieve an agent by docid
1020
+ agent delete Remove an agent
1021
+
1022
+ Server:
1023
+ mcp Start MCP server mode (stdio)
1024
+
1025
+ Global Options:
1026
+ -h, --help Show this help message
1027
+ -v, --version Show version information
1028
+ --db <path> Path to .kbdb directory
1029
+ --format <fmt> Output format (json|text|mcp)
1030
+
1031
+ Run "kbdb <command> --help" for detailed information.
1032
+ `;
1033
+ }
1034
+ function generateCommandHelp(command) {
1035
+ if (command in GROUP_SUBCOMMANDS) {
1036
+ return generateGroupHelp(command);
1037
+ }
1038
+ const leaf = LEAF_HELP[command];
1039
+ if (leaf) {
1040
+ return leaf;
1041
+ }
1042
+ return `Unknown command: ${command}
1043
+
1044
+ ` + generateGlobalHelp();
1045
+ }
1046
+ function generateGroupHelp(group) {
1047
+ const subs = GROUP_SUBCOMMANDS[group] ?? [];
1048
+ const subLines = subs.map(([name, desc2]) => ` ${name.padEnd(20)}${desc2}`).join("\n");
1049
+ const desc = GROUP_DESCRIPTIONS[group] ?? group;
1050
+ return `kbdb ${group} - ${desc}
1051
+
1052
+ Usage: kbdb ${group} <subcommand> [options]
1053
+
1054
+ Subcommands:
1055
+ ${subLines}
1056
+
1057
+ Global Options:
1058
+ --db <path> Path to .kbdb directory
1059
+ -h, --help Show this help message
1060
+
1061
+ Run "kbdb ${group} <subcommand> --help" for details.
1062
+ `;
1063
+ }
1064
+ var GROUP_DESCRIPTIONS = {
1065
+ db: "Database management",
1066
+ skill: "Skill management",
1067
+ agent: "Agent management"
1068
+ };
1069
+ var LEAF_HELP = {
1070
+ learn: `kbdb learn - Import content from files or stdin
1071
+
1072
+ Usage: kbdb learn [options] <path | ->...
1073
+
1074
+ Arguments:
1075
+ <path | -> File path, directory, or - for stdin
1076
+
1077
+ Options:
1078
+ --title <title> Section title
1079
+ --description <d> Section description
1080
+ --docid <docid> Document ID to group under
1081
+ --db <path> Path to .kbdb directory
1082
+
1083
+ Output:
1084
+ JSON array of { kbid, path, size, skipped }
1085
+
1086
+ Examples:
1087
+ kbdb learn README.md
1088
+ kbdb learn ./docs/
1089
+ cat notes.txt | kbdb learn -
1090
+ `,
1091
+ unlearn: `kbdb unlearn - Remove sections by kbid
1092
+
1093
+ Usage: kbdb unlearn [options] <kbid>...
1094
+
1095
+ Arguments:
1096
+ <kbid> 26-character knowledge base identifier
1097
+
1098
+ Options:
1099
+ --db <path> Path to .kbdb directory
1100
+
1101
+ Output:
1102
+ JSON array of { kbid, removed }
1103
+
1104
+ Examples:
1105
+ kbdb unlearn abcdef1234567890abcdef1234
1106
+ kbdb unlearn id1 id2 id3
1107
+ `,
1108
+ search: `kbdb search - Query the knowledge base
1109
+
1110
+ Usage: kbdb search [options] <query>...
1111
+
1112
+ Arguments:
1113
+ <query> One or more query terms
1114
+
1115
+ Options:
1116
+ --mode <mode> Result granularity (sections|documents|stats)
1117
+ --limit <n> Max results (default: 20)
1118
+ --format <fmt> Output format (json|text|mcp)
1119
+ --content, -c Hydrate results with section content
1120
+ --db <path> Path to .kbdb directory
1121
+
1122
+ Output:
1123
+ JSON array of { kbid, score, preview, matches }
1124
+
1125
+ Examples:
1126
+ kbdb search "machine learning"
1127
+ kbdb search --limit 5 --format text query
1128
+ kbdb search --mode documents --content term
1129
+ `,
1130
+ content: `kbdb content - Compose rendered content from ids
1131
+
1132
+ Usage: kbdb content [options] <id>...
1133
+
1134
+ Arguments:
1135
+ <id> kbid or docid identifier
1136
+
1137
+ Options:
1138
+ --db <path> Path to .kbdb directory
1139
+
1140
+ Output:
1141
+ JSON { type, data, total }
1142
+
1143
+ Examples:
1144
+ kbdb content abcdef1234567890abcdef1234
1145
+ kbdb content id1 id2
1146
+ `,
1147
+ check: `kbdb check - Verify knowledge base integrity
1148
+
1149
+ Usage: kbdb check [options]
1150
+
1151
+ Options:
1152
+ --db <path> Path to .kbdb directory
1153
+
1154
+ Output:
1155
+ JSON { ok, errors }
1156
+
1157
+ Examples:
1158
+ kbdb check
1159
+ kbdb check --db /path/to/project
1160
+ `,
1161
+ gc: `kbdb gc - Garbage collect unreferenced sections
1162
+
1163
+ Usage: kbdb gc [options]
1164
+
1165
+ Options:
1166
+ --db <path> Path to .kbdb directory
1167
+
1168
+ Output:
1169
+ JSON { removed_sections, removed_bytes }
1170
+
1171
+ Examples:
1172
+ kbdb gc
1173
+ kbdb gc --db /path/to/project
1174
+ `,
1175
+ rebuild: `kbdb rebuild - Reconstruct all index files
1176
+
1177
+ Usage: kbdb rebuild [options]
1178
+
1179
+ Options:
1180
+ --db <path> Path to .kbdb directory
1181
+
1182
+ Output:
1183
+ JSON { sections_reindexed, terms_indexed }
1184
+
1185
+ Examples:
1186
+ kbdb rebuild
1187
+ kbdb rebuild --db /path/to/project
1188
+ `,
1189
+ status: `kbdb status - Show database status
1190
+
1191
+ Usage: kbdb status [options]
1192
+
1193
+ Options:
1194
+ --db <path> Path to .kbdb directory
1195
+
1196
+ Output:
1197
+ JSON database status object
1198
+
1199
+ Examples:
1200
+ kbdb status
1201
+ kbdb status --db /path/to/project
1202
+ `,
1203
+ mcp: `kbdb mcp - Start MCP server mode (stdio)
1204
+
1205
+ Usage: kbdb mcp [options]
1206
+
1207
+ Options:
1208
+ --db <path> Path to .kbdb directory
1209
+
1210
+ Environment:
1211
+ KBDB_DIR Fallback database path
1212
+
1213
+ Examples:
1214
+ kbdb mcp --db /path/to/project
1215
+ KBDB_DIR=/path/to/project kbdb mcp
1216
+ `
1217
+ };
1218
+ var SUBCOMMAND_HELP = {
1219
+ "db-init": `kbdb db init - Initialise a new .kbdb directory
1220
+
1221
+ Usage: kbdb db init [options]
1222
+
1223
+ Options:
1224
+ --db <path> Path to create .kbdb in
1225
+ (default: current directory)
1226
+ -h, --help Show this help message
1227
+
1228
+ Output:
1229
+ JSON { path, created }
1230
+
1231
+ Examples:
1232
+ kbdb db init
1233
+ kbdb db init --db /path/to/project
1234
+ `,
1235
+ "db-migrate": `kbdb db migrate - Migrate database to current format
1236
+
1237
+ Usage: kbdb db migrate [options]
1238
+
1239
+ Options:
1240
+ --db <path> Path containing .kbdb
1241
+ (default: current directory)
1242
+ -h, --help Show this help message
1243
+
1244
+ Output:
1245
+ JSON MigrateResult or "already up to date"
1246
+
1247
+ Examples:
1248
+ kbdb db migrate
1249
+ kbdb db migrate --db /path/to/project
1250
+ `,
1251
+ "skill-learn": `kbdb skill learn - Create a new skill definition
1252
+
1253
+ Usage: kbdb skill learn [options] --name <n> --body <file|->
1254
+
1255
+ Options:
1256
+ --name <name> Skill name (required)
1257
+ --description <d> Skill description
1258
+ --body <file|-> Template body file or stdin (required)
1259
+ --db <path> Path to .kbdb directory
1260
+
1261
+ Output:
1262
+ JSON { kbid, name, arguments }
1263
+
1264
+ Examples:
1265
+ kbdb skill learn --name summarize --body prompt.txt
1266
+ cat body.txt | kbdb skill learn --name my-skill --body -
1267
+ `,
1268
+ "skill-list": `kbdb skill list - List all skills
1269
+
1270
+ Usage: kbdb skill list [options]
1271
+
1272
+ Options:
1273
+ --db <path> Path to .kbdb directory
1274
+
1275
+ Output:
1276
+ JSON array of { kbid, name, description, argumentCount }
1277
+
1278
+ Examples:
1279
+ kbdb skill list
1280
+ kbdb skill list --db /path/to/project
1281
+ `,
1282
+ "skill-get": `kbdb skill get - Retrieve a skill by name or kbid
1283
+
1284
+ Usage: kbdb skill get [options] <name-or-kbid>
1285
+
1286
+ Arguments:
1287
+ <name-or-kbid> Skill name or 26-char kbid
1288
+
1289
+ Options:
1290
+ --db <path> Path to .kbdb directory
1291
+
1292
+ Output:
1293
+ JSON SkillDefinition object
1294
+
1295
+ Examples:
1296
+ kbdb skill get summarize-document
1297
+ kbdb skill get abcdef1234567890abcdef1234
1298
+ `,
1299
+ "skill-delete": `kbdb skill delete - Remove a skill
1300
+
1301
+ Usage: kbdb skill delete [options] <kbid>
1302
+
1303
+ Arguments:
1304
+ <kbid> 26-character kbid of the skill to remove
1305
+
1306
+ Options:
1307
+ --db <path> Path to .kbdb directory
1308
+
1309
+ Output:
1310
+ JSON { kbid, removed }
1311
+
1312
+ Examples:
1313
+ kbdb skill delete abcdef1234567890abcdef1234
1314
+ `,
1315
+ "agent-create": `kbdb agent create - Create an agent with skill refs
1316
+
1317
+ Usage: kbdb agent create [options] --name <n> --persona <file|-> --skills <kbid,...>
1318
+
1319
+ Options:
1320
+ --name <name> Agent name (required)
1321
+ --description <d> Agent description
1322
+ --persona <file|-> Persona file or stdin (required)
1323
+ --skills <kbid,...> Comma-separated skill kbids (required)
1324
+ --db <path> Path to .kbdb directory
1325
+
1326
+ Output:
1327
+ JSON { docid, name, skills }
1328
+
1329
+ Examples:
1330
+ kbdb agent create --name code-reviewer --persona ./p.txt --skills abc123
1331
+ cat persona.txt | kbdb agent create --name my-agent --persona - --skills abc123
1332
+ `,
1333
+ "agent-list": `kbdb agent list - List all agents
1334
+
1335
+ Usage: kbdb agent list [options]
1336
+
1337
+ Options:
1338
+ --db <path> Path to .kbdb directory
1339
+
1340
+ Output:
1341
+ JSON array of { docid, name, description, skillCount }
1342
+
1343
+ Examples:
1344
+ kbdb agent list
1345
+ kbdb agent list --db /path/to/project
1346
+ `,
1347
+ "agent-get": `kbdb agent get - Retrieve an agent by docid
1348
+
1349
+ Usage: kbdb agent get [options] <docid>
1350
+
1351
+ Arguments:
1352
+ <docid> Agent document identifier
1353
+
1354
+ Options:
1355
+ --db <path> Path to .kbdb directory
1356
+
1357
+ Output:
1358
+ JSON AgentDefinition object with resolved skills
1359
+
1360
+ Examples:
1361
+ kbdb agent get agent-code-reviewer
1362
+ `,
1363
+ "agent-delete": `kbdb agent delete - Remove an agent
1364
+
1365
+ Usage: kbdb agent delete [options] <docid>
1366
+
1367
+ Arguments:
1368
+ <docid> Agent document identifier
1369
+
1370
+ Options:
1371
+ --db <path> Path to .kbdb directory
1372
+
1373
+ Output:
1374
+ JSON { docid, removed }
1375
+
1376
+ Examples:
1377
+ kbdb agent delete agent-code-reviewer
1378
+ `
1379
+ };
1380
+ function generateSubcommandHelp(command, subcommand) {
1381
+ const key = `${command}-${subcommand}`;
1382
+ const text = SUBCOMMAND_HELP[key];
1383
+ if (text) {
1384
+ return text;
1385
+ }
1386
+ return generateCommandHelp(command);
1387
+ }
1388
+
1389
+ // src/shared/cli/functions/run-cli.function.ts
1390
+ async function runCli(argv, deps2) {
1391
+ const options = parseArgs(argv);
1392
+ if (options.command === "help" || !options.command) {
1393
+ const helpCommand = options.args[0];
1394
+ const helpSubcommand = options.args[1];
1395
+ const helpText = generateHelp(helpCommand, helpSubcommand);
1396
+ if (helpCommand && !isKnownCommand(helpCommand)) {
1397
+ return { output: helpText, exitCode: 1 };
1398
+ }
1399
+ return { output: helpText, exitCode: 0 };
1400
+ }
1401
+ if (options.command === "version") {
1402
+ return { output: VERSION, exitCode: 0 };
1403
+ }
1404
+ if (options.command === "init" || options.command === "db-init") {
1405
+ return handleInit(options, deps2);
1406
+ }
1407
+ if (options.command === "mcp") {
1408
+ return handleMcp(options, deps2);
1409
+ }
1410
+ if (options.command === "migrate" || options.command === "db-migrate") {
1411
+ return handleMigrate(options, deps2);
1412
+ }
1413
+ return handleDataCommand(options, deps2);
1414
+ }
1415
+ function handleInit(options, deps2) {
1416
+ const result = deps2.runInit(options);
1417
+ if (result.ok) {
1418
+ return {
1419
+ output: result.targetPath,
1420
+ exitCode: 0
1421
+ };
1422
+ }
1423
+ return {
1424
+ error: `error: ${result.errorMessage ?? "init failed"}`,
1425
+ exitCode: 1
1426
+ };
1427
+ }
1428
+ async function handleMcp(options, deps2) {
1429
+ const rawDbPath = options.dbPath ?? process.env["KBDB_DIR"];
1430
+ if (!rawDbPath) {
1431
+ return {
1432
+ error: "error: --db or KBDB_DIR required in MCP mode",
1433
+ exitCode: 1
1434
+ };
1435
+ }
1436
+ const dbDir = deps2.findDb(rawDbPath);
1437
+ if (!dbDir) {
1438
+ return {
1439
+ error: `error: no .kbdb database found at ${rawDbPath}`,
1440
+ exitCode: 1
1441
+ };
1442
+ }
1443
+ let client;
1444
+ try {
1445
+ client = await deps2.createWorkerClient({
1446
+ contextPath: dbDir
1447
+ });
1448
+ } catch (err) {
1449
+ return {
1450
+ error: `error: ${errorToMessage(err)}`,
1451
+ exitCode: 1
1452
+ };
1453
+ }
1454
+ try {
1455
+ const gateResult = await versionGate(client, dbDir);
1456
+ if (gateResult) return gateResult;
1457
+ if (deps2.startMcpServer) {
1458
+ await deps2.startMcpServer(dbDir);
1459
+ }
1460
+ return { exitCode: 0 };
1461
+ } catch (err) {
1462
+ return {
1463
+ error: `error: mcp failed: ${errorToMessage(err)}`,
1464
+ exitCode: 1
1465
+ };
1466
+ } finally {
1467
+ client.disconnect();
1468
+ }
1469
+ }
1470
+ async function handleMigrate(options, deps2) {
1471
+ const dbDir = deps2.findDb(options.dbPath);
1472
+ if (!dbDir) {
1473
+ const basePath = options.dbPath ?? process.cwd();
1474
+ return {
1475
+ error: `error: no .kbdb database found at ${basePath}`,
1476
+ exitCode: 1
1477
+ };
1478
+ }
1479
+ let client;
1480
+ try {
1481
+ client = await deps2.createWorkerClient({
1482
+ contextPath: dbDir
1483
+ });
1484
+ } catch (err) {
1485
+ return {
1486
+ error: `error: ${errorToMessage(err)}`,
1487
+ exitCode: 1
1488
+ };
1489
+ }
1490
+ try {
1491
+ const versionStatus = await client.checkVersion(dbDir);
1492
+ if (versionStatus.status === "too_new") {
1493
+ return {
1494
+ error: `error: database version ${versionStatus.currentVersion.toString()} is newer than kbdb version ${versionStatus.requiredVersion.toString()} -- upgrade kbdb`,
1495
+ exitCode: 1
1496
+ };
1497
+ }
1498
+ if (versionStatus.status === "needs_migration") {
1499
+ const migrateResult = await client.migrateDatabase(dbDir);
1500
+ return {
1501
+ output: JSON.stringify(migrateResult, null, 2),
1502
+ exitCode: 0
1503
+ };
1504
+ }
1505
+ return { output: "already up to date", exitCode: 0 };
1506
+ } catch (err) {
1507
+ return {
1508
+ error: `error: migrate failed: ${errorToMessage(err)}`,
1509
+ exitCode: 1
1510
+ };
1511
+ } finally {
1512
+ client.disconnect();
1513
+ }
1514
+ }
1515
+ async function handleDataCommand(options, deps2) {
1516
+ let dbDir = deps2.findDb(options.dbPath);
1517
+ if (!dbDir) {
1518
+ const basePath = options.dbPath ?? process.cwd();
1519
+ if (!deps2.isStdinTty()) {
1520
+ return {
1521
+ error: `error: no .kbdb database found at ${basePath} -- run \`kbdb --init\` to create one`,
1522
+ exitCode: 1
1523
+ };
1524
+ }
1525
+ const answer = await deps2.promptUser(
1526
+ `No .kbdb database found. Create one in ${basePath}? [y/N] `
1527
+ );
1528
+ if (answer.toLowerCase() !== "y") {
1529
+ return {
1530
+ error: "aborted: no database created",
1531
+ exitCode: 1
1532
+ };
1533
+ }
1534
+ const initResult = deps2.runInit(options);
1535
+ if (!initResult.ok) {
1536
+ return {
1537
+ error: `error: ${initResult.errorMessage ?? "init failed"}`,
1538
+ exitCode: 1
1539
+ };
1540
+ }
1541
+ dbDir = initResult.targetPath;
1542
+ }
1543
+ let client;
1544
+ try {
1545
+ client = await deps2.createWorkerClient({
1546
+ contextPath: dbDir
1547
+ });
1548
+ } catch (err) {
1549
+ return {
1550
+ error: `error: ${errorToMessage(err)}`,
1551
+ exitCode: 1
1552
+ };
1553
+ }
1554
+ try {
1555
+ const gateResult = await versionGate(client, dbDir);
1556
+ if (gateResult) return gateResult;
1557
+ return await dispatchCommand(client, options);
1558
+ } finally {
1559
+ client.disconnect();
1560
+ }
1561
+ }
1562
+ async function versionGate(client, dbDir) {
1563
+ const versionStatus = await client.checkVersion(dbDir);
1564
+ if (versionStatus.status === "needs_migration") {
1565
+ return {
1566
+ error: "error: database needs migration -- run `kbdb --migrate`",
1567
+ exitCode: 1
1568
+ };
1569
+ }
1570
+ if (versionStatus.status === "too_new") {
1571
+ return {
1572
+ error: `error: database version ${versionStatus.currentVersion.toString()} is newer than kbdb version ${versionStatus.requiredVersion.toString()} -- upgrade kbdb`,
1573
+ exitCode: 1
1574
+ };
1575
+ }
1576
+ return null;
1577
+ }
1578
+
1579
+ // src/shared/cli/constants/help-text.constant.ts
1580
+ var HELP_TEXT = generateHelp();
1581
+
1582
+ // src/shared/worker-client/classes/worker-client.class.ts
1583
+ var import_node_net = require("node:net");
1584
+ var WorkerClient = class {
1585
+ /**
1586
+ * @param socketPath - absolute path to the daemon's IPC socket
1587
+ * (or Windows named pipe path)
1588
+ * @param contextId - 16-character context identifier sent as
1589
+ * `ctx` in every JSON-RPC request
1590
+ */
1591
+ constructor(socketPath, contextId) {
1592
+ this.socketPath = socketPath;
1593
+ this.contextId = contextId;
1594
+ }
1595
+ /** Underlying socket; `null` when not connected. */
1596
+ socket = null;
1597
+ /** Monotonically increasing request ID counter. */
1598
+ nextId = 1;
1599
+ /** Map of outstanding request IDs to their resolve/reject pairs. */
1600
+ pending = /* @__PURE__ */ new Map();
1601
+ /** Partial line buffer for split TCP/IPC frames. */
1602
+ buffer = "";
1603
+ /**
1604
+ * Establishes the IPC connection to the worker daemon.
1605
+ *
1606
+ * @throws {Error} if the connection cannot be established
1607
+ */
1608
+ async connect() {
1609
+ return new Promise((resolve4, reject) => {
1610
+ this.socket = (0, import_node_net.connect)(this.socketPath, () => {
1611
+ resolve4();
1612
+ });
1613
+ this.socket.on("error", (err) => {
1614
+ reject(err);
1615
+ });
1616
+ this.socket.on("data", (chunk) => {
1617
+ this.handleData(chunk.toString());
1618
+ });
1619
+ });
1620
+ }
1621
+ /** Destroys the IPC socket and clears the connection state. */
1622
+ disconnect() {
1623
+ if (this.socket) {
1624
+ this.socket.destroy();
1625
+ this.socket = null;
1626
+ }
1627
+ }
1628
+ /**
1629
+ * Searches the knowledge base.
1630
+ *
1631
+ * @param params - query parameters including the search string
1632
+ * @returns ranked list of matching sections
1633
+ */
1634
+ async search(params) {
1635
+ return this.call("search", params);
1636
+ }
1637
+ /**
1638
+ * Adds a new section to the knowledge base.
1639
+ *
1640
+ * @param params - section content and metadata
1641
+ * @returns the result including the assigned knowledge-base
1642
+ * identifier and indexing statistics
1643
+ */
1644
+ async addSection(params) {
1645
+ return this.call(
1646
+ "addSection",
1647
+ params
1648
+ );
1649
+ }
1650
+ /**
1651
+ * Replaces an existing section's content and metadata.
1652
+ *
1653
+ * @param kbid - identifier of the section to update
1654
+ * @param params - new content and metadata
1655
+ * @returns the knowledge-base identifier of the updated section
1656
+ */
1657
+ async updateSection(kbid, params) {
1658
+ return this.call("updateSection", {
1659
+ kbid,
1660
+ ...params
1661
+ });
1662
+ }
1663
+ /**
1664
+ * Removes a section from the knowledge base.
1665
+ *
1666
+ * @param kbid - identifier of the section to remove
1667
+ * @returns removal result with `removed` flag and elapsed time
1668
+ */
1669
+ async removeSection(kbid) {
1670
+ return this.call("removeSection", {
1671
+ kbid
1672
+ });
1673
+ }
1674
+ /**
1675
+ * Retrieves multiple sections by their identifiers.
1676
+ *
1677
+ * @param kbids - list of knowledge-base identifiers to fetch
1678
+ * @returns sections in the order their IDs were requested
1679
+ */
1680
+ async readSections(kbids) {
1681
+ return this.call("readSections", {
1682
+ kbids
1683
+ });
1684
+ }
1685
+ /**
1686
+ * Groups a set of sections under a named document.
1687
+ *
1688
+ * @param title - human-readable document title
1689
+ * @param kbids - identifiers of the sections to group
1690
+ * @param docType - application-level document type tag; omit or
1691
+ * pass an empty string for untagged documents
1692
+ * @returns the assigned document identifier
1693
+ */
1694
+ async groupSections(title, kbids, docType) {
1695
+ const result = await this.call("groupSections", {
1696
+ title,
1697
+ kbids,
1698
+ docType: docType ?? ""
1699
+ });
1700
+ return typeof result === "string" ? result : result.docid;
1701
+ }
1702
+ /**
1703
+ * Removes the document grouping for the given document.
1704
+ *
1705
+ * The sections themselves are not deleted; only the grouping
1706
+ * record is removed.
1707
+ *
1708
+ * @param docid - identifier of the document grouping to remove
1709
+ */
1710
+ async removeGrouping(docid) {
1711
+ await this.call("removeGrouping", { docid });
1712
+ }
1713
+ /**
1714
+ * Retrieves a full document record including its sections.
1715
+ *
1716
+ * @param docid - identifier of the document to retrieve
1717
+ * @returns the document record as returned by the daemon
1718
+ */
1719
+ async retrieveDocument(docid) {
1720
+ return this.call("retrieveDocument", { docid });
1721
+ }
1722
+ /**
1723
+ * Composes a rendered Markdown document from one or more kbid
1724
+ * or docid identifiers.
1725
+ *
1726
+ * @param ids - list of kbid or docid identifiers (may be mixed)
1727
+ * @returns composed Markdown result with character count
1728
+ */
1729
+ async content(ids) {
1730
+ return this.call("content", { ids });
1731
+ }
1732
+ /**
1733
+ * Runs an integrity check on the knowledge-base database.
1734
+ *
1735
+ * @returns a report of all issues found; `ok` is `true` when
1736
+ * no errors were detected
1737
+ */
1738
+ async integrityCheck() {
1739
+ return this.call(
1740
+ "integrityCheck",
1741
+ {}
1742
+ );
1743
+ }
1744
+ /**
1745
+ * Removes unreferenced sections from the database.
1746
+ *
1747
+ * @returns a report of sections removed and bytes freed
1748
+ */
1749
+ async gc() {
1750
+ return this.call("gc", {});
1751
+ }
1752
+ /**
1753
+ * Reconstructs all index files from section files and document
1754
+ * manifests on disk. Text and code sections are re-tokenized;
1755
+ * image sections are skipped.
1756
+ *
1757
+ * @returns a report of sections and terms re-indexed
1758
+ */
1759
+ async rebuildIndexes() {
1760
+ return this.call("rebuildIndexes", {});
1761
+ }
1762
+ /**
1763
+ * Invalidates the in-memory cache entry for a single section.
1764
+ *
1765
+ * @param kbid - identifier of the section to evict from cache
1766
+ */
1767
+ async invalidate(kbid) {
1768
+ await this.call("invalidate", { kbid });
1769
+ }
1770
+ /** Clears all entries from the daemon's in-memory cache. */
1771
+ async invalidateAll() {
1772
+ await this.call("invalidateAll", {});
1773
+ }
1774
+ /**
1775
+ * Retrieves diagnostic status information from the daemon.
1776
+ *
1777
+ * @returns current initialization state and cache statistics
1778
+ */
1779
+ async status() {
1780
+ return this.call("status", {});
1781
+ }
1782
+ /**
1783
+ * Returns database metadata and status from the daemon,
1784
+ * including document count, section count, index size, and
1785
+ * cache statistics.
1786
+ *
1787
+ * @returns database metadata from the daemon's cached state
1788
+ */
1789
+ async dbStatus() {
1790
+ return this.call("dbStatus", {});
1791
+ }
1792
+ /**
1793
+ * Initialises a new `.kbdb` database directory at the given path
1794
+ * by sending an init request to the worker daemon.
1795
+ *
1796
+ * The daemon creates all required subdirectories and seed files via
1797
+ * the `worker_init_directory` WASM export.
1798
+ *
1799
+ * @param targetPath - absolute path to the directory that will
1800
+ * contain the new `.kbdb` database
1801
+ * @throws {Error} if the `.kbdb` directory already exists or the
1802
+ * daemon cannot create the layout
1803
+ */
1804
+ async initDirectory(targetPath) {
1805
+ await this.call("initDirectory", { targetPath });
1806
+ }
1807
+ /**
1808
+ * Runs all pending database migrations for the `.kbdb` directory
1809
+ * at the given path.
1810
+ *
1811
+ * Delegates to the `worker_migrate` WASM export on the daemon.
1812
+ * Each migration step updates `catalog.toml` on success, so
1813
+ * retrying after a partial failure is safe.
1814
+ *
1815
+ * @param targetPath - absolute path to the `.kbdb` database root
1816
+ * @returns migration report with old version, new version, and
1817
+ * number of migration steps applied
1818
+ */
1819
+ async migrateDatabase(targetPath) {
1820
+ return this.call("migrateDatabase", {
1821
+ targetPath
1822
+ });
1823
+ }
1824
+ /**
1825
+ * Checks the format version of the `.kbdb` database at the given
1826
+ * path against the version required by the current WASM engine.
1827
+ *
1828
+ * This is a read-only operation: it reads `catalog.toml` and
1829
+ * returns the compatibility status without making any changes.
1830
+ *
1831
+ * @param targetPath - absolute path to the `.kbdb` database root
1832
+ * @returns version compatibility report
1833
+ */
1834
+ async checkVersion(targetPath) {
1835
+ return this.call("checkVersion", {
1836
+ targetPath
1837
+ });
1838
+ }
1839
+ /**
1840
+ * Retrieves all sections whose type name matches the given string.
1841
+ *
1842
+ * @param sectionType - the application-level type name to filter by
1843
+ * @returns all section records with a matching type name
1844
+ */
1845
+ async listByType(sectionType) {
1846
+ return this.call("listByType", {
1847
+ sectionType
1848
+ });
1849
+ }
1850
+ /**
1851
+ * Retrieves all documents whose type name matches the given string.
1852
+ *
1853
+ * @param docType - the application-level document type to filter by
1854
+ * @returns all document manifests with a matching type name
1855
+ */
1856
+ async listDocumentsByType(docType) {
1857
+ return this.call("listDocumentsByType", {
1858
+ docType
1859
+ });
1860
+ }
1861
+ /**
1862
+ * Sends a JSON-RPC 2.0 request and awaits the response.
1863
+ *
1864
+ * @param method - the RPC method name
1865
+ * @param params - parameters to include in the request
1866
+ * @throws {Error} if not connected
1867
+ * @throws {Error} when the daemon returns an error response
1868
+ */
1869
+ async call(method, params) {
1870
+ const socket = this.socket;
1871
+ if (!socket) {
1872
+ throw new Error("not connected");
1873
+ }
1874
+ const id = this.nextId++;
1875
+ const request = {
1876
+ jsonrpc: "2.0",
1877
+ id,
1878
+ method,
1879
+ params: { ctx: this.contextId, ...params }
1880
+ };
1881
+ return new Promise((resolve4, reject) => {
1882
+ this.pending.set(id, { resolve: resolve4, reject });
1883
+ socket.write(JSON.stringify(request) + "\n");
1884
+ });
1885
+ }
1886
+ /**
1887
+ * Processes incoming data from the socket, splitting on newlines
1888
+ * and dispatching complete JSON-RPC response objects.
1889
+ *
1890
+ * @param data - raw string chunk received from the socket
1891
+ */
1892
+ handleData(data) {
1893
+ this.buffer += data;
1894
+ const lines = this.buffer.split("\n");
1895
+ this.buffer = lines.pop() ?? "";
1896
+ for (const line of lines) {
1897
+ if (!line.trim()) continue;
1898
+ try {
1899
+ const response = JSON.parse(line);
1900
+ const pending = this.pending.get(response.id);
1901
+ if (pending) {
1902
+ this.pending.delete(response.id);
1903
+ if (response.error) {
1904
+ const err = new Error(response.error.message);
1905
+ err.code = response.error.code;
1906
+ pending.reject(err);
1907
+ } else {
1908
+ pending.resolve(response.result);
1909
+ }
1910
+ }
1911
+ } catch {
1912
+ }
1913
+ }
1914
+ }
1915
+ };
1916
+
1917
+ // src/shared/worker-client/functions/create-worker-client.function.ts
1918
+ var import_node_fs7 = require("node:fs");
1919
+ var import_node_path10 = require("node:path");
1920
+ var import_node_os4 = require("node:os");
1921
+
1922
+ // src/shared/worker-client/functions/resolve-db-path.function.ts
1923
+ var import_node_fs4 = require("node:fs");
1924
+ var import_node_path6 = require("node:path");
1925
+ function resolveDbPath(targetDir) {
1926
+ const base = targetDir ? (0, import_node_path6.resolve)(targetDir) : process.cwd();
1927
+ const dbPath = (0, import_node_path6.join)(base, ".kbdb");
1928
+ if (!(0, import_node_fs4.existsSync)(dbPath)) {
1929
+ throw new Error(`database not found: ${dbPath}`);
1930
+ }
1931
+ return dbPath;
1932
+ }
1933
+
1934
+ // src/shared/hash/functions/compute-sha256.ts
1935
+ async function computeSha256(input) {
1936
+ const data = new TextEncoder().encode(input);
1937
+ const hash = await crypto.subtle.digest("SHA-256", data);
1938
+ const bytes = new Uint8Array(hash);
1939
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1940
+ }
1941
+
1942
+ // src/shared/worker-client/functions/compute-context-id.function.ts
1943
+ async function computeContextId(absolutePath) {
1944
+ const hash = await computeSha256(absolutePath);
1945
+ return hash.slice(0, 16);
1946
+ }
1947
+
1948
+ // src/shared/worker-client/functions/discover-daemon.function.ts
1949
+ var import_node_fs5 = require("node:fs");
1950
+ var import_node_path7 = require("node:path");
1951
+ var import_node_os = require("node:os");
1952
+
1953
+ // src/shared/platform/functions/is-process-alive.function.ts
1954
+ function isProcessAlive(pid) {
1955
+ try {
1956
+ process.kill(pid, 0);
1957
+ return true;
1958
+ } catch {
1959
+ return false;
1960
+ }
1961
+ }
1962
+
1963
+ // src/shared/worker-client/functions/discover-daemon.function.ts
1964
+ function discoverDaemon(contextId) {
1965
+ const pidPath = (0, import_node_path7.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.pid`);
1966
+ if (!(0, import_node_fs5.existsSync)(pidPath)) return null;
1967
+ const pidStr = (0, import_node_fs5.readFileSync)(pidPath, "utf-8").trim();
1968
+ const pid = parseInt(pidStr, 10);
1969
+ if (isNaN(pid) || !isProcessAlive(pid)) {
1970
+ try {
1971
+ (0, import_node_fs5.unlinkSync)(pidPath);
1972
+ } catch {
1973
+ }
1974
+ return null;
1975
+ }
1976
+ const socketPath = (0, import_node_path7.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.sock`);
1977
+ const crashPath = (0, import_node_path7.join)((0, import_node_os.tmpdir)(), `kbdb-${contextId}.crash`);
1978
+ try {
1979
+ (0, import_node_fs5.unlinkSync)(crashPath);
1980
+ } catch {
1981
+ }
1982
+ return { pid, socketPath };
1983
+ }
1984
+
1985
+ // src/shared/worker-client/functions/spawn-daemon.function.ts
1986
+ var import_node_child_process = require("node:child_process");
1987
+ function spawnDaemon(contextPath, runtime2, workerScript2) {
1988
+ if (!workerScript2) {
1989
+ throw new Error(
1990
+ "workerScript must be provided (resolve at entry point)"
1991
+ );
1992
+ }
1993
+ const execPath = runtime2 === "deno" ? "deno" : process.execPath;
1994
+ const args = runtime2 === "deno" ? ["run", "--allow-all", workerScript2, contextPath] : [workerScript2, contextPath];
1995
+ const child = (0, import_node_child_process.spawn)(execPath, args, {
1996
+ detached: true,
1997
+ stdio: "ignore"
1998
+ });
1999
+ child.unref();
2000
+ }
2001
+
2002
+ // src/shared/worker-client/functions/wait-for-daemon.function.ts
2003
+ var import_node_fs6 = require("node:fs");
2004
+ var import_node_path8 = require("node:path");
2005
+ var import_node_os2 = require("node:os");
2006
+ var DEFAULT_TIMEOUT_MS = 1e4;
2007
+ var POLL_INTERVAL_MS = 100;
2008
+ async function waitForDaemon(contextId, timeoutMs = DEFAULT_TIMEOUT_MS) {
2009
+ const pidPath = (0, import_node_path8.join)((0, import_node_os2.tmpdir)(), `kbdb-${contextId}.pid`);
2010
+ const start = Date.now();
2011
+ while (Date.now() - start < timeoutMs) {
2012
+ if ((0, import_node_fs6.existsSync)(pidPath)) return true;
2013
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
2014
+ }
2015
+ return false;
2016
+ }
2017
+
2018
+ // src/shared/platform/functions/get-ipc-path.function.ts
2019
+ var import_node_path9 = require("node:path");
2020
+
2021
+ // src/shared/platform/functions/get-tmpdir.function.ts
2022
+ var import_node_os3 = require("node:os");
2023
+ function getTmpdir() {
2024
+ return (0, import_node_os3.tmpdir)();
2025
+ }
2026
+
2027
+ // src/shared/platform/functions/get-ipc-path.function.ts
2028
+ function getIpcPath(ctx) {
2029
+ if (process.platform === "win32") {
2030
+ return `\\\\.\\pipe\\kbdb-${ctx}`;
2031
+ }
2032
+ return (0, import_node_path9.join)(getTmpdir(), `kbdb-${ctx}.sock`);
2033
+ }
2034
+
2035
+ // src/shared/worker-client/functions/create-worker-client.function.ts
2036
+ async function createWorkerClient(options) {
2037
+ const dbPath = options?.contextPath ?? resolveDbPath(options?.dbPath);
2038
+ const contextId = await computeContextId(dbPath);
2039
+ const socketPath = getIpcPath(contextId);
2040
+ let daemon = discoverDaemon(contextId);
2041
+ if (!daemon && options?.autoSpawn !== false) {
2042
+ const runtime2 = detectRuntime();
2043
+ spawnDaemon(dbPath, runtime2, options?.workerScript);
2044
+ await waitForDaemon(contextId, options?.connectTimeoutMs);
2045
+ daemon = discoverDaemon(contextId);
2046
+ }
2047
+ if (!daemon) {
2048
+ throw new Error(
2049
+ `kbdb worker daemon did not start: ${readCrashReason(contextId)}`
2050
+ );
2051
+ }
2052
+ const client = new WorkerClient(socketPath, contextId);
2053
+ await client.connect();
2054
+ return client;
2055
+ }
2056
+ function readCrashReason(contextId) {
2057
+ const crashPath = (0, import_node_path10.join)((0, import_node_os4.tmpdir)(), `kbdb-${contextId}.crash`);
2058
+ if (!(0, import_node_fs7.existsSync)(crashPath)) {
2059
+ return "daemon failed to start (no details available)";
2060
+ }
2061
+ try {
2062
+ const raw = (0, import_node_fs7.readFileSync)(crashPath, "utf-8");
2063
+ const crash = JSON.parse(raw);
2064
+ (0, import_node_fs7.unlinkSync)(crashPath);
2065
+ return crash.error ?? "unknown error (crash log empty)";
2066
+ } catch {
2067
+ return "daemon failed to start (crash log unreadable)";
2068
+ }
2069
+ }
2070
+
2071
+ // src/shared/mcp/classes/mcp-server.class.ts
2072
+ var import_node_readline2 = require("node:readline");
2073
+
2074
+ // src/shared/mcp/functions/create-tool-definitions.function.ts
2075
+ function createToolDefinitions() {
2076
+ return [
2077
+ {
2078
+ name: "search",
2079
+ description: "Search the knowledge base for relevant sections using natural language queries.",
2080
+ inputSchema: {
2081
+ type: "object",
2082
+ properties: {
2083
+ query: {
2084
+ type: "string",
2085
+ description: "Search query text"
2086
+ },
2087
+ mode: {
2088
+ type: "string",
2089
+ enum: ["sections", "documents", "stats"],
2090
+ description: "Search mode (default: sections)"
2091
+ },
2092
+ limit: {
2093
+ type: "number",
2094
+ description: "Maximum results (default: 20)"
2095
+ }
2096
+ },
2097
+ required: ["query"]
2098
+ },
2099
+ annotations: {
2100
+ title: "Search KB",
2101
+ readOnlyHint: true,
2102
+ destructiveHint: false,
2103
+ idempotentHint: true
2104
+ }
2105
+ },
2106
+ {
2107
+ name: "learn",
2108
+ description: "Add a text section to the knowledge base.",
2109
+ inputSchema: {
2110
+ type: "object",
2111
+ properties: {
2112
+ content: {
2113
+ type: "string",
2114
+ description: "Text content to add"
2115
+ },
2116
+ type: {
2117
+ type: "string",
2118
+ description: "MIME type (default: text/markdown). Use image/* for images."
2119
+ },
2120
+ title: {
2121
+ type: "string",
2122
+ description: "Section title. Required for image/* types."
2123
+ },
2124
+ description: {
2125
+ type: "string",
2126
+ description: "Optional section description"
2127
+ },
2128
+ docid: {
2129
+ type: "string",
2130
+ description: "Document ID to group under"
2131
+ }
2132
+ },
2133
+ required: ["content"]
2134
+ },
2135
+ annotations: {
2136
+ title: "Import Content",
2137
+ readOnlyHint: false,
2138
+ destructiveHint: false,
2139
+ idempotentHint: true
2140
+ }
2141
+ },
2142
+ {
2143
+ name: "unlearn",
2144
+ description: "Remove a section from the knowledge base by its kb-id.",
2145
+ inputSchema: {
2146
+ type: "object",
2147
+ properties: {
2148
+ kbid: {
2149
+ type: "string",
2150
+ description: "Knowledge base ID of the section"
2151
+ }
2152
+ },
2153
+ required: ["kbid"]
2154
+ },
2155
+ annotations: {
2156
+ title: "Remove Section",
2157
+ readOnlyHint: false,
2158
+ destructiveHint: true,
2159
+ idempotentHint: true
2160
+ }
2161
+ },
2162
+ {
2163
+ name: "retrieve",
2164
+ description: "Retrieve a section or document by ID. Provide kbid or docid.",
2165
+ inputSchema: {
2166
+ type: "object",
2167
+ properties: {
2168
+ kbid: {
2169
+ type: "string",
2170
+ description: "Section kb-id"
2171
+ },
2172
+ docid: {
2173
+ type: "string",
2174
+ description: "Document ID"
2175
+ }
2176
+ }
2177
+ },
2178
+ annotations: {
2179
+ title: "Fetch Content",
2180
+ readOnlyHint: true,
2181
+ destructiveHint: false,
2182
+ idempotentHint: true
2183
+ }
2184
+ },
2185
+ {
2186
+ name: "status",
2187
+ description: "Get database metadata including document count, section count, index size, and cache statistics.",
2188
+ inputSchema: {
2189
+ type: "object",
2190
+ properties: {}
2191
+ },
2192
+ annotations: {
2193
+ title: "DB Status",
2194
+ readOnlyHint: true,
2195
+ destructiveHint: false,
2196
+ idempotentHint: true
2197
+ }
2198
+ },
2199
+ {
2200
+ name: "content",
2201
+ description: "Compose a rendered Markdown document from one or more kbid or docid identifiers.",
2202
+ inputSchema: {
2203
+ type: "object",
2204
+ properties: {
2205
+ ids: {
2206
+ type: "array",
2207
+ items: { type: "string" },
2208
+ description: "One or more kbid or docid identifiers (may be mixed)"
2209
+ }
2210
+ },
2211
+ required: ["ids"]
2212
+ },
2213
+ annotations: {
2214
+ title: "Compose Content",
2215
+ readOnlyHint: true,
2216
+ destructiveHint: false,
2217
+ idempotentHint: true
2218
+ }
2219
+ },
2220
+ {
2221
+ name: "check",
2222
+ description: "Verify the integrity of the knowledge base. Reports checksum mismatches, orphan sections, broken references, and circular reference chains.",
2223
+ inputSchema: {
2224
+ type: "object",
2225
+ properties: {}
2226
+ },
2227
+ annotations: {
2228
+ title: "Integrity Check",
2229
+ readOnlyHint: true,
2230
+ destructiveHint: false,
2231
+ idempotentHint: true
2232
+ }
2233
+ },
2234
+ {
2235
+ name: "gc",
2236
+ description: "Remove unreferenced sections from the knowledge base. A section is eligible when no document manifest references it.",
2237
+ inputSchema: {
2238
+ type: "object",
2239
+ properties: {}
2240
+ },
2241
+ annotations: {
2242
+ title: "Garbage Collect",
2243
+ readOnlyHint: false,
2244
+ destructiveHint: true,
2245
+ idempotentHint: false
2246
+ }
2247
+ },
2248
+ {
2249
+ name: "rebuild",
2250
+ description: "Reconstruct all index files from section files and document manifests on disk. Use this to recover from index corruption.",
2251
+ inputSchema: {
2252
+ type: "object",
2253
+ properties: {}
2254
+ },
2255
+ annotations: {
2256
+ title: "Rebuild Indexes",
2257
+ readOnlyHint: false,
2258
+ destructiveHint: false,
2259
+ idempotentHint: false
2260
+ }
2261
+ },
2262
+ {
2263
+ name: "skill-learn",
2264
+ description: "Create or update a skill definition. Skills are reusable AI agent capabilities with template placeholders.",
2265
+ inputSchema: {
2266
+ type: "object",
2267
+ properties: {
2268
+ name: {
2269
+ type: "string",
2270
+ description: "Skill name"
2271
+ },
2272
+ description: {
2273
+ type: "string",
2274
+ description: "Skill description"
2275
+ },
2276
+ body: {
2277
+ type: "string",
2278
+ description: "Skill body template. Use {{argName}} for placeholders."
2279
+ }
2280
+ },
2281
+ required: ["name", "body"]
2282
+ },
2283
+ annotations: {
2284
+ title: "Create Skill",
2285
+ readOnlyHint: false,
2286
+ destructiveHint: false,
2287
+ idempotentHint: true
2288
+ }
2289
+ },
2290
+ {
2291
+ name: "skill-list",
2292
+ description: "List all skills in the knowledge base.",
2293
+ inputSchema: {
2294
+ type: "object",
2295
+ properties: {}
2296
+ },
2297
+ annotations: {
2298
+ title: "List Skills",
2299
+ readOnlyHint: true,
2300
+ destructiveHint: false,
2301
+ idempotentHint: true
2302
+ }
2303
+ },
2304
+ {
2305
+ name: "skill-get",
2306
+ description: "Get a skill definition by name or kbid.",
2307
+ inputSchema: {
2308
+ type: "object",
2309
+ properties: {
2310
+ name: {
2311
+ type: "string",
2312
+ description: "Skill name"
2313
+ },
2314
+ kbid: {
2315
+ type: "string",
2316
+ description: "Knowledge base ID"
2317
+ }
2318
+ }
2319
+ },
2320
+ annotations: {
2321
+ title: "Get Skill",
2322
+ readOnlyHint: true,
2323
+ destructiveHint: false,
2324
+ idempotentHint: true
2325
+ }
2326
+ },
2327
+ {
2328
+ name: "skill-delete",
2329
+ description: "Delete a skill by its kbid.",
2330
+ inputSchema: {
2331
+ type: "object",
2332
+ properties: {
2333
+ kbid: {
2334
+ type: "string",
2335
+ description: "Knowledge base ID"
2336
+ }
2337
+ },
2338
+ required: ["kbid"]
2339
+ },
2340
+ annotations: {
2341
+ title: "Delete Skill",
2342
+ readOnlyHint: false,
2343
+ destructiveHint: true,
2344
+ idempotentHint: true
2345
+ }
2346
+ },
2347
+ {
2348
+ name: "agent-create",
2349
+ description: "Create an AI agent with a persona and optional skill references.",
2350
+ inputSchema: {
2351
+ type: "object",
2352
+ properties: {
2353
+ name: {
2354
+ type: "string",
2355
+ description: "Agent name"
2356
+ },
2357
+ description: {
2358
+ type: "string",
2359
+ description: "Agent description"
2360
+ },
2361
+ persona: {
2362
+ type: "string",
2363
+ description: "Agent persona prompt"
2364
+ },
2365
+ skills: {
2366
+ type: "array",
2367
+ items: { type: "string" },
2368
+ description: "Skill kbid references to attach"
2369
+ }
2370
+ },
2371
+ required: ["name", "persona"]
2372
+ },
2373
+ annotations: {
2374
+ title: "Create Agent",
2375
+ readOnlyHint: false,
2376
+ destructiveHint: false,
2377
+ idempotentHint: true
2378
+ }
2379
+ },
2380
+ {
2381
+ name: "agent-list",
2382
+ description: "List all agents in the knowledge base.",
2383
+ inputSchema: {
2384
+ type: "object",
2385
+ properties: {}
2386
+ },
2387
+ annotations: {
2388
+ title: "List Agents",
2389
+ readOnlyHint: true,
2390
+ destructiveHint: false,
2391
+ idempotentHint: true
2392
+ }
2393
+ },
2394
+ {
2395
+ name: "agent-get",
2396
+ description: "Get an agent definition by document ID.",
2397
+ inputSchema: {
2398
+ type: "object",
2399
+ properties: {
2400
+ docid: {
2401
+ type: "string",
2402
+ description: "Document ID of the agent"
2403
+ }
2404
+ },
2405
+ required: ["docid"]
2406
+ },
2407
+ annotations: {
2408
+ title: "Get Agent",
2409
+ readOnlyHint: true,
2410
+ destructiveHint: false,
2411
+ idempotentHint: true
2412
+ }
2413
+ },
2414
+ {
2415
+ name: "agent-delete",
2416
+ description: "Delete an agent by its document ID. Skill sections are not removed.",
2417
+ inputSchema: {
2418
+ type: "object",
2419
+ properties: {
2420
+ docid: {
2421
+ type: "string",
2422
+ description: "Document ID of the agent"
2423
+ }
2424
+ },
2425
+ required: ["docid"]
2426
+ },
2427
+ annotations: {
2428
+ title: "Delete Agent",
2429
+ readOnlyHint: false,
2430
+ destructiveHint: true,
2431
+ idempotentHint: true
2432
+ }
2433
+ }
2434
+ ];
2435
+ }
2436
+
2437
+ // src/shared/mcp/functions/create-resource-templates.function.ts
2438
+ function createResourceTemplates() {
2439
+ return [
2440
+ {
2441
+ uriTemplate: "kbdb://section/{kb_id}",
2442
+ name: "Section",
2443
+ description: "A knowledge base section by its kb-id.",
2444
+ mimeType: "text/plain"
2445
+ },
2446
+ {
2447
+ uriTemplate: "kbdb://document/{doc_id}",
2448
+ name: "Document",
2449
+ description: "A document with its ordered sections.",
2450
+ mimeType: "application/json"
2451
+ }
2452
+ ];
2453
+ }
2454
+
2455
+ // src/shared/mcp/functions/handle-agent-create.function.ts
2456
+ function asString(value, fallback) {
2457
+ return typeof value === "string" ? value : fallback;
2458
+ }
2459
+ function asStringArray(value) {
2460
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
2461
+ return value;
2462
+ }
2463
+ return [];
2464
+ }
2465
+ async function handleAgentCreate(client, args) {
2466
+ const name = asString(args["name"], "");
2467
+ const description = asString(args["description"], "");
2468
+ const persona = asString(args["persona"], "");
2469
+ const skills = asStringArray(args["skills"]);
2470
+ if (!name) {
2471
+ return {
2472
+ content: [{ type: "text", text: "name is required" }],
2473
+ isError: true
2474
+ };
2475
+ }
2476
+ if (!persona) {
2477
+ return {
2478
+ content: [{ type: "text", text: "persona is required" }],
2479
+ isError: true
2480
+ };
2481
+ }
2482
+ if (skills.length > 0) {
2483
+ const sections = await client.readSections(skills);
2484
+ const found = new Set(sections.map((s) => s.kbid));
2485
+ const missing = skills.filter((k) => !found.has(k));
2486
+ if (missing.length > 0) {
2487
+ return {
2488
+ content: [
2489
+ {
2490
+ type: "text",
2491
+ text: `skill not found: ${missing.join(", ")}`
2492
+ }
2493
+ ],
2494
+ isError: true
2495
+ };
2496
+ }
2497
+ }
2498
+ const metadata = JSON.stringify({ name, description, persona });
2499
+ const metaResult = await client.addSection({
2500
+ sectionType: "text",
2501
+ content: metadata,
2502
+ title: name,
2503
+ description
2504
+ });
2505
+ const allKbids = [metaResult.kbid, ...skills];
2506
+ const docid = await client.groupSections(name, allKbids);
2507
+ return {
2508
+ content: [
2509
+ {
2510
+ type: "text",
2511
+ text: JSON.stringify({
2512
+ docid,
2513
+ name,
2514
+ skillCount: skills.length
2515
+ })
2516
+ }
2517
+ ]
2518
+ };
2519
+ }
2520
+
2521
+ // src/shared/mcp/functions/handle-agent-list.function.ts
2522
+ async function handleAgentList(client) {
2523
+ const docs = await client.listDocumentsByType("agent");
2524
+ const items = docs.map((d) => ({
2525
+ docid: d.docid,
2526
+ name: d.title,
2527
+ skillCount: Math.max(0, d.sections.length - 1)
2528
+ }));
2529
+ return {
2530
+ content: [
2531
+ {
2532
+ type: "text",
2533
+ text: JSON.stringify(items, null, 2)
2534
+ }
2535
+ ]
2536
+ };
2537
+ }
2538
+
2539
+ // src/shared/mcp/functions/handle-agent-get.function.ts
2540
+ async function readAgentMeta2(client, metaKbid, fallbackName) {
2541
+ const metaSections = await client.readSections([metaKbid]);
2542
+ const first = metaSections.at(0);
2543
+ if (!first) {
2544
+ return { name: fallbackName, description: "", persona: "" };
2545
+ }
2546
+ try {
2547
+ const meta = JSON.parse(first.content);
2548
+ return {
2549
+ name: typeof meta["name"] === "string" ? meta["name"] : fallbackName,
2550
+ description: typeof meta["description"] === "string" ? meta["description"] : "",
2551
+ persona: typeof meta["persona"] === "string" ? meta["persona"] : ""
2552
+ };
2553
+ } catch {
2554
+ return { name: fallbackName, description: "", persona: "" };
2555
+ }
2556
+ }
2557
+ async function resolveSkillRefs(client, skillRefs) {
2558
+ if (skillRefs.length === 0) {
2559
+ return [];
2560
+ }
2561
+ const skillKbids = skillRefs.map((s) => s.kbid);
2562
+ const skillSections = await client.readSections(skillKbids);
2563
+ const sectionMap = new Map(skillSections.map((s) => [s.kbid, s]));
2564
+ return skillRefs.map((ref) => {
2565
+ const sec = sectionMap.get(ref.kbid);
2566
+ if (!sec) {
2567
+ return { kbid: ref.kbid, name: null, position: ref.position };
2568
+ }
2569
+ try {
2570
+ const parsed = JSON.parse(sec.content);
2571
+ const skillName = typeof parsed["name"] === "string" ? parsed["name"] : null;
2572
+ return {
2573
+ kbid: ref.kbid,
2574
+ name: skillName,
2575
+ position: ref.position
2576
+ };
2577
+ } catch {
2578
+ return { kbid: ref.kbid, name: null, position: ref.position };
2579
+ }
2580
+ });
2581
+ }
2582
+ async function handleAgentGet(client, args) {
2583
+ const docid = typeof args["docid"] === "string" ? args["docid"] : "";
2584
+ if (!docid) {
2585
+ return {
2586
+ content: [{ type: "text", text: "docid is required" }],
2587
+ isError: true
2588
+ };
2589
+ }
2590
+ const doc = await client.retrieveDocument(docid);
2591
+ const metaKbid = doc.sections[0]?.kbid;
2592
+ const skillRefs = doc.sections.slice(1);
2593
+ const { name, description, persona } = metaKbid ? await readAgentMeta2(client, metaKbid, doc.title) : { name: doc.title, description: "", persona: "" };
2594
+ const skills = await resolveSkillRefs(client, skillRefs);
2595
+ const agent = {
2596
+ docid,
2597
+ name,
2598
+ description,
2599
+ persona,
2600
+ skills
2601
+ };
2602
+ return {
2603
+ content: [
2604
+ {
2605
+ type: "text",
2606
+ text: JSON.stringify(agent, null, 2)
2607
+ }
2608
+ ]
2609
+ };
2610
+ }
2611
+
2612
+ // src/shared/mcp/functions/handle-agent-delete.function.ts
2613
+ async function handleAgentDelete(client, args) {
2614
+ const docid = typeof args["docid"] === "string" ? args["docid"] : "";
2615
+ if (!docid) {
2616
+ return {
2617
+ content: [{ type: "text", text: "docid is required" }],
2618
+ isError: true
2619
+ };
2620
+ }
2621
+ await client.removeGrouping(docid);
2622
+ return {
2623
+ content: [
2624
+ {
2625
+ type: "text",
2626
+ text: JSON.stringify({ docid, removed: true })
2627
+ }
2628
+ ]
2629
+ };
2630
+ }
2631
+
2632
+ // src/shared/mcp/functions/handle-tool-call.function.ts
2633
+ function asString2(value, fallback) {
2634
+ return typeof value === "string" ? value : fallback;
2635
+ }
2636
+ function asStringArray2(value) {
2637
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
2638
+ return value;
2639
+ }
2640
+ return [];
2641
+ }
2642
+ async function handleToolCall(client, name, args) {
2643
+ try {
2644
+ switch (name) {
2645
+ case "search":
2646
+ return await handleSearch2(client, args);
2647
+ case "learn":
2648
+ return await handleLearn2(client, args);
2649
+ case "unlearn":
2650
+ return await handleUnlearn2(client, args);
2651
+ case "retrieve":
2652
+ return await handleRetrieve(client, args);
2653
+ case "status":
2654
+ return await handleStatus2(client);
2655
+ case "content":
2656
+ return await handleContent2(client, args);
2657
+ case "check":
2658
+ return await handleCheck2(client);
2659
+ case "gc":
2660
+ return await handleGc2(client);
2661
+ case "rebuild":
2662
+ return await handleRebuild2(client);
2663
+ case "skill-learn":
2664
+ return await handleSkillLearn(client, args);
2665
+ case "skill-list":
2666
+ return await handleSkillList(client);
2667
+ case "skill-get":
2668
+ return await handleSkillGet(client, args);
2669
+ case "skill-delete":
2670
+ return await handleSkillDelete(client, args);
2671
+ case "agent-create":
2672
+ return await handleAgentCreate(client, args);
2673
+ case "agent-list":
2674
+ return await handleAgentList(client);
2675
+ case "agent-get":
2676
+ return await handleAgentGet(client, args);
2677
+ case "agent-delete":
2678
+ return await handleAgentDelete(client, args);
2679
+ default:
2680
+ return {
2681
+ content: [
2682
+ {
2683
+ type: "text",
2684
+ text: `Unknown tool: ${name}`
2685
+ }
2686
+ ],
2687
+ isError: true
2688
+ };
2689
+ }
2690
+ } catch (err) {
2691
+ return {
2692
+ content: [
2693
+ {
2694
+ type: "text",
2695
+ text: err instanceof Error ? err.message : String(err)
2696
+ }
2697
+ ],
2698
+ isError: true
2699
+ };
2700
+ }
2701
+ }
2702
+ async function handleSearch2(client, args) {
2703
+ const results = await client.search({
2704
+ query: asString2(args["query"], ""),
2705
+ mode: args["mode"],
2706
+ limit: args["limit"]
2707
+ });
2708
+ return {
2709
+ content: [
2710
+ {
2711
+ type: "text",
2712
+ text: JSON.stringify(results, null, 2)
2713
+ }
2714
+ ]
2715
+ };
2716
+ }
2717
+ async function handleLearn2(client, args) {
2718
+ const sectionType = asString2(args["type"], "text/markdown");
2719
+ const title = typeof args["title"] === "string" ? args["title"] : void 0;
2720
+ const description = typeof args["description"] === "string" ? args["description"] : void 0;
2721
+ const docid = typeof args["docid"] === "string" ? args["docid"] : void 0;
2722
+ if (sectionType.startsWith("image/") && !title) {
2723
+ return {
2724
+ content: [
2725
+ {
2726
+ type: "text",
2727
+ text: "title is required for image/* types"
2728
+ }
2729
+ ],
2730
+ isError: true
2731
+ };
2732
+ }
2733
+ const result = await client.addSection({
2734
+ sectionType,
2735
+ content: asString2(args["content"], ""),
2736
+ title,
2737
+ description,
2738
+ docid
2739
+ });
2740
+ return {
2741
+ content: [
2742
+ {
2743
+ type: "text",
2744
+ text: JSON.stringify(result)
2745
+ }
2746
+ ]
2747
+ };
2748
+ }
2749
+ async function handleUnlearn2(client, args) {
2750
+ const result = await client.removeSection(
2751
+ asString2(args["kbid"], "")
2752
+ );
2753
+ return {
2754
+ content: [
2755
+ {
2756
+ type: "text",
2757
+ text: JSON.stringify(result)
2758
+ }
2759
+ ]
2760
+ };
2761
+ }
2762
+ async function handleRetrieve(client, args) {
2763
+ if (typeof args["kbid"] === "string") {
2764
+ const sections = await client.readSections([args["kbid"]]);
2765
+ return {
2766
+ content: [
2767
+ {
2768
+ type: "text",
2769
+ text: JSON.stringify(sections, null, 2)
2770
+ }
2771
+ ]
2772
+ };
2773
+ }
2774
+ if (typeof args["docid"] === "string") {
2775
+ const doc = await client.retrieveDocument(args["docid"]);
2776
+ return {
2777
+ content: [
2778
+ {
2779
+ type: "text",
2780
+ text: JSON.stringify(doc, null, 2)
2781
+ }
2782
+ ]
2783
+ };
2784
+ }
2785
+ return {
2786
+ content: [
2787
+ {
2788
+ type: "text",
2789
+ text: "Provide kbid or docid"
2790
+ }
2791
+ ],
2792
+ isError: true
2793
+ };
2794
+ }
2795
+ async function handleStatus2(client) {
2796
+ const status = await client.dbStatus();
2797
+ return {
2798
+ content: [
2799
+ {
2800
+ type: "text",
2801
+ text: JSON.stringify(status, null, 2)
2802
+ }
2803
+ ]
2804
+ };
2805
+ }
2806
+ async function handleContent2(client, args) {
2807
+ const ids = asStringArray2(args["ids"]);
2808
+ const result = await client.content(ids);
2809
+ return {
2810
+ content: [
2811
+ {
2812
+ type: "text",
2813
+ text: JSON.stringify(result)
2814
+ }
2815
+ ]
2816
+ };
2817
+ }
2818
+ async function handleCheck2(client) {
2819
+ const report = await client.integrityCheck();
2820
+ return {
2821
+ content: [
2822
+ {
2823
+ type: "text",
2824
+ text: JSON.stringify(report, null, 2)
2825
+ }
2826
+ ]
2827
+ };
2828
+ }
2829
+ async function handleGc2(client) {
2830
+ const report = await client.gc();
2831
+ return {
2832
+ content: [
2833
+ {
2834
+ type: "text",
2835
+ text: JSON.stringify(report, null, 2)
2836
+ }
2837
+ ]
2838
+ };
2839
+ }
2840
+ async function handleRebuild2(client) {
2841
+ const report = await client.rebuildIndexes();
2842
+ return {
2843
+ content: [
2844
+ {
2845
+ type: "text",
2846
+ text: JSON.stringify(report, null, 2)
2847
+ }
2848
+ ]
2849
+ };
2850
+ }
2851
+ async function handleSkillLearn(client, args) {
2852
+ const name = asString2(args["name"], "");
2853
+ if (!name) {
2854
+ return {
2855
+ content: [{ type: "text", text: "name is required" }],
2856
+ isError: true
2857
+ };
2858
+ }
2859
+ const body = asString2(args["body"], "");
2860
+ if (!body) {
2861
+ return {
2862
+ content: [{ type: "text", text: "body is required" }],
2863
+ isError: true
2864
+ };
2865
+ }
2866
+ const description = typeof args["description"] === "string" ? args["description"] : void 0;
2867
+ const skillArgs = extractSkillArguments(body);
2868
+ const skill = {
2869
+ name,
2870
+ description,
2871
+ arguments: skillArgs.length > 0 ? skillArgs : void 0,
2872
+ body
2873
+ };
2874
+ const json = serializeSkillContent(skill);
2875
+ const result = await client.addSection({
2876
+ sectionType: "skill",
2877
+ content: json,
2878
+ title: name,
2879
+ description
2880
+ });
2881
+ return {
2882
+ content: [
2883
+ {
2884
+ type: "text",
2885
+ text: JSON.stringify({ kbid: result.kbid, name })
2886
+ }
2887
+ ]
2888
+ };
2889
+ }
2890
+ async function handleSkillList(client) {
2891
+ const records = await client.listByType("skill");
2892
+ const items = records.map((r) => {
2893
+ let argumentCount = 0;
2894
+ try {
2895
+ const parsed = JSON.parse(r.content);
2896
+ if (Array.isArray(parsed["arguments"])) {
2897
+ argumentCount = parsed["arguments"].length;
2898
+ }
2899
+ } catch {
2900
+ }
2901
+ return {
2902
+ kbid: r.kbid,
2903
+ name: r.title,
2904
+ description: r.description,
2905
+ argumentCount
2906
+ };
2907
+ });
2908
+ return {
2909
+ content: [
2910
+ {
2911
+ type: "text",
2912
+ text: JSON.stringify(items, null, 2)
2913
+ }
2914
+ ]
2915
+ };
2916
+ }
2917
+ async function handleSkillGet(client, args) {
2918
+ const kbid = typeof args["kbid"] === "string" ? args["kbid"] : void 0;
2919
+ const name = typeof args["name"] === "string" ? args["name"] : void 0;
2920
+ if (!kbid && !name) {
2921
+ return {
2922
+ content: [
2923
+ {
2924
+ type: "text",
2925
+ text: "name or kbid is required"
2926
+ }
2927
+ ],
2928
+ isError: true
2929
+ };
2930
+ }
2931
+ let content;
2932
+ if (kbid) {
2933
+ const sections = await client.readSections([kbid]);
2934
+ if (sections.length > 0) {
2935
+ content = sections[0]?.content;
2936
+ }
2937
+ }
2938
+ if (content === void 0 && name) {
2939
+ const records = await client.listByType("skill");
2940
+ const match = records.filter((r) => r.title === name).pop();
2941
+ if (match) {
2942
+ content = match.content;
2943
+ }
2944
+ }
2945
+ if (content === void 0) {
2946
+ const identifier = kbid ?? name ?? "";
2947
+ return {
2948
+ content: [
2949
+ {
2950
+ type: "text",
2951
+ text: `skill not found: ${identifier}`
2952
+ }
2953
+ ],
2954
+ isError: true
2955
+ };
2956
+ }
2957
+ const skill = parseSkillContent(content);
2958
+ return {
2959
+ content: [
2960
+ {
2961
+ type: "text",
2962
+ text: JSON.stringify(skill, null, 2)
2963
+ }
2964
+ ]
2965
+ };
2966
+ }
2967
+ async function handleSkillDelete(client, args) {
2968
+ const kbid = asString2(args["kbid"], "");
2969
+ if (!kbid) {
2970
+ return {
2971
+ content: [{ type: "text", text: "kbid is required" }],
2972
+ isError: true
2973
+ };
2974
+ }
2975
+ const result = await client.removeSection(kbid);
2976
+ return {
2977
+ content: [
2978
+ {
2979
+ type: "text",
2980
+ text: JSON.stringify({ kbid, removed: result.removed })
2981
+ }
2982
+ ]
2983
+ };
2984
+ }
2985
+
2986
+ // src/shared/mcp/functions/handle-resource-read.function.ts
2987
+ async function handleResourceRead(client, uri) {
2988
+ const sectionMatch = uri.match(/^kbdb:\/\/section\/(.+)$/);
2989
+ if (sectionMatch) {
2990
+ const sections = await client.readSections([sectionMatch[1]]);
2991
+ const text = sections.length > 0 ? sections[0].content : "";
2992
+ return {
2993
+ contents: [{ uri, mimeType: "text/plain", text }]
2994
+ };
2995
+ }
2996
+ const docMatch = uri.match(/^kbdb:\/\/document\/(.+)$/);
2997
+ if (docMatch) {
2998
+ const doc = await client.retrieveDocument(docMatch[1]);
2999
+ return {
3000
+ contents: [
3001
+ {
3002
+ uri,
3003
+ mimeType: "application/json",
3004
+ text: JSON.stringify(doc, null, 2)
3005
+ }
3006
+ ]
3007
+ };
3008
+ }
3009
+ throw new Error(`Unknown resource URI: ${uri}`);
3010
+ }
3011
+
3012
+ // src/shared/mcp/functions/create-prompt-definitions.function.ts
3013
+ function parseSkillArguments(content) {
3014
+ try {
3015
+ const parsed = JSON.parse(content);
3016
+ if (!Array.isArray(parsed["arguments"])) {
3017
+ return void 0;
3018
+ }
3019
+ return parsed["arguments"].map(
3020
+ (arg) => ({
3021
+ name: typeof arg["name"] === "string" ? arg["name"] : "",
3022
+ description: typeof arg["description"] === "string" ? arg["description"] : void 0,
3023
+ required: typeof arg["required"] === "boolean" ? arg["required"] : void 0
3024
+ })
3025
+ );
3026
+ } catch {
3027
+ return void 0;
3028
+ }
3029
+ }
3030
+ function createPromptDefinitions(skills, agents) {
3031
+ const skillPrompts = skills.filter(
3032
+ (r) => r.title !== null
3033
+ ).map((record) => {
3034
+ const args = parseSkillArguments(record.content);
3035
+ const prompt = {
3036
+ name: record.title,
3037
+ description: record.description ?? void 0,
3038
+ arguments: args
3039
+ };
3040
+ return prompt;
3041
+ });
3042
+ const agentPrompts = agents.map((doc) => ({
3043
+ name: `agent:${doc.title}`,
3044
+ arguments: []
3045
+ }));
3046
+ return [...skillPrompts, ...agentPrompts];
3047
+ }
3048
+
3049
+ // src/shared/mcp/functions/handle-prompt-get.function.ts
3050
+ function parseAgentMeta(content) {
3051
+ try {
3052
+ const parsed = JSON.parse(content);
3053
+ return {
3054
+ persona: typeof parsed["persona"] === "string" ? parsed["persona"] : ""
3055
+ };
3056
+ } catch {
3057
+ return { persona: "" };
3058
+ }
3059
+ }
3060
+ function buildSkillsText(skillSections) {
3061
+ const lines = [];
3062
+ for (const sec of skillSections) {
3063
+ try {
3064
+ const parsed = JSON.parse(sec.content);
3065
+ const name = typeof parsed["name"] === "string" ? parsed["name"] : null;
3066
+ if (name === null) {
3067
+ continue;
3068
+ }
3069
+ const description = typeof parsed["description"] === "string" ? parsed["description"] : "";
3070
+ lines.push(`- ${name}: ${description}`);
3071
+ } catch {
3072
+ }
3073
+ }
3074
+ if (lines.length === 0) {
3075
+ return null;
3076
+ }
3077
+ return `Available skills:
3078
+ ${lines.join("\n")}`;
3079
+ }
3080
+ async function handleAgentPrompt(name, client) {
3081
+ const docid = name.slice(6);
3082
+ const doc = await client.retrieveDocument(docid);
3083
+ const sections = doc.sections;
3084
+ const metaSection = sections.at(0);
3085
+ const skillRefs = sections.slice(1);
3086
+ let persona = "";
3087
+ if (metaSection !== void 0) {
3088
+ const metaSections = await client.readSections([
3089
+ metaSection.kbid
3090
+ ]);
3091
+ const metaContent = metaSections.at(0);
3092
+ if (metaContent !== void 0) {
3093
+ persona = parseAgentMeta(metaContent.content).persona;
3094
+ }
3095
+ }
3096
+ const messages = [
3097
+ {
3098
+ role: "assistant",
3099
+ content: { type: "text", text: persona }
3100
+ }
3101
+ ];
3102
+ if (skillRefs.length === 0) {
3103
+ return messages;
3104
+ }
3105
+ const skillKbids = skillRefs.map((s) => s.kbid);
3106
+ const skillSections = await client.readSections(skillKbids);
3107
+ const skillsText = buildSkillsText(skillSections);
3108
+ if (skillsText !== null) {
3109
+ messages.push({
3110
+ role: "user",
3111
+ content: { type: "text", text: skillsText }
3112
+ });
3113
+ }
3114
+ return messages;
3115
+ }
3116
+ async function handleSkillPrompt(name, promptArgs, client) {
3117
+ const sections = await client.listByType("skill");
3118
+ let matchContent;
3119
+ for (const sec of sections) {
3120
+ if (sec.title === name) {
3121
+ matchContent = sec.content;
3122
+ }
3123
+ }
3124
+ if (matchContent === void 0) {
3125
+ throw new Error(`Prompt not found: ${name}`);
3126
+ }
3127
+ const parsed = JSON.parse(matchContent);
3128
+ const body = typeof parsed["body"] === "string" ? parsed["body"] : "";
3129
+ const rendered = body.replace(
3130
+ /\{\{(\w+)\}\}/g,
3131
+ (_match, key) => key in promptArgs ? promptArgs[key] ?? _match : _match
3132
+ );
3133
+ return [
3134
+ {
3135
+ role: "user",
3136
+ content: { type: "text", text: rendered }
3137
+ }
3138
+ ];
3139
+ }
3140
+ async function handlePromptGet(name, promptArgs, client) {
3141
+ if (name.startsWith("agent:")) {
3142
+ return handleAgentPrompt(name, client);
3143
+ }
3144
+ return handleSkillPrompt(name, promptArgs, client);
3145
+ }
3146
+
3147
+ // src/shared/mcp/functions/handle-completion.function.ts
3148
+ async function handleCompletion(ref, argument, client) {
3149
+ if (ref.type !== "ref/prompt") {
3150
+ return { completion: { values: [], hasMore: false, total: 0 } };
3151
+ }
3152
+ const [skills, agents] = await Promise.all([
3153
+ client.listByType("skill"),
3154
+ client.listDocumentsByType("agent")
3155
+ ]);
3156
+ const names = [];
3157
+ for (const skill of skills) {
3158
+ if (skill.title !== null) {
3159
+ names.push(skill.title);
3160
+ }
3161
+ }
3162
+ for (const agent of agents) {
3163
+ names.push(`agent:${agent.title}`);
3164
+ }
3165
+ const prefix = argument.value;
3166
+ function matchesPrefix(candidate) {
3167
+ if (prefix.length === 0) {
3168
+ return true;
3169
+ }
3170
+ if (candidate.startsWith(prefix)) {
3171
+ return true;
3172
+ }
3173
+ const AGENT_PREFIX = "agent:";
3174
+ if (candidate.startsWith(AGENT_PREFIX)) {
3175
+ return candidate.slice(AGENT_PREFIX.length).startsWith(prefix);
3176
+ }
3177
+ return false;
3178
+ }
3179
+ const values = names.filter(matchesPrefix);
3180
+ return {
3181
+ completion: {
3182
+ values,
3183
+ hasMore: false,
3184
+ total: values.length
3185
+ }
3186
+ };
3187
+ }
3188
+
3189
+ // src/shared/mcp/functions/handle-roots-list.function.ts
3190
+ function handleRootsList(contextPath) {
3191
+ return [
3192
+ {
3193
+ uri: `file://${contextPath}`,
3194
+ name: "kbdb database"
3195
+ }
3196
+ ];
3197
+ }
3198
+
3199
+ // src/shared/mcp/functions/should-emit-log.function.ts
3200
+ var LOG_LEVEL_ORDER = [
3201
+ "debug",
3202
+ "info",
3203
+ "notice",
3204
+ "warning",
3205
+ "error",
3206
+ "critical",
3207
+ "alert",
3208
+ "emergency"
3209
+ ];
3210
+ function shouldEmitLog(messageLevel, threshold) {
3211
+ const messageIndex = LOG_LEVEL_ORDER.indexOf(messageLevel);
3212
+ const thresholdIndex = LOG_LEVEL_ORDER.indexOf(threshold);
3213
+ return messageIndex >= thresholdIndex;
3214
+ }
3215
+
3216
+ // src/shared/mcp/constants/mcp-error-codes.constant.ts
3217
+ var PARSE_ERROR = -32700;
3218
+ var METHOD_NOT_FOUND = -32601;
3219
+ var RESOURCE_NOT_FOUND = -32002;
3220
+
3221
+ // src/shared/mcp/classes/mcp-server.class.ts
3222
+ var McpServer = class {
3223
+ client;
3224
+ contextPath;
3225
+ initialized = false;
3226
+ hostCapabilities = null;
3227
+ logLevel = null;
3228
+ subscriptions = /* @__PURE__ */ new Set();
3229
+ nextRequestId = 1;
3230
+ pendingRequests = /* @__PURE__ */ new Map();
3231
+ constructor(client, contextPath) {
3232
+ this.client = client;
3233
+ this.contextPath = contextPath ?? "";
3234
+ }
3235
+ async listen() {
3236
+ const rl = (0, import_node_readline2.createInterface)({
3237
+ input: process.stdin,
3238
+ terminal: false
3239
+ });
3240
+ await new Promise((resolve4) => {
3241
+ rl.on("line", (line) => {
3242
+ void this.dispatchLine(line);
3243
+ });
3244
+ rl.on("close", () => {
3245
+ this.client.disconnect();
3246
+ resolve4();
3247
+ });
3248
+ });
3249
+ }
3250
+ async handleLineForTest(line) {
3251
+ return this.processLine(line);
3252
+ }
3253
+ /**
3254
+ * Sends a JSON-RPC notification (no `id`, no response
3255
+ * expected) to stdout.
3256
+ */
3257
+ notify(method, params) {
3258
+ const notification = {
3259
+ jsonrpc: "2.0",
3260
+ method
3261
+ };
3262
+ if (params !== void 0) {
3263
+ notification["params"] = params;
3264
+ }
3265
+ process.stdout.write(JSON.stringify(notification) + "\n");
3266
+ }
3267
+ /**
3268
+ * Emits a log notification if the message severity meets or
3269
+ * exceeds the configured log level threshold.
3270
+ */
3271
+ log(level, message, logger) {
3272
+ if (this.logLevel === null) return;
3273
+ if (!shouldEmitLog(level, this.logLevel)) return;
3274
+ this.notify("notifications/message", {
3275
+ level,
3276
+ logger: logger ?? "kbdb",
3277
+ data: message
3278
+ });
3279
+ }
3280
+ /**
3281
+ * Sends a JSON-RPC request to the host (server-to-client)
3282
+ * and returns a Promise that resolves with the response
3283
+ * result. Times out after 30 seconds.
3284
+ */
3285
+ sendRequest(method, params) {
3286
+ const id = this.nextRequestId++;
3287
+ const request = { jsonrpc: "2.0", id, method, params };
3288
+ process.stdout.write(JSON.stringify(request) + "\n");
3289
+ return new Promise((resolve4, reject) => {
3290
+ const timer = setTimeout(() => {
3291
+ this.pendingRequests.delete(id);
3292
+ reject(new Error(`Request ${method} timed out`));
3293
+ }, 3e4);
3294
+ this.pendingRequests.set(id, {
3295
+ resolve: resolve4,
3296
+ reject,
3297
+ timer
3298
+ });
3299
+ });
3300
+ }
3301
+ /**
3302
+ * Requests the host to generate text via the sampling
3303
+ * capability. Throws if the host did not advertise sampling
3304
+ * support during initialization.
3305
+ */
3306
+ async requestSampling(messages, maxTokens) {
3307
+ if (!this.hostCapabilities?.["sampling"]) {
3308
+ throw new Error("Host does not support sampling");
3309
+ }
3310
+ return this.sendRequest("sampling/createMessage", {
3311
+ messages,
3312
+ maxTokens
3313
+ });
3314
+ }
3315
+ async dispatchLine(line) {
3316
+ const response = await this.processLine(line);
3317
+ if (response !== null) {
3318
+ this.send(response);
3319
+ }
3320
+ }
3321
+ async processLine(line) {
3322
+ if (!line.trim()) return null;
3323
+ let parsed;
3324
+ try {
3325
+ parsed = JSON.parse(line);
3326
+ } catch {
3327
+ return {
3328
+ jsonrpc: "2.0",
3329
+ id: 0,
3330
+ error: {
3331
+ code: PARSE_ERROR,
3332
+ message: "Parse error"
3333
+ }
3334
+ };
3335
+ }
3336
+ if (parsed["id"] !== void 0 && typeof parsed["method"] !== "string") {
3337
+ const responseId = parsed["id"];
3338
+ const pending = this.pendingRequests.get(responseId);
3339
+ if (pending) {
3340
+ this.pendingRequests.delete(responseId);
3341
+ clearTimeout(pending.timer);
3342
+ if (parsed["error"]) {
3343
+ const err = parsed["error"];
3344
+ pending.reject(
3345
+ new Error(err.message ?? "Request failed")
3346
+ );
3347
+ } else {
3348
+ pending.resolve(parsed["result"]);
3349
+ }
3350
+ }
3351
+ return null;
3352
+ }
3353
+ const request = parsed;
3354
+ if (request.id === void 0) {
3355
+ if (request.method === "notifications/initialized" || request.method === "notifications/cancelled") {
3356
+ if (request.method === "notifications/initialized") {
3357
+ this.initialized = true;
3358
+ }
3359
+ }
3360
+ return null;
3361
+ }
3362
+ const id = request.id;
3363
+ if (!this.initialized && request.method !== "initialize" && request.method !== "ping") {
3364
+ return {
3365
+ jsonrpc: "2.0",
3366
+ id,
3367
+ error: {
3368
+ code: RESOURCE_NOT_FOUND,
3369
+ message: "Server not initialized"
3370
+ }
3371
+ };
3372
+ }
3373
+ const response = await this.handleRequest(request);
3374
+ return response;
3375
+ }
3376
+ async handleRequest(request) {
3377
+ const id = request.id;
3378
+ switch (request.method) {
3379
+ case "initialize": {
3380
+ const params = request.params ?? {};
3381
+ const caps = params["capabilities"];
3382
+ this.hostCapabilities = caps ? caps : null;
3383
+ return {
3384
+ jsonrpc: "2.0",
3385
+ id,
3386
+ result: {
3387
+ protocolVersion: "2025-11-25",
3388
+ serverInfo: {
3389
+ name: "kbdb",
3390
+ version: "0.1.0"
3391
+ },
3392
+ capabilities: {
3393
+ tools: {},
3394
+ resources: { subscribe: true },
3395
+ prompts: {},
3396
+ logging: {},
3397
+ completions: {}
3398
+ }
3399
+ }
3400
+ };
3401
+ }
3402
+ case "ping":
3403
+ return { jsonrpc: "2.0", id, result: {} };
3404
+ case "tools/list":
3405
+ return {
3406
+ jsonrpc: "2.0",
3407
+ id,
3408
+ result: {
3409
+ tools: createToolDefinitions()
3410
+ }
3411
+ };
3412
+ case "resources/list":
3413
+ return {
3414
+ jsonrpc: "2.0",
3415
+ id,
3416
+ result: { resources: [] }
3417
+ };
3418
+ case "resources/templates/list":
3419
+ return {
3420
+ jsonrpc: "2.0",
3421
+ id,
3422
+ result: {
3423
+ resourceTemplates: createResourceTemplates()
3424
+ }
3425
+ };
3426
+ case "tools/call": {
3427
+ const params = request.params ?? {};
3428
+ const rawName = params["name"];
3429
+ const name = typeof rawName === "string" ? rawName : "";
3430
+ const args = params["arguments"] ?? {};
3431
+ const result = await handleToolCall(
3432
+ this.client,
3433
+ name,
3434
+ args
3435
+ );
3436
+ return { jsonrpc: "2.0", id, result };
3437
+ }
3438
+ case "resources/read": {
3439
+ const params = request.params ?? {};
3440
+ const rawUri = params["uri"];
3441
+ const uri = typeof rawUri === "string" ? rawUri : "";
3442
+ try {
3443
+ const result = await handleResourceRead(
3444
+ this.client,
3445
+ uri
3446
+ );
3447
+ return { jsonrpc: "2.0", id, result };
3448
+ } catch (err) {
3449
+ return {
3450
+ jsonrpc: "2.0",
3451
+ id,
3452
+ error: {
3453
+ code: RESOURCE_NOT_FOUND,
3454
+ message: err instanceof Error ? err.message : String(err)
3455
+ }
3456
+ };
3457
+ }
3458
+ }
3459
+ case "prompts/list": {
3460
+ const skills = await this.client.listByType("skill");
3461
+ const agents = await this.client.listDocumentsByType("agent");
3462
+ const prompts = createPromptDefinitions(skills, agents);
3463
+ return {
3464
+ jsonrpc: "2.0",
3465
+ id,
3466
+ result: { prompts }
3467
+ };
3468
+ }
3469
+ case "prompts/get": {
3470
+ const params = request.params ?? {};
3471
+ const name = typeof params["name"] === "string" ? params["name"] : "";
3472
+ const promptArgs = params["arguments"] ?? {};
3473
+ try {
3474
+ const messages = await handlePromptGet(
3475
+ name,
3476
+ promptArgs,
3477
+ this.client
3478
+ );
3479
+ return {
3480
+ jsonrpc: "2.0",
3481
+ id,
3482
+ result: { messages }
3483
+ };
3484
+ } catch (err) {
3485
+ return {
3486
+ jsonrpc: "2.0",
3487
+ id,
3488
+ error: {
3489
+ code: RESOURCE_NOT_FOUND,
3490
+ message: err instanceof Error ? err.message : String(err)
3491
+ }
3492
+ };
3493
+ }
3494
+ }
3495
+ case "completion/complete": {
3496
+ const params = request.params ?? {};
3497
+ const ref = params["ref"];
3498
+ const argument = params["argument"] ?? {
3499
+ name: "",
3500
+ value: ""
3501
+ };
3502
+ const result = await handleCompletion(
3503
+ ref,
3504
+ argument,
3505
+ this.client
3506
+ );
3507
+ return { jsonrpc: "2.0", id, result };
3508
+ }
3509
+ case "roots/list": {
3510
+ const roots = handleRootsList(this.contextPath);
3511
+ return {
3512
+ jsonrpc: "2.0",
3513
+ id,
3514
+ result: { roots }
3515
+ };
3516
+ }
3517
+ case "logging/setLevel": {
3518
+ const params = request.params ?? {};
3519
+ const level = params["level"];
3520
+ this.logLevel = level ?? null;
3521
+ return { jsonrpc: "2.0", id, result: {} };
3522
+ }
3523
+ case "resources/subscribe": {
3524
+ const params = request.params ?? {};
3525
+ const uri = typeof params["uri"] === "string" ? params["uri"] : "";
3526
+ this.subscriptions.add(uri);
3527
+ return { jsonrpc: "2.0", id, result: {} };
3528
+ }
3529
+ case "resources/unsubscribe": {
3530
+ const params = request.params ?? {};
3531
+ const uri = typeof params["uri"] === "string" ? params["uri"] : "";
3532
+ this.subscriptions.delete(uri);
3533
+ return { jsonrpc: "2.0", id, result: {} };
3534
+ }
3535
+ default:
3536
+ return {
3537
+ jsonrpc: "2.0",
3538
+ id,
3539
+ error: {
3540
+ code: METHOD_NOT_FOUND,
3541
+ message: `Method not found: ` + request.method
3542
+ }
3543
+ };
3544
+ }
3545
+ }
3546
+ send(response) {
3547
+ const json = JSON.stringify(response);
3548
+ process.stdout.write(json + "\n");
3549
+ }
3550
+ };
3551
+
3552
+ // src/shared/mcp/functions/create-mcp-server.function.ts
3553
+ function createMcpServer(client) {
3554
+ return new McpServer(client);
3555
+ }
3556
+
3557
+ // src/cli.ts
3558
+ var import_meta = {};
3559
+ var runtime = detectRuntime();
3560
+ var baseDir = resolveBaseDir(import_meta.url, import_meta.dirname);
3561
+ var workerScript = resolveWorkerScript(baseDir.scriptDir, runtime);
3562
+ var deps = {
3563
+ isStdinTty,
3564
+ promptUser,
3565
+ createWorkerClient: (opts) => createWorkerClient({ ...opts, workerScript }),
3566
+ findDb,
3567
+ runInit,
3568
+ startMcpServer: async (contextPath) => {
3569
+ const client = await createWorkerClient({
3570
+ contextPath,
3571
+ workerScript
3572
+ });
3573
+ try {
3574
+ const server = createMcpServer(client);
3575
+ await server.listen();
3576
+ } finally {
3577
+ client.disconnect();
3578
+ }
3579
+ }
3580
+ };
3581
+ async function main() {
3582
+ const result = await runCli(getArgs(), deps);
3583
+ if (result.output) {
3584
+ console.log(result.output);
3585
+ }
3586
+ if (result.error) {
3587
+ console.error(result.error);
3588
+ }
3589
+ if (result.exitCode !== 0) {
3590
+ process.exitCode = result.exitCode;
3591
+ }
3592
+ }
3593
+ main().catch((err) => {
3594
+ const msg = err instanceof Error ? err.message : String(err);
3595
+ console.error(`error: ${msg}`);
3596
+ process.exitCode = 1;
3597
+ });
3598
+ //# sourceMappingURL=cli.cjs.map