@wirecat/tg-cli 0.116.0 → 0.117.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-VNQ72MBK.js} +70 -61
  7. package/dist/bundle/{all-profiles-R2UZMH24.js → all-profiles-3W2UQTCK.js} +10 -10
  8. package/dist/bundle/{anthropic-QKIPHV2Z.js → anthropic-DFUW2KTG.js} +6 -6
  9. package/dist/bundle/{app-server-AZB2MFK6.js → app-server-5XJIMLHB.js} +49 -46
  10. package/dist/bundle/{bot-api-2IM243J4.js → bot-api-HRRBF3W6.js} +49 -49
  11. package/dist/bundle/{bot-history-G6CRVCL2.js → bot-history-GBH5XE4N.js} +18 -18
  12. package/dist/bundle/{bun-JDKPISPX.js → bun-ZMOYGG6F.js} +2 -2
  13. package/dist/bundle/{bun-sqlite-X5PY5IQT.js → bun-sqlite-6FZFMA7K.js} +5 -5
  14. package/dist/bundle/{chunk-577MFPCP.js → chunk-2452HCIV.js} +3 -3
  15. package/dist/bundle/{chunk-H72UEHNG.js → chunk-2XLKZL6K.js} +34 -28
  16. package/dist/bundle/{chunk-RSDIPQXP.js → chunk-3GRX7WP6.js} +2 -2
  17. package/dist/bundle/{chunk-PPLFOIYX.js → chunk-3MQOLYAN.js} +4 -4
  18. package/dist/bundle/{chunk-JFTCOV37.js → chunk-3RJYLN5V.js} +73 -21
  19. package/dist/bundle/{chunk-BGMV66FC.js → chunk-4JDGN6OD.js} +1 -1
  20. package/dist/bundle/{chunk-MQ7MCVZV.js → chunk-56Q5JV3Z.js} +2 -2
  21. package/dist/bundle/{chunk-4IQZRW4O.js → chunk-66FZBLRJ.js} +13 -13
  22. package/dist/bundle/{chunk-QHBVGKC3.js → chunk-6GFUL4OU.js} +206 -81
  23. package/dist/bundle/{chunk-5FCONCJO.js → chunk-6HRN7BW6.js} +1 -1
  24. package/dist/bundle/{chunk-I6JF43YP.js → chunk-7NBUT62O.js} +3 -3
  25. package/dist/bundle/{chunk-VQPLHOVQ.js → chunk-7Y3RUEVY.js} +6 -6
  26. package/dist/bundle/chunk-AG6HWPQP.js +64 -0
  27. package/dist/bundle/{chunk-HK6SIIGG.js → chunk-AUBRELCM.js} +3 -3
  28. package/dist/bundle/{chunk-4D5AUWAY.js → chunk-B2YPB5AE.js} +43 -25
  29. package/dist/bundle/{chunk-EB2IULWB.js → chunk-BXTDAGM4.js} +2 -2
  30. package/dist/bundle/{chunk-QGL2UGML.js → chunk-C6TUVV7E.js} +466 -224
  31. package/dist/bundle/{chunk-42GK3XRS.js → chunk-EA2PGDER.js} +2 -2
  32. package/dist/bundle/{chunk-N6TIFJHW.js → chunk-EL6I4WTB.js} +1 -1
  33. package/dist/bundle/{chunk-76CX2YPT.js → chunk-EPCFXKTX.js} +8 -8
  34. package/dist/bundle/{chunk-Y6VWGJ4Q.js → chunk-EZTYJ43A.js} +4 -2
  35. package/dist/bundle/{chunk-T7CDLV33.js → chunk-F6KBVIJP.js} +4 -4
  36. package/dist/bundle/{chunk-PXMHBTK3.js → chunk-FAHHERJ7.js} +4 -4
  37. package/dist/bundle/{chunk-DP5LRU7K.js → chunk-FEKXHILZ.js} +1 -1
  38. package/dist/bundle/chunk-G7B5UIE7.js +182 -0
  39. package/dist/bundle/{chunk-YLRTLZF6.js → chunk-GFHNQBD2.js} +1 -1
  40. package/dist/bundle/{chunk-SD5PUYKF.js → chunk-HORGORHK.js} +12 -12
  41. package/dist/bundle/{chunk-N42VUNTO.js → chunk-HWYSRB64.js} +2 -2
  42. package/dist/bundle/{chunk-5VFPUOJO.js → chunk-HZZGOLGP.js} +11 -11
  43. package/dist/bundle/{chunk-B4UOCWM4.js → chunk-JWIUK3SK.js} +2 -2
  44. package/dist/bundle/{chunk-NL3PAFAE.js → chunk-KVTLT4V7.js} +6 -6
  45. package/dist/bundle/{chunk-KA6EGOJY.js → chunk-L5WNE4WS.js} +2 -2
  46. package/dist/bundle/{chunk-PPSUA3IZ.js → chunk-M7V5XRM6.js} +3 -3
  47. package/dist/bundle/{chunk-XQUTJITP.js → chunk-MLHKQDUN.js} +647 -129
  48. package/dist/bundle/{chunk-RSNGMNU5.js → chunk-MP7M6FFU.js} +6 -6
  49. package/dist/bundle/{chunk-5ZIBAYIZ.js → chunk-NUCDEOFC.js} +2 -2
  50. package/dist/bundle/{chunk-KV4267S4.js → chunk-P3ASN72F.js} +1 -1
  51. package/dist/bundle/{chunk-QAKL3GXB.js → chunk-PTIB7NEE.js} +1 -1
  52. package/dist/bundle/{chunk-TZVL4U7U.js → chunk-Q7O4CQDO.js} +4 -2
  53. package/dist/bundle/{chunk-XBIPSSKI.js → chunk-QOGYHU3Q.js} +4 -4
  54. package/dist/bundle/{chunk-R52RMHWF.js → chunk-RDH2QBUE.js} +3 -3
  55. package/dist/bundle/{chunk-NUYRMU56.js → chunk-RDSLSV4M.js} +2 -2
  56. package/dist/bundle/{chunk-UCSFO5GW.js → chunk-SQXB5ZUZ.js} +3 -3
  57. package/dist/bundle/{chunk-K62YATVD.js → chunk-TFBHDIGY.js} +4 -4
  58. package/dist/bundle/{chunk-IR4S7POE.js → chunk-TG6ZYL4B.js} +8 -8
  59. package/dist/bundle/{chunk-FDI4GOIP.js → chunk-UGPZCNYC.js} +329 -291
  60. package/dist/bundle/{chunk-GV7ZJ33M.js → chunk-UYK5AXSW.js} +4 -4
  61. package/dist/bundle/{chunk-HUOXUI2M.js → chunk-V2T7NYNU.js} +55 -46
  62. package/dist/bundle/{chunk-HBUJNNZD.js → chunk-V47NPSSV.js} +28 -28
  63. package/dist/bundle/{chunk-YYKJN6H5.js → chunk-VMCQGZIA.js} +1390 -690
  64. package/dist/bundle/{chunk-LXH3SKY3.js → chunk-VRDVXXXD.js} +8 -8
  65. package/dist/bundle/{chunk-YPF6OS37.js → chunk-VW6BF6M7.js} +1 -1
  66. package/dist/bundle/{chunk-LFKEKSI5.js → chunk-X3CD475M.js} +470 -234
  67. package/dist/bundle/{chunk-SKZ2E3WC.js → chunk-XW5C4TI7.js} +1 -1
  68. package/dist/bundle/{chunk-OX6EWGSG.js → chunk-YHZFGUAP.js} +19 -19
  69. package/dist/bundle/{chunk-HLNYJPAB.js → chunk-YIXXH74F.js} +2 -2
  70. package/dist/bundle/{chunk-LSKGCJWD.js → chunk-Z4QKLHJW.js} +13617 -1795
  71. package/dist/bundle/{chunk-JJMQA272.js → chunk-ZPILMEFY.js} +9 -9
  72. package/dist/bundle/command-contract-KMMHARMR.js +33 -0
  73. package/dist/bundle/{decode-W6YPTGJA.js → decode-YMSOY2AY.js} +5 -5
  74. package/dist/bundle/{dispatch-H7EFNBEH.js → dispatch-OP27MWX5.js} +8 -8
  75. package/dist/bundle/{echarts-YAWDIC5D.js → echarts-7XS55TQY.js} +2 -2
  76. package/dist/bundle/{embed-EN4UTLV5.js → embed-QTOE7NN3.js} +6 -6
  77. package/dist/bundle/{embedder-HEKHRL7E.js → embedder-KBBRYSNH.js} +9 -9
  78. package/dist/bundle/{entry-2KB6MTCG.js → entry-HGEUYYMX.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-CSGMEJXY.js} +11 -11
  81. package/dist/bundle/first-screen-K2PBNJNE.js +31 -0
  82. package/dist/bundle/{instructions-HA62QNPR.js → instructions-S6ZXCTFH.js} +1 -1
  83. package/dist/bundle/{mcp-PPVOM4SE.js → mcp-M4QN2E7R.js} +2 -2
  84. package/dist/bundle/{node-MZ2VWSQQ.js → node-LCIUWXXG.js} +2 -2
  85. package/dist/bundle/{node-sqlite-KNNS6DCM.js → node-sqlite-HL4WY4N2.js} +6 -6
  86. package/dist/bundle/{oauth-KWUABBSQ.js → oauth-U4KIMDKG.js} +7 -7
  87. package/dist/bundle/{open-JXMCYCIV.js → open-EH7OS7M7.js} +5 -5
  88. package/dist/bundle/{openai-HL3IR4VT.js → openai-W5TB3NA5.js} +14 -14
  89. package/dist/bundle/{process-K2FICLWY.js → process-3CVLTCTA.js} +1 -1
  90. package/dist/bundle/{program-IFOMT4JS.js → program-LOIZTK2P.js} +51 -51
  91. package/dist/bundle/{prompt-HVD3Q77P.js → prompt-IDNH7N3W.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-G5EWYXIF.js} +4 -4
  94. package/dist/bundle/{remote-HUAKXJCS.js → remote-4XTBZVZD.js} +7 -7
  95. package/dist/bundle/{rerank-NWFIV7OF.js → rerank-OWSTDLZN.js} +7 -7
  96. package/dist/bundle/{serve-ANUKAJJN.js → serve-YCPSEWP3.js} +9 -9
  97. package/dist/bundle/server-KELKX6S3.js +60 -0
  98. package/dist/bundle/{server-7Q7WAOHO.js → server-ODG4A2KK.js} +35 -35
  99. package/dist/bundle/{state-Y2AJ5XTP.js → state-OL2235G5.js} +6 -6
  100. package/dist/bundle/{store-S3IG5KWL.js → store-5AACYNDM.js} +15 -13
  101. package/dist/bundle/store-maintenance-command-3J7WZYVN.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-V2T7NYNU.js";
7
7
  import {
8
8
  FETCHING,
9
9
  RULES_VERSION,
@@ -22,8 +22,15 @@ import {
22
22
  servicesFor,
23
23
  syncsOneChat,
24
24
  typedQuery,
25
- withQuery
26
- } from "./chunk-FDI4GOIP.js";
25
+ withQuery,
26
+ withTimeLimit
27
+ } from "./chunk-UGPZCNYC.js";
28
+ import {
29
+ QUICK_HEALTH_CHECKS,
30
+ explainDamage,
31
+ fts5Tables,
32
+ storeHealth
33
+ } from "./chunk-G7B5UIE7.js";
27
34
  import {
28
35
  stringWidth,
29
36
  wrapAnsi
@@ -55,30 +62,35 @@ import {
55
62
  snakeKeys,
56
63
  storeTable,
57
64
  withoutProviderRefs
58
- } from "./chunk-LFKEKSI5.js";
65
+ } from "./chunk-X3CD475M.js";
59
66
  import {
60
67
  failureKey
61
- } from "./chunk-JJMQA272.js";
68
+ } from "./chunk-ZPILMEFY.js";
62
69
  import {
63
70
  envName
64
- } from "./chunk-TZVL4U7U.js";
71
+ } from "./chunk-Q7O4CQDO.js";
65
72
  import {
66
73
  holdLock,
67
74
  lockPath,
68
75
  releaseLock,
69
76
  servingProfiles,
70
77
  takeLock
71
- } from "./chunk-HK6SIIGG.js";
78
+ } from "./chunk-AUBRELCM.js";
72
79
  import {
73
80
  holdersOf
74
- } from "./chunk-N6TIFJHW.js";
81
+ } from "./chunk-EL6I4WTB.js";
75
82
  import {
83
+ CORPORA,
76
84
  MIGRATIONS,
85
+ drainCorpus,
86
+ drainMeetingIndex,
77
87
  drainNoteIndex,
78
88
  dropAllUnusedVectors,
79
89
  fileFacts,
80
90
  fillSearchIndex,
81
91
  fillStems,
92
+ fillTrigrams,
93
+ fillVectorIndexes,
82
94
  formatLocator,
83
95
  involvementStoreOver,
84
96
  migrate,
@@ -89,10 +101,12 @@ import {
89
101
  parseLocator,
90
102
  pendingNormalization,
91
103
  readStoreTables,
104
+ rebuildMentions,
92
105
  resetAttachmentWords,
93
106
  resetNoteIndex,
94
107
  resetSearchIndex,
95
108
  resetStems,
109
+ rollBack,
96
110
  rowCounts,
97
111
  searchIndexState,
98
112
  stemmerCache,
@@ -100,34 +114,34 @@ import {
100
114
  storeClients,
101
115
  storeContents,
102
116
  vectorIndexCounts
103
- } from "./chunk-LSKGCJWD.js";
117
+ } from "./chunk-Z4QKLHJW.js";
104
118
  import {
105
119
  queryFieldsOf
106
- } from "./chunk-QGL2UGML.js";
120
+ } from "./chunk-C6TUVV7E.js";
107
121
  import {
108
122
  readSecret
109
- } from "./chunk-UCSFO5GW.js";
123
+ } from "./chunk-SQXB5ZUZ.js";
110
124
  import {
111
125
  checkedOptions,
112
126
  range
113
- } from "./chunk-I6JF43YP.js";
127
+ } from "./chunk-7NBUT62O.js";
114
128
  import {
115
129
  messagesFor,
116
130
  systemFor,
117
131
  validateImages
118
- } from "./chunk-MQ7MCVZV.js";
132
+ } from "./chunk-56Q5JV3Z.js";
119
133
  import {
120
134
  storePath
121
- } from "./chunk-RSDIPQXP.js";
135
+ } from "./chunk-3GRX7WP6.js";
122
136
  import {
123
137
  openCache
124
- } from "./chunk-RSNGMNU5.js";
138
+ } from "./chunk-MP7M6FFU.js";
125
139
  import {
126
140
  Credentials,
127
141
  pathsAreOverridden,
128
142
  resolvePaths,
129
143
  writeSecurely
130
- } from "./chunk-OX6EWGSG.js";
144
+ } from "./chunk-YHZFGUAP.js";
131
145
  import {
132
146
  array,
133
147
  boolean,
@@ -151,12 +165,12 @@ import {
151
165
  transform,
152
166
  trim,
153
167
  union
154
- } from "./chunk-76CX2YPT.js";
168
+ } from "./chunk-EPCFXKTX.js";
155
169
  import {
156
170
  CliError,
157
171
  singleLine,
158
172
  visibleControls
159
- } from "./chunk-EB2IULWB.js";
173
+ } from "./chunk-BXTDAGM4.js";
160
174
  import {
161
175
  __commonJS,
162
176
  __name,
@@ -1810,7 +1824,7 @@ var require_liquid_node = __commonJS({
1810
1824
  return readFileAsync(filepath, "utf8");
1811
1825
  }
1812
1826
  __name(readFile, "readFile");
1813
- function existsSync8(filepath) {
1827
+ function existsSync10(filepath) {
1814
1828
  try {
1815
1829
  fs$1.statSync(filepath);
1816
1830
  return true;
@@ -1818,11 +1832,11 @@ var require_liquid_node = __commonJS({
1818
1832
  return false;
1819
1833
  }
1820
1834
  }
1821
- __name(existsSync8, "existsSync");
1822
- function readFileSync4(filepath) {
1835
+ __name(existsSync10, "existsSync");
1836
+ function readFileSync5(filepath) {
1823
1837
  return fs$1.readFileSync(filepath, "utf8");
1824
1838
  }
1825
- __name(readFileSync4, "readFileSync");
1839
+ __name(readFileSync5, "readFileSync");
1826
1840
  function resolve2(root, file2, ext) {
1827
1841
  if (!path.extname(file2))
1828
1842
  file2 += ext;
@@ -1836,10 +1850,10 @@ var require_liquid_node = __commonJS({
1836
1850
  }
1837
1851
  }
1838
1852
  __name(fallback, "fallback");
1839
- function dirname2(filepath) {
1853
+ function dirname3(filepath) {
1840
1854
  return path.dirname(filepath);
1841
1855
  }
1842
- __name(dirname2, "dirname");
1856
+ __name(dirname3, "dirname");
1843
1857
  var realpathAsync = promisify(fs$1.realpath);
1844
1858
  async function contains(root, file2) {
1845
1859
  try {
@@ -1867,11 +1881,11 @@ var require_liquid_node = __commonJS({
1867
1881
  __proto__: null,
1868
1882
  exists,
1869
1883
  readFile,
1870
- existsSync: existsSync8,
1871
- readFileSync: readFileSync4,
1884
+ existsSync: existsSync10,
1885
+ readFileSync: readFileSync5,
1872
1886
  resolve: resolve2,
1873
1887
  fallback,
1874
- dirname: dirname2,
1888
+ dirname: dirname3,
1875
1889
  contains,
1876
1890
  containsSync,
1877
1891
  sep: path.sep
@@ -3596,7 +3610,7 @@ var require_liquid_node = __commonJS({
3596
3610
  uri_escape,
3597
3611
  slugify
3598
3612
  });
3599
- var join4 = argumentsToValue(function(v, arg) {
3613
+ var join5 = argumentsToValue(function(v, arg) {
3600
3614
  const array2 = toArray(v);
3601
3615
  const sep = isNil(arg) ? " " : stringify(arg);
3602
3616
  let outputSize = sep.length * Math.max(array2.length - 1, 0);
@@ -3872,7 +3886,7 @@ var require_liquid_node = __commonJS({
3872
3886
  __name(sample, "sample");
3873
3887
  var arrayFilters = /* @__PURE__ */ Object.freeze({
3874
3888
  __proto__: null,
3875
- join: join4,
3889
+ join: join5,
3876
3890
  last,
3877
3891
  first,
3878
3892
  reverse,
@@ -4800,15 +4814,15 @@ var require_liquid_node = __commonJS({
4800
4814
  }
4801
4815
  *render(ctx, emitter) {
4802
4816
  const group = yield evalToken(this.group, ctx);
4803
- const fingerprint = `cycle:${group}:` + this.candidates.join(",");
4817
+ const fingerprint2 = `cycle:${group}:` + this.candidates.join(",");
4804
4818
  const groups = ctx.getRegister("cycle", {});
4805
- let idx = groups[fingerprint];
4819
+ let idx = groups[fingerprint2];
4806
4820
  if (idx === void 0) {
4807
- idx = groups[fingerprint] = 0;
4821
+ idx = groups[fingerprint2] = 0;
4808
4822
  }
4809
4823
  const candidate = this.candidates[idx];
4810
4824
  idx = (idx + 1) % this.candidates.length;
4811
- groups[fingerprint] = idx;
4825
+ groups[fingerprint2] = idx;
4812
4826
  return yield evalToken(candidate, ctx);
4813
4827
  }
4814
4828
  *arguments() {
@@ -5496,11 +5510,11 @@ var require_liquid_node = __commonJS({
5496
5510
  }
5497
5511
  });
5498
5512
 
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";
5513
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
5514
+ 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";
5515
+ import { dirname as dirname2, resolve } from "node:path";
5502
5516
 
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
5517
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/sealed.js
5504
5518
  import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
5505
5519
  import { closeSync, createReadStream, createWriteStream, existsSync, openSync, readSync, renameSync, rmSync, statSync } from "node:fs";
5506
5520
  import { Transform } from "node:stream";
@@ -5607,7 +5621,7 @@ var unsealFile = /* @__PURE__ */ __name(async (from, to, password) => {
5607
5621
  renameSync(pending, to);
5608
5622
  }, "unsealFile");
5609
5623
 
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
5624
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/store/compatibility.js
5611
5625
  var SPEAKS = MIGRATIONS.at(-1)?.version ?? 0;
5612
5626
  var fileSchemaOf = /* @__PURE__ */ __name((database) => {
5613
5627
  const tracked = database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'schema_migrations'").get();
@@ -5631,7 +5645,7 @@ var compatibilityOf = /* @__PURE__ */ __name((file2, migrations = MIGRATIONS) =>
5631
5645
  };
5632
5646
  }, "compatibilityOf");
5633
5647
 
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
5648
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/store/repair.js
5635
5649
  import { createHash as createHash2 } from "node:crypto";
5636
5650
  var COPY_MARK = "__repair_";
5637
5651
  var COPY_NAME = /__repair_[0-9a-f]{8}(_\d+)?$/;
@@ -5885,10 +5899,457 @@ var deleteCopy = /* @__PURE__ */ __name((database, name) => {
5885
5899
  return found;
5886
5900
  }, "deleteCopy");
5887
5901
 
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";
5902
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5903
+ import { existsSync as existsSync4, statSync as statSync3 } from "node:fs";
5904
+
5905
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
5906
+ import { existsSync as existsSync3 } from "node:fs";
5907
+
5908
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/store/recover.js
5909
+ import { execFileSync, spawn } from "node:child_process";
5910
+ import { existsSync as existsSync2, readFileSync, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statfsSync, statSync as statSync2, writeFileSync } from "node:fs";
5911
+ import { basename, dirname, join } from "node:path";
5912
+ import { Transform as Transform2 } from "node:stream";
5913
+ var SQLITE3_MINIMUM = [3, 43, 0];
5914
+ var STORE_PARTS = ["", "-wal", "-shm"];
5915
+ var INSERTED = /^INSERT OR IGNORE INTO '([^']+)'/;
5916
+ var LOST_AND_FOUND = "recover_lost_and_found";
5917
+ var recovers = /* @__PURE__ */ __name((program) => {
5918
+ try {
5919
+ execFileSync(program, [":memory:", ".recover"], { stdio: ["ignore", "ignore", "pipe"] });
5920
+ return true;
5921
+ } catch {
5922
+ return false;
5923
+ }
5924
+ }, "recovers");
5925
+ var sqlite3Program = /* @__PURE__ */ __name((program = "sqlite3") => {
5926
+ let version = null;
5927
+ try {
5928
+ version = execFileSync(program, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split(" ")[0] ?? null;
5929
+ } catch {
5930
+ return { program, version: null, usable: false };
5931
+ }
5932
+ const parts2 = (version ?? "").split(".").map(Number);
5933
+ const at = SQLITE3_MINIMUM.findIndex((wanted, i) => (parts2[i] ?? 0) !== wanted);
5934
+ const recent = at === -1 || (parts2[at] ?? 0) > (SQLITE3_MINIMUM[at] ?? 0);
5935
+ return { program, version, usable: recent && recovers(program) };
5936
+ }, "sqlite3Program");
5937
+ var activeTimers = /* @__PURE__ */ __name(() => {
5938
+ if (process.platform !== "linux")
5939
+ return void 0;
5940
+ try {
5941
+ return execFileSync("systemctl", ["--user", "list-timers", "--plain", "--no-legend"], {
5942
+ encoding: "utf8",
5943
+ stdio: ["ignore", "pipe", "ignore"]
5944
+ }).split("\n").map((line) => line.trim().split(/\s+/).at(-2) ?? "").filter((unit) => /^(memo|mail|tg|max|whatsapp|zoom|drive|gcal|wirecat)-.*\.timer$/.test(unit));
5945
+ } catch {
5946
+ return void 0;
5947
+ }
5948
+ }, "activeTimers");
5949
+ var storeHolders = /* @__PURE__ */ __name((path) => {
5950
+ const folder = realpathSync(dirname(path));
5951
+ const files = STORE_PARTS.map((suffix) => join(folder, `${basename(path)}${suffix}`));
5952
+ const wanted = process.platform === "linux" ? files.flatMap((file2) => [file2, `${file2} (deleted)`]) : files.filter(existsSync2);
5953
+ return holdersOf(wanted)?.map((pid) => {
5954
+ let name = "?";
5955
+ try {
5956
+ name = readFileSync(`/proc/${pid}/comm`, "utf8").trim();
5957
+ } catch {
5958
+ }
5959
+ return { pid, name };
5960
+ });
5961
+ }, "storeHolders");
5962
+ var tableRows = /* @__PURE__ */ __name((database) => {
5963
+ const indexes = fts5Tables(database).map((index) => index.name);
5964
+ 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}_`)));
5965
+ return Object.fromEntries(tables.map((table) => {
5966
+ try {
5967
+ return [table, Number(database.prepare(`SELECT count(*) AS n FROM "${table}"`).get()?.n)];
5968
+ } catch {
5969
+ return [table, null];
5970
+ }
5971
+ }));
5972
+ }, "tableRows");
5973
+ var copyReadableRows = /* @__PURE__ */ __name((path, target, program = "sqlite3") => new Promise((resolve2, reject) => {
5974
+ const reader = spawn(program, ["-readonly", path, `.recover --ignore-freelist --lost-and-found ${LOST_AND_FOUND}`], {
5975
+ stdio: ["ignore", "pipe", "pipe"]
5976
+ });
5977
+ const writer = spawn(program, ["-cmd", ".dbconfig defensive off", target], { stdio: ["pipe", "ignore", "pipe"] });
5978
+ const errors = [];
5979
+ const collect = /* @__PURE__ */ __name((chunk) => {
5980
+ for (const line of chunk.toString("utf8").split("\n"))
5981
+ if (line && errors.length < 50)
5982
+ errors.push(line.slice(0, 300));
5983
+ }, "collect");
5984
+ reader.stderr.on("data", collect);
5985
+ writer.stderr.on("data", collect);
5986
+ const read = {};
5987
+ let rest = "";
5988
+ const counter = new Transform2({
5989
+ transform(chunk, _encoding, done) {
5990
+ const lines = (rest + chunk.toString("latin1")).split("\n");
5991
+ rest = lines.pop() ?? "";
5992
+ for (const line of lines) {
5993
+ const table = INSERTED.exec(line)?.[1];
5994
+ if (table)
5995
+ read[table] = (read[table] ?? 0) + 1;
5996
+ }
5997
+ done(null, chunk);
5998
+ }
5999
+ });
6000
+ reader.stdout.pipe(counter).pipe(writer.stdin);
6001
+ let exits = 0;
6002
+ let readerCode = null;
6003
+ const exited = /* @__PURE__ */ __name(() => {
6004
+ exits += 1;
6005
+ if (exits < 2)
6006
+ return;
6007
+ if (readerCode !== 0)
6008
+ reject(new CliError("validation_error", `sqlite3 could not read the store: ${errors.join("; ")}`));
6009
+ else
6010
+ resolve2({ errors, read });
6011
+ }, "exited");
6012
+ reader.on("error", reject);
6013
+ writer.on("error", reject);
6014
+ reader.on("close", (code) => {
6015
+ readerCode = code;
6016
+ exited();
6017
+ });
6018
+ writer.on("close", exited);
6019
+ }), "copyReadableRows");
6020
+ var FILLERS = {
6021
+ message_words: /* @__PURE__ */ __name((database, now) => {
6022
+ resetSearchIndex(database);
6023
+ fillSearchIndex(database, { now });
6024
+ }, "message_words"),
6025
+ message_stems: /* @__PURE__ */ __name((database, now) => {
6026
+ resetStems(database, { force: true, now });
6027
+ fillStems(database, { now });
6028
+ }, "message_stems"),
6029
+ attachment_words: /* @__PURE__ */ __name((database) => void resetAttachmentWords(database), "attachment_words"),
6030
+ attachment_name_words: /* @__PURE__ */ __name((database) => (
6031
+ // As migration 20 filled it: й and ё fold as the triggers fold them.
6032
+ 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")
6033
+ ), "attachment_name_words"),
6034
+ meeting_words: /* @__PURE__ */ __name((database) => {
6035
+ 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");
6036
+ drainMeetingIndex(database);
6037
+ }, "meeting_words"),
6038
+ // Built per account by the first search that needs them.
6039
+ 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")
6040
+ };
6041
+ var CORPUS_TABLES = new Set(Object.values(CORPORA).flatMap((corpus) => [`${corpus.type}_words`, `${corpus.type}_stems`]));
6042
+ var TRIGRAMS = ["note_trigrams", "document_trigrams"];
6043
+ var rebuildDerived = /* @__PURE__ */ __name((database, { now = Date.now, note = /* @__PURE__ */ __name(() => {
6044
+ }, "note") } = {}) => {
6045
+ const lost = database.prepare("SELECT 1 FROM sqlite_master WHERE name = ?").get(LOST_AND_FOUND);
6046
+ const lostAndFound = lost ? Number(database.prepare(`SELECT count(*) AS n FROM ${LOST_AND_FOUND}`).get()?.n) : 0;
6047
+ if (lost)
6048
+ database.exec(`DROP TABLE ${LOST_AND_FOUND}`);
6049
+ const indexes = fts5Tables(database);
6050
+ for (const { name, sql } of indexes) {
6051
+ database.exec(`DROP TABLE "${name}"`);
6052
+ database.exec(sql);
6053
+ }
6054
+ 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));
6055
+ for (const table of vectors) {
6056
+ database.exec(`DROP TRIGGER IF EXISTS "${table}_redo"`);
6057
+ database.exec(`DROP TABLE "${table}"`);
6058
+ database.prepare("DELETE FROM vector_indexes WHERE id = ?").run(Number(table.replace("vector_index_", "")));
6059
+ }
6060
+ const unfilled = [];
6061
+ const stemmerFor = stemmerCache();
6062
+ for (const { name, external } of indexes) {
6063
+ note(`rebuilding ${name}`);
6064
+ if (external)
6065
+ database.exec(`INSERT INTO "${name}" ("${name}") VALUES ('rebuild')`);
6066
+ else if (FILLERS[name])
6067
+ FILLERS[name](database, now);
6068
+ else if (!CORPUS_TABLES.has(name) && !TRIGRAMS.includes(name))
6069
+ unfilled.push(name);
6070
+ }
6071
+ note("rebuilding the words of notes, documents, memories, mail, tasks, transcripts and events");
6072
+ resetNoteIndex(database);
6073
+ for (const corpus of Object.values(CORPORA))
6074
+ drainCorpus(database, corpus, stemmerFor);
6075
+ for (const name of TRIGRAMS) {
6076
+ const type = name.replace("_trigrams", "");
6077
+ database.prepare(`UPDATE search_index_state SET filled_through = 0, watermark = (SELECT coalesce(max(id), 0) FROM ${type}s) WHERE name = ?`).run(name);
6078
+ }
6079
+ fillTrigrams(database);
6080
+ note("finding mentions again");
6081
+ const mentions = rebuildMentions(database, { now: now() }).mentions;
6082
+ involvementStoreOver({ database, now }).rebuild();
6083
+ note("indexing the stored vectors");
6084
+ const vectorModels = fillVectorIndexes(database);
6085
+ 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)");
6086
+ 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)]));
6087
+ return {
6088
+ lostAndFound,
6089
+ searchIndexes: indexes.map((index) => index.name),
6090
+ unfilled,
6091
+ mentions,
6092
+ vectorModels,
6093
+ chunksWithoutVector
6094
+ };
6095
+ }, "rebuildDerived");
6096
+ 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) => {
6097
+ const child = String(group.child);
6098
+ 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;
6099
+ let missing = [];
6100
+ try {
6101
+ 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));
6102
+ } catch {
6103
+ }
6104
+ return { table: child, parent: String(group.parent), rows: Number(group.n), missing };
6105
+ }), "danglingRows");
6106
+ var mailToFetch = /* @__PURE__ */ __name((database) => {
6107
+ try {
6108
+ return database.prepare(`SELECT a.external_id AS account, count(DISTINCT l.email_id) AS n FROM email_locations l
6109
+ JOIN mailboxes b ON b.id = l.mailbox_id JOIN accounts a ON a.id = b.account_id
6110
+ 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) }));
6111
+ } catch {
6112
+ return [];
6113
+ }
6114
+ }, "mailToFetch");
6115
+ var fingerprint = /* @__PURE__ */ __name((path) => ["", "-wal"].map((suffix) => {
6116
+ const stat = statSync2(`${path}${suffix}`, { throwIfNoEntry: false });
6117
+ return stat ? `${stat.size}:${stat.mtimeMs}` : "-";
6118
+ }).join("|"), "fingerprint");
6119
+ var refuseInUse = /* @__PURE__ */ __name((path) => {
6120
+ const holders = storeHolders(path);
6121
+ if (holders && holders.length > 0) {
6122
+ const timers = activeTimers() ?? [];
6123
+ 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" });
6124
+ }
6125
+ }, "refuseInUse");
6126
+ var recoverStore = /* @__PURE__ */ __name(async ({ path, command, version, sqlite3 = "sqlite3", now = Date.now, note = /* @__PURE__ */ __name(() => {
6127
+ }, "note"), copy }) => {
6128
+ const started = Date.now();
6129
+ if (!existsSync2(path))
6130
+ throw new CliError("not_found", `no store at ${path}`);
6131
+ const program = copy ? { program: sqlite3, version: "given", usable: true } : sqlite3Program(sqlite3);
6132
+ if (!program.usable) {
6133
+ 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" });
6134
+ }
6135
+ refuseInUse(path);
6136
+ const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync2(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
6137
+ const { bavail, bsize } = statfsSync(dirname(path));
6138
+ if (Number(bavail) * Number(bsize) < bytes * 1.2)
6139
+ throw new CliError("validation_error", `the recovery needs about ${Math.ceil(bytes * 1.2 / 1e9)} GB free beside the store`);
6140
+ const old = await openSqlite(path, { readOnly: true });
6141
+ let rowsBefore;
6142
+ try {
6143
+ rowsBefore = tableRows(old.database);
6144
+ } finally {
6145
+ old.database.close();
6146
+ }
6147
+ const before = fingerprint(path);
6148
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
6149
+ const target = `${path}.recovering-${stamp}`;
6150
+ writeFileSync(target, "", { flag: "wx", mode: 384 });
6151
+ const dropTarget = /* @__PURE__ */ __name(() => {
6152
+ for (const suffix of [...STORE_PARTS, "-journal"])
6153
+ rmSync2(`${target}${suffix}`, { force: true });
6154
+ }, "dropTarget");
6155
+ note(`copying the readable rows into ${target}`);
6156
+ let copied;
6157
+ let copyErrors;
6158
+ let read;
6159
+ let opened;
6160
+ try {
6161
+ ;
6162
+ ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
6163
+ copied = Date.now();
6164
+ opened = await openSqlite(target);
6165
+ } catch (error) {
6166
+ dropTarget();
6167
+ throw error;
6168
+ }
6169
+ let rebuilt;
6170
+ let kept;
6171
+ let dangling;
6172
+ let fetch2;
6173
+ try {
6174
+ kept = tableRows(opened.database);
6175
+ migrate(opened.database, { command, ...version ? { version } : {} });
6176
+ rebuilt = rebuildDerived(opened.database, { now, note });
6177
+ note("looking for rows that point at rows that were lost");
6178
+ dangling = danglingRows(opened.database);
6179
+ fetch2 = mailToFetch(opened.database);
6180
+ opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
6181
+ } catch (error) {
6182
+ opened.database.close();
6183
+ dropTarget();
6184
+ throw error;
6185
+ }
6186
+ opened.database.close();
6187
+ const rebuiltAt = Date.now();
6188
+ note("checking the recovered file");
6189
+ const health = await storeHealth(target, { deep: true });
6190
+ const checkedAt = Date.now();
6191
+ if (!health.ok) {
6192
+ 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" });
6193
+ }
6194
+ refuseInUse(path);
6195
+ if (fingerprint(path) !== before) {
6196
+ 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" });
6197
+ }
6198
+ const keptAt = `${path}.before-recover-${stamp}`;
6199
+ for (const suffix of STORE_PARTS)
6200
+ if (existsSync2(`${path}${suffix}`))
6201
+ renameSync2(`${path}${suffix}`, `${keptAt}${suffix}`);
6202
+ for (const suffix of STORE_PARTS)
6203
+ if (existsSync2(`${target}${suffix}`))
6204
+ renameSync2(`${target}${suffix}`, `${path}${suffix}`);
6205
+ 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);
6206
+ const seconds = /* @__PURE__ */ __name((from, to) => Math.round((to - from) / 100) / 10, "seconds");
6207
+ return {
6208
+ path,
6209
+ keptAt,
6210
+ sqlite3: program.version,
6211
+ lost,
6212
+ dangling,
6213
+ mailToFetch: fetch2,
6214
+ rebuilt,
6215
+ copyErrors,
6216
+ health,
6217
+ seconds: {
6218
+ copy: seconds(started, copied),
6219
+ rebuild: seconds(copied, rebuiltAt),
6220
+ check: seconds(rebuiltAt, checkedAt),
6221
+ total: seconds(started, Date.now())
6222
+ }
6223
+ };
6224
+ }, "recoverStore");
6225
+
6226
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
6227
+ var COUNTED = [
6228
+ "accounts",
6229
+ "chats",
6230
+ "messages",
6231
+ "attachments",
6232
+ "emails",
6233
+ "documents",
6234
+ "notes",
6235
+ "meetings",
6236
+ "chunks",
6237
+ "embeddings",
6238
+ "mentions"
6239
+ ];
6240
+ var stopTimers = /* @__PURE__ */ __name((timers) => `systemctl --user stop ${timers.join(" ")}`, "stopTimers");
6241
+ var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command) => {
6242
+ const path = storePath(env);
6243
+ if (!existsSync3(path))
6244
+ return { path, exists: false, ok: true, next: [] };
6245
+ const health = await storeHealth(path, { deep: true });
6246
+ let rows = {};
6247
+ try {
6248
+ const { database } = await openSqlite(path, { readOnly: true });
6249
+ try {
6250
+ const all = tableRows(database);
6251
+ rows = Object.fromEntries(COUNTED.filter((table) => table in all).map((table) => [table, all[table] ?? null]));
6252
+ } finally {
6253
+ database.close();
6254
+ }
6255
+ } catch {
6256
+ }
6257
+ const explanation = explainDamage(health, command);
6258
+ const inUse = storeHolders(path) ?? null;
6259
+ const timers = activeTimers() ?? null;
6260
+ const sqlite3 = sqlite3Program();
6261
+ const next = health.ok ? [] : [
6262
+ ...timers?.length ? [stopTimers(timers)] : [],
6263
+ ...(inUse ?? []).map(({ pid, name }) => `stop ${name} (process ${pid}): it has the store open`),
6264
+ ...sqlite3.usable ? [] : ["install sqlite3 3.43 or newer (apt install sqlite3, brew install sqlite)"],
6265
+ `${command} store recover run`
6266
+ ];
6267
+ return {
6268
+ path,
6269
+ exists: true,
6270
+ ok: health.ok,
6271
+ seconds: Math.round(health.ms / 100) / 10,
6272
+ problems: health.problems ?? 0,
6273
+ damagedTables: health.damagedTables ?? [],
6274
+ damagedSearchIndexes: (health.searchIndexes ?? []).filter((index) => !index.ok).map(({ name, error }) => ({ name, ...error ? { error } : {} })),
6275
+ rows,
6276
+ explanation,
6277
+ inUse,
6278
+ timers,
6279
+ sqlite3: { version: sqlite3.version, usable: sqlite3.usable },
6280
+ next
6281
+ };
6282
+ }, "storeRecoveryCheck");
6283
+ var storeRecoveryRun = /* @__PURE__ */ __name(async (env, { command, version, note, timers: scheduled = activeTimers, copy }) => {
6284
+ const timers = scheduled() ?? [];
6285
+ if (timers.length > 0)
6286
+ throw new CliError("validation_error", `stop the timers first, they open the store: ${stopTimers(timers)}`, {
6287
+ reason: "store.in-use"
6288
+ });
6289
+ const recovery = await recoverStore({
6290
+ path: storePath(env),
6291
+ command,
6292
+ ...version ? { version } : {},
6293
+ ...note ? { note } : {},
6294
+ ...copy ? { copy } : {}
6295
+ });
6296
+ const mail = recovery.mailToFetch.map(({ account, emails }) => `mail <profile of ${account}> sync --rescan # ${emails} emails`);
6297
+ const lostMail = recovery.lost.some(({ table }) => table === "emails") && mail.length === 0 ? ["mail <profile> sync --rescan # each mail profile"] : [];
6298
+ const { health, copyErrors, ...kept } = recovery;
6299
+ return {
6300
+ ...kept,
6301
+ copyErrors: copyErrors.length,
6302
+ checkedOk: health.ok,
6303
+ next: [...mail, ...lostMail, "systemctl --user start <the timers stopped before>"]
6304
+ };
6305
+ }, "storeRecoveryRun");
6306
+ var recoveryNotes = /* @__PURE__ */ __name((answer) => {
6307
+ if ("keptAt" in answer) {
6308
+ const lost = answer.lost.map(({ table, before, read, kept }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}`);
6309
+ return [
6310
+ `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
6311
+ ...lost.length ? lost : ["no table lost a row"],
6312
+ ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
6313
+ ...answer.next.map((line) => `next: ${line}`)
6314
+ ];
6315
+ }
6316
+ if (!answer.exists)
6317
+ return ["no store yet"];
6318
+ if (answer.ok)
6319
+ return [`the store is healthy (checked every page and search index in ${answer.seconds} s)`];
6320
+ const why = answer.explanation;
6321
+ return [
6322
+ ...why ? [why.what, ...why.impact, why.externalUnaffected] : [],
6323
+ ...answer.next.map((line) => `next: ${line}`)
6324
+ ];
6325
+ }, "recoveryNotes");
6326
+ var storeRecoverCommand = /* @__PURE__ */ __name(({ command, version }) => {
6327
+ 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() {
6328
+ const output = outputFor(this);
6329
+ const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command);
6330
+ renderAnswer(this, output, itemOf(snakeKeys(answer)));
6331
+ if (output.format === "pretty")
6332
+ for (const line of recoveryNotes(answer))
6333
+ output.renderer.note(line);
6334
+ });
6335
+ 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() {
6336
+ const output = outputFor(this);
6337
+ const answer = await storeRecoveryRun(environmentOf(this).env ?? process.env, {
6338
+ command,
6339
+ ...version ? { version } : {},
6340
+ note: /* @__PURE__ */ __name((text) => output.renderer.note(text), "note")
6341
+ });
6342
+ renderAnswer(this, output, itemOf(snakeKeys(answer)));
6343
+ if (output.format === "pretty")
6344
+ for (const line of recoveryNotes(answer))
6345
+ output.renderer.note(line);
6346
+ }));
6347
+ return recover;
6348
+ }, "storeRecoverCommand");
6349
+
6350
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5890
6351
  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");
6352
+ var bytesOf = /* @__PURE__ */ __name((path) => existsSync4(path) ? statSync3(path).size : 0, "bytesOf");
5892
6353
  var messageOf = /* @__PURE__ */ __name((error) => error instanceof Error ? error.message : String(error), "messageOf");
5893
6354
  var contentsOf = /* @__PURE__ */ __name((database, version, writable) => version > 0 && writable ? {
5894
6355
  rows: rowCounts(database),
@@ -5899,7 +6360,7 @@ var contentsOf = /* @__PURE__ */ __name((database, version, writable) => version
5899
6360
  } : { rows: {}, pendingNormalization: null, wordIndex: null, stemIndex: null }, "contentsOf");
5900
6361
  var storeInfo = /* @__PURE__ */ __name(async (env) => {
5901
6362
  const path = storePath(env);
5902
- if (!existsSync2(path))
6363
+ if (!existsSync4(path))
5903
6364
  return snakeKeys({ path, exists: false, schema: compatibilityOf(void 0) });
5904
6365
  let schema = compatibilityOf(void 0);
5905
6366
  try {
@@ -5932,7 +6393,7 @@ var storeInfoCommand = /* @__PURE__ */ __name(() => annotate(new Command("info")
5932
6393
  renderAnswer(this, outputFor(this), itemOf(answer));
5933
6394
  }), "storeInfoCommand");
5934
6395
 
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
6396
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/password.js
5936
6397
  var ENCRYPT_OPTION = [
5937
6398
  "--encrypt",
5938
6399
  "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 +6412,9 @@ var passwordOf = /* @__PURE__ */ __name(async (command, { twice }) => {
5951
6412
  return password;
5952
6413
  }, "passwordOf");
5953
6414
 
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";
6415
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/rules.js
6416
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
6417
+ import { join as join2 } from "node:path";
5957
6418
  var REPLY_ACTIONS = ["reply", "task"];
5958
6419
  var REPLY_MODELS = ["fill-only", "may-reword"];
5959
6420
  var REPLY_KINDS = ["dialog", "group"];
@@ -6039,7 +6500,7 @@ var defaultRule = /* @__PURE__ */ __name((id) => ({
6039
6500
  reply: { template: "", asReply: true },
6040
6501
  limits: { perChat: "1/1d", perPerson: "1/1d" }
6041
6502
  }), "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");
6503
+ var repliesPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join2(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config, `${profile}.replies.json`), "repliesPathFor");
6043
6504
  var EVERYONE = { reply: "all", allow: { people: [], chats: [] }, deny: { people: [], chats: [] } };
6044
6505
  var outsideAudience = /* @__PURE__ */ __name((audience, person, chat) => {
6045
6506
  if (person !== null && audience.deny.people.includes(person))
@@ -6069,11 +6530,11 @@ var readReplies = /* @__PURE__ */ __name((path, provider) => {
6069
6530
  return parseReplies(readRepliesFile(path, provider), path, provider);
6070
6531
  }, "readReplies");
6071
6532
  var readRepliesFile = /* @__PURE__ */ __name((path, provider) => {
6072
- if (!existsSync3(path))
6533
+ if (!existsSync5(path))
6073
6534
  return { audience: structuredClone(EVERYONE), rules: [] };
6074
6535
  let parsed;
6075
6536
  try {
6076
- parsed = JSON.parse(readFileSync(path, "utf8"));
6537
+ parsed = JSON.parse(readFileSync2(path, "utf8"));
6077
6538
  } catch (error) {
6078
6539
  throw broken(path, error instanceof Error ? error.message : String(error));
6079
6540
  }
@@ -6122,9 +6583,9 @@ var problem = /* @__PURE__ */ __name((issue) => {
6122
6583
  }, "problem");
6123
6584
  var broken = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the reply rules ${path} cannot be read (${why}) \u2014 fix the file`), "broken");
6124
6585
 
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";
6586
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/state.js
6587
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
6588
+ import { join as join3 } from "node:path";
6128
6589
  var ANSWERED_KEPT = 1e3;
6129
6590
  var times = record(string(), array(string()));
6130
6591
  var stateFile = object({
@@ -6136,13 +6597,13 @@ var stateFile = object({
6136
6597
  });
6137
6598
  var emptyState = /* @__PURE__ */ __name(() => ({ paused: false, answered: [], sent: {} }), "emptyState");
6138
6599
  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");
6600
+ 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
6601
  var readRepliesState = /* @__PURE__ */ __name((path) => {
6141
- if (!existsSync4(path))
6602
+ if (!existsSync6(path))
6142
6603
  return emptyState();
6143
6604
  let parsed;
6144
6605
  try {
6145
- parsed = JSON.parse(readFileSync2(path, "utf8"));
6606
+ parsed = JSON.parse(readFileSync3(path, "utf8"));
6146
6607
  } catch (error) {
6147
6608
  throw broken2(path, error instanceof Error ? error.message : String(error));
6148
6609
  }
@@ -6175,7 +6636,7 @@ var recordReply = /* @__PURE__ */ __name((state, rule2, message, now) => {
6175
6636
  }, "recordReply");
6176
6637
  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
6638
 
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
6639
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/decide.js
6179
6640
  var skip = /* @__PURE__ */ __name((why) => ({ skip: why }), "skip");
6180
6641
  var decide = /* @__PURE__ */ __name((rule2, incoming, state, now) => {
6181
6642
  const { message, chat, owner, sender } = incoming;
@@ -6281,7 +6742,7 @@ var filled = /* @__PURE__ */ __name((template2, senderName) => {
6281
6742
  return template2.replaceAll("{firstName}", name.split(/\s+/)[0] ?? name).replaceAll("{name}", name);
6282
6743
  }, "filled");
6283
6744
 
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
6745
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/template.js
6285
6746
  var import_liquidjs = __toESM(require_liquid_node(), 1);
6286
6747
  var TEMPLATE_LIMITS = {
6287
6748
  parse: 32768,
@@ -6441,7 +6902,7 @@ var renderReplyTemplate = /* @__PURE__ */ __name(async (reply, input) => {
6441
6902
  }
6442
6903
  }, "renderReplyTemplate");
6443
6904
 
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
6905
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/dry-run.js
6445
6906
  var DRY_RUN_DAYS = 7;
6446
6907
  var PAGE = 500;
6447
6908
  var dryRun = /* @__PURE__ */ __name(async (store, account, rules, { since, until = Date.now(), only, audience, render }) => {
@@ -6555,7 +7016,7 @@ var storedSince = /* @__PURE__ */ __name(async (store, account, chat, since) =>
6555
7016
  }
6556
7017
  }, "storedSince");
6557
7018
 
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
7019
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/embeddings/keys.js
6559
7020
  var endpointKeyName = /* @__PURE__ */ __name((baseUrl) => {
6560
7021
  const host = new URL(baseUrl).host;
6561
7022
  return ["openai", "anthropic"].includes(host) ? `endpoint:${host}` : host;
@@ -6586,7 +7047,7 @@ var embeddingKeys = /* @__PURE__ */ __name((app, env = process.env, keyring) =>
6586
7047
  };
6587
7048
  }, "embeddingKeys");
6588
7049
 
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
7050
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/models/openai.js
6590
7051
  var options = strictObject({
6591
7052
  temperature: range(0, 2),
6592
7053
  top_p: range(0, 1),
@@ -6600,7 +7061,7 @@ var openai = {
6600
7061
  images: true,
6601
7062
  baseUrl: "https://api.openai.com/v1",
6602
7063
  validate: /* @__PURE__ */ __name((given) => checkedOptions("openai", options, given), "validate"),
6603
- complete: /* @__PURE__ */ __name(async (target, request, checked, apiKey, fetcher) => {
7064
+ complete: /* @__PURE__ */ __name((target, request, checked, apiKey, fetcher) => withTimeLimit(12e4, async (deadline) => {
6604
7065
  const response = await fetcher(`${target.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
6605
7066
  method: "POST",
6606
7067
  headers: { "Content-Type": "application/json", ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
@@ -6622,7 +7083,7 @@ var openai = {
6622
7083
  ],
6623
7084
  ...new URL(target.baseUrl).hostname === "api.openai.com" ? { max_completion_tokens: request.maxTokens } : { max_tokens: request.maxTokens }
6624
7085
  }),
6625
- signal: AbortSignal.timeout(12e4),
7086
+ signal: deadline,
6626
7087
  redirect: "error"
6627
7088
  });
6628
7089
  if (!response.ok)
@@ -6632,10 +7093,10 @@ var openai = {
6632
7093
  if (choice?.finish_reason !== "stop" || typeof choice.message?.content !== "string" || !Number.isInteger(body.usage?.total_tokens) || (body.usage?.total_tokens ?? 0) < 1)
6633
7094
  throw new Error("incomplete response");
6634
7095
  return { text: choice.message.content, tokens: body.usage?.total_tokens };
6635
- }, "complete")
7096
+ }), "complete")
6636
7097
  };
6637
7098
 
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
7099
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/models/index.js
6639
7100
  var modelGateway = /* @__PURE__ */ __name((deps) => ({
6640
7101
  complete: /* @__PURE__ */ __name(async (request) => {
6641
7102
  if (deps.signal?.aborted)
@@ -6650,7 +7111,7 @@ var modelGateway = /* @__PURE__ */ __name((deps) => ({
6650
7111
  if (!adapter && target.provider === "openai")
6651
7112
  adapter = openai;
6652
7113
  if (!adapter && target.provider === "anthropic")
6653
- adapter = (await import("./anthropic-QKIPHV2Z.js")).anthropic;
7114
+ adapter = (await import("./anthropic-DFUW2KTG.js")).anthropic;
6654
7115
  if (!adapter)
6655
7116
  throw new CliError("validation_error", `no model adapter for ${target.provider}`);
6656
7117
  if (request.images !== void 0 && adapter.images !== true)
@@ -6691,19 +7152,19 @@ var modelGateway = /* @__PURE__ */ __name((deps) => ({
6691
7152
  }, "complete")
6692
7153
  }), "modelGateway");
6693
7154
 
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";
7155
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/consents.js
7156
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
7157
+ import { join as join4 } from "node:path";
6697
7158
  var shape = strictObject({
6698
7159
  provider: nullable(pipe(string(), minLength(1))),
6699
7160
  deniedChats: array(pipe(string(), minLength(1)))
6700
7161
  });
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");
7162
+ 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
7163
  var readReplyConsent = /* @__PURE__ */ __name((path) => {
6703
- if (!existsSync5(path))
7164
+ if (!existsSync7(path))
6704
7165
  return { provider: null, deniedChats: [] };
6705
7166
  try {
6706
- return parse(shape, JSON.parse(readFileSync3(path, "utf8")));
7167
+ return parse(shape, JSON.parse(readFileSync4(path, "utf8")));
6707
7168
  } catch {
6708
7169
  throw new CliError("configuration_error", "reply model consent is invalid; fix its file before granting consent");
6709
7170
  }
@@ -6716,7 +7177,7 @@ var mayModelReply = /* @__PURE__ */ __name((path, provider, chat) => {
6716
7177
  return consent.provider === provider && !consent.deniedChats.includes(chat);
6717
7178
  }, "mayModelReply");
6718
7179
 
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
7180
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/rendering.js
6720
7181
  var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, options2 = {
6721
7182
  ai: true
6722
7183
  }) => async (rule2, message, chat, now) => {
@@ -6763,7 +7224,7 @@ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, o
6763
7224
  return result2;
6764
7225
  }, "replyRenderer");
6765
7226
 
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
7227
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/replies/serve.js
6767
7228
  var NOT_ALLOWED = "replies.send is not allow";
6768
7229
  var NO_RULES = "no rules";
6769
7230
  var ONLY_TASK = "opened a task, sent nothing";
@@ -6856,7 +7317,7 @@ var replyTo = /* @__PURE__ */ __name(async (deps, message) => {
6856
7317
  return { skip: why };
6857
7318
  }, "replyTo");
6858
7319
 
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
7320
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-catch-up.js
6860
7321
  var START_SYNC_DELAY_MS = 3e4;
6861
7322
  var START_SYNC_BUDGET_MS = 5 * 6e4;
6862
7323
  var START_SYNC_WINDOW_MS = 7 * 864e5;
@@ -6867,8 +7328,8 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6867
7328
  let pass = Promise.resolve();
6868
7329
  let started = false;
6869
7330
  let done;
6870
- const run = /* @__PURE__ */ __name(async () => {
6871
- const stop = AbortSignal.any([controller.signal, AbortSignal.timeout(budgetMs)]);
7331
+ const run = /* @__PURE__ */ __name(() => withTimeLimit(budgetMs, (deadline) => catchUp(AbortSignal.any([controller.signal, deadline]))), "run");
7332
+ const catchUp = /* @__PURE__ */ __name(async (stop) => {
6872
7333
  const floor = now() - windowMs;
6873
7334
  const moved = [];
6874
7335
  for (const chat of await chats(stop)) {
@@ -6909,7 +7370,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6909
7370
  code: "start_sync",
6910
7371
  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
7372
  });
6912
- }, "run");
7373
+ }, "catchUp");
6913
7374
  return {
6914
7375
  start: /* @__PURE__ */ __name(() => {
6915
7376
  if (started || controller.signal.aborted)
@@ -6933,7 +7394,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
6933
7394
  };
6934
7395
  }, "startSync");
6935
7396
 
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
7397
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-members.js
6937
7398
  var FIRST_FETCH_MS = 6e4;
6938
7399
  var DAY_MS = 864e5;
6939
7400
  var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, firstMs = FIRST_FETCH_MS, everyMs = DAY_MS }) => {
@@ -6987,7 +7448,7 @@ var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, fi
6987
7448
  };
6988
7449
  }, "memberFetches");
6989
7450
 
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
7451
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-notice.js
6991
7452
  var record2 = /* @__PURE__ */ __name((context, app, severity, attributes) => recordLogFor(context.streams.diagnostic, app, { command: currentRun().command || "serve" })[severity](attributes), "record");
6992
7453
  var noticeFor = /* @__PURE__ */ __name((context, app, severity = "warn") => ({ text, ...attributes }) => {
6993
7454
  if (context.format === "pretty") {
@@ -7020,7 +7481,7 @@ var recordDiagnostics = /* @__PURE__ */ __name((context, app) => {
7020
7481
  return context;
7021
7482
  }, "recordDiagnostics");
7022
7483
 
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
7484
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-stems.js
7024
7485
  var STEMS_EVERY_MS = 3e4;
7025
7486
  var STEMS_SLICE_MS = 2e3;
7026
7487
  var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY_MS, sliceMs = STEMS_SLICE_MS }) => {
@@ -7060,7 +7521,7 @@ var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY
7060
7521
  };
7061
7522
  }, "stemFills");
7062
7523
 
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
7524
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/render/messages.js
7064
7525
  import { styleText } from "node:util";
7065
7526
  var TIME_WIDTH = 8;
7066
7527
  var INDENT = " ".repeat(TIME_WIDTH + 2);
@@ -7236,7 +7697,7 @@ var editedAt = /* @__PURE__ */ __name((message, options2) => {
7236
7697
  return day(edited) === day(message.timestamp) ? time : `${day(edited)} ${time}`;
7237
7698
  }, "editedAt");
7238
7699
 
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
7700
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/message-items.js
7240
7701
  var defined = /* @__PURE__ */ __name((value) => Object.fromEntries(Object.entries(value).filter(([, one]) => one !== void 0)), "defined");
7241
7702
  var attachmentItem = /* @__PURE__ */ __name((attachment) => defined({
7242
7703
  kind: attachment.kind,
@@ -7331,7 +7792,7 @@ var viewOf = /* @__PURE__ */ __name((context, messenger) => ({
7331
7792
  locale: messenger.app.locale
7332
7793
  }), "viewOf");
7333
7794
 
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
7795
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-answers.js
7335
7796
  var observed = /* @__PURE__ */ __name((value) => ({
7336
7797
  value: value.value,
7337
7798
  observed_at: value.observedAt,
@@ -7398,7 +7859,7 @@ var watchEventItem = /* @__PURE__ */ __name((value, account) => {
7398
7859
  }
7399
7860
  }, "watchEventItem");
7400
7861
 
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
7862
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-command.js
7402
7863
  var watchCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("watch"), {
7403
7864
  output: { entity: "watch_item" },
7404
7865
  effects: REMOTE_READ,
@@ -7553,7 +8014,7 @@ var describe = /* @__PURE__ */ __name((event, render) => {
7553
8014
  }
7554
8015
  }, "describe");
7555
8016
 
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
8017
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-command.js
7557
8018
  var serveCommand = /* @__PURE__ */ __name((messenger) => {
7558
8019
  const command = annotate(new Command("serve"), {
7559
8020
  output: { entity: "serve_summary" },
@@ -7817,8 +8278,8 @@ var tasking = /* @__PURE__ */ __name((context, warn) => {
7817
8278
  };
7818
8279
  }, "tasking");
7819
8280
 
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";
8281
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/store-tables-command.js
8282
+ import { existsSync as existsSync8 } from "node:fs";
7822
8283
  var PATH = "store tables list";
7823
8284
  var STORE_TABLES_QUERY = {
7824
8285
  entity: "store_table",
@@ -7847,7 +8308,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
7847
8308
  const filter = filterOf(words);
7848
8309
  const { full } = this.optsWithGlobals();
7849
8310
  const path = storePath(environmentOf(this).env ?? process.env);
7850
- if (!existsSync6(path))
8311
+ if (!existsSync8(path))
7851
8312
  throw new CliError("not_found", `no store at ${path}`);
7852
8313
  const items = await readStoreTables(path, { filter, sizes: full === true });
7853
8314
  renderAnswer(this, outputFor(this), listOf(PATH, {
@@ -7860,7 +8321,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
7860
8321
  return tables;
7861
8322
  }, "storeTablesCommand");
7862
8323
 
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
8324
+ // node_modules/.pnpm/@wirecat+cli-core@0.600.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.80.8_commander@15._6a3165a3e9bffd3483d86046d9ef2956/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
7864
8325
  var SEARCH_INDEXES = ["messages_fts", "chats_fts", "identities_fts"];
7865
8326
  var WORD_INDEX = "message_words";
7866
8327
  var schemaOf = /* @__PURE__ */ __name((database) => {
@@ -7869,7 +8330,7 @@ var schemaOf = /* @__PURE__ */ __name((database) => {
7869
8330
  }, "schemaOf");
7870
8331
  var count2 = /* @__PURE__ */ __name((database, table) => Number(database.prepare(`SELECT count(*) AS n FROM ${table}`).get()?.n ?? 0), "count");
7871
8332
  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");
8333
+ var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync9(path) ? statSync4(path).size : 0, "bytesOf");
7873
8334
  var reading = /* @__PURE__ */ __name(async (path, read) => {
7874
8335
  const database = await openCache(path);
7875
8336
  try {
@@ -7886,10 +8347,22 @@ var readingOnly = /* @__PURE__ */ __name(async (path, read) => {
7886
8347
  database.close();
7887
8348
  }
7888
8349
  }, "readingOnly");
7889
- var storeSummary = /* @__PURE__ */ __name(async (env) => {
8350
+ var storeSummary = /* @__PURE__ */ __name(async (env, { deep = false, command } = {}) => {
7890
8351
  const path = storePath(env);
7891
- if (!existsSync7(path))
8352
+ if (!existsSync9(path))
7892
8353
  return { path, exists: false };
8354
+ const checked = await storeHealth(path, { deep });
8355
+ const health = {
8356
+ checked: checked.checked,
8357
+ covers: deep ? "every page and every search index" : QUICK_HEALTH_CHECKS,
8358
+ ok: checked.ok,
8359
+ ms: checked.ms,
8360
+ ...checked.problems ? { problems: checked.problems } : {},
8361
+ ...checked.damagedTables?.length ? { damagedTables: checked.damagedTables } : {},
8362
+ ...checked.searchIndexes?.some((index) => !index.ok) ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) } : {}
8363
+ };
8364
+ const damage = command ? explainDamage(checked, command) : null;
8365
+ const healthOf = { health, ...damage ? { damage } : {} };
7893
8366
  try {
7894
8367
  return await reading(path, (database) => {
7895
8368
  const { version, writable } = schemaOf(database);
@@ -7899,11 +8372,12 @@ var storeSummary = /* @__PURE__ */ __name(async (env) => {
7899
8372
  schema: version,
7900
8373
  speaks: SPEAKS,
7901
8374
  writable,
7902
- ...version > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {}
8375
+ ...version > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {},
8376
+ ...healthOf
7903
8377
  };
7904
8378
  });
7905
8379
  } catch (error) {
7906
- return { path, exists: true, error: messageOf2(error) };
8380
+ return { path, exists: true, error: messageOf2(error), ...healthOf };
7907
8381
  }
7908
8382
  }, "storeSummary");
7909
8383
  var result = /* @__PURE__ */ __name((command, value, next = []) => renderAnswer(command, outputFor(command), itemOf(snakeKeys(value), { next })), "result");
@@ -7918,7 +8392,8 @@ var storeMaintenanceCommands = /* @__PURE__ */ __name((messenger) => [
7918
8392
  repairCommand(messenger),
7919
8393
  resetCommand(messenger),
7920
8394
  copiesCommand(),
7921
- storeTablesCommand(messenger)
8395
+ storeTablesCommand(messenger),
8396
+ storeRecoverCommand({ command: messenger.app.command, version: messenger.app.version })
7922
8397
  ], "storeMaintenanceCommands");
7923
8398
  var refuseWhileServing = /* @__PURE__ */ __name((command, messenger) => {
7924
8399
  const serving = servingProfiles(messenger.app, environmentOf(command).env ?? process.env);
@@ -7930,7 +8405,7 @@ var repairCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("
7930
8405
  const { renderer, format } = outputFor(this);
7931
8406
  const { dryRun: dryRun2 } = this.opts();
7932
8407
  const path = storePath(environmentOf(this).env ?? process.env);
7933
- if (!existsSync7(path)) {
8408
+ if (!existsSync9(path)) {
7934
8409
  result(this, { path, exists: false });
7935
8410
  return;
7936
8411
  }
@@ -7970,7 +8445,7 @@ var notesOf = /* @__PURE__ */ __name((report, command) => {
7970
8445
  }, "notesOf");
7971
8446
  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
8447
  const path = storePath(environmentOf(this).env ?? process.env);
7973
- if (!existsSync7(path))
8448
+ if (!existsSync9(path))
7974
8449
  throw new CliError("not_found", `no store at ${path}`);
7975
8450
  const deleted = await reading(path, (database) => deleteCopy(database, name));
7976
8451
  result(this, { path, deleted });
@@ -7978,7 +8453,7 @@ var copiesCommand = /* @__PURE__ */ __name(() => new Command("copies").descripti
7978
8453
  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
8454
  const { renderer } = outputFor(this);
7980
8455
  const path = storePath(environmentOf(this).env ?? process.env);
7981
- if (!existsSync7(path)) {
8456
+ if (!existsSync9(path)) {
7982
8457
  result(this, { path, exists: false, ok: true });
7983
8458
  return;
7984
8459
  }
@@ -8041,7 +8516,7 @@ var inspect = /* @__PURE__ */ __name((path) => reading(path, (database) => {
8041
8516
  ...schema.version > 0 ? [["attachment_words", indexIntegrity(database, "attachment_words", 0)]] : []
8042
8517
  ]);
8043
8518
  const size = bytesOf2(path) + bytesOf2(`${path}-wal`);
8044
- const { bavail, bsize } = statfsSync(dirname(path));
8519
+ const { bavail, bsize } = statfsSync2(dirname2(path));
8045
8520
  const free = Number(bavail) * Number(bsize);
8046
8521
  const behind = schema.version > 0 ? chatsBehind(database) : [];
8047
8522
  const vectorIndexes = schema.version >= 34 ? vectorIndexCounts(database) : [];
@@ -8129,14 +8604,18 @@ var chatsBehind = /* @__PURE__ */ __name((database) => database.prepare(`SELECT
8129
8604
  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
8605
  const { renderer } = outputFor(this);
8131
8606
  const path = storePath(environmentOf(this).env ?? process.env);
8132
- if (!existsSync7(path)) {
8607
+ if (!existsSync9(path)) {
8133
8608
  result(this, { path, exists: false });
8134
8609
  renderer.note(`no store yet \u2014 the first \`${messenger.app.command}\` command that reads a chat creates it`);
8135
8610
  return;
8136
8611
  }
8137
8612
  const answer = await reading(path, (database) => {
8138
8613
  const from = schemaOf(database).version;
8139
- migrate(database, { command: messenger.app.command, version: messenger.app.version });
8614
+ migrate(database, {
8615
+ command: messenger.app.command,
8616
+ version: messenger.app.version,
8617
+ rollback: { store: path, warn: /* @__PURE__ */ __name((line) => renderer.warn(line), "warn") }
8618
+ });
8140
8619
  const { normalized, indexed, terms } = buildWordIndex(database, (note) => renderer.note(note));
8141
8620
  const stemmed = buildStems(database, (note) => renderer.note(note));
8142
8621
  const notes = buildNoteIndex(database, (note) => renderer.note(note));
@@ -8189,7 +8668,7 @@ var buildNoteIndex = /* @__PURE__ */ __name((database, note, { reset = false } =
8189
8668
  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
8669
  const { renderer } = outputFor(this);
8191
8670
  const path = storePath(environmentOf(this).env ?? process.env);
8192
- if (!existsSync7(path)) {
8671
+ if (!existsSync9(path)) {
8193
8672
  result(this, { path, exists: false });
8194
8673
  return;
8195
8674
  }
@@ -8218,11 +8697,11 @@ var reindexCommand = /* @__PURE__ */ __name((messenger) => destroysNothing(annot
8218
8697
  result(this, answer);
8219
8698
  }), "reindexCommand");
8220
8699
  var vacuumInto = /* @__PURE__ */ __name(async (path, target) => {
8221
- writeFileSync(target, "", { flag: "wx", mode: 384 });
8700
+ writeFileSync2(target, "", { flag: "wx", mode: 384 });
8222
8701
  try {
8223
8702
  await reading(path, (database) => database.prepare("VACUUM INTO ?").run(target));
8224
8703
  } catch (error) {
8225
- rmSync2(target, { force: true });
8704
+ rmSync3(target, { force: true });
8226
8705
  throw error;
8227
8706
  }
8228
8707
  }, "vacuumInto");
@@ -8231,9 +8710,9 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8231
8710
  const { encrypt } = this.opts();
8232
8711
  const path = storePath(environmentOf(this).env ?? process.env);
8233
8712
  const target = resolve(file2);
8234
- if (!existsSync7(path))
8713
+ if (!existsSync9(path))
8235
8714
  throw new CliError("not_found", `no store at ${path} to back up`);
8236
- if (existsSync7(target))
8715
+ if (existsSync9(target))
8237
8716
  throw new CliError("validation_error", `${target} exists \u2014 a backup never overwrites a file`);
8238
8717
  const password = encrypt ? await passwordOf(this, { twice: true }) : void 0;
8239
8718
  const copyAt = password === void 0 ? target : `${path}.backup-${process.pid}`;
@@ -8255,67 +8734,69 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8255
8734
  });
8256
8735
  } catch (error) {
8257
8736
  if (password === void 0)
8258
- rmSync2(target, { force: true });
8737
+ rmSync3(target, { force: true });
8259
8738
  throw error;
8260
8739
  } finally {
8261
8740
  if (password !== void 0)
8262
- rmSync2(copyAt, { force: true });
8741
+ rmSync3(copyAt, { force: true });
8263
8742
  }
8264
8743
  }), "backupCommand");
8265
8744
  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
8745
  const { output } = this.opts();
8267
8746
  const from = resolve(file2);
8268
8747
  const to = resolve(output);
8269
- if (!existsSync7(from))
8748
+ if (!existsSync9(from))
8270
8749
  throw new CliError("not_found", `no file at ${from}`);
8271
8750
  if (!isSealed(from))
8272
8751
  throw new CliError("validation_error", `${from} was not written with --encrypt`);
8273
- if (existsSync7(to))
8752
+ if (existsSync9(to))
8274
8753
  throw new CliError("validation_error", `${to} exists \u2014 never overwritten`);
8275
8754
  await unsealFile(from, to, await passwordOf(this, { twice: false }));
8276
8755
  result(this, { path: to, from, bytes: bytesOf2(to) });
8277
8756
  }), "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) {
8757
+ 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
8758
  const path = storePath(environmentOf(this).env ?? process.env);
8280
8759
  const given = resolve(file2);
8281
- if (!existsSync7(given))
8760
+ if (!existsSync9(given))
8282
8761
  throw new CliError("not_found", `no file at ${given}`);
8283
8762
  refuseWhileServing(this, messenger);
8284
8763
  if (!isSealed(given))
8285
8764
  return restoreFrom(this, messenger, given, given);
8286
8765
  const opened = `${path}.unsealing-${process.pid}`;
8287
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8766
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
8288
8767
  try {
8289
8768
  await unsealFile(given, opened, await passwordOf(this, { twice: false }));
8290
8769
  await restoreFrom(this, messenger, opened, given);
8291
8770
  } finally {
8292
- rmSync2(opened, { force: true });
8771
+ rmSync3(opened, { force: true });
8293
8772
  }
8294
8773
  }), "restoreCommand");
8295
8774
  var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, given) => {
8296
8775
  const { renderer } = outputFor(command);
8297
8776
  const path = storePath(environmentOf(command).env ?? process.env);
8298
- if (existsSync7(path) && realpathSync(backup) === realpathSync(path)) {
8777
+ if (existsSync9(path) && realpathSync2(backup) === realpathSync2(path)) {
8299
8778
  throw new CliError("validation_error", `${backup} is the store itself`);
8300
8779
  }
8780
+ if (await isRollbackCopy(backup))
8781
+ return rollBackFrom(command, messenger, backup);
8301
8782
  const schema = await backupSchema(backup);
8302
8783
  const stamp = stampNow();
8303
- const kept = existsSync7(path) ? `${path}.before-restore-${stamp}` : null;
8784
+ const kept = existsSync9(path) ? `${path}.before-restore-${stamp}` : null;
8304
8785
  if (kept) {
8305
8786
  const waitMs = environmentOf(command).storeLockWaitMs;
8306
8787
  await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8307
8788
  } else
8308
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8789
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
8309
8790
  const incoming = `${path}.restoring-${stamp}`;
8310
8791
  copyFileSync(backup, incoming, constants.COPYFILE_EXCL);
8311
8792
  chmodSync(incoming, 384);
8312
8793
  if (kept) {
8313
- renameSync2(path, kept);
8794
+ renameSync3(path, kept);
8314
8795
  for (const suffix of ["-wal", "-shm"])
8315
- if (existsSync7(`${path}${suffix}`))
8316
- renameSync2(`${path}${suffix}`, `${kept}${suffix}`);
8796
+ if (existsSync9(`${path}${suffix}`))
8797
+ renameSync3(`${path}${suffix}`, `${kept}${suffix}`);
8317
8798
  }
8318
- renameSync2(incoming, path);
8799
+ renameSync3(incoming, path);
8319
8800
  result(command, { path, restoredFrom: given, keptAt: kept, schema: schema.version });
8320
8801
  if (kept)
8321
8802
  renderer.note(`the store it replaced is kept at ${kept}`);
@@ -8324,6 +8805,43 @@ var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, give
8324
8805
  renderer.note(`the backup is behind this build; the next command migrates it \u2014 \`${lineOf(command, "store migrate")}\` now`);
8325
8806
  }
8326
8807
  }, "restoreFrom");
8808
+ var isRollbackCopy = /* @__PURE__ */ __name(async (file2) => {
8809
+ try {
8810
+ return await readingOnly(file2, (database) => database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'rollback_meta'").get() !== void 0);
8811
+ } catch {
8812
+ return false;
8813
+ }
8814
+ }, "isRollbackCopy");
8815
+ var rollBackFrom = /* @__PURE__ */ __name(async (command, messenger, copy) => {
8816
+ const { renderer } = outputFor(command);
8817
+ const path = storePath(environmentOf(command).env ?? process.env);
8818
+ if (!existsSync9(path))
8819
+ throw new CliError("not_found", `no store at ${path} to roll back`);
8820
+ const waitMs = environmentOf(command).storeLockWaitMs;
8821
+ await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8822
+ const { database } = await openSqlite(path);
8823
+ let rolled;
8824
+ try {
8825
+ rolled = rollBack(database, copy);
8826
+ } finally {
8827
+ database.close();
8828
+ }
8829
+ result(command, {
8830
+ path,
8831
+ restoredFrom: copy,
8832
+ rolledBack: true,
8833
+ schema: rolled.from,
8834
+ was: rolled.was,
8835
+ tables: rolled.restored,
8836
+ rebuilt: rolled.rebuilt,
8837
+ foreignKeyViolations: rolled.foreignKeyViolations
8838
+ });
8839
+ const taken = new Date(rolled.createdAt).toISOString();
8840
+ 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`);
8841
+ renderer.note("open it with the older tool and run its `store rebuild`: the search indexes are behind the tables");
8842
+ renderer.note(`a tool that speaks schema ${rolled.to} or later migrates it again on its next run`);
8843
+ renderer.note("restart every serve and mcp of either CLI that was running, so they read the restored store");
8844
+ }, "rollBackFrom");
8327
8845
  var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8328
8846
  let read;
8329
8847
  try {
@@ -8347,7 +8865,7 @@ var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8347
8865
  var STORE_LOCK_WAIT_MS = 1e3;
8348
8866
  var quiesce = /* @__PURE__ */ __name(async (path, messenger, then, warn, waitMs = STORE_LOCK_WAIT_MS) => {
8349
8867
  const { command } = messenger.app;
8350
- const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync7(file2)).map((file2) => realpathSync(file2));
8868
+ const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync9(file2)).map((file2) => realpathSync2(file2));
8351
8869
  const holders = holdersOf(files);
8352
8870
  if (holders === void 0) {
8353
8871
  warn(`this system cannot say which processes have the store open \u2014 restart every running serve and mcp after this`);
@@ -8373,7 +8891,7 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8373
8891
  const { command } = messenger.app;
8374
8892
  const env = environmentOf(this).env ?? process.env;
8375
8893
  const path = storePath(env);
8376
- if (!existsSync7(path)) {
8894
+ if (!existsSync9(path)) {
8377
8895
  result(this, { path, exists: false, reset: false });
8378
8896
  renderer.note(`no store at ${path} \u2014 nothing to reset; the first \`${command}\` command that reads a chat creates it`);
8379
8897
  return;
@@ -8409,17 +8927,17 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8409
8927
  });
8410
8928
  renderer.note(`backed the store up to ${backup}`);
8411
8929
  }
8412
- for (const suffix of STORE_PARTS)
8413
- rmSync2(`${path}${suffix}`, { force: true });
8930
+ for (const suffix of STORE_PARTS2)
8931
+ rmSync3(`${path}${suffix}`, { force: true });
8414
8932
  await (await openStore({ path, command })).close();
8415
8933
  const schema = await reading(path, (database) => schemaOf(database).version);
8416
8934
  result(this, { path, exists: true, reset: true, backup, backedUp, schema });
8417
8935
  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
8936
  }), "resetCommand");
8419
- var STORE_PARTS = ["", "-wal", "-shm"];
8937
+ var STORE_PARTS2 = ["", "-wal", "-shm"];
8420
8938
  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)));
8939
+ const files = STORE_PARTS2.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync9(file2));
8940
+ const holders = holdersOf(files.map((file2) => realpathSync2(file2)));
8423
8941
  const serving = servingProfiles(messenger.app, env).length > 0;
8424
8942
  const read = await readingOnly(path, (database) => ({
8425
8943
  schema: schemaOf(database).version,