kiki-agent 0.4.2 → 0.5.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 (171) hide show
  1. package/dist/docs/en/configuration/config-files.md +32 -19
  2. package/dist/docs/en/configuration/data-locations.md +23 -1
  3. package/dist/docs/en/configuration/env-vars.md +6 -8
  4. package/dist/docs/en/configuration/overrides.md +19 -8
  5. package/dist/docs/en/configuration/providers.md +75 -4
  6. package/dist/docs/en/customization/agents-and-subagents.md +6 -2
  7. package/dist/docs/en/customization/personas.md +36 -2
  8. package/dist/docs/en/customization/plugins.md +41 -1
  9. package/dist/docs/en/customization/prompt-fields.md +4 -0
  10. package/dist/docs/en/features/agent-workflows.md +8 -8
  11. package/dist/docs/en/features/browser-and-computer.md +40 -0
  12. package/dist/docs/en/features/daily.md +10 -10
  13. package/dist/docs/en/features/ecosystem.md +5 -5
  14. package/dist/docs/en/features/extend.md +9 -8
  15. package/dist/docs/en/features/freedom.md +8 -8
  16. package/dist/docs/en/features/index.md +44 -28
  17. package/dist/docs/en/features/long-work.md +9 -9
  18. package/dist/docs/en/features/look.md +5 -5
  19. package/dist/docs/en/features/people.md +6 -6
  20. package/dist/docs/en/features/phone.md +5 -3
  21. package/dist/docs/en/features/spaces.md +7 -7
  22. package/dist/docs/en/features/workbench.md +8 -8
  23. package/dist/docs/en/guides/interface.md +16 -4
  24. package/dist/docs/en/guides/sessions.md +6 -2
  25. package/dist/docs/en/guides/settings.md +15 -2
  26. package/dist/docs/en/reference/command.md +58 -1
  27. package/dist/docs/en/reference/tools.md +25 -5
  28. package/dist/docs/en/server/acp.md +3 -1
  29. package/dist/docs/en/server/mcp.md +5 -1
  30. package/dist/docs/en/server/rest-api.md +115 -4
  31. package/dist/docs/zh/configuration/config-files.md +32 -19
  32. package/dist/docs/zh/configuration/data-locations.md +23 -1
  33. package/dist/docs/zh/configuration/env-vars.md +6 -8
  34. package/dist/docs/zh/configuration/overrides.md +19 -8
  35. package/dist/docs/zh/configuration/providers.md +75 -4
  36. package/dist/docs/zh/customization/agents-and-subagents.md +6 -2
  37. package/dist/docs/zh/customization/personas.md +36 -2
  38. package/dist/docs/zh/customization/plugins.md +41 -1
  39. package/dist/docs/zh/customization/prompt-fields.md +4 -0
  40. package/dist/docs/zh/features/agent-workflows.md +10 -10
  41. package/dist/docs/zh/features/browser-and-computer.md +40 -0
  42. package/dist/docs/zh/features/daily.md +10 -10
  43. package/dist/docs/zh/features/ecosystem.md +5 -5
  44. package/dist/docs/zh/features/extend.md +8 -7
  45. package/dist/docs/zh/features/freedom.md +8 -8
  46. package/dist/docs/zh/features/index.md +44 -28
  47. package/dist/docs/zh/features/long-work.md +8 -8
  48. package/dist/docs/zh/features/look.md +5 -5
  49. package/dist/docs/zh/features/people.md +5 -5
  50. package/dist/docs/zh/features/phone.md +5 -3
  51. package/dist/docs/zh/features/spaces.md +7 -7
  52. package/dist/docs/zh/features/workbench.md +8 -8
  53. package/dist/docs/zh/guides/interface.md +16 -4
  54. package/dist/docs/zh/guides/sessions.md +6 -2
  55. package/dist/docs/zh/guides/settings.md +15 -2
  56. package/dist/docs/zh/reference/command.md +58 -1
  57. package/dist/docs/zh/reference/tools.md +25 -5
  58. package/dist/docs/zh/server/acp.md +3 -1
  59. package/dist/docs/zh/server/mcp.md +5 -1
  60. package/dist/docs/zh/server/rest-api.md +114 -3
  61. package/dist/hostRunner.mjs +92 -1
  62. package/dist/mailbox-worker.mjs +297 -0
  63. package/dist/main.mjs +2 -2
  64. package/dist/native/windows-process-helper.exe +0 -0
  65. package/dist/query-store-worker.mjs +446 -0
  66. package/dist/sqlite-indexer.mjs +223 -401
  67. package/dist/sqlite-query-worker.mjs +226 -249
  68. package/dist/usage-parser-worker.mjs +24 -5
  69. package/dist/web/assets/AppErrorBoundary-BN6IDdP1.js +1 -0
  70. package/dist/web/assets/{LifeMark-CL6-HWDu.js → LifeMark-UBMVaTWr.js} +1 -1
  71. package/dist/web/assets/{NavScopeBoundary-CFCnvZR0.js → NavScopeBoundary-BCryw-UG.js} +1 -1
  72. package/dist/web/assets/{arc-DYDCMlOS.js → arc-C7IAvCCJ.js} +1 -1
  73. package/dist/web/assets/{architectureDiagram-3BPJPVTR-C9Y7T0O2.js → architectureDiagram-3BPJPVTR-CbwFBxn7.js} +1 -1
  74. package/dist/web/assets/{blockDiagram-GPEHLZMM-CdUrp-tD.js → blockDiagram-GPEHLZMM-B20N4t8r.js} +1 -1
  75. package/dist/web/assets/{c4Diagram-AAUBKEIU-PrwvB9IJ.js → c4Diagram-AAUBKEIU-3BYtlcP-.js} +1 -1
  76. package/dist/web/assets/channel-BJs5vJuh.js +1 -0
  77. package/dist/web/assets/{chunk-2J33WTMH-BL56g_Es.js → chunk-2J33WTMH-CpjgczxM.js} +1 -1
  78. package/dist/web/assets/{chunk-4BX2VUAB-DvJD5M9M.js → chunk-4BX2VUAB-BScxUF5G.js} +1 -1
  79. package/dist/web/assets/{chunk-55IACEB6-C8f-nzvx.js → chunk-55IACEB6-CrcLYJXd.js} +1 -1
  80. package/dist/web/assets/{chunk-727SXJPM-DOGkWKkV.js → chunk-727SXJPM-BwlyIOjw.js} +1 -1
  81. package/dist/web/assets/{chunk-AQP2D5EJ-fFOuz7g6.js → chunk-AQP2D5EJ-DKKIRkRv.js} +1 -1
  82. package/dist/web/assets/{chunk-FMBD7UC4-BpeXZ9LM.js → chunk-FMBD7UC4-CVDMj2kX.js} +1 -1
  83. package/dist/web/assets/{chunk-ND2GUHAM-CRUh76fb.js → chunk-ND2GUHAM-CL-PM6r8.js} +1 -1
  84. package/dist/web/assets/{chunk-QZHKN3VN-uNfxaPk0.js → chunk-QZHKN3VN-DPV2KbKZ.js} +1 -1
  85. package/dist/web/assets/classDiagram-4FO5ZUOK-BookeACB.js +1 -0
  86. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-BookeACB.js +1 -0
  87. package/dist/web/assets/client-CXcrCawx.js +3 -0
  88. package/dist/web/assets/connection-C8nwzwXB.js +1 -0
  89. package/dist/web/assets/{cose-bilkent-S5V4N54A-BNkxG-qX.js → cose-bilkent-S5V4N54A-D1CEiQM6.js} +1 -1
  90. package/dist/web/assets/{dagre-BM42HDAG-BerioUei.js → dagre-BM42HDAG-BlFV941E.js} +1 -1
  91. package/dist/web/assets/{diagram-2AECGRRQ-Czv2SR07.js → diagram-2AECGRRQ-BC0ldkFY.js} +1 -1
  92. package/dist/web/assets/{diagram-5GNKFQAL-Uzi1weGK.js → diagram-5GNKFQAL-B22Iej6G.js} +1 -1
  93. package/dist/web/assets/{diagram-KO2AKTUF-W36h_ff3.js → diagram-KO2AKTUF-B75UNw6D.js} +1 -1
  94. package/dist/web/assets/{diagram-LMA3HP47-FG4dDk52.js → diagram-LMA3HP47-CypI7IJM.js} +1 -1
  95. package/dist/web/assets/{diagram-OG6HWLK6-CQoEjIAY.js → diagram-OG6HWLK6-OsXumvcD.js} +1 -1
  96. package/dist/web/assets/{erDiagram-TEJ5UH35-Ck06KVyZ.js → erDiagram-TEJ5UH35-3756GOvS.js} +1 -1
  97. package/dist/web/assets/{export-T_izwEkQ.js → export-Bn8PqPg4.js} +1 -1
  98. package/dist/web/assets/{flowDiagram-I6XJVG4X-C5hgxdFZ.js → flowDiagram-I6XJVG4X-DB6Y_UDg.js} +1 -1
  99. package/dist/web/assets/{ganttDiagram-6RSMTGT7-BS52Pw5_.js → ganttDiagram-6RSMTGT7-CHJeuoAY.js} +1 -1
  100. package/dist/web/assets/{gitGraphDiagram-PVQCEYII-DLlQKZHs.js → gitGraphDiagram-PVQCEYII-Dj85554Y.js} +1 -1
  101. package/dist/web/assets/{highlighted-body-OFNGDK62-Btm6MuZ4.js → highlighted-body-OFNGDK62-DMgPHetp.js} +1 -1
  102. package/dist/web/assets/{index-CZX3qUe2.js → index-0tHq8zh2.js} +1 -1
  103. package/dist/web/assets/index-7ySDqvaN.css +1 -0
  104. package/dist/web/assets/index-B0KPRi1U.js +166 -0
  105. package/dist/web/assets/{index-CRDDqofN.js → index-B599VnpP.js} +1 -1
  106. package/dist/web/assets/{index-Cd62y0wD.js → index-BFK-GypQ.js} +1 -1
  107. package/dist/web/assets/{index-BMWid2q9.js → index-BPX8gmpB.js} +1 -1
  108. package/dist/web/assets/{index-5_yzg61S.js → index-BSGYc1tb.js} +1 -1
  109. package/dist/web/assets/{index-CJ92kLtO.js → index-BTt9Q5iv.js} +1 -1
  110. package/dist/web/assets/{index-B4iu4SJW.js → index-BWzUsoY_.js} +1 -1
  111. package/dist/web/assets/{index-CgcJPsK6.js → index-BYlSV3FO.js} +1 -1
  112. package/dist/web/assets/{index-BkPV0psm.js → index-BpXQ1q-u.js} +1 -1
  113. package/dist/web/assets/{index-Dceu0bqY.js → index-BqPxpGUh.js} +1 -1
  114. package/dist/web/assets/{index-CM-nNfuV.js → index-C6qeLCPw.js} +4 -4
  115. package/dist/web/assets/{index-ByiwExpV.js → index-C7mOS2T4.js} +1 -1
  116. package/dist/web/assets/{index-CG8uIlD7.js → index-C8OFfbEs.js} +1 -1
  117. package/dist/web/assets/{index-B-6LiYTY.js → index-CI7yuMGZ.js} +1 -1
  118. package/dist/web/assets/{index-B2Pu0Iuu.js → index-CJqIcuAl.js} +1 -1
  119. package/dist/web/assets/{index-BECSk4If.js → index-CTRJmDep.js} +1 -1
  120. package/dist/web/assets/{index-Bezli3SF.js → index-CXGCKoId.js} +1 -1
  121. package/dist/web/assets/{index-hG2s2Spn.js → index-CsY571EL.js} +1 -1
  122. package/dist/web/assets/{index-BFcyN2Zw.js → index-CwQG_9rB.js} +1 -1
  123. package/dist/web/assets/{index-BLU8_Um7.js → index-D--cw39y.js} +1 -1
  124. package/dist/web/assets/{index-B9MlqF7J.js → index-D260jsUJ.js} +1 -1
  125. package/dist/web/assets/{index-D_oPSlBL.js → index-DJjmEXx4.js} +1 -1
  126. package/dist/web/assets/{index-BNch_a4L.js → index-DRMjjql1.js} +1 -1
  127. package/dist/web/assets/{index-BeMvPEXs.js → index-DUxOVxHS.js} +1 -1
  128. package/dist/web/assets/{index-Ca607_hK.js → index-DZMkZKhW.js} +1 -1
  129. package/dist/web/assets/{index-BwcG86o3.js → index-DqK8MfQN.js} +1 -1
  130. package/dist/web/assets/{index-DKIysLbI.js → index-DxUmR9aV.js} +1 -1
  131. package/dist/web/assets/{index-Cy8C_eFR.js → index-GK8aa9pT.js} +1 -1
  132. package/dist/web/assets/{index-Bg99yVX_.js → index-bYtKyBMB.js} +1 -1
  133. package/dist/web/assets/{index-eUyF-8Sq.js → index-wxHFHTgD.js} +1 -1
  134. package/dist/web/assets/{infoDiagram-5YYISTIA-CD4XJGFm.js → infoDiagram-5YYISTIA-DeDPIdEH.js} +1 -1
  135. package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-fu5E3_CT.js → ishikawaDiagram-YF4QCWOH-ButuBiBW.js} +1 -1
  136. package/dist/web/assets/{journeyDiagram-JHISSGLW-CXcnKBfJ.js → journeyDiagram-JHISSGLW-Dlbmqm-j.js} +1 -1
  137. package/dist/web/assets/{kanban-definition-UN3LZRKU-BawKH6Pl.js → kanban-definition-UN3LZRKU-tlQK1cOz.js} +1 -1
  138. package/dist/web/assets/{linear-BplJuXph.js → linear-iXuNfUWp.js} +1 -1
  139. package/dist/web/assets/mermaid-GHXKKRXX-sDJax95P.js +624 -0
  140. package/dist/web/assets/{mindmap-definition-RKZ34NQL-DA1SE2uy.js → mindmap-definition-RKZ34NQL-2qPv-mwT.js} +1 -1
  141. package/dist/web/assets/{pieDiagram-4H26LBE5-6i021QeX.js → pieDiagram-4H26LBE5-CrLe1C-O.js} +1 -1
  142. package/dist/web/assets/{quadrantDiagram-W4KKPZXB-CcKSZDMT.js → quadrantDiagram-W4KKPZXB-DfeIFxc0.js} +1 -1
  143. package/dist/web/assets/{requirementDiagram-4Y6WPE33-lYVuWRuD.js → requirementDiagram-4Y6WPE33-BWtjdxie.js} +1 -1
  144. package/dist/web/assets/{sankeyDiagram-5OEKKPKP-4Zfb4_h4.js → sankeyDiagram-5OEKKPKP-B5TxJ6mb.js} +1 -1
  145. package/dist/web/assets/{sequenceDiagram-3UESZ5HK-DqltKmlY.js → sequenceDiagram-3UESZ5HK-Cf92ZCl1.js} +1 -1
  146. package/dist/web/assets/{spaces-CjuXbmxF.js → spaces-DqMTtCXX.js} +1 -1
  147. package/dist/web/assets/{stateDiagram-AJRCARHV-HFdhqxzx.js → stateDiagram-AJRCARHV-NR9I-Q4d.js} +1 -1
  148. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-BiegFWxE.js +1 -0
  149. package/dist/web/assets/{theme-beWE_6f8.js → theme-6OL1RXgY.js} +1 -1
  150. package/dist/web/assets/{timeline-definition-PNZ67QCA-HNRxaB3t.js → timeline-definition-PNZ67QCA-CBAOVMfm.js} +1 -1
  151. package/dist/web/assets/{vennDiagram-CIIHVFJN-DwsCTyaD.js → vennDiagram-CIIHVFJN-C68x6TdS.js} +1 -1
  152. package/dist/web/assets/{wardley-L42UT6IY-BWW2wtVO.js → wardley-L42UT6IY-DuZZr5jm.js} +1 -1
  153. package/dist/web/assets/{wardleyDiagram-YWT4CUSO-C-ktKm7v.js → wardleyDiagram-YWT4CUSO-D6dVGtHd.js} +1 -1
  154. package/dist/web/assets/{xychartDiagram-2RQKCTM6-48AxNW9k.js → xychartDiagram-2RQKCTM6-DYLUhZX4.js} +1 -1
  155. package/dist/web/index.html +2 -2
  156. package/native/auth-native/prebuilds/linux-arm64/auth-native.node +0 -0
  157. package/native/auth-native/prebuilds/linux-x64/auth-native.node +0 -0
  158. package/native/auth-native/prebuilds/win32-arm64/auth-native.node +0 -0
  159. package/native/auth-native/prebuilds/win32-x64/auth-native.node +0 -0
  160. package/package.json +2 -2
  161. package/dist/search-worker.mjs +0 -14177
  162. package/dist/web/assets/AppErrorBoundary-DiGMUg4r.js +0 -1
  163. package/dist/web/assets/channel-Bj_gZ_Lv.js +0 -1
  164. package/dist/web/assets/classDiagram-4FO5ZUOK-ssCwe2R4.js +0 -1
  165. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-ssCwe2R4.js +0 -1
  166. package/dist/web/assets/client-DGj93bGT.js +0 -3
  167. package/dist/web/assets/connection-Bpf-EjrL.js +0 -1
  168. package/dist/web/assets/index-BIebkSEI.css +0 -1
  169. package/dist/web/assets/index-D8z7lcQn.js +0 -166
  170. package/dist/web/assets/mermaid-GHXKKRXX-BO9hkP3Z.js +0 -621
  171. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-Dx28QuZF.js +0 -1
@@ -5,10 +5,23 @@ 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";
11
8
 
9
+ //#region ../../packages/kap-server/src/search/contract.ts
10
+ /**
11
+ * Service-level error with a machine-readable reason. Lives in the contract
12
+ * (not the service module) so the search-index core — which also runs inside
13
+ * the search worker thread — can raise it without importing the service.
14
+ */
15
+ var GlobalSearchError = class extends Error {
16
+ reason;
17
+ constructor(reason, message) {
18
+ super(message);
19
+ this.reason = reason;
20
+ this.name = "GlobalSearchError";
21
+ }
22
+ };
23
+
24
+ //#endregion
12
25
  //#region ../../packages/agent-core-v2/src/agent/media/mediaRef.ts
13
26
  const IMAGE_MIME_BY_SUFFIX = Object.freeze({
14
27
  ".png": "image/png",
@@ -84,56 +97,9 @@ function matchSingleMediaPathTag(text) {
84
97
  }
85
98
 
86
99
  //#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
100
+ //#region ../../packages/lexical/src/index.ts
135
101
  const LATIN = /[a-z0-9]+/g;
136
- const CJK = /[\u3400-\u9fff\u3040-\u30ff\uff00-\uffef]+/g;
102
+ const CJK = /[\u3400-\u9FFF\u3040-\u30FF\uFF00-\uFFEF]+/g;
137
103
  const MAX_TERM_CHARS = 65535;
138
104
  /** Tokenize text into terms (lowercased latin words + CJK uni/bigrams). */
139
105
  function tokenize(str) {
@@ -150,110 +116,7 @@ function tokenize(str) {
150
116
  }
151
117
  return terms;
152
118
  }
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. */
119
+ /** Normalize text for literal matching with Unicode NFKC and lowercase. */
257
120
  function normalizeLiteral(text) {
258
121
  return text.normalize("NFKC").toLowerCase();
259
122
  }
@@ -262,22 +125,6 @@ function normalizeLiteral(text) {
262
125
  //#region ../../packages/kap-server/src/search/docs.ts
263
126
  const MAX_DOC_TEXT_CHARS = 2e4;
264
127
 
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
128
  //#endregion
282
129
  //#region ../../packages/kap-server/src/services/history/historyQuery.ts
283
130
  function clausePosition(text, clause, literal) {
@@ -804,7 +651,7 @@ function analyzeWireLine(line) {
804
651
  //#region ../../packages/kap-server/src/search/sqlite/schema.ts
805
652
  /** Schema guard adapted from dsh-core/packages/session-query/session-query-sqlite/src/schema.ts (MIT). */
806
653
  const APPLICATION_ID = 1263749464;
807
- const SCHEMA_VERSION = 1;
654
+ const SCHEMA_VERSION = 2;
808
655
  const DERIVED_TABLES = new Set([
809
656
  "sessions",
810
657
  "files",
@@ -846,7 +693,7 @@ async function openSearchDatabase(path) {
846
693
  if (applicationId === 1263749464) {
847
694
  const unknown = tables.filter((name) => !DERIVED_TABLES.has(name));
848
695
  if (unknown.length) throw new Error(`search database at "${actual}" has unrecognized user tables: ${unknown.join(", ")}`);
849
- if (version !== 1) {
696
+ if (version !== 2) {
850
697
  for (const name of [
851
698
  "docs_tri",
852
699
  "docs_terms",
@@ -882,7 +729,7 @@ async function openSearchDatabase(path) {
882
729
  CREATE TABLE IF NOT EXISTS file_failures (path TEXT PRIMARY KEY, strikes INTEGER NOT NULL,
883
730
  error TEXT NOT NULL) STRICT;
884
731
  `);
885
- db.exec(`PRAGMA application_id=${APPLICATION_ID}; PRAGMA user_version=${1}`);
732
+ db.exec(`PRAGMA application_id=${APPLICATION_ID}; PRAGMA user_version=${2}`);
886
733
  db.prepare("INSERT OR IGNORE INTO meta(k,v) VALUES('generation','0')").run();
887
734
  const extractor = db.prepare("SELECT v FROM meta WHERE k='extractor_version'").get();
888
735
  if (extractor && extractor.v !== "3") {
@@ -904,6 +751,51 @@ async function openSearchDatabase(path) {
904
751
  }
905
752
  }
906
753
 
754
+ //#endregion
755
+ //#region ../../packages/kap-server/src/search/sqlite/queryBudget.ts
756
+ const DEFAULT_SEARCH_BUDGETS = {
757
+ literalCandidateCap: 1e4,
758
+ maxTextHits: 1e5,
759
+ postingsVisitBudget: 25e4,
760
+ queryDeadlineMs: 500,
761
+ queryTextBudgetChars: 16e6
762
+ };
763
+ function queryBudget(budgets, deadlineAt = Date.now() + budgets.queryDeadlineMs) {
764
+ return {
765
+ deadlineAt,
766
+ textCharsLeft: budgets.queryTextBudgetChars,
767
+ candidatesLeft: Math.max(budgets.literalCandidateCap, budgets.maxTextHits)
768
+ };
769
+ }
770
+ async function beforeDeadline(work, deadlineAt) {
771
+ const remaining = deadlineAt - Date.now();
772
+ if (remaining <= 0) {
773
+ work.catch(() => {});
774
+ return;
775
+ }
776
+ let timer;
777
+ try {
778
+ return await Promise.race([work, new Promise((resolve) => {
779
+ timer = setTimeout(() => resolve(void 0), remaining);
780
+ })]);
781
+ } finally {
782
+ if (timer) clearTimeout(timer);
783
+ }
784
+ }
785
+
786
+ //#endregion
787
+ //#region ../../packages/kap-server/src/search/sqlite/terms.ts
788
+ function encodeTerm(term) {
789
+ return [
790
+ "b",
791
+ ...Buffer.from(term, "utf8").toString("hex").match(/.{1,128}/g).map((chunk) => `x${chunk}`),
792
+ "e"
793
+ ].join(" ");
794
+ }
795
+ function encodeTerms(text) {
796
+ return tokenize(text).map(encodeTerm).join(" ");
797
+ }
798
+
907
799
  //#endregion
908
800
  //#region ../../packages/kap-server/src/search/sqlite/index.ts
909
801
  const CHUNK = 1 << 20;
@@ -1031,11 +923,11 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1031
923
  throw error;
1032
924
  }
1033
925
  }
1034
- static openReader(path, bootSalt) {
926
+ static openReader(path, bootSalt, options = {}) {
1035
927
  const db = new DatabaseSync(path, { readOnly: true });
1036
928
  try {
1037
929
  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);
930
+ return new SqliteSearchIndex(db, false, path, options, true, bootSalt);
1039
931
  } catch (error) {
1040
932
  db.close();
1041
933
  throw error;
@@ -1150,14 +1042,14 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1150
1042
  const db = this.db;
1151
1043
  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
1044
  const id = Number(info.lastInsertRowid);
1153
- db.prepare("INSERT INTO docs_terms(rowid,terms) VALUES(?,?)").run(id, tokenize(text).join(" "));
1045
+ db.prepare("INSERT INTO docs_terms(rowid,terms) VALUES(?,?)").run(id, encodeTerms(text));
1154
1046
  db.prepare("INSERT INTO docs_tri(rowid,text) VALUES(?,?)").run(id, normalizeLiteral(text));
1155
1047
  }
1156
1048
  deleteDocs(where, key) {
1157
1049
  const db = this.db;
1158
1050
  const rows = db.prepare(`SELECT id,text FROM docs WHERE ${where}=?`).iterate(key);
1159
1051
  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(" "));
1052
+ db.prepare("INSERT INTO docs_terms(docs_terms,rowid,terms) VALUES('delete',?,?)").run(row.id, encodeTerms(row.text));
1161
1053
  db.prepare("INSERT INTO docs_tri(docs_tri,rowid,text) VALUES('delete',?,?)").run(row.id, normalizeLiteral(row.text));
1162
1054
  db.prepare("DELETE FROM docs WHERE id=?").run(row.id);
1163
1055
  }
@@ -1175,6 +1067,55 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1175
1067
  await fd.close();
1176
1068
  }
1177
1069
  }
1070
+ reconcileSessions(current) {
1071
+ const task = this.syncQueue.catch(() => {}).then(async () => {
1072
+ for (const id of this.pendingSessions.keys()) if (!current.has(id)) this.pendingSessions.delete(id);
1073
+ let after = "";
1074
+ while (!this.closed && !this.options.isStopped?.()) {
1075
+ const batch = this.db.prepare("SELECT id FROM sessions WHERE id>? ORDER BY id LIMIT 100").all(after);
1076
+ if (!batch.length) return true;
1077
+ for (const { id } of batch) {
1078
+ if (!current.has(id) && !await this.removeSession(id)) return false;
1079
+ after = id;
1080
+ }
1081
+ await new Promise((resolve) => setImmediate(resolve));
1082
+ }
1083
+ return false;
1084
+ });
1085
+ this.syncQueue = task;
1086
+ return task;
1087
+ }
1088
+ async removeSession(id) {
1089
+ const db = this.db;
1090
+ while (!this.closed && !this.options.isStopped?.()) {
1091
+ if (this.walStuck) return false;
1092
+ const docs = db.prepare("SELECT id FROM docs WHERE session_id=? LIMIT 128").all(id);
1093
+ const file = docs.length ? void 0 : db.prepare("SELECT id,path FROM files WHERE session_id=? LIMIT 1").get(id);
1094
+ db.exec("BEGIN");
1095
+ try {
1096
+ for (const doc of docs) this.deleteDocs("id", doc.id);
1097
+ if (file) {
1098
+ 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);
1099
+ if (!db.prepare("SELECT 1 FROM turn_openers WHERE file_id=? LIMIT 1").get(file.id)) {
1100
+ db.prepare("DELETE FROM file_failures WHERE path=?").run(file.path);
1101
+ db.prepare("DELETE FROM files WHERE id=?").run(file.id);
1102
+ }
1103
+ } else if (!docs.length) db.prepare("DELETE FROM sessions WHERE id=?").run(id);
1104
+ this.bumpGeneration();
1105
+ db.exec("COMMIT");
1106
+ } catch (error) {
1107
+ db.exec("ROLLBACK");
1108
+ throw error;
1109
+ }
1110
+ this.afterCommit();
1111
+ if (!docs.length && !file) {
1112
+ this.pendingSessions.delete(id);
1113
+ return true;
1114
+ }
1115
+ await new Promise((resolve) => setImmediate(resolve));
1116
+ }
1117
+ return false;
1118
+ }
1178
1119
  syncSession(session) {
1179
1120
  const task = this.syncQueue.catch(() => {}).then(() => this.syncSessionInner(session));
1180
1121
  this.syncQueue = task;
@@ -1188,7 +1129,10 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1188
1129
  return;
1189
1130
  }
1190
1131
  const id = await identity(session.dir);
1191
- if (id === void 0) return;
1132
+ if (id === void 0) {
1133
+ await this.removeSession(session.id);
1134
+ return;
1135
+ }
1192
1136
  const db = this.db;
1193
1137
  const title = await titleAt(session.dir);
1194
1138
  const existing = db.prepare("SELECT title,identity,dir FROM sessions WHERE id=?").get(session.id);
@@ -1282,7 +1226,7 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1282
1226
  }
1283
1227
  if (file?.policy === "quarantined") return;
1284
1228
  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)));
1229
+ 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
1230
  if (!replace && file?.offset === st.size) {
1287
1231
  if (changed) db.prepare("UPDATE files SET size=?,mtime_ms=? WHERE id=?").run(st.size, st.mtimeMs, file.id);
1288
1232
  return;
@@ -1429,17 +1373,21 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1429
1373
  await fd.close();
1430
1374
  }
1431
1375
  }
1432
- async search(q, pageToken, budgets = {
1433
- literalCandidateCap: 1e4,
1434
- maxTextHits: 1e5,
1435
- postingsVisitBudget: 25e4,
1436
- queryDeadlineMs: 500,
1437
- queryTextBudgetChars: 16e6
1438
- }) {
1376
+ async search(q, pageToken, budgets = DEFAULT_SEARCH_BUDGETS, budget = queryBudget(budgets)) {
1439
1377
  const db = this.db;
1440
1378
  const generation = this.generation;
1441
1379
  const page = decodePageToken(q, "index", pageToken, generation);
1442
- const deadlineAt = Date.now() + budgets.queryDeadlineMs;
1380
+ const { deadlineAt } = budget;
1381
+ if (Date.now() >= deadlineAt || budget.textCharsLeft < 0) return {
1382
+ rows: [],
1383
+ hasMore: false,
1384
+ incomplete: "deadline"
1385
+ };
1386
+ budgets = {
1387
+ ...budgets,
1388
+ maxTextHits: Math.min(budgets.maxTextHits, budget.candidatesLeft),
1389
+ literalCandidateCap: Math.min(budgets.literalCandidateCap, budget.candidatesLeft)
1390
+ };
1443
1391
  let incomplete;
1444
1392
  const terms = q.termsQuery ?? [...new Set(tokenize(q.query))];
1445
1393
  const literal = q.literalQuery ?? normalizeLiteral(q.query);
@@ -1478,7 +1426,7 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1478
1426
  const scopedWhere = filters.length ? ` AND ${filters.join(" AND ")}` : "";
1479
1427
  if (q.mode === "terms") if (!terms.length) matchedIds = [];
1480
1428
  else {
1481
- const expression = terms.map(quoteTerm).join(q.op === "OR" ? " OR " : " AND ");
1429
+ const expression = terms.map((term) => quoteTerm(encodeTerm(term))).join(q.op === "OR" ? " OR " : " AND ");
1482
1430
  if (ranked) matchedIds = db.prepare(`SELECT docs_terms.rowid, docs_terms.rank FROM docs_terms
1483
1431
  ${scopedWhere ? "JOIN docs d ON d.id=docs_terms.rowid" : ""}
1484
1432
  WHERE docs_terms MATCH ?${scopedWhere} ORDER BY rank LIMIT ?`).all(expression, Math.min(budgets.maxTextHits, 64) + 1);
@@ -1495,20 +1443,21 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1495
1443
  else if (Array.from(literal).length >= 3) matchedIds = db.prepare(`SELECT docs_tri.rowid FROM docs_tri ${joins("docs_tri")}
1496
1444
  WHERE docs_tri MATCH ?${scopedWhere} LIMIT ?`).all(quoteTerm(literal), ...filterValues, budgets.literalCandidateCap + 1);
1497
1445
  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
1446
+ 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
1447
  LEFT JOIN files f ON f.id=d.file_id WHERE 1=1${scopedWhere} LIMIT ?`).all(...filterValues, budgets.literalCandidateCap + 1);
1500
1448
  const cap = ranked ? Math.min(budgets.maxTextHits, 64) : q.mode === "terms" ? budgets.maxTextHits : budgets.literalCandidateCap;
1501
1449
  if (matchedIds.length > cap) {
1502
1450
  matchedIds.length = cap;
1503
1451
  incomplete = "candidate_cap";
1504
1452
  }
1453
+ budget.candidatesLeft -= matchedIds.length;
1505
1454
  const rows = [];
1506
1455
  const N = q.mode === "terms" && !ranked ? db.prepare(`SELECT count(*) AS n FROM docs d
1507
1456
  JOIN sessions s ON s.id=d.session_id LEFT JOIN files f ON f.id=d.file_id
1508
1457
  WHERE 1=1${scopedWhere}`).get(...filterValues).n : 0;
1509
1458
  const dfs = /* @__PURE__ */ new Map();
1510
1459
  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);
1460
+ WHERE docs_terms MATCH ?${scopedWhere}`).get(quoteTerm(encodeTerm(term)), ...filterValues).n);
1512
1461
  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
1462
  for (const { rowid, rank } of matchedIds) {
1514
1463
  if (Date.now() > deadlineAt - 25) {
@@ -1552,45 +1501,18 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1552
1501
  score
1553
1502
  });
1554
1503
  }
1555
- const budget = {
1556
- deadlineAt,
1557
- textCharsLeft: budgets.queryTextBudgetChars
1558
- };
1559
1504
  const matched = matchDocs(q, rows, page.kind === "keyset" ? page.boundary : void 0, budget);
1560
1505
  incomplete ??= matched.incomplete;
1561
1506
  const valid = [];
1562
1507
  const identities = /* @__PURE__ */ new Map();
1563
- const sourceQuery = db.prepare("SELECT dir,identity FROM sessions WHERE id=?");
1564
- const sources = /* @__PURE__ */ new Map();
1565
1508
  for (let offset = 0; offset < matched.rows.length; offset += 16) {
1566
- if (Date.now() > deadlineAt) {
1567
- incomplete ??= "deadline";
1509
+ const batch = matched.rows.slice(offset, offset + 16);
1510
+ const verified = await this.verifySources(batch, budget, identities);
1511
+ if (verified === void 0) {
1512
+ incomplete = "deadline";
1568
1513
  break;
1569
1514
  }
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;
1515
+ for (let i = 0; i < batch.length; i++) if (verified[i]) valid.push(batch[i]);
1594
1516
  }
1595
1517
  const { pageRows, hasMore } = paginateRows(q, page, valid);
1596
1518
  return {
@@ -1600,6 +1522,81 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1600
1522
  pageToken: hasMore ? encodePageToken(q, "index", boundaryOf(q, pageRows[pageRows.length - 1]), generation) : void 0
1601
1523
  };
1602
1524
  }
1525
+ async verifySources(rows, budget, identities) {
1526
+ if (Date.now() >= budget.deadlineAt) return void 0;
1527
+ const sources = this.db.prepare("SELECT dir,identity FROM sessions WHERE id=?");
1528
+ const checks = rows.map((row) => {
1529
+ const source = sources.get(row.value.sessionId);
1530
+ if (!source || source.identity !== row.value.sessionIdentity) return Promise.resolve(false);
1531
+ let check = identities.get(source.dir);
1532
+ if (!check) {
1533
+ check = (this.options.sourceIdentity ?? identity)(source.dir);
1534
+ identities.set(source.dir, check);
1535
+ }
1536
+ return check.then((current) => current === source.identity);
1537
+ });
1538
+ return beforeDeadline(Promise.all(checks), budget.deadlineAt);
1539
+ }
1540
+ async sourcesCurrent(rows, budget) {
1541
+ const identities = /* @__PURE__ */ new Map();
1542
+ for (let offset = 0; offset < rows.length; offset += 16) {
1543
+ const verified = await this.verifySources(rows.slice(offset, offset + 16), budget, identities);
1544
+ if (verified === void 0) return void 0;
1545
+ if (!verified.every(Boolean)) return false;
1546
+ }
1547
+ return true;
1548
+ }
1549
+ };
1550
+
1551
+ //#endregion
1552
+ //#region ../../packages/kap-server/src/search/sqlite/queries.ts
1553
+ const deadlineResult = () => ({
1554
+ rows: [],
1555
+ hasMore: false,
1556
+ incomplete: "deadline"
1557
+ });
1558
+ var SqliteSearchQueries = class {
1559
+ reader;
1560
+ cacheMs;
1561
+ recent = /* @__PURE__ */ new Map();
1562
+ constructor(reader, cacheMs = 500) {
1563
+ this.reader = reader;
1564
+ this.cacheMs = cacheMs;
1565
+ }
1566
+ async search(query, pageToken, budgets = DEFAULT_SEARCH_BUDGETS, deadlineAt = Date.now() + budgets.queryDeadlineMs) {
1567
+ const budget = queryBudget(budgets, deadlineAt);
1568
+ if (Date.now() >= deadlineAt) return deadlineResult();
1569
+ const key = this.cacheMs ? JSON.stringify([
1570
+ query,
1571
+ pageToken,
1572
+ budgets
1573
+ ]) : "";
1574
+ const version = this.cacheMs ? this.reader.db.prepare("PRAGMA data_version").get().data_version : 0;
1575
+ const cached = this.cacheMs ? this.recent.get(key) : void 0;
1576
+ if (cached && cached.expires >= Date.now() && cached.version === version) {
1577
+ const value = await beforeDeadline(cached.result, deadlineAt);
1578
+ if (value === void 0) return deadlineResult();
1579
+ const current = await this.reader.sourcesCurrent(value.rows, budget);
1580
+ if (current === true) return value;
1581
+ if (this.recent.get(key) === cached) this.recent.delete(key);
1582
+ if (current === void 0) return deadlineResult();
1583
+ return this.reader.search(query, pageToken, budgets, budget);
1584
+ }
1585
+ if (this.cacheMs && this.recent.size >= 16) this.recent.delete(this.recent.keys().next().value);
1586
+ const result = this.reader.search(query, pageToken, budgets, budget);
1587
+ if (this.cacheMs) {
1588
+ const entry = {
1589
+ expires: Date.now() + this.cacheMs,
1590
+ version,
1591
+ result
1592
+ };
1593
+ this.recent.set(key, entry);
1594
+ result.catch(() => {
1595
+ if (this.recent.get(key) === entry) this.recent.delete(key);
1596
+ });
1597
+ }
1598
+ return result;
1599
+ }
1603
1600
  };
1604
1601
 
1605
1602
  //#endregion
@@ -1607,8 +1604,8 @@ var SqliteSearchIndex = class SqliteSearchIndex {
1607
1604
  const port = parentPort;
1608
1605
  if (!port) throw new Error("query entry requires a worker thread");
1609
1606
  let reader;
1607
+ let queries;
1610
1608
  const source = typeof workerData === "string" ? { database: workerData } : workerData;
1611
- const recent = /* @__PURE__ */ new Map();
1612
1609
  const cacheMs = process.env["KIKI_SEARCH_QUERY_CACHE_MS"] === "0" ? 0 : 500;
1613
1610
  const send = (event) => port.postMessage(event);
1614
1611
  send({ type: "ready" });
@@ -1626,29 +1623,8 @@ const handleMessage = async (message) => {
1626
1623
  await setTimeout$1(50 * (attempt + 1));
1627
1624
  }
1628
1625
  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;
1626
+ queries ??= new SqliteSearchQueries(reader, cacheMs);
1627
+ const value = await queries.search(message.query, message.pageToken, message.budgets, message.deadlineAt);
1652
1628
  send({
1653
1629
  id: message.id,
1654
1630
  type: "result",
@@ -1658,7 +1634,8 @@ const handleMessage = async (message) => {
1658
1634
  send({
1659
1635
  id: message.id,
1660
1636
  type: "error",
1661
- message: error instanceof Error ? error.message : String(error)
1637
+ message: error instanceof Error ? error.message : String(error),
1638
+ reason: error instanceof GlobalSearchError ? error.reason : void 0
1662
1639
  });
1663
1640
  }
1664
1641
  };