@wirecat/tg-cli 0.117.0 → 0.119.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 (137) hide show
  1. package/contracts/wirecat.json +7621 -0
  2. package/dist/bin/tg.js +2 -2
  3. package/dist/bot/transport.d.ts.map +1 -1
  4. package/dist/bot/transport.js +15 -8
  5. package/dist/bot/transport.js.map +1 -1
  6. package/dist/bundle/{adapter-VNQ72MBK.js → adapter-NEQQOANM.js} +47 -48
  7. package/dist/bundle/{all-profiles-3W2UQTCK.js → all-profiles-QFT46FTF.js} +10 -10
  8. package/dist/bundle/{anthropic-DFUW2KTG.js → anthropic-UJ4RYCWU.js} +10 -8
  9. package/dist/bundle/{app-server-5XJIMLHB.js → app-server-NE3EL5IK.js} +43 -43
  10. package/dist/bundle/{bot-api-HRRBF3W6.js → bot-api-D4H5SCP5.js} +49 -49
  11. package/dist/bundle/{bot-history-GBH5XE4N.js → bot-history-KF2PUMWA.js} +18 -18
  12. package/dist/bundle/{bun-ZMOYGG6F.js → bun-F7MH5YKA.js} +2 -2
  13. package/dist/bundle/{bun-sqlite-6FZFMA7K.js → bun-sqlite-FYDJXUHF.js} +5 -5
  14. package/dist/bundle/{chunk-HZZGOLGP.js → chunk-23JGV5FQ.js} +11 -11
  15. package/dist/bundle/{chunk-PTIB7NEE.js → chunk-2BAJ6ORN.js} +1 -1
  16. package/dist/bundle/{chunk-L5WNE4WS.js → chunk-3EQ7USKJ.js} +2 -2
  17. package/dist/bundle/{chunk-YIXXH74F.js → chunk-3K65KTXD.js} +16 -3
  18. package/dist/bundle/{chunk-66FZBLRJ.js → chunk-4AACB23H.js} +13 -13
  19. package/dist/bundle/{chunk-NUCDEOFC.js → chunk-5EHJWIW4.js} +2 -2
  20. package/dist/bundle/{chunk-VW6BF6M7.js → chunk-5FEEFXJA.js} +1 -1
  21. package/dist/bundle/{chunk-HWYSRB64.js → chunk-65BWMPCI.js} +2 -2
  22. package/dist/bundle/{chunk-Q7O4CQDO.js → chunk-6ERQJRL2.js} +2 -2
  23. package/dist/bundle/{chunk-3GRX7WP6.js → chunk-6K5R3YPN.js} +2 -2
  24. package/dist/bundle/{chunk-KVTLT4V7.js → chunk-6OE5I3PR.js} +6 -6
  25. package/dist/bundle/{chunk-B2YPB5AE.js → chunk-72QLHHSO.js} +93 -29
  26. package/dist/bundle/{chunk-FEKXHILZ.js → chunk-7C6POLLO.js} +1 -1
  27. package/dist/bundle/{chunk-F6KBVIJP.js → chunk-7VUNJDYU.js} +22 -14
  28. package/dist/bundle/{chunk-EZTYJ43A.js → chunk-BXIPT2BO.js} +1 -1
  29. package/dist/bundle/{chunk-GFHNQBD2.js → chunk-CIDFV3IT.js} +1 -1
  30. package/dist/bundle/{chunk-C6TUVV7E.js → chunk-CX2WCEQU.js} +552 -222
  31. package/dist/bundle/{chunk-UYK5AXSW.js → chunk-D4Y2KL5V.js} +4 -4
  32. package/dist/bundle/{chunk-EL6I4WTB.js → chunk-D6YTBJY6.js} +1 -1
  33. package/dist/bundle/{chunk-X3CD475M.js → chunk-DQELQ7BL.js} +419 -198
  34. package/dist/bundle/{chunk-4JDGN6OD.js → chunk-F223KYWG.js} +1 -1
  35. package/dist/bundle/{chunk-RDH2QBUE.js → chunk-FJKP6MMP.js} +5 -3
  36. package/dist/bundle/{chunk-2452HCIV.js → chunk-FQ3C6DFV.js} +3 -3
  37. package/dist/bundle/{chunk-7Y3RUEVY.js → chunk-FQZSS3AB.js} +6 -6
  38. package/dist/bundle/{chunk-V47NPSSV.js → chunk-FRW3CWC7.js} +31 -29
  39. package/dist/bundle/{chunk-AG6HWPQP.js → chunk-G3MQOH6Z.js} +3 -3
  40. package/dist/bundle/{chunk-RDSLSV4M.js → chunk-HGMMRT4G.js} +2 -2
  41. package/dist/bundle/{chunk-SQXB5ZUZ.js → chunk-HPQQ76WF.js} +23 -5
  42. package/dist/bundle/{chunk-3RJYLN5V.js → chunk-HV5YYAJX.js} +158 -20
  43. package/dist/bundle/{chunk-3MQOLYAN.js → chunk-IAGX5VFL.js} +4 -4
  44. package/dist/bundle/{chunk-TFBHDIGY.js → chunk-JKKEMVW3.js} +18 -4
  45. package/dist/bundle/{chunk-P3ASN72F.js → chunk-KBHK5UGL.js} +1 -1
  46. package/dist/bundle/{chunk-EPCFXKTX.js → chunk-KC4MQRAB.js} +34 -8
  47. package/dist/bundle/{chunk-VMCQGZIA.js → chunk-L33G5ARH.js} +2801 -718
  48. package/dist/bundle/{chunk-V2T7NYNU.js → chunk-MDLSI3EN.js} +25 -23
  49. package/dist/bundle/chunk-NDSRND3E.js +138 -0
  50. package/dist/bundle/{chunk-HORGORHK.js → chunk-OG2CG2GS.js} +12 -12
  51. package/dist/bundle/{chunk-ZPILMEFY.js → chunk-QD27C3BG.js} +8 -21
  52. package/dist/bundle/{chunk-QOGYHU3Q.js → chunk-QG5U6HCI.js} +61 -21
  53. package/dist/bundle/{chunk-TG6ZYL4B.js → chunk-QQ3QZFFD.js} +8 -8
  54. package/dist/bundle/{chunk-56Q5JV3Z.js → chunk-QTFXYR5W.js} +24 -2
  55. package/dist/bundle/{chunk-FAHHERJ7.js → chunk-RGU2G3KL.js} +4 -4
  56. package/dist/bundle/{chunk-Z4QKLHJW.js → chunk-ROOUBFUW.js} +10148 -3906
  57. package/dist/bundle/{chunk-MLHKQDUN.js → chunk-RUNFFBJU.js} +872 -562
  58. package/dist/bundle/{chunk-G7B5UIE7.js → chunk-S3HAFJVC.js} +37 -11
  59. package/dist/bundle/{chunk-BXTDAGM4.js → chunk-SMHLQEE2.js} +2 -2
  60. package/dist/bundle/{chunk-JWIUK3SK.js → chunk-TEZKCH5B.js} +2 -2
  61. package/dist/bundle/{chunk-VRDVXXXD.js → chunk-TKHEVAEG.js} +9 -8
  62. package/dist/bundle/{chunk-MP7M6FFU.js → chunk-TT4CIXVH.js} +6 -6
  63. package/dist/bundle/{chunk-M7V5XRM6.js → chunk-UBCLVM7C.js} +3 -3
  64. package/dist/bundle/{chunk-YHZFGUAP.js → chunk-V5Z2JO6X.js} +19 -19
  65. package/dist/bundle/{chunk-6GFUL4OU.js → chunk-W2BIBPRU.js} +237 -38
  66. package/dist/bundle/{chunk-6HRN7BW6.js → chunk-X5PDWCG7.js} +1 -1
  67. package/dist/bundle/{chunk-AUBRELCM.js → chunk-XDMJVWWR.js} +3 -3
  68. package/dist/bundle/{chunk-EA2PGDER.js → chunk-XM3P7LLT.js} +2 -2
  69. package/dist/bundle/{chunk-UGPZCNYC.js → chunk-YMWPRHXG.js} +1411 -809
  70. package/dist/bundle/{chunk-2XLKZL6K.js → chunk-Z4CGZAFQ.js} +65 -31
  71. package/dist/bundle/{chunk-XW5C4TI7.js → chunk-ZEQ7ONPZ.js} +47 -1
  72. package/dist/bundle/command-contract-7TGMZRBE.js +33 -0
  73. package/dist/bundle/{decode-YMSOY2AY.js → decode-5N4ERCHC.js} +5 -5
  74. package/dist/bundle/{dispatch-OP27MWX5.js → dispatch-TBGXBDHE.js} +10 -10
  75. package/dist/bundle/{echarts-7XS55TQY.js → echarts-YDEBAMXT.js} +2 -2
  76. package/dist/bundle/{embed-QTOE7NN3.js → embed-T7H62XFR.js} +6 -6
  77. package/dist/bundle/{embedder-KBBRYSNH.js → embedder-AW3O2TR3.js} +9 -9
  78. package/dist/bundle/{entry-HGEUYYMX.js → entry-L2LJ2VPY.js} +7 -7
  79. package/dist/bundle/{failure-4JUQFXJT.js → failure-AWHPW2HE.js} +2 -2
  80. package/dist/bundle/{first-run-CSGMEJXY.js → first-run-6PBZSRZU.js} +11 -11
  81. package/dist/bundle/first-screen-UKCD7D2R.js +31 -0
  82. package/dist/bundle/{instructions-S6ZXCTFH.js → instructions-C3NJERO7.js} +1 -1
  83. package/dist/bundle/{mcp-M4QN2E7R.js → mcp-CWLASTLV.js} +2 -2
  84. package/dist/bundle/{node-LCIUWXXG.js → node-P3CIIYWU.js} +2 -2
  85. package/dist/bundle/{node-sqlite-HL4WY4N2.js → node-sqlite-YVHMNRVA.js} +6 -6
  86. package/dist/bundle/{oauth-U4KIMDKG.js → oauth-5OQYA2SV.js} +7 -7
  87. package/dist/bundle/{open-EH7OS7M7.js → open-YGWUVSU7.js} +5 -5
  88. package/dist/bundle/{openai-W5TB3NA5.js → openai-U45JBQ6F.js} +16 -37
  89. package/dist/bundle/{process-3CVLTCTA.js → process-DCYX5EDG.js} +1 -1
  90. package/dist/bundle/{program-LOIZTK2P.js → program-UZBFH2EZ.js} +55 -52
  91. package/dist/bundle/{prompt-IDNH7N3W.js → prompt-HPVTPTFI.js} +7 -5
  92. package/dist/bundle/{proxy-transport-4DPZB2W2.js → proxy-transport-D7MCHGSV.js} +5 -5
  93. package/dist/bundle/{recognize-G5EWYXIF.js → recognize-IJCPFJ76.js} +4 -4
  94. package/dist/bundle/{remote-4XTBZVZD.js → remote-MWDYQWFW.js} +7 -7
  95. package/dist/bundle/{rerank-OWSTDLZN.js → rerank-SXG64475.js} +7 -7
  96. package/dist/bundle/{serve-YCPSEWP3.js → serve-KJQENHEH.js} +9 -9
  97. package/dist/bundle/{server-ODG4A2KK.js → server-MXVXZWN6.js} +35 -35
  98. package/dist/bundle/server-RTMCRKQF.js +60 -0
  99. package/dist/bundle/{state-OL2235G5.js → state-CKKJWH27.js} +6 -6
  100. package/dist/bundle/{store-5AACYNDM.js → store-R3BE4V56.js} +44 -13
  101. package/dist/bundle/store-maintenance-command-KDGBSBNU.js +49 -0
  102. package/dist/bundle/tg.js +38 -14
  103. package/dist/commands/account-removal.d.ts +3 -0
  104. package/dist/commands/account-removal.d.ts.map +1 -0
  105. package/dist/commands/account-removal.js +57 -0
  106. package/dist/commands/account-removal.js.map +1 -0
  107. package/dist/commands/context.d.ts.map +1 -1
  108. package/dist/commands/context.js +2 -0
  109. package/dist/commands/context.js.map +1 -1
  110. package/dist/http.d.ts +6 -0
  111. package/dist/http.d.ts.map +1 -0
  112. package/dist/http.js +8 -0
  113. package/dist/http.js.map +1 -0
  114. package/dist/identity.d.ts +4 -0
  115. package/dist/identity.d.ts.map +1 -1
  116. package/dist/identity.js +14 -0
  117. package/dist/identity.js.map +1 -1
  118. package/dist/telegram/map.d.ts.map +1 -1
  119. package/dist/telegram/map.js +3 -0
  120. package/dist/telegram/map.js.map +1 -1
  121. package/dist/telegram/registration.d.ts +1 -1
  122. package/dist/telegram/registration.d.ts.map +1 -1
  123. package/dist/telegram/registration.js +4 -1
  124. package/dist/telegram/registration.js.map +1 -1
  125. package/dist/version.d.ts +1 -1
  126. package/dist/version.js +1 -1
  127. package/dist/wcat.d.ts +3 -0
  128. package/dist/wcat.d.ts.map +1 -0
  129. package/dist/wcat.js +4 -0
  130. package/dist/wcat.js.map +1 -0
  131. package/package.json +7 -6
  132. package/dist/bundle/chunk-7NBUT62O.js +0 -33
  133. package/dist/bundle/command-contract-KMMHARMR.js +0 -33
  134. package/dist/bundle/first-screen-K2PBNJNE.js +0 -31
  135. package/dist/bundle/server-KELKX6S3.js +0 -60
  136. package/dist/bundle/store-maintenance-command-3J7WZYVN.js +0 -50
  137. /package/dist/bundle/{chunk-VOXIGICJ.js → chunk-DWX4DE2I.js} +0 -0
@@ -3,14 +3,17 @@ const require = __bundleRequire(import.meta.url);
3
3
  import {
4
4
  answerOf,
5
5
  messengerContext
6
- } from "./chunk-V2T7NYNU.js";
6
+ } from "./chunk-MDLSI3EN.js";
7
7
  import {
8
8
  FETCHING,
9
9
  RULES_VERSION,
10
10
  applyTaskRulesOnArrival,
11
11
  capability,
12
12
  chatEventAnswer,
13
+ embeddingKeys,
14
+ endpointKeyName,
13
15
  memberAnswer,
16
+ modelGateway,
14
17
  newSendId,
15
18
  onlineDeps,
16
19
  openRequestTask,
@@ -24,13 +27,14 @@ import {
24
27
  typedQuery,
25
28
  withQuery,
26
29
  withTimeLimit
27
- } from "./chunk-UGPZCNYC.js";
30
+ } from "./chunk-YMWPRHXG.js";
28
31
  import {
29
32
  QUICK_HEALTH_CHECKS,
30
33
  explainDamage,
31
34
  fts5Tables,
35
+ invalidJson,
32
36
  storeHealth
33
- } from "./chunk-G7B5UIE7.js";
37
+ } from "./chunk-S3HAFJVC.js";
34
38
  import {
35
39
  stringWidth,
36
40
  wrapAnsi
@@ -45,7 +49,6 @@ import {
45
49
  codeOf,
46
50
  currentRun,
47
51
  destroysNothing,
48
- endpoint,
49
52
  environmentOf,
50
53
  itemOf,
51
54
  jsonlRecords,
@@ -62,23 +65,17 @@ import {
62
65
  snakeKeys,
63
66
  storeTable,
64
67
  withoutProviderRefs
65
- } from "./chunk-X3CD475M.js";
66
- import {
67
- failureKey
68
- } from "./chunk-ZPILMEFY.js";
69
- import {
70
- envName
71
- } from "./chunk-Q7O4CQDO.js";
68
+ } from "./chunk-DQELQ7BL.js";
72
69
  import {
73
70
  holdLock,
74
71
  lockPath,
75
72
  releaseLock,
76
73
  servingProfiles,
77
74
  takeLock
78
- } from "./chunk-AUBRELCM.js";
75
+ } from "./chunk-XDMJVWWR.js";
79
76
  import {
80
77
  holdersOf
81
- } from "./chunk-EL6I4WTB.js";
78
+ } from "./chunk-D6YTBJY6.js";
82
79
  import {
83
80
  CORPORA,
84
81
  MIGRATIONS,
@@ -93,6 +90,7 @@ import {
93
90
  fillVectorIndexes,
94
91
  formatLocator,
95
92
  involvementStoreOver,
93
+ isDerivedTable,
96
94
  migrate,
97
95
  noteIndexState,
98
96
  openSqlite,
@@ -114,44 +112,38 @@ import {
114
112
  storeClients,
115
113
  storeContents,
116
114
  vectorIndexCounts
117
- } from "./chunk-Z4QKLHJW.js";
118
- import {
119
- queryFieldsOf
120
- } from "./chunk-C6TUVV7E.js";
115
+ } from "./chunk-ROOUBFUW.js";
121
116
  import {
122
- readSecret
123
- } from "./chunk-SQXB5ZUZ.js";
117
+ queryFieldsOf,
118
+ readDamageMark,
119
+ readHealthMark,
120
+ recordDeepCheck
121
+ } from "./chunk-CX2WCEQU.js";
124
122
  import {
125
- checkedOptions,
126
- range
127
- } from "./chunk-7NBUT62O.js";
123
+ failureKey,
124
+ isStoreDamage
125
+ } from "./chunk-ZEQ7ONPZ.js";
128
126
  import {
129
- messagesFor,
130
- systemFor,
131
- validateImages
132
- } from "./chunk-56Q5JV3Z.js";
127
+ readSecret
128
+ } from "./chunk-HPQQ76WF.js";
133
129
  import {
134
130
  storePath
135
- } from "./chunk-3GRX7WP6.js";
131
+ } from "./chunk-6K5R3YPN.js";
136
132
  import {
137
133
  openCache
138
- } from "./chunk-MP7M6FFU.js";
134
+ } from "./chunk-TT4CIXVH.js";
139
135
  import {
140
- Credentials,
141
- pathsAreOverridden,
142
136
  resolvePaths,
143
137
  writeSecurely
144
- } from "./chunk-YHZFGUAP.js";
138
+ } from "./chunk-V5Z2JO6X.js";
145
139
  import {
146
140
  array,
147
141
  boolean,
148
142
  check,
149
143
  forward,
150
144
  getDotPath,
151
- integer,
152
145
  minLength,
153
146
  nullable,
154
- number,
155
147
  object,
156
148
  optional,
157
149
  parse,
@@ -163,14 +155,13 @@ import {
163
155
  strictObject,
164
156
  string,
165
157
  transform,
166
- trim,
167
- union
168
- } from "./chunk-EPCFXKTX.js";
158
+ trim
159
+ } from "./chunk-KC4MQRAB.js";
169
160
  import {
170
161
  CliError,
171
162
  singleLine,
172
163
  visibleControls
173
- } from "./chunk-BXTDAGM4.js";
164
+ } from "./chunk-SMHLQEE2.js";
174
165
  import {
175
166
  __commonJS,
176
167
  __name,
@@ -348,14 +339,14 @@ var require_liquid_node = __commonJS({
348
339
  return value !== null && (type === "object" || type === "function");
349
340
  }
350
341
  __name(isObject, "isObject");
351
- function range2(start, stop, step = 1) {
342
+ function range(start, stop, step = 1) {
352
343
  const arr = [];
353
344
  for (let i = start; i < stop; i += step) {
354
345
  arr.push(i);
355
346
  }
356
347
  return arr;
357
348
  }
358
- __name(range2, "range");
349
+ __name(range, "range");
359
350
  function padStart(str, length, ch = " ") {
360
351
  return pad(str, length, ch, (str2, ch2) => ch2 + str2);
361
352
  }
@@ -549,7 +540,7 @@ var require_liquid_node = __commonJS({
549
540
  const lines = token.input.split("\n");
550
541
  const begin = Math.max(line - 2, 1);
551
542
  const end = Math.min(line + 3, lines.length);
552
- const context = range2(begin, end + 1).map((lineNumber) => {
543
+ const context = range(begin, end + 1).map((lineNumber) => {
553
544
  const rowIndicator = lineNumber === line ? ">> " : " ";
554
545
  const num = padStart(String(lineNumber), String(end).length);
555
546
  let text = `${rowIndicator}${num}| `;
@@ -1127,8 +1118,8 @@ var require_liquid_node = __commonJS({
1127
1118
  valid() {
1128
1119
  return !isNaN(this.getTime());
1129
1120
  }
1130
- format(options2) {
1131
- return this.DateTimeFormat && this.DateTimeFormat(this.locale, options2).format(this.displayDate);
1121
+ format(options) {
1122
+ return this.DateTimeFormat && this.DateTimeFormat(this.locale, options).format(this.displayDate);
1132
1123
  }
1133
1124
  /**
1134
1125
  * Create a Date object fixed to it's declared Timezone. Both
@@ -1212,11 +1203,11 @@ var require_liquid_node = __commonJS({
1212
1203
  static {
1213
1204
  __name(this, "TagToken");
1214
1205
  }
1215
- constructor(input, begin, end, options2, file2) {
1216
- const { trimTagLeft, trimTagRight, tagDelimiterLeft, tagDelimiterRight } = options2;
1206
+ constructor(input, begin, end, options, file2) {
1207
+ const { trimTagLeft, trimTagRight, tagDelimiterLeft, tagDelimiterRight } = options;
1217
1208
  const [valueBegin, valueEnd] = [begin + tagDelimiterLeft.length, end - tagDelimiterRight.length];
1218
1209
  super(exports.TokenKind.Tag, [valueBegin, valueEnd], input, begin, end, trimTagLeft, trimTagRight, file2);
1219
- this.tokenizer = new Tokenizer(input, options2.operators, file2, this.contentRange, options2.groupedExpressions);
1210
+ this.tokenizer = new Tokenizer(input, options.operators, file2, this.contentRange, options.groupedExpressions);
1220
1211
  this.name = this.tokenizer.readTagName();
1221
1212
  this.tokenizer.assert(this.name, `illegal tag syntax, tag name expected`);
1222
1213
  this.tokenizer.skipBlank();
@@ -1227,8 +1218,8 @@ var require_liquid_node = __commonJS({
1227
1218
  static {
1228
1219
  __name(this, "OutputToken");
1229
1220
  }
1230
- constructor(input, begin, end, options2, file2) {
1231
- const { trimOutputLeft, trimOutputRight, outputDelimiterLeft, outputDelimiterRight } = options2;
1221
+ constructor(input, begin, end, options, file2) {
1222
+ const { trimOutputLeft, trimOutputRight, outputDelimiterLeft, outputDelimiterRight } = options;
1232
1223
  const valueRange = [begin + outputDelimiterLeft.length, end - outputDelimiterRight.length];
1233
1224
  super(exports.TokenKind.Output, valueRange, input, begin, end, trimOutputLeft, trimOutputRight, file2);
1234
1225
  }
@@ -1447,9 +1438,9 @@ var require_liquid_node = __commonJS({
1447
1438
  static {
1448
1439
  __name(this, "LiquidTagToken");
1449
1440
  }
1450
- constructor(input, begin, end, options2, file2) {
1441
+ constructor(input, begin, end, options, file2) {
1451
1442
  super(exports.TokenKind.Tag, [begin, end], input, begin, end, false, false, file2);
1452
- this.tokenizer = new Tokenizer(input, options2.operators, file2, this.contentRange, options2.groupedExpressions);
1443
+ this.tokenizer = new Tokenizer(input, options.operators, file2, this.contentRange, options.groupedExpressions);
1453
1444
  this.name = this.tokenizer.readTagName();
1454
1445
  this.tokenizer.assert(this.name, "illegal liquid tag syntax");
1455
1446
  this.tokenizer.skipBlank();
@@ -1523,11 +1514,11 @@ var require_liquid_node = __commonJS({
1523
1514
  static {
1524
1515
  __name(this, "Filter");
1525
1516
  }
1526
- constructor(token, options2, liquid) {
1517
+ constructor(token, options, liquid) {
1527
1518
  this.token = token;
1528
1519
  this.name = token.name;
1529
- this.handler = isFunction(options2) ? options2 : isFunction(options2?.handler) ? options2.handler : identify;
1530
- this.raw = !isFunction(options2) && !!options2?.raw;
1520
+ this.handler = isFunction(options) ? options : isFunction(options?.handler) ? options.handler : identify;
1521
+ this.raw = !isFunction(options) && !!options?.raw;
1531
1522
  this.args = token.args;
1532
1523
  this.liquid = liquid;
1533
1524
  }
@@ -1630,7 +1621,7 @@ var require_liquid_node = __commonJS({
1630
1621
  const low = yield evalTokenValue(token.lhs, ctx);
1631
1622
  const high = yield evalTokenValue(token.rhs, ctx);
1632
1623
  ctx.memoryLimit.use(high - low + 1);
1633
- return range2(+low, +high + 1);
1624
+ return range(+low, +high + 1);
1634
1625
  }
1635
1626
  __name(evalRangeToken, "evalRangeToken");
1636
1627
  function* toPostfix(tokens) {
@@ -1824,7 +1815,7 @@ var require_liquid_node = __commonJS({
1824
1815
  return readFileAsync(filepath, "utf8");
1825
1816
  }
1826
1817
  __name(readFile, "readFile");
1827
- function existsSync10(filepath) {
1818
+ function existsSync11(filepath) {
1828
1819
  try {
1829
1820
  fs$1.statSync(filepath);
1830
1821
  return true;
@@ -1832,11 +1823,11 @@ var require_liquid_node = __commonJS({
1832
1823
  return false;
1833
1824
  }
1834
1825
  }
1835
- __name(existsSync10, "existsSync");
1836
- function readFileSync5(filepath) {
1826
+ __name(existsSync11, "existsSync");
1827
+ function readFileSync6(filepath) {
1837
1828
  return fs$1.readFileSync(filepath, "utf8");
1838
1829
  }
1839
- __name(readFileSync5, "readFileSync");
1830
+ __name(readFileSync6, "readFileSync");
1840
1831
  function resolve2(root, file2, ext) {
1841
1832
  if (!path.extname(file2))
1842
1833
  file2 += ext;
@@ -1850,10 +1841,10 @@ var require_liquid_node = __commonJS({
1850
1841
  }
1851
1842
  }
1852
1843
  __name(fallback, "fallback");
1853
- function dirname3(filepath) {
1844
+ function dirname4(filepath) {
1854
1845
  return path.dirname(filepath);
1855
1846
  }
1856
- __name(dirname3, "dirname");
1847
+ __name(dirname4, "dirname");
1857
1848
  var realpathAsync = promisify(fs$1.realpath);
1858
1849
  async function contains(root, file2) {
1859
1850
  try {
@@ -1881,11 +1872,11 @@ var require_liquid_node = __commonJS({
1881
1872
  __proto__: null,
1882
1873
  exists,
1883
1874
  readFile,
1884
- existsSync: existsSync10,
1885
- readFileSync: readFileSync5,
1875
+ existsSync: existsSync11,
1876
+ readFileSync: readFileSync6,
1886
1877
  resolve: resolve2,
1887
1878
  fallback,
1888
- dirname: dirname3,
1879
+ dirname: dirname4,
1889
1880
  contains,
1890
1881
  containsSync,
1891
1882
  sep: path.sep
@@ -2111,41 +2102,41 @@ var require_liquid_node = __commonJS({
2111
2102
  parseLimit: Infinity,
2112
2103
  renderLimit: Infinity
2113
2104
  };
2114
- function normalize(options2) {
2115
- if (options2.hasOwnProperty("root")) {
2116
- if (!options2.hasOwnProperty("partials"))
2117
- options2.partials = options2.root;
2118
- if (!options2.hasOwnProperty("layouts"))
2119
- options2.layouts = options2.root;
2120
- }
2121
- if (options2.hasOwnProperty("cache")) {
2105
+ function normalize(options) {
2106
+ if (options.hasOwnProperty("root")) {
2107
+ if (!options.hasOwnProperty("partials"))
2108
+ options.partials = options.root;
2109
+ if (!options.hasOwnProperty("layouts"))
2110
+ options.layouts = options.root;
2111
+ }
2112
+ if (options.hasOwnProperty("cache")) {
2122
2113
  let cache;
2123
- if (typeof options2.cache === "number")
2124
- cache = options2.cache > 0 ? new LRU(options2.cache) : void 0;
2125
- else if (typeof options2.cache === "object")
2126
- cache = options2.cache;
2114
+ if (typeof options.cache === "number")
2115
+ cache = options.cache > 0 ? new LRU(options.cache) : void 0;
2116
+ else if (typeof options.cache === "object")
2117
+ cache = options.cache;
2127
2118
  else
2128
- cache = options2.cache ? new LRU(1024) : void 0;
2129
- options2.cache = cache;
2119
+ cache = options.cache ? new LRU(1024) : void 0;
2120
+ options.cache = cache;
2130
2121
  }
2131
- options2 = { ...defaultOptions, ...options2.jekyllInclude ? { dynamicPartials: false } : {}, ...options2 };
2132
- if ((!options2.fs.dirname || !options2.fs.sep) && options2.relativeReference) {
2122
+ options = { ...defaultOptions, ...options.jekyllInclude ? { dynamicPartials: false } : {}, ...options };
2123
+ if ((!options.fs.dirname || !options.fs.sep) && options.relativeReference) {
2133
2124
  console.warn("[LiquidJS] `fs.dirname` and `fs.sep` are required for relativeReference, set relativeReference to `false` to suppress this warning");
2134
- options2.relativeReference = false;
2125
+ options.relativeReference = false;
2135
2126
  }
2136
- options2.root = normalizeDirectoryList(options2.root);
2137
- options2.partials = normalizeDirectoryList(options2.partials);
2138
- options2.layouts = normalizeDirectoryList(options2.layouts);
2139
- options2.outputEscape = options2.outputEscape && getOutputEscapeFunction(options2.outputEscape);
2140
- if (!options2.locale) {
2141
- options2.locale = getDateTimeFormat()?.().resolvedOptions().locale ?? "en-US";
2127
+ options.root = normalizeDirectoryList(options.root);
2128
+ options.partials = normalizeDirectoryList(options.partials);
2129
+ options.layouts = normalizeDirectoryList(options.layouts);
2130
+ options.outputEscape = options.outputEscape && getOutputEscapeFunction(options.outputEscape);
2131
+ if (!options.locale) {
2132
+ options.locale = getDateTimeFormat()?.().resolvedOptions().locale ?? "en-US";
2142
2133
  }
2143
- if (options2.templates) {
2144
- options2.fs = new MapFS(options2.templates);
2145
- options2.relativeReference = true;
2146
- options2.root = options2.partials = options2.layouts = ".";
2134
+ if (options.templates) {
2135
+ options.fs = new MapFS(options.templates);
2136
+ options.relativeReference = true;
2137
+ options.root = options.partials = options.layouts = ".";
2147
2138
  }
2148
- return options2;
2139
+ return options;
2149
2140
  }
2150
2141
  __name(normalize, "normalize");
2151
2142
  function getOutputEscapeFunction(nameOrFunction) {
@@ -2166,14 +2157,14 @@ var require_liquid_node = __commonJS({
2166
2157
  return list;
2167
2158
  }
2168
2159
  __name(normalizeDirectoryList, "normalizeDirectoryList");
2169
- function whiteSpaceCtrl(tokens, options2) {
2160
+ function whiteSpaceCtrl(tokens, options) {
2170
2161
  let inRaw = false;
2171
2162
  for (let i = 0; i < tokens.length; i++) {
2172
2163
  const token = tokens[i];
2173
2164
  if (!isDelimitedToken(token))
2174
2165
  continue;
2175
2166
  if (!inRaw && token.trimLeft) {
2176
- trimLeft(tokens[i - 1], options2.greedy);
2167
+ trimLeft(tokens[i - 1], options.greedy);
2177
2168
  }
2178
2169
  if (isTagToken(token)) {
2179
2170
  if (token.name === "raw")
@@ -2182,7 +2173,7 @@ var require_liquid_node = __commonJS({
2182
2173
  inRaw = false;
2183
2174
  }
2184
2175
  if (!inRaw && token.trimRight) {
2185
- trimRight(tokens[i + 1], options2.greedy);
2176
+ trimRight(tokens[i + 1], options.greedy);
2186
2177
  }
2187
2178
  }
2188
2179
  }
@@ -2209,12 +2200,12 @@ var require_liquid_node = __commonJS({
2209
2200
  static {
2210
2201
  __name(this, "Tokenizer");
2211
2202
  }
2212
- constructor(input, operators = defaultOptions.operators, file2, range3, groupedExpressions = false) {
2203
+ constructor(input, operators = defaultOptions.operators, file2, range2, groupedExpressions = false) {
2213
2204
  this.input = input;
2214
2205
  this.file = file2;
2215
2206
  this.rawBeginAt = -1;
2216
- this.p = range3 ? range3[0] : 0;
2217
- this.N = range3 ? range3[1] : input.length;
2207
+ this.p = range2 ? range2[0] : 0;
2208
+ this.N = range2 ? range2[1] : input.length;
2218
2209
  this.opTrie = createTrie(operators);
2219
2210
  this.literalTrie = createTrie(literalValues);
2220
2211
  this.groupedExpressions = groupedExpressions;
@@ -2314,23 +2305,23 @@ var require_liquid_node = __commonJS({
2314
2305
  const value = this.readValue();
2315
2306
  return [key.getText(), value];
2316
2307
  }
2317
- readTopLevelTokens(options2 = defaultOptions) {
2308
+ readTopLevelTokens(options = defaultOptions) {
2318
2309
  const tokens = [];
2319
2310
  while (this.p < this.N) {
2320
- const token = this.readTopLevelToken(options2);
2311
+ const token = this.readTopLevelToken(options);
2321
2312
  tokens.push(token);
2322
2313
  }
2323
- whiteSpaceCtrl(tokens, options2);
2314
+ whiteSpaceCtrl(tokens, options);
2324
2315
  return tokens;
2325
2316
  }
2326
- readTopLevelToken(options2) {
2327
- const { tagDelimiterLeft, outputDelimiterLeft } = options2;
2317
+ readTopLevelToken(options) {
2318
+ const { tagDelimiterLeft, outputDelimiterLeft } = options;
2328
2319
  if (this.rawBeginAt > -1)
2329
- return this.readEndrawOrRawContent(options2);
2320
+ return this.readEndrawOrRawContent(options);
2330
2321
  if (this.match(tagDelimiterLeft))
2331
- return this.readTagToken(options2);
2322
+ return this.readTagToken(options);
2332
2323
  if (this.match(outputDelimiterLeft))
2333
- return this.readOutputToken(options2);
2324
+ return this.readOutputToken(options);
2334
2325
  return this.readHTMLToken([tagDelimiterLeft, outputDelimiterLeft]);
2335
2326
  }
2336
2327
  readHTMLToken(stopStrings) {
@@ -2342,13 +2333,13 @@ var require_liquid_node = __commonJS({
2342
2333
  }
2343
2334
  return new HTMLToken(this.input, begin, this.p, this.file);
2344
2335
  }
2345
- readTagToken(options2) {
2336
+ readTagToken(options) {
2346
2337
  const { file: file2, input } = this;
2347
2338
  const begin = this.p;
2348
- if (this.readToDelimiter(options2.tagDelimiterRight) === -1) {
2339
+ if (this.readToDelimiter(options.tagDelimiterRight) === -1) {
2349
2340
  throw this.error(`tag ${this.snapshot(begin)} not closed`, begin);
2350
2341
  }
2351
- const token = new TagToken(input, begin, this.p, options2, file2);
2342
+ const token = new TagToken(input, begin, this.p, options, file2);
2352
2343
  if (token.name === "raw")
2353
2344
  this.rawBeginAt = begin;
2354
2345
  return token;
@@ -2366,17 +2357,17 @@ var require_liquid_node = __commonJS({
2366
2357
  }
2367
2358
  return -1;
2368
2359
  }
2369
- readOutputToken(options2 = defaultOptions) {
2360
+ readOutputToken(options = defaultOptions) {
2370
2361
  const { file: file2, input } = this;
2371
- const { outputDelimiterRight } = options2;
2362
+ const { outputDelimiterRight } = options;
2372
2363
  const begin = this.p;
2373
2364
  if (this.readToDelimiter(outputDelimiterRight, true) === -1) {
2374
2365
  throw this.error(`output ${this.snapshot(begin)} not closed`, begin);
2375
2366
  }
2376
- return new OutputToken(input, begin, this.p, options2, file2);
2367
+ return new OutputToken(input, begin, this.p, options, file2);
2377
2368
  }
2378
- readEndrawOrRawContent(options2) {
2379
- const { tagDelimiterLeft, tagDelimiterRight } = options2;
2369
+ readEndrawOrRawContent(options) {
2370
+ const { tagDelimiterLeft, tagDelimiterRight } = options;
2380
2371
  const begin = this.p;
2381
2372
  let leftPos = this.readTo(tagDelimiterLeft) - tagDelimiterLeft.length;
2382
2373
  while (this.p < this.N) {
@@ -2389,7 +2380,7 @@ var require_liquid_node = __commonJS({
2389
2380
  const end = this.p;
2390
2381
  if (begin === leftPos) {
2391
2382
  this.rawBeginAt = -1;
2392
- return new TagToken(this.input, begin, end, options2, this.file);
2383
+ return new TagToken(this.input, begin, end, options, this.file);
2393
2384
  } else {
2394
2385
  this.p = leftPos;
2395
2386
  return new HTMLToken(this.input, begin, leftPos, this.file);
@@ -2402,22 +2393,22 @@ var require_liquid_node = __commonJS({
2402
2393
  }
2403
2394
  throw this.error(`raw ${this.snapshot(this.rawBeginAt)} not closed`, begin);
2404
2395
  }
2405
- readLiquidTagTokens(options2 = defaultOptions) {
2396
+ readLiquidTagTokens(options = defaultOptions) {
2406
2397
  const tokens = [];
2407
2398
  while (this.p < this.N) {
2408
- const token = this.readLiquidTagToken(options2);
2399
+ const token = this.readLiquidTagToken(options);
2409
2400
  token && tokens.push(token);
2410
2401
  }
2411
2402
  return tokens;
2412
2403
  }
2413
- readLiquidTagToken(options2) {
2404
+ readLiquidTagToken(options) {
2414
2405
  this.skipBlank();
2415
2406
  if (this.end())
2416
2407
  return;
2417
2408
  const begin = this.p;
2418
2409
  this.readToDelimiter("\n");
2419
2410
  const end = this.p;
2420
- return new LiquidTagToken(this.input, begin, end, options2, this.file);
2411
+ return new LiquidTagToken(this.input, begin, end, options, this.file);
2421
2412
  }
2422
2413
  error(msg, pos = this.p) {
2423
2414
  return new TokenizationError(msg, new IdentifierToken(this.input, pos, this.N, this.file));
@@ -2629,12 +2620,12 @@ var require_liquid_node = __commonJS({
2629
2620
  }
2630
2621
  return new QuotedToken(this.input, begin, this.p, this.file);
2631
2622
  }
2632
- *readFileNameTemplate(options2) {
2633
- const { outputDelimiterLeft } = options2;
2623
+ *readFileNameTemplate(options) {
2624
+ const { outputDelimiterLeft } = options;
2634
2625
  const htmlStopStrings = [",", " ", "\r", "\n", " ", outputDelimiterLeft];
2635
2626
  const htmlStopStringSet = new Set(htmlStopStrings);
2636
2627
  while (this.p < this.N && !htmlStopStringSet.has(this.peek())) {
2637
- yield this.match(outputDelimiterLeft) ? this.readOutputToken(options2) : this.readHTMLToken(htmlStopStrings);
2628
+ yield this.match(outputDelimiterLeft) ? this.readOutputToken(options) : this.readHTMLToken(htmlStopStrings);
2638
2629
  }
2639
2630
  }
2640
2631
  match(word) {
@@ -2709,7 +2700,7 @@ var require_liquid_node = __commonJS({
2709
2700
  this.token = token;
2710
2701
  }
2711
2702
  };
2712
- var Tag2 = class extends TemplateImpl {
2703
+ var Tag3 = class extends TemplateImpl {
2713
2704
  static {
2714
2705
  __name(this, "Tag");
2715
2706
  }
@@ -2739,17 +2730,17 @@ var require_liquid_node = __commonJS({
2739
2730
  return hash2;
2740
2731
  }
2741
2732
  };
2742
- function createTagClass(options2) {
2743
- return class extends Tag2 {
2733
+ function createTagClass(options) {
2734
+ return class extends Tag3 {
2744
2735
  constructor(token, tokens, liquid) {
2745
2736
  super(token, tokens, liquid);
2746
- if (isFunction(options2.parse)) {
2747
- options2.parse.call(this, token, tokens);
2737
+ if (isFunction(options.parse)) {
2738
+ options.parse.call(this, token, tokens);
2748
2739
  }
2749
2740
  }
2750
2741
  *render(ctx, emitter) {
2751
2742
  const hash2 = yield new Hash(this.token.args, ctx.opts.keyValueSeparator).render(ctx);
2752
- return yield options2.render.call(this, ctx, emitter, hash2);
2743
+ return yield options.render.call(this, ctx, emitter, hash2);
2753
2744
  }
2754
2745
  };
2755
2746
  }
@@ -2966,13 +2957,13 @@ var require_liquid_node = __commonJS({
2966
2957
  };
2967
2958
  }
2968
2959
  __name(_analyze, "_analyze");
2969
- function analyze(template2, options2 = {}) {
2970
- const opts = { ...defaultStaticAnalysisOptions, ...options2 };
2960
+ function analyze(template2, options = {}) {
2961
+ const opts = { ...defaultStaticAnalysisOptions, ...options };
2971
2962
  return toPromise(_analyze(template2, opts.partials, false));
2972
2963
  }
2973
2964
  __name(analyze, "analyze");
2974
- function analyzeSync(template2, options2 = {}) {
2975
- const opts = { ...defaultStaticAnalysisOptions, ...options2 };
2965
+ function analyzeSync(template2, options = {}) {
2966
+ const opts = { ...defaultStaticAnalysisOptions, ...options };
2976
2967
  return toValueSync(_analyze(template2, opts.partials, true));
2977
2968
  }
2978
2969
  __name(analyzeSync, "analyzeSync");
@@ -3148,17 +3139,17 @@ var require_liquid_node = __commonJS({
3148
3139
  static {
3149
3140
  __name(this, "Loader");
3150
3141
  }
3151
- constructor(options2) {
3152
- this.options = options2;
3153
- if (options2.relativeReference) {
3154
- const sep = options2.fs.sep;
3142
+ constructor(options) {
3143
+ this.options = options;
3144
+ if (options.relativeReference) {
3145
+ const sep = options.fs.sep;
3155
3146
  assert(sep, "`fs.sep` is required for relative reference");
3156
3147
  const prefixes = ["." + sep, ".." + sep, "./", "../"];
3157
3148
  this.shouldLoadRelative = (referencedFile) => prefixes.some((prefix) => referencedFile.startsWith(prefix));
3158
3149
  } else {
3159
3150
  this.shouldLoadRelative = (_referencedFile) => false;
3160
3151
  }
3161
- const fs2 = options2.fs;
3152
+ const fs2 = options.fs;
3162
3153
  this.contains = toLiquidAsync(fs2.contains?.bind(fs2) || (async () => true), fs2.containsSync?.bind(fs2) || (() => true));
3163
3154
  this.exists = toLiquidAsync(fs2.exists?.bind(fs2) || (async () => false), fs2.existsSync?.bind(fs2));
3164
3155
  }
@@ -3610,7 +3601,7 @@ var require_liquid_node = __commonJS({
3610
3601
  uri_escape,
3611
3602
  slugify
3612
3603
  });
3613
- var join5 = argumentsToValue(function(v, arg) {
3604
+ var join6 = argumentsToValue(function(v, arg) {
3614
3605
  const array2 = toArray(v);
3615
3606
  const sep = isNil(arg) ? " " : stringify(arg);
3616
3607
  let outputSize = sep.length * Math.max(array2.length - 1, 0);
@@ -3886,7 +3877,7 @@ var require_liquid_node = __commonJS({
3886
3877
  __name(sample, "sample");
3887
3878
  var arrayFilters = /* @__PURE__ */ Object.freeze({
3888
3879
  __proto__: null,
3889
- join: join5,
3880
+ join: join6,
3890
3881
  last,
3891
3882
  first,
3892
3883
  reverse,
@@ -4308,7 +4299,7 @@ var require_liquid_node = __commonJS({
4308
4299
  ...cryptoFilters,
4309
4300
  ...misc
4310
4301
  };
4311
- var AssignTag = class extends Tag2 {
4302
+ var AssignTag = class extends Tag3 {
4312
4303
  static {
4313
4304
  __name(this, "AssignTag");
4314
4305
  }
@@ -4333,7 +4324,7 @@ var require_liquid_node = __commonJS({
4333
4324
  }
4334
4325
  };
4335
4326
  var MODIFIERS = ["offset", "limit", "reversed"];
4336
- var ForTag = class extends Tag2 {
4327
+ var ForTag = class extends Tag3 {
4337
4328
  static {
4338
4329
  __name(this, "ForTag");
4339
4330
  }
@@ -4426,7 +4417,7 @@ var require_liquid_node = __commonJS({
4426
4417
  return arr.slice(0, count3);
4427
4418
  }
4428
4419
  __name(limit2, "limit");
4429
- var CaptureTag = class extends Tag2 {
4420
+ var CaptureTag = class extends Tag3 {
4430
4421
  static {
4431
4422
  __name(this, "CaptureTag");
4432
4423
  }
@@ -4464,7 +4455,7 @@ var require_liquid_node = __commonJS({
4464
4455
  yield this.identifier;
4465
4456
  }
4466
4457
  };
4467
- var CaseTag = class extends Tag2 {
4458
+ var CaseTag = class extends Tag3 {
4468
4459
  static {
4469
4460
  __name(this, "CaseTag");
4470
4461
  }
@@ -4537,7 +4528,7 @@ var require_liquid_node = __commonJS({
4537
4528
  return templates;
4538
4529
  }
4539
4530
  };
4540
- var CommentTag = class extends Tag2 {
4531
+ var CommentTag = class extends Tag3 {
4541
4532
  static {
4542
4533
  __name(this, "CommentTag");
4543
4534
  }
@@ -4553,7 +4544,7 @@ var require_liquid_node = __commonJS({
4553
4544
  render() {
4554
4545
  }
4555
4546
  };
4556
- var RenderTag = class extends Tag2 {
4547
+ var RenderTag = class extends Tag3 {
4557
4548
  static {
4558
4549
  __name(this, "RenderTag");
4559
4550
  }
@@ -4700,7 +4691,7 @@ var require_liquid_node = __commonJS({
4700
4691
  return yield evalToken(file2, ctx);
4701
4692
  }
4702
4693
  __name(renderFilePath, "renderFilePath");
4703
- var IncludeTag = class extends Tag2 {
4694
+ var IncludeTag = class extends Tag3 {
4704
4695
  static {
4705
4696
  __name(this, "IncludeTag");
4706
4697
  }
@@ -4768,7 +4759,7 @@ var require_liquid_node = __commonJS({
4768
4759
  }
4769
4760
  }
4770
4761
  };
4771
- var DecrementTag = class extends Tag2 {
4762
+ var DecrementTag = class extends Tag3 {
4772
4763
  static {
4773
4764
  __name(this, "DecrementTag");
4774
4765
  }
@@ -4788,7 +4779,7 @@ var require_liquid_node = __commonJS({
4788
4779
  yield this.identifier;
4789
4780
  }
4790
4781
  };
4791
- var CycleTag = class extends Tag2 {
4782
+ var CycleTag = class extends Tag3 {
4792
4783
  static {
4793
4784
  __name(this, "CycleTag");
4794
4785
  }
@@ -4814,15 +4805,15 @@ var require_liquid_node = __commonJS({
4814
4805
  }
4815
4806
  *render(ctx, emitter) {
4816
4807
  const group = yield evalToken(this.group, ctx);
4817
- const fingerprint2 = `cycle:${group}:` + this.candidates.join(",");
4808
+ const fingerprint = `cycle:${group}:` + this.candidates.join(",");
4818
4809
  const groups = ctx.getRegister("cycle", {});
4819
- let idx = groups[fingerprint2];
4810
+ let idx = groups[fingerprint];
4820
4811
  if (idx === void 0) {
4821
- idx = groups[fingerprint2] = 0;
4812
+ idx = groups[fingerprint] = 0;
4822
4813
  }
4823
4814
  const candidate = this.candidates[idx];
4824
4815
  idx = (idx + 1) % this.candidates.length;
4825
- groups[fingerprint2] = idx;
4816
+ groups[fingerprint] = idx;
4826
4817
  return yield evalToken(candidate, ctx);
4827
4818
  }
4828
4819
  *arguments() {
@@ -4832,7 +4823,7 @@ var require_liquid_node = __commonJS({
4832
4823
  }
4833
4824
  }
4834
4825
  };
4835
- var IfTag = class extends Tag2 {
4826
+ var IfTag = class extends Tag3 {
4836
4827
  static {
4837
4828
  __name(this, "IfTag");
4838
4829
  }
@@ -4882,7 +4873,7 @@ var require_liquid_node = __commonJS({
4882
4873
  return this.branches.map((b) => b.value);
4883
4874
  }
4884
4875
  };
4885
- var IncrementTag = class extends Tag2 {
4876
+ var IncrementTag = class extends Tag3 {
4886
4877
  static {
4887
4878
  __name(this, "IncrementTag");
4888
4879
  }
@@ -4904,7 +4895,7 @@ var require_liquid_node = __commonJS({
4904
4895
  yield this.identifier;
4905
4896
  }
4906
4897
  };
4907
- var LayoutTag = class extends Tag2 {
4898
+ var LayoutTag = class extends Tag3 {
4908
4899
  static {
4909
4900
  __name(this, "LayoutTag");
4910
4901
  }
@@ -4959,7 +4950,7 @@ var require_liquid_node = __commonJS({
4959
4950
  }
4960
4951
  }
4961
4952
  };
4962
- var BlockTag = class extends Tag2 {
4953
+ var BlockTag = class extends Tag3 {
4963
4954
  static {
4964
4955
  __name(this, "BlockTag");
4965
4956
  }
@@ -5008,7 +4999,7 @@ var require_liquid_node = __commonJS({
5008
4999
  return ["block"];
5009
5000
  }
5010
5001
  };
5011
- var RawTag = class extends Tag2 {
5002
+ var RawTag = class extends Tag3 {
5012
5003
  static {
5013
5004
  __name(this, "RawTag");
5014
5005
  }
@@ -5052,7 +5043,7 @@ var require_liquid_node = __commonJS({
5052
5043
  return this.col() === this.cols;
5053
5044
  }
5054
5045
  };
5055
- var TablerowTag = class extends Tag2 {
5046
+ var TablerowTag = class extends Tag3 {
5056
5047
  static {
5057
5048
  __name(this, "TablerowTag");
5058
5049
  }
@@ -5116,7 +5107,7 @@ var require_liquid_node = __commonJS({
5116
5107
  return [this.variable, "tablerowloop"];
5117
5108
  }
5118
5109
  };
5119
- var UnlessTag = class extends Tag2 {
5110
+ var UnlessTag = class extends Tag3 {
5120
5111
  static {
5121
5112
  __name(this, "UnlessTag");
5122
5113
  }
@@ -5175,7 +5166,7 @@ var require_liquid_node = __commonJS({
5175
5166
  return this.branches.map((b) => b.value);
5176
5167
  }
5177
5168
  };
5178
- var BreakTag = class extends Tag2 {
5169
+ var BreakTag = class extends Tag3 {
5179
5170
  static {
5180
5171
  __name(this, "BreakTag");
5181
5172
  }
@@ -5183,7 +5174,7 @@ var require_liquid_node = __commonJS({
5183
5174
  ctx.breakCalled = true;
5184
5175
  }
5185
5176
  };
5186
- var ContinueTag = class extends Tag2 {
5177
+ var ContinueTag = class extends Tag3 {
5187
5178
  static {
5188
5179
  __name(this, "ContinueTag");
5189
5180
  }
@@ -5191,7 +5182,7 @@ var require_liquid_node = __commonJS({
5191
5182
  ctx.continueCalled = true;
5192
5183
  }
5193
5184
  };
5194
- var EchoTag = class extends Tag2 {
5185
+ var EchoTag = class extends Tag3 {
5195
5186
  static {
5196
5187
  __name(this, "EchoTag");
5197
5188
  }
@@ -5214,7 +5205,7 @@ var require_liquid_node = __commonJS({
5214
5205
  }
5215
5206
  }
5216
5207
  };
5217
- var LiquidTag = class extends Tag2 {
5208
+ var LiquidTag = class extends Tag3 {
5218
5209
  static {
5219
5210
  __name(this, "LiquidTag");
5220
5211
  }
@@ -5230,7 +5221,7 @@ var require_liquid_node = __commonJS({
5230
5221
  return this.templates;
5231
5222
  }
5232
5223
  };
5233
- var InlineCommentTag = class extends Tag2 {
5224
+ var InlineCommentTag = class extends Tag3 {
5234
5225
  static {
5235
5226
  __name(this, "InlineCommentTag");
5236
5227
  }
@@ -5373,76 +5364,76 @@ var require_liquid_node = __commonJS({
5373
5364
  self.renderFile(filePath, ctx).then((html) => callback(null, html), callback);
5374
5365
  };
5375
5366
  }
5376
- async analyze(template2, options2 = {}) {
5377
- return analyze(template2, options2);
5367
+ async analyze(template2, options = {}) {
5368
+ return analyze(template2, options);
5378
5369
  }
5379
- analyzeSync(template2, options2 = {}) {
5380
- return analyzeSync(template2, options2);
5370
+ analyzeSync(template2, options = {}) {
5371
+ return analyzeSync(template2, options);
5381
5372
  }
5382
- async parseAndAnalyze(html, filename, options2 = {}) {
5383
- return analyze(this.parse(html, filename), options2);
5373
+ async parseAndAnalyze(html, filename, options = {}) {
5374
+ return analyze(this.parse(html, filename), options);
5384
5375
  }
5385
- parseAndAnalyzeSync(html, filename, options2 = {}) {
5386
- return analyzeSync(this.parse(html, filename), options2);
5376
+ parseAndAnalyzeSync(html, filename, options = {}) {
5377
+ return analyzeSync(this.parse(html, filename), options);
5387
5378
  }
5388
5379
  /** Return an array of all variables without their properties. */
5389
- async variables(template2, options2 = {}) {
5390
- const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options2);
5380
+ async variables(template2, options = {}) {
5381
+ const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options);
5391
5382
  return Object.keys(analysis.variables);
5392
5383
  }
5393
5384
  /** Return an array of all variables without their properties. */
5394
- variablesSync(template2, options2 = {}) {
5395
- const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options2);
5385
+ variablesSync(template2, options = {}) {
5386
+ const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options);
5396
5387
  return Object.keys(analysis.variables);
5397
5388
  }
5398
5389
  /** Return an array of all variables including their properties/paths. */
5399
- async fullVariables(template2, options2 = {}) {
5400
- const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options2);
5390
+ async fullVariables(template2, options = {}) {
5391
+ const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options);
5401
5392
  return Array.from(new Set(Object.values(analysis.variables).flatMap((a) => a.map((v) => String(v)))));
5402
5393
  }
5403
5394
  /** Return an array of all variables including their properties/paths. */
5404
- fullVariablesSync(template2, options2 = {}) {
5405
- const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options2);
5395
+ fullVariablesSync(template2, options = {}) {
5396
+ const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options);
5406
5397
  return Array.from(new Set(Object.values(analysis.variables).flatMap((a) => a.map((v) => String(v)))));
5407
5398
  }
5408
5399
  /** Return an array of all variables, each as an array of properties/segments. */
5409
- async variableSegments(template2, options2 = {}) {
5410
- const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options2);
5400
+ async variableSegments(template2, options = {}) {
5401
+ const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options);
5411
5402
  return Array.from(strictUniq(Object.values(analysis.variables).flatMap((a) => a.map((v) => v.toArray()))));
5412
5403
  }
5413
5404
  /** Return an array of all variables, each as an array of properties/segments. */
5414
- variableSegmentsSync(template2, options2 = {}) {
5415
- const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options2);
5405
+ variableSegmentsSync(template2, options = {}) {
5406
+ const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options);
5416
5407
  return Array.from(strictUniq(Object.values(analysis.variables).flatMap((a) => a.map((v) => v.toArray()))));
5417
5408
  }
5418
5409
  /** Return an array of all expected context variables without their properties. */
5419
- async globalVariables(template2, options2 = {}) {
5420
- const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options2);
5410
+ async globalVariables(template2, options = {}) {
5411
+ const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options);
5421
5412
  return Object.keys(analysis.globals);
5422
5413
  }
5423
5414
  /** Return an array of all expected context variables without their properties. */
5424
- globalVariablesSync(template2, options2 = {}) {
5425
- const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options2);
5415
+ globalVariablesSync(template2, options = {}) {
5416
+ const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options);
5426
5417
  return Object.keys(analysis.globals);
5427
5418
  }
5428
5419
  /** Return an array of all expected context variables including their properties/paths. */
5429
- async globalFullVariables(template2, options2 = {}) {
5430
- const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options2);
5420
+ async globalFullVariables(template2, options = {}) {
5421
+ const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options);
5431
5422
  return Array.from(new Set(Object.values(analysis.globals).flatMap((a) => a.map((v) => String(v)))));
5432
5423
  }
5433
5424
  /** Return an array of all expected context variables including their properties/paths. */
5434
- globalFullVariablesSync(template2, options2 = {}) {
5435
- const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options2);
5425
+ globalFullVariablesSync(template2, options = {}) {
5426
+ const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options);
5436
5427
  return Array.from(new Set(Object.values(analysis.globals).flatMap((a) => a.map((v) => String(v)))));
5437
5428
  }
5438
5429
  /** Return an array of all expected context variables, each as an array of properties/segments. */
5439
- async globalVariableSegments(template2, options2 = {}) {
5440
- const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options2);
5430
+ async globalVariableSegments(template2, options = {}) {
5431
+ const analysis = await analyze(isString(template2) ? this.parse(template2) : template2, options);
5441
5432
  return Array.from(strictUniq(Object.values(analysis.globals).flatMap((a) => a.map((v) => v.toArray()))));
5442
5433
  }
5443
5434
  /** Return an array of all expected context variables, each as an array of properties/segments. */
5444
- globalVariableSegmentsSync(template2, options2 = {}) {
5445
- const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options2);
5435
+ globalVariableSegmentsSync(template2, options = {}) {
5436
+ const analysis = analyzeSync(isString(template2) ? this.parse(template2) : template2, options);
5446
5437
  return Array.from(strictUniq(Object.values(analysis.globals).flatMap((a) => a.map((v) => v.toArray()))));
5447
5438
  }
5448
5439
  };
@@ -5480,7 +5471,7 @@ var require_liquid_node = __commonJS({
5480
5471
  exports.RenderError = RenderError;
5481
5472
  exports.RenderTag = RenderTag;
5482
5473
  exports.TablerowTag = TablerowTag;
5483
- exports.Tag = Tag2;
5474
+ exports.Tag = Tag3;
5484
5475
  exports.TagToken = TagToken;
5485
5476
  exports.Token = Token;
5486
5477
  exports.TokenizationError = TokenizationError;
@@ -5510,11 +5501,11 @@ var require_liquid_node = __commonJS({
5510
5501
  }
5511
5502
  });
5512
5503
 
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";
5504
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
5505
+ import { chmodSync, constants, copyFileSync, existsSync as existsSync10, mkdirSync, realpathSync as realpathSync3, renameSync as renameSync3, rmSync as rmSync3, statfsSync as statfsSync2, statSync as statSync4, writeFileSync as writeFileSync2 } from "node:fs";
5506
+ import { dirname as dirname3, resolve } from "node:path";
5516
5507
 
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
5508
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/sealed.js
5518
5509
  import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
5519
5510
  import { closeSync, createReadStream, createWriteStream, existsSync, openSync, readSync, renameSync, rmSync, statSync } from "node:fs";
5520
5511
  import { Transform } from "node:stream";
@@ -5621,7 +5612,7 @@ var unsealFile = /* @__PURE__ */ __name(async (from, to, password) => {
5621
5612
  renameSync(pending, to);
5622
5613
  }, "unsealFile");
5623
5614
 
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
5615
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/store/compatibility.js
5625
5616
  var SPEAKS = MIGRATIONS.at(-1)?.version ?? 0;
5626
5617
  var fileSchemaOf = /* @__PURE__ */ __name((database) => {
5627
5618
  const tracked = database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'schema_migrations'").get();
@@ -5645,7 +5636,7 @@ var compatibilityOf = /* @__PURE__ */ __name((file2, migrations = MIGRATIONS) =>
5645
5636
  };
5646
5637
  }, "compatibilityOf");
5647
5638
 
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
5639
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/store/repair.js
5649
5640
  import { createHash as createHash2 } from "node:crypto";
5650
5641
  var COPY_MARK = "__repair_";
5651
5642
  var COPY_NAME = /__repair_[0-9a-f]{8}(_\d+)?$/;
@@ -5899,19 +5890,102 @@ var deleteCopy = /* @__PURE__ */ __name((database, name) => {
5899
5890
  return found;
5900
5891
  }, "deleteCopy");
5901
5892
 
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
5893
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/store-info.js
5903
5894
  import { existsSync as existsSync4, statSync as statSync3 } from "node:fs";
5904
5895
 
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
5896
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
5906
5897
  import { existsSync as existsSync3 } from "node:fs";
5907
5898
 
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
5899
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/store/recover.js
5909
5900
  import { execFileSync, spawn } from "node:child_process";
5910
5901
  import { existsSync as existsSync2, readFileSync, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statfsSync, statSync as statSync2, writeFileSync } from "node:fs";
5911
5902
  import { basename, dirname, join } from "node:path";
5912
5903
  import { Transform as Transform2 } from "node:stream";
5904
+
5905
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/store/refill.js
5906
+ var REFILL_MARGIN_MS = 864e5;
5907
+ var TIME_KEYS = 1e12;
5908
+ var integerId = `external_id GLOB '[0-9]*' AND NOT external_id GLOB '*[^0-9]*'`;
5909
+ var forgetCoverageSince = /* @__PURE__ */ __name((database, cutoff, now = Date.now()) => {
5910
+ database.exec("BEGIN");
5911
+ try {
5912
+ const refetch = forget(database, cutoff, now);
5913
+ database.exec("COMMIT");
5914
+ return refetch;
5915
+ } catch (error) {
5916
+ database.exec("ROLLBACK");
5917
+ throw error;
5918
+ }
5919
+ }, "forgetCoverageSince");
5920
+ var forget = /* @__PURE__ */ __name((database, cutoff, now) => {
5921
+ const chats = /* @__PURE__ */ new Map();
5922
+ const held = database.prepare(`SELECT c.id, c.account_id, c.external_id AS chat, a.provider, a.external_id AS account,
5923
+ max(r.to_key) AS top FROM sync_ranges r JOIN chats c ON c.id = r.chat_id JOIN accounts a ON a.id = c.account_id
5924
+ GROUP BY c.id`).all();
5925
+ for (const row of held) {
5926
+ const chat = Number(row.id);
5927
+ const top = Number(row.top);
5928
+ const keepTo = cutoff === null ? null : top >= TIME_KEYS ? cutoff : database.prepare(`SELECT max(CAST(external_id AS INTEGER)) AS k FROM messages WHERE chat_id = ? AND sent_at < ? AND ${integerId}`).get(chat, cutoff)?.k;
5929
+ if (keepTo !== null && top <= keepTo)
5930
+ continue;
5931
+ if (keepTo === null)
5932
+ database.prepare("DELETE FROM sync_ranges WHERE chat_id = ?").run(chat);
5933
+ else {
5934
+ database.prepare("DELETE FROM sync_ranges WHERE chat_id = ? AND from_key > ?").run(chat, keepTo);
5935
+ database.prepare("UPDATE sync_ranges SET to_key = ?, updated_at = ? WHERE chat_id = ? AND to_key > ?").run(keepTo, now, chat, keepTo);
5936
+ }
5937
+ const account = Number(row.account_id);
5938
+ const external = String(row.chat);
5939
+ database.prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?").run(account, `fetched:${external}`);
5940
+ database.prepare(`DELETE FROM sync_cursors WHERE account_id = ? AND key = ? AND NOT EXISTS
5941
+ (SELECT 1 FROM sync_ranges WHERE chat_id = ? AND from_key <= CAST(sync_cursors.value AS INTEGER))`).run(account, `history_start:${external}`, chat);
5942
+ const key = `${row.provider}\0${row.account}`;
5943
+ const one = chats.get(key) ?? { provider: String(row.provider), account: String(row.account), chats: 0 };
5944
+ one.chats += 1;
5945
+ chats.set(key, one);
5946
+ }
5947
+ return {
5948
+ since: cutoff === null ? null : new Date(cutoff).toISOString(),
5949
+ chats: [...chats.values()],
5950
+ mail: forgetMail(database, cutoff, now)
5951
+ };
5952
+ }, "forget");
5953
+ var forgetMail = /* @__PURE__ */ __name((database, cutoff, now) => {
5954
+ const folders = /* @__PURE__ */ new Map();
5955
+ const points = database.prepare(`SELECT s.account_id, s.key, s.value, a.external_id AS account FROM sync_cursors s
5956
+ JOIN accounts a ON a.id = s.account_id WHERE a.provider = 'email' AND s.key LIKE 'mail_resume:%'`).all();
5957
+ for (const row of points) {
5958
+ let point;
5959
+ try {
5960
+ point = JSON.parse(String(row.value));
5961
+ } catch {
5962
+ continue;
5963
+ }
5964
+ const account = String(row.account);
5965
+ if (!Array.isArray(point.done)) {
5966
+ if (cutoff !== null && Date.parse(point.updatedAt ?? "") < cutoff)
5967
+ continue;
5968
+ database.prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?").run(Number(row.account_id), String(row.key));
5969
+ folders.set(account, (folders.get(account) ?? 0) + 1);
5970
+ continue;
5971
+ }
5972
+ const folder = String(row.key).slice("mail_resume:".length);
5973
+ const last = cutoff === null ? null : database.prepare(`SELECT max(l.uid) AS uid FROM email_locations l JOIN emails e ON e.id = l.email_id
5974
+ WHERE l.mailbox_id = (SELECT id FROM mailboxes WHERE account_id = ? AND external_id = ?)
5975
+ AND l.uidvalidity = ? AND coalesce(e.received_at, e.sent_at) < ?`).get(Number(row.account_id), folder, point.validity ?? "", cutoff)?.uid;
5976
+ const done = last === null ? [] : point.done.filter(([from]) => from <= last).map(([from, to]) => [from, Math.min(to, last)]);
5977
+ if (JSON.stringify(done) === JSON.stringify(point.done))
5978
+ continue;
5979
+ database.prepare("UPDATE sync_cursors SET value = ?, updated_at = ? WHERE account_id = ? AND key = ?").run(JSON.stringify({ ...point, done }), now, Number(row.account_id), String(row.key));
5980
+ folders.set(account, (folders.get(account) ?? 0) + 1);
5981
+ }
5982
+ return [...folders].map(([account, count3]) => ({ account, folders: count3 }));
5983
+ }, "forgetMail");
5984
+
5985
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/store/recover.js
5913
5986
  var SQLITE3_MINIMUM = [3, 43, 0];
5914
5987
  var STORE_PARTS = ["", "-wal", "-shm"];
5988
+ var RECOVER_LOCK = ".recover-lock";
5915
5989
  var INSERTED = /^INSERT OR IGNORE INTO '([^']+)'/;
5916
5990
  var LOST_AND_FOUND = "recover_lost_and_found";
5917
5991
  var recovers = /* @__PURE__ */ __name((program) => {
@@ -5946,11 +6020,55 @@ var activeTimers = /* @__PURE__ */ __name(() => {
5946
6020
  return void 0;
5947
6021
  }
5948
6022
  }, "activeTimers");
6023
+ var alive = /* @__PURE__ */ __name((pid) => {
6024
+ try {
6025
+ process.kill(pid, 0);
6026
+ return true;
6027
+ } catch (error) {
6028
+ return error.code === "EPERM";
6029
+ }
6030
+ }, "alive");
6031
+ var runningRecovery = /* @__PURE__ */ __name((path) => {
6032
+ let pid;
6033
+ try {
6034
+ pid = Number(readFileSync(`${path}${RECOVER_LOCK}`, "utf8").trim());
6035
+ } catch {
6036
+ return null;
6037
+ }
6038
+ return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
6039
+ }, "runningRecovery");
6040
+ var takeRecoverLock = /* @__PURE__ */ __name((path) => {
6041
+ const lock = `${path}${RECOVER_LOCK}`;
6042
+ const take = /* @__PURE__ */ __name(() => writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 }), "take");
6043
+ try {
6044
+ take();
6045
+ } catch (error) {
6046
+ if (error.code !== "EEXIST")
6047
+ throw error;
6048
+ const pid = runningRecovery(path);
6049
+ if (pid === null) {
6050
+ rmSync2(lock, { force: true });
6051
+ take();
6052
+ } else {
6053
+ throw new CliError("validation_error", `the store is being recovered by process ${pid} \u2014 wait for it to finish`, {
6054
+ reason: "store.recovering"
6055
+ });
6056
+ }
6057
+ }
6058
+ return () => rmSync2(lock, { force: true });
6059
+ }, "takeRecoverLock");
5949
6060
  var storeHolders = /* @__PURE__ */ __name((path) => {
5950
6061
  const folder = realpathSync(dirname(path));
5951
6062
  const files = STORE_PARTS.map((suffix) => join(folder, `${basename(path)}${suffix}`));
5952
6063
  const wanted = process.platform === "linux" ? files.flatMap((file2) => [file2, `${file2} (deleted)`]) : files.filter(existsSync2);
5953
- return holdersOf(wanted)?.map((pid) => {
6064
+ const recovering = runningRecovery(path);
6065
+ const pids = holdersOf(wanted);
6066
+ if (pids === void 0 && recovering === null)
6067
+ return void 0;
6068
+ const all = [
6069
+ .../* @__PURE__ */ new Set([...pids ?? [], ...recovering !== null && recovering !== process.pid ? [recovering] : []])
6070
+ ];
6071
+ return all.map((pid) => {
5954
6072
  let name = "?";
5955
6073
  try {
5956
6074
  name = readFileSync(`/proc/${pid}/comm`, "utf8").trim();
@@ -5959,9 +6077,12 @@ var storeHolders = /* @__PURE__ */ __name((path) => {
5959
6077
  return { pid, name };
5960
6078
  });
5961
6079
  }, "storeHolders");
5962
- var tableRows = /* @__PURE__ */ __name((database) => {
6080
+ var dataTables = /* @__PURE__ */ __name((database) => {
5963
6081
  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}_`)));
6082
+ return 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}_`)));
6083
+ }, "dataTables");
6084
+ var tableRows = /* @__PURE__ */ __name((database) => {
6085
+ const tables = dataTables(database);
5965
6086
  return Object.fromEntries(tables.map((table) => {
5966
6087
  try {
5967
6088
  return [table, Number(database.prepare(`SELECT count(*) AS n FROM "${table}"`).get()?.n)];
@@ -5970,6 +6091,117 @@ var tableRows = /* @__PURE__ */ __name((database) => {
5970
6091
  }
5971
6092
  }));
5972
6093
  }, "tableRows");
6094
+ var sourceTables = /* @__PURE__ */ __name((database) => {
6095
+ const withoutRowid = new Set(database.prepare("SELECT name FROM pragma_table_list WHERE wr = 1").all().map((row) => String(row.name)));
6096
+ return dataTables(database).filter((table) => table !== LOST_AND_FOUND && !withoutRowid.has(table) && !isDerivedTable(table));
6097
+ }, "sourceTables");
6098
+ var indexedButGone = /* @__PURE__ */ __name((database) => {
6099
+ const found = {};
6100
+ for (const table of sourceTables(database)) {
6101
+ const indexes = database.prepare("SELECT name FROM pragma_index_list(?) WHERE partial = 0 ORDER BY name").all(table).map((row) => String(row.name));
6102
+ for (const index of indexes) {
6103
+ const columns = database.prepare("SELECT cid, name FROM pragma_index_xinfo(?) WHERE key = 1 ORDER BY seqno").all(index);
6104
+ if (columns.some((column) => Number(column.cid) < 0))
6105
+ continue;
6106
+ const keys = columns.map((column) => `"${String(column.name)}"`).join(", ");
6107
+ const grouped = `${keys}, row_id`;
6108
+ let rows;
6109
+ try {
6110
+ rows = Number(database.prepare(`SELECT count(*) AS n FROM (SELECT 1 FROM (SELECT ${keys}, rowid AS row_id, 1 AS side FROM "${table}" INDEXED BY "${index}" UNION ALL SELECT ${keys}, rowid, 2 FROM "${table}" NOT INDEXED) GROUP BY ${grouped} HAVING max(side) = 1)`).get()?.n);
6111
+ } catch {
6112
+ continue;
6113
+ }
6114
+ if (rows > (found[table]?.rows ?? 0))
6115
+ found[table] = { rows, index };
6116
+ }
6117
+ }
6118
+ return found;
6119
+ }, "indexedButGone");
6120
+ var storedAs = /* @__PURE__ */ __name((declared) => {
6121
+ const type = declared.toUpperCase();
6122
+ if (type.includes("INT"))
6123
+ return ["integer"];
6124
+ if (/CHAR|CLOB|TEXT/.test(type))
6125
+ return ["text"];
6126
+ if (type === "" || type.includes("BLOB"))
6127
+ return null;
6128
+ if (/REAL|FLOA|DOUB/.test(type))
6129
+ return ["real", "integer"];
6130
+ return null;
6131
+ }, "storedAs");
6132
+ var columnsOf = /* @__PURE__ */ __name((database, table) => {
6133
+ const all = database.prepare('SELECT name, type, "notnull" AS required, dflt_value, pk FROM pragma_table_info(?)').all(table);
6134
+ const keys = all.filter((column) => Number(column.pk) > 0);
6135
+ return all.map((column) => ({
6136
+ name: String(column.name),
6137
+ type: String(column.type),
6138
+ required: Number(column.required) === 1,
6139
+ hasDefault: column.dflt_value !== null,
6140
+ rowid: keys.length === 1 && Number(column.pk) === 1 && String(column.type).toUpperCase() === "INTEGER"
6141
+ }));
6142
+ }, "columnsOf");
6143
+ var fits = /* @__PURE__ */ __name((columns, fields, types) => fields <= columns.length && columns.every((column, at) => {
6144
+ if (at >= fields)
6145
+ return !column.required || column.hasDefault;
6146
+ const type = types[at];
6147
+ if (column.rowid)
6148
+ return type === "null" || type === "integer";
6149
+ if (type === "null")
6150
+ return !column.required;
6151
+ const allowed = storedAs(column.type);
6152
+ return allowed === null || allowed.includes(type);
6153
+ }), "fits");
6154
+ var placeLostRows = /* @__PURE__ */ __name((database) => {
6155
+ if (!database.prepare("SELECT 1 FROM sqlite_master WHERE name = ?").get(LOST_AND_FOUND))
6156
+ return {};
6157
+ const fields = database.prepare("SELECT name FROM pragma_table_info(?) WHERE name GLOB 'c[0-9]*'").all(LOST_AND_FOUND).map((row) => String(row.name));
6158
+ const tables = sourceTables(database).map((table) => ({ table, columns: columnsOf(database, table) }));
6159
+ const rows = database.prepare(`SELECT rowid AS at, nfield, ${fields.map((field) => `typeof(${field}) AS "${field}"`).join(", ")} FROM ${LOST_AND_FOUND} WHERE id IS NOT NULL`).all();
6160
+ const placed = {};
6161
+ const triggers = [];
6162
+ const quiet = /* @__PURE__ */ __name((table) => {
6163
+ if (table in placed)
6164
+ return;
6165
+ placed[table] = 0;
6166
+ for (const row of database.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ?").all(table)) {
6167
+ triggers.push(String(row.sql));
6168
+ database.exec(`DROP TRIGGER "${String(row.name)}"`);
6169
+ }
6170
+ }, "quiet");
6171
+ database.exec("PRAGMA foreign_keys = OFF");
6172
+ database.exec("BEGIN");
6173
+ try {
6174
+ for (const row of rows) {
6175
+ const count3 = Number(row.nfield);
6176
+ const types = fields.slice(0, count3).map((field) => String(row[field]));
6177
+ const fitting = tables.filter(({ columns: columns2 }) => fits(columns2, count3, types));
6178
+ if (fitting.length !== 1)
6179
+ continue;
6180
+ const { table, columns } = fitting[0];
6181
+ quiet(table);
6182
+ const given = columns.slice(0, count3);
6183
+ const names = [...given.some((column) => column.rowid) ? [] : ["rowid"], ...given.map((column) => column.name)];
6184
+ const values = [
6185
+ ...given.some((column) => column.rowid) ? [] : ["id"],
6186
+ ...given.map((column, at) => column.rowid ? "id" : `c${at}`)
6187
+ ];
6188
+ const inserted = database.prepare(`INSERT OR IGNORE INTO "${table}" (${names.map((name) => `"${name}"`).join(", ")}) SELECT ${values.join(", ")} FROM ${LOST_AND_FOUND} WHERE rowid = ?`).run(Number(row.at));
6189
+ if (Number(inserted.changes) === 0)
6190
+ continue;
6191
+ placed[table] = (placed[table] ?? 0) + 1;
6192
+ database.prepare(`DELETE FROM ${LOST_AND_FOUND} WHERE rowid = ?`).run(Number(row.at));
6193
+ }
6194
+ for (const sql of triggers)
6195
+ database.exec(sql);
6196
+ database.exec("COMMIT");
6197
+ } catch (error) {
6198
+ database.exec("ROLLBACK");
6199
+ throw error;
6200
+ } finally {
6201
+ database.exec("PRAGMA foreign_keys = ON");
6202
+ }
6203
+ return Object.fromEntries(Object.entries(placed).filter(([, rows2]) => rows2 > 0));
6204
+ }, "placeLostRows");
5973
6205
  var copyReadableRows = /* @__PURE__ */ __name((path, target, program = "sqlite3") => new Promise((resolve2, reject) => {
5974
6206
  const reader = spawn(program, ["-readonly", path, `.recover --ignore-freelist --lost-and-found ${LOST_AND_FOUND}`], {
5975
6207
  stdio: ["ignore", "pipe", "pipe"]
@@ -6112,10 +6344,14 @@ var mailToFetch = /* @__PURE__ */ __name((database) => {
6112
6344
  return [];
6113
6345
  }
6114
6346
  }, "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");
6347
+ var clearInvalidJson = /* @__PURE__ */ __name((database) => {
6348
+ const found = invalidJson(database);
6349
+ for (const { table, column, required } of found) {
6350
+ const invalid = `"${column}" IS NOT NULL AND NOT json_valid("${column}")`;
6351
+ database.exec(required ? `DELETE FROM "${table}" WHERE ${invalid}` : `UPDATE "${table}" SET "${column}" = NULL WHERE ${invalid}`);
6352
+ }
6353
+ return found;
6354
+ }, "clearInvalidJson");
6119
6355
  var refuseInUse = /* @__PURE__ */ __name((path) => {
6120
6356
  const holders = storeHolders(path);
6121
6357
  if (holders && holders.length > 0) {
@@ -6132,98 +6368,149 @@ var recoverStore = /* @__PURE__ */ __name(async ({ path, command, version, sqlit
6132
6368
  if (!program.usable) {
6133
6369
  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
6370
  }
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;
6371
+ const releaseLock2 = takeRecoverLock(path);
6142
6372
  try {
6143
- rowsBefore = tableRows(old.database);
6373
+ refuseInUse(path);
6374
+ const bytes = STORE_PARTS.reduce((sum, suffix) => sum + (statSync2(`${path}${suffix}`, { throwIfNoEntry: false })?.size ?? 0), 0);
6375
+ const { bavail, bsize } = statfsSync(dirname(path));
6376
+ if (Number(bavail) * Number(bsize) < bytes * 1.2)
6377
+ throw new CliError("validation_error", `the recovery needs about ${Math.ceil(bytes * 1.2 / 1e9)} GB free beside the store`);
6378
+ return await recoverLocked({ path, command, version, sqlite3, now, note, copy, started, program });
6144
6379
  } finally {
6145
- old.database.close();
6380
+ releaseLock2();
6146
6381
  }
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;
6382
+ }, "recoverStore");
6383
+ var recoverLocked = /* @__PURE__ */ __name(async ({ path, command, version, sqlite3, now, note, copy, started, program }) => {
6384
+ const watch = (await openSqlite(path, { readOnly: true })).database;
6385
+ let watching = true;
6386
+ const stopWatching = /* @__PURE__ */ __name(() => {
6387
+ if (watching)
6388
+ watch.close();
6389
+ watching = false;
6390
+ }, "stopWatching");
6173
6391
  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) {
6392
+ const dataVersion = /* @__PURE__ */ __name(() => Number(watch.prepare("PRAGMA data_version").get()?.data_version), "dataVersion");
6393
+ let rowsBefore;
6394
+ try {
6395
+ rowsBefore = tableRows(watch);
6396
+ } catch (error) {
6397
+ if (!isStoreDamage(error))
6398
+ throw error;
6399
+ throw new CliError("configuration_error", "the store file's header or schema is damaged, so its tables cannot be listed and it cannot be recovered; the file was left as it was", { reason: "store.unreadable" });
6400
+ }
6401
+ note("looking for rows the indexes list and the tables no longer hold");
6402
+ const gone = indexedButGone(watch);
6403
+ const lastKnownGood = readHealthMark(path)?.last_ok_at ?? null;
6404
+ const before = { data: dataVersion(), inode: statSync2(path).ino };
6405
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, "-");
6406
+ const target = `${path}.recovering-${stamp}`;
6407
+ writeFileSync(target, "", { flag: "wx", mode: 384 });
6408
+ const dropTarget = /* @__PURE__ */ __name(() => {
6409
+ for (const suffix of [...STORE_PARTS, "-journal"])
6410
+ rmSync2(`${target}${suffix}`, { force: true });
6411
+ }, "dropTarget");
6412
+ note(`copying the readable rows into ${target}`);
6413
+ let copied;
6414
+ let copyErrors;
6415
+ let read;
6416
+ let opened;
6417
+ try {
6418
+ ;
6419
+ ({ errors: copyErrors, read } = await (copy ?? ((from, to) => copyReadableRows(from, to, sqlite3)))(path, target));
6420
+ copied = Date.now();
6421
+ opened = await openSqlite(target);
6422
+ } catch (error) {
6423
+ dropTarget();
6424
+ throw error;
6425
+ }
6426
+ let rebuilt;
6427
+ let kept;
6428
+ let dangling;
6429
+ let json;
6430
+ let fetch;
6431
+ let schema;
6432
+ let placed;
6433
+ let refetch;
6434
+ try {
6435
+ placed = placeLostRows(opened.database);
6436
+ kept = tableRows(opened.database);
6437
+ migrate(opened.database, { command, ...version ? { version } : {} });
6438
+ note("clearing values that are not valid JSON");
6439
+ json = clearInvalidJson(opened.database);
6440
+ rebuilt = rebuildDerived(opened.database, { now, note });
6441
+ note("looking for rows that point at rows that were lost");
6442
+ dangling = danglingRows(opened.database);
6443
+ fetch = mailToFetch(opened.database);
6444
+ const good = lastKnownGood === null ? Number.NaN : Date.parse(lastKnownGood);
6445
+ refetch = forgetCoverageSince(opened.database, Number.isNaN(good) ? null : good - REFILL_MARGIN_MS, now());
6446
+ schema = fileSchemaOf(opened.database).version;
6447
+ opened.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
6448
+ } catch (error) {
6449
+ opened.database.close();
6450
+ dropTarget();
6451
+ throw error;
6452
+ }
6182
6453
  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" });
6454
+ const rebuiltAt = Date.now();
6455
+ note("checking the recovered file");
6456
+ const health = await storeHealth(target, { deep: true });
6457
+ const checkedAt = Date.now();
6458
+ if (!health.ok) {
6459
+ 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" });
6460
+ }
6461
+ refuseInUse(path);
6462
+ const changed = dataVersion() !== before.data || statSync2(path, { throwIfNoEntry: false })?.ino !== before.inode;
6463
+ stopWatching();
6464
+ if (changed) {
6465
+ 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" });
6466
+ }
6467
+ const keptAt = `${path}.before-recover-${stamp}`;
6468
+ for (const suffix of STORE_PARTS)
6469
+ if (existsSync2(`${path}${suffix}`))
6470
+ renameSync2(`${path}${suffix}`, `${keptAt}${suffix}`);
6471
+ for (const suffix of STORE_PARTS)
6472
+ if (existsSync2(`${target}${suffix}`))
6473
+ renameSync2(`${target}${suffix}`, `${path}${suffix}`);
6474
+ recordDeepCheck(path, health, { cli: command, ...version ? { version } : {}, schema, now });
6475
+ const lost = Object.entries(rowsBefore).map(([table, before2]) => {
6476
+ const goneAtLeast = Math.max(0, (gone[table]?.rows ?? 0) - (placed[table] ?? 0));
6477
+ return {
6478
+ table,
6479
+ before: before2,
6480
+ read: read[table] ?? 0,
6481
+ kept: kept[table] ?? 0,
6482
+ goneAtLeast,
6483
+ seenIn: goneAtLeast > 0 ? gone[table]?.index ?? null : null
6484
+ };
6485
+ }).filter(({ before: before2, read: read2, kept: kept2, goneAtLeast }) => before2 === null || before2 > kept2 || read2 > kept2 || goneAtLeast > 0);
6486
+ const seconds = /* @__PURE__ */ __name((from, to) => Math.round((to - from) / 100) / 10, "seconds");
6487
+ return {
6488
+ path,
6489
+ keptAt,
6490
+ sqlite3: program.version,
6491
+ lost,
6492
+ placed,
6493
+ lastKnownGood,
6494
+ dangling,
6495
+ invalidJson: json,
6496
+ mailToFetch: fetch,
6497
+ refetch,
6498
+ rebuilt,
6499
+ copyErrors,
6500
+ health,
6501
+ seconds: {
6502
+ copy: seconds(started, copied),
6503
+ rebuild: seconds(copied, rebuiltAt),
6504
+ check: seconds(rebuiltAt, checkedAt),
6505
+ total: seconds(started, Date.now())
6506
+ }
6507
+ };
6508
+ } finally {
6509
+ stopWatching();
6197
6510
  }
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");
6511
+ }, "recoverLocked");
6225
6512
 
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
6513
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/store-recover.js
6227
6514
  var COUNTED = [
6228
6515
  "accounts",
6229
6516
  "chats",
@@ -6238,15 +6525,17 @@ var COUNTED = [
6238
6525
  "mentions"
6239
6526
  ];
6240
6527
  var stopTimers = /* @__PURE__ */ __name((timers) => `systemctl --user stop ${timers.join(" ")}`, "stopTimers");
6241
- var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command) => {
6528
+ var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command, version) => {
6242
6529
  const path = storePath(env);
6243
6530
  if (!existsSync3(path))
6244
6531
  return { path, exists: false, ok: true, next: [] };
6245
6532
  const health = await storeHealth(path, { deep: true });
6246
6533
  let rows = {};
6534
+ let schema = null;
6247
6535
  try {
6248
6536
  const { database } = await openSqlite(path, { readOnly: true });
6249
6537
  try {
6538
+ schema = fileSchemaOf(database).version;
6250
6539
  const all = tableRows(database);
6251
6540
  rows = Object.fromEntries(COUNTED.filter((table) => table in all).map((table) => [table, all[table] ?? null]));
6252
6541
  } finally {
@@ -6254,7 +6543,9 @@ var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command) => {
6254
6543
  }
6255
6544
  } catch {
6256
6545
  }
6257
- const explanation = explainDamage(health, command);
6546
+ recordDeepCheck(path, health, { cli: command, ...version ? { version } : {}, schema });
6547
+ const mark = readDamageMark(path);
6548
+ const explanation = explainDamage(health, command, mark);
6258
6549
  const inUse = storeHolders(path) ?? null;
6259
6550
  const timers = activeTimers() ?? null;
6260
6551
  const sqlite3 = sqlite3Program();
@@ -6272,8 +6563,11 @@ var storeRecoveryCheck = /* @__PURE__ */ __name(async (env, command) => {
6272
6563
  problems: health.problems ?? 0,
6273
6564
  damagedTables: health.damagedTables ?? [],
6274
6565
  damagedSearchIndexes: (health.searchIndexes ?? []).filter((index) => !index.ok).map(({ name, error }) => ({ name, ...error ? { error } : {} })),
6566
+ invalidJson: health.invalidJson ?? [],
6275
6567
  rows,
6276
6568
  explanation,
6569
+ damageMark: mark ? (({ inode: _, ...seen }) => seen)(mark) : null,
6570
+ lastKnownGood: readHealthMark(path)?.last_ok_at ?? null,
6277
6571
  inUse,
6278
6572
  timers,
6279
6573
  sqlite3: { version: sqlite3.version, usable: sqlite3.usable },
@@ -6303,13 +6597,30 @@ var storeRecoveryRun = /* @__PURE__ */ __name(async (env, { command, version, no
6303
6597
  next: [...mail, ...lostMail, "systemctl --user start <the timers stopped before>"]
6304
6598
  };
6305
6599
  }, "storeRecoveryRun");
6600
+ var refetchNotes = /* @__PURE__ */ __name(({ since, chats, mail }) => {
6601
+ const from = since === null ? "from the start" : `from ${since} on`;
6602
+ const marked = [
6603
+ ...chats.map(({ provider, account, chats: chats2 }) => `${chats2} chats of ${provider} ${account}`),
6604
+ ...mail.map(({ account, folders }) => `${folders} mail folders of ${account}`)
6605
+ ];
6606
+ return [
6607
+ marked.length > 0 ? `marked as not fetched ${from}, so the next sync or serve fetches it again: ${marked.join(", ")}` : `nothing held ${from} was marked as fetched, so there is nothing to fetch again`,
6608
+ ...chats.filter(({ provider }) => provider === "whatsapp").map(({ account }) => `whatsapp ${account}: WhatsApp cannot be asked for its chats, so only what the phone pushes while serve runs comes back`),
6609
+ "notes, memories, tags and whatever else only this store held cannot be fetched again"
6610
+ ];
6611
+ }, "refetchNotes");
6306
6612
  var recoveryNotes = /* @__PURE__ */ __name((answer) => {
6307
6613
  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` : ""}`);
6614
+ const lost = answer.lost.map(({ table, before, read, kept, goneAtLeast, seenIn }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}` + (goneAtLeast > 0 ? `; at least ${goneAtLeast} rows are gone (the index ${seenIn} lists them)` : ""));
6615
+ const since = answer.lastKnownGood ? `since the last deep check that passed (${answer.lastKnownGood})` : "since the store was made (no deep check that passed is on record)";
6309
6616
  return [
6310
6617
  `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
6311
- ...lost.length ? lost : ["no table lost a row"],
6618
+ ...lost,
6619
+ ...Object.entries(answer.placed).map(([table, rows]) => `${table}: ${rows} rows found on pages no table claimed were put back`),
6620
+ ...refetchNotes(answer.refetch),
6621
+ `${lost.some((line) => line.includes("are gone")) ? "more rows may be gone" : "how many rows were lost is unknown"}: damage can take rows written ${since} without leaving a trace; a sync fetches again what the servers still hold`,
6312
6622
  ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
6623
+ ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON \u2014 ${required ? "those rows were dropped" : "set to empty"}`),
6313
6624
  ...answer.next.map((line) => `next: ${line}`)
6314
6625
  ];
6315
6626
  }
@@ -6320,13 +6631,14 @@ var recoveryNotes = /* @__PURE__ */ __name((answer) => {
6320
6631
  const why = answer.explanation;
6321
6632
  return [
6322
6633
  ...why ? [why.what, ...why.impact, why.externalUnaffected] : [],
6634
+ answer.lastKnownGood ? `the store last passed a deep check at ${answer.lastKnownGood}` : "no deep check that passed is on record for this store",
6323
6635
  ...answer.next.map((line) => `next: ${line}`)
6324
6636
  ];
6325
6637
  }, "recoveryNotes");
6326
6638
  var storeRecoverCommand = /* @__PURE__ */ __name(({ command, version }) => {
6327
6639
  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
6640
  const output = outputFor(this);
6329
- const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command);
6641
+ const answer = await storeRecoveryCheck(environmentOf(this).env ?? process.env, command, version);
6330
6642
  renderAnswer(this, output, itemOf(snakeKeys(answer)));
6331
6643
  if (output.format === "pretty")
6332
6644
  for (const line of recoveryNotes(answer))
@@ -6347,7 +6659,7 @@ var storeRecoverCommand = /* @__PURE__ */ __name(({ command, version }) => {
6347
6659
  return recover;
6348
6660
  }, "storeRecoverCommand");
6349
6661
 
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
6662
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/store-info.js
6351
6663
  var pendingIfKnown = /* @__PURE__ */ __name((database) => database.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'normalized_text'").get() ? pendingNormalization(database) : null, "pendingIfKnown");
6352
6664
  var bytesOf = /* @__PURE__ */ __name((path) => existsSync4(path) ? statSync3(path).size : 0, "bytesOf");
6353
6665
  var messageOf = /* @__PURE__ */ __name((error) => error instanceof Error ? error.message : String(error), "messageOf");
@@ -6393,7 +6705,7 @@ var storeInfoCommand = /* @__PURE__ */ __name(() => annotate(new Command("info")
6393
6705
  renderAnswer(this, outputFor(this), itemOf(answer));
6394
6706
  }), "storeInfoCommand");
6395
6707
 
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
6708
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/password.js
6397
6709
  var ENCRYPT_OPTION = [
6398
6710
  "--encrypt",
6399
6711
  "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"
@@ -6412,7 +6724,7 @@ var passwordOf = /* @__PURE__ */ __name(async (command, { twice }) => {
6412
6724
  return password;
6413
6725
  }, "passwordOf");
6414
6726
 
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
6727
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/rules.js
6416
6728
  import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
6417
6729
  import { join as join2 } from "node:path";
6418
6730
  var REPLY_ACTIONS = ["reply", "task"];
@@ -6583,7 +6895,7 @@ var problem = /* @__PURE__ */ __name((issue) => {
6583
6895
  }, "problem");
6584
6896
  var broken = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the reply rules ${path} cannot be read (${why}) \u2014 fix the file`), "broken");
6585
6897
 
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
6898
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/state.js
6587
6899
  import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
6588
6900
  import { join as join3 } from "node:path";
6589
6901
  var ANSWERED_KEPT = 1e3;
@@ -6636,7 +6948,7 @@ var recordReply = /* @__PURE__ */ __name((state, rule2, message, now) => {
6636
6948
  }, "recordReply");
6637
6949
  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");
6638
6950
 
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
6951
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/decide.js
6640
6952
  var skip = /* @__PURE__ */ __name((why) => ({ skip: why }), "skip");
6641
6953
  var decide = /* @__PURE__ */ __name((rule2, incoming, state, now) => {
6642
6954
  const { message, chat, owner, sender } = incoming;
@@ -6742,8 +7054,37 @@ var filled = /* @__PURE__ */ __name((template2, senderName) => {
6742
7054
  return template2.replaceAll("{firstName}", name.split(/\s+/)[0] ?? name).replaceAll("{name}", name);
6743
7055
  }, "filled");
6744
7056
 
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
7057
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/template.js
7058
+ var import_liquidjs2 = __toESM(require_liquid_node(), 1);
7059
+
7060
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/render/liquid.js
6746
7061
  var import_liquidjs = __toESM(require_liquid_node(), 1);
7062
+ var safeLiquid = /* @__PURE__ */ __name((limits) => {
7063
+ const engine = new import_liquidjs.Liquid({
7064
+ ownPropertyOnly: true,
7065
+ strictVariables: true,
7066
+ strictFilters: true,
7067
+ lenientIf: false,
7068
+ parseLimit: limits.parse,
7069
+ renderLimit: limits.milliseconds,
7070
+ memoryLimit: limits.memory,
7071
+ preserveTimezones: true
7072
+ });
7073
+ for (const name of ["include", "render", "layout"]) {
7074
+ engine.registerTag(name, class extends import_liquidjs.Tag {
7075
+ constructor(token, tokens, liquid) {
7076
+ super(token, tokens, liquid);
7077
+ throw new Error("templates cannot read files");
7078
+ }
7079
+ render() {
7080
+ return "";
7081
+ }
7082
+ });
7083
+ }
7084
+ return engine;
7085
+ }, "safeLiquid");
7086
+
7087
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/template.js
6747
7088
  var TEMPLATE_LIMITS = {
6748
7089
  parse: 32768,
6749
7090
  renders: 2e3,
@@ -6797,28 +7138,8 @@ var renderReplyTemplate = /* @__PURE__ */ __name(async (reply, input) => {
6797
7138
  hourCycle: "h23"
6798
7139
  }).formatToParts(input.now).map(({ type, value }) => [type, value]));
6799
7140
  const localTime = `${parts2.year}-${parts2.month}-${parts2.day}T${parts2.hour}:${parts2.minute}:${parts2.second}${parts2.timeZoneName?.replace("GMT", "") || "+00:00"}`;
6800
- const engine = new import_liquidjs.Liquid({
6801
- ownPropertyOnly: true,
6802
- strictVariables: true,
6803
- strictFilters: true,
6804
- lenientIf: false,
6805
- parseLimit: limits.parse,
6806
- renderLimit: limits.milliseconds,
6807
- memoryLimit: limits.memory,
6808
- preserveTimezones: true
6809
- });
6810
- for (const name2 of ["include", "render", "layout"]) {
6811
- engine.registerTag(name2, class extends import_liquidjs.Tag {
6812
- constructor(token, tokens, liquid) {
6813
- super(token, tokens, liquid);
6814
- throw new Error("reply templates cannot read files");
6815
- }
6816
- render() {
6817
- return "";
6818
- }
6819
- });
6820
- }
6821
- engine.registerTag("ai", class extends import_liquidjs.Tag {
7141
+ const engine = safeLiquid({ parse: limits.parse, memory: limits.memory, milliseconds: limits.milliseconds });
7142
+ engine.registerTag("ai", class extends import_liquidjs2.Tag {
6822
7143
  body = [];
6823
7144
  fallback = null;
6824
7145
  constructor(token, tokens, liquid, parser) {
@@ -6879,7 +7200,7 @@ var renderReplyTemplate = /* @__PURE__ */ __name(async (reply, input) => {
6879
7200
  });
6880
7201
  const templates = engine.parse(source);
6881
7202
  const name = input.senderName?.trim() ?? "";
6882
- const context = new import_liquidjs.Context({
7203
+ const context = new import_liquidjs2.Context({
6883
7204
  sender: { firstName: name.split(/\s+/)[0] ?? "", name },
6884
7205
  chat: { title: input.chat.title ?? "", kind: input.chat.kind },
6885
7206
  now: localTime
@@ -6902,7 +7223,7 @@ var renderReplyTemplate = /* @__PURE__ */ __name(async (reply, input) => {
6902
7223
  }
6903
7224
  }, "renderReplyTemplate");
6904
7225
 
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
7226
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/dry-run.js
6906
7227
  var DRY_RUN_DAYS = 7;
6907
7228
  var PAGE = 500;
6908
7229
  var dryRun = /* @__PURE__ */ __name(async (store, account, rules, { since, until = Date.now(), only, audience, render }) => {
@@ -7016,143 +7337,7 @@ var storedSince = /* @__PURE__ */ __name(async (store, account, chat, since) =>
7016
7337
  }
7017
7338
  }, "storedSince");
7018
7339
 
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
7020
- var endpointKeyName = /* @__PURE__ */ __name((baseUrl) => {
7021
- const host = new URL(baseUrl).host;
7022
- return ["openai", "anthropic"].includes(host) ? `endpoint:${host}` : host;
7023
- }, "endpointKeyName");
7024
- var embeddingKeys = /* @__PURE__ */ __name((app, env = process.env, keyring) => {
7025
- const where = { appName: app.appName, prefix: app.envPrefix, env };
7026
- const credentials = /* @__PURE__ */ __name((provider) => new Credentials({
7027
- configDir: resolvePaths(where).config,
7028
- service: app.appName,
7029
- ...["openai", "anthropic"].includes(provider) ? { envVar: envName(app, `${provider.toUpperCase()}_API_KEY`) } : {},
7030
- isolated: pathsAreOverridden(where),
7031
- env,
7032
- ...keyring ? { keyring } : {},
7033
- warn: /* @__PURE__ */ __name((message) => process.stderr.write(`${message}
7034
- `), "warn")
7035
- }), "credentials");
7036
- const account = /* @__PURE__ */ __name((provider) => `embeddings:${provider}`, "account");
7037
- return {
7038
- read: /* @__PURE__ */ __name((provider) => {
7039
- const stored = credentials(provider).read(account(provider));
7040
- if (stored)
7041
- return { key: stored.secret, source: stored.source };
7042
- const shared = ["openai", "anthropic"].includes(provider) ? env[`${provider.toUpperCase()}_API_KEY`]?.trim() : void 0;
7043
- return shared ? { key: shared, source: "env" } : void 0;
7044
- }, "read"),
7045
- write: /* @__PURE__ */ __name((provider, key) => credentials(provider).write(account(provider), key, { signIn: true }), "write"),
7046
- remove: /* @__PURE__ */ __name((provider) => credentials(provider).remove(account(provider)), "remove")
7047
- };
7048
- }, "embeddingKeys");
7049
-
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
7051
- var options = strictObject({
7052
- temperature: range(0, 2),
7053
- top_p: range(0, 1),
7054
- presence_penalty: range(-2, 2),
7055
- frequency_penalty: range(-2, 2),
7056
- seed: optional(pipe(number(), integer())),
7057
- stop: optional(union([string(), array(string())])),
7058
- response_format: optional(strictObject({ type: picklist(["text", "json_object"]) }))
7059
- });
7060
- var openai = {
7061
- images: true,
7062
- baseUrl: "https://api.openai.com/v1",
7063
- validate: /* @__PURE__ */ __name((given) => checkedOptions("openai", options, given), "validate"),
7064
- complete: /* @__PURE__ */ __name((target, request, checked, apiKey, fetcher) => withTimeLimit(12e4, async (deadline) => {
7065
- const response = await fetcher(`${target.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
7066
- method: "POST",
7067
- headers: { "Content-Type": "application/json", ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
7068
- body: JSON.stringify({
7069
- ...checked,
7070
- model: target.model,
7071
- messages: [
7072
- { role: "system", content: systemFor(request) },
7073
- ...messagesFor(request),
7074
- ...request.images === void 0 ? [] : [
7075
- {
7076
- role: "user",
7077
- content: request.images.map((image) => ({
7078
- type: "image_url",
7079
- image_url: { url: `data:${image.mimeType};base64,${image.data}`, detail: "high" }
7080
- }))
7081
- }
7082
- ]
7083
- ],
7084
- ...new URL(target.baseUrl).hostname === "api.openai.com" ? { max_completion_tokens: request.maxTokens } : { max_tokens: request.maxTokens }
7085
- }),
7086
- signal: deadline,
7087
- redirect: "error"
7088
- });
7089
- if (!response.ok)
7090
- throw new Error("provider rejected request");
7091
- const body = await response.json();
7092
- const choice = body.choices?.[0];
7093
- if (choice?.finish_reason !== "stop" || typeof choice.message?.content !== "string" || !Number.isInteger(body.usage?.total_tokens) || (body.usage?.total_tokens ?? 0) < 1)
7094
- throw new Error("incomplete response");
7095
- return { text: choice.message.content, tokens: body.usage?.total_tokens };
7096
- }), "complete")
7097
- };
7098
-
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
7100
- var modelGateway = /* @__PURE__ */ __name((deps) => ({
7101
- complete: /* @__PURE__ */ __name(async (request) => {
7102
- if (deps.signal?.aborted)
7103
- throw new CliError("cancelled", "model request cancelled");
7104
- const target = deps.resolve(request.purpose);
7105
- if (!target || target.provider === "off")
7106
- throw new CliError("configuration_error", `models.${request.purpose}.provider is not configured; no model was called`);
7107
- if (!request.purpose || !Number.isSafeInteger(request.maxTokens) || request.maxTokens < 1 || typeof request.prompt !== "string")
7108
- throw new CliError("validation_error", "a model request needs a purpose, prompt and positive whole maxTokens");
7109
- validateImages(request.images);
7110
- let adapter = deps.adapters?.[target.provider];
7111
- if (!adapter && target.provider === "openai")
7112
- adapter = openai;
7113
- if (!adapter && target.provider === "anthropic")
7114
- adapter = (await import("./anthropic-DFUW2KTG.js")).anthropic;
7115
- if (!adapter)
7116
- throw new CliError("validation_error", `no model adapter for ${target.provider}`);
7117
- if (request.images !== void 0 && adapter.images !== true)
7118
- throw new CliError("validation_error", "the model adapter does not support image inputs");
7119
- const options2 = adapter.validate(request.options ?? {});
7120
- const baseUrl = target.baseUrl ?? adapter.baseUrl;
7121
- if (!target.model.trim() || !endpoint(baseUrl))
7122
- throw new CliError("validation_error", "a model target needs a model and an HTTP/S endpoint without credentials, query or fragment");
7123
- if (!await deps.consent(request, { ...target, baseUrl }))
7124
- throw new CliError("permission_error", `model consent for ${request.purpose} is missing; no data was sent`);
7125
- const apiKey = await deps.key?.(target.provider, target);
7126
- if (deps.signal?.aborted)
7127
- throw new CliError("cancelled", "model request cancelled");
7128
- const fetcher = deps.fetch ?? fetch;
7129
- let limited = false;
7130
- const cancellable = /* @__PURE__ */ __name(async (input, init) => {
7131
- const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
7132
- const response = await fetcher(input, {
7133
- ...init,
7134
- signal: deps.signal ? AbortSignal.any([deps.signal, ...signal ? [signal] : []]) : signal
7135
- });
7136
- if (response.status === 429)
7137
- limited = true;
7138
- return response;
7139
- }, "cancellable");
7140
- try {
7141
- const answer = await adapter.complete({ ...target, baseUrl }, request, options2, apiKey, cancellable);
7142
- if (deps.signal?.aborted)
7143
- throw new Error("cancelled");
7144
- if (typeof answer.text !== "string" || !Number.isSafeInteger(answer.tokens) || answer.tokens < 1)
7145
- throw new Error("incomplete");
7146
- return { ...answer, provider: target.provider, model: target.model };
7147
- } catch {
7148
- if (limited)
7149
- throw new CliError("rate_limited", `${request.purpose} provider rate limit reached; no result was stored`);
7150
- throw new CliError("invalid_response", `${request.purpose} provider failed or returned an incomplete response; no result was stored`);
7151
- }
7152
- }, "complete")
7153
- }), "modelGateway");
7154
-
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
7340
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/consents.js
7156
7341
  import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
7157
7342
  import { join as join4 } from "node:path";
7158
7343
  var shape = strictObject({
@@ -7177,21 +7362,21 @@ var mayModelReply = /* @__PURE__ */ __name((path, provider, chat) => {
7177
7362
  return consent.provider === provider && !consent.deniedChats.includes(chat);
7178
7363
  }, "mayModelReply");
7179
7364
 
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
7181
- var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, options2 = {
7365
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/rendering.js
7366
+ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, options = {
7182
7367
  ai: true
7183
7368
  }) => async (rule2, message, chat, now) => {
7184
7369
  let called;
7185
7370
  const gateway = modelGateway({
7186
- signal: options2.signal,
7371
+ signal: options.signal,
7187
7372
  resolve: /* @__PURE__ */ __name((purpose) => {
7188
7373
  called = modelTarget(settings(), purpose);
7189
7374
  return called;
7190
7375
  }, "resolve"),
7191
7376
  consent: /* @__PURE__ */ __name((_request, target) => mayModelReply(replyConsentPathFor(app, profile, env), replyModelIdentity(target.provider, target.baseUrl ?? ""), message.chatId), "consent"),
7192
- key: /* @__PURE__ */ __name((provider, target) => embeddingKeys(app, env, options2.keyring).read(target.baseUrl === void 0 ? provider : endpointKeyName(target.baseUrl))?.key, "key")
7377
+ key: /* @__PURE__ */ __name((provider, target) => embeddingKeys(app, env, options.keyring).read(target.baseUrl === void 0 ? provider : endpointKeyName(target.baseUrl))?.key, "key")
7193
7378
  });
7194
- if (options2.signal?.aborted)
7379
+ if (options.signal?.aborted)
7195
7380
  throw new CliError("cancelled", "reply rendering cancelled");
7196
7381
  const result2 = await renderReplyTemplate(rule2.reply, {
7197
7382
  senderName: message.senderName,
@@ -7199,8 +7384,8 @@ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, o
7199
7384
  now,
7200
7385
  timezone: rule2.when.hours?.timezone,
7201
7386
  data: message.text,
7202
- allowAI: options2.ai === true,
7203
- preview: options2.preview === true,
7387
+ allowAI: options.ai === true,
7388
+ preview: options.preview === true,
7204
7389
  complete: /* @__PURE__ */ __name(async (prompt, data) => {
7205
7390
  const result3 = await gateway.complete({
7206
7391
  purpose: "replies",
@@ -7209,7 +7394,7 @@ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, o
7209
7394
  data,
7210
7395
  maxTokens: 512
7211
7396
  });
7212
- if (options2.signal?.aborted)
7397
+ if (options.signal?.aborted)
7213
7398
  throw new CliError("cancelled", "reply rendering cancelled");
7214
7399
  const current = modelTarget(settings(), "replies");
7215
7400
  const baseUrl = called?.baseUrl ?? (called?.provider === "anthropic" ? "https://api.anthropic.com" : "https://api.openai.com/v1");
@@ -7224,7 +7409,7 @@ var replyRenderer = /* @__PURE__ */ __name((app, profile, settings, env, warn, o
7224
7409
  return result2;
7225
7410
  }, "replyRenderer");
7226
7411
 
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
7412
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/replies/serve.js
7228
7413
  var NOT_ALLOWED = "replies.send is not allow";
7229
7414
  var NO_RULES = "no rules";
7230
7415
  var ONLY_TASK = "opened a task, sent nothing";
@@ -7317,12 +7502,12 @@ var replyTo = /* @__PURE__ */ __name(async (deps, message) => {
7317
7502
  return { skip: why };
7318
7503
  }, "replyTo");
7319
7504
 
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
7505
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-catch-up.js
7321
7506
  var START_SYNC_DELAY_MS = 3e4;
7322
7507
  var START_SYNC_BUDGET_MS = 5 * 6e4;
7323
7508
  var START_SYNC_WINDOW_MS = 7 * 864e5;
7324
7509
  var START_SYNC_PER_CHAT = 500;
7325
- var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note, warn, delayMs = START_SYNC_DELAY_MS, budgetMs = START_SYNC_BUDGET_MS, windowMs = START_SYNC_WINDOW_MS, now = Date.now }) => {
7510
+ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch, note, warn, delayMs = START_SYNC_DELAY_MS, budgetMs = START_SYNC_BUDGET_MS, windowMs = START_SYNC_WINDOW_MS, now = Date.now }) => {
7326
7511
  const controller = new AbortController();
7327
7512
  let timer;
7328
7513
  let pass = Promise.resolve();
@@ -7350,7 +7535,7 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
7350
7535
  if (stop.aborted)
7351
7536
  break;
7352
7537
  try {
7353
- summary.fetched += (await fetch2(chat.id, Math.max(held ?? anywhere, floor), stop)).fetched;
7538
+ summary.fetched += (await fetch(chat.id, Math.max(held ?? anywhere, floor), stop)).fetched;
7354
7539
  summary.chats += 1;
7355
7540
  } catch (error) {
7356
7541
  if (stop.aborted)
@@ -7394,10 +7579,10 @@ var startSync = /* @__PURE__ */ __name(({ chats, newestHeld, fetch: fetch2, note
7394
7579
  };
7395
7580
  }, "startSync");
7396
7581
 
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
7582
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-members.js
7398
7583
  var FIRST_FETCH_MS = 6e4;
7399
7584
  var DAY_MS = 864e5;
7400
- var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, firstMs = FIRST_FETCH_MS, everyMs = DAY_MS }) => {
7585
+ var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch, warn, firstMs = FIRST_FETCH_MS, everyMs = DAY_MS }) => {
7401
7586
  let timer;
7402
7587
  let round = Promise.resolve();
7403
7588
  let stopped = false;
@@ -7410,7 +7595,7 @@ var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, fi
7410
7595
  if (lastCount?.day === today)
7411
7596
  continue;
7412
7597
  try {
7413
- await fetch2(store, account, chatId);
7598
+ await fetch(store, account, chatId);
7414
7599
  done.fetched += 1;
7415
7600
  } catch (error) {
7416
7601
  done.failed += 1;
@@ -7448,7 +7633,7 @@ var memberFetches = /* @__PURE__ */ __name(({ withStore, fetch: fetch2, warn, fi
7448
7633
  };
7449
7634
  }, "memberFetches");
7450
7635
 
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
7636
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-notice.js
7452
7637
  var record2 = /* @__PURE__ */ __name((context, app, severity, attributes) => recordLogFor(context.streams.diagnostic, app, { command: currentRun().command || "serve" })[severity](attributes), "record");
7453
7638
  var noticeFor = /* @__PURE__ */ __name((context, app, severity = "warn") => ({ text, ...attributes }) => {
7454
7639
  if (context.format === "pretty") {
@@ -7481,7 +7666,93 @@ var recordDiagnostics = /* @__PURE__ */ __name((context, app) => {
7481
7666
  return context;
7482
7667
  }, "recordDiagnostics");
7483
7668
 
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
7669
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-outdated.js
7670
+ import { existsSync as existsSync8, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "node:fs";
7671
+ import { dirname as dirname2, join as join5 } from "node:path";
7672
+ var OUTDATED_CHECK_MS = 6e4;
7673
+ var ownPackageRoot = /* @__PURE__ */ __name((running, script = process.argv[1]) => {
7674
+ let dir;
7675
+ try {
7676
+ dir = dirname2(realpathSync2(script ?? ""));
7677
+ } catch {
7678
+ return void 0;
7679
+ }
7680
+ for (let up = 0; up < 8; up++) {
7681
+ const manifest = join5(dir, "package.json");
7682
+ if (existsSync8(manifest))
7683
+ return installedVersion(dir) === running ? dir : void 0;
7684
+ const parent = dirname2(dir);
7685
+ if (parent === dir)
7686
+ return void 0;
7687
+ dir = parent;
7688
+ }
7689
+ return void 0;
7690
+ }, "ownPackageRoot");
7691
+ var installedVersion = /* @__PURE__ */ __name((root) => {
7692
+ try {
7693
+ const { version } = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
7694
+ return typeof version === "string" ? version : void 0;
7695
+ } catch {
7696
+ return void 0;
7697
+ }
7698
+ }, "installedVersion");
7699
+ var newer = /* @__PURE__ */ __name((one, other) => {
7700
+ const parts2 = /* @__PURE__ */ __name((version) => version.split(/[.+-]/, 3).map(Number), "parts");
7701
+ const [a, b] = [parts2(one), parts2(other)];
7702
+ for (let i = 0; i < 3; i++)
7703
+ if ((a[i] ?? 0) !== (b[i] ?? 0))
7704
+ return (a[i] ?? 0) > (b[i] ?? 0);
7705
+ return false;
7706
+ }, "newer");
7707
+ var outdatedReason = /* @__PURE__ */ __name(async ({ command, running, storePath: storePath2, packageRoot, speaks = SPEAKS }) => {
7708
+ const installed = packageRoot === void 0 ? void 0 : installedVersion(packageRoot);
7709
+ if (installed !== void 0 && newer(installed, running))
7710
+ return `${command} ${installed} is installed and this serve runs ${running}: stopping so it starts again on ${installed}`;
7711
+ if (!existsSync8(storePath2))
7712
+ return void 0;
7713
+ let schema;
7714
+ try {
7715
+ const { database } = await openSqlite(storePath2, { readOnly: true });
7716
+ try {
7717
+ schema = fileSchemaOf(database);
7718
+ } finally {
7719
+ database.close();
7720
+ }
7721
+ } catch {
7722
+ return void 0;
7723
+ }
7724
+ if (writableBy(schema, speaks))
7725
+ return void 0;
7726
+ return `the store is at format ${schema.version} and needs at least ${schema.minCompatible}; this serve (${command} ${running}) speaks ${speaks} and can no longer write it: stopping \u2014 \`${command} upgrade\` if it does not start again on a newer version`;
7727
+ }, "outdatedReason");
7728
+ var watchOutdated = /* @__PURE__ */ __name(({ check: check2, onOutdated, everyMs = OUTDATED_CHECK_MS }) => {
7729
+ let busy = false;
7730
+ let done = false;
7731
+ const timer = setInterval(() => {
7732
+ if (busy || done)
7733
+ return;
7734
+ busy = true;
7735
+ check2().then((reason) => {
7736
+ if (reason === void 0 || done)
7737
+ return;
7738
+ done = true;
7739
+ clearInterval(timer);
7740
+ onOutdated(reason);
7741
+ }).catch(() => {
7742
+ }).finally(() => {
7743
+ busy = false;
7744
+ });
7745
+ }, everyMs);
7746
+ timer.unref();
7747
+ return {
7748
+ stop: /* @__PURE__ */ __name(() => {
7749
+ done = true;
7750
+ clearInterval(timer);
7751
+ }, "stop")
7752
+ };
7753
+ }, "watchOutdated");
7754
+
7755
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-stems.js
7485
7756
  var STEMS_EVERY_MS = 3e4;
7486
7757
  var STEMS_SLICE_MS = 2e3;
7487
7758
  var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY_MS, sliceMs = STEMS_SLICE_MS }) => {
@@ -7521,17 +7792,17 @@ var stemFills = /* @__PURE__ */ __name(({ withStore, warn, everyMs = STEMS_EVERY
7521
7792
  };
7522
7793
  }, "stemFills");
7523
7794
 
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
7795
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/render/messages.js
7525
7796
  import { styleText } from "node:util";
7526
7797
  var TIME_WIDTH = 8;
7527
7798
  var INDENT = " ".repeat(TIME_WIDTH + 2);
7528
7799
  var MIN_WIDTH = 40;
7529
7800
  var SENDER_COLOURS = ["green", "yellow", "magenta", "blue", "red"];
7530
- var renderMessages = /* @__PURE__ */ __name((messages, options2 = {}) => {
7801
+ var renderMessages = /* @__PURE__ */ __name((messages, options = {}) => {
7531
7802
  if (messages.length === 0)
7532
7803
  return "(nothing)";
7533
- const day = dayFormatter(options2);
7534
- const paint = painter(options2);
7804
+ const day = dayFormatter(options);
7805
+ const paint = painter(options);
7535
7806
  let previous;
7536
7807
  const blocks = [];
7537
7808
  for (const message of messages) {
@@ -7539,40 +7810,40 @@ var renderMessages = /* @__PURE__ */ __name((messages, options2 = {}) => {
7539
7810
  if (date !== previous)
7540
7811
  blocks.push(paint("dim", `\u2500\u2500 ${date} \u2500\u2500`));
7541
7812
  previous = date;
7542
- blocks.push(renderMessage(message, options2));
7813
+ blocks.push(renderMessage(message, options));
7543
7814
  }
7544
7815
  return blocks.join("\n\n");
7545
7816
  }, "renderMessages");
7546
- var renderMessage = /* @__PURE__ */ __name((message, options2 = {}) => {
7547
- const paint = painter(options2);
7548
- const width = Math.max(MIN_WIDTH, options2.width ?? 80);
7817
+ var renderMessage = /* @__PURE__ */ __name((message, options = {}) => {
7818
+ const paint = painter(options);
7819
+ const width = Math.max(MIN_WIDTH, options.width ?? 80);
7549
7820
  const room = width - INDENT.length;
7550
- const time = timeFormatter(options2);
7551
- const verbosity = options2.verbosity ?? 0;
7821
+ const time = timeFormatter(options);
7822
+ const verbosity = options.verbosity ?? 0;
7552
7823
  const chat = "chatTitle" in message ? paint("dim", ` \xB7 ${singleLine(message.chatTitle ?? message.chatId)}`) : "";
7553
7824
  const mark = "anchor" in message && message.anchor ? paint("bold", " \u25C0") : "";
7554
- const lines = [`${paint("dim", time(message.timestamp))} ${senderOf(message, options2)}${chat}${mark}`];
7825
+ const lines = [`${paint("dim", time(message.timestamp))} ${senderOf(message, options)}${chat}${mark}`];
7555
7826
  const body = /* @__PURE__ */ __name((text) => wrapAnsi(visibleControls(text), room, { hard: true }).split("\n"), "body");
7556
7827
  const email = message.email;
7557
7828
  if (email)
7558
7829
  lines.push(paint("dim", mailLine(email)));
7559
7830
  if (message.replyTo)
7560
- lines.push(paint("dim", preview("\u21B3", message.replyTo, room, options2)));
7831
+ lines.push(paint("dim", preview("\u21B3", message.replyTo, room, options)));
7561
7832
  if (message.forwardedFrom) {
7562
- lines.push(paint("dim", `\u21AA ${nameOf(message.forwardedFrom, options2)}`));
7833
+ lines.push(paint("dim", `\u21AA ${nameOf(message.forwardedFrom, options)}`));
7563
7834
  if (message.forwardedFrom.text)
7564
7835
  for (const line of body(message.forwardedFrom.text))
7565
7836
  lines.push(line);
7566
- lines.push(...attachmentLines(message.forwardedFrom.attachments, paint, options2));
7837
+ lines.push(...attachmentLines(message.forwardedFrom.attachments, paint, options));
7567
7838
  }
7568
7839
  if (message.text)
7569
7840
  for (const line of body(message.text))
7570
7841
  lines.push(line);
7571
- lines.push(...attachmentLines(message.attachments, paint, options2));
7842
+ lines.push(...attachmentLines(message.attachments, paint, options));
7572
7843
  if (message.reactions && message.reactions.total > 0)
7573
7844
  lines.push(paint("dim", reactionLine(message.reactions)));
7574
7845
  if (message.editedAt)
7575
- lines.push(paint("dim", `edited ${editedAt(message, options2)}`));
7846
+ lines.push(paint("dim", `edited ${editedAt(message, options)}`));
7576
7847
  if (verbosity >= 1) {
7577
7848
  const fields = [
7578
7849
  ["message", message.id],
@@ -7584,7 +7855,7 @@ var renderMessage = /* @__PURE__ */ __name((message, options2 = {}) => {
7584
7855
  ...message.attachments.map((a) => ["link", a.url])
7585
7856
  ];
7586
7857
  if (verbosity >= 2) {
7587
- fields.push(["provider", options2.provider], ["profile", options2.profile], ["sent", message.timestamp], ["edited", message.editedAt], ["outgoing", message.outgoing === null ? "unknown" : String(message.outgoing)], ...message.attachments.map((a) => ["attachment", JSON.stringify(a)]), ["metadata", message.providerMetadata && JSON.stringify(message.providerMetadata)]);
7858
+ fields.push(["provider", options.provider], ["profile", options.profile], ["sent", message.timestamp], ["edited", message.editedAt], ["outgoing", message.outgoing === null ? "unknown" : String(message.outgoing)], ...message.attachments.map((a) => ["attachment", JSON.stringify(a)]), ["metadata", message.providerMetadata && JSON.stringify(message.providerMetadata)]);
7588
7859
  }
7589
7860
  const shown = fields.filter((field) => typeof field[1] === "string");
7590
7861
  const label = Math.max(...shown.map(([key]) => key.length));
@@ -7597,36 +7868,36 @@ var mailLine = /* @__PURE__ */ __name(({ to, cc, labels }) => {
7597
7868
  return [to.length ? `to ${names(to)}` : "", cc.length ? `cc ${names(cc)}` : "", labels.join(", ")].filter(Boolean).join(" \xB7 ");
7598
7869
  }, "mailLine");
7599
7870
  var painter = /* @__PURE__ */ __name(({ color = false }) => (style, text) => color ? styleText(style, text, { validateStream: false }) : text, "painter");
7600
- var senderOf = /* @__PURE__ */ __name((message, options2) => {
7601
- const paint = painter(options2);
7871
+ var senderOf = /* @__PURE__ */ __name((message, options) => {
7872
+ const paint = painter(options);
7602
7873
  if (message.outgoing === true)
7603
- return paint(["bold", "cyan"], you(options2));
7604
- const name = nameOf(message, options2);
7605
- if (!options2.senderColors)
7874
+ return paint(["bold", "cyan"], you(options));
7875
+ const name = nameOf(message, options);
7876
+ if (!options.senderColors)
7606
7877
  return paint("bold", name);
7607
7878
  const colour = SENDER_COLOURS[hash(message.senderId ?? name) % SENDER_COLOURS.length] ?? "green";
7608
7879
  return paint(["bold", colour], name);
7609
7880
  }, "senderOf");
7610
- var nameOf = /* @__PURE__ */ __name(({ senderName, senderId, outgoing }, options2) => outgoing === true ? you(options2) : singleLine(senderName ?? senderId ?? "unknown"), "nameOf");
7881
+ var nameOf = /* @__PURE__ */ __name(({ senderName, senderId, outgoing }, options) => outgoing === true ? you(options) : singleLine(senderName ?? senderId ?? "unknown"), "nameOf");
7611
7882
  var DEFAULT_LOCALE = "ru-RU";
7612
7883
  var you = /* @__PURE__ */ __name(({ locale = DEFAULT_LOCALE }) => locale.startsWith("ru") ? "\u0432\u044B" : "you", "you");
7613
7884
  var hash = /* @__PURE__ */ __name((value) => [...value].reduce((sum, char) => sum * 31 + char.charCodeAt(0) >>> 0, 7), "hash");
7614
- var preview = /* @__PURE__ */ __name((mark, quoted, room, options2) => {
7885
+ var preview = /* @__PURE__ */ __name((mark, quoted, room, options) => {
7615
7886
  const text = singleLine(quoted.text.split("\n")[0] ?? "") || (quoted.attachments[0] ? `\u{1F4CE} ${quoted.attachments[0].kind}` : "");
7616
- const line = text ? `${mark} ${nameOf(quoted, options2)}: ${text}` : `${mark} message ${quoted.id}`;
7887
+ const line = text ? `${mark} ${nameOf(quoted, options)}: ${text}` : `${mark} message ${quoted.id}`;
7617
7888
  if (stringWidth(line) <= room)
7618
7889
  return line;
7619
7890
  return `${wrapAnsi(line, room - 1, { hard: true }).split("\n")[0]}\u2026`;
7620
7891
  }, "preview");
7621
- var attachmentLines = /* @__PURE__ */ __name((attachments, paint, options2) => {
7892
+ var attachmentLines = /* @__PURE__ */ __name((attachments, paint, options) => {
7622
7893
  const link = /* @__PURE__ */ __name((label, raw) => {
7623
7894
  if (raw === void 0)
7624
7895
  return label;
7625
7896
  const url = singleLine(raw);
7626
- return options2.color ? `\x1B]8;;${url}\x07${label}\x1B]8;;\x07` : `${label} ${url}`;
7897
+ return options.color ? `\x1B]8;;${url}\x07${label}\x1B]8;;\x07` : `${label} ${url}`;
7627
7898
  }, "link");
7628
- let number2 = 0;
7629
- const keyboard = attachments.flatMap((attachment) => attachment.buttons ?? []).map((row) => paint("dim", row.map((button) => link(`[${++number2} ${singleLine(button.text)}]`, button.url)).join(" ")));
7899
+ let number = 0;
7900
+ const keyboard = attachments.flatMap((attachment) => attachment.buttons ?? []).map((row) => paint("dim", row.map((button) => link(`[${++number} ${singleLine(button.text)}]`, button.url)).join(" ")));
7630
7901
  const polls = attachments.flatMap((attachment) => attachment.poll ? pollLines(attachment.poll) : []);
7631
7902
  const cards = attachments.flatMap(({ contact }) => contact ? [
7632
7903
  paint("dim", `\u{1F464} ${[contact.name, contact.phone].flatMap((part) => part ? [singleLine(part)] : []).join(" \xB7 ")}`)
@@ -7690,14 +7961,14 @@ var reactionLine = /* @__PURE__ */ __name(({ counts, mine }) => {
7690
7961
  const shown = counts.map(({ reaction, count: count3 }) => `${singleLine(reaction)} ${count3}`).join(" ");
7691
7962
  return mine ? `${shown} (you: ${singleLine(mine)})` : shown;
7692
7963
  }, "reactionLine");
7693
- var editedAt = /* @__PURE__ */ __name((message, options2) => {
7964
+ var editedAt = /* @__PURE__ */ __name((message, options) => {
7694
7965
  const edited = message.editedAt ?? message.timestamp;
7695
- const time = timeFormatter(options2)(edited);
7696
- const day = dayFormatter(options2);
7966
+ const time = timeFormatter(options)(edited);
7967
+ const day = dayFormatter(options);
7697
7968
  return day(edited) === day(message.timestamp) ? time : `${day(edited)} ${time}`;
7698
7969
  }, "editedAt");
7699
7970
 
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
7971
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/message-items.js
7701
7972
  var defined = /* @__PURE__ */ __name((value) => Object.fromEntries(Object.entries(value).filter(([, one]) => one !== void 0)), "defined");
7702
7973
  var attachmentItem = /* @__PURE__ */ __name((attachment) => defined({
7703
7974
  kind: attachment.kind,
@@ -7792,7 +8063,7 @@ var viewOf = /* @__PURE__ */ __name((context, messenger) => ({
7792
8063
  locale: messenger.app.locale
7793
8064
  }), "viewOf");
7794
8065
 
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
8066
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-answers.js
7796
8067
  var observed = /* @__PURE__ */ __name((value) => ({
7797
8068
  value: value.value,
7798
8069
  observed_at: value.observedAt,
@@ -7859,7 +8130,7 @@ var watchEventItem = /* @__PURE__ */ __name((value, account) => {
7859
8130
  }
7860
8131
  }, "watchEventItem");
7861
8132
 
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
8133
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/watch-command.js
7863
8134
  var watchCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("watch"), {
7864
8135
  output: { entity: "watch_item" },
7865
8136
  effects: REMOTE_READ,
@@ -8014,7 +8285,7 @@ var describe = /* @__PURE__ */ __name((event, render) => {
8014
8285
  }
8015
8286
  }, "describe");
8016
8287
 
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
8288
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/serve-command.js
8018
8289
  var serveCommand = /* @__PURE__ */ __name((messenger) => {
8019
8290
  const command = annotate(new Command("serve"), {
8020
8291
  output: { entity: "serve_summary" },
@@ -8038,8 +8309,8 @@ var serveCommand = /* @__PURE__ */ __name((messenger) => {
8038
8309
  }
8039
8310
  let relaying;
8040
8311
  const onReady = /* @__PURE__ */ __name(() => {
8041
- const listening = { pid: process.pid, startedAt, version, listeningAt: (/* @__PURE__ */ new Date()).toISOString() };
8042
- holdLock(path, listening);
8312
+ const listening2 = { pid: process.pid, startedAt, version, listeningAt: (/* @__PURE__ */ new Date()).toISOString() };
8313
+ holdLock(path, listening2);
8043
8314
  note({
8044
8315
  code: "listening",
8045
8316
  text: `listening for profile ${context.profile}, catching up on what arrived while it was down`
@@ -8048,7 +8319,7 @@ var serveCommand = /* @__PURE__ */ __name((messenger) => {
8048
8319
  return;
8049
8320
  relaying = relay.open(path, context.profile).then((address) => {
8050
8321
  if (address)
8051
- holdLock(path, { ...listening, relay: address });
8322
+ holdLock(path, { ...listening2, relay: address });
8052
8323
  }).catch((error) => {
8053
8324
  const errorCode = failureKey(error);
8054
8325
  warn({ code: "relay_failed", errorCode, text: `commands cannot run through this serve: ${errorCode}` });
@@ -8057,7 +8328,7 @@ var serveCommand = /* @__PURE__ */ __name((messenger) => {
8057
8328
  const counts = {};
8058
8329
  const rules = replying(context, messenger, Date.parse(startedAt));
8059
8330
  const tasks = tasking(context, warn);
8060
- const { handled, startSyncDelayMs } = environmentOf(this);
8331
+ const { handled, startSyncDelayMs, outdated: outdatedHook } = environmentOf(this);
8061
8332
  const count3 = /* @__PURE__ */ __name((event) => {
8062
8333
  counts[event.event] = (counts[event.event] ?? 0) + 1;
8063
8334
  if (event.event === "message") {
@@ -8129,9 +8400,25 @@ var serveCommand = /* @__PURE__ */ __name((messenger) => {
8129
8400
  withStore: /* @__PURE__ */ __name((work) => context.withStore((store) => work(store), { name: "serve stems" }), "withStore"),
8130
8401
  warn
8131
8402
  });
8403
+ const listening = new AbortController();
8404
+ let outdated;
8405
+ const packageRoot = outdatedHook?.packageRoot ?? ownPackageRoot(version);
8406
+ const watch = watchOutdated({
8407
+ check: /* @__PURE__ */ __name(() => outdatedReason({
8408
+ command: messenger.app.command,
8409
+ running: version,
8410
+ storePath: storePath(context.env),
8411
+ packageRoot
8412
+ }), "check"),
8413
+ onOutdated: /* @__PURE__ */ __name((reason) => {
8414
+ outdated = reason;
8415
+ listening.abort();
8416
+ }, "onOutdated"),
8417
+ ...outdatedHook?.everyMs === void 0 ? {} : { everyMs: outdatedHook.everyMs }
8418
+ });
8132
8419
  try {
8133
8420
  await listenUntilStopped(this, context, relay?.messenger ?? messenger, count3, {
8134
- stop: new AbortController(),
8421
+ stop: listening,
8135
8422
  catchUp: true,
8136
8423
  onReady,
8137
8424
  connected: /* @__PURE__ */ __name((open) => {
@@ -8144,6 +8431,7 @@ var serveCommand = /* @__PURE__ */ __name((messenger) => {
8144
8431
  }, "connected")
8145
8432
  });
8146
8433
  } finally {
8434
+ watch.stop();
8147
8435
  await relaying;
8148
8436
  await relay?.close();
8149
8437
  rules.stop();
@@ -8154,6 +8442,8 @@ var serveCommand = /* @__PURE__ */ __name((messenger) => {
8154
8442
  await tasks.settled();
8155
8443
  releaseLock(path);
8156
8444
  }
8445
+ if (outdated !== void 0)
8446
+ throw new CliError("configuration_error", outdated, { reason: "serve.outdated" });
8157
8447
  renderAnswer(this, context, itemOf({
8158
8448
  profile: context.profile,
8159
8449
  started_at: startedAt,
@@ -8278,8 +8568,8 @@ var tasking = /* @__PURE__ */ __name((context, warn) => {
8278
8568
  };
8279
8569
  }, "tasking");
8280
8570
 
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";
8571
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/store-tables-command.js
8572
+ import { existsSync as existsSync9 } from "node:fs";
8283
8573
  var PATH = "store tables list";
8284
8574
  var STORE_TABLES_QUERY = {
8285
8575
  entity: "store_table",
@@ -8308,7 +8598,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
8308
8598
  const filter = filterOf(words);
8309
8599
  const { full } = this.optsWithGlobals();
8310
8600
  const path = storePath(environmentOf(this).env ?? process.env);
8311
- if (!existsSync8(path))
8601
+ if (!existsSync9(path))
8312
8602
  throw new CliError("not_found", `no store at ${path}`);
8313
8603
  const items = await readStoreTables(path, { filter, sizes: full === true });
8314
8604
  renderAnswer(this, outputFor(this), listOf(PATH, {
@@ -8321,7 +8611,7 @@ var storeTablesCommand = /* @__PURE__ */ __name((messenger) => {
8321
8611
  return tables;
8322
8612
  }, "storeTablesCommand");
8323
8613
 
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
8614
+ // node_modules/.pnpm/@wirecat+cli-core@0.618.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.87.0_commander@15._c25084c4731872baba927966435ce31d/node_modules/@wirecat/cli-core/dist/cli/messenger/store-maintenance-command.js
8325
8615
  var SEARCH_INDEXES = ["messages_fts", "chats_fts", "identities_fts"];
8326
8616
  var WORD_INDEX = "message_words";
8327
8617
  var schemaOf = /* @__PURE__ */ __name((database) => {
@@ -8330,7 +8620,7 @@ var schemaOf = /* @__PURE__ */ __name((database) => {
8330
8620
  }, "schemaOf");
8331
8621
  var count2 = /* @__PURE__ */ __name((database, table) => Number(database.prepare(`SELECT count(*) AS n FROM ${table}`).get()?.n ?? 0), "count");
8332
8622
  var pendingIfKnown2 = /* @__PURE__ */ __name((database) => database.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'normalized_text'").get() ? pendingNormalization(database) : null, "pendingIfKnown");
8333
- var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync9(path) ? statSync4(path).size : 0, "bytesOf");
8623
+ var bytesOf2 = /* @__PURE__ */ __name((path) => existsSync10(path) ? statSync4(path).size : 0, "bytesOf");
8334
8624
  var reading = /* @__PURE__ */ __name(async (path, read) => {
8335
8625
  const database = await openCache(path);
8336
8626
  try {
@@ -8347,11 +8637,26 @@ var readingOnly = /* @__PURE__ */ __name(async (path, read) => {
8347
8637
  database.close();
8348
8638
  }
8349
8639
  }, "readingOnly");
8350
- var storeSummary = /* @__PURE__ */ __name(async (env, { deep = false, command } = {}) => {
8640
+ var withoutInode = /* @__PURE__ */ __name(({ inode: _, ...mark }) => mark, "withoutInode");
8641
+ var fileSchema = /* @__PURE__ */ __name(async (path) => {
8642
+ try {
8643
+ return await readingOnly(path, (database) => fileSchemaOf(database).version);
8644
+ } catch {
8645
+ return null;
8646
+ }
8647
+ }, "fileSchema");
8648
+ var storeSummary = /* @__PURE__ */ __name(async (env, { deep = false, command, version } = {}) => {
8351
8649
  const path = storePath(env);
8352
- if (!existsSync9(path))
8650
+ if (!existsSync10(path))
8353
8651
  return { path, exists: false };
8354
8652
  const checked = await storeHealth(path, { deep });
8653
+ const recorded = deep ? recordDeepCheck(path, checked, {
8654
+ cli: command ?? "unknown",
8655
+ ...version ? { version } : {},
8656
+ schema: await fileSchema(path)
8657
+ }) : null;
8658
+ const mark = readDamageMark(path);
8659
+ const lastKnownGood = readHealthMark(path)?.last_ok_at ?? null;
8355
8660
  const health = {
8356
8661
  checked: checked.checked,
8357
8662
  covers: deep ? "every page and every search index" : QUICK_HEALTH_CHECKS,
@@ -8359,20 +8664,27 @@ var storeSummary = /* @__PURE__ */ __name(async (env, { deep = false, command }
8359
8664
  ms: checked.ms,
8360
8665
  ...checked.problems ? { problems: checked.problems } : {},
8361
8666
  ...checked.damagedTables?.length ? { damagedTables: checked.damagedTables } : {},
8667
+ ...checked.invalidJson?.length ? { invalidJson: checked.invalidJson } : {},
8362
8668
  ...checked.searchIndexes?.some((index) => !index.ok) ? { damagedSearchIndexes: checked.searchIndexes.filter((index) => !index.ok).map((index) => index.name) } : {}
8363
8669
  };
8364
- const damage = command ? explainDamage(checked, command) : null;
8365
- const healthOf = { health, ...damage ? { damage } : {} };
8670
+ const damage = command ? explainDamage(checked, command, mark) : null;
8671
+ const healthOf = {
8672
+ health,
8673
+ lastKnownGood,
8674
+ ...mark ? { damageMark: withoutInode(mark) } : {},
8675
+ ...recorded?.cleared ? { damageMarkCleared: withoutInode(recorded.cleared) } : {},
8676
+ ...damage ? { damage } : {}
8677
+ };
8366
8678
  try {
8367
8679
  return await reading(path, (database) => {
8368
- const { version, writable } = schemaOf(database);
8680
+ const { version: version2, writable } = schemaOf(database);
8369
8681
  return {
8370
8682
  path,
8371
8683
  exists: true,
8372
- schema: version,
8684
+ schema: version2,
8373
8685
  speaks: SPEAKS,
8374
8686
  writable,
8375
- ...version > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {},
8687
+ ...version2 > 0 ? { chats: count2(database, "chats"), messages: count2(database, "messages") } : {},
8376
8688
  ...healthOf
8377
8689
  };
8378
8690
  });
@@ -8405,7 +8717,7 @@ var repairCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("
8405
8717
  const { renderer, format } = outputFor(this);
8406
8718
  const { dryRun: dryRun2 } = this.opts();
8407
8719
  const path = storePath(environmentOf(this).env ?? process.env);
8408
- if (!existsSync9(path)) {
8720
+ if (!existsSync10(path)) {
8409
8721
  result(this, { path, exists: false });
8410
8722
  return;
8411
8723
  }
@@ -8445,7 +8757,7 @@ var notesOf = /* @__PURE__ */ __name((report, command) => {
8445
8757
  }, "notesOf");
8446
8758
  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) {
8447
8759
  const path = storePath(environmentOf(this).env ?? process.env);
8448
- if (!existsSync9(path))
8760
+ if (!existsSync10(path))
8449
8761
  throw new CliError("not_found", `no store at ${path}`);
8450
8762
  const deleted = await reading(path, (database) => deleteCopy(database, name));
8451
8763
  result(this, { path, deleted });
@@ -8453,7 +8765,7 @@ var copiesCommand = /* @__PURE__ */ __name(() => new Command("copies").descripti
8453
8765
  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() {
8454
8766
  const { renderer } = outputFor(this);
8455
8767
  const path = storePath(environmentOf(this).env ?? process.env);
8456
- if (!existsSync9(path)) {
8768
+ if (!existsSync10(path)) {
8457
8769
  result(this, { path, exists: false, ok: true });
8458
8770
  return;
8459
8771
  }
@@ -8516,7 +8828,7 @@ var inspect = /* @__PURE__ */ __name((path) => reading(path, (database) => {
8516
8828
  ...schema.version > 0 ? [["attachment_words", indexIntegrity(database, "attachment_words", 0)]] : []
8517
8829
  ]);
8518
8830
  const size = bytesOf2(path) + bytesOf2(`${path}-wal`);
8519
- const { bavail, bsize } = statfsSync2(dirname2(path));
8831
+ const { bavail, bsize } = statfsSync2(dirname3(path));
8520
8832
  const free = Number(bavail) * Number(bsize);
8521
8833
  const behind = schema.version > 0 ? chatsBehind(database) : [];
8522
8834
  const vectorIndexes = schema.version >= 34 ? vectorIndexCounts(database) : [];
@@ -8604,7 +8916,7 @@ var chatsBehind = /* @__PURE__ */ __name((database) => database.prepare(`SELECT
8604
8916
  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() {
8605
8917
  const { renderer } = outputFor(this);
8606
8918
  const path = storePath(environmentOf(this).env ?? process.env);
8607
- if (!existsSync9(path)) {
8919
+ if (!existsSync10(path)) {
8608
8920
  result(this, { path, exists: false });
8609
8921
  renderer.note(`no store yet \u2014 the first \`${messenger.app.command}\` command that reads a chat creates it`);
8610
8922
  return;
@@ -8668,7 +8980,7 @@ var buildNoteIndex = /* @__PURE__ */ __name((database, note, { reset = false } =
8668
8980
  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() {
8669
8981
  const { renderer } = outputFor(this);
8670
8982
  const path = storePath(environmentOf(this).env ?? process.env);
8671
- if (!existsSync9(path)) {
8983
+ if (!existsSync10(path)) {
8672
8984
  result(this, { path, exists: false });
8673
8985
  return;
8674
8986
  }
@@ -8710,9 +9022,9 @@ var backupCommand = /* @__PURE__ */ __name(() => destroysNothing(annotate(new Co
8710
9022
  const { encrypt } = this.opts();
8711
9023
  const path = storePath(environmentOf(this).env ?? process.env);
8712
9024
  const target = resolve(file2);
8713
- if (!existsSync9(path))
9025
+ if (!existsSync10(path))
8714
9026
  throw new CliError("not_found", `no store at ${path} to back up`);
8715
- if (existsSync9(target))
9027
+ if (existsSync10(target))
8716
9028
  throw new CliError("validation_error", `${target} exists \u2014 a backup never overwrites a file`);
8717
9029
  const password = encrypt ? await passwordOf(this, { twice: true }) : void 0;
8718
9030
  const copyAt = password === void 0 ? target : `${path}.backup-${process.pid}`;
@@ -8745,11 +9057,11 @@ var decryptCommand = /* @__PURE__ */ __name(() => annotate(new Command("decrypt"
8745
9057
  const { output } = this.opts();
8746
9058
  const from = resolve(file2);
8747
9059
  const to = resolve(output);
8748
- if (!existsSync9(from))
9060
+ if (!existsSync10(from))
8749
9061
  throw new CliError("not_found", `no file at ${from}`);
8750
9062
  if (!isSealed(from))
8751
9063
  throw new CliError("validation_error", `${from} was not written with --encrypt`);
8752
- if (existsSync9(to))
9064
+ if (existsSync10(to))
8753
9065
  throw new CliError("validation_error", `${to} exists \u2014 never overwritten`);
8754
9066
  await unsealFile(from, to, await passwordOf(this, { twice: false }));
8755
9067
  result(this, { path: to, from, bytes: bytesOf2(to) });
@@ -8757,13 +9069,13 @@ var decryptCommand = /* @__PURE__ */ __name(() => annotate(new Command("decrypt"
8757
9069
  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) {
8758
9070
  const path = storePath(environmentOf(this).env ?? process.env);
8759
9071
  const given = resolve(file2);
8760
- if (!existsSync9(given))
9072
+ if (!existsSync10(given))
8761
9073
  throw new CliError("not_found", `no file at ${given}`);
8762
9074
  refuseWhileServing(this, messenger);
8763
9075
  if (!isSealed(given))
8764
9076
  return restoreFrom(this, messenger, given, given);
8765
9077
  const opened = `${path}.unsealing-${process.pid}`;
8766
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
9078
+ mkdirSync(dirname3(path), { recursive: true, mode: 448 });
8767
9079
  try {
8768
9080
  await unsealFile(given, opened, await passwordOf(this, { twice: false }));
8769
9081
  await restoreFrom(this, messenger, opened, given);
@@ -8774,26 +9086,26 @@ var restoreCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command(
8774
9086
  var restoreFrom = /* @__PURE__ */ __name(async (command, messenger, backup, given) => {
8775
9087
  const { renderer } = outputFor(command);
8776
9088
  const path = storePath(environmentOf(command).env ?? process.env);
8777
- if (existsSync9(path) && realpathSync2(backup) === realpathSync2(path)) {
9089
+ if (existsSync10(path) && realpathSync3(backup) === realpathSync3(path)) {
8778
9090
  throw new CliError("validation_error", `${backup} is the store itself`);
8779
9091
  }
8780
9092
  if (await isRollbackCopy(backup))
8781
9093
  return rollBackFrom(command, messenger, backup);
8782
9094
  const schema = await backupSchema(backup);
8783
9095
  const stamp = stampNow();
8784
- const kept = existsSync9(path) ? `${path}.before-restore-${stamp}` : null;
9096
+ const kept = existsSync10(path) ? `${path}.before-restore-${stamp}` : null;
8785
9097
  if (kept) {
8786
9098
  const waitMs = environmentOf(command).storeLockWaitMs;
8787
9099
  await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
8788
9100
  } else
8789
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
9101
+ mkdirSync(dirname3(path), { recursive: true, mode: 448 });
8790
9102
  const incoming = `${path}.restoring-${stamp}`;
8791
9103
  copyFileSync(backup, incoming, constants.COPYFILE_EXCL);
8792
9104
  chmodSync(incoming, 384);
8793
9105
  if (kept) {
8794
9106
  renameSync3(path, kept);
8795
9107
  for (const suffix of ["-wal", "-shm"])
8796
- if (existsSync9(`${path}${suffix}`))
9108
+ if (existsSync10(`${path}${suffix}`))
8797
9109
  renameSync3(`${path}${suffix}`, `${kept}${suffix}`);
8798
9110
  }
8799
9111
  renameSync3(incoming, path);
@@ -8815,7 +9127,7 @@ var isRollbackCopy = /* @__PURE__ */ __name(async (file2) => {
8815
9127
  var rollBackFrom = /* @__PURE__ */ __name(async (command, messenger, copy) => {
8816
9128
  const { renderer } = outputFor(command);
8817
9129
  const path = storePath(environmentOf(command).env ?? process.env);
8818
- if (!existsSync9(path))
9130
+ if (!existsSync10(path))
8819
9131
  throw new CliError("not_found", `no store at ${path} to roll back`);
8820
9132
  const waitMs = environmentOf(command).storeLockWaitMs;
8821
9133
  await quiesce(path, messenger, "restore", (message) => renderer.warn(message), waitMs);
@@ -8865,7 +9177,7 @@ var backupSchema = /* @__PURE__ */ __name(async (backup) => {
8865
9177
  var STORE_LOCK_WAIT_MS = 1e3;
8866
9178
  var quiesce = /* @__PURE__ */ __name(async (path, messenger, then, warn, waitMs = STORE_LOCK_WAIT_MS) => {
8867
9179
  const { command } = messenger.app;
8868
- const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync9(file2)).map((file2) => realpathSync2(file2));
9180
+ const files = [path, `${path}-wal`, `${path}-shm`].filter((file2) => existsSync10(file2)).map((file2) => realpathSync3(file2));
8869
9181
  const holders = holdersOf(files);
8870
9182
  if (holders === void 0) {
8871
9183
  warn(`this system cannot say which processes have the store open \u2014 restart every running serve and mcp after this`);
@@ -8891,7 +9203,7 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8891
9203
  const { command } = messenger.app;
8892
9204
  const env = environmentOf(this).env ?? process.env;
8893
9205
  const path = storePath(env);
8894
- if (!existsSync9(path)) {
9206
+ if (!existsSync10(path)) {
8895
9207
  result(this, { path, exists: false, reset: false });
8896
9208
  renderer.note(`no store at ${path} \u2014 nothing to reset; the first \`${command}\` command that reads a chat creates it`);
8897
9209
  return;
@@ -8936,8 +9248,8 @@ var resetCommand = /* @__PURE__ */ __name((messenger) => annotate(new Command("r
8936
9248
  }), "resetCommand");
8937
9249
  var STORE_PARTS2 = ["", "-wal", "-shm"];
8938
9250
  var resetPreview = /* @__PURE__ */ __name(async (path, messenger, env, keep) => {
8939
- const files = STORE_PARTS2.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync9(file2));
8940
- const holders = holdersOf(files.map((file2) => realpathSync2(file2)));
9251
+ const files = STORE_PARTS2.map((suffix) => `${path}${suffix}`).filter((file2) => existsSync10(file2));
9252
+ const holders = holdersOf(files.map((file2) => realpathSync3(file2)));
8941
9253
  const serving = servingProfiles(messenger.app, env).length > 0;
8942
9254
  const read = await readingOnly(path, (database) => ({
8943
9255
  schema: schemaOf(database).version,
@@ -8983,11 +9295,9 @@ export {
8983
9295
  readRepliesState,
8984
9296
  writeRepliesState,
8985
9297
  paused,
9298
+ safeLiquid,
8986
9299
  DRY_RUN_DAYS,
8987
9300
  dryRun,
8988
- endpointKeyName,
8989
- embeddingKeys,
8990
- modelGateway,
8991
9301
  replyConsentPathFor,
8992
9302
  readReplyConsent,
8993
9303
  writeReplyConsent,