@wirecat/tg-cli 0.116.0 → 0.118.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 (125) hide show
  1. package/dist/bin/tg.js +2 -2
  2. package/dist/bot/transport.d.ts +1 -1
  3. package/dist/bot/transport.d.ts.map +1 -1
  4. package/dist/bot/transport.js +42 -30
  5. package/dist/bot/transport.js.map +1 -1
  6. package/dist/bundle/{adapter-6CLMTQOV.js → adapter-4YNP6VCO.js} +70 -61
  7. package/dist/bundle/{all-profiles-R2UZMH24.js → all-profiles-MIQDYAGO.js} +10 -10
  8. package/dist/bundle/{anthropic-QKIPHV2Z.js → anthropic-NTASPJYE.js} +6 -6
  9. package/dist/bundle/{app-server-AZB2MFK6.js → app-server-UJZBJ2SK.js} +49 -46
  10. package/dist/bundle/{bot-api-2IM243J4.js → bot-api-JZAD4L3N.js} +49 -49
  11. package/dist/bundle/{bot-history-G6CRVCL2.js → bot-history-OUDHH3NU.js} +18 -18
  12. package/dist/bundle/{bun-JDKPISPX.js → bun-EC4HDIRD.js} +2 -2
  13. package/dist/bundle/{bun-sqlite-X5PY5IQT.js → bun-sqlite-A4HJR6KO.js} +5 -5
  14. package/dist/bundle/{chunk-SD5PUYKF.js → chunk-2KQHUBTV.js} +12 -12
  15. package/dist/bundle/{chunk-QHBVGKC3.js → chunk-2NA5KVP6.js} +210 -82
  16. package/dist/bundle/{chunk-PPLFOIYX.js → chunk-3MQOLYAN.js} +4 -4
  17. package/dist/bundle/{chunk-QGL2UGML.js → chunk-4BV4UMBB.js} +738 -235
  18. package/dist/bundle/{chunk-Y6VWGJ4Q.js → chunk-57LKX6N2.js} +4 -2
  19. package/dist/bundle/{chunk-BGMV66FC.js → chunk-5IIU7X4S.js} +1 -1
  20. package/dist/bundle/{chunk-H72UEHNG.js → chunk-5LDWBEWU.js} +55 -33
  21. package/dist/bundle/{chunk-XQUTJITP.js → chunk-5QYU7B27.js} +763 -130
  22. package/dist/bundle/chunk-65XV5PPI.js +64 -0
  23. package/dist/bundle/{chunk-NUYRMU56.js → chunk-6AXUEJGL.js} +2 -2
  24. package/dist/bundle/{chunk-N42VUNTO.js → chunk-6RI4TEIC.js} +2 -2
  25. package/dist/bundle/{chunk-VQPLHOVQ.js → chunk-6ZMTEUVU.js} +6 -6
  26. package/dist/bundle/{chunk-MQ7MCVZV.js → chunk-76EKXFX2.js} +2 -2
  27. package/dist/bundle/{chunk-K62YATVD.js → chunk-BNEP5EOV.js} +18 -4
  28. package/dist/bundle/{chunk-EB2IULWB.js → chunk-BXTDAGM4.js} +2 -2
  29. package/dist/bundle/{chunk-HBUJNNZD.js → chunk-CEY43D3A.js} +31 -29
  30. package/dist/bundle/chunk-DKFC5ZZ3.js +208 -0
  31. package/dist/bundle/{chunk-FDI4GOIP.js → chunk-DSZJREEO.js} +463 -358
  32. package/dist/bundle/{chunk-76CX2YPT.js → chunk-EPCFXKTX.js} +8 -8
  33. package/dist/bundle/{chunk-KA6EGOJY.js → chunk-EPXVRJAX.js} +2 -2
  34. package/dist/bundle/{chunk-4IQZRW4O.js → chunk-EQJ6NLF5.js} +13 -13
  35. package/dist/bundle/{chunk-4D5AUWAY.js → chunk-FHMK6OK4.js} +43 -25
  36. package/dist/bundle/{chunk-RSDIPQXP.js → chunk-G3RT2EQI.js} +2 -2
  37. package/dist/bundle/{chunk-IR4S7POE.js → chunk-GI4MTNA2.js} +8 -8
  38. package/dist/bundle/{chunk-HK6SIIGG.js → chunk-GIM37COQ.js} +3 -3
  39. package/dist/bundle/{chunk-UCSFO5GW.js → chunk-GLRRCKP6.js} +3 -3
  40. package/dist/bundle/{chunk-YYKJN6H5.js → chunk-GXCJ47SJ.js} +1499 -710
  41. package/dist/bundle/{chunk-GV7ZJ33M.js → chunk-H6S3C3MH.js} +4 -4
  42. package/dist/bundle/{chunk-LXH3SKY3.js → chunk-HJNRIK5X.js} +8 -8
  43. package/dist/bundle/{chunk-5VFPUOJO.js → chunk-I4TI5HDJ.js} +11 -11
  44. package/dist/bundle/{chunk-RSNGMNU5.js → chunk-JLJKGKU2.js} +6 -6
  45. package/dist/bundle/{chunk-T7CDLV33.js → chunk-JPVFYMSQ.js} +22 -14
  46. package/dist/bundle/{chunk-B4UOCWM4.js → chunk-JWIUK3SK.js} +2 -2
  47. package/dist/bundle/{chunk-LSKGCJWD.js → chunk-JWPSVS6C.js} +21246 -4044
  48. package/dist/bundle/{chunk-JJMQA272.js → chunk-JZETEZHC.js} +8 -21
  49. package/dist/bundle/{chunk-42GK3XRS.js → chunk-KEDHX6XG.js} +2 -2
  50. package/dist/bundle/{chunk-QAKL3GXB.js → chunk-MBH7IKLT.js} +1 -1
  51. package/dist/bundle/{chunk-HLNYJPAB.js → chunk-MZNOASAW.js} +2 -2
  52. package/dist/bundle/{chunk-YLRTLZF6.js → chunk-NKFTZVQU.js} +1 -1
  53. package/dist/bundle/{chunk-577MFPCP.js → chunk-NMT2VGEI.js} +3 -3
  54. package/dist/bundle/{chunk-5ZIBAYIZ.js → chunk-NUCDEOFC.js} +2 -2
  55. package/dist/bundle/{chunk-NL3PAFAE.js → chunk-OTQDJUES.js} +6 -6
  56. package/dist/bundle/{chunk-KV4267S4.js → chunk-P3ASN72F.js} +1 -1
  57. package/dist/bundle/{chunk-TZVL4U7U.js → chunk-PB252TT3.js} +4 -2
  58. package/dist/bundle/{chunk-HUOXUI2M.js → chunk-PO74BDER.js} +58 -47
  59. package/dist/bundle/{chunk-LFKEKSI5.js → chunk-PW3HFIJA.js} +523 -239
  60. package/dist/bundle/{chunk-5FCONCJO.js → chunk-PWCQC56A.js} +1 -1
  61. package/dist/bundle/{chunk-XBIPSSKI.js → chunk-QOGYHU3Q.js} +4 -4
  62. package/dist/bundle/{chunk-JFTCOV37.js → chunk-RG2E7ZQZ.js} +180 -25
  63. package/dist/bundle/{chunk-R52RMHWF.js → chunk-TMTEWOQS.js} +3 -3
  64. package/dist/bundle/{chunk-I6JF43YP.js → chunk-TSTEZNSX.js} +3 -3
  65. package/dist/bundle/{chunk-YPF6OS37.js → chunk-VW6BF6M7.js} +1 -1
  66. package/dist/bundle/{chunk-SKZ2E3WC.js → chunk-Y64SI2RO.js} +47 -1
  67. package/dist/bundle/{chunk-DP5LRU7K.js → chunk-YEOSV6JC.js} +1 -1
  68. package/dist/bundle/{chunk-OX6EWGSG.js → chunk-YHZFGUAP.js} +19 -19
  69. package/dist/bundle/{chunk-N6TIFJHW.js → chunk-YPRUWRKE.js} +1 -1
  70. package/dist/bundle/{chunk-PPSUA3IZ.js → chunk-ZMUC3UQO.js} +3 -3
  71. package/dist/bundle/{chunk-PXMHBTK3.js → chunk-ZXXTJF4Z.js} +4 -4
  72. package/dist/bundle/command-contract-7GZ6HAA6.js +33 -0
  73. package/dist/bundle/{decode-W6YPTGJA.js → decode-NMNPLKNR.js} +5 -5
  74. package/dist/bundle/{dispatch-H7EFNBEH.js → dispatch-OP27MWX5.js} +8 -8
  75. package/dist/bundle/{echarts-YAWDIC5D.js → echarts-S46LEIPS.js} +2 -2
  76. package/dist/bundle/{embed-EN4UTLV5.js → embed-I5ZYHGYC.js} +6 -6
  77. package/dist/bundle/{embedder-HEKHRL7E.js → embedder-LTJI67N2.js} +9 -9
  78. package/dist/bundle/{entry-2KB6MTCG.js → entry-O6BUPXF7.js} +7 -7
  79. package/dist/bundle/{failure-3DU3HLBQ.js → failure-4JUQFXJT.js} +2 -2
  80. package/dist/bundle/{first-run-LBG26WWO.js → first-run-PMZNCDGD.js} +11 -11
  81. package/dist/bundle/first-screen-BGML5DSO.js +31 -0
  82. package/dist/bundle/{instructions-HA62QNPR.js → instructions-AUEGY3VO.js} +1 -1
  83. package/dist/bundle/{mcp-PPVOM4SE.js → mcp-M4QN2E7R.js} +2 -2
  84. package/dist/bundle/{node-MZ2VWSQQ.js → node-XRA7RBCQ.js} +2 -2
  85. package/dist/bundle/{node-sqlite-KNNS6DCM.js → node-sqlite-DEZO6LRS.js} +6 -6
  86. package/dist/bundle/{oauth-KWUABBSQ.js → oauth-DAVC7WCD.js} +7 -7
  87. package/dist/bundle/{open-JXMCYCIV.js → open-DE2YO4T7.js} +5 -5
  88. package/dist/bundle/{openai-HL3IR4VT.js → openai-5BKGAULH.js} +14 -14
  89. package/dist/bundle/{process-K2FICLWY.js → process-4ZHPNUIQ.js} +1 -1
  90. package/dist/bundle/{program-IFOMT4JS.js → program-EGTKSNB4.js} +51 -51
  91. package/dist/bundle/{prompt-HVD3Q77P.js → prompt-HWCWHHPE.js} +5 -5
  92. package/dist/bundle/{proxy-transport-PA5SGMRY.js → proxy-transport-4DPZB2W2.js} +5 -5
  93. package/dist/bundle/{recognize-HHLVETKI.js → recognize-NG6RXNGF.js} +4 -4
  94. package/dist/bundle/{remote-HUAKXJCS.js → remote-ZKXIIGYH.js} +7 -7
  95. package/dist/bundle/{rerank-NWFIV7OF.js → rerank-TX5QFURV.js} +7 -7
  96. package/dist/bundle/{serve-ANUKAJJN.js → serve-XAS6DECW.js} +9 -9
  97. package/dist/bundle/{server-7Q7WAOHO.js → server-CNPIWBYU.js} +35 -35
  98. package/dist/bundle/server-FRTKLHZF.js +60 -0
  99. package/dist/bundle/{state-Y2AJ5XTP.js → state-3HTUETTS.js} +6 -6
  100. package/dist/bundle/{store-S3IG5KWL.js → store-B5VZWJHN.js} +23 -13
  101. package/dist/bundle/store-maintenance-command-VG3CLELA.js +50 -0
  102. package/dist/bundle/tg.js +13 -13
  103. package/dist/telegram/account.d.ts.map +1 -1
  104. package/dist/telegram/account.js +4 -1
  105. package/dist/telegram/account.js.map +1 -1
  106. package/dist/telegram/errors.d.ts.map +1 -1
  107. package/dist/telegram/errors.js +2 -1
  108. package/dist/telegram/errors.js.map +1 -1
  109. package/dist/telegram/feature.d.ts +4 -1
  110. package/dist/telegram/feature.d.ts.map +1 -1
  111. package/dist/telegram/feature.js +5 -2
  112. package/dist/telegram/feature.js.map +1 -1
  113. package/dist/telegram/sending.d.ts.map +1 -1
  114. package/dist/telegram/sending.js +24 -10
  115. package/dist/telegram/sending.js.map +1 -1
  116. package/dist/version.d.ts +1 -1
  117. package/dist/version.js +1 -1
  118. package/package.json +3 -3
  119. package/dist/bundle/chunk-K2RYCCTP.js +0 -48
  120. package/dist/bundle/chunk-ZDIAPICE.js +0 -132
  121. package/dist/bundle/command-contract-DPXM4SZT.js +0 -33
  122. package/dist/bundle/first-screen-TGTSLUI6.js +0 -31
  123. package/dist/bundle/server-HCQS4YDQ.js +0 -60
  124. package/dist/bundle/store-maintenance-command-V2WC4G6J.js +0 -50
  125. /package/dist/bundle/{chunk-LU3WKZBA.js → chunk-VOXIGICJ.js} +0 -0
@@ -3,7 +3,7 @@ const require = __bundleRequire(import.meta.url);
3
3
  import {
4
4
  answerOf,
5
5
  messengerContext
6
- } from "./chunk-HUOXUI2M.js";
6
+ } from "./chunk-PO74BDER.js";
7
7
  import {
8
8
  FETCHING,
9
9
  RULES_VERSION,
@@ -22,8 +22,16 @@ import {
22
22
  servicesFor,
23
23
  syncsOneChat,
24
24
  typedQuery,
25
- withQuery
26
- } from "./chunk-FDI4GOIP.js";
25
+ withQuery,
26
+ withTimeLimit
27
+ } from "./chunk-DSZJREEO.js";
28
+ import {
29
+ QUICK_HEALTH_CHECKS,
30
+ explainDamage,
31
+ fts5Tables,
32
+ invalidJson,
33
+ storeHealth
34
+ } from "./chunk-DKFC5ZZ3.js";
27
35
  import {
28
36
  stringWidth,
29
37
  wrapAnsi
@@ -55,30 +63,32 @@ import {
55
63
  snakeKeys,
56
64
  storeTable,
57
65
  withoutProviderRefs
58
- } from "./chunk-LFKEKSI5.js";
59
- import {
60
- failureKey
61
- } from "./chunk-JJMQA272.js";
66
+ } from "./chunk-PW3HFIJA.js";
62
67
  import {
63
68
  envName
64
- } from "./chunk-TZVL4U7U.js";
69
+ } from "./chunk-PB252TT3.js";
65
70
  import {
66
71
  holdLock,
67
72
  lockPath,
68
73
  releaseLock,
69
74
  servingProfiles,
70
75
  takeLock
71
- } from "./chunk-HK6SIIGG.js";
76
+ } from "./chunk-GIM37COQ.js";
72
77
  import {
73
78
  holdersOf
74
- } from "./chunk-N6TIFJHW.js";
79
+ } from "./chunk-YPRUWRKE.js";
75
80
  import {
81
+ CORPORA,
76
82
  MIGRATIONS,
83
+ drainCorpus,
84
+ drainMeetingIndex,
77
85
  drainNoteIndex,
78
86
  dropAllUnusedVectors,
79
87
  fileFacts,
80
88
  fillSearchIndex,
81
89
  fillStems,
90
+ fillTrigrams,
91
+ fillVectorIndexes,
82
92
  formatLocator,
83
93
  involvementStoreOver,
84
94
  migrate,
@@ -89,10 +99,12 @@ import {
89
99
  parseLocator,
90
100
  pendingNormalization,
91
101
  readStoreTables,
102
+ rebuildMentions,
92
103
  resetAttachmentWords,
93
104
  resetNoteIndex,
94
105
  resetSearchIndex,
95
106
  resetStems,
107
+ rollBack,
96
108
  rowCounts,
97
109
  searchIndexState,
98
110
  stemmerCache,
@@ -100,34 +112,41 @@ import {
100
112
  storeClients,
101
113
  storeContents,
102
114
  vectorIndexCounts
103
- } from "./chunk-LSKGCJWD.js";
115
+ } from "./chunk-JWPSVS6C.js";
116
+ import {
117
+ queryFieldsOf,
118
+ readDamageMark,
119
+ readHealthMark,
120
+ recordDeepCheck
121
+ } from "./chunk-4BV4UMBB.js";
104
122
  import {
105
- queryFieldsOf
106
- } from "./chunk-QGL2UGML.js";
123
+ failureKey,
124
+ isStoreDamage
125
+ } from "./chunk-Y64SI2RO.js";
107
126
  import {
108
127
  readSecret
109
- } from "./chunk-UCSFO5GW.js";
128
+ } from "./chunk-GLRRCKP6.js";
110
129
  import {
111
130
  checkedOptions,
112
131
  range
113
- } from "./chunk-I6JF43YP.js";
132
+ } from "./chunk-TSTEZNSX.js";
114
133
  import {
115
134
  messagesFor,
116
135
  systemFor,
117
136
  validateImages
118
- } from "./chunk-MQ7MCVZV.js";
137
+ } from "./chunk-76EKXFX2.js";
119
138
  import {
120
139
  storePath
121
- } from "./chunk-RSDIPQXP.js";
140
+ } from "./chunk-G3RT2EQI.js";
122
141
  import {
123
142
  openCache
124
- } from "./chunk-RSNGMNU5.js";
143
+ } from "./chunk-JLJKGKU2.js";
125
144
  import {
126
145
  Credentials,
127
146
  pathsAreOverridden,
128
147
  resolvePaths,
129
148
  writeSecurely
130
- } from "./chunk-OX6EWGSG.js";
149
+ } from "./chunk-YHZFGUAP.js";
131
150
  import {
132
151
  array,
133
152
  boolean,
@@ -151,12 +170,12 @@ import {
151
170
  transform,
152
171
  trim,
153
172
  union
154
- } from "./chunk-76CX2YPT.js";
173
+ } from "./chunk-EPCFXKTX.js";
155
174
  import {
156
175
  CliError,
157
176
  singleLine,
158
177
  visibleControls
159
- } from "./chunk-EB2IULWB.js";
178
+ } from "./chunk-BXTDAGM4.js";
160
179
  import {
161
180
  __commonJS,
162
181
  __name,
@@ -1810,7 +1829,7 @@ var require_liquid_node = __commonJS({
1810
1829
  return readFileAsync(filepath, "utf8");
1811
1830
  }
1812
1831
  __name(readFile, "readFile");
1813
- function existsSync8(filepath) {
1832
+ function existsSync10(filepath) {
1814
1833
  try {
1815
1834
  fs$1.statSync(filepath);
1816
1835
  return true;
@@ -1818,11 +1837,11 @@ var require_liquid_node = __commonJS({
1818
1837
  return false;
1819
1838
  }
1820
1839
  }
1821
- __name(existsSync8, "existsSync");
1822
- function readFileSync4(filepath) {
1840
+ __name(existsSync10, "existsSync");
1841
+ function readFileSync5(filepath) {
1823
1842
  return fs$1.readFileSync(filepath, "utf8");
1824
1843
  }
1825
- __name(readFileSync4, "readFileSync");
1844
+ __name(readFileSync5, "readFileSync");
1826
1845
  function resolve2(root, file2, ext) {
1827
1846
  if (!path.extname(file2))
1828
1847
  file2 += ext;
@@ -1836,10 +1855,10 @@ var require_liquid_node = __commonJS({
1836
1855
  }
1837
1856
  }
1838
1857
  __name(fallback, "fallback");
1839
- function dirname2(filepath) {
1858
+ function dirname3(filepath) {
1840
1859
  return path.dirname(filepath);
1841
1860
  }
1842
- __name(dirname2, "dirname");
1861
+ __name(dirname3, "dirname");
1843
1862
  var realpathAsync = promisify(fs$1.realpath);
1844
1863
  async function contains(root, file2) {
1845
1864
  try {
@@ -1867,11 +1886,11 @@ var require_liquid_node = __commonJS({
1867
1886
  __proto__: null,
1868
1887
  exists,
1869
1888
  readFile,
1870
- existsSync: existsSync8,
1871
- readFileSync: readFileSync4,
1889
+ existsSync: existsSync10,
1890
+ readFileSync: readFileSync5,
1872
1891
  resolve: resolve2,
1873
1892
  fallback,
1874
- dirname: dirname2,
1893
+ dirname: dirname3,
1875
1894
  contains,
1876
1895
  containsSync,
1877
1896
  sep: path.sep
@@ -3596,7 +3615,7 @@ var require_liquid_node = __commonJS({
3596
3615
  uri_escape,
3597
3616
  slugify
3598
3617
  });
3599
- var join4 = argumentsToValue(function(v, arg) {
3618
+ var join5 = argumentsToValue(function(v, arg) {
3600
3619
  const array2 = toArray(v);
3601
3620
  const sep = isNil(arg) ? " " : stringify(arg);
3602
3621
  let outputSize = sep.length * Math.max(array2.length - 1, 0);
@@ -3872,7 +3891,7 @@ var require_liquid_node = __commonJS({
3872
3891
  __name(sample, "sample");
3873
3892
  var arrayFilters = /* @__PURE__ */ Object.freeze({
3874
3893
  __proto__: null,
3875
- join: join4,
3894
+ join: join5,
3876
3895
  last,
3877
3896
  first,
3878
3897
  reverse,
@@ -5496,11 +5515,11 @@ var require_liquid_node = __commonJS({
5496
5515
  }
5497
5516
  });
5498
5517
 
5499
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
5500
- import { chmodSync, constants, copyFileSync, existsSync as existsSync7, mkdirSync, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statfsSync, statSync as statSync3, writeFileSync } from "node:fs";
5501
- import { dirname, resolve } from "node:path";
5518
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
5519
+ import { chmodSync, constants, copyFileSync, existsSync as existsSync9, mkdirSync, realpathSync as realpathSync2, renameSync as renameSync3, rmSync as rmSync3, statfsSync as statfsSync2, statSync as statSync4, writeFileSync as writeFileSync2 } from "node:fs";
5520
+ import { dirname as dirname2, resolve } from "node:path";
5502
5521
 
5503
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/sealed.js
5522
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/sealed.js
5504
5523
  import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
5505
5524
  import { closeSync, createReadStream, createWriteStream, existsSync, openSync, readSync, renameSync, rmSync, statSync } from "node:fs";
5506
5525
  import { Transform } from "node:stream";
@@ -5607,7 +5626,7 @@ var unsealFile = /* @__PURE__ */ __name(async (from, to, password) => {
5607
5626
  renameSync(pending, to);
5608
5627
  }, "unsealFile");
5609
5628
 
5610
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/store/compatibility.js
5629
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/store/compatibility.js
5611
5630
  var SPEAKS = MIGRATIONS.at(-1)?.version ?? 0;
5612
5631
  var fileSchemaOf = /* @__PURE__ */ __name((database) => {
5613
5632
  const tracked = database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'schema_migrations'").get();
@@ -5631,7 +5650,7 @@ var compatibilityOf = /* @__PURE__ */ __name((file2, migrations = MIGRATIONS) =>
5631
5650
  };
5632
5651
  }, "compatibilityOf");
5633
5652
 
5634
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/store/repair.js
5653
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/store/repair.js
5635
5654
  import { createHash as createHash2 } from "node:crypto";
5636
5655
  var COPY_MARK = "__repair_";
5637
5656
  var COPY_NAME = /__repair_[0-9a-f]{8}(_\d+)?$/;
@@ -5885,10 +5904,545 @@ var deleteCopy = /* @__PURE__ */ __name((database, name) => {
5885
5904
  return found;
5886
5905
  }, "deleteCopy");
5887
5906
 
5888
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5889
- import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
5907
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5908
+ import { existsSync as existsSync4, statSync as statSync3 } from "node:fs";
5909
+
5910
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
5911
+ import { existsSync as existsSync3 } from "node:fs";
5912
+
5913
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/store/recover.js
5914
+ import { execFileSync, spawn } from "node:child_process";
5915
+ import { existsSync as existsSync2, readFileSync, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statfsSync, statSync as statSync2, writeFileSync } from "node:fs";
5916
+ import { basename, dirname, join } from "node:path";
5917
+ import { Transform as Transform2 } from "node:stream";
5918
+ var SQLITE3_MINIMUM = [3, 43, 0];
5919
+ var STORE_PARTS = ["", "-wal", "-shm"];
5920
+ var RECOVER_LOCK = ".recover-lock";
5921
+ var INSERTED = /^INSERT OR IGNORE INTO '([^']+)'/;
5922
+ var LOST_AND_FOUND = "recover_lost_and_found";
5923
+ var recovers = /* @__PURE__ */ __name((program) => {
5924
+ try {
5925
+ execFileSync(program, [":memory:", ".recover"], { stdio: ["ignore", "ignore", "pipe"] });
5926
+ return true;
5927
+ } catch {
5928
+ return false;
5929
+ }
5930
+ }, "recovers");
5931
+ var sqlite3Program = /* @__PURE__ */ __name((program = "sqlite3") => {
5932
+ let version = null;
5933
+ try {
5934
+ version = execFileSync(program, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split(" ")[0] ?? null;
5935
+ } catch {
5936
+ return { program, version: null, usable: false };
5937
+ }
5938
+ const parts2 = (version ?? "").split(".").map(Number);
5939
+ const at = SQLITE3_MINIMUM.findIndex((wanted, i) => (parts2[i] ?? 0) !== wanted);
5940
+ const recent = at === -1 || (parts2[at] ?? 0) > (SQLITE3_MINIMUM[at] ?? 0);
5941
+ return { program, version, usable: recent && recovers(program) };
5942
+ }, "sqlite3Program");
5943
+ var activeTimers = /* @__PURE__ */ __name(() => {
5944
+ if (process.platform !== "linux")
5945
+ return void 0;
5946
+ try {
5947
+ return execFileSync("systemctl", ["--user", "list-timers", "--plain", "--no-legend"], {
5948
+ encoding: "utf8",
5949
+ stdio: ["ignore", "pipe", "ignore"]
5950
+ }).split("\n").map((line) => line.trim().split(/\s+/).at(-2) ?? "").filter((unit) => /^(memo|mail|tg|max|whatsapp|zoom|drive|gcal|wirecat)-.*\.timer$/.test(unit));
5951
+ } catch {
5952
+ return void 0;
5953
+ }
5954
+ }, "activeTimers");
5955
+ var alive = /* @__PURE__ */ __name((pid) => {
5956
+ try {
5957
+ process.kill(pid, 0);
5958
+ return true;
5959
+ } catch (error) {
5960
+ return error.code === "EPERM";
5961
+ }
5962
+ }, "alive");
5963
+ var runningRecovery = /* @__PURE__ */ __name((path) => {
5964
+ let pid;
5965
+ try {
5966
+ pid = Number(readFileSync(`${path}${RECOVER_LOCK}`, "utf8").trim());
5967
+ } catch {
5968
+ return null;
5969
+ }
5970
+ return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
5971
+ }, "runningRecovery");
5972
+ var takeRecoverLock = /* @__PURE__ */ __name((path) => {
5973
+ const lock = `${path}${RECOVER_LOCK}`;
5974
+ const take = /* @__PURE__ */ __name(() => writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 }), "take");
5975
+ try {
5976
+ take();
5977
+ } catch (error) {
5978
+ if (error.code !== "EEXIST")
5979
+ throw error;
5980
+ const pid = runningRecovery(path);
5981
+ if (pid === null) {
5982
+ rmSync2(lock, { force: true });
5983
+ take();
5984
+ } else {
5985
+ throw new CliError("validation_error", `the store is being recovered by process ${pid} \u2014 wait for it to finish`, {
5986
+ reason: "store.recovering"
5987
+ });
5988
+ }
5989
+ }
5990
+ return () => rmSync2(lock, { force: true });
5991
+ }, "takeRecoverLock");
5992
+ var storeHolders = /* @__PURE__ */ __name((path) => {
5993
+ const folder = realpathSync(dirname(path));
5994
+ const files = STORE_PARTS.map((suffix) => join(folder, `${basename(path)}${suffix}`));
5995
+ const wanted = process.platform === "linux" ? files.flatMap((file2) => [file2, `${file2} (deleted)`]) : files.filter(existsSync2);
5996
+ const recovering = runningRecovery(path);
5997
+ const pids = holdersOf(wanted);
5998
+ if (pids === void 0 && recovering === null)
5999
+ return void 0;
6000
+ const all = [
6001
+ .../* @__PURE__ */ new Set([...pids ?? [], ...recovering !== null && recovering !== process.pid ? [recovering] : []])
6002
+ ];
6003
+ return all.map((pid) => {
6004
+ let name = "?";
6005
+ try {
6006
+ name = readFileSync(`/proc/${pid}/comm`, "utf8").trim();
6007
+ } catch {
6008
+ }
6009
+ return { pid, name };
6010
+ });
6011
+ }, "storeHolders");
6012
+ var tableRows = /* @__PURE__ */ __name((database) => {
6013
+ const indexes = fts5Tables(database).map((index) => index.name);
6014
+ const tables = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND rootpage > 0 AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'vector_index_%' ORDER BY name").all().map((row) => String(row.name)).filter((name) => !indexes.some((index) => name.startsWith(`${index}_`)));
6015
+ return Object.fromEntries(tables.map((table) => {
6016
+ try {
6017
+ return [table, Number(database.prepare(`SELECT count(*) AS n FROM "${table}"`).get()?.n)];
6018
+ } catch {
6019
+ return [table, null];
6020
+ }
6021
+ }));
6022
+ }, "tableRows");
6023
+ var copyReadableRows = /* @__PURE__ */ __name((path, target, program = "sqlite3") => new Promise((resolve2, reject) => {
6024
+ const reader = spawn(program, ["-readonly", path, `.recover --ignore-freelist --lost-and-found ${LOST_AND_FOUND}`], {
6025
+ stdio: ["ignore", "pipe", "pipe"]
6026
+ });
6027
+ const writer = spawn(program, ["-cmd", ".dbconfig defensive off", target], { stdio: ["pipe", "ignore", "pipe"] });
6028
+ const errors = [];
6029
+ const collect = /* @__PURE__ */ __name((chunk) => {
6030
+ for (const line of chunk.toString("utf8").split("\n"))
6031
+ if (line && errors.length < 50)
6032
+ errors.push(line.slice(0, 300));
6033
+ }, "collect");
6034
+ reader.stderr.on("data", collect);
6035
+ writer.stderr.on("data", collect);
6036
+ const read = {};
6037
+ let rest = "";
6038
+ const counter = new Transform2({
6039
+ transform(chunk, _encoding, done) {
6040
+ const lines = (rest + chunk.toString("latin1")).split("\n");
6041
+ rest = lines.pop() ?? "";
6042
+ for (const line of lines) {
6043
+ const table = INSERTED.exec(line)?.[1];
6044
+ if (table)
6045
+ read[table] = (read[table] ?? 0) + 1;
6046
+ }
6047
+ done(null, chunk);
6048
+ }
6049
+ });
6050
+ reader.stdout.pipe(counter).pipe(writer.stdin);
6051
+ let exits = 0;
6052
+ let readerCode = null;
6053
+ const exited = /* @__PURE__ */ __name(() => {
6054
+ exits += 1;
6055
+ if (exits < 2)
6056
+ return;
6057
+ if (readerCode !== 0)
6058
+ reject(new CliError("validation_error", `sqlite3 could not read the store: ${errors.join("; ")}`));
6059
+ else
6060
+ resolve2({ errors, read });
6061
+ }, "exited");
6062
+ reader.on("error", reject);
6063
+ writer.on("error", reject);
6064
+ reader.on("close", (code) => {
6065
+ readerCode = code;
6066
+ exited();
6067
+ });
6068
+ writer.on("close", exited);
6069
+ }), "copyReadableRows");
6070
+ var FILLERS = {
6071
+ message_words: /* @__PURE__ */ __name((database, now) => {
6072
+ resetSearchIndex(database);
6073
+ fillSearchIndex(database, { now });
6074
+ }, "message_words"),
6075
+ message_stems: /* @__PURE__ */ __name((database, now) => {
6076
+ resetStems(database, { force: true, now });
6077
+ fillStems(database, { now });
6078
+ }, "message_stems"),
6079
+ attachment_words: /* @__PURE__ */ __name((database) => void resetAttachmentWords(database), "attachment_words"),
6080
+ attachment_name_words: /* @__PURE__ */ __name((database) => (
6081
+ // As migration 20 filled it: й and ё fold as the triggers fold them.
6082
+ database.exec("INSERT INTO attachment_name_words (rowid, name) SELECT id, replace(replace(replace(replace(name, '\u0439', '\u0438'), '\u0419', '\u0418'), '\u0451', '\u0435'), '\u0401', '\u0415') FROM attachments WHERE name IS NOT NULL")
6083
+ ), "attachment_name_words"),
6084
+ meeting_words: /* @__PURE__ */ __name((database) => {
6085
+ database.exec("INSERT OR IGNORE INTO meeting_index_pending (indexable_type, id) SELECT 'meeting_transcript_row', id FROM meeting_transcript_rows UNION ALL SELECT 'meeting_chat_message', id FROM meeting_chat_messages UNION ALL SELECT 'meeting_summary', id FROM meeting_summaries");
6086
+ drainMeetingIndex(database);
6087
+ }, "meeting_words"),
6088
+ // Built per account by the first search that needs them.
6089
+ meeting_stems: /* @__PURE__ */ __name((database) => database.exec("UPDATE search_index_state SET filled_through = 0, built_at = NULL WHERE name LIKE 'meeting_stems:%'"), "meeting_stems")
6090
+ };
6091
+ var CORPUS_TABLES = new Set(Object.values(CORPORA).flatMap((corpus) => [`${corpus.type}_words`, `${corpus.type}_stems`]));
6092
+ var TRIGRAMS = ["note_trigrams", "document_trigrams"];
6093
+ var rebuildDerived = /* @__PURE__ */ __name((database, { now = Date.now, note = /* @__PURE__ */ __name(() => {
6094
+ }, "note") } = {}) => {
6095
+ const lost = database.prepare("SELECT 1 FROM sqlite_master WHERE name = ?").get(LOST_AND_FOUND);
6096
+ const lostAndFound = lost ? Number(database.prepare(`SELECT count(*) AS n FROM ${LOST_AND_FOUND}`).get()?.n) : 0;
6097
+ if (lost)
6098
+ database.exec(`DROP TABLE ${LOST_AND_FOUND}`);
6099
+ const indexes = fts5Tables(database);
6100
+ for (const { name, sql } of indexes) {
6101
+ database.exec(`DROP TABLE "${name}"`);
6102
+ database.exec(sql);
6103
+ }
6104
+ const vectors = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name GLOB 'vector_index_[0-9]*' AND sql LIKE 'CREATE VIRTUAL%'").all().map((row) => String(row.name));
6105
+ for (const table of vectors) {
6106
+ database.exec(`DROP TRIGGER IF EXISTS "${table}_redo"`);
6107
+ database.exec(`DROP TABLE "${table}"`);
6108
+ database.prepare("DELETE FROM vector_indexes WHERE id = ?").run(Number(table.replace("vector_index_", "")));
6109
+ }
6110
+ const unfilled = [];
6111
+ const stemmerFor = stemmerCache();
6112
+ for (const { name, external } of indexes) {
6113
+ note(`rebuilding ${name}`);
6114
+ if (external)
6115
+ database.exec(`INSERT INTO "${name}" ("${name}") VALUES ('rebuild')`);
6116
+ else if (FILLERS[name])
6117
+ FILLERS[name](database, now);
6118
+ else if (!CORPUS_TABLES.has(name) && !TRIGRAMS.includes(name))
6119
+ unfilled.push(name);
6120
+ }
6121
+ note("rebuilding the words of notes, documents, memories, mail, tasks, transcripts and events");
6122
+ resetNoteIndex(database);
6123
+ for (const corpus of Object.values(CORPORA))
6124
+ drainCorpus(database, corpus, stemmerFor);
6125
+ for (const name of TRIGRAMS) {
6126
+ const type = name.replace("_trigrams", "");
6127
+ database.prepare(`UPDATE search_index_state SET filled_through = 0, watermark = (SELECT coalesce(max(id), 0) FROM ${type}s) WHERE name = ?`).run(name);
6128
+ }
6129
+ fillTrigrams(database);
6130
+ note("finding mentions again");
6131
+ const mentions = rebuildMentions(database, { now: now() }).mentions;
6132
+ involvementStoreOver({ database, now }).rebuild();
6133
+ note("indexing the stored vectors");
6134
+ const vectorModels = fillVectorIndexes(database);
6135
+ const without = database.prepare("SELECT count(*) AS n FROM chunks k WHERE NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)");
6136
+ const chunksWithoutVector = Object.fromEntries(database.prepare("SELECT model FROM vector_indexes ORDER BY model").all().map((row) => [String(row.model), Number(without.get(String(row.model))?.n)]));
6137
+ return {
6138
+ lostAndFound,
6139
+ searchIndexes: indexes.map((index) => index.name),
6140
+ unfilled,
6141
+ mentions,
6142
+ vectorModels,
6143
+ chunksWithoutVector
6144
+ };
6145
+ }, "rebuildDerived");
6146
+ var danglingRows = /* @__PURE__ */ __name((database) => database.prepare(`SELECT "table" AS child, parent, fkid, count(*) AS n FROM pragma_foreign_key_check GROUP BY 1, 2, 3 ORDER BY 4 DESC`).all().map((group) => {
6147
+ const child = String(group.child);
6148
+ const column = database.prepare(`SELECT "from" AS name FROM pragma_foreign_key_list(?) WHERE id = ? ORDER BY seq LIMIT 1`).get(child, Number(group.fkid))?.name;
6149
+ let missing = [];
6150
+ try {
6151
+ missing = database.prepare(`SELECT DISTINCT "${String(column)}" AS id FROM "${child}" WHERE rowid IN (SELECT rowid FROM pragma_foreign_key_check(?) WHERE fkid = ?) ORDER BY 1 LIMIT 20`).all(child, Number(group.fkid)).map((row) => typeof row.id === "number" ? row.id : String(row.id));
6152
+ } catch {
6153
+ }
6154
+ return { table: child, parent: String(group.parent), rows: Number(group.n), missing };
6155
+ }), "danglingRows");
6156
+ var mailToFetch = /* @__PURE__ */ __name((database) => {
6157
+ try {
6158
+ return database.prepare(`SELECT a.external_id AS account, count(DISTINCT l.email_id) AS n FROM email_locations l
6159
+ JOIN mailboxes b ON b.id = l.mailbox_id JOIN accounts a ON a.id = b.account_id
6160
+ WHERE NOT EXISTS (SELECT 1 FROM emails e WHERE e.id = l.email_id) GROUP BY a.id ORDER BY a.external_id`).all().map((row) => ({ account: String(row.account), emails: Number(row.n) }));
6161
+ } catch {
6162
+ return [];
6163
+ }
6164
+ }, "mailToFetch");
6165
+ var clearInvalidJson = /* @__PURE__ */ __name((database) => {
6166
+ const found = invalidJson(database);
6167
+ for (const { table, column, required } of found) {
6168
+ const invalid = `"${column}" IS NOT NULL AND NOT json_valid("${column}")`;
6169
+ database.exec(required ? `DELETE FROM "${table}" WHERE ${invalid}` : `UPDATE "${table}" SET "${column}" = NULL WHERE ${invalid}`);
6170
+ }
6171
+ return found;
6172
+ }, "clearInvalidJson");
6173
+ var refuseInUse = /* @__PURE__ */ __name((path) => {
6174
+ const holders = storeHolders(path);
6175
+ if (holders && holders.length > 0) {
6176
+ const timers = activeTimers() ?? [];
6177
+ throw new CliError("validation_error", `the store is open in ${holders.map(({ pid, name }) => `${name} (process ${pid})`).join(", ")} \u2014 stop it first` + (timers.length ? `, and the timers: systemctl --user stop ${timers.join(" ")}` : ""), { reason: "store.in-use" });
6178
+ }
6179
+ }, "refuseInUse");
6180
+ var recoverStore = /* @__PURE__ */ __name(async ({ path, command, version, sqlite3 = "sqlite3", now = Date.now, note = /* @__PURE__ */ __name(() => {
6181
+ }, "note"), copy }) => {
6182
+ const started = Date.now();
6183
+ if (!existsSync2(path))
6184
+ throw new CliError("not_found", `no store at ${path}`);
6185
+ const program = copy ? { program: sqlite3, version: "given", usable: true } : sqlite3Program(sqlite3);
6186
+ if (!program.usable) {
6187
+ throw new CliError("configuration_error", program.version ? `sqlite3 ${program.version} cannot recover: the recovery needs ${SQLITE3_MINIMUM.join(".")} or newer, built with .recover` : "the recovery needs the sqlite3 program with its .recover command: install it (apt install sqlite3, brew install sqlite)", { reason: "store.sqlite3-missing" });
6188
+ }
6189
+ const releaseLock2 = takeRecoverLock(path);
6190
+ try {
6191
+ refuseInUse(path);
6192
+ const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync2(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
6193
+ const { bavail, bsize } = statfsSync(dirname(path));
6194
+ if (Number(bavail) * Number(bsize) < bytes * 1.2)
6195
+ throw new CliError("validation_error", `the recovery needs about ${Math.ceil(bytes * 1.2 / 1e9)} GB free beside the store`);
6196
+ return await recoverLocked({ path, command, version, sqlite3, now, note, copy, started, program });
6197
+ } finally {
6198
+ releaseLock2();
6199
+ }
6200
+ }, "recoverStore");
6201
+ var recoverLocked = /* @__PURE__ */ __name(async ({ path, command, version, sqlite3, now, note, copy, started, program }) => {
6202
+ const watch = (await openSqlite(path, { readOnly: true })).database;
6203
+ let watching = true;
6204
+ const stopWatching = /* @__PURE__ */ __name(() => {
6205
+ if (watching)
6206
+ watch.close();
6207
+ watching = false;
6208
+ }, "stopWatching");
6209
+ try {
6210
+ const dataVersion = /* @__PURE__ */ __name(() => Number(watch.prepare("PRAGMA data_version").get()?.data_version), "dataVersion");
6211
+ let rowsBefore;
6212
+ try {
6213
+ rowsBefore = tableRows(watch);
6214
+ } catch (error) {
6215
+ if (!isStoreDamage(error))
6216
+ throw error;
6217
+ throw new CliError("configuration_error", "the store file's header or schema is damaged, so its tables cannot be listed and it cannot be recovered; the file was left as it was", { reason: "store.unreadable" });
6218
+ }
6219
+ const before = { data: dataVersion(), inode: statSync2(path).ino };
6220
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
6221
+ const target = `${path}.recovering-${stamp}`;
6222
+ writeFileSync(target, "", { flag: "wx", mode: 384 });
6223
+ const dropTarget = /* @__PURE__ */ __name(() => {
6224
+ for (const suffix of [...STORE_PARTS, "-journal"])
6225
+ rmSync2(`${target}${suffix}`, { force: true });
6226
+ }, "dropTarget");
6227
+ note(`copying the readable rows into ${target}`);
6228
+ let copied;
6229
+ let copyErrors;
6230
+ let read;
6231
+ let opened;
6232
+ try {
6233
+ ;
6234
+ ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
6235
+ copied = Date.now();
6236
+ opened = await openSqlite(target);
6237
+ } catch (error) {
6238
+ dropTarget();
6239
+ throw error;
6240
+ }
6241
+ let rebuilt;
6242
+ let kept;
6243
+ let dangling;
6244
+ let json;
6245
+ let fetch2;
6246
+ let schema;
6247
+ try {
6248
+ kept = tableRows(opened.database);
6249
+ migrate(opened.database, { command, ...version ? { version } : {} });
6250
+ note("clearing values that are not valid JSON");
6251
+ json = clearInvalidJson(opened.database);
6252
+ rebuilt = rebuildDerived(opened.database, { now, note });
6253
+ note("looking for rows that point at rows that were lost");
6254
+ dangling = danglingRows(opened.database);
6255
+ fetch2 = mailToFetch(opened.database);
6256
+ schema = fileSchemaOf(opened.database).version;
6257
+ opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
6258
+ } catch (error) {
6259
+ opened.database.close();
6260
+ dropTarget();
6261
+ throw error;
6262
+ }
6263
+ opened.database.close();
6264
+ const rebuiltAt = Date.now();
6265
+ note("checking the recovered file");
6266
+ const health = await storeHealth(target, { deep: true });
6267
+ const checkedAt = Date.now();
6268
+ if (!health.ok) {
6269
+ throw new CliError("validation_error", `the recovered file did not pass its check, so the store was left as it was; the file is kept at ${target}`, { reason: "store.recovery-failed" });
6270
+ }
6271
+ refuseInUse(path);
6272
+ const changed = dataVersion() !== before.data || statSync2(path, { throwIfNoEntry: false })?.ino !== before.inode;
6273
+ stopWatching();
6274
+ if (changed) {
6275
+ throw new CliError("validation_error", `the store was written to during the recovery, so it was left as it was \u2014 stop every timer and run it again; ${target} can be deleted`, { reason: "store.changed-during-recovery" });
6276
+ }
6277
+ const keptAt = `${path}.before-recover-${stamp}`;
6278
+ for (const suffix of STORE_PARTS)
6279
+ if (existsSync2(`${path}${suffix}`))
6280
+ renameSync2(`${path}${suffix}`, `${keptAt}${suffix}`);
6281
+ for (const suffix of STORE_PARTS)
6282
+ if (existsSync2(`${target}${suffix}`))
6283
+ renameSync2(`${target}${suffix}`, `${path}${suffix}`);
6284
+ recordDeepCheck(path, health, { cli: command, ...version ? { version } : {}, schema, now });
6285
+ const lost = Object.entries(rowsBefore).map(([table, before2]) => ({ table, before: before2, read: read[table] ?? 0, kept: kept[table] ?? 0 })).filter(({ before: before2, read: read2, kept: kept2 }) => before2 === null || before2 > kept2 || read2 > kept2);
6286
+ const seconds = /* @__PURE__ */ __name((from, to) => Math.round((to - from) / 100) / 10, "seconds");
6287
+ return {
6288
+ path,
6289
+ keptAt,
6290
+ sqlite3: program.version,
6291
+ lost,
6292
+ dangling,
6293
+ invalidJson: json,
6294
+ mailToFetch: fetch2,
6295
+ rebuilt,
6296
+ copyErrors,
6297
+ health,
6298
+ seconds: {
6299
+ copy: seconds(started, copied),
6300
+ rebuild: seconds(copied, rebuiltAt),
6301
+ check: seconds(rebuiltAt, checkedAt),
6302
+ total: seconds(started, Date.now())
6303
+ }
6304
+ };
6305
+ } finally {
6306
+ stopWatching();
6307
+ }
6308
+ }, "recoverLocked");
6309
+
6310
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
6311
+ var COUNTED = [
6312
+ "accounts",
6313
+ "chats",
6314
+ "messages",
6315
+ "attachments",
6316
+ "emails",
6317
+ "documents",
6318
+ "notes",
6319
+ "meetings",
6320
+ "chunks",
6321
+ "embeddings",
6322
+ "mentions"
6323
+ ];
6324
+ var stopTimers = /* @__PURE__ */ __name((timers) => `systemctl --user stop ${timers.join(" ")}`, "stopTimers");
6325
+ var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command, version) => {
6326
+ const path = storePath(env);
6327
+ if (!existsSync3(path))
6328
+ return { path, exists: false, ok: true, next: [] };
6329
+ const health = await storeHealth(path, { deep: true });
6330
+ let rows = {};
6331
+ let schema = null;
6332
+ try {
6333
+ const { database } = await openSqlite(path, { readOnly: true });
6334
+ try {
6335
+ schema = fileSchemaOf(database).version;
6336
+ const all = tableRows(database);
6337
+ rows = Object.fromEntries(COUNTED.filter((table) => table in all).map((table) => [table, all[table] ?? null]));
6338
+ } finally {
6339
+ database.close();
6340
+ }
6341
+ } catch {
6342
+ }
6343
+ recordDeepCheck(path, health, { cli: command, ...version ? { version } : {}, schema });
6344
+ const mark = readDamageMark(path);
6345
+ const explanation = explainDamage(health, command, mark);
6346
+ const inUse = storeHolders(path) ?? null;
6347
+ const timers = activeTimers() ?? null;
6348
+ const sqlite3 = sqlite3Program();
6349
+ const next = health.ok ? [] : [
6350
+ ...timers?.length ? [stopTimers(timers)] : [],
6351
+ ...(inUse ?? []).map(({ pid, name }) => `stop ${name} (process ${pid}): it has the store open`),
6352
+ ...sqlite3.usable ? [] : ["install sqlite3 3.43 or newer (apt install sqlite3, brew install sqlite)"],
6353
+ `${command} store recover run`
6354
+ ];
6355
+ return {
6356
+ path,
6357
+ exists: true,
6358
+ ok: health.ok,
6359
+ seconds: Math.round(health.ms / 100) / 10,
6360
+ problems: health.problems ?? 0,
6361
+ damagedTables: health.damagedTables ?? [],
6362
+ damagedSearchIndexes: (health.searchIndexes ?? []).filter((index) => !index.ok).map(({ name, error }) => ({ name, ...error ? { error } : {} })),
6363
+ invalidJson: health.invalidJson ?? [],
6364
+ rows,
6365
+ explanation,
6366
+ damageMark: mark ? (({ inode: _, ...seen }) => seen)(mark) : null,
6367
+ lastKnownGood: readHealthMark(path)?.last_ok_at ?? null,
6368
+ inUse,
6369
+ timers,
6370
+ sqlite3: { version: sqlite3.version, usable: sqlite3.usable },
6371
+ next
6372
+ };
6373
+ }, "storeRecoveryCheck");
6374
+ var storeRecoveryRun = /* @__PURE__ */ __name(async (env, { command, version, note, timers: scheduled = activeTimers, copy }) => {
6375
+ const timers = scheduled() ?? [];
6376
+ if (timers.length > 0)
6377
+ throw new CliError("validation_error", `stop the timers first, they open the store: ${stopTimers(timers)}`, {
6378
+ reason: "store.in-use"
6379
+ });
6380
+ const recovery = await recoverStore({
6381
+ path: storePath(env),
6382
+ command,
6383
+ ...version ? { version } : {},
6384
+ ...note ? { note } : {},
6385
+ ...copy ? { copy } : {}
6386
+ });
6387
+ const mail = recovery.mailToFetch.map(({ account, emails }) => `mail <profile of ${account}> sync --rescan # ${emails} emails`);
6388
+ const lostMail = recovery.lost.some(({ table }) => table === "emails") && mail.length === 0 ? ["mail <profile> sync --rescan # each mail profile"] : [];
6389
+ const { health, copyErrors, ...kept } = recovery;
6390
+ return {
6391
+ ...kept,
6392
+ copyErrors: copyErrors.length,
6393
+ checkedOk: health.ok,
6394
+ next: [...mail, ...lostMail, "systemctl --user start <the timers stopped before>"]
6395
+ };
6396
+ }, "storeRecoveryRun");
6397
+ var recoveryNotes = /* @__PURE__ */ __name((answer) => {
6398
+ if ("keptAt" in answer) {
6399
+ const lost = answer.lost.map(({ table, before, read, kept }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}`);
6400
+ return [
6401
+ `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
6402
+ ...lost.length ? lost : ["no table lost a row"],
6403
+ ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
6404
+ ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON \u2014 ${required ? "those rows were dropped" : "set to empty"}`),
6405
+ ...answer.next.map((line) => `next: ${line}`)
6406
+ ];
6407
+ }
6408
+ if (!answer.exists)
6409
+ return ["no store yet"];
6410
+ if (answer.ok)
6411
+ return [`the store is healthy (checked every page and search index in ${answer.seconds} s)`];
6412
+ const why = answer.explanation;
6413
+ return [
6414
+ ...why ? [why.what, ...why.impact, why.externalUnaffected] : [],
6415
+ answer.lastKnownGood ? `the store last passed a deep check at ${answer.lastKnownGood}` : "no deep check that passed is on record for this store",
6416
+ ...answer.next.map((line) => `next: ${line}`)
6417
+ ];
6418
+ }, "recoveryNotes");
6419
+ var storeRecoverCommand = /* @__PURE__ */ __name(({ command, version }) => {
6420
+ const recover = annotate(new Command("recover"), { effects: LOCAL_READ, examples: [`${command} store recover`] }).summary("what is damaged in the store and how to recover it").description("check every page and search index of the store, say what is damaged, what it means and the commands that recover it; changes nothing").action(async function() {
6421
+ const output = outputFor(this);
6422
+ const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command, version);
6423
+ renderAnswer(this, output, itemOf(snakeKeys(answer)));
6424
+ if (output.format === "pretty")
6425
+ for (const line of recoveryNotes(answer))
6426
+ output.renderer.note(line);
6427
+ });
6428
+ recover.addCommand(annotate(new Command("run"), { effects: LOCAL_WRITE, examples: [`${command} store recover run`] }).summary("rebuild a damaged store from every row it can read").description("copy every readable row into a new file with the sqlite3 program, rebuild the search indexes, mentions and vector index, check it, and put it in place of the store; the damaged file is kept beside it. Refuses while a WireCat timer or process has the store").action(async function() {
6429
+ const output = outputFor(this);
6430
+ const answer = await storeRecoveryRun(environmentOf(this).env ?? process.env, {
6431
+ command,
6432
+ ...version ? { version } : {},
6433
+ note: /* @__PURE__ */ __name((text) => output.renderer.note(text), "note")
6434
+ });
6435
+ renderAnswer(this, output, itemOf(snakeKeys(answer)));
6436
+ if (output.format === "pretty")
6437
+ for (const line of recoveryNotes(answer))
6438
+ output.renderer.note(line);
6439
+ }));
6440
+ return recover;
6441
+ }, "storeRecoverCommand");
6442
+
6443
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5890
6444
  var pendingIfKnown = /* @__PURE__ */ __name((database) => database.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'normalized_text'").get() ? pendingNormalization(database) : null, "pendingIfKnown");
5891
- var bytesOf = /* @__PURE__ */ __name((path) => existsSync2(path) ? statSync2(path).size : 0, "bytesOf");
6445
+ var bytesOf = /* @__PURE__ */ __name((path) => existsSync4(path) ? statSync3(path).size : 0, "bytesOf");
5892
6446
  var messageOf = /* @__PURE__ */ __name((error) => error instanceof Error ? error.message : String(error), "messageOf");
5893
6447
  var contentsOf = /* @__PURE__ */ __name((database, version, writable) => version > 0 && writable ? {
5894
6448
  rows: rowCounts(database),
@@ -5899,7 +6453,7 @@ var contentsOf = /* @__PURE__ */ __name((database, version, writable) => version
5899
6453
  } : { rows: {}, pendingNormalization: null, wordIndex: null, stemIndex: null }, "contentsOf");
5900
6454
  var storeInfo = /* @__PURE__ */ __name(async (env) => {
5901
6455
  const path = storePath(env);
5902
- if (!existsSync2(path))
6456
+ if (!existsSync4(path))
5903
6457
  return snakeKeys({ path, exists: false, schema: compatibilityOf(void 0) });
5904
6458
  let schema = compatibilityOf(void 0);
5905
6459
  try {
@@ -5932,7 +6486,7 @@ var storeInfoCommand = /* @__PURE__ */ __name(() => annotate(new Command("info")
5932
6486
  renderAnswer(this, outputFor(this), itemOf(answer));
5933
6487
  }), "storeInfoCommand");
5934
6488
 
5935
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/password.js
6489
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/password.js
5936
6490
  var ENCRYPT_OPTION = [
5937
6491
  "--encrypt",
5938
6492
  "compress and encrypt with a password, typed at a hidden prompt or piped on stdin; it is never kept \u2014 lose it and the file cannot be opened"
@@ -5951,9 +6505,9 @@ var passwordOf = /* @__PURE__ */ __name(async (command, { twice }) => {
5951
6505
  return password;
5952
6506
  }, "passwordOf");
5953
6507
 
5954
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/rules.js
5955
- import { existsSync as existsSync3, readFileSync } from "node:fs";
5956
- import { join } from "node:path";
6508
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/rules.js
6509
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
6510
+ import { join as join2 } from "node:path";
5957
6511
  var REPLY_ACTIONS = ["reply", "task"];
5958
6512
  var REPLY_MODELS = ["fill-only", "may-reword"];
5959
6513
  var REPLY_KINDS = ["dialog", "group"];
@@ -6039,7 +6593,7 @@ var defaultRule = /* @__PURE__ */ __name((id) => ({
6039
6593
  reply: { template: "", asReply: true },
6040
6594
  limits: { perChat: "1/1d", perPerson: "1/1d" }
6041
6595
  }), "defaultRule");
6042
- var repliesPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies.json`), "repliesPathFor");
6596
+ var repliesPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join2(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies.json`), "repliesPathFor");
6043
6597
  var EVERYONE = { reply: "all", allow: { people: [], chats: [] }, deny: { people: [], chats: [] } };
6044
6598
  var outsideAudience = /* @__PURE__ */ __name((audience, person, chat) => {
6045
6599
  if (person !== null && audience.deny.people.includes(person))
@@ -6069,11 +6623,11 @@ var readReplies = /* @__PURE__ */ __name((path, provider) => {
6069
6623
  return parseReplies(readRepliesFile(path, provider), path, provider);
6070
6624
  }, "readReplies");
6071
6625
  var readRepliesFile = /* @__PURE__ */ __name((path, provider) => {
6072
- if (!existsSync3(path))
6626
+ if (!existsSync5(path))
6073
6627
  return { audience: structuredClone(EVERYONE), rules: [] };
6074
6628
  let parsed;
6075
6629
  try {
6076
- parsed = JSON.parse(readFileSync(path, "utf8"));
6630
+ parsed = JSON.parse(readFileSync2(path, "utf8"));
6077
6631
  } catch (error) {
6078
6632
  throw broken(path, error instanceof Error ? error.message : String(error));
6079
6633
  }
@@ -6122,9 +6676,9 @@ var problem = /* @__PURE__ */ __name((issue) => {
6122
6676
  }, "problem");
6123
6677
  var broken = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the reply rules ${path} cannot be read (${why}) \u2014 fix the file`), "broken");
6124
6678
 
6125
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/state.js
6126
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
6127
- import { join as join2 } from "node:path";
6679
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/state.js
6680
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
6681
+ import { join as join3 } from "node:path";
6128
6682
  var ANSWERED_KEPT = 1e3;
6129
6683
  var times = record(string(), array(string()));
6130
6684
  var stateFile = object({
@@ -6136,13 +6690,13 @@ var stateFile = object({
6136
6690
  });
6137
6691
  var emptyState = /* @__PURE__ */ __name(() => ({ paused: false, answered: [], sent: {} }), "emptyState");
6138
6692
  var answeredKey = /* @__PURE__ */ __name((message) => `${message.chatId}:${message.id}`, "answeredKey");
6139
- var repliesStatePathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join2(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, `${profile}.replies-state.json`), "repliesStatePathFor");
6693
+ var repliesStatePathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join3(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, `${profile}.replies-state.json`), "repliesStatePathFor");
6140
6694
  var readRepliesState = /* @__PURE__ */ __name((path) => {
6141
- if (!existsSync4(path))
6695
+ if (!existsSync6(path))
6142
6696
  return emptyState();
6143
6697
  let parsed;
6144
6698
  try {
6145
- parsed = JSON.parse(readFileSync2(path, "utf8"));
6699
+ parsed = JSON.parse(readFileSync3(path, "utf8"));
6146
6700
  } catch (error) {
6147
6701
  throw broken2(path, error instanceof Error ? error.message : String(error));
6148
6702
  }
@@ -6175,7 +6729,7 @@ var recordReply = /* @__PURE__ */ __name((state, rule2, message, now) => {
6175
6729
  }, "recordReply");
6176
6730
  var broken2 = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the reply state ${path} cannot be read (${why}) \u2014 fix or move the file`), "broken");
6177
6731
 
6178
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/decide.js
6732
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/decide.js
6179
6733
  var skip = /* @__PURE__ */ __name((why) => ({ skip: why }), "skip");
6180
6734
  var decide = /* @__PURE__ */ __name((rule2, incoming, state, now) => {
6181
6735
  const { message, chat, owner, sender } = incoming;
@@ -6281,7 +6835,7 @@ var filled = /* @__PURE__ */ __name((template2, senderName) => {
6281
6835
  return template2.replaceAll("{firstName}", name.split(/\s+/)[0] ?? name).replaceAll("{name}", name);
6282
6836
  }, "filled");
6283
6837
 
6284
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/template.js
6838
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/template.js
6285
6839
  var import_liquidjs = __toESM(require_liquid_node(), 1);
6286
6840
  var TEMPLATE_LIMITS = {
6287
6841
  parse: 32768,
@@ -6441,7 +6995,7 @@ var renderReplyTemplate = /* @__PURE__ */ __name(async (reply, input) => {
6441
6995
  }
6442
6996
  }, "renderReplyTemplate");
6443
6997
 
6444
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/dry-run.js
6998
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/dry-run.js
6445
6999
  var DRY_RUN_DAYS = 7;
6446
7000
  var PAGE = 500;
6447
7001
  var dryRun = /* @__PURE__ */ __name(async (store, account, rules, { since, until = Date.now(), only, audience, render }) => {
@@ -6555,7 +7109,7 @@ var storedSince = /* @__PURE__ */ __name(async (store, account, chat, since) =>
6555
7109
  }
6556
7110
  }, "storedSince");
6557
7111
 
6558
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/embeddings/keys.js
7112
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/embeddings/keys.js
6559
7113
  var endpointKeyName = /* @__PURE__ */ __name((baseUrl) => {
6560
7114
  const host = new URL(baseUrl).host;
6561
7115
  return ["openai", "anthropic"].includes(host) ? `endpoint:${host}` : host;
@@ -6586,7 +7140,7 @@ var embeddingKeys = /* @__PURE__ */ __name((app, env = process.env, keyring) =>
6586
7140
  };
6587
7141
  }, "embeddingKeys");
6588
7142
 
6589
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/models/openai.js
7143
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/models/openai.js
6590
7144
  var options = strictObject({
6591
7145
  temperature: range(0, 2),
6592
7146
  top_p: range(0, 1),
@@ -6600,7 +7154,7 @@ var openai = {
6600
7154
  images: true,
6601
7155
  baseUrl: "https://api.openai.com/v1",
6602
7156
  validate: /* @__PURE__ */ __name((given) => checkedOptions("openai", options, given), "validate"),
6603
- complete: /* @__PURE__ */ __name(async (target, request, checked, apiKey, fetcher) => {
7157
+ complete: /* @__PURE__ */ __name((target, request, checked, apiKey, fetcher) => withTimeLimit(12e4, async (deadline) => {
6604
7158
  const response = await fetcher(`${target.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
6605
7159
  method: "POST",
6606
7160
  headers: { "Content-Type": "application/json", ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
@@ -6622,7 +7176,7 @@ var openai = {
6622
7176
  ],
6623
7177
  ...new URL(target.baseUrl).hostname === "api.openai.com" ? { max_completion_tokens: request.maxTokens } : { max_tokens: request.maxTokens }
6624
7178
  }),
6625
- signal: AbortSignal.timeout(12e4),
7179
+ signal: deadline,
6626
7180
  redirect: "error"
6627
7181
  });
6628
7182
  if (!response.ok)
@@ -6632,10 +7186,10 @@ var openai = {
6632
7186
  if (choice?.finish_reason !== "stop" || typeof choice.message?.content !== "string" || !Number.isInteger(body.usage?.total_tokens) || (body.usage?.total_tokens ?? 0) < 1)
6633
7187
  throw new Error("incomplete response");
6634
7188
  return { text: choice.message.content, tokens: body.usage?.total_tokens };
6635
- }, "complete")
7189
+ }), "complete")
6636
7190
  };
6637
7191
 
6638
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/models/index.js
7192
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/models/index.js
6639
7193
  var modelGateway = /* @__PURE__ */ __name((deps) => ({
6640
7194
  complete: /* @__PURE__ */ __name(async (request) => {
6641
7195
  if (deps.signal?.aborted)
@@ -6650,7 +7204,7 @@ var modelGateway = /* @__PURE__ */ __name((deps) => ({
6650
7204
  if (!adapter && target.provider === "openai")
6651
7205
  adapter = openai;
6652
7206
  if (!adapter && target.provider === "anthropic")
6653
- adapter = (await import("./anthropic-QKIPHV2Z.js")).anthropic;
7207
+ adapter = (await import("./anthropic-NTASPJYE.js")).anthropic;
6654
7208
  if (!adapter)
6655
7209
  throw new CliError("validation_error", `no model adapter for ${target.provider}`);
6656
7210
  if (request.images !== void 0 && adapter.images !== true)
@@ -6691,19 +7245,19 @@ var modelGateway = /* @__PURE__ */ __name((deps) => ({
6691
7245
  }, "complete")
6692
7246
  }), "modelGateway");
6693
7247
 
6694
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/consents.js
6695
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
6696
- import { join as join3 } from "node:path";
7248
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/consents.js
7249
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
7250
+ import { join as join4 } from "node:path";
6697
7251
  var shape = strictObject({
6698
7252
  provider: nullable(pipe(string(), minLength(1))),
6699
7253
  deniedChats: array(pipe(string(), minLength(1)))
6700
7254
  });
6701
- var replyConsentPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join3(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies-consents.json`), "replyConsentPathFor");
7255
+ var replyConsentPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join4(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies-consents.json`), "replyConsentPathFor");
6702
7256
  var readReplyConsent = /* @__PURE__ */ __name((path) => {
6703
- if (!existsSync5(path))
7257
+ if (!existsSync7(path))
6704
7258
  return { provider: null, deniedChats: [] };
6705
7259
  try {
6706
- return parse(shape, JSON.parse(readFileSync3(path, "utf8")));
7260
+ return parse(shape, JSON.parse(readFileSync4(path, "utf8")));
6707
7261
  } catch {
6708
7262
  throw new CliError("configuration_error", "reply model consent is invalid; fix its file before granting consent");
6709
7263
  }
@@ -6716,7 +7270,7 @@ var mayModelReply = /* @__PURE__ */ __name((path, provider, chat) => {
6716
7270
  return consent.provider === provider && !consent.deniedChats.includes(chat);
6717
7271
  }, "mayModelReply");
6718
7272
 
6719
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/rendering.js
7273
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/rendering.js
6720
7274
  var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, options2 = {
6721
7275
  ai: true
6722
7276
  }) => async (rule2, message, chat, now) => {
@@ -6763,7 +7317,7 @@ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, o
6763
7317
  return result2;
6764
7318
  }, "replyRenderer");
6765
7319
 
6766
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/replies/serve.js
7320
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/replies/serve.js
6767
7321
  var NOT_ALLOWED = "replies.send is not allow";
6768
7322
  var NO_RULES = "no rules";
6769
7323
  var ONLY_TASK = "opened a task, sent nothing";
@@ -6856,7 +7410,7 @@ var replyTo = /* @__PURE__ */ __name(async (deps, message) => {
6856
7410
  return { skip: why };
6857
7411
  }, "replyTo");
6858
7412
 
6859
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-catch-up.js
7413
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-catch-up.js
6860
7414
  var START_SYNC_DELAY_MS = 3e4;
6861
7415
  var START_SYNC_BUDGET_MS = 5 * 6e4;
6862
7416
  var START_SYNC_WINDOW_MS = 7 * 864e5;
@@ -6867,8 +7421,8 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6867
7421
  let pass = Promise.resolve();
6868
7422
  let started = false;
6869
7423
  let done;
6870
- const run = /* @__PURE__ */ __name(async () => {
6871
- const stop = AbortSignal.any([controller.signal, AbortSignal.timeout(budgetMs)]);
7424
+ const run = /* @__PURE__ */ __name(() => withTimeLimit(budgetMs, (deadline) => catchUp(AbortSignal.any([controller.signal, deadline]))), "run");
7425
+ const catchUp = /* @__PURE__ */ __name(async (stop) => {
6872
7426
  const floor = now() - windowMs;
6873
7427
  const moved = [];
6874
7428
  for (const chat of await chats(stop)) {
@@ -6909,7 +7463,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6909
7463
  code: "start_sync",
6910
7464
  text: `caught up ${summary.fetched} message(s) in ${summary.chats} chat(s) that moved while serve was down` + (summary.stopped ? ` \u2014 stopped at the time limit, ${behind.length - summary.chats - summary.failed} left` : "")
6911
7465
  });
6912
- }, "run");
7466
+ }, "catchUp");
6913
7467
  return {
6914
7468
  start: /* @__PURE__ */ __name(() => {
6915
7469
  if (started || controller.signal.aborted)
@@ -6933,7 +7487,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6933
7487
  };
6934
7488
  }, "startSync");
6935
7489
 
6936
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-members.js
7490
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-members.js
6937
7491
  var FIRST_FETCH_MS = 6e4;
6938
7492
  var DAY_MS = 864e5;
6939
7493
  var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, firstMs = FIRST_FETCH_MS, everyMs = DAY_MS }) => {
@@ -6987,7 +7541,7 @@ var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, fi
6987
7541
  };
6988
7542
  }, "memberFetches");
6989
7543
 
6990
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-notice.js
7544
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-notice.js
6991
7545
  var record2 = /* @__PURE__ */ __name((context, app, severity, attributes) => recordLogFor(context.streams.diagnostic, app, { command: currentRun().command || "serve" })[severity](attributes), "record");
6992
7546
  var noticeFor = /* @__PURE__ */ __name((context, app, severity = "warn") => ({ text, ...attributes }) => {
6993
7547
  if (context.format === "pretty") {
@@ -7020,7 +7574,7 @@ var recordDiagnostics = /* @__PURE__ */ __name((context, app) => {
7020
7574
  return context;
7021
7575
  }, "recordDiagnostics");
7022
7576
 
7023
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-stems.js
7577
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-stems.js
7024
7578
  var STEMS_EVERY_MS = 3e4;
7025
7579
  var STEMS_SLICE_MS = 2e3;
7026
7580
  var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY_MS, sliceMs = STEMS_SLICE_MS }) => {
@@ -7060,7 +7614,7 @@ var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY
7060
7614
  };
7061
7615
  }, "stemFills");
7062
7616
 
7063
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/render/messages.js
7617
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/render/messages.js
7064
7618
  import { styleText } from "node:util";
7065
7619
  var TIME_WIDTH = 8;
7066
7620
  var INDENT = " ".repeat(TIME_WIDTH + 2);
@@ -7236,7 +7790,7 @@ var editedAt = /* @__PURE__ */ __name((message, options2) => {
7236
7790
  return day(edited) === day(message.timestamp) ? time : `${day(edited)} ${time}`;
7237
7791
  }, "editedAt");
7238
7792
 
7239
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/message-items.js
7793
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/message-items.js
7240
7794
  var defined = /* @__PURE__ */ __name((value) => Object.fromEntries(Object.entries(value).filter(([, one]) => one !== void 0)), "defined");
7241
7795
  var attachmentItem = /* @__PURE__ */ __name((attachment) => defined({
7242
7796
  kind: attachment.kind,
@@ -7331,7 +7885,7 @@ var viewOf = /* @__PURE__ */ __name((context, messenger) => ({
7331
7885
  locale: messenger.app.locale
7332
7886
  }), "viewOf");
7333
7887
 
7334
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-answers.js
7888
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-answers.js
7335
7889
  var observed = /* @__PURE__ */ __name((value) => ({
7336
7890
  value: value.value,
7337
7891
  observed_at: value.observedAt,
@@ -7398,7 +7952,7 @@ var watchEventItem = /* @__PURE__ */ __name((value, account) => {
7398
7952
  }
7399
7953
  }, "watchEventItem");
7400
7954
 
7401
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-command.js
7955
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-command.js
7402
7956
  var watchCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("watch"), {
7403
7957
  output: { entity: "watch_item" },
7404
7958
  effects: REMOTE_READ,
@@ -7553,7 +8107,7 @@ var describe = /* @__PURE__ */ __name((event, render) => {
7553
8107
  }
7554
8108
  }, "describe");
7555
8109
 
7556
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-command.js
8110
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-command.js
7557
8111
  var serveCommand = /* @__PURE__ */ __name((messenger) => {
7558
8112
  const command = annotate(new Command("serve"), {
7559
8113
  output: { entity: "serve_summary" },
@@ -7817,8 +8371,8 @@ var tasking = /* @__PURE__ */ __name((context, warn) => {
7817
8371
  };
7818
8372
  }, "tasking");
7819
8373
 
7820
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/store-tables-command.js
7821
- import { existsSync as existsSync6 } from "node:fs";
8374
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/store-tables-command.js
8375
+ import { existsSync as existsSync8 } from "node:fs";
7822
8376
  var PATH = "store tables list";
7823
8377
  var STORE_TABLES_QUERY = {
7824
8378
  entity: "store_table",
@@ -7847,7 +8401,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
7847
8401
  const filter = filterOf(words);
7848
8402
  const { full } = this.optsWithGlobals();
7849
8403
  const path = storePath(environmentOf(this).env ?? process.env);
7850
- if (!existsSync6(path))
8404
+ if (!existsSync8(path))
7851
8405
  throw new CliError("not_found", `no store at ${path}`);
7852
8406
  const items = await readStoreTables(path, { filter, sizes: full === true });
7853
8407
  renderAnswer(this, outputFor(this), listOf(PATH, {
@@ -7860,7 +8414,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
7860
8414
  return tables;
7861
8415
  }, "storeTablesCommand");
7862
8416
 
7863
- // node_modules/.pnpm/@wirecat+cli-core@0.567.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.77.1_commander@15._f1cdf35b93ce465cee2c32ebaca13ce7/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
8417
+ // node_modules/.pnpm/@wirecat+cli-core@0.608.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._981e87e6afb3f510e9b2b59ded3c7286/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
7864
8418
  var SEARCH_INDEXES = ["messages_fts", "chats_fts", "identities_fts"];
7865
8419
  var WORD_INDEX = "message_words";
7866
8420
  var schemaOf = /* @__PURE__ */ __name((database) => {
@@ -7869,7 +8423,7 @@ var schemaOf = /* @__PURE__ */ __name((database) => {
7869
8423
  }, "schemaOf");
7870
8424
  var count2 = /* @__PURE__ */ __name((database, table) => Number(database.prepare(`SELECT count(*) AS n FROM ${table}`).get()?.n ?? 0), "count");
7871
8425
  var pendingIfKnown2 = /* @__PURE__ */ __name((database) => database.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'normalized_text'").get() ? pendingNormalization(database) : null, "pendingIfKnown");
7872
- var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync7(path) ? statSync3(path).size : 0, "bytesOf");
8426
+ var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync9(path) ? statSync4(path).size : 0, "bytesOf");
7873
8427
  var reading = /* @__PURE__ */ __name(async (path, read) => {
7874
8428
  const database = await openCache(path);
7875
8429
  try {
@@ -7886,24 +8440,59 @@ var readingOnly = /* @__PURE__ */ __name(async (path, read) => {
7886
8440
  database.close();
7887
8441
  }
7888
8442
  }, "readingOnly");
7889
- var storeSummary = /* @__PURE__ */ __name(async (env) => {
8443
+ var withoutInode = /* @__PURE__ */ __name(({ inode: _, ...mark }) => mark, "withoutInode");
8444
+ var fileSchema = /* @__PURE__ */ __name(async (path) => {
8445
+ try {
8446
+ return await readingOnly(path, (database) => fileSchemaOf(database).version);
8447
+ } catch {
8448
+ return null;
8449
+ }
8450
+ }, "fileSchema");
8451
+ var storeSummary = /* @__PURE__ */ __name(async (env, { deep = false, command, version } = {}) => {
7890
8452
  const path = storePath(env);
7891
- if (!existsSync7(path))
8453
+ if (!existsSync9(path))
7892
8454
  return { path, exists: false };
8455
+ const checked = await storeHealth(path, { deep });
8456
+ const recorded = deep ? recordDeepCheck(path, checked, {
8457
+ cli: command ?? "unknown",
8458
+ ...version ? { version } : {},
8459
+ schema: await fileSchema(path)
8460
+ }) : null;
8461
+ const mark = readDamageMark(path);
8462
+ const lastKnownGood = readHealthMark(path)?.last_ok_at ?? null;
8463
+ const health = {
8464
+ checked: checked.checked,
8465
+ covers: deep ? "every page and every search index" : QUICK_HEALTH_CHECKS,
8466
+ ok: checked.ok,
8467
+ ms: checked.ms,
8468
+ ...checked.problems ? { problems: checked.problems } : {},
8469
+ ...checked.damagedTables?.length ? { damagedTables: checked.damagedTables } : {},
8470
+ ...checked.invalidJson?.length ? { invalidJson: checked.invalidJson } : {},
8471
+ ...checked.searchIndexes?.some((index) => !index.ok) ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) } : {}
8472
+ };
8473
+ const damage = command ? explainDamage(checked, command, mark) : null;
8474
+ const healthOf = {
8475
+ health,
8476
+ lastKnownGood,
8477
+ ...mark ? { damageMark: withoutInode(mark) } : {},
8478
+ ...recorded?.cleared ? { damageMarkCleared: withoutInode(recorded.cleared) } : {},
8479
+ ...damage ? { damage } : {}
8480
+ };
7893
8481
  try {
7894
8482
  return await reading(path, (database) => {
7895
- const { version, writable } = schemaOf(database);
8483
+ const { version: version2, writable } = schemaOf(database);
7896
8484
  return {
7897
8485
  path,
7898
8486
  exists: true,
7899
- schema: version,
8487
+ schema: version2,
7900
8488
  speaks: SPEAKS,
7901
8489
  writable,
7902
- ...version > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {}
8490
+ ...version2 > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {},
8491
+ ...healthOf
7903
8492
  };
7904
8493
  });
7905
8494
  } catch (error) {
7906
- return { path, exists: true, error: messageOf2(error) };
8495
+ return { path, exists: true, error: messageOf2(error), ...healthOf };
7907
8496
  }
7908
8497
  }, "storeSummary");
7909
8498
  var result = /* @__PURE__ */ __name((command, value, next = []) => renderAnswer(command, outputFor(command), itemOf(snakeKeys(value), { next })), "result");
@@ -7918,7 +8507,8 @@ var storeMaintenanceCommands = /* @__PURE__ */ __name((messenger) => [
7918
8507
  repairCommand(messenger),
7919
8508
  resetCommand(messenger),
7920
8509
  copiesCommand(),
7921
- storeTablesCommand(messenger)
8510
+ storeTablesCommand(messenger),
8511
+ storeRecoverCommand({ command: messenger.app.command, version: messenger.app.version })
7922
8512
  ], "storeMaintenanceCommands");
7923
8513
  var refuseWhileServing = /* @__PURE__ */ __name((command, messenger) => {
7924
8514
  const serving = servingProfiles(messenger.app, environmentOf(command).env ?? process.env);
@@ -7930,7 +8520,7 @@ var repairCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("
7930
8520
  const { renderer, format } = outputFor(this);
7931
8521
  const { dryRun: dryRun2 } = this.opts();
7932
8522
  const path = storePath(environmentOf(this).env ?? process.env);
7933
- if (!existsSync7(path)) {
8523
+ if (!existsSync9(path)) {
7934
8524
  result(this, { path, exists: false });
7935
8525
  return;
7936
8526
  }
@@ -7970,7 +8560,7 @@ var notesOf = /* @__PURE__ */ __name((report, command) => {
7970
8560
  }, "notesOf");
7971
8561
  var copiesCommand = /* @__PURE__ */ __name(() => new Command("copies").description("the tables `store repair` kept as copies").addCommand(annotate(new Command("delete"), { output: { entity: "store_copy_removal" }, effects: LOCAL_WRITE }).description("delete one copy `store repair` kept, named exactly; refuses any other table").argument("<name>", "the copy's name, as `store repair` printed it").action(async function(name) {
7972
8562
  const path = storePath(environmentOf(this).env ?? process.env);
7973
- if (!existsSync7(path))
8563
+ if (!existsSync9(path))
7974
8564
  throw new CliError("not_found", `no store at ${path}`);
7975
8565
  const deleted = await reading(path, (database) => deleteCopy(database, name));
7976
8566
  result(this, { path, deleted });
@@ -7978,7 +8568,7 @@ var copiesCommand = /* @__PURE__ */ __name(() => new Command("copies").descripti
7978
8568
  var checkCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("check"), { output: { entity: "store_check" }, effects: LOCAL_READ }).summary("check the local archive for problems").description("whether the store is healthy \u2014 integrity, search indexes, disk, and which chats are behind").action(async function() {
7979
8569
  const { renderer } = outputFor(this);
7980
8570
  const path = storePath(environmentOf(this).env ?? process.env);
7981
- if (!existsSync7(path)) {
8571
+ if (!existsSync9(path)) {
7982
8572
  result(this, { path, exists: false, ok: true });
7983
8573
  return;
7984
8574
  }
@@ -8041,7 +8631,7 @@ var inspect = /* @__PURE__ */ __name((path) => reading(path, (database) => {
8041
8631
  ...schema.version > 0 ? [["attachment_words", indexIntegrity(database, "attachment_words", 0)]] : []
8042
8632
  ]);
8043
8633
  const size = bytesOf2(path) + bytesOf2(`${path}-wal`);
8044
- const { bavail, bsize } = statfsSync(dirname(path));
8634
+ const { bavail, bsize } = statfsSync2(dirname2(path));
8045
8635
  const free = Number(bavail) * Number(bsize);
8046
8636
  const behind = schema.version > 0 ? chatsBehind(database) : [];
8047
8637
  const vectorIndexes = schema.version >= 34 ? vectorIndexCounts(database) : [];
@@ -8129,14 +8719,18 @@ var chatsBehind = /* @__PURE__ */ __name((database) => database.prepare(`SELECT
8129
8719
  var migrateCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("migrate"), { output: { entity: "store_migration" }, effects: LOCAL_WRITE }).summary("migrate an older local archive").description("bring the store up to this build's schema, then normalize, index and stem the messages and notes stored before it").action(async function() {
8130
8720
  const { renderer } = outputFor(this);
8131
8721
  const path = storePath(environmentOf(this).env ?? process.env);
8132
- if (!existsSync7(path)) {
8722
+ if (!existsSync9(path)) {
8133
8723
  result(this, { path, exists: false });
8134
8724
  renderer.note(`no store yet \u2014 the first \`${messenger.app.command}\` command that reads a chat creates it`);
8135
8725
  return;
8136
8726
  }
8137
8727
  const answer = await reading(path, (database) => {
8138
8728
  const from = schemaOf(database).version;
8139
- migrate(database, { command: messenger.app.command, version: messenger.app.version });
8729
+ migrate(database, {
8730
+ command: messenger.app.command,
8731
+ version: messenger.app.version,
8732
+ rollback: { store: path, warn: /* @__PURE__ */ __name((line) => renderer.warn(line), "warn") }
8733
+ });
8140
8734
  const { normalized, indexed, terms } = buildWordIndex(database, (note) => renderer.note(note));
8141
8735
  const stemmed = buildStems(database, (note) => renderer.note(note));
8142
8736
  const notes = buildNoteIndex(database, (note) => renderer.note(note));
@@ -8189,7 +8783,7 @@ var buildNoteIndex = /* @__PURE__ */ __name((database, note, { reset = false } =
8189
8783
  var reindexCommand = /* @__PURE__ */ __name((messenger) => destroysNothing(annotate(new Command("rebuild"), { output: { entity: "store_reindex" }, effects: LOCAL_WRITE })).summary("rebuild the local archive's search indexes").description("rebuild the word index, its typo vocabulary, the stems, the files' word index, the notes' indexes and who took part in what, from what is stored, and drop the vectors no stored text uses; loses nothing").action(async function() {
8190
8784
  const { renderer } = outputFor(this);
8191
8785
  const path = storePath(environmentOf(this).env ?? process.env);
8192
- if (!existsSync7(path)) {
8786
+ if (!existsSync9(path)) {
8193
8787
  result(this, { path, exists: false });
8194
8788
  return;
8195
8789
  }
@@ -8218,11 +8812,11 @@ var reindexCommand = /* @__PURE__ */ __name((messenger) => destroysNothing(annot
8218
8812
  result(this, answer);
8219
8813
  }), "reindexCommand");
8220
8814
  var vacuumInto = /* @__PURE__ */ __name(async (path, target) => {
8221
- writeFileSync(target, "", { flag: "wx", mode: 384 });
8815
+ writeFileSync2(target, "", { flag: "wx", mode: 384 });
8222
8816
  try {
8223
8817
  await reading(path, (database) => database.prepare("VACUUM INTO ?").run(target));
8224
8818
  } catch (error) {
8225
- rmSync2(target, { force: true });
8819
+ rmSync3(target, { force: true });
8226
8820
  throw error;
8227
8821
  }
8228
8822
  }, "vacuumInto");
@@ -8231,9 +8825,9 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8231
8825
  const { encrypt } = this.opts();
8232
8826
  const path = storePath(environmentOf(this).env ?? process.env);
8233
8827
  const target = resolve(file2);
8234
- if (!existsSync7(path))
8828
+ if (!existsSync9(path))
8235
8829
  throw new CliError("not_found", `no store at ${path} to back up`);
8236
- if (existsSync7(target))
8830
+ if (existsSync9(target))
8237
8831
  throw new CliError("validation_error", `${target} exists \u2014 a backup never overwrites a file`);
8238
8832
  const password = encrypt ? await passwordOf(this, { twice: true }) : void 0;
8239
8833
  const copyAt = password === void 0 ? target : `${path}.backup-${process.pid}`;
@@ -8255,67 +8849,69 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8255
8849
  });
8256
8850
  } catch (error) {
8257
8851
  if (password === void 0)
8258
- rmSync2(target, { force: true });
8852
+ rmSync3(target, { force: true });
8259
8853
  throw error;
8260
8854
  } finally {
8261
8855
  if (password !== void 0)
8262
- rmSync2(copyAt, { force: true });
8856
+ rmSync3(copyAt, { force: true });
8263
8857
  }
8264
8858
  }), "backupCommand");
8265
8859
  var decryptCommand = /* @__PURE__ */ __name(() => annotate(new Command("decrypt"), { output: { entity: "store_decrypt" }, effects: LOCAL_WRITE }).description("open a file written with --encrypt into a new file; asks for its password").argument("<file>", "a file `store backup --encrypt` or `store export --encrypt` wrote").requiredOption("--output <file>", "the new file, readable only by you").action(async function(file2) {
8266
8860
  const { output } = this.opts();
8267
8861
  const from = resolve(file2);
8268
8862
  const to = resolve(output);
8269
- if (!existsSync7(from))
8863
+ if (!existsSync9(from))
8270
8864
  throw new CliError("not_found", `no file at ${from}`);
8271
8865
  if (!isSealed(from))
8272
8866
  throw new CliError("validation_error", `${from} was not written with --encrypt`);
8273
- if (existsSync7(to))
8867
+ if (existsSync9(to))
8274
8868
  throw new CliError("validation_error", `${to} exists \u2014 never overwritten`);
8275
8869
  await unsealFile(from, to, await passwordOf(this, { twice: false }));
8276
8870
  result(this, { path: to, from, bytes: bytesOf2(to) });
8277
8871
  }), "decryptCommand");
8278
- var restoreCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("restore"), { output: { entity: "store_restore" }, effects: LOCAL_WRITE }).summary("restore a backup while keeping the current store").description("put a backup in place of the store; the store it replaces is kept beside it, never deleted").argument("<file>", "a file `store backup` wrote; one written with --encrypt asks for its password").action(async function(file2) {
8872
+ var restoreCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("restore"), { output: { entity: "store_restore" }, effects: LOCAL_WRITE }).summary("restore a backup and keep the current store, or roll back a breaking upgrade").description("put a backup in place of the store; the store it replaces is kept beside it, never deleted. Given a rollback copy (backups/<store>-rollback-schema-<version>-<time>.db, kept for a day before an upgrade older tools cannot open), put its tables back in the store and return it to that version instead").argument("<file>", "a file `store backup` wrote, or a rollback copy; one written with --encrypt asks for its password").action(async function(file2) {
8279
8873
  const path = storePath(environmentOf(this).env ?? process.env);
8280
8874
  const given = resolve(file2);
8281
- if (!existsSync7(given))
8875
+ if (!existsSync9(given))
8282
8876
  throw new CliError("not_found", `no file at ${given}`);
8283
8877
  refuseWhileServing(this, messenger);
8284
8878
  if (!isSealed(given))
8285
8879
  return restoreFrom(this, messenger, given, given);
8286
8880
  const opened = `${path}.unsealing-${process.pid}`;
8287
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8881
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
8288
8882
  try {
8289
8883
  await unsealFile(given, opened, await passwordOf(this, { twice: false }));
8290
8884
  await restoreFrom(this, messenger, opened, given);
8291
8885
  } finally {
8292
- rmSync2(opened, { force: true });
8886
+ rmSync3(opened, { force: true });
8293
8887
  }
8294
8888
  }), "restoreCommand");
8295
8889
  var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, given) => {
8296
8890
  const { renderer } = outputFor(command);
8297
8891
  const path = storePath(environmentOf(command).env ?? process.env);
8298
- if (existsSync7(path) && realpathSync(backup) === realpathSync(path)) {
8892
+ if (existsSync9(path) && realpathSync2(backup) === realpathSync2(path)) {
8299
8893
  throw new CliError("validation_error", `${backup} is the store itself`);
8300
8894
  }
8895
+ if (await isRollbackCopy(backup))
8896
+ return rollBackFrom(command, messenger, backup);
8301
8897
  const schema = await backupSchema(backup);
8302
8898
  const stamp = stampNow();
8303
- const kept = existsSync7(path) ? `${path}.before-restore-${stamp}` : null;
8899
+ const kept = existsSync9(path) ? `${path}.before-restore-${stamp}` : null;
8304
8900
  if (kept) {
8305
8901
  const waitMs = environmentOf(command).storeLockWaitMs;
8306
8902
  await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8307
8903
  } else
8308
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8904
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
8309
8905
  const incoming = `${path}.restoring-${stamp}`;
8310
8906
  copyFileSync(backup, incoming, constants.COPYFILE_EXCL);
8311
8907
  chmodSync(incoming, 384);
8312
8908
  if (kept) {
8313
- renameSync2(path, kept);
8909
+ renameSync3(path, kept);
8314
8910
  for (const suffix of ["-wal", "-shm"])
8315
- if (existsSync7(`${path}${suffix}`))
8316
- renameSync2(`${path}${suffix}`, `${kept}${suffix}`);
8911
+ if (existsSync9(`${path}${suffix}`))
8912
+ renameSync3(`${path}${suffix}`, `${kept}${suffix}`);
8317
8913
  }
8318
- renameSync2(incoming, path);
8914
+ renameSync3(incoming, path);
8319
8915
  result(command, { path, restoredFrom: given, keptAt: kept, schema: schema.version });
8320
8916
  if (kept)
8321
8917
  renderer.note(`the store it replaced is kept at ${kept}`);
@@ -8324,6 +8920,43 @@ var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, give
8324
8920
  renderer.note(`the backup is behind this build; the next command migrates it \u2014 \`${lineOf(command, "store migrate")}\` now`);
8325
8921
  }
8326
8922
  }, "restoreFrom");
8923
+ var isRollbackCopy = /* @__PURE__ */ __name(async (file2) => {
8924
+ try {
8925
+ return await readingOnly(file2, (database) => database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'rollback_meta'").get() !== void 0);
8926
+ } catch {
8927
+ return false;
8928
+ }
8929
+ }, "isRollbackCopy");
8930
+ var rollBackFrom = /* @__PURE__ */ __name(async (command, messenger, copy) => {
8931
+ const { renderer } = outputFor(command);
8932
+ const path = storePath(environmentOf(command).env ?? process.env);
8933
+ if (!existsSync9(path))
8934
+ throw new CliError("not_found", `no store at ${path} to roll back`);
8935
+ const waitMs = environmentOf(command).storeLockWaitMs;
8936
+ await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8937
+ const { database } = await openSqlite(path);
8938
+ let rolled;
8939
+ try {
8940
+ rolled = rollBack(database, copy);
8941
+ } finally {
8942
+ database.close();
8943
+ }
8944
+ result(command, {
8945
+ path,
8946
+ restoredFrom: copy,
8947
+ rolledBack: true,
8948
+ schema: rolled.from,
8949
+ was: rolled.was,
8950
+ tables: rolled.restored,
8951
+ rebuilt: rolled.rebuilt,
8952
+ foreignKeyViolations: rolled.foreignKeyViolations
8953
+ });
8954
+ const taken = new Date(rolled.createdAt).toISOString();
8955
+ renderer.note(`the store is back at schema ${rolled.from}; ${rolled.tables.length > 0 ? rolled.tables.join(", ") : "no table"} hold what they held at ${taken}, and what was written to them since is not kept`);
8956
+ renderer.note("open it with the older tool and run its `store rebuild`: the search indexes are behind the tables");
8957
+ renderer.note(`a tool that speaks schema ${rolled.to} or later migrates it again on its next run`);
8958
+ renderer.note("restart every serve and mcp of either CLI that was running, so they read the restored store");
8959
+ }, "rollBackFrom");
8327
8960
  var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8328
8961
  let read;
8329
8962
  try {
@@ -8347,7 +8980,7 @@ var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8347
8980
  var STORE_LOCK_WAIT_MS = 1e3;
8348
8981
  var quiesce = /* @__PURE__ */ __name(async (path, messenger, then, warn, waitMs = STORE_LOCK_WAIT_MS) => {
8349
8982
  const { command } = messenger.app;
8350
- const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync7(file2)).map((file2) => realpathSync(file2));
8983
+ const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync9(file2)).map((file2) => realpathSync2(file2));
8351
8984
  const holders = holdersOf(files);
8352
8985
  if (holders === void 0) {
8353
8986
  warn(`this system cannot say which processes have the store open \u2014 restart every running serve and mcp after this`);
@@ -8373,7 +9006,7 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8373
9006
  const { command } = messenger.app;
8374
9007
  const env = environmentOf(this).env ?? process.env;
8375
9008
  const path = storePath(env);
8376
- if (!existsSync7(path)) {
9009
+ if (!existsSync9(path)) {
8377
9010
  result(this, { path, exists: false, reset: false });
8378
9011
  renderer.note(`no store at ${path} \u2014 nothing to reset; the first \`${command}\` command that reads a chat creates it`);
8379
9012
  return;
@@ -8409,17 +9042,17 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8409
9042
  });
8410
9043
  renderer.note(`backed the store up to ${backup}`);
8411
9044
  }
8412
- for (const suffix of STORE_PARTS)
8413
- rmSync2(`${path}${suffix}`, { force: true });
9045
+ for (const suffix of STORE_PARTS2)
9046
+ rmSync3(`${path}${suffix}`, { force: true });
8414
9047
  await (await openStore({ path, command })).close();
8415
9048
  const schema = await reading(path, (database) => schemaOf(database).version);
8416
9049
  result(this, { path, exists: true, reset: true, backup, backedUp, schema });
8417
9050
  renderer.note(backup ? `the store is empty at schema ${schema}; \`${command} store restore ${backup}\` puts the old one back once a build can read it` : `the store is empty at schema ${schema}; there is no backup`);
8418
9051
  }), "resetCommand");
8419
- var STORE_PARTS = ["", "-wal", "-shm"];
9052
+ var STORE_PARTS2 = ["", "-wal", "-shm"];
8420
9053
  var resetPreview = /* @__PURE__ */ __name(async (path, messenger, env, keep) => {
8421
- const files = STORE_PARTS.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync7(file2));
8422
- const holders = holdersOf(files.map((file2) => realpathSync(file2)));
9054
+ const files = STORE_PARTS2.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync9(file2));
9055
+ const holders = holdersOf(files.map((file2) => realpathSync2(file2)));
8423
9056
  const serving = servingProfiles(messenger.app, env).length > 0;
8424
9057
  const read = await readingOnly(path, (database) => ({
8425
9058
  schema: schemaOf(database).version,