kiki-agent 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +3 -3
  2. package/dist/cpu-worker.mjs +52744 -0
  3. package/dist/docs/en/configuration/config-files.md +121 -46
  4. package/dist/docs/en/configuration/data-locations.md +34 -7
  5. package/dist/docs/en/configuration/env-vars.md +37 -9
  6. package/dist/docs/en/configuration/overrides.md +20 -9
  7. package/dist/docs/en/configuration/providers.md +114 -9
  8. package/dist/docs/en/customization/agent-profiles.md +1 -1
  9. package/dist/docs/en/customization/agents-and-subagents.md +55 -12
  10. package/dist/docs/en/customization/hooks.md +3 -3
  11. package/dist/docs/en/customization/personas.md +36 -2
  12. package/dist/docs/en/customization/plugins.md +56 -3
  13. package/dist/docs/en/customization/prompt-fields.md +65 -5
  14. package/dist/docs/en/customization/recipes.md +77 -0
  15. package/dist/docs/en/customization/skins.md +2 -2
  16. package/dist/docs/en/customization/themes.md +1 -1
  17. package/dist/docs/en/features/agent-workflows.md +8 -8
  18. package/dist/docs/en/features/browser-and-computer.md +40 -0
  19. package/dist/docs/en/features/daily.md +13 -13
  20. package/dist/docs/en/features/ecosystem.md +6 -6
  21. package/dist/docs/en/features/extend.md +11 -10
  22. package/dist/docs/en/features/freedom.md +9 -9
  23. package/dist/docs/en/features/index.md +58 -28
  24. package/dist/docs/en/features/long-work.md +18 -14
  25. package/dist/docs/en/features/look.md +6 -6
  26. package/dist/docs/en/features/people.md +6 -6
  27. package/dist/docs/en/features/phone.md +13 -3
  28. package/dist/docs/en/features/spaces.md +12 -12
  29. package/dist/docs/en/features/workbench.md +8 -8
  30. package/dist/docs/en/getting-started/desktop-app.md +4 -8
  31. package/dist/docs/en/getting-started/first-launch.md +1 -1
  32. package/dist/docs/en/guides/goals.md +4 -2
  33. package/dist/docs/en/guides/interface.md +32 -10
  34. package/dist/docs/en/guides/memory.md +64 -10
  35. package/dist/docs/en/guides/sessions.md +21 -9
  36. package/dist/docs/en/guides/settings.md +64 -40
  37. package/dist/docs/en/index.md +3 -1
  38. package/dist/docs/en/reference/command.md +90 -31
  39. package/dist/docs/en/reference/model-vocabulary.md +2 -2
  40. package/dist/docs/en/reference/slash-commands.md +1 -1
  41. package/dist/docs/en/reference/tools.md +65 -20
  42. package/dist/docs/en/server/acp.md +9 -3
  43. package/dist/docs/en/server/local-server.md +19 -27
  44. package/dist/docs/en/server/mcp.md +9 -5
  45. package/dist/docs/en/server/rest-api.md +350 -22
  46. package/dist/docs/en/server/script-tools.md +268 -0
  47. package/dist/docs/zh/configuration/config-files.md +121 -46
  48. package/dist/docs/zh/configuration/data-locations.md +34 -7
  49. package/dist/docs/zh/configuration/env-vars.md +37 -9
  50. package/dist/docs/zh/configuration/overrides.md +20 -9
  51. package/dist/docs/zh/configuration/providers.md +114 -9
  52. package/dist/docs/zh/customization/agent-profiles.md +1 -1
  53. package/dist/docs/zh/customization/agents-and-subagents.md +55 -12
  54. package/dist/docs/zh/customization/hooks.md +3 -3
  55. package/dist/docs/zh/customization/personas.md +36 -2
  56. package/dist/docs/zh/customization/plugins.md +56 -3
  57. package/dist/docs/zh/customization/prompt-fields.md +65 -5
  58. package/dist/docs/zh/customization/recipes.md +77 -0
  59. package/dist/docs/zh/customization/skins.md +2 -2
  60. package/dist/docs/zh/customization/themes.md +1 -1
  61. package/dist/docs/zh/features/agent-workflows.md +10 -10
  62. package/dist/docs/zh/features/browser-and-computer.md +40 -0
  63. package/dist/docs/zh/features/daily.md +13 -13
  64. package/dist/docs/zh/features/ecosystem.md +6 -6
  65. package/dist/docs/zh/features/extend.md +10 -9
  66. package/dist/docs/zh/features/freedom.md +9 -9
  67. package/dist/docs/zh/features/index.md +58 -28
  68. package/dist/docs/zh/features/long-work.md +17 -13
  69. package/dist/docs/zh/features/look.md +6 -6
  70. package/dist/docs/zh/features/people.md +5 -5
  71. package/dist/docs/zh/features/phone.md +13 -3
  72. package/dist/docs/zh/features/spaces.md +12 -12
  73. package/dist/docs/zh/features/workbench.md +8 -8
  74. package/dist/docs/zh/getting-started/desktop-app.md +4 -8
  75. package/dist/docs/zh/getting-started/first-launch.md +1 -1
  76. package/dist/docs/zh/guides/goals.md +4 -2
  77. package/dist/docs/zh/guides/interface.md +32 -10
  78. package/dist/docs/zh/guides/memory.md +64 -10
  79. package/dist/docs/zh/guides/sessions.md +21 -9
  80. package/dist/docs/zh/guides/settings.md +64 -40
  81. package/dist/docs/zh/index.md +4 -2
  82. package/dist/docs/zh/reference/command.md +90 -31
  83. package/dist/docs/zh/reference/model-vocabulary.md +2 -2
  84. package/dist/docs/zh/reference/slash-commands.md +1 -1
  85. package/dist/docs/zh/reference/tools.md +65 -20
  86. package/dist/docs/zh/server/acp.md +9 -3
  87. package/dist/docs/zh/server/local-server.md +19 -27
  88. package/dist/docs/zh/server/mcp.md +9 -5
  89. package/dist/docs/zh/server/rest-api.md +338 -21
  90. package/dist/docs/zh/server/script-tools.md +268 -0
  91. package/dist/external-harness/agy-cli-acp.mjs +168 -162
  92. package/dist/external-harness/agy-hook-registration.mjs +69 -30
  93. package/dist/external-harness/agy-mcp-plugin.mjs +19 -0
  94. package/dist/external-harness/agy-permission-hook.mjs +29 -2
  95. package/dist/hostRunner.mjs +112 -3
  96. package/dist/mailbox-worker.mjs +403 -0
  97. package/dist/main.mjs +2 -2
  98. package/dist/memory-worker.mjs +1008 -0
  99. package/dist/native/windows-process-helper.exe +0 -0
  100. package/dist/query-store-worker.mjs +487 -0
  101. package/dist/sqlite-indexer.mjs +255 -403
  102. package/dist/sqlite-query-worker.mjs +261 -249
  103. package/dist/usage-parser-worker.mjs +3977 -9
  104. package/dist/usage-read-model-worker.mjs +761 -0
  105. package/dist/web/assets/AppErrorBoundary-B5Fc4f6-.js +1 -0
  106. package/dist/web/assets/NavScopeBoundary-C7MnGQio.js +1 -0
  107. package/dist/web/assets/{arc-DYDCMlOS.js → arc-DGB9OVgQ.js} +1 -1
  108. package/dist/web/assets/{architectureDiagram-3BPJPVTR-C9Y7T0O2.js → architectureDiagram-3BPJPVTR-glnQCMub.js} +1 -1
  109. package/dist/web/assets/{blockDiagram-GPEHLZMM-CdUrp-tD.js → blockDiagram-GPEHLZMM-bM0tnGby.js} +1 -1
  110. package/dist/web/assets/{c4Diagram-AAUBKEIU-PrwvB9IJ.js → c4Diagram-AAUBKEIU-DMf_rTtt.js} +1 -1
  111. package/dist/web/assets/channel-Cj8SKJ38.js +1 -0
  112. package/dist/web/assets/{chunk-2J33WTMH-BL56g_Es.js → chunk-2J33WTMH-mTccJ3tW.js} +1 -1
  113. package/dist/web/assets/{chunk-4BX2VUAB-DvJD5M9M.js → chunk-4BX2VUAB-DhqPYMjY.js} +1 -1
  114. package/dist/web/assets/{chunk-55IACEB6-C8f-nzvx.js → chunk-55IACEB6-BujrYRoO.js} +1 -1
  115. package/dist/web/assets/{chunk-727SXJPM-DOGkWKkV.js → chunk-727SXJPM-ciMmSI4G.js} +1 -1
  116. package/dist/web/assets/{chunk-AQP2D5EJ-fFOuz7g6.js → chunk-AQP2D5EJ-CZW9pKTc.js} +1 -1
  117. package/dist/web/assets/{chunk-FMBD7UC4-BpeXZ9LM.js → chunk-FMBD7UC4-hdALNnnU.js} +1 -1
  118. package/dist/web/assets/{chunk-ND2GUHAM-CRUh76fb.js → chunk-ND2GUHAM-CgKyqUdb.js} +1 -1
  119. package/dist/web/assets/{chunk-QZHKN3VN-uNfxaPk0.js → chunk-QZHKN3VN-B2mmUz_E.js} +1 -1
  120. package/dist/web/assets/classDiagram-4FO5ZUOK-f8V9p-dD.js +1 -0
  121. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-f8V9p-dD.js +1 -0
  122. package/dist/web/assets/client-ClWQBErG.js +3 -0
  123. package/dist/web/assets/connection-C0J3BPgk.js +1 -0
  124. package/dist/web/assets/{cose-bilkent-S5V4N54A-BNkxG-qX.js → cose-bilkent-S5V4N54A-UV3uPjkK.js} +1 -1
  125. package/dist/web/assets/{dagre-BM42HDAG-BerioUei.js → dagre-BM42HDAG-Zjy-gQ6C.js} +1 -1
  126. package/dist/web/assets/{diagram-2AECGRRQ-Czv2SR07.js → diagram-2AECGRRQ-DL-kilIf.js} +1 -1
  127. package/dist/web/assets/{diagram-5GNKFQAL-Uzi1weGK.js → diagram-5GNKFQAL-CjB_xR5B.js} +1 -1
  128. package/dist/web/assets/{diagram-KO2AKTUF-W36h_ff3.js → diagram-KO2AKTUF-CjN4i3b9.js} +1 -1
  129. package/dist/web/assets/{diagram-LMA3HP47-FG4dDk52.js → diagram-LMA3HP47-CPCAMndo.js} +1 -1
  130. package/dist/web/assets/{diagram-OG6HWLK6-CQoEjIAY.js → diagram-OG6HWLK6-DVeBWBKd.js} +1 -1
  131. package/dist/web/assets/{erDiagram-TEJ5UH35-Ck06KVyZ.js → erDiagram-TEJ5UH35-CHKzBHrr.js} +1 -1
  132. package/dist/web/assets/export-CXoWon32.js +2 -0
  133. package/dist/web/assets/{flowDiagram-I6XJVG4X-C5hgxdFZ.js → flowDiagram-I6XJVG4X-C5rQa2pq.js} +1 -1
  134. package/dist/web/assets/{ganttDiagram-6RSMTGT7-BS52Pw5_.js → ganttDiagram-6RSMTGT7-BrLjEsNJ.js} +1 -1
  135. package/dist/web/assets/{gitGraphDiagram-PVQCEYII-DLlQKZHs.js → gitGraphDiagram-PVQCEYII-3DRR5VZj.js} +1 -1
  136. package/dist/web/assets/highlighted-body-OFNGDK62-Bdj5SJfv.js +1 -0
  137. package/dist/web/assets/index-2Vx5mHRn.js +1 -0
  138. package/dist/web/assets/index-B1UXw2C9.js +1 -0
  139. package/dist/web/assets/{index-CM-nNfuV.js → index-BJxtlf4P.js} +4 -4
  140. package/dist/web/assets/{index-DKIysLbI.js → index-BY7jPurv.js} +1 -1
  141. package/dist/web/assets/index-Bq79v-Sa.js +1 -0
  142. package/dist/web/assets/index-BqD3iTIl.js +1 -0
  143. package/dist/web/assets/index-Br3AlBrQ.js +1 -0
  144. package/dist/web/assets/{index-Ca607_hK.js → index-BvRBCpc6.js} +2 -2
  145. package/dist/web/assets/index-BxYCSNg_.js +3 -0
  146. package/dist/web/assets/{index-B2Pu0Iuu.js → index-C62wjCF_.js} +1 -1
  147. package/dist/web/assets/index-CBvwNH_H.js +1 -0
  148. package/dist/web/assets/{index-BNch_a4L.js → index-CG9e6lgq.js} +1 -1
  149. package/dist/web/assets/{index-ByiwExpV.js → index-CPSWYh_R.js} +2 -2
  150. package/dist/web/assets/index-CS4xJLZV.js +1 -0
  151. package/dist/web/assets/index-CjvqtF2I.js +1 -0
  152. package/dist/web/assets/index-CprdjRRk.js +13 -0
  153. package/dist/web/assets/{index-Bg99yVX_.js → index-CypTtrCB.js} +1 -1
  154. package/dist/web/assets/{index-BwcG86o3.js → index-DDJQGcUL.js} +1 -1
  155. package/dist/web/assets/index-DLWzxUOO.js +1 -0
  156. package/dist/web/assets/index-DQxkxZmn.js +7 -0
  157. package/dist/web/assets/index-DRo5Y_9p.js +1 -0
  158. package/dist/web/assets/index-De_LkTZx.js +1 -0
  159. package/dist/web/assets/{index-CZX3qUe2.js → index-DfUpwUTM.js} +2 -2
  160. package/dist/web/assets/{index-BLU8_Um7.js → index-Dkbz748K.js} +2 -2
  161. package/dist/web/assets/index-DmwFFSkV.js +1 -0
  162. package/dist/web/assets/index-DpcWEDhW.js +1 -0
  163. package/dist/web/assets/index-Dqq1RDP4.js +1 -0
  164. package/dist/web/assets/index-H1uMvIoa.css +1 -0
  165. package/dist/web/assets/index-ICHWJ2SM.js +1 -0
  166. package/dist/web/assets/index-O5fSd569.js +229 -0
  167. package/dist/web/assets/index-odjtqLLS.js +1 -0
  168. package/dist/web/assets/index-v_yAQ0Am.js +1 -0
  169. package/dist/web/assets/{infoDiagram-5YYISTIA-CD4XJGFm.js → infoDiagram-5YYISTIA-CCwV4Z0v.js} +1 -1
  170. package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-fu5E3_CT.js → ishikawaDiagram-YF4QCWOH-BwwZcGyZ.js} +1 -1
  171. package/dist/web/assets/{journeyDiagram-JHISSGLW-CXcnKBfJ.js → journeyDiagram-JHISSGLW-Dc6WqniQ.js} +1 -1
  172. package/dist/web/assets/{kanban-definition-UN3LZRKU-BawKH6Pl.js → kanban-definition-UN3LZRKU-DVUqULOS.js} +1 -1
  173. package/dist/web/assets/{linear-BplJuXph.js → linear-d6rWsNOU.js} +1 -1
  174. package/dist/web/assets/memoryAdvisor-DBQXJB1o.js +1 -0
  175. package/dist/web/assets/mermaid-GHXKKRXX-Ik6SkVDT.js +642 -0
  176. package/dist/web/assets/{mindmap-definition-RKZ34NQL-DA1SE2uy.js → mindmap-definition-RKZ34NQL-_JHAkhHL.js} +1 -1
  177. package/dist/web/assets/navViewState-DaCMIYWA.js +1 -0
  178. package/dist/web/assets/{pieDiagram-4H26LBE5-6i021QeX.js → pieDiagram-4H26LBE5-BlhlygGy.js} +1 -1
  179. package/dist/web/assets/{quadrantDiagram-W4KKPZXB-CcKSZDMT.js → quadrantDiagram-W4KKPZXB-jn6R_C0S.js} +1 -1
  180. package/dist/web/assets/{requirementDiagram-4Y6WPE33-lYVuWRuD.js → requirementDiagram-4Y6WPE33-B9fXCHBr.js} +1 -1
  181. package/dist/web/assets/{sankeyDiagram-5OEKKPKP-4Zfb4_h4.js → sankeyDiagram-5OEKKPKP-fPJwIxkl.js} +1 -1
  182. package/dist/web/assets/{sequenceDiagram-3UESZ5HK-DqltKmlY.js → sequenceDiagram-3UESZ5HK-1v1DTNGt.js} +1 -1
  183. package/dist/web/assets/{spaces-CjuXbmxF.js → spaces-CvL2DRZM.js} +1 -1
  184. package/dist/web/assets/{stateDiagram-AJRCARHV-HFdhqxzx.js → stateDiagram-AJRCARHV-CEc_PLov.js} +1 -1
  185. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-iAMctzaT.js +1 -0
  186. package/dist/web/assets/theme-LRSmy8mD.js +1 -0
  187. package/dist/web/assets/{timeline-definition-PNZ67QCA-HNRxaB3t.js → timeline-definition-PNZ67QCA-CEjhuitj.js} +1 -1
  188. package/dist/web/assets/{vennDiagram-CIIHVFJN-DwsCTyaD.js → vennDiagram-CIIHVFJN-CActt9h9.js} +1 -1
  189. package/dist/web/assets/{wardley-L42UT6IY-BWW2wtVO.js → wardley-L42UT6IY-Bp3q2izt.js} +1 -1
  190. package/dist/web/assets/{wardleyDiagram-YWT4CUSO-C-ktKm7v.js → wardleyDiagram-YWT4CUSO-C_zutiQ2.js} +1 -1
  191. package/dist/web/assets/{xychartDiagram-2RQKCTM6-48AxNW9k.js → xychartDiagram-2RQKCTM6-CRafvv33.js} +1 -1
  192. package/dist/web/icons/apple-touch-icon.png +0 -0
  193. package/dist/web/icons/icon-192.png +0 -0
  194. package/dist/web/icons/icon-512.png +0 -0
  195. package/dist/web/icons/maskable-512.png +0 -0
  196. package/dist/web/index.html +12 -2
  197. package/dist/web/manifest.webmanifest +16 -0
  198. package/native/auth-native/prebuilds/linux-arm64/auth-native.node +0 -0
  199. package/native/auth-native/prebuilds/linux-x64/auth-native.node +0 -0
  200. package/native/auth-native/prebuilds/win32-arm64/auth-native.node +0 -0
  201. package/native/auth-native/prebuilds/win32-x64/auth-native.node +0 -0
  202. package/package.json +23 -4
  203. package/dist/search-worker.mjs +0 -14177
  204. package/dist/web/assets/AppErrorBoundary-DiGMUg4r.js +0 -1
  205. package/dist/web/assets/LifeMark-CL6-HWDu.js +0 -1
  206. package/dist/web/assets/NavScopeBoundary-CFCnvZR0.js +0 -1
  207. package/dist/web/assets/channel-Bj_gZ_Lv.js +0 -1
  208. package/dist/web/assets/classDiagram-4FO5ZUOK-ssCwe2R4.js +0 -1
  209. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-ssCwe2R4.js +0 -1
  210. package/dist/web/assets/client-DGj93bGT.js +0 -3
  211. package/dist/web/assets/connection-Bpf-EjrL.js +0 -1
  212. package/dist/web/assets/export-T_izwEkQ.js +0 -2
  213. package/dist/web/assets/highlighted-body-OFNGDK62-Btm6MuZ4.js +0 -1
  214. package/dist/web/assets/index-5_yzg61S.js +0 -1
  215. package/dist/web/assets/index-B-6LiYTY.js +0 -1
  216. package/dist/web/assets/index-B4iu4SJW.js +0 -1
  217. package/dist/web/assets/index-B9MlqF7J.js +0 -1
  218. package/dist/web/assets/index-BECSk4If.js +0 -1
  219. package/dist/web/assets/index-BFcyN2Zw.js +0 -1
  220. package/dist/web/assets/index-BIebkSEI.css +0 -1
  221. package/dist/web/assets/index-BMWid2q9.js +0 -1
  222. package/dist/web/assets/index-BeMvPEXs.js +0 -1
  223. package/dist/web/assets/index-Bezli3SF.js +0 -1
  224. package/dist/web/assets/index-BkPV0psm.js +0 -1
  225. package/dist/web/assets/index-CG8uIlD7.js +0 -1
  226. package/dist/web/assets/index-CJ92kLtO.js +0 -1
  227. package/dist/web/assets/index-CRDDqofN.js +0 -1
  228. package/dist/web/assets/index-Cd62y0wD.js +0 -1
  229. package/dist/web/assets/index-CgcJPsK6.js +0 -3
  230. package/dist/web/assets/index-Cy8C_eFR.js +0 -7
  231. package/dist/web/assets/index-D8z7lcQn.js +0 -166
  232. package/dist/web/assets/index-D_oPSlBL.js +0 -1
  233. package/dist/web/assets/index-Dceu0bqY.js +0 -1
  234. package/dist/web/assets/index-eUyF-8Sq.js +0 -1
  235. package/dist/web/assets/index-hG2s2Spn.js +0 -13
  236. package/dist/web/assets/mermaid-GHXKKRXX-BO9hkP3Z.js +0 -621
  237. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-Dx28QuZF.js +0 -1
  238. package/dist/web/assets/theme-beWE_6f8.js +0 -1
@@ -5,10 +5,25 @@ import { statSync } from "node:fs";
5
5
  import { mkdir, open, readFile, readdir, stat } from "node:fs/promises";
6
6
  import { dirname, join, resolve } from "node:path";
7
7
  import { DatabaseSync } from "node:sqlite";
8
- import { execFile } from "node:child_process";
9
- import { promisify } from "node:util";
10
- import os from "node:os";
8
+ import { availableParallelism, totalmem } from "node:os";
9
+ import { getHeapStatistics } from "node:v8";
11
10
 
11
+ //#region ../../packages/kap-server/src/search/contract.ts
12
+ /**
13
+ * Service-level error with a machine-readable reason. Lives in the contract
14
+ * (not the service module) so the search-index core — which also runs inside
15
+ * the search worker thread — can raise it without importing the service.
16
+ */
17
+ var GlobalSearchError = class extends Error {
18
+ reason;
19
+ constructor(reason, message) {
20
+ super(message);
21
+ this.reason = reason;
22
+ this.name = "GlobalSearchError";
23
+ }
24
+ };
25
+
26
+ //#endregion
12
27
  //#region ../../packages/agent-core-v2/src/agent/media/mediaRef.ts
13
28
  const IMAGE_MIME_BY_SUFFIX = Object.freeze({
14
29
  ".png": "image/png",
@@ -84,56 +99,9 @@ function matchSingleMediaPathTag(text) {
84
99
  }
85
100
 
86
101
  //#endregion
87
- //#region ../../packages/minidb/src/codec.ts
88
- const MAGIC = Buffer.from([77, 68]);
89
- const EMPTY = Buffer.alloc(0);
90
-
91
- //#endregion
92
- //#region ../../packages/minidb/src/generation.ts
93
- /** The primary data pair recovery pairs up: the snapshot, then the WAL. */
94
- const SNAPSHOT_FILE = "db.snapshot";
95
- const WAL_FILE = "db.wal";
96
- /** Index-definition sidecars, rewritten atomically (tmp + rename) on every
97
- * definition change. */
98
- const SECONDARY_INDEXES_FILE = "db.indexes.json";
99
- const COMPOUND_INDEXES_FILE = "db.compound-indexes.json";
100
- const TEXT_INDEXES_FILE = "db.textindexes.json";
101
- const SIDECAR_FILES = [
102
- SECONDARY_INDEXES_FILE,
103
- COMPOUND_INDEXES_FILE,
104
- TEXT_INDEXES_FILE
105
- ];
106
- const CURRENT_FILE = "CURRENT";
107
- /** The files the cluster reader fingerprint MUST track: a change to any of
108
- * them means a cached read-only instance can no longer serve without a
109
- * refresh. The WAL comes first — the lock pool's "WAL-only append" fast path
110
- * compares every OTHER entry by position (see shardFingerprint). CURRENT is
111
- * tracked so a generation switch (compaction publish) refreshes readers even
112
- * though the snapshot entry already covers the rotation; both are kept
113
- * because a compaction with generation builds disabled rotates the snapshot
114
- * without touching CURRENT. */
115
- const FINGERPRINT_FILES = [
116
- WAL_FILE,
117
- SNAPSHOT_FILE,
118
- CURRENT_FILE,
119
- ...SIDECAR_FILES
120
- ];
121
- /** Atomic-write temp siblings a crashed previous run may have left behind:
122
- * a compaction's snapshot/WAL temps (fixed names), plus sidecar-definition
123
- * temps from before sidecar writes gained unique suffixes. Current sidecar
124
- * writes use `<file>.tmp-<pid>-<seq>` names, matched by isStaleTmpFile
125
- * instead. Only the sole writer may delete them at open — a read-only
126
- * opener must never touch a live writer's in-flight temps. */
127
- const STALE_TMP_FILES = [
128
- SNAPSHOT_FILE,
129
- WAL_FILE,
130
- ...SIDECAR_FILES
131
- ].map((f) => `${f}.tmp`);
132
-
133
- //#endregion
134
- //#region ../../packages/minidb/src/text-index/tokenize.ts
102
+ //#region ../../packages/lexical/src/index.ts
135
103
  const LATIN = /[a-z0-9]+/g;
136
- const CJK = /[\u3400-\u9fff\u3040-\u30ff\uff00-\uffef]+/g;
104
+ const CJK = /[\u3400-\u9FFF\u3040-\u30FF\uFF00-\uFFEF]+/g;
137
105
  const MAX_TERM_CHARS = 65535;
138
106
  /** Tokenize text into terms (lowercased latin words + CJK uni/bigrams). */
139
107
  function tokenize(str) {
@@ -150,110 +118,7 @@ function tokenize(str) {
150
118
  }
151
119
  return terms;
152
120
  }
153
-
154
- //#endregion
155
- //#region ../../packages/minidb/src/lockfile.ts
156
- const PROCESS_STARTED_AT = Math.floor(Date.now() - process.uptime() * 1e3);
157
- const execFileAsync = promisify(execFile);
158
-
159
- //#endregion
160
- //#region ../../packages/minidb/src/maintenance.ts
161
- var MaintenanceCancelledError = class extends Error {
162
- code = "MAINTENANCE_CANCELLED";
163
- constructor(kind) {
164
- super(`maintenance task ${kind} was cancelled`);
165
- this.name = "AbortError";
166
- }
167
- };
168
- /** Process-wide cap on concurrently spawned maintenance worker threads
169
- * (stage 6's CPU-worker budget). A worker build acquires a slot before
170
- * spawning and releases it when the worker exits; additional builds wait (or
171
- * the caller falls back to the in-thread path). */
172
- var WorkerSlots = class {
173
- total;
174
- available;
175
- waiters = [];
176
- constructor(total) {
177
- this.total = total;
178
- this.available = total;
179
- }
180
- /** Try to take a slot without waiting. */
181
- tryAcquire() {
182
- if (this.available <= 0) return null;
183
- this.available--;
184
- return () => this.release();
185
- }
186
- /** Wait for a slot (observing the optional abort signal). */
187
- async acquire(signal) {
188
- const immediate = this.tryAcquire();
189
- if (immediate) return immediate;
190
- if (signal?.aborted) throw new MaintenanceCancelledError("generation-build");
191
- return new Promise((resolve, reject) => {
192
- const onAbort = () => {
193
- const i = this.waiters.indexOf(grant);
194
- if (i >= 0) this.waiters.splice(i, 1);
195
- reject(new MaintenanceCancelledError("generation-build"));
196
- };
197
- const grant = () => {
198
- signal?.removeEventListener("abort", onAbort);
199
- resolve(() => this.release());
200
- };
201
- signal?.addEventListener("abort", onAbort, { once: true });
202
- this.waiters.push(grant);
203
- });
204
- }
205
- /** TUI-safe slot policy: queue for a slot up to `waitMs` (observing the
206
- * optional abort signal) instead of dropping a large worker-eligible
207
- * build onto the main thread the moment every slot is busy. Resolves null
208
- * on timeout — the caller decides whether its bounded inline core is an
209
- * acceptable last resort. Rejects MaintenanceCancelledError on abort. */
210
- async acquireBounded(waitMs, signal) {
211
- const immediate = this.tryAcquire();
212
- if (immediate) return immediate;
213
- if (signal?.aborted) throw new MaintenanceCancelledError("generation-build");
214
- return new Promise((resolve, reject) => {
215
- const cleanup = () => {
216
- clearTimeout(timer);
217
- signal?.removeEventListener("abort", onAbort);
218
- const i = this.waiters.indexOf(grant);
219
- if (i >= 0) this.waiters.splice(i, 1);
220
- };
221
- const timer = setTimeout(() => {
222
- cleanup();
223
- resolve(null);
224
- }, waitMs);
225
- timer.unref?.();
226
- const onAbort = () => {
227
- cleanup();
228
- reject(new MaintenanceCancelledError("generation-build"));
229
- };
230
- const grant = () => {
231
- cleanup();
232
- resolve(() => this.release());
233
- };
234
- signal?.addEventListener("abort", onAbort, { once: true });
235
- this.waiters.push(grant);
236
- });
237
- }
238
- release() {
239
- const next = this.waiters.shift();
240
- if (next) {
241
- next();
242
- return;
243
- }
244
- this.available++;
245
- }
246
- };
247
- /** The process-wide default worker slot pool: half the CPUs, at least one,
248
- * capped at two — one worker build already saturates a core for seconds,
249
- * and the main thread must stay responsive. */
250
- const defaultWorkerSlots = new WorkerSlots(Math.max(1, Math.min(2, Math.floor(os.cpus().length / 2))));
251
-
252
- //#endregion
253
- //#region ../../packages/minidb/src/trigram.ts
254
- /** Normalize text for literal matching: Unicode NFKC (fullwidth `$` -> `$`,
255
- * compatibility glyphs folded) + lowercase. The search layer's confirmation
256
- * step must use this exact function so index and comparison agree. */
121
+ /** Normalize text for literal matching with Unicode NFKC and lowercase. */
257
122
  function normalizeLiteral(text) {
258
123
  return text.normalize("NFKC").toLowerCase();
259
124
  }
@@ -262,22 +127,6 @@ function normalizeLiteral(text) {
262
127
  //#region ../../packages/kap-server/src/search/docs.ts
263
128
  const MAX_DOC_TEXT_CHARS = 2e4;
264
129
 
265
- //#endregion
266
- //#region ../../packages/kap-server/src/search/contract.ts
267
- /**
268
- * Service-level error with a machine-readable reason. Lives in the contract
269
- * (not the service module) so the search-index core — which also runs inside
270
- * the search worker thread — can raise it without importing the service.
271
- */
272
- var GlobalSearchError = class extends Error {
273
- reason;
274
- constructor(reason, message) {
275
- super(message);
276
- this.reason = reason;
277
- this.name = "GlobalSearchError";
278
- }
279
- };
280
-
281
130
  //#endregion
282
131
  //#region ../../packages/kap-server/src/services/history/historyQuery.ts
283
132
  function clausePosition(text, clause, literal) {
@@ -804,7 +653,7 @@ function analyzeWireLine(line) {
804
653
  //#region ../../packages/kap-server/src/search/sqlite/schema.ts
805
654
  /** Schema guard adapted from dsh-core/packages/session-query/session-query-sqlite/src/schema.ts (MIT). */
806
655
  const APPLICATION_ID = 1263749464;
807
- const SCHEMA_VERSION = 1;
656
+ const SCHEMA_VERSION = 2;
808
657
  const DERIVED_TABLES = new Set([
809
658
  "sessions",
810
659
  "files",
@@ -846,7 +695,7 @@ async function openSearchDatabase(path) {
846
695
  if (applicationId === 1263749464) {
847
696
  const unknown = tables.filter((name) => !DERIVED_TABLES.has(name));
848
697
  if (unknown.length) throw new Error(`search database at "${actual}" has unrecognized user tables: ${unknown.join(", ")}`);
849
- if (version !== 1) {
698
+ if (version !== 2) {
850
699
  for (const name of [
851
700
  "docs_tri",
852
701
  "docs_terms",
@@ -882,7 +731,7 @@ async function openSearchDatabase(path) {
882
731
  CREATE TABLE IF NOT EXISTS file_failures (path TEXT PRIMARY KEY, strikes INTEGER NOT NULL,
883
732
  error TEXT NOT NULL) STRICT;
884
733
  `);
885
- db.exec(`PRAGMA application_id=${APPLICATION_ID}; PRAGMA user_version=${1}`);
734
+ db.exec(`PRAGMA application_id=${APPLICATION_ID}; PRAGMA user_version=${2}`);
886
735
  db.prepare("INSERT OR IGNORE INTO meta(k,v) VALUES('generation','0')").run();
887
736
  const extractor = db.prepare("SELECT v FROM meta WHERE k='extractor_version'").get();
888
737
  if (extractor && extractor.v !== "3") {
@@ -904,6 +753,51 @@ async function openSearchDatabase(path) {
904
753
  }
905
754
  }
906
755
 
756
+ //#endregion
757
+ //#region ../../packages/kap-server/src/search/sqlite/queryBudget.ts
758
+ const DEFAULT_SEARCH_BUDGETS = {
759
+ literalCandidateCap: 1e4,
760
+ maxTextHits: 1e5,
761
+ postingsVisitBudget: 25e4,
762
+ queryDeadlineMs: 500,
763
+ queryTextBudgetChars: 16e6
764
+ };
765
+ function queryBudget(budgets, deadlineAt = Date.now() + budgets.queryDeadlineMs) {
766
+ return {
767
+ deadlineAt,
768
+ textCharsLeft: budgets.queryTextBudgetChars,
769
+ candidatesLeft: Math.max(budgets.literalCandidateCap, budgets.maxTextHits)
770
+ };
771
+ }
772
+ async function beforeDeadline(work, deadlineAt) {
773
+ const remaining = deadlineAt - Date.now();
774
+ if (remaining <= 0) {
775
+ work.catch(() => {});
776
+ return;
777
+ }
778
+ let timer;
779
+ try {
780
+ return await Promise.race([work, new Promise((resolve) => {
781
+ timer = setTimeout(() => resolve(void 0), remaining);
782
+ })]);
783
+ } finally {
784
+ if (timer) clearTimeout(timer);
785
+ }
786
+ }
787
+
788
+ //#endregion
789
+ //#region ../../packages/kap-server/src/search/sqlite/terms.ts
790
+ function encodeTerm(term) {
791
+ return [
792
+ "b",
793
+ ...Buffer.from(term, "utf8").toString("hex").match(/.{1,128}/g).map((chunk) => `x${chunk}`),
794
+ "e"
795
+ ].join(" ");
796
+ }
797
+ function encodeTerms(text) {
798
+ return tokenize(text).map(encodeTerm).join(" ");
799
+ }
800
+
907
801
  //#endregion
908
802
  //#region ../../packages/kap-server/src/search/sqlite/index.ts
909
803
  const CHUNK = 1 << 20;
@@ -1031,11 +925,11 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1031
925
  throw error;
1032
926
  }
1033
927
  }
1034
- static openReader(path, bootSalt) {
928
+ static openReader(path, bootSalt, options = {}) {
1035
929
  const db = new DatabaseSync(path, { readOnly: true });
1036
930
  try {
1037
931
  db.exec("PRAGMA query_only=ON; PRAGMA cache_size=-16384; PRAGMA mmap_size=0; PRAGMA busy_timeout=1000");
1038
- return new SqliteSearchIndex(db, false, path, {}, true, bootSalt);
932
+ return new SqliteSearchIndex(db, false, path, options, true, bootSalt);
1039
933
  } catch (error) {
1040
934
  db.close();
1041
935
  throw error;
@@ -1150,14 +1044,14 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1150
1044
  const db = this.db;
1151
1045
  const info = db.prepare("INSERT INTO docs(file_id,session_id,line_offset,ord,role,time,turn,step_id,text) VALUES(?,?,?,?,?,?,?,?,?)").run(fileId, sessionId, lineOffset, ord, role, time, turn ?? null, stepId ?? null, text);
1152
1046
  const id = Number(info.lastInsertRowid);
1153
- db.prepare("INSERT INTO docs_terms(rowid,terms) VALUES(?,?)").run(id, tokenize(text).join(" "));
1047
+ db.prepare("INSERT INTO docs_terms(rowid,terms) VALUES(?,?)").run(id, encodeTerms(text));
1154
1048
  db.prepare("INSERT INTO docs_tri(rowid,text) VALUES(?,?)").run(id, normalizeLiteral(text));
1155
1049
  }
1156
1050
  deleteDocs(where, key) {
1157
1051
  const db = this.db;
1158
1052
  const rows = db.prepare(`SELECT id,text FROM docs WHERE ${where}=?`).iterate(key);
1159
1053
  for (const row of rows) {
1160
- db.prepare("INSERT INTO docs_terms(docs_terms,rowid,terms) VALUES('delete',?,?)").run(row.id, tokenize(row.text).join(" "));
1054
+ db.prepare("INSERT INTO docs_terms(docs_terms,rowid,terms) VALUES('delete',?,?)").run(row.id, encodeTerms(row.text));
1161
1055
  db.prepare("INSERT INTO docs_tri(docs_tri,rowid,text) VALUES('delete',?,?)").run(row.id, normalizeLiteral(row.text));
1162
1056
  db.prepare("DELETE FROM docs WHERE id=?").run(row.id);
1163
1057
  }
@@ -1175,6 +1069,55 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1175
1069
  await fd.close();
1176
1070
  }
1177
1071
  }
1072
+ reconcileSessions(current) {
1073
+ const task = this.syncQueue.catch(() => {}).then(async () => {
1074
+ for (const id of this.pendingSessions.keys()) if (!current.has(id)) this.pendingSessions.delete(id);
1075
+ let after = "";
1076
+ while (!this.closed && !this.options.isStopped?.()) {
1077
+ const batch = this.db.prepare("SELECT id FROM sessions WHERE id>? ORDER BY id LIMIT 100").all(after);
1078
+ if (!batch.length) return true;
1079
+ for (const { id } of batch) {
1080
+ if (!current.has(id) && !await this.removeSession(id)) return false;
1081
+ after = id;
1082
+ }
1083
+ await new Promise((resolve) => setImmediate(resolve));
1084
+ }
1085
+ return false;
1086
+ });
1087
+ this.syncQueue = task;
1088
+ return task;
1089
+ }
1090
+ async removeSession(id) {
1091
+ const db = this.db;
1092
+ while (!this.closed && !this.options.isStopped?.()) {
1093
+ if (this.walStuck) return false;
1094
+ const docs = db.prepare("SELECT id FROM docs WHERE session_id=? LIMIT 128").all(id);
1095
+ const file = docs.length ? void 0 : db.prepare("SELECT id,path FROM files WHERE session_id=? LIMIT 1").get(id);
1096
+ db.exec("BEGIN");
1097
+ try {
1098
+ for (const doc of docs) this.deleteDocs("id", doc.id);
1099
+ if (file) {
1100
+ db.prepare("DELETE FROM turn_openers WHERE file_id=? AND idx IN (SELECT idx FROM turn_openers WHERE file_id=? LIMIT 256)").run(file.id, file.id);
1101
+ if (!db.prepare("SELECT 1 FROM turn_openers WHERE file_id=? LIMIT 1").get(file.id)) {
1102
+ db.prepare("DELETE FROM file_failures WHERE path=?").run(file.path);
1103
+ db.prepare("DELETE FROM files WHERE id=?").run(file.id);
1104
+ }
1105
+ } else if (!docs.length) db.prepare("DELETE FROM sessions WHERE id=?").run(id);
1106
+ this.bumpGeneration();
1107
+ db.exec("COMMIT");
1108
+ } catch (error) {
1109
+ db.exec("ROLLBACK");
1110
+ throw error;
1111
+ }
1112
+ this.afterCommit();
1113
+ if (!docs.length && !file) {
1114
+ this.pendingSessions.delete(id);
1115
+ return true;
1116
+ }
1117
+ await new Promise((resolve) => setImmediate(resolve));
1118
+ }
1119
+ return false;
1120
+ }
1178
1121
  syncSession(session) {
1179
1122
  const task = this.syncQueue.catch(() => {}).then(() => this.syncSessionInner(session));
1180
1123
  this.syncQueue = task;
@@ -1188,7 +1131,10 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1188
1131
  return;
1189
1132
  }
1190
1133
  const id = await identity(session.dir);
1191
- if (id === void 0) return;
1134
+ if (id === void 0) {
1135
+ await this.removeSession(session.id);
1136
+ return;
1137
+ }
1192
1138
  const db = this.db;
1193
1139
  const title = await titleAt(session.dir);
1194
1140
  const existing = db.prepare("SELECT title,identity,dir FROM sessions WHERE id=?").get(session.id);
@@ -1282,7 +1228,7 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1282
1228
  }
1283
1229
  if (file?.policy === "quarantined") return;
1284
1230
  const changed = file && (st.size !== file.size || st.mtimeMs !== file.mtime_ms || file.ino !== String(st.ino));
1285
- const replace = file && (st.size < file.offset || file.policy !== policy || changed && file.offset > 0 && (file.ino !== String(st.ino) || file.tail_hash !== await this.tailHash(path, file.offset)));
1231
+ const replace = file && (st.size < file.offset || file.policy !== policy || changed && file.offset > 0 && (file.ino !== String(st.ino) || st.size === file.size && st.mtimeMs !== file.mtime_ms || file.tail_hash !== await this.tailHash(path, file.offset)));
1286
1232
  if (!replace && file?.offset === st.size) {
1287
1233
  if (changed) db.prepare("UPDATE files SET size=?,mtime_ms=? WHERE id=?").run(st.size, st.mtimeMs, file.id);
1288
1234
  return;
@@ -1429,17 +1375,21 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1429
1375
  await fd.close();
1430
1376
  }
1431
1377
  }
1432
- async search(q, pageToken, budgets = {
1433
- literalCandidateCap: 1e4,
1434
- maxTextHits: 1e5,
1435
- postingsVisitBudget: 25e4,
1436
- queryDeadlineMs: 500,
1437
- queryTextBudgetChars: 16e6
1438
- }) {
1378
+ async search(q, pageToken, budgets = DEFAULT_SEARCH_BUDGETS, budget = queryBudget(budgets)) {
1439
1379
  const db = this.db;
1440
1380
  const generation = this.generation;
1441
1381
  const page = decodePageToken(q, "index", pageToken, generation);
1442
- const deadlineAt = Date.now() + budgets.queryDeadlineMs;
1382
+ const { deadlineAt } = budget;
1383
+ if (Date.now() >= deadlineAt || budget.textCharsLeft < 0) return {
1384
+ rows: [],
1385
+ hasMore: false,
1386
+ incomplete: "deadline"
1387
+ };
1388
+ budgets = {
1389
+ ...budgets,
1390
+ maxTextHits: Math.min(budgets.maxTextHits, budget.candidatesLeft),
1391
+ literalCandidateCap: Math.min(budgets.literalCandidateCap, budget.candidatesLeft)
1392
+ };
1443
1393
  let incomplete;
1444
1394
  const terms = q.termsQuery ?? [...new Set(tokenize(q.query))];
1445
1395
  const literal = q.literalQuery ?? normalizeLiteral(q.query);
@@ -1478,7 +1428,7 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1478
1428
  const scopedWhere = filters.length ? ` AND ${filters.join(" AND ")}` : "";
1479
1429
  if (q.mode === "terms") if (!terms.length) matchedIds = [];
1480
1430
  else {
1481
- const expression = terms.map(quoteTerm).join(q.op === "OR" ? " OR " : " AND ");
1431
+ const expression = terms.map((term) => quoteTerm(encodeTerm(term))).join(q.op === "OR" ? " OR " : " AND ");
1482
1432
  if (ranked) matchedIds = db.prepare(`SELECT docs_terms.rowid, docs_terms.rank FROM docs_terms
1483
1433
  ${scopedWhere ? "JOIN docs d ON d.id=docs_terms.rowid" : ""}
1484
1434
  WHERE docs_terms MATCH ?${scopedWhere} ORDER BY rank LIMIT ?`).all(expression, Math.min(budgets.maxTextHits, 64) + 1);
@@ -1495,20 +1445,21 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1495
1445
  else if (Array.from(literal).length >= 3) matchedIds = db.prepare(`SELECT docs_tri.rowid FROM docs_tri ${joins("docs_tri")}
1496
1446
  WHERE docs_tri MATCH ?${scopedWhere} LIMIT ?`).all(quoteTerm(literal), ...filterValues, budgets.literalCandidateCap + 1);
1497
1447
  else matchedIds = /^[\u3400-\u9fff\u3040-\u30ff\uff00-\uffef]{2}$/.test(literal) ? db.prepare(`SELECT docs_terms.rowid FROM docs_terms ${joins("docs_terms")}
1498
- WHERE docs_terms MATCH ?${scopedWhere} LIMIT ?`).all(quoteTerm(literal), ...filterValues, budgets.literalCandidateCap + 1) : db.prepare(`SELECT d.id AS rowid FROM docs d JOIN sessions s ON s.id=d.session_id
1448
+ WHERE docs_terms MATCH ?${scopedWhere} LIMIT ?`).all(quoteTerm(encodeTerm(literal)), ...filterValues, budgets.literalCandidateCap + 1) : db.prepare(`SELECT d.id AS rowid FROM docs d JOIN sessions s ON s.id=d.session_id
1499
1449
  LEFT JOIN files f ON f.id=d.file_id WHERE 1=1${scopedWhere} LIMIT ?`).all(...filterValues, budgets.literalCandidateCap + 1);
1500
1450
  const cap = ranked ? Math.min(budgets.maxTextHits, 64) : q.mode === "terms" ? budgets.maxTextHits : budgets.literalCandidateCap;
1501
1451
  if (matchedIds.length > cap) {
1502
1452
  matchedIds.length = cap;
1503
1453
  incomplete = "candidate_cap";
1504
1454
  }
1455
+ budget.candidatesLeft -= matchedIds.length;
1505
1456
  const rows = [];
1506
1457
  const N = q.mode === "terms" && !ranked ? db.prepare(`SELECT count(*) AS n FROM docs d
1507
1458
  JOIN sessions s ON s.id=d.session_id LEFT JOIN files f ON f.id=d.file_id
1508
1459
  WHERE 1=1${scopedWhere}`).get(...filterValues).n : 0;
1509
1460
  const dfs = /* @__PURE__ */ new Map();
1510
1461
  if (q.mode === "terms" && !ranked) for (const term of terms) dfs.set(term, db.prepare(`SELECT count(*) AS n FROM docs_terms ${joins("docs_terms")}
1511
- WHERE docs_terms MATCH ?${scopedWhere}`).get(quoteTerm(term), ...filterValues).n);
1462
+ WHERE docs_terms MATCH ?${scopedWhere}`).get(quoteTerm(encodeTerm(term)), ...filterValues).n);
1512
1463
  const candidate = db.prepare("SELECT d.*,s.workspace_id,s.title,s.identity,s.dir,f.agent_id,f.path FROM docs d JOIN sessions s ON s.id=d.session_id LEFT JOIN files f ON f.id=d.file_id WHERE d.id=?");
1513
1464
  for (const { rowid, rank } of matchedIds) {
1514
1465
  if (Date.now() > deadlineAt - 25) {
@@ -1552,45 +1503,18 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1552
1503
  score
1553
1504
  });
1554
1505
  }
1555
- const budget = {
1556
- deadlineAt,
1557
- textCharsLeft: budgets.queryTextBudgetChars
1558
- };
1559
1506
  const matched = matchDocs(q, rows, page.kind === "keyset" ? page.boundary : void 0, budget);
1560
1507
  incomplete ??= matched.incomplete;
1561
1508
  const valid = [];
1562
1509
  const identities = /* @__PURE__ */ new Map();
1563
- const sourceQuery = db.prepare("SELECT dir,identity FROM sessions WHERE id=?");
1564
- const sources = /* @__PURE__ */ new Map();
1565
1510
  for (let offset = 0; offset < matched.rows.length; offset += 16) {
1566
- if (Date.now() > deadlineAt) {
1567
- incomplete ??= "deadline";
1511
+ const batch = matched.rows.slice(offset, offset + 16);
1512
+ const verified = await this.verifySources(batch, budget, identities);
1513
+ if (verified === void 0) {
1514
+ incomplete = "deadline";
1568
1515
  break;
1569
1516
  }
1570
- const batch = matched.rows.slice(offset, offset + 16).map((row) => {
1571
- if (!sources.has(row.value.sessionId)) sources.set(row.value.sessionId, sourceQuery.get(row.value.sessionId));
1572
- return {
1573
- row,
1574
- source: sources.get(row.value.sessionId)
1575
- };
1576
- });
1577
- const verified = await Promise.all(batch.map(async ({ row, source }) => {
1578
- if (!source || source.identity !== row.value.sessionIdentity) return false;
1579
- let check = identities.get(source.dir);
1580
- if (!check) {
1581
- check = identity(source.dir);
1582
- identities.set(source.dir, check);
1583
- }
1584
- return await check === source.identity;
1585
- }));
1586
- for (let i = 0; i < batch.length; i++) {
1587
- if (Date.now() > deadlineAt) {
1588
- incomplete ??= "deadline";
1589
- break;
1590
- }
1591
- if (verified[i]) valid.push(batch[i].row);
1592
- }
1593
- if (incomplete === "deadline") break;
1517
+ for (let i = 0; i < batch.length; i++) if (verified[i]) valid.push(batch[i]);
1594
1518
  }
1595
1519
  const { pageRows, hasMore } = paginateRows(q, page, valid);
1596
1520
  return {
@@ -1600,15 +1524,123 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1600
1524
  pageToken: hasMore ? encodePageToken(q, "index", boundaryOf(q, pageRows[pageRows.length - 1]), generation) : void 0
1601
1525
  };
1602
1526
  }
1527
+ async verifySources(rows, budget, identities) {
1528
+ if (Date.now() >= budget.deadlineAt) return void 0;
1529
+ const sources = this.db.prepare("SELECT dir,identity FROM sessions WHERE id=?");
1530
+ const checks = rows.map((row) => {
1531
+ const source = sources.get(row.value.sessionId);
1532
+ if (!source || source.identity !== row.value.sessionIdentity) return Promise.resolve(false);
1533
+ let check = identities.get(source.dir);
1534
+ if (!check) {
1535
+ check = (this.options.sourceIdentity ?? identity)(source.dir);
1536
+ identities.set(source.dir, check);
1537
+ }
1538
+ return check.then((current) => current === source.identity);
1539
+ });
1540
+ return beforeDeadline(Promise.all(checks), budget.deadlineAt);
1541
+ }
1542
+ async sourcesCurrent(rows, budget) {
1543
+ const identities = /* @__PURE__ */ new Map();
1544
+ for (let offset = 0; offset < rows.length; offset += 16) {
1545
+ const verified = await this.verifySources(rows.slice(offset, offset + 16), budget, identities);
1546
+ if (verified === void 0) return void 0;
1547
+ if (!verified.every(Boolean)) return false;
1548
+ }
1549
+ return true;
1550
+ }
1551
+ };
1552
+
1553
+ //#endregion
1554
+ //#region ../../packages/kap-server/src/search/sqlite/queries.ts
1555
+ const deadlineResult = () => ({
1556
+ rows: [],
1557
+ hasMore: false,
1558
+ incomplete: "deadline"
1559
+ });
1560
+ var SqliteSearchQueries = class {
1561
+ reader;
1562
+ cacheMs;
1563
+ recent = /* @__PURE__ */ new Map();
1564
+ constructor(reader, cacheMs = 500) {
1565
+ this.reader = reader;
1566
+ this.cacheMs = cacheMs;
1567
+ }
1568
+ async search(query, pageToken, budgets = DEFAULT_SEARCH_BUDGETS, deadlineAt = Date.now() + budgets.queryDeadlineMs) {
1569
+ const budget = queryBudget(budgets, deadlineAt);
1570
+ if (Date.now() >= deadlineAt) return deadlineResult();
1571
+ const key = this.cacheMs ? JSON.stringify([
1572
+ query,
1573
+ pageToken,
1574
+ budgets
1575
+ ]) : "";
1576
+ const version = this.cacheMs ? this.reader.db.prepare("PRAGMA data_version").get().data_version : 0;
1577
+ const cached = this.cacheMs ? this.recent.get(key) : void 0;
1578
+ if (cached && cached.expires >= Date.now() && cached.version === version) {
1579
+ const value = await beforeDeadline(cached.result, deadlineAt);
1580
+ if (value === void 0) return deadlineResult();
1581
+ const current = await this.reader.sourcesCurrent(value.rows, budget);
1582
+ if (current === true) return value;
1583
+ if (this.recent.get(key) === cached) this.recent.delete(key);
1584
+ if (current === void 0) return deadlineResult();
1585
+ return this.reader.search(query, pageToken, budgets, budget);
1586
+ }
1587
+ if (this.cacheMs && this.recent.size >= 16) this.recent.delete(this.recent.keys().next().value);
1588
+ const result = this.reader.search(query, pageToken, budgets, budget);
1589
+ if (this.cacheMs) {
1590
+ const entry = {
1591
+ expires: Date.now() + this.cacheMs,
1592
+ version,
1593
+ result
1594
+ };
1595
+ this.recent.set(key, entry);
1596
+ result.catch(() => {
1597
+ if (this.recent.get(key) === entry) this.recent.delete(key);
1598
+ });
1599
+ }
1600
+ return result;
1601
+ }
1603
1602
  };
1604
1603
 
1604
+ //#endregion
1605
+ //#region ../../packages/agent-core-v2/src/_base/node/resourceDefaults.ts
1606
+ function resourceDefaults(hardware = {
1607
+ parallelism: availableParallelism(),
1608
+ memoryBytes: totalmem()
1609
+ }) {
1610
+ const memoryMiB = Math.floor(hardware.memoryBytes / 1024 / 1024);
1611
+ const spareCpus = Math.max(1, hardware.parallelism - 1);
1612
+ const workerHeapMb = Math.max(512, Math.floor(memoryMiB / 64));
1613
+ const cpuWorkers = Math.max(1, Math.min(spareCpus, Math.floor(memoryMiB / 4 / workerHeapMb)));
1614
+ return {
1615
+ workerHeapMb,
1616
+ searchIndexerSoftMb: workerHeapMb * 2 + 256,
1617
+ searchIndexerHardMb: workerHeapMb * 3 + 256,
1618
+ cpuWorkers,
1619
+ workerQueue: Math.max(128, hardware.parallelism * 16),
1620
+ cpuQueue: Math.max(128, cpuWorkers * 16),
1621
+ cpuQueuedBytes: Math.max(64, Math.floor(memoryMiB / 128)) * 1024 * 1024,
1622
+ liveSessions: Math.max(16, Math.floor(memoryMiB / 128)),
1623
+ queuedRestores: Math.max(128, hardware.parallelism * 16),
1624
+ residentHeapBytes: Math.max(256, Math.floor(memoryMiB / 8)) * 1024 * 1024
1625
+ };
1626
+ }
1627
+ const RESOURCE_DEFAULTS = resourceDefaults();
1628
+
1629
+ //#endregion
1630
+ //#region ../../packages/agent-core-v2/src/_base/node/workerHeapPolicy.ts
1631
+ function warnIfWorkerHeapLimit(expectedMb) {
1632
+ const observedMb = getHeapStatistics().heap_size_limit / 1024 / 1024;
1633
+ if (observedMb < expectedMb * .9 || observedMb > expectedMb + 256) process.emitWarning(`Worker heap limit is ${Math.round(observedMb)} MiB; expected ${expectedMb} MiB old-space plus at most 256 MiB young/code space. Check inherited Node heap flags.`, { code: "KIKI_WORKER_HEAP_LIMIT" });
1634
+ }
1635
+
1605
1636
  //#endregion
1606
1637
  //#region ../../packages/kap-server/src/search/sqlite/queryEntry.ts
1638
+ warnIfWorkerHeapLimit(RESOURCE_DEFAULTS.workerHeapMb);
1607
1639
  const port = parentPort;
1608
1640
  if (!port) throw new Error("query entry requires a worker thread");
1609
1641
  let reader;
1642
+ let queries;
1610
1643
  const source = typeof workerData === "string" ? { database: workerData } : workerData;
1611
- const recent = /* @__PURE__ */ new Map();
1612
1644
  const cacheMs = process.env["KIKI_SEARCH_QUERY_CACHE_MS"] === "0" ? 0 : 500;
1613
1645
  const send = (event) => port.postMessage(event);
1614
1646
  send({ type: "ready" });
@@ -1626,29 +1658,8 @@ const handleMessage = async (message) => {
1626
1658
  await setTimeout$1(50 * (attempt + 1));
1627
1659
  }
1628
1660
  if (!reader) throw new Error("search database reader did not open");
1629
- const key = cacheMs ? JSON.stringify([
1630
- message.query,
1631
- message.pageToken,
1632
- message.budgets
1633
- ]) : "";
1634
- const version = cacheMs ? reader.db.prepare("PRAGMA data_version").get().data_version : 0;
1635
- let entry = cacheMs ? recent.get(key) : void 0;
1636
- if (!entry || entry.expires < Date.now() || entry.version !== version) {
1637
- if (cacheMs && recent.size >= 16) recent.delete(recent.keys().next().value);
1638
- const result = reader.search(message.query, message.pageToken, message.budgets);
1639
- entry = {
1640
- expires: Date.now() + cacheMs,
1641
- version,
1642
- result
1643
- };
1644
- if (cacheMs) {
1645
- recent.set(key, entry);
1646
- result.catch(() => {
1647
- if (recent.get(key) === entry) recent.delete(key);
1648
- });
1649
- }
1650
- }
1651
- const value = await entry.result;
1661
+ queries ??= new SqliteSearchQueries(reader, cacheMs);
1662
+ const value = await queries.search(message.query, message.pageToken, message.budgets, message.deadlineAt);
1652
1663
  send({
1653
1664
  id: message.id,
1654
1665
  type: "result",
@@ -1658,7 +1669,8 @@ const handleMessage = async (message) => {
1658
1669
  send({
1659
1670
  id: message.id,
1660
1671
  type: "error",
1661
- message: error instanceof Error ? error.message : String(error)
1672
+ message: error instanceof Error ? error.message : String(error),
1673
+ reason: error instanceof GlobalSearchError ? error.reason : void 0
1662
1674
  });
1663
1675
  }
1664
1676
  };