@wirecat/drive-cli 0.71.0 → 0.72.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 (258) hide show
  1. package/README.md +150 -71
  2. package/contracts/wirecat.json +77 -8
  3. package/dist/bin/drive.js +2 -2
  4. package/dist/bundle/agent-23OB2NZP.js +46 -0
  5. package/dist/bundle/{all-profiles-3QJG2NAN.js → all-profiles-GXGDVNQJ.js} +67 -25
  6. package/dist/bundle/{anthropic-PSWTEU6G.js → anthropic-H5C4GQHC.js} +9 -9
  7. package/dist/bundle/{app-server-PVTA6ABR.js → app-server-EQ3UK4C7.js} +97 -79
  8. package/dist/bundle/{bun-LU5LP3JI.js → bun-DTJVSRY3.js} +2 -2
  9. package/dist/bundle/{bun-sqlite-PYMKLBRU.js → bun-sqlite-JIFY7MAE.js} +9 -9
  10. package/dist/bundle/chunk-2Q325BBD.js +353 -0
  11. package/dist/bundle/chunk-35FIJGTT.js +52 -0
  12. package/dist/bundle/{chunk-RWDKMU74.js → chunk-3FRQ6V4T.js} +3 -3
  13. package/dist/bundle/chunk-47L262VI.js +340 -0
  14. package/dist/bundle/chunk-4HP6KGBI.js +32 -0
  15. package/dist/bundle/{chunk-YVI5SQPY.js → chunk-4HPXWYTE.js} +1 -1
  16. package/dist/bundle/{chunk-QETR5HIZ.js → chunk-4IUNYYYL.js} +4385 -2684
  17. package/dist/bundle/{chunk-I4RWW3UD.js → chunk-4JS32SRX.js} +20 -5
  18. package/dist/bundle/chunk-4ZAQMDLD.js +1308 -0
  19. package/dist/bundle/chunk-4ZTB7LS3.js +87 -0
  20. package/dist/bundle/{chunk-3N2OFXB5.js → chunk-55FH6IEL.js} +5 -5
  21. package/dist/bundle/{chunk-6TNNT2MQ.js → chunk-5BNMWSU2.js} +483 -176
  22. package/dist/bundle/{chunk-6XFIITOG.js → chunk-5H747A76.js} +5532 -3265
  23. package/dist/bundle/{chunk-MNLL5YLM.js → chunk-5KWCO56H.js} +2 -2
  24. package/dist/bundle/{chunk-GZ2D4KXG.js → chunk-5U3NCE5R.js} +35 -12
  25. package/dist/bundle/{chunk-CJLVYIOP.js → chunk-6CCO3JCM.js} +30 -21
  26. package/dist/bundle/{chunk-26DHFMGZ.js → chunk-6ZW2ZJYC.js} +2 -2
  27. package/dist/bundle/{chunk-COJSWDNU.js → chunk-75DAHQOV.js} +3 -3
  28. package/dist/bundle/{chunk-Q7DOMFJ4.js → chunk-77OBW43F.js} +6 -6
  29. package/dist/bundle/{chunk-FCS26CYQ.js → chunk-7EFM6AW3.js} +4 -4
  30. package/dist/bundle/{chunk-XMMFBPGC.js → chunk-A3S7QM5L.js} +3 -3
  31. package/dist/bundle/{chunk-ASMMG72J.js → chunk-AA4LKC6W.js} +244 -565
  32. package/dist/bundle/chunk-ASTKHB6B.js +3233 -0
  33. package/dist/bundle/{chunk-LXKYKRHD.js → chunk-BM6V7456.js} +8 -227
  34. package/dist/bundle/chunk-BO6EDBYJ.js +50 -0
  35. package/dist/bundle/{chunk-YPFWNVHV.js → chunk-BPA3R4KN.js} +2 -100
  36. package/dist/bundle/chunk-CIFE4KPX.js +2159 -0
  37. package/dist/bundle/chunk-CKB4XZZJ.js +730 -0
  38. package/dist/bundle/{chunk-RJOQH5YY.js → chunk-COJTCEZP.js} +111 -859
  39. package/dist/bundle/{chunk-FJH7DJWK.js → chunk-CWPYDT73.js} +6 -6
  40. package/dist/bundle/{chunk-BKSQBBYG.js → chunk-D4JNCXS7.js} +9 -9
  41. package/dist/bundle/chunk-DCPWZIOV.js +696 -0
  42. package/dist/bundle/{chunk-PRW6SYA3.js → chunk-DHMNCOQI.js} +313 -257
  43. package/dist/bundle/chunk-DOQMH4DC.js +280 -0
  44. package/dist/bundle/chunk-DQSOYH6N.js +20 -0
  45. package/dist/bundle/{chunk-YJIGGUPI.js → chunk-DWRUOLBF.js} +4 -4
  46. package/dist/bundle/{chunk-6W763DZN.js → chunk-E3VWZC3K.js} +14 -13
  47. package/dist/bundle/chunk-ECYOTDJM.js +14 -0
  48. package/dist/bundle/{chunk-KGYVHPGE.js → chunk-EVG3AA5M.js} +2 -2
  49. package/dist/bundle/chunk-F4BX7TH2.js +15 -0
  50. package/dist/bundle/{chunk-Y2NWGNUB.js → chunk-FBEZSA76.js} +5 -5
  51. package/dist/bundle/{chunk-2BVVU7GG.js → chunk-FBQJN74J.js} +1 -1
  52. package/dist/bundle/{chunk-Z56QFOBR.js → chunk-FIZOPJYY.js} +1 -1
  53. package/dist/bundle/chunk-FNAYSZWK.js +783 -0
  54. package/dist/bundle/{chunk-GPQ44Y2R.js → chunk-FRCJHGZM.js} +2 -2
  55. package/dist/bundle/{chunk-35SCQ4VI.js → chunk-FTG5QBSD.js} +41 -33
  56. package/dist/bundle/{chunk-KYKW2W6X.js → chunk-FUDUXIVG.js} +1 -1
  57. package/dist/bundle/{chunk-NYECVHFH.js → chunk-G4NHRFS7.js} +755 -0
  58. package/dist/bundle/{chunk-FT3LN3HP.js → chunk-GIEZYBRC.js} +1 -1
  59. package/dist/bundle/chunk-GTPPUBYU.js +1876 -0
  60. package/dist/bundle/chunk-GU6ICH53.js +108 -0
  61. package/dist/bundle/{chunk-ACUAV6VX.js → chunk-GUMKKRE6.js} +107 -71
  62. package/dist/bundle/{chunk-KGERXYTV.js → chunk-GWCDOYSC.js} +1 -1
  63. package/dist/bundle/{chunk-OJSBWP3F.js → chunk-GXGSC622.js} +69 -7
  64. package/dist/bundle/chunk-HAGXTGJC.js +188 -0
  65. package/dist/bundle/{chunk-XF4EXO2C.js → chunk-IMAWQC5K.js} +6 -6
  66. package/dist/bundle/{chunk-HKY7X6NY.js → chunk-IVGVVSPW.js} +4 -4
  67. package/dist/bundle/{chunk-P7CUM5IB.js → chunk-J4NUHSM7.js} +1 -1
  68. package/dist/bundle/{chunk-MIA7P6FZ.js → chunk-K652FYCO.js} +6 -6
  69. package/dist/bundle/chunk-K6ZWNTXY.js +561 -0
  70. package/dist/bundle/{chunk-COOOO5B3.js → chunk-KF3ZBQJV.js} +4 -4
  71. package/dist/bundle/chunk-KFZCHJRT.js +80 -0
  72. package/dist/bundle/chunk-KLPFDFLI.js +221 -0
  73. package/dist/bundle/{chunk-EOEU3AZN.js → chunk-KP2XMCNT.js} +13 -13
  74. package/dist/bundle/{chunk-FP54WSIR.js → chunk-KWDZ3KVH.js} +4 -4
  75. package/dist/bundle/{chunk-QNRRK3CN.js → chunk-KX4C32WD.js} +2 -2
  76. package/dist/bundle/chunk-L7P3LUDQ.js +286 -0
  77. package/dist/bundle/{chunk-2LHAVY4U.js → chunk-M2ZWYVWO.js} +1 -1
  78. package/dist/bundle/chunk-MEYYH47C.js +25 -0
  79. package/dist/bundle/{chunk-3EBBLKIT.js → chunk-ML2QIWX2.js} +4 -4
  80. package/dist/bundle/{chunk-ZM63SUHG.js → chunk-MUFF2YTH.js} +2 -2
  81. package/dist/bundle/{chunk-2PUNKUYJ.js → chunk-N24YSLED.js} +9150 -9869
  82. package/dist/bundle/chunk-N4GTCPML.js +7 -0
  83. package/dist/bundle/{chunk-B5KSXHJ7.js → chunk-NBMGDRP4.js} +1 -1
  84. package/dist/bundle/chunk-NMQRSEZM.js +37 -0
  85. package/dist/bundle/{chunk-JDV7HNNQ.js → chunk-NNGA4QDR.js} +13 -26
  86. package/dist/bundle/{chunk-5DPV7X27.js → chunk-NTZWY5R3.js} +321 -0
  87. package/dist/bundle/chunk-O7CZZ36M.js +80 -0
  88. package/dist/bundle/{chunk-ICDCAQ6K.js → chunk-OAONP6KI.js} +13 -9
  89. package/dist/bundle/{chunk-WVDCCYS3.js → chunk-OESP4PHB.js} +17 -17
  90. package/dist/bundle/chunk-OHR6IZNH.js +116 -0
  91. package/dist/bundle/{chunk-4QNW4NK6.js → chunk-OLCU7Q2B.js} +1 -1
  92. package/dist/bundle/{chunk-SDKQNOL5.js → chunk-OLDQLEPA.js} +6 -6
  93. package/dist/bundle/{chunk-ZCR3IRZ2.js → chunk-OPIPG6AP.js} +16 -9
  94. package/dist/bundle/{chunk-5D4AEUVA.js → chunk-PL5P7UKW.js} +434 -1
  95. package/dist/bundle/chunk-PRYMT3OG.js +30 -0
  96. package/dist/bundle/chunk-QDUIVMEW.js +36 -0
  97. package/dist/bundle/{chunk-ZZ32DXTH.js → chunk-QKBPCX7Y.js} +1 -1
  98. package/dist/bundle/{chunk-QXC6IEH6.js → chunk-QSLOACDT.js} +201 -423
  99. package/dist/bundle/{chunk-7PDHGZN4.js → chunk-QUZFDU4K.js} +4 -4
  100. package/dist/bundle/{chunk-3UGYFXH6.js → chunk-R32DHS6J.js} +187 -379
  101. package/dist/bundle/{chunk-6SJOTNHF.js → chunk-R57QUYBG.js} +6 -28
  102. package/dist/bundle/{chunk-UTO2GO4P.js → chunk-R64OSDOD.js} +45 -66
  103. package/dist/bundle/{chunk-GBKNJWOZ.js → chunk-RSPBVKOC.js} +8 -8
  104. package/dist/bundle/{chunk-HL52XXZX.js → chunk-SPNPJ3FZ.js} +3 -4
  105. package/dist/bundle/chunk-SQHDSIFL.js +388 -0
  106. package/dist/bundle/{chunk-YPNWIB6H.js → chunk-ST35FIUG.js} +3 -3
  107. package/dist/bundle/{chunk-37MAA6F2.js → chunk-STUPCKAA.js} +11 -2221
  108. package/dist/bundle/chunk-SZ7XJZGH.js +2231 -0
  109. package/dist/bundle/chunk-TRYYWV7J.js +291 -0
  110. package/dist/bundle/{chunk-X4TIMMKJ.js → chunk-TTPWKTVR.js} +1 -1
  111. package/dist/bundle/{chunk-TAFHYHKA.js → chunk-U7VEJ3CW.js} +45 -27
  112. package/dist/bundle/{chunk-6Y2BYFXQ.js → chunk-UC7JLE6J.js} +0 -7
  113. package/dist/bundle/{chunk-4HWJOU7N.js → chunk-UIQ35CA5.js} +1 -1
  114. package/dist/bundle/{chunk-SAKO3P4H.js → chunk-UJY26HW4.js} +1 -1
  115. package/dist/bundle/{chunk-D5TGYUVU.js → chunk-UWG3PRY7.js} +9 -60
  116. package/dist/bundle/{chunk-JZHBZOJR.js → chunk-VAR3MJU6.js} +3 -3
  117. package/dist/bundle/{chunk-GOWXXYEF.js → chunk-VPQSI5IU.js} +4 -4
  118. package/dist/bundle/{chunk-QFR2PNJN.js → chunk-VQPT3Y7W.js} +12 -12
  119. package/dist/bundle/{chunk-Z3KUSRCF.js → chunk-WMG3H2VK.js} +2 -2
  120. package/dist/bundle/{chunk-4PA4DHYV.js → chunk-X5BGAZC5.js} +6 -6
  121. package/dist/bundle/{chunk-2UUWXPOB.js → chunk-XC6TRWLZ.js} +3 -3
  122. package/dist/bundle/{chunk-OF422U5D.js → chunk-XQZEMRCU.js} +402 -402
  123. package/dist/bundle/{chunk-72C4YOCH.js → chunk-XZ7MO6EU.js} +7 -7
  124. package/dist/bundle/{chunk-SERXSCN3.js → chunk-YAIOEPKU.js} +337 -390
  125. package/dist/bundle/chunk-YHWFF6DN.js +39 -0
  126. package/dist/bundle/{chunk-RESDD3Q4.js → chunk-YWOLQEDV.js} +16 -3
  127. package/dist/bundle/{chunk-YMJ6IDGT.js → chunk-ZFDSJ5YJ.js} +38 -8
  128. package/dist/bundle/{chunk-HMS6EEQL.js → chunk-ZFUZEFU6.js} +3 -3
  129. package/dist/bundle/{chunk-TAUBRNC5.js → chunk-ZJKXSMXK.js} +72 -59
  130. package/dist/bundle/{chunk-22QQUKWA.js → chunk-ZKWT6HXT.js} +1 -1
  131. package/dist/bundle/chunk-ZPUY3COZ.js +250 -0
  132. package/dist/bundle/{cli-556DERZL.js → cli-2P5FW2RL.js} +201 -98
  133. package/dist/bundle/command-contract-BMQT2G5X.js +45 -0
  134. package/dist/bundle/{command-server-entry-AYLGNZWD.js → command-server-entry-KP2UDGLA.js} +36 -34
  135. package/dist/bundle/{decode-QU24MWMN.js → decode-K2JZ5D6V.js} +10 -10
  136. package/dist/bundle/{dispatch-4KODNOXV.js → dispatch-KOQZA74A.js} +10 -10
  137. package/dist/bundle/dist-PAKDDIBT.js +191 -0
  138. package/dist/bundle/drive.js +11 -11
  139. package/dist/bundle/{echarts-BXX4OQWC.js → echarts-URO3QGCG.js} +2 -2
  140. package/dist/bundle/{embed-KG27KG3D.js → embed-JLIPWTNN.js} +10 -10
  141. package/dist/bundle/{embedder-IPAVUQUV.js → embedder-LUTDO3HS.js} +15 -15
  142. package/dist/bundle/entry-AVF6LMG7.js +25 -0
  143. package/dist/bundle/{failure-ESL7ETL4.js → failure-GJMQLM7O.js} +4 -4
  144. package/dist/bundle/first-run-VYTIEUDA.js +31 -0
  145. package/dist/bundle/first-screen-QVZPF7KL.js +45 -0
  146. package/dist/bundle/google-VX7IPACN.js +46 -0
  147. package/dist/bundle/{google-api-VCDBSNOW.js → google-api-RFXKRLL4.js} +88 -73
  148. package/dist/bundle/grants-4XWJFVD6.js +133 -0
  149. package/dist/bundle/hast-util-from-html-X2DCPS3T.js +10531 -0
  150. package/dist/bundle/hast-util-to-html-VP6XLPKJ.js +998 -0
  151. package/dist/bundle/hast-util-to-mdast-IZ5PRX72.js +2272 -0
  152. package/dist/bundle/{identity-LOWMVGZY.js → identity-FXPB5EMT.js} +7 -6
  153. package/dist/bundle/{instructions-2VECIDXF.js → instructions-IROIUVZI.js} +1 -1
  154. package/dist/bundle/{login-7GBONT7V.js → login-WIY5VQU7.js} +96 -81
  155. package/dist/bundle/{mcp-O6ACR2DX.js → mcp-NJIOKW3E.js} +2 -2
  156. package/dist/bundle/{mdast-util-from-markdown-FXEPSNER.js → mdast-util-from-markdown-HEZF7KJ4.js} +137 -195
  157. package/dist/bundle/mdast-util-gfm-AQW6R6MG.js +925 -0
  158. package/dist/bundle/mdast-util-to-hast-DF2QVIRV.js +879 -0
  159. package/dist/bundle/mdast-util-to-markdown-XYLXB3Z3.js +18 -0
  160. package/dist/bundle/meeting-combined-JUNV35GM.js +28 -0
  161. package/dist/bundle/meeting-model-XY4UNWWK.js +29 -0
  162. package/dist/bundle/{meeting-semantic-G7PFOKU7.js → meeting-semantic-62QNQMOM.js} +10 -10
  163. package/dist/bundle/{micromark-extension-gfm-GRL24TU6.js → micromark-extension-gfm-OE2GBORZ.js} +11 -78
  164. package/dist/bundle/{node-MPEQSFI3.js → node-IACCI2CW.js} +2 -2
  165. package/dist/bundle/{node-sqlite-OLQMAYB4.js → node-sqlite-WYIRC7C7.js} +10 -10
  166. package/dist/bundle/notes-search-DEDUJKSN.js +70 -0
  167. package/dist/bundle/oauth-HXBXF4VI.js +22 -0
  168. package/dist/bundle/{open-OXTE672W.js → open-H32B6BCT.js} +8 -8
  169. package/dist/bundle/{openai-EB3TPIZY.js → openai-VHMPJJUG.js} +22 -21
  170. package/dist/bundle/{process-F6TKXWWA.js → process-RNHPF5OK.js} +1 -1
  171. package/dist/bundle/{program-4IFDZ7FM.js → program-GYMJ3DDH.js} +275 -1148
  172. package/dist/bundle/{prompt-F5RRHPN2.js → prompt-TOG2CRCE.js} +8 -8
  173. package/dist/bundle/{reasons-UORHJDHK.js → reasons-TLFQ45YX.js} +6 -5
  174. package/dist/bundle/{recognize-DAVNZND3.js → recognize-GYGY45EY.js} +7 -7
  175. package/dist/bundle/remote-6XN2QLI5.js +35 -0
  176. package/dist/bundle/{rerank-CND2GVLZ.js → rerank-HJO3O4TW.js} +11 -11
  177. package/dist/bundle/{serve-ZHSPUIGX.js → serve-XPCNLHCR.js} +19 -19
  178. package/dist/bundle/server-UBJZ66XE.js +97 -0
  179. package/dist/bundle/{server-YMAK4LHC.js → server-WPT3NC5B.js} +89 -70
  180. package/dist/bundle/{services-ZILSFJ6E.js → services-253KKKVU.js} +109 -89
  181. package/dist/bundle/{sqlite-runtime-S5VPMZQH.js → sqlite-runtime-EZASGJXW.js} +9 -9
  182. package/dist/bundle/{start-CR6X25RT.js → start-UHI35JFL.js} +7 -7
  183. package/dist/bundle/{state-YFPHVIIJ.js → state-KJTSPFGK.js} +9 -9
  184. package/dist/bundle/{store-UODRT6X4.js → store-62J2H2A3.js} +36 -25
  185. package/dist/bundle/{store-CL4ZJZRI.js → store-G5B7T7M7.js} +38 -23
  186. package/dist/bundle/store-maintenance-command-C6T4YLVF.js +85 -0
  187. package/dist/bundle/surface-3OT64BHS.js +83 -0
  188. package/dist/bundle/tokens-EHYO6D2X.js +133 -0
  189. package/dist/commands/documents.d.ts.map +1 -1
  190. package/dist/commands/documents.js +11 -1
  191. package/dist/commands/documents.js.map +1 -1
  192. package/dist/commands/remote.d.ts.map +1 -1
  193. package/dist/commands/remote.js +8 -22
  194. package/dist/commands/remote.js.map +1 -1
  195. package/dist/commands/sync.d.ts.map +1 -1
  196. package/dist/commands/sync.js +14 -4
  197. package/dist/commands/sync.js.map +1 -1
  198. package/dist/config.d.ts +5 -0
  199. package/dist/config.d.ts.map +1 -1
  200. package/dist/config.js +5 -0
  201. package/dist/config.js.map +1 -1
  202. package/dist/first-screen.d.ts.map +1 -1
  203. package/dist/first-screen.js +2 -1
  204. package/dist/first-screen.js.map +1 -1
  205. package/dist/generated/manifest.d.ts +2 -1
  206. package/dist/generated/manifest.d.ts.map +1 -1
  207. package/dist/generated/manifest.js +782 -0
  208. package/dist/generated/manifest.js.map +1 -1
  209. package/dist/generated/types.d.ts +262 -58
  210. package/dist/generated/types.d.ts.map +1 -1
  211. package/dist/google.d.ts.map +1 -1
  212. package/dist/google.js +5 -5
  213. package/dist/google.js.map +1 -1
  214. package/dist/model.d.ts +5 -2
  215. package/dist/model.d.ts.map +1 -1
  216. package/dist/model.js.map +1 -1
  217. package/dist/policy-keys.js +1 -1
  218. package/dist/policy-keys.js.map +1 -1
  219. package/dist/program.d.ts.map +1 -1
  220. package/dist/program.js +9 -4
  221. package/dist/program.js.map +1 -1
  222. package/dist/state.d.ts.map +1 -1
  223. package/dist/state.js +6 -1
  224. package/dist/state.js.map +1 -1
  225. package/dist/store.d.ts.map +1 -1
  226. package/dist/store.js +2 -7
  227. package/dist/store.js.map +1 -1
  228. package/dist/supported.d.ts +2 -2
  229. package/dist/supported.d.ts.map +1 -1
  230. package/dist/supported.js +2 -3
  231. package/dist/supported.js.map +1 -1
  232. package/dist/sync.d.ts +2 -1
  233. package/dist/sync.d.ts.map +1 -1
  234. package/dist/sync.js +5 -2
  235. package/dist/sync.js.map +1 -1
  236. package/dist/version.d.ts +1 -1
  237. package/dist/version.js +1 -1
  238. package/package.json +3 -3
  239. package/scenarios/find-decision.md +1 -1
  240. package/skills/drive-cli/SKILL.md +4 -2
  241. package/dist/bundle/chunk-J5Q5FS2N.js +0 -593
  242. package/dist/bundle/chunk-L46C6HQ7.js +0 -729
  243. package/dist/bundle/chunk-UDMNY63V.js +0 -899
  244. package/dist/bundle/chunk-VKE77B3F.js +0 -2
  245. package/dist/bundle/command-contract-VRTOAV6W.js +0 -43
  246. package/dist/bundle/entry-MVXQETWS.js +0 -25
  247. package/dist/bundle/first-run-4UVLW2WR.js +0 -31
  248. package/dist/bundle/first-screen-JAKAIINI.js +0 -41
  249. package/dist/bundle/google-22NXXJX5.js +0 -45
  250. package/dist/bundle/grants-MQMTVCRQ.js +0 -118
  251. package/dist/bundle/mdast-util-gfm-SZM5GBDF.js +0 -2103
  252. package/dist/bundle/meeting-combined-LVP4AZKA.js +0 -27
  253. package/dist/bundle/meeting-model-RAY5XDXZ.js +0 -29
  254. package/dist/bundle/oauth-SGH2I2BY.js +0 -22
  255. package/dist/bundle/remote-D5EYYIAU.js +0 -35
  256. package/dist/bundle/server-DUVJWP3Q.js +0 -80
  257. package/dist/bundle/store-maintenance-command-DY5XIBWR.js +0 -72
  258. package/dist/bundle/tokens-AF7QOFOF.js +0 -118
@@ -0,0 +1,3233 @@
1
+ import { createRequire as __bundleRequire } from "node:module";
2
+ const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ operations
5
+ } from "./chunk-G4NHRFS7.js";
6
+ import {
7
+ DOC,
8
+ KEEP_VERSIONS_FOR_DAYS,
9
+ extractDocumentMemories,
10
+ guardedFileWrite,
11
+ mirrorId,
12
+ mirrorStatus,
13
+ remoteChanged,
14
+ syncMirrors,
15
+ watchMirrors
16
+ } from "./chunk-5BNMWSU2.js";
17
+ import {
18
+ honoursDryRun,
19
+ privateFiles
20
+ } from "./chunk-5H747A76.js";
21
+ import {
22
+ commandPathKey,
23
+ commandPermissions
24
+ } from "./chunk-U7VEJ3CW.js";
25
+ import {
26
+ ReaderLimit,
27
+ columnName,
28
+ mainPart,
29
+ readContainer,
30
+ readSpreadsheet,
31
+ relationships,
32
+ xmlPart
33
+ } from "./chunk-QSLOACDT.js";
34
+ import {
35
+ LIST_QUERY_GUIDE,
36
+ listQuery,
37
+ momentOf,
38
+ nativeField,
39
+ queryHelp,
40
+ queryTerms,
41
+ termField,
42
+ typedQuery,
43
+ withQuery
44
+ } from "./chunk-CKB4XZZJ.js";
45
+ import {
46
+ deflateSync
47
+ } from "./chunk-NTZWY5R3.js";
48
+ import {
49
+ AI_ENTRIES,
50
+ FETCH,
51
+ InvalidArgumentError,
52
+ LEVELS,
53
+ LOCAL_READ,
54
+ LOCAL_WRITE,
55
+ Option,
56
+ REMOTE_READ,
57
+ REMOTE_WRITE,
58
+ annotate,
59
+ answerEntity,
60
+ checkConfigText,
61
+ count,
62
+ environmentOf,
63
+ fromFile,
64
+ issueMessage,
65
+ itemOf,
66
+ jsonlRecords,
67
+ listOf,
68
+ parseDuration,
69
+ runBudgetOf,
70
+ settingsFor,
71
+ sharedCommand,
72
+ usableProfileName,
73
+ withSettingDefaults
74
+ } from "./chunk-YAIOEPKU.js";
75
+ import {
76
+ note
77
+ } from "./chunk-ZFUZEFU6.js";
78
+ import {
79
+ MAX_BUFFERED_INPUT,
80
+ bufferedInput
81
+ } from "./chunk-KX4C32WD.js";
82
+ import {
83
+ CATALOG_QUERY,
84
+ DOCUMENT_EVENTS,
85
+ IMPORTED_DOCUMENT_QUERY
86
+ } from "./chunk-4IUNYYYL.js";
87
+ import {
88
+ MAX_TEXT_CHARS
89
+ } from "./chunk-VAR3MJU6.js";
90
+ import {
91
+ FACT_STATUSES,
92
+ MEMORY_KINDS,
93
+ MEMORY_SCOPES,
94
+ MEMORY_STATUSES
95
+ } from "./chunk-FNAYSZWK.js";
96
+ import {
97
+ FACT_TYPES,
98
+ TRANSCRIPT_WORDS
99
+ } from "./chunk-DHMNCOQI.js";
100
+ import {
101
+ dateRange,
102
+ defineQuery,
103
+ parseLucene,
104
+ queryError,
105
+ queryFieldsOf,
106
+ timezoneOf,
107
+ validateQuery
108
+ } from "./chunk-XQZEMRCU.js";
109
+ import {
110
+ DRIVE_APP
111
+ } from "./chunk-MUFF2YTH.js";
112
+ import {
113
+ BASE_CONSTANTS,
114
+ baseConstantsSchema,
115
+ loadConstants,
116
+ resolvePaths,
117
+ saveConfigFile
118
+ } from "./chunk-6CCO3JCM.js";
119
+ import {
120
+ array,
121
+ boolean,
122
+ defineSteps,
123
+ integer,
124
+ isoTime,
125
+ literal,
126
+ looseObject,
127
+ maxLength,
128
+ maxValue,
129
+ minLength,
130
+ minValue,
131
+ nonEmpty,
132
+ null_,
133
+ nullable,
134
+ number,
135
+ object,
136
+ optional,
137
+ parse,
138
+ picklist,
139
+ pipe,
140
+ record,
141
+ regex,
142
+ safeParse,
143
+ stepOf,
144
+ strictObject,
145
+ string,
146
+ transform,
147
+ trim,
148
+ union,
149
+ unknown
150
+ } from "./chunk-GXGSC622.js";
151
+ import {
152
+ CliError,
153
+ isCliError
154
+ } from "./chunk-OLCU7Q2B.js";
155
+ import {
156
+ __name
157
+ } from "./chunk-ZVVMGPBJ.js";
158
+
159
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/oauth/client-file.js
160
+ import { readFileSync } from "node:fs";
161
+ var readClientFile = /* @__PURE__ */ __name((location, options = {}) => {
162
+ if (!options.shipped && typeof location === "string") {
163
+ const mode = privateFiles({ files: [location], dirs: [] }, options.platform);
164
+ if (mode.checked && !mode.ok)
165
+ throw new CliError("configuration_error", `the client file can be read by other users of this computer; run chmod 600 ${location} and try again`, { reason: "sign-in.client-file-open" });
166
+ }
167
+ try {
168
+ const { installed } = JSON.parse(readFileSync(location, "utf8"));
169
+ const { client_id: clientId, client_secret: clientSecret } = installed;
170
+ if (typeof clientId !== "string" || !clientId)
171
+ throw new TypeError("client_id");
172
+ if (clientSecret !== void 0 && typeof clientSecret !== "string")
173
+ throw new TypeError("client_secret");
174
+ return { clientId, ...clientSecret ? { clientSecret } : {} };
175
+ } catch {
176
+ throw options.invalid ?? new CliError("configuration_error", "could not read a Desktop app OAuth client JSON from the client file; its contents were not logged", { reason: "sign-in.client-file-invalid" });
177
+ }
178
+ }, "readClientFile");
179
+
180
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/constants/obscure.js
181
+ import { createDecipheriv } from "node:crypto";
182
+ var KEY = Buffer.from("d43012779aa2dded3e98092a3dbcf5d8980c564172f5ce0a5fd0574e5f740339", "hex");
183
+ var reveal = /* @__PURE__ */ __name((obscured) => {
184
+ const bytes = Buffer.from(obscured, "base64url");
185
+ const decipher = createDecipheriv("aes-256-ctr", KEY, bytes.subarray(0, 16));
186
+ return Buffer.concat([decipher.update(bytes.subarray(16)), decipher.final()]).toString("utf8");
187
+ }, "reveal");
188
+
189
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/constants/index.js
190
+ var CORE_CONSTANTS = new URL("../../constants.json", new URL("constants/index.js", import.meta.resolve("@wirecat/cli-core")).href);
191
+ var constantsSchema = object({
192
+ ...baseConstantsSchema.entries,
193
+ google: object({
194
+ app: object({
195
+ client_id: pipe(string(), nonEmpty(), transform(reveal)),
196
+ client_secret: optional(pipe(string(), transform(reveal)))
197
+ })
198
+ }),
199
+ microsoft: object({ app: object({ client_id: pipe(string(), nonEmpty()) }) })
200
+ });
201
+ var loaded = /* @__PURE__ */ new Map();
202
+ var constants = /* @__PURE__ */ __name((toolLayer, schema2) => {
203
+ const key = toolLayer?.href ?? "";
204
+ if (!loaded.has(key)) {
205
+ const layers = toolLayer ? [BASE_CONSTANTS, CORE_CONSTANTS, toolLayer] : [BASE_CONSTANTS, CORE_CONSTANTS];
206
+ loaded.set(key, loadConstants(layers, schema2 ?? constantsSchema));
207
+ }
208
+ return loaded.get(key);
209
+ }, "constants");
210
+ var oauthApp = /* @__PURE__ */ __name((options) => {
211
+ const { env, prefix, provider } = options;
212
+ const name = `${prefix}_${provider.toUpperCase()}_CLIENT`;
213
+ const clientSecret = env[`${name}_SECRET`];
214
+ const own = [
215
+ [options.clientId, "flag"],
216
+ [env[`${name}_ID`], "env"],
217
+ [options.configClientId, "config"]
218
+ ];
219
+ const [clientId, source] = own.find(([id]) => id) ?? [];
220
+ if (clientId && source)
221
+ return app({ clientId, ...clientSecret ? { clientSecret } : {} }, source);
222
+ if (clientSecret)
223
+ throw new CliError("configuration_error", `${name}_SECRET is set without a client id; set ${name}_ID too, or unset it to use WireCat's app`, { reason: "sign-in.secret-without-id" });
224
+ const wirecat = options.wirecat;
225
+ if (!wirecat?.client_id)
226
+ return void 0;
227
+ return app({ clientId: wirecat.client_id, ...wirecat.client_secret ? { clientSecret: wirecat.client_secret } : {} }, "constants");
228
+ }, "oauthApp");
229
+ var app = /* @__PURE__ */ __name((client, source) => ({ client: { ...client, source }, source }), "app");
230
+ var googleApp = /* @__PURE__ */ __name((options) => {
231
+ const { clientFile, platform } = options;
232
+ if (clientFile)
233
+ return app(readClientFile(clientFile, platform ? { platform } : {}), "flag");
234
+ const wirecat = (options.constants ?? constants()).google.app;
235
+ return oauthApp({ ...options, provider: "google", wirecat });
236
+ }, "googleApp");
237
+ var oauthClientReport = /* @__PURE__ */ __name((app2, reason) => app2?.source ? { client: app2.source === "constants" ? "wirecat" : "own", source: app2.source } : { client: null, source: null, ...reason ? { reason } : {} }, "oauthClientReport");
238
+
239
+ // dist/policy-keys.js
240
+ var permissionKeys = /* @__PURE__ */ __name((paths2) => {
241
+ const keys = /* @__PURE__ */ new Set([
242
+ "mcp.authority",
243
+ "mcp",
244
+ "sheets.create",
245
+ "sheets.rename",
246
+ "sheets.insert",
247
+ "sheets.format",
248
+ "sheets.update"
249
+ ]);
250
+ for (const path of paths2)
251
+ keys.add(path.join("."));
252
+ for (const operation of operations)
253
+ for (const key of methodPolicyKeys(operation.id))
254
+ keys.add(key);
255
+ return keys;
256
+ }, "permissionKeys");
257
+ var permissionNames = /* @__PURE__ */ __name((keys) => {
258
+ const names = /* @__PURE__ */ new Set();
259
+ for (const key of keys) {
260
+ const parts = key.split(".");
261
+ for (let end = 1; end <= parts.length; end++)
262
+ names.add(parts.slice(0, end).join("."));
263
+ }
264
+ return names;
265
+ }, "permissionNames");
266
+ var DEFAULT_LEVELS = {
267
+ "mcp.authority": "deny",
268
+ ...Object.fromEntries(operations.filter((op) => op.effect === "destructive").map((op) => [`api.${op.id}`, "ask"]))
269
+ };
270
+ var methodPolicyKeys = /* @__PURE__ */ __name((method, body) => {
271
+ const parts = method.split(".");
272
+ const verb = parts.at(-1);
273
+ const alias = method.startsWith("drive.files.") ? `files.${verb}` : method.startsWith("docs.documents.") ? `documents.${verb === "batchUpdate" ? "update" : verb}` : method.startsWith("sheets.spreadsheets.") ? `sheets.${method === "sheets.spreadsheets.get" ? "info" : method === "sheets.spreadsheets.values.get" ? "show" : verb === "append" ? "add" : verb}` : method === "driveactivity.activity.query" ? "activities.list" : method.startsWith("drive.") ? `${parts[1]}.${verb}` : void 0;
274
+ const keys = [`api.${method}`, ...alias ? [alias] : []];
275
+ if (method === "drive.replies.create" && body)
276
+ keys.push(body.action === "resolve" ? "comments.resolve" : body.action === "reopen" ? "comments.reopen" : "comments.reply");
277
+ if (method === "drive.replies.create" && body?.content !== void 0)
278
+ keys.push("comments.reply");
279
+ if (method === "sheets.spreadsheets.batchUpdate" && Array.isArray(body?.requests)) {
280
+ const object2 = /* @__PURE__ */ __name((value) => !!value && typeof value === "object" && !Array.isArray(value), "object");
281
+ for (const request of body.requests) {
282
+ if (!object2(request))
283
+ continue;
284
+ if (request.addSheet || request.duplicateSheet)
285
+ keys.push("sheets.create");
286
+ if (object2(request.updateSheetProperties)) {
287
+ const update = request.updateSheetProperties;
288
+ if (object2(update.properties) && update.properties.title !== void 0 || String(update.fields).split(",").some((field) => field.trim() === "title" || field.trim() === "*"))
289
+ keys.push("sheets.rename");
290
+ if (object2(update.properties) && update.properties.gridProperties)
291
+ keys.push("sheets.insert");
292
+ }
293
+ if (request.insertDimension || request.appendDimension || request.insertRange)
294
+ keys.push("sheets.insert");
295
+ if (request.repeatCell || request.updateCells || request.appendCells || request.updateBorders || request.addConditionalFormatRule || request.updateConditionalFormatRule || request.deleteConditionalFormatRule || request.addBanding || request.updateBanding || request.deleteBanding)
296
+ keys.push("sheets.format");
297
+ if (request.updateCells || request.appendCells || request.findReplace || request.pasteData || request.copyPaste || request.cutPaste || request.autoFill)
298
+ keys.push("sheets.update");
299
+ if (request.pasteData || request.copyPaste || request.cutPaste || request.autoFill)
300
+ keys.push("sheets.format");
301
+ if (object2(request.repeatCell) && (String(request.repeatCell.fields).split(",").some((field) => field.trim() === "*" || field.includes("userEnteredValue")) || object2(request.repeatCell.cell) && request.repeatCell.cell.userEnteredValue !== void 0))
302
+ keys.push("sheets.update");
303
+ }
304
+ }
305
+ return [...new Set(keys)];
306
+ }, "methodPolicyKeys");
307
+
308
+ // dist/config.js
309
+ import { readFileSync as readFileSync2 } from "node:fs";
310
+ import { join as join3 } from "node:path";
311
+
312
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/queries.js
313
+ var registry = /* @__PURE__ */ __name((entity, schema2, native, examples2) => ({
314
+ entity,
315
+ backend: "native",
316
+ fields: queryFieldsOf(schema2, { native, examples: examples2 }).map((field) => field.native ? { ...field, operators: ["term", "phrase"] } : field)
317
+ }), "registry");
318
+ var folderRow = strictObject({
319
+ id: string(),
320
+ /** The folder as `folders add` named it; left out for a folder chosen before its name was kept. */
321
+ name: optional(string()),
322
+ /** Where the provider says it is, when the CLI gives a `folderPath`: a Disk path. */
323
+ path: optional(string())
324
+ });
325
+ var mirrorRow = strictObject({ id: string(), path: string(), folder: string() });
326
+ var tagRow = strictObject({ tag: string() });
327
+ var linkRow = looseObject({
328
+ id: string(),
329
+ from: string(),
330
+ to: nullable(string()),
331
+ kind: string(),
332
+ role: nullable(string()),
333
+ confirmed: boolean(),
334
+ origin: picklist(["file", "owner", "suggested", "message"])
335
+ });
336
+ var IDENTITY_ROLES = ["owner", "last-editor"];
337
+ var identityRow = looseObject({
338
+ remote_id: nullable(string()),
339
+ provider: string(),
340
+ role: picklist(IDENTITY_ROLES),
341
+ person: nullable(record(string(), unknown()))
342
+ });
343
+ var documentQueries = /* @__PURE__ */ __name(() => {
344
+ return {
345
+ folders: registry("selected_folder", folderRow, ["id"], { id: "id:FOLDER_ID" }),
346
+ mirrors: registry("mirror", mirrorRow, ["id", "path", "folder"], {
347
+ id: "id:example",
348
+ path: 'path:"/example/notes"',
349
+ folder: "folder:FOLDER_ID"
350
+ }),
351
+ tags: registry("document_tag", tagRow, ["tag"], { tag: "tag:budget" }),
352
+ notes: registry("note", note, ["text"], { text: "text:review" }),
353
+ links: registry("document_relationship", linkRow, ["id", "role", "origin", "confirmed"], {
354
+ id: "id:1",
355
+ role: "role:reviewer",
356
+ origin: "origin:owner",
357
+ confirmed: "confirmed:true"
358
+ }),
359
+ identities: registry("document_identity", identityRow, ["remote_id", "role"], {
360
+ remote_id: "remote_id:example",
361
+ role: "role:owner"
362
+ })
363
+ };
364
+ }, "documentQueries");
365
+ var bindQuery = /* @__PURE__ */ __name((command, query, schema2) => answerEntity(withQuery(command, query), query.entity, schema2), "bindQuery");
366
+ var termsOf = /* @__PURE__ */ __name((words, query, command) => Object.fromEntries(queryTerms(words, query, command)), "termsOf");
367
+ var FACT_QUERY = {
368
+ entity: "fact",
369
+ backend: "native",
370
+ fields: [
371
+ termField("kind", "enum", "kind:decision", { values: FACT_TYPES }),
372
+ termField("status", "enum", "status:proposed", { values: FACT_STATUSES })
373
+ ]
374
+ };
375
+ var MEMORY_QUERY = {
376
+ entity: "memory",
377
+ backend: "native",
378
+ fields: [
379
+ termField("kind", "enum", "kind:preference", { values: MEMORY_KINDS }),
380
+ termField("status", "enum", "status:proposed", { values: MEMORY_STATUSES }),
381
+ termField("scope", "enum", "scope:work", { values: MEMORY_SCOPES })
382
+ ]
383
+ };
384
+ var MEMORY_SEARCH_QUERY = {
385
+ entity: "memory",
386
+ backend: "native",
387
+ fields: [
388
+ nativeField({
389
+ name: "text",
390
+ type: "txt",
391
+ operators: ["term", "phrase"],
392
+ example: "text:reviews",
393
+ relation: "words of the memory; a bare word means the same"
394
+ }),
395
+ termField("scope", "enum", "scope:work", { values: MEMORY_SCOPES })
396
+ ]
397
+ };
398
+ var factItem = /* @__PURE__ */ __name(({ type, statement, source, confirmedBy, ...fact }) => ({
399
+ ref: fact.ref,
400
+ id: fact.id,
401
+ kind: type,
402
+ text: statement,
403
+ status: fact.status,
404
+ project: fact.project,
405
+ subject: fact.subject,
406
+ occurred_at: fact.occurredAt,
407
+ supersedes: fact.supersedes,
408
+ author: fact.author,
409
+ model: fact.model,
410
+ confirmed_by: confirmedBy,
411
+ scope: fact.scope,
412
+ origin: source,
413
+ evidence: fact.evidence,
414
+ created_at: fact.createdAt,
415
+ updated_at: fact.updatedAt
416
+ }), "factItem");
417
+ var memoryItem = /* @__PURE__ */ __name(({ body, ...memory }) => ({
418
+ ref: memory.ref,
419
+ id: memory.id,
420
+ kind: memory.kind,
421
+ text: body,
422
+ subject: memory.subject,
423
+ author: memory.author,
424
+ model: memory.model,
425
+ confidence: memory.confidence,
426
+ status: memory.status,
427
+ scope: memory.scope,
428
+ supersedes: memory.supersedes,
429
+ evidence: memory.evidence,
430
+ last_verified_at: memory.lastVerifiedAt,
431
+ created_at: memory.createdAt,
432
+ updated_at: memory.updatedAt
433
+ }), "memoryItem");
434
+ var memorySearch = /* @__PURE__ */ __name((words) => {
435
+ const command = "memories search";
436
+ const context = { command, guide: LIST_QUERY_GUIDE };
437
+ const ast = validateQuery(parseLucene(typedQuery(words), { defaultField: "text", ...context }), MEMORY_SEARCH_QUERY, context);
438
+ const text = [];
439
+ let scope;
440
+ const add = /* @__PURE__ */ __name((node) => {
441
+ if (node.kind === "boolean") {
442
+ for (const clause of node.clauses) {
443
+ if (clause.occur !== "must")
444
+ queryError("query.unsupported-placement", clause.node.span, "this search joins its terms by AND", context);
445
+ add(clause.node);
446
+ }
447
+ return;
448
+ }
449
+ if (node.field === "text")
450
+ text.push(node.value);
451
+ else if (scope !== void 0)
452
+ queryError("query.unsupported-placement", node.span, "scope only once here", context);
453
+ else
454
+ scope = node.value.toLowerCase();
455
+ }, "add");
456
+ add(ast.root);
457
+ if (text.length === 0)
458
+ queryError("query.missing-value", ast.root.span, "say which words to look for beside scope:", context);
459
+ return { text: text.join(" "), ...scope === void 0 ? {} : { scope } };
460
+ }, "memorySearch");
461
+
462
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/words.js
463
+ var wordsOf = /* @__PURE__ */ __name((words) => {
464
+ const profile = words.profile ?? "personal";
465
+ const place = words.place ?? words.provider;
466
+ const { provider } = words;
467
+ return {
468
+ ...words,
469
+ profile,
470
+ place,
471
+ prefix: `${words.app} ${profile}`,
472
+ text: {
473
+ documents: `read imported documents and ${provider} documents`,
474
+ documentsList: `list imported documents with their ${provider} URLs`,
475
+ documentArgument: `document id, ${provider} URL, or a search hit's document: ref`,
476
+ knowledgeArgument: `${provider} file or folder id or URL in the local catalog, or a document:<n> ref`,
477
+ catalog: `browse stored ${place} files and folders offline`,
478
+ catalogArgument: `${provider} file or folder id, or its URL`,
479
+ treeArgument: `${provider} folder id or URL; defaults to the explicitly selected profile's roots`,
480
+ folders: `choose the ${place} folders that sync imports`,
481
+ folderArgument: `folder id or ${place} URL`,
482
+ folderToAdd: "FOLDER_ID",
483
+ syncLimit: `how many documents to read from ${provider} in this run`,
484
+ identities: `the ${provider} accounts seen on a document, and the people they belong to`,
485
+ identitiesList: `list the people ${provider} shows for a document`,
486
+ identitiesLink: `record that a ${provider} account belongs to a known person`,
487
+ identityArgument: `${provider} account id, as identities list prints it`,
488
+ mirrors: `keep local folders mirrored into ${place}`,
489
+ mirrorsAdd: `mirror a local folder into ${place}`,
490
+ mirrorsSync: `sync both ways with ${place}; a part changed on both sides is reported`,
491
+ mirrorParent: `the ${place} folder to write into, by id or URL`,
492
+ ...words.text
493
+ }
494
+ };
495
+ }, "wordsOf");
496
+ var examples = /* @__PURE__ */ __name((command, lines) => annotate(command, { examples: lines }), "examples");
497
+ var positive = /* @__PURE__ */ __name((input) => {
498
+ const n = Number(input);
499
+ if (!Number.isSafeInteger(n) || n < 1)
500
+ throw new InvalidArgumentError("use a positive integer");
501
+ return n;
502
+ }, "positive");
503
+ var nonnegative = /* @__PURE__ */ __name((input) => {
504
+ const n = Number(input);
505
+ if (!Number.isSafeInteger(n) || n < 0)
506
+ throw new InvalidArgumentError("use a nonnegative integer");
507
+ return n;
508
+ }, "nonnegative");
509
+ var allOf = /* @__PURE__ */ __name((items) => listOf("", { items, limit: Math.max(1, items.length), has_more: false }), "allOf");
510
+ var documentsGroup = /* @__PURE__ */ __name((program, words) => program.commands.find((command) => command.name() === "documents") ?? annotate(program.command("documents"), { effects: { remote: "none", local: "read" } }).description(words.text.documents), "documentsGroup");
511
+ var DAY = 24 * 60 * 60 * 1e3;
512
+ var ageOf = /* @__PURE__ */ __name((lastSync, now = Date.now()) => {
513
+ const at = lastSync ? Date.parse(lastSync) : Number.NaN;
514
+ return Number.isNaN(at) ? { synced_at: null, age_days: null } : { synced_at: lastSync ?? null, age_days: Math.max(0, Math.floor((now - at) / DAY)) };
515
+ }, "ageOf");
516
+ var staleCopy = /* @__PURE__ */ __name((provider, lastSync, now = Date.now()) => {
517
+ const sync = defineSteps([
518
+ { id: "sync.run", command: "sync", args: [], why: `copy the changes ${provider} has made into the local store` }
519
+ ])[0];
520
+ const { synced_at, age_days } = ageOf(lastSync, now);
521
+ const old = synced_at === null || now - Date.parse(synced_at) > DAY;
522
+ if (!old)
523
+ return {};
524
+ const why = age_days === null ? `the local copy has no sync time; ${provider} may have changed the document since it was copied` : `the local copy was synced ${age_days} day${age_days === 1 ? "" : "s"} ago; ${provider} may have changed the document since`;
525
+ return {
526
+ missing: [{ field: "synced_at", why, step: sync.id }],
527
+ next: [stepOf(sync)],
528
+ meta: { complete: false }
529
+ };
530
+ }, "staleCopy");
531
+
532
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/catalog.js
533
+ var CATALOG_TREE_LIMIT = 1e4;
534
+ var CATALOG_PAGE = 1e3;
535
+ var PARENT_BATCH = 200;
536
+ var catalogSource = /* @__PURE__ */ __name((catalog, principal) => ({
537
+ get: /* @__PURE__ */ __name((externalId) => catalog.get(principal, catalogId({ externalId })), "get"),
538
+ children: /* @__PURE__ */ __name((externalId, page) => catalog.list(principal, { parent: catalogId({ externalId }), ...page }), "children"),
539
+ // Each read scans the account's catalog, so the branches cut at the depth are asked about 200 at a time, in one read.
540
+ withChildren: /* @__PURE__ */ __name(async (externalIds) => {
541
+ const found = /* @__PURE__ */ new Set();
542
+ for (let start = 0; start < externalIds.length; start += PARENT_BATCH) {
543
+ const batch = new Set(externalIds.slice(start, start + PARENT_BATCH));
544
+ const parent = [...batch].map((externalId) => catalogId({ externalId }));
545
+ for (let offset = 0; ; offset += CATALOG_PAGE) {
546
+ const page = await catalog.list(principal, { parent, limit: CATALOG_PAGE, offset });
547
+ for (const item of page.items)
548
+ for (const parent2 of item.parents)
549
+ if (batch.delete(parent2))
550
+ found.add(parent2);
551
+ if (!page.hasMore || batch.size === 0)
552
+ break;
553
+ }
554
+ }
555
+ return found;
556
+ }, "withChildren")
557
+ }), "catalogSource");
558
+ var tooLarge = /* @__PURE__ */ __name((limit) => new CliError("validation_error", `the tree is over ${limit} entries; name a smaller FOLDER or lower --depth`, {
559
+ reason: "catalog.tree-limit"
560
+ }), "tooLarge");
561
+ var catalogTree = /* @__PURE__ */ __name(async (source, roots, depth, limit = CATALOG_TREE_LIMIT) => {
562
+ if (!Number.isSafeInteger(depth) || depth < 0 || depth > 50)
563
+ throw new CliError("validation_error", "tree depth must be between 0 and 50", { reason: "catalog.depth-invalid" });
564
+ let nodes = 0;
565
+ const seen = /* @__PURE__ */ new Set();
566
+ const cut = [];
567
+ const cutIds = [];
568
+ const hasChildren = /* @__PURE__ */ __name(async (externalId) => (await source.children(externalId, { limit: 1, offset: 0 })).items.length > 0, "hasChildren");
569
+ const childrenOf2 = /* @__PURE__ */ __name(async (externalId) => {
570
+ const items = [];
571
+ for (let offset = 0; ; offset += CATALOG_PAGE) {
572
+ const page = await source.children(externalId, { limit: CATALOG_PAGE, offset });
573
+ for (const item of page.items)
574
+ items.push(item);
575
+ if (nodes + items.length > limit)
576
+ throw tooLarge(limit);
577
+ if (!page.hasMore)
578
+ return items;
579
+ }
580
+ }, "childrenOf");
581
+ const node = /* @__PURE__ */ __name(async (entry, level, ancestors) => {
582
+ if (ancestors.has(entry.externalId))
583
+ throw new CliError("invalid_response", "local folder ancestry contains a cycle", { reason: "catalog.cycle" });
584
+ if (++nodes > limit)
585
+ throw tooLarge(limit);
586
+ const tree = {
587
+ item: {
588
+ id: catalogId(entry),
589
+ ref: entry.ref,
590
+ name: entry.name,
591
+ kind: entry.kind,
592
+ url: entry.url,
593
+ content: entry.content
594
+ },
595
+ children: [],
596
+ truncated: false
597
+ };
598
+ if (seen.has(entry.externalId))
599
+ return { ...tree, repeated: true };
600
+ seen.add(entry.externalId);
601
+ if (level >= depth) {
602
+ cut.push(tree);
603
+ cutIds.push(entry.externalId);
604
+ return tree;
605
+ }
606
+ const next = new Set(ancestors).add(entry.externalId);
607
+ for (const child of await childrenOf2(entry.externalId))
608
+ tree.children.push(await node(child, level + 1, next));
609
+ return tree;
610
+ }, "node");
611
+ const trees = [];
612
+ for (const id of roots) {
613
+ const entry = await source.get(id);
614
+ if (!entry || entry.kind !== "folder" && !await hasChildren(entry.externalId))
615
+ throw new CliError("not_found", "no folder or page with sub-pages by that id in the active local catalog", {
616
+ reason: "catalog.not-found"
617
+ });
618
+ trees.push(await node(entry, 0, /* @__PURE__ */ new Set()));
619
+ }
620
+ const parents = source.withChildren ? await source.withChildren(cutIds) : new Set((await Promise.all(cutIds.map(async (id) => await hasChildren(id) ? id : ""))).filter(Boolean));
621
+ cut.forEach((tree, i) => {
622
+ tree.truncated = parents.has(cutIds[i]);
623
+ });
624
+ return trees;
625
+ }, "catalogTree");
626
+ var catalogId = /* @__PURE__ */ __name((entry) => entry.externalId.replace(/\.md$/, ""), "catalogId");
627
+ var catalogOutput = /* @__PURE__ */ __name((entry) => ({
628
+ id: catalogId(entry),
629
+ ref: entry.ref,
630
+ kind: entry.kind,
631
+ name: entry.name,
632
+ parents: entry.parents.map((id) => id.replace(/\.md$/, "")),
633
+ url: entry.url,
634
+ mime: entry.mime,
635
+ size: entry.size,
636
+ created_at: entry.createdAt,
637
+ modified_at: entry.modifiedAt,
638
+ observed_at: entry.observedAt,
639
+ description: entry.description,
640
+ actors: entry.actors,
641
+ provider_metadata: entry.metadata,
642
+ active: entry.active,
643
+ content: entry.content
644
+ }), "catalogOutput");
645
+ var CATALOG_FIELDS = Object.keys({
646
+ id: true,
647
+ ref: true,
648
+ kind: true,
649
+ name: true,
650
+ parents: true,
651
+ url: true,
652
+ mime: true,
653
+ size: true,
654
+ created_at: true,
655
+ modified_at: true,
656
+ observed_at: true,
657
+ description: true,
658
+ actors: true,
659
+ provider_metadata: true,
660
+ active: true,
661
+ content: true
662
+ });
663
+ var local = /* @__PURE__ */ __name((command, mutates = false) => annotate(command, { effects: mutates ? LOCAL_WRITE : LOCAL_READ }), "local");
664
+ var addDocumentCatalogCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
665
+ const { output } = helpers;
666
+ const wording = wordsOf(helpers.words);
667
+ const { prefix, text } = wording;
668
+ const queries = documentQueries();
669
+ const view = "catalog";
670
+ const catalog = local(program.command("catalog")).description(text.catalog);
671
+ const run = /* @__PURE__ */ __name((fn, write = false) => helpers.run(async (index, principal) => {
672
+ if (!index.catalog)
673
+ throw new CliError("configuration_error", "index has no shared catalog adapter", {
674
+ reason: "catalog.unavailable"
675
+ });
676
+ return fn({ ...index, catalog: index.catalog }, principal);
677
+ }, write), "run");
678
+ const entry = /* @__PURE__ */ __name(async (index, principal, id) => {
679
+ const found = await index.catalog?.get(principal, helpers.id(id));
680
+ if (!found)
681
+ throw new CliError("not_found", "file or folder is not in the active local catalog; run catalog import or sync", {
682
+ reason: "catalog.not-found"
683
+ });
684
+ return found;
685
+ }, "entry");
686
+ examples(local(catalog.command("import").description("put cached file and folder metadata into the shared database"), true), [`${prefix} catalog import --offline`]).action(async () => output(itemOf(await run((index, principal) => index.catalog.import(principal), true))));
687
+ examples(annotate(local(catalog.command("show").description("show stored metadata and the stable file or folder reference")), {
688
+ output: { entity: "document", view }
689
+ }), [`${prefix} catalog show FILE_ID --offline`]).argument("<file>", text.catalogArgument).action(async (id) => output(itemOf(await run(async (index, principal) => catalogOutput(await entry(index, principal, id))))));
690
+ const list = /* @__PURE__ */ __name(async (terms, args, search) => {
691
+ const ast = terms.length ? validateQuery(parseLucene(terms.join(" "), { defaultField: search ? "text" : "none" }), CATALOG_QUERY) : void 0;
692
+ const result = await run((index, principal) => index.catalog.list(principal, { ast, limit: args.limit, offset: (args.page - 1) * args.limit }));
693
+ output(listOf(`catalog ${search ? "search" : "list"}`, {
694
+ items: result.items.map(catalogOutput),
695
+ limit: args.limit,
696
+ has_more: result.hasMore,
697
+ page: args.page,
698
+ args: { query: terms.length ? terms.join(" ") : void 0 }
699
+ }));
700
+ }, "list");
701
+ for (const action of ["list", "search"]) {
702
+ const command = examples(local(catalog.command(action).description(action === "list" ? "list cached files and folders using metadata queries" : "search cached names, descriptions, types and observed people")), [
703
+ action === "list" ? `${prefix} catalog list "parent:FOLDER_ID AND kind:file" --offline` : `${prefix} catalog search "budget AND person:Rin*" --offline`
704
+ ]).argument(action === "list" ? "[query...]" : "<query...>", "metadata query: kind, mime, name, parent, person, tag; AND, OR, NOT").option("--limit <n>", "how many entries to return (at most 1000)", positive, 50).option("--page <n>", "which page to return", positive, 1).action(async (terms, args) => list(terms, args, action === "search"));
705
+ annotate(command, { query: CATALOG_QUERY, output: { entity: "document", view } });
706
+ }
707
+ examples(local(catalog.command("tree").description("show the cached hierarchy below a folder or all selected roots")), [`${prefix} catalog tree --offline`, `${prefix} catalog tree FOLDER_ID --depth 3 --offline`]).argument("[folder]", text.treeArgument).option("--depth <n>", "maximum descendant depth, from 0 to 50", nonnegative, 5).action(async (id, args) => output(await run(async (index, principal) => {
708
+ const roots = id ? [helpers.id(id)] : helpers.roots();
709
+ const tree = await catalogTree(catalogSource(index.catalog, principal), roots.map((root) => `${root}.md`), args.depth);
710
+ return allOf(tree);
711
+ })));
712
+ const tags = local(catalog.command("tags")).description("add owner tags to cached files or folders");
713
+ for (const action of ["list", "add", "remove"]) {
714
+ const command = examples(local(tags.command(action).description(`${action} local tags on a cached file or folder`), action !== "list"), [`${prefix} catalog tags ${action} FOLDER_ID${action === "list" ? "" : " project"} --offline`]).argument("<file>", text.catalogArgument);
715
+ if (action === "list")
716
+ bindQuery(command, queries.tags, tagRow);
717
+ else
718
+ command.argument("<tags...>", "local tag names");
719
+ command.action(async (id, values = []) => {
720
+ const filter = action === "list" ? termsOf(values, queries.tags, "catalog tags list") : void 0;
721
+ return output(allOf(await run(async (index, principal) => {
722
+ const found = await entry(index, principal, id);
723
+ if (!index.knowledge)
724
+ throw new CliError("configuration_error", "index has no shared knowledge adapter");
725
+ const tags2 = await index.knowledge.tags(principal, found.ref, action, action === "list" ? void 0 : values, filter);
726
+ return action === "list" ? tags2.map((tag) => ({ tag })) : tags2;
727
+ }, action !== "list")));
728
+ });
729
+ }
730
+ }, "addDocumentCatalogCommandsDefinition");
731
+ var addDocumentCatalogCommands = honoursDryRun(sharedCommand(addDocumentCatalogCommandsDefinition));
732
+
733
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/documents.js
734
+ import { writeFileSync } from "node:fs";
735
+ var addLocalDocumentCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
736
+ const { output, lastSync } = helpers;
737
+ const wording = wordsOf(helpers.words);
738
+ const { prefix, provider, text } = wording;
739
+ const documents = documentsGroup(program, wording);
740
+ annotate(withQuery(examples(annotate(documents.command("list"), { effects: LOCAL_READ }).description(text.documentsList), [
741
+ `${prefix} documents list`,
742
+ `${prefix} documents list tag:budget`,
743
+ `${prefix} documents list person:PERSON_UID --limit 10`
744
+ ]), IMPORTED_DOCUMENT_QUERY), { output: { entity: "document", view: "imported" }, partial: true }).option("--limit <n>", "how many documents to return", positive, 50).option("--page <n>", "which page to return", positive, 1).action(async (words, { limit, page }) => {
745
+ const query = typedQuery(words);
746
+ const ast = listQuery(query, IMPORTED_DOCUMENT_QUERY, "documents list");
747
+ const found = await helpers.list(ast, { limit, offset: (page - 1) * limit });
748
+ const synced = lastSync();
749
+ const age = ageOf(synced);
750
+ output(listOf("documents list", {
751
+ ...staleCopy(provider, synced),
752
+ items: found.items.map((item) => ({ ...item, ...age })),
753
+ limit,
754
+ has_more: found.hasMore,
755
+ page,
756
+ args: { query: query || void 0 }
757
+ }));
758
+ });
759
+ examples(annotate(documents.command("show"), { effects: LOCAL_READ, partial: true }).argument("<document>", text.documentArgument).description("show an imported document's text, tabs and metadata"), [`${prefix} documents show DOC_ID`, `${prefix} documents show document:42 --offline`]).action((input) => {
760
+ const { metadata, snapshot } = helpers.document(input);
761
+ const synced = lastSync();
762
+ output(itemOf({
763
+ metadata,
764
+ ...ageOf(synced),
765
+ text: snapshot.text,
766
+ tabs: snapshot.tabs,
767
+ ...snapshot.notRead ? { not_read: snapshot.notRead } : {}
768
+ }, staleCopy(provider, synced)));
769
+ });
770
+ examples(annotate(documents.command("export"), { effects: LOCAL_WRITE, partial: true }).argument("<document>", text.documentArgument).description("write an imported document to a new Markdown file"), [`${prefix} documents export DOC_ID --output notes.md`]).requiredOption("--output <file>", "path of the Markdown file to write; an existing file is refused").action((input, args) => {
771
+ const { id, snapshot } = helpers.document(input);
772
+ try {
773
+ writeFileSync(args.output, snapshot.markdown, { flag: "wx", mode: 384 });
774
+ } catch (error) {
775
+ if (error.code === "EEXIST")
776
+ throw new CliError("validation_error", "the output file already exists; choose another --output", {
777
+ reason: "export.exists",
778
+ param: "--output"
779
+ });
780
+ throw error;
781
+ }
782
+ const synced = lastSync();
783
+ output(itemOf({ id, path: args.output, format: "markdown", ...ageOf(synced) }, staleCopy(provider, synced)));
784
+ });
785
+ return documents;
786
+ }, "addLocalDocumentCommandsDefinition");
787
+ var addLocalDocumentCommands = honoursDryRun(sharedCommand(addLocalDocumentCommandsDefinition));
788
+
789
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/folders.js
790
+ var addDocumentFolderCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
791
+ const { output } = helpers;
792
+ const wording = wordsOf(helpers.words);
793
+ const { prefix, text } = wording;
794
+ const queries = documentQueries();
795
+ const folders = annotate(program.command("folders"), { effects: LOCAL_READ }).description(text.folders);
796
+ examples(annotate(folders.command("add"), { effects: FETCH }).argument("<folder>", text.folderArgument).description("import a folder and everything under it on the next sync"), [`${prefix} folders add ${text.folderToAdd}`]).action(async (input) => {
797
+ const { id, name } = await helpers.add(input);
798
+ output(itemOf({ id, name, added: true }));
799
+ });
800
+ bindQuery(examples(annotate(folders.command("list"), { effects: LOCAL_READ }).description("list the folder ids sync imports"), [`${prefix} folders list`]), queries.folders, folderRow).action((words) => {
801
+ const filter = termsOf(words, queries.folders, "folders list");
802
+ output(allOf(helpers.list(filter)));
803
+ });
804
+ examples(annotate(folders.command("remove"), { effects: LOCAL_WRITE }).argument("<folder>", text.folderArgument).description("stop importing a folder; the next sync drops its documents"), [`${prefix} folders remove FOLDER_ID`]).action((input) => {
805
+ output(itemOf({ id: helpers.remove(input), removed: true }));
806
+ });
807
+ return folders;
808
+ }, "addDocumentFolderCommandsDefinition");
809
+ var sharedFolderCommands = honoursDryRun(sharedCommand(addDocumentFolderCommandsDefinition));
810
+ var addDocumentFolderCommands = /* @__PURE__ */ __name((program, helpers) => {
811
+ const folders = sharedFolderCommands(program, helpers);
812
+ if (!helpers.browse)
813
+ return folders;
814
+ const before = new Set(folders.commands);
815
+ helpers.browse(folders);
816
+ const added = folders.commands.filter((command) => !before.has(command));
817
+ const children = folders.commands;
818
+ const rest = children.filter((command) => before.has(command));
819
+ const at = rest.findIndex((command) => command.name() === "remove");
820
+ children.splice(0, children.length, ...rest.slice(0, at), ...added, ...rest.slice(at));
821
+ return folders;
822
+ }, "addDocumentFolderCommands");
823
+
824
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/history.js
825
+ var DOCUMENT_HISTORY_SETTINGS = {
826
+ profile: { keep_versions_for_days: optional(count) },
827
+ settings: [
828
+ {
829
+ key: "keep_versions_for_days",
830
+ default: KEEP_VERSIONS_FOR_DAYS,
831
+ description: "days earlier versions of synced documents, and the change log, are kept"
832
+ }
833
+ ]
834
+ };
835
+ var keepVersionsForDays = /* @__PURE__ */ __name((settings) => fromFile(settings, "keep_versions_for_days", KEEP_VERSIONS_FOR_DAYS).value, "keepVersionsForDays");
836
+ var eventList = /* @__PURE__ */ __name((input, before = []) => {
837
+ const events = input.split(",").map((one) => one.trim());
838
+ for (const event of events)
839
+ if (!DOCUMENT_EVENTS.includes(event))
840
+ throw new InvalidArgumentError(`use ${DOCUMENT_EVENTS.join(", ")}`);
841
+ return [...before, ...events];
842
+ }, "eventList");
843
+ var addDocumentHistoryCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
844
+ const wording = wordsOf(helpers.words);
845
+ const { prefix, text } = wording;
846
+ const documents = documentsGroup(program, wording);
847
+ const reference = /* @__PURE__ */ __name(async (history, principal, input) => {
848
+ const found = await history.reference(principal, /^document:\d+$/.test(input) ? input : helpers.id(input));
849
+ if (!found)
850
+ throw new CliError("not_found", "this document is not in the selected profile's local copy", {
851
+ reason: "document.not-imported"
852
+ });
853
+ return found;
854
+ }, "reference");
855
+ examples(annotate(documents.command("history"), { effects: LOCAL_READ }).argument("<document>", text.documentArgument).description("list the versions of a document kept in the local copy, or show one with --revision"), [`${prefix} documents history DOC_ID`, `${prefix} documents history DOC_ID --revision 3`]).option("--revision <n>", "show the text of this version", positive).action((input, args) => helpers.run(async (history, principal) => {
856
+ const ref = await reference(history, principal, input);
857
+ if (args.revision !== void 0) {
858
+ helpers.output(itemOf({ document: ref, ...await history.version(ref, args.revision) }));
859
+ return;
860
+ }
861
+ helpers.output(itemOf(await history.versions(ref)));
862
+ }));
863
+ return examples(annotate(program.command("changes"), { effects: LOCAL_READ }).description("list the documents the sync added, changed, removed or brought back, newest first"), [`${prefix} changes`, `${prefix} changes --since 7d --event deleted,unavailable`]).option("--since <when>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d").option("--until <when>", "up to this time, in the same forms").option(`--event <events>`, `only these, comma separated: ${DOCUMENT_EVENTS.join(", ")}`, eventList).option("--limit <n>", "how many changes to return", positive, 50).option("--page <n>", "which page to return", positive, 1).action((args) => helpers.run(async (history, principal) => {
864
+ const now = Date.now();
865
+ const since = new Date(momentOf(args.since, "--since", now)).toISOString();
866
+ const until = args.until === void 0 ? void 0 : new Date(momentOf(args.until, "--until", now, { end: true })).toISOString();
867
+ const found = await history.changes(principal, {
868
+ since,
869
+ ...until ? { until } : {},
870
+ ...args.event ? { events: args.event } : {},
871
+ limit: args.limit,
872
+ offset: (args.page - 1) * args.limit
873
+ });
874
+ helpers.output(listOf("changes", {
875
+ items: found.items,
876
+ limit: args.limit,
877
+ has_more: found.hasMore,
878
+ page: args.page,
879
+ args: { since, ...until ? { until } : {}, ...args.event ? { event: args.event } : {} }
880
+ }));
881
+ }));
882
+ }, "addDocumentHistoryCommandsDefinition");
883
+ var addDocumentHistoryCommands = honoursDryRun(sharedCommand(addDocumentHistoryCommandsDefinition));
884
+
885
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/knowledge.js
886
+ var addDocumentKnowledgeCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
887
+ const { run, output, author, decider } = helpers;
888
+ const wording = wordsOf(helpers.words);
889
+ const { prefix, text } = wording;
890
+ const queries = documentQueries();
891
+ const documentArgument = text.knowledgeArgument;
892
+ const scopes = ["personal", "work"];
893
+ const documents = documentsGroup(program, wording);
894
+ examples(annotate(documents.command("context"), { effects: LOCAL_READ }).argument("<document>", documentArgument).description("show a document with its tags, relationships, notes, memories and editors"), [`${prefix} documents context DOC_ID`]).action(async (doc) => output(itemOf(await run(doc, (k, p, ref) => k.context(p, ref)))));
895
+ const tags = annotate(program.command("tags"), { effects: LOCAL_READ }).description("label imported documents; labels survive a sync");
896
+ for (const action of ["list", "add", "remove"]) {
897
+ const command = examples(annotate(tags.command(action), { effects: action === "list" ? LOCAL_READ : LOCAL_WRITE }).description(action === "list" ? "list a document's tags" : action === "add" ? "tag a document" : "untag a document").argument("<document>", documentArgument), [`${prefix} tags ${action} DOC_ID${action === "list" ? "" : " budget q3"}`]);
898
+ if (action === "list") {
899
+ bindQuery(command, queries.tags, tagRow).action(async (doc, words) => {
900
+ const filter = termsOf(words, queries.tags, "tags list");
901
+ output(allOf((await run(doc, (k, p, ref) => k.tags(p, ref, "list", [], filter))).map((tag) => ({ tag }))));
902
+ });
903
+ } else
904
+ command.argument("<tags...>", "one or more tags").action(async (doc, values) => output(itemOf({ tags: await run(doc, (k, p, ref) => k.tags(p, ref, action, values)) })));
905
+ }
906
+ const relationships2 = annotate(program.command("relationships"), { effects: LOCAL_READ }).description("connect a document to people, projects, notes and other references");
907
+ bindQuery(examples(annotate(relationships2.command("list"), { effects: LOCAL_READ }).description("list a document's relationships"), [`${prefix} relationships list DOC_ID`]).argument("<document>", documentArgument), queries.links, linkRow).action(async (doc, words) => {
908
+ const { confirmed, ...filter } = termsOf(words, queries.links, "relationships list");
909
+ output(allOf(await run(doc, (k, p, ref) => k.links(p, ref, { ...filter, ...confirmed === void 0 ? {} : { confirmed: confirmed === "true" } }))));
910
+ });
911
+ examples(annotate(relationships2.command("add"), { effects: LOCAL_WRITE }).description("connect a document to another reference"), [
912
+ `${prefix} relationships add DOC_ID project:PROJECT_ID --kind about`,
913
+ `${prefix} relationships add DOC_ID person:PERSON_UID --kind assigned-to --role reviewer`
914
+ ]).argument("<document>", documentArgument).argument("<reference>", "what it connects to, such as person:<uid>, project:<id> or note:<id>").addOption(new Option("--kind <kind>", "how the two relate").choices(["links-to", "about", "evidence", "created-from", "related-to", "assigned-to"]).default("related-to")).option("--role <role>", "the part the reference plays, in a word or two").option("--reason <text>", "why the two are connected").action(async (doc, to, { reason, ...args }) => output(itemOf(await run(doc, (k, p, ref) => k.addLink(p, ref, { to, ...args, by: decider(), ...reason ? { evidence: reason } : {} })))));
915
+ examples(annotate(relationships2.command("remove"), { effects: LOCAL_WRITE }).description("remove one of a document's relationships"), [`${prefix} relationships remove DOC_ID LINK_ID`]).argument("<document>", documentArgument).argument("<relationship-id>", "id, as relationships list prints it").action(async (doc, id) => output(itemOf(await run(doc, (k, p, ref) => k.removeLink(p, ref, id, decider())))));
916
+ const notes = annotate(program.command("notes"), { effects: LOCAL_READ }).description("write notes about an imported document");
917
+ const noteArgument = "note:<id> reference, as notes list prints it";
918
+ examples(annotate(notes.command("add"), {
919
+ effects: LOCAL_WRITE,
920
+ output: { entity: "note" },
921
+ literal_after_dashes: true
922
+ }).description("write a note about a document"), [`${prefix} notes add DOC_ID "Check the numbers" --title Review`]).argument("<document>", documentArgument).argument("<text>", "the note's text").option("--title <title>", "a title for the note").action(async (doc, text2, args) => output(itemOf(await run(doc, (k, p, ref) => k.addNote(p, ref, text2, args.title)))));
923
+ withQuery(examples(annotate(notes.command("list"), { effects: LOCAL_READ }).description("list a document's notes"), [
924
+ `${prefix} notes list DOC_ID`,
925
+ `${prefix} notes list DOC_ID text:review --limit 10`
926
+ ]).argument("<document>", documentArgument), queries.notes).option("--limit <n>", "how many notes to return", positive, 50).option("--page <n>", "which page to return", positive, 1).action(async (doc, words, { page, limit }) => {
927
+ const query = termsOf(words, queries.notes, "notes list").text;
928
+ const found = await run(doc, (k, p, ref) => k.notes(p, ref, { ...query ? { search: query } : {}, limit, offset: (page - 1) * limit }));
929
+ output(listOf("notes list", {
930
+ items: found.items,
931
+ limit,
932
+ has_more: found.hasMore,
933
+ page,
934
+ args: { document: doc, query: words.join(" ") }
935
+ }));
936
+ });
937
+ examples(annotate(notes.command("show"), { effects: LOCAL_READ, output: { entity: "note" } }).description("show one note"), [`${prefix} notes show DOC_ID note:NOTE_ID`]).argument("<document>", documentArgument).argument("<note>", noteArgument).action(async (doc, noteRef) => output(itemOf(await run(doc, (k, p, ref) => k.note(p, ref, noteRef)))));
938
+ examples(annotate(notes.command("edit"), {
939
+ effects: LOCAL_WRITE,
940
+ output: { entity: "note" },
941
+ literal_after_dashes: true
942
+ }).description("replace a note's text"), [`${prefix} notes edit DOC_ID note:NOTE_ID "Numbers checked" --revision 2`]).argument("<document>", documentArgument).argument("<note>", noteArgument).argument("<text>", "the note's new text").requiredOption("--revision <n>", "revision from notes show; a newer note is not overwritten", positive).action(async (doc, noteRef, text2, args) => output(itemOf(await run(doc, (k, p, ref) => k.editNote(p, ref, noteRef, text2, args.revision)))));
943
+ examples(annotate(notes.command("remove"), { effects: LOCAL_WRITE }).description("delete one note"), [
944
+ `${prefix} notes remove DOC_ID note:NOTE_ID`
945
+ ]).argument("<document>", documentArgument).argument("<note>", noteArgument).action(async (doc, noteRef) => output(itemOf(await run(doc, (k, p, ref) => k.removeNote(p, ref, noteRef)))));
946
+ const memories = annotate(program.command("memories"), { effects: LOCAL_READ }).description("keep what was learned from a document, with evidence; an agent's stay proposed");
947
+ const memoryArgument = "memory:<id> reference, as memories list prints it";
948
+ const scope = /* @__PURE__ */ __name((description) => new Option("--scope <scope>", description).choices(scopes), "scope");
949
+ examples(annotate(memories.command("add"), { effects: LOCAL_WRITE }).description("record a memory about a document"), [`${prefix} memories add DOC_ID "The team prefers async reviews" --scope work --kind preference`]).argument("<document>", documentArgument).argument("<text>", "what to remember").addOption(scope("whose memory it is: personal or work").makeOptionMandatory()).addOption(new Option("--kind <kind>", "what kind of memory it is").choices(MEMORY_KINDS).default("summary")).option("--supersedes <ref>", "a memory:<id> about the same document that this one replaces").action(async (doc, body, args) => output(itemOf(memoryItem(await run(doc, (k, p, ref) => k.addMemory(p, ref, { body, ...args, status: "proposed", author: author() }))))));
950
+ withQuery(examples(annotate(memories.command("list"), { effects: LOCAL_READ }).description("list a document's memories"), [
951
+ `${prefix} memories list DOC_ID scope:work`,
952
+ `${prefix} memories list DOC_ID kind:preference status:confirmed`
953
+ ]).argument("<document>", documentArgument), MEMORY_QUERY).option("--limit <n>", "how many memories to return", positive, 50).action(async (doc, words, { limit }) => {
954
+ const terms = queryTerms(words, MEMORY_QUERY, "memories list");
955
+ const filters = {
956
+ ...terms.has("kind") ? { kind: terms.get("kind") } : {},
957
+ ...terms.has("status") ? { status: terms.get("status") } : {},
958
+ ...terms.has("scope") ? { scope: terms.get("scope") } : {}
959
+ };
960
+ output(allOf((await run(doc, (k, p, ref) => k.memories(p, ref, { ...filters, limit }))).items.map(memoryItem)));
961
+ });
962
+ const memoryActions = {
963
+ show: "show one memory",
964
+ confirm: "confirm a proposed memory as true",
965
+ stale: "mark a memory as out of date"
966
+ };
967
+ for (const [action, description] of Object.entries(memoryActions))
968
+ examples(annotate(memories.command(action), { effects: action === "show" ? LOCAL_READ : LOCAL_WRITE }).description(description), [`${prefix} memories ${action} DOC_ID memory:MEMORY_ID`]).argument("<document>", documentArgument).argument("<memory>", memoryArgument).action(async (doc, memoryRef) => output(itemOf(memoryItem(await run(doc, (k, p, ref) => action === "show" ? k.memory(p, ref, memoryRef) : k.memory(p, ref, memoryRef, action, decider()))))));
969
+ const search = examples(annotate(memories.command("search"), { effects: LOCAL_READ }).description("search a document's memories by words"), [`${prefix} memories search DOC_ID reviews scope:work`, `${prefix} memories search DOC_ID "async reviews"`]).argument("<document>", documentArgument).argument("<query...>", "words to look for, and scope:personal or scope:work \u2014 the fields are below").allowUnknownOption().addHelpText("after", queryHelp(MEMORY_SEARCH_QUERY)).action(async (doc, words) => {
970
+ const { text: text2, scope: scope2 } = memorySearch(words);
971
+ const found = await run(doc, (k, p, ref) => k.searchMemories(p, ref, text2, scope2));
972
+ output({
973
+ ...allOf(found.items.map(memoryItem)),
974
+ ...found.hasMore ? { meta: { truncated: true } } : {}
975
+ });
976
+ });
977
+ annotate(search, { query: defineQuery(MEMORY_SEARCH_QUERY), output: { entity: "memory" } });
978
+ examples(annotate(memories.command("extract"), { effects: REMOTE_WRITE }).argument("<document>", documentArgument).description("send a document's text to the model and show the memories it proposes"), [`${prefix} memories extract DOC_ID --scope work`, `${prefix} memories extract DOC_ID --scope work --yes`]).addOption(scope("whose memories they become: personal or work").makeOptionMandatory()).option("--tab <id>", "send only this tab of the document").option("--yes", "save the proposals, each with its quote and the document's version").action(async function(doc) {
979
+ const args = this.opts();
980
+ await run(doc, async () => void 0);
981
+ const result = await extractDocumentMemories({
982
+ read: /* @__PURE__ */ __name(() => helpers.document(doc), "read"),
983
+ complete: helpers.complete(),
984
+ scope: args.scope,
985
+ author: `${wording.app}-memory`,
986
+ tab: args.tab,
987
+ save: args.yes,
988
+ withWrite: /* @__PURE__ */ __name((write) => run(doc, write), "withWrite")
989
+ });
990
+ output(itemOf({ ...result, saved: result.saved.map((item) => "type" in item ? factItem(item) : memoryItem(item)) }));
991
+ });
992
+ const facts = annotate(program.command("facts"), { effects: LOCAL_READ }).description("what happened, as a document shows it; an agent's stay proposed until confirmed");
993
+ const factArgument = "fact:<id> reference, as facts list prints it";
994
+ examples(annotate(facts.command("add"), { effects: LOCAL_WRITE }).description("record a fact a document shows"), [
995
+ `${prefix} facts add DOC_ID "Budget approved" --type decision --scope work`
996
+ ]).argument("<document>", documentArgument).argument("<statement>", "the fact, in one sentence").addOption(new Option("--type <type>", "what kind of fact it is").choices(FACT_TYPES).default("fact")).addOption(scope("whose fact it is: personal or work")).option("--supersedes <ref>", "a decision only: the decision this one replaces").option("--occurred-time <time>", "when it happened, as the evidence shows, ISO 8601; a time without a zone is read in this computer's zone, a date alone as its midnight").action(async (doc, statement, { occurredTime, ...args }) => output(itemOf(factItem(await run(doc, (k, p, ref) => k.addFact(p, ref, {
997
+ statement,
998
+ ...args,
999
+ by: author(),
1000
+ ...occurredTime === void 0 ? {} : { occurredAt: occurredTime }
1001
+ }))))));
1002
+ withQuery(examples(annotate(facts.command("list"), { effects: LOCAL_READ }).description("list a document's facts"), [
1003
+ `${prefix} facts list DOC_ID status:proposed`,
1004
+ `${prefix} facts list DOC_ID kind:decision`
1005
+ ]).argument("<document>", documentArgument), FACT_QUERY).option("--limit <n>", "how many facts to return", positive, 50).action(async (doc, words, { limit }) => {
1006
+ const terms = queryTerms(words, FACT_QUERY, "facts list");
1007
+ const filters = {
1008
+ ...terms.has("kind") ? { type: terms.get("kind") } : {},
1009
+ ...terms.has("status") ? { status: terms.get("status") } : {}
1010
+ };
1011
+ output(allOf((await run(doc, (k, p, ref) => k.facts(p, ref, { ...filters, limit }))).items.map(factItem)));
1012
+ });
1013
+ const factActions = {
1014
+ show: "show one fact",
1015
+ confirm: "confirm a proposed fact; a decision it supersedes stops holding",
1016
+ reverse: "an accepted decision no longer holds, and nothing replaced it"
1017
+ };
1018
+ for (const [action, description] of Object.entries(factActions))
1019
+ examples(annotate(facts.command(action), { effects: action === "show" ? LOCAL_READ : LOCAL_WRITE }).description(description), [`${prefix} facts ${action} DOC_ID fact:FACT_ID`]).argument("<document>", documentArgument).argument("<fact>", factArgument).action(async (doc, factRef) => output(itemOf(factItem(await run(doc, (k, p, ref) => action === "show" ? k.fact(p, ref, factRef) : k.fact(p, ref, factRef, action, decider()))))));
1020
+ const identities = annotate(program.command("identities"), { effects: LOCAL_READ }).description(text.identities);
1021
+ bindQuery(examples(annotate(identities.command("list"), { effects: LOCAL_READ }).description(text.identitiesList), [
1022
+ `${prefix} identities list DOC_ID`
1023
+ ]).argument("<document>", documentArgument), queries.identities, identityRow).action(async (doc, words) => {
1024
+ const filter = termsOf(words, queries.identities, "identities list");
1025
+ output(itemOf(await run(doc, (k, p, ref) => k.people(p, ref, filter))));
1026
+ });
1027
+ examples(annotate(identities.command("link"), { effects: LOCAL_WRITE }).description(text.identitiesLink), [
1028
+ `${prefix} identities link DOC_ID ${wording.remote.toUpperCase()}_ID person:PERSON_UID`
1029
+ ]).argument("<document>", documentArgument).argument(`<${wording.remote}-id>`, text.identityArgument).argument("<person>", "person:<uid> reference of someone already known").action(async (doc, remoteId, personRef) => output(itemOf(await run(doc, (k, p, ref) => k.linkPerson(p, ref, remoteId, personRef)))));
1030
+ }, "addDocumentKnowledgeCommandsDefinition");
1031
+ var addDocumentKnowledgeCommands = honoursDryRun(sharedCommand(addDocumentKnowledgeCommandsDefinition));
1032
+
1033
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/mirrors.js
1034
+ import { statSync } from "node:fs";
1035
+ import { resolve } from "node:path";
1036
+ var addDocumentMirrorCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
1037
+ const { output } = helpers;
1038
+ const wording = wordsOf(helpers.words);
1039
+ const { app: app2, prefix, provider, remote, text } = wording;
1040
+ const queries = documentQueries();
1041
+ const mirrors = annotate(program.command("mirrors"), { effects: LOCAL_READ }).description(text.mirrors);
1042
+ const find = /* @__PURE__ */ __name((id) => {
1043
+ const mirror = helpers.mirrors().find((item) => item.id === id);
1044
+ if (!mirror)
1045
+ throw new CliError("not_found", `no mirror ${id} in profile ${helpers.profile()}; see ${app2} ${helpers.profile()} mirrors list`, {
1046
+ reason: "mirror.not-found"
1047
+ });
1048
+ return mirror;
1049
+ }, "find");
1050
+ const syncing = /* @__PURE__ */ __name((connection) => ({
1051
+ ...connection.sync,
1052
+ stateOf: /* @__PURE__ */ __name((mirror) => helpers.stateOf(mirror), "stateOf"),
1053
+ remote
1054
+ }), "syncing");
1055
+ const chosenOf = /* @__PURE__ */ __name((id) => {
1056
+ const name = helpers.profile();
1057
+ const chosen = id ? [find(id)] : helpers.mirrors();
1058
+ if (!chosen.length)
1059
+ throw new CliError("not_found", `profile ${name} has no mirrors; add one with ${app2} ${name} mirrors add`, {
1060
+ reason: "mirror.none"
1061
+ });
1062
+ return chosen;
1063
+ }, "chosenOf");
1064
+ examples(annotate(mirrors.command("add"), { effects: FETCH }).argument("<path>", "local folder to mirror").requiredOption("--parent <id>", text.mirrorParent).description(text.mirrorsAdd), [`${prefix} mirrors add ./notes --parent FOLDER_ID`]).action(async (path, args) => {
1065
+ const root = resolve(path);
1066
+ let directory = false;
1067
+ try {
1068
+ directory = statSync(root).isDirectory();
1069
+ } catch {
1070
+ }
1071
+ if (!directory)
1072
+ throw new CliError("validation_error", "the path to mirror is not a folder", { reason: "mirror.not-folder" });
1073
+ const parent = await helpers.parent(args.parent);
1074
+ const folder = parent.id;
1075
+ const id = mirrorId(root, folder);
1076
+ const list = helpers.mirrors();
1077
+ if (!list.some((mirror) => mirror.id === id))
1078
+ list.push({ id, path: root, folder });
1079
+ helpers.save(list);
1080
+ output(itemOf({ id, path: root, folder, folder_name: parent.name, added: true }));
1081
+ });
1082
+ bindQuery(examples(annotate(mirrors.command("list"), { effects: LOCAL_READ }).description("list this profile's mirrors"), [
1083
+ `${prefix} mirrors list`
1084
+ ]), queries.mirrors, mirrorRow).action((words) => {
1085
+ const filter = termsOf(words, queries.mirrors, "mirrors list");
1086
+ output(allOf(helpers.mirrors().filter((row) => Object.entries(filter).every(([key, value]) => row[key] === value))));
1087
+ });
1088
+ examples(annotate(mirrors.command("remove"), { effects: LOCAL_WRITE }).argument("<id>", "mirror id from mirrors list").description(`stop mirroring a folder; nothing in ${wording.place} is changed or deleted`), [`${prefix} mirrors remove 1a2b3c4d`]).action((id) => {
1089
+ find(id);
1090
+ helpers.save(helpers.mirrors().filter((mirror) => mirror.id !== id));
1091
+ output(itemOf({ id, removed: true }));
1092
+ });
1093
+ examples(annotate(mirrors.command("status"), { effects: LOCAL_READ }).argument("[id]", "mirror id; every mirror of the profile when omitted").description(`show which local files the next sync would create or send; ${provider} is not asked`), [`${prefix} mirrors status`]).action(async (id) => {
1094
+ const items = await mirrorStatus(id ? [find(id)] : helpers.mirrors(), helpers.kindOf, (mirror) => helpers.stateOf(mirror));
1095
+ output(allOf(items.map(({ id: id2, folder, create, update, unchanged, orphans, unsupported, remote_checked }) => ({
1096
+ id: id2,
1097
+ folder,
1098
+ create: create.length,
1099
+ update: update.length,
1100
+ unchanged,
1101
+ orphans: orphans.length,
1102
+ unsupported,
1103
+ remote_checked
1104
+ }))));
1105
+ });
1106
+ examples(annotate(mirrors.command("sync"), { effects: REMOTE_WRITE }).argument("[id]", "mirror id; every mirror of the profile when omitted").addOption(new Option("--keep <side>", "where a part changed on both sides, keep this side").choices([
1107
+ "local",
1108
+ remote,
1109
+ "both"
1110
+ ])).option("--replace", `same as --keep local, and create again files deleted in ${provider}`).description(text.mirrorsSync), [
1111
+ `${prefix} mirrors sync`,
1112
+ `${prefix} mirrors sync 1a2b3c4d --keep ${remote}`,
1113
+ `${prefix} mirrors sync 1a2b3c4d --replace`
1114
+ ]).action(async (id, args) => {
1115
+ const chosen = chosenOf(id);
1116
+ if (args.replace && args.keep && args.keep !== "local")
1117
+ throw new CliError("validation_error", `--replace keeps the local side; it cannot be combined with --keep ${remote} or both`);
1118
+ const keep = args.replace ? "local" : args.keep === remote ? "remote" : args.keep;
1119
+ const connection = await helpers.connect();
1120
+ const { items, issues } = await syncMirrors({
1121
+ ...syncing(connection),
1122
+ mirrors: chosen,
1123
+ ...keep ? { keep } : {},
1124
+ recreate: args.replace === true
1125
+ });
1126
+ const body = allOf(items);
1127
+ if (issues.length)
1128
+ body.meta = { complete: false, issues };
1129
+ output(body);
1130
+ if (issues.length)
1131
+ throw new CliError("provider_error", `some files were not synced; see conflicts, missing and errors, then rerun with --keep local, ${remote} or both`, { reason: "mirror.partial" });
1132
+ });
1133
+ examples(annotate(mirrors.command("watch"), { effects: REMOTE_WRITE, lifetime: "persistent" }).argument("[id]", "mirror id; every mirror of the profile when omitted").option("--every <duration>", `how often to ask ${provider} for changes`, "60s").summary("keep syncing both ways until Ctrl-C or --timeout").description(`keep syncing both ways until Ctrl-C or --timeout: on each local save and each ${provider} change; a part changed on both sides is reported and left for mirrors sync --keep`), [`${prefix} mirrors watch`, `${prefix} mirrors watch 1a2b3c4d --every 2m --jsonl`]).action(async (id, args) => {
1134
+ const pollMs = parseDuration(args.every, "--every");
1135
+ if (pollMs < 1e4)
1136
+ throw new CliError("validation_error", "--every must be at least 10s");
1137
+ const chosen = chosenOf(id);
1138
+ const signal = helpers.endsOnStop() ?? new AbortController().signal;
1139
+ const connection = await helpers.connect();
1140
+ const states = /* @__PURE__ */ __name((mirror) => helpers.stateOf(mirror), "states");
1141
+ let token = await connection.startToken();
1142
+ const remoteChanges = /* @__PURE__ */ __name(async () => {
1143
+ let changed;
1144
+ try {
1145
+ const feed = await connection.changes(token);
1146
+ token = feed.cursor;
1147
+ changed = new Set(feed.items.map((item) => item.id));
1148
+ } catch (error) {
1149
+ if (!isCliError(error) || error.details?.reason !== "listing.too-large")
1150
+ throw error;
1151
+ token = await connection.startToken();
1152
+ return "all";
1153
+ }
1154
+ return chosen.filter((mirror) => Object.values(states(mirror).read().entries).some((entry) => changed.has(entry.id))).map((mirror) => mirror.id);
1155
+ }, "remoteChanges");
1156
+ let cycles = 0;
1157
+ for await (const event of watchMirrors((mirrors2) => syncMirrors({ ...syncing(connection), mirrors: mirrors2 }), {
1158
+ mirrors: chosen,
1159
+ signal,
1160
+ kindOf: helpers.kindOf,
1161
+ stateOf: states,
1162
+ remoteChanges,
1163
+ pollMs
1164
+ })) {
1165
+ cycles++;
1166
+ const data = {
1167
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1168
+ triggers: event.triggers,
1169
+ mirrors: event.mirrors,
1170
+ ..."error" in event ? { error: { code: event.error.code, message: event.error.message } } : { results: event.result.items, ...event.result.issues.length ? { issues: event.result.issues } : {} }
1171
+ };
1172
+ helpers.print((format, write) => write(format === "pretty" ? describeCycle(data) : JSON.stringify({ type: "item", data })));
1173
+ }
1174
+ helpers.print((format, write) => {
1175
+ if (format === "pretty")
1176
+ return;
1177
+ const end = listOf("mirrors watch", {
1178
+ items: [],
1179
+ limit: Math.max(1, cycles),
1180
+ has_more: false,
1181
+ paging: "cursor",
1182
+ meta: { complete: true }
1183
+ });
1184
+ for (const record2 of jsonlRecords(end))
1185
+ write(JSON.stringify(record2));
1186
+ });
1187
+ });
1188
+ }, "addDocumentMirrorCommandsDefinition");
1189
+ var describeCycle = /* @__PURE__ */ __name((cycle) => {
1190
+ const time = cycle.at.slice(11, 19);
1191
+ if (cycle.error)
1192
+ return `${time} ${cycle.triggers.join("+")}: ${cycle.error.message}; trying again`;
1193
+ const parts = (cycle.results ?? []).map((result) => `${result.id} ${result.created.length} created, ${result.updated.length} sent, ${result.pulled.length} pulled` + (result.conflicts.length ? `, ${result.conflicts.length} conflicts (mirrors sync ${result.id} --keep \u2026)` : ""));
1194
+ return `${time} ${cycle.triggers.join("+")}: ${parts.join("; ") || "nothing to do"}`;
1195
+ }, "describeCycle");
1196
+ var addDocumentMirrorCommands = honoursDryRun(sharedCommand(addDocumentMirrorCommandsDefinition));
1197
+
1198
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/search.js
1199
+ var notImported = /* @__PURE__ */ __name((app2, folder, { profile, chosen, documents }) => {
1200
+ if (documents > 0)
1201
+ return void 0;
1202
+ return !chosen ? `profile ${profile} has no folders selected, so nothing is imported to search \u2014 ${app2} ${profile} folders add ${folder}, then ${app2} ${profile} sync` : `profile ${profile} has imported no documents yet \u2014 ${app2} ${profile} sync`;
1203
+ }, "notImported");
1204
+ var addDocumentSearchCommandDefinition = /* @__PURE__ */ __name((program, helpers) => {
1205
+ const wording = wordsOf(helpers.words);
1206
+ const { prefix } = wording;
1207
+ return examples(annotate(program.command("search"), { effects: LOCAL_READ }).argument("<query>", "words to look for, and fields such as tag: and date: that every hit must match").description("search imported documents by words, and by meaning when indexed"), [`${prefix} search budget`, `${prefix} search "quarterly plan" --exact --limit 5`]).option("--limit <n>", "how many results to return", positive, 20).option("--page <n>", "which page to return", positive, 1).option("--exact", "match the words exactly: no word forms, no meaning").action(async (query, { page, ...args }) => {
1208
+ const result = await helpers.search(query, {
1209
+ ...args,
1210
+ offset: (page - 1) * args.limit,
1211
+ exact: args.exact ?? false
1212
+ });
1213
+ const hint = notImported(wording.app, wording.text.folderToAdd, helpers.imported());
1214
+ helpers.output(itemOf(hint ? { ...result, not_imported: hint } : result));
1215
+ });
1216
+ }, "addDocumentSearchCommandDefinition");
1217
+ var addDocumentSearchCommand = honoursDryRun(sharedCommand(addDocumentSearchCommandDefinition));
1218
+
1219
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/sync.js
1220
+ var enrichmentOutOfTime = /* @__PURE__ */ __name((embeddings) => {
1221
+ const enrichment = typeof embeddings === "object" && embeddings !== null && "enrichment" in embeddings ? embeddings.enrichment : void 0;
1222
+ return enrichment?.reason_id === "enrichment.deadline" && enrichment.enriched === 0;
1223
+ }, "enrichmentOutOfTime");
1224
+ var addDocumentSyncCommandsDefinition = /* @__PURE__ */ __name((program, helpers) => {
1225
+ const { output } = helpers;
1226
+ const wording = wordsOf(helpers.words);
1227
+ const { prefix, text } = wording;
1228
+ const sync = examples(
1229
+ // Cooperative: it stops on its own at its budget, its deadline or a cancel and keeps its work, so it gets a sync's
1230
+ // deadline (15 min in a terminal, 45 s over MCP) instead of a one-shot's 30 s.
1231
+ annotate(program.command("sync"), { effects: FETCH, cooperative: true, partial: true }).summary("import what changed in the chosen folders, and finish an unfinished sync").description(`import what changed in the chosen folders, and finish an unfinished sync; one sync walks about ${helpers.maxEntries} entries under the chosen folders, saves where it stopped, and the next sync goes on from there`),
1232
+ [`${prefix} sync`, `${prefix} sync --rescan --limit 500`]
1233
+ ).option("--limit <n>", text.syncLimit, positive, 200).option("--rescan", "read every chosen folder again instead of only what changed; each --rescan starts the walk over, so run it once and continue with a plain sync").option("--embed", "also index pending text for meaning search, with a model already downloaded").action(async (args, command) => {
1234
+ const deadline = environmentOf(command).deadline?.();
1235
+ const result = await helpers.sync({ ...args, budget: runBudgetOf(command), ...deadline ? { deadline } : {} });
1236
+ const unfinished = result.complete === false || result.pending > 0;
1237
+ const moved = (result.walk?.listed ?? 0) > 0 || [result.saved, result.names_only, result.removed, result.unchanged].some((count2) => (count2 ?? 0) > 0);
1238
+ const again = `${wording.app} ${helpers.profile()} sync`;
1239
+ const timeout = command.optsWithGlobals().timeout;
1240
+ const resume = unfinished && !result.errors.length && moved ? [
1241
+ {
1242
+ kind: "command",
1243
+ step: "sync.run",
1244
+ command: "sync",
1245
+ args: {
1246
+ limit: args.limit,
1247
+ ...timeout === void 0 ? {} : { timeout },
1248
+ ...args.embed ? { embed: true } : {}
1249
+ },
1250
+ why: "the sync stopped before the end of its pass; running it again goes on from there",
1251
+ safe_to_auto_execute: true
1252
+ }
1253
+ ] : [];
1254
+ const longer = enrichmentOutOfTime(result.embeddings) ? [
1255
+ {
1256
+ kind: "command",
1257
+ step: "sync.longer",
1258
+ command: "sync",
1259
+ args: { limit: args.limit, embed: true, timeout: "15m" },
1260
+ why: "enrichment needs more time than this run had left, so it sent nothing; run this in a terminal, where a sync may take 15 minutes",
1261
+ safe_to_auto_execute: false
1262
+ }
1263
+ ] : [];
1264
+ const next = [...resume, ...longer];
1265
+ output(itemOf(result, {
1266
+ meta: result.errors.length ? {
1267
+ complete: false,
1268
+ issues: [{ code: "provider_error", reason: "sync.partial", source: wording.source }]
1269
+ } : unfinished ? { complete: false } : {},
1270
+ next
1271
+ }));
1272
+ if (result.walk)
1273
+ helpers.diagnostic(`${result.walk.folders_left} folders remain to list; run ${again} again
1274
+ `);
1275
+ else if (result.errors.length || result.pending)
1276
+ helpers.diagnostic(`${result.pending} source operations remain; run ${again} again
1277
+ `);
1278
+ if (result.errors.length)
1279
+ throw new CliError("provider_error", "sync completed partially; failed operations remain pending", {
1280
+ reason: "sync.partial"
1281
+ });
1282
+ });
1283
+ const status = examples(annotate(program.command("status"), { effects: LOCAL_READ }).description("show the last sync, imported documents and pending work"), [`${prefix} status`]).action(async () => {
1284
+ output(itemOf(await helpers.status()));
1285
+ });
1286
+ return [sync, status];
1287
+ }, "addDocumentSyncCommandsDefinition");
1288
+ var addDocumentSyncCommands = honoursDryRun(sharedCommand(addDocumentSyncCommandsDefinition));
1289
+
1290
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/file-edit.js
1291
+ import { createHash } from "node:crypto";
1292
+ import { mkdtemp as mkdtemp2, readFile, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
1293
+ import { tmpdir as tmpdir2 } from "node:os";
1294
+ import { join as join2 } from "node:path";
1295
+
1296
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/office/xml.js
1297
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
1298
+ var ATTRIBUTE = /([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
1299
+ var invalid = /* @__PURE__ */ __name((reason) => new CliError("validation_error", `the file's XML cannot be edited: ${reason}`), "invalid");
1300
+ var decodeEntities = /* @__PURE__ */ __name((raw) => raw.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-z]+);/g, (whole, entity) => {
1301
+ if (entity.startsWith("#x"))
1302
+ return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
1303
+ if (entity.startsWith("#"))
1304
+ return String.fromCodePoint(Number(entity.slice(1)));
1305
+ const value = ENTITIES[entity];
1306
+ if (value === void 0)
1307
+ throw invalid(`unknown entity ${whole}`);
1308
+ return value;
1309
+ }), "decodeEntities");
1310
+ var contentText = /* @__PURE__ */ __name((raw) => raw.split(/(<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->|<\?[\s\S]*?\?>)/).map((part) => part.startsWith("<![CDATA[") ? part.slice(9, -3) : part.startsWith("<!--") || part.startsWith("<?") ? "" : decodeEntities(part)).join(""), "contentText");
1311
+ var storable = /* @__PURE__ */ __name((value) => {
1312
+ for (const character of value) {
1313
+ const code = character.codePointAt(0);
1314
+ if (code < 32 ? ![9, 10, 13].includes(code) : code >= 55296 && code <= 57343 || code === 65534 || code === 65535)
1315
+ return false;
1316
+ }
1317
+ return true;
1318
+ }, "storable");
1319
+ var escapeText = /* @__PURE__ */ __name((value) => {
1320
+ if (!storable(value))
1321
+ throw new CliError("validation_error", "the text holds a character XML cannot store (a control character)");
1322
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1323
+ }, "escapeText");
1324
+ var parseXml = /* @__PURE__ */ __name((text) => {
1325
+ if (/<!DOCTYPE|<!ENTITY/i.test(text))
1326
+ throw invalid("a DOCTYPE");
1327
+ const root = [];
1328
+ const stack = [];
1329
+ for (let index = text.indexOf("<"); index >= 0 && index < text.length; index = text.indexOf("<", index)) {
1330
+ const skip = text.startsWith("<!--", index) ? "-->" : text.startsWith("<![CDATA[", index) ? "]]>" : text.startsWith("<?", index) ? "?>" : void 0;
1331
+ if (skip) {
1332
+ const end = text.indexOf(skip, index);
1333
+ if (end < 0)
1334
+ throw invalid("an unclosed comment or CDATA");
1335
+ index = end + skip.length;
1336
+ continue;
1337
+ }
1338
+ const start = index;
1339
+ let quote2 = "";
1340
+ for (index++; index < text.length; index++) {
1341
+ const char = text[index];
1342
+ if (quote2) {
1343
+ if (char === quote2)
1344
+ quote2 = "";
1345
+ } else if (char === '"' || char === "'")
1346
+ quote2 = char;
1347
+ else if (char === ">")
1348
+ break;
1349
+ }
1350
+ if (index >= text.length)
1351
+ throw invalid("an unclosed tag");
1352
+ index++;
1353
+ const tag = text.slice(start, index);
1354
+ if (tag.startsWith("</")) {
1355
+ const name2 = tag.slice(2, -1).trim();
1356
+ const open = stack.pop();
1357
+ if (!open || open.name !== name2)
1358
+ throw invalid(`a closing </${name2}> without its opening tag`);
1359
+ open.closeStart = start;
1360
+ open.end = index;
1361
+ continue;
1362
+ }
1363
+ const selfClosing = /\/\s*>$/.test(tag);
1364
+ const body = tag.slice(1, selfClosing ? tag.lastIndexOf("/") : -1);
1365
+ const name = /^[^\s/>]+/.exec(body)?.[0];
1366
+ if (!name)
1367
+ throw invalid("a tag without a name");
1368
+ const attributes = /* @__PURE__ */ new Map();
1369
+ for (const match of body.slice(name.length).matchAll(ATTRIBUTE))
1370
+ attributes.set(match[1], decodeEntities(match[2] ?? match[3] ?? ""));
1371
+ const parent = stack.at(-1);
1372
+ const namespaces = new Map(parent?.namespaces ?? [["xml", "http://www.w3.org/XML/1998/namespace"]]);
1373
+ for (const [key, value] of attributes) {
1374
+ if (key === "xmlns")
1375
+ namespaces.set("", value);
1376
+ else if (key.startsWith("xmlns:"))
1377
+ namespaces.set(key.slice(6), value);
1378
+ }
1379
+ const colon = name.indexOf(":");
1380
+ const prefix = colon < 0 ? "" : name.slice(0, colon);
1381
+ const ns = namespaces.get(prefix);
1382
+ if (ns === void 0 && prefix)
1383
+ throw invalid(`an undeclared prefix ${prefix}:`);
1384
+ const element = {
1385
+ name,
1386
+ prefix,
1387
+ local: colon < 0 ? name : name.slice(colon + 1),
1388
+ ns: ns ?? "",
1389
+ attributes,
1390
+ start,
1391
+ openEnd: index,
1392
+ closeStart: index,
1393
+ end: index,
1394
+ children: [],
1395
+ parent,
1396
+ namespaces
1397
+ };
1398
+ (parent ? parent.children : root).push(element);
1399
+ if (!selfClosing)
1400
+ stack.push(element);
1401
+ }
1402
+ if (stack.length || root.length !== 1)
1403
+ throw invalid("unbalanced elements");
1404
+ return root[0];
1405
+ }, "parseXml");
1406
+ var attributeOf = /* @__PURE__ */ __name((element, ns, local2) => {
1407
+ for (const [key, value] of element.attributes) {
1408
+ const colon = key.indexOf(":");
1409
+ if (colon < 0) {
1410
+ if (!ns && key === local2)
1411
+ return value;
1412
+ continue;
1413
+ }
1414
+ if (key.slice(colon + 1) === local2 && element.namespaces.get(key.slice(0, colon)) === ns)
1415
+ return value;
1416
+ }
1417
+ return void 0;
1418
+ }, "attributeOf");
1419
+ var childrenOf = /* @__PURE__ */ __name((element, ns, local2) => element.children.filter((child) => child.ns === ns && child.local === local2), "childrenOf");
1420
+ var descendants = /* @__PURE__ */ __name((element, ns, local2) => {
1421
+ const found = [];
1422
+ const visit = /* @__PURE__ */ __name((current) => {
1423
+ for (const child of current.children) {
1424
+ if (child.ns === ns && child.local === local2)
1425
+ found.push(child);
1426
+ visit(child);
1427
+ }
1428
+ }, "visit");
1429
+ visit(element);
1430
+ return found;
1431
+ }, "descendants");
1432
+ var applySplices = /* @__PURE__ */ __name((text, splices) => {
1433
+ const ordered = splices.map((splice, order) => ({ ...splice, order })).sort((a, b) => a.start - b.start || Number(a.end > a.start) - Number(b.end > b.start) || a.order - b.order);
1434
+ let result = "";
1435
+ let at = 0;
1436
+ for (const splice of ordered) {
1437
+ if (splice.start < at)
1438
+ throw new Error("overlapping_edits");
1439
+ result += text.slice(at, splice.start) + splice.text;
1440
+ at = splice.end;
1441
+ }
1442
+ return result + text.slice(at);
1443
+ }, "applySplices");
1444
+ var decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1445
+ var encoder = new TextEncoder();
1446
+ var partText = /* @__PURE__ */ __name((bytes, path) => {
1447
+ const head = new TextDecoder("latin1").decode(bytes.subarray(0, 100));
1448
+ const declared = /^(?:|)?<\?xml[^>]*encoding\s*=\s*["']([^"']+)["']/.exec(head)?.[1];
1449
+ if (declared && !/^utf-?8$/i.test(declared))
1450
+ throw new CliError("validation_error", `${path} is stored as ${declared}; only UTF-8 parts can be edited`);
1451
+ try {
1452
+ return decoder.decode(bytes);
1453
+ } catch {
1454
+ throw new CliError("validation_error", `${path} is not UTF-8; only UTF-8 parts can be edited`);
1455
+ }
1456
+ }, "partText");
1457
+ var partBytes = /* @__PURE__ */ __name((text) => encoder.encode(text), "partBytes");
1458
+
1459
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/office/zip.js
1460
+ import { crc32 } from "node:zlib";
1461
+ var decoder2 = new TextDecoder();
1462
+ var openPackage = /* @__PURE__ */ __name(async (bytes) => {
1463
+ try {
1464
+ return await readContainer(bytes);
1465
+ } catch (error) {
1466
+ if (error instanceof CliError)
1467
+ throw error;
1468
+ throw new CliError("validation_error", error instanceof ReaderLimit ? "the file is too large to edit (over 50 MB unpacked, 10 MB in one part or 1,000 entries)" : `the file is not a readable Office file (${error instanceof Error ? error.message : String(error)})`);
1469
+ }
1470
+ }, "openPackage");
1471
+ var endRecord = /* @__PURE__ */ __name((view) => {
1472
+ for (let index = view.byteLength - 22; index >= Math.max(0, view.byteLength - 65557); index--)
1473
+ if (view.getUint32(index, true) === 101010256)
1474
+ return index;
1475
+ throw new CliError("validation_error", "the file is not a zip archive");
1476
+ }, "endRecord");
1477
+ var entriesOf = /* @__PURE__ */ __name((bytes) => {
1478
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1479
+ const end = endRecord(view);
1480
+ const count2 = view.getUint16(end + 10, true);
1481
+ const directory = view.getUint32(end + 16, true);
1482
+ const entries = [];
1483
+ let offset = directory;
1484
+ for (let index = 0; index < count2; index++) {
1485
+ const length = view.getUint16(offset + 28, true);
1486
+ const next = offset + 46 + length + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);
1487
+ entries.push({
1488
+ name: decoder2.decode(bytes.subarray(offset + 46, offset + 46 + length)),
1489
+ central: offset,
1490
+ centralEnd: next,
1491
+ local: view.getUint32(offset + 42, true)
1492
+ });
1493
+ offset = next;
1494
+ }
1495
+ return { view, end, directory, entries };
1496
+ }, "entriesOf");
1497
+ var concat = /* @__PURE__ */ __name((parts) => {
1498
+ const result = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
1499
+ let offset = 0;
1500
+ for (const part of parts) {
1501
+ result.set(part, offset);
1502
+ offset += part.length;
1503
+ }
1504
+ return result;
1505
+ }, "concat");
1506
+ var rewriteZip = /* @__PURE__ */ __name((bytes, replaced) => {
1507
+ const { view, end, directory, entries } = entriesOf(bytes);
1508
+ const starts = [...entries.map((entry) => entry.local), directory].sort((a, b) => a - b);
1509
+ const locals = [];
1510
+ const centrals = [];
1511
+ let written = 0;
1512
+ let kept = 0;
1513
+ for (const entry of entries) {
1514
+ const replacement = replaced.get(entry.name);
1515
+ if (replacement === null)
1516
+ continue;
1517
+ const central = bytes.slice(entry.central, entry.centralEnd);
1518
+ const centralView = new DataView(central.buffer);
1519
+ let local2;
1520
+ if (replacement === void 0) {
1521
+ const spanEnd = starts.find((start) => start > entry.local);
1522
+ local2 = bytes.subarray(entry.local, spanEnd);
1523
+ } else {
1524
+ const header = entry.local + 30 + view.getUint16(entry.local + 26, true) + view.getUint16(entry.local + 28, true);
1525
+ const data = deflateSync(replacement, { level: 6 });
1526
+ local2 = concat([bytes.slice(entry.local, header), data]);
1527
+ const localView = new DataView(local2.buffer);
1528
+ for (const [target, base] of [
1529
+ [localView, 0],
1530
+ [centralView, 2]
1531
+ ]) {
1532
+ target.setUint16(base + 6, target.getUint16(base + 6, true) & ~8, true);
1533
+ target.setUint16(base + 8, 8, true);
1534
+ target.setUint32(base + 14, crc32(replacement), true);
1535
+ target.setUint32(base + 18, data.length, true);
1536
+ target.setUint32(base + 22, replacement.length, true);
1537
+ }
1538
+ }
1539
+ centralView.setUint32(42, written, true);
1540
+ locals.push(local2);
1541
+ centrals.push(central);
1542
+ written += local2.length;
1543
+ kept++;
1544
+ }
1545
+ const tail = bytes.slice(end);
1546
+ const tailView = new DataView(tail.buffer);
1547
+ const centralSize = centrals.reduce((sum, part) => sum + part.length, 0);
1548
+ tailView.setUint16(8, kept, true);
1549
+ tailView.setUint16(10, kept, true);
1550
+ tailView.setUint32(12, centralSize, true);
1551
+ tailView.setUint32(16, written, true);
1552
+ return concat([...locals, ...centrals, tail]);
1553
+ }, "rewriteZip");
1554
+
1555
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/office/package.js
1556
+ var REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
1557
+ var STRICT_REL = "http://purl.oclc.org/ooxml/officeDocument/relationships";
1558
+ var unreadable = /* @__PURE__ */ __name((what, error) => error instanceof CliError ? error : new CliError("validation_error", `the file is not a ${what} this editor reads (${error.message})`), "unreadable");
1559
+ var OfficePackage = class _OfficePackage {
1560
+ static {
1561
+ __name(this, "OfficePackage");
1562
+ }
1563
+ bytes;
1564
+ archive;
1565
+ what;
1566
+ changed = /* @__PURE__ */ new Map();
1567
+ constructor(bytes, archive, what) {
1568
+ this.bytes = bytes;
1569
+ this.archive = archive;
1570
+ this.what = what;
1571
+ }
1572
+ static async open(bytes, what) {
1573
+ return new _OfficePackage(bytes, await openPackage(bytes), what);
1574
+ }
1575
+ main(contentType) {
1576
+ try {
1577
+ return mainPart(this.archive, contentType);
1578
+ } catch (error) {
1579
+ throw unreadable(this.what, error);
1580
+ }
1581
+ }
1582
+ relationships(owner) {
1583
+ try {
1584
+ return relationships(this.archive, owner);
1585
+ } catch (error) {
1586
+ throw unreadable(this.what, error);
1587
+ }
1588
+ }
1589
+ related(owner, type) {
1590
+ return [...this.relationships(owner).entries()].find(([, entry]) => entry.type.endsWith(`/${type}`));
1591
+ }
1592
+ has(path) {
1593
+ return this.archive.has(path);
1594
+ }
1595
+ part(path) {
1596
+ const bytes = this.archive.get(path);
1597
+ if (!bytes)
1598
+ throw new CliError("validation_error", `the ${this.what} has no ${path}`);
1599
+ try {
1600
+ xmlPart(this.archive, path);
1601
+ } catch (error) {
1602
+ throw unreadable(this.what, error);
1603
+ }
1604
+ const text = partText(bytes, path);
1605
+ return { path, text, root: parseXml(text) };
1606
+ }
1607
+ write(part, splices) {
1608
+ if (!splices.length)
1609
+ return;
1610
+ const text = applySplices(part.text, splices);
1611
+ const bytes = partBytes(text);
1612
+ const archive = new Map(this.archive);
1613
+ archive.set(part.path, bytes);
1614
+ try {
1615
+ xmlPart(archive, part.path);
1616
+ } catch (error) {
1617
+ throw new Error(`the edit produced invalid XML in ${part.path} (${error.message})`);
1618
+ }
1619
+ this.changed.set(part.path, bytes);
1620
+ }
1621
+ remove(path) {
1622
+ this.changed.set(path, null);
1623
+ }
1624
+ /** The new file: changed parts recompressed, every other entry copied as it was. */
1625
+ build() {
1626
+ return this.changed.size ? rewriteZip(this.bytes, this.changed) : this.bytes.slice();
1627
+ }
1628
+ };
1629
+ var escapeAttribute = /* @__PURE__ */ __name((value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll('"', "&quot;"), "escapeAttribute");
1630
+ var withAttribute = /* @__PURE__ */ __name((tag, name, value) => {
1631
+ const pattern = new RegExp(`(\\s)${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);
1632
+ if (pattern.test(tag))
1633
+ return tag.replace(pattern, `$1${name}="${escapeAttribute(value)}"`);
1634
+ return tag.replace(/\s*(\/?)>$/, ` ${name}="${escapeAttribute(value)}"$1>`);
1635
+ }, "withAttribute");
1636
+ var withoutAttribute = /* @__PURE__ */ __name((tag, name) => tag.replace(new RegExp(`\\s+${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`), ""), "withoutAttribute");
1637
+ var startTag = /* @__PURE__ */ __name((text, element) => text.slice(element.start, element.openEnd), "startTag");
1638
+ var isSelfClosing = /* @__PURE__ */ __name((text, element) => /\/\s*>$/.test(text.slice(element.start, element.openEnd)), "isSelfClosing");
1639
+ var openTag = /* @__PURE__ */ __name((text, element) => {
1640
+ const tag = text.slice(element.start, element.openEnd);
1641
+ return isSelfClosing(text, element) ? tag.replace(/\s*\/\s*>$/, ">") : tag;
1642
+ }, "openTag");
1643
+ var qualified = /* @__PURE__ */ __name((element, local2) => element.prefix ? `${element.prefix}:${local2}` : local2, "qualified");
1644
+
1645
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/office/docx.js
1646
+ var MAIN = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
1647
+ var WORD_NAMESPACES = [
1648
+ "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
1649
+ "http://purl.oclc.org/ooxml/wordprocessingml/main"
1650
+ ];
1651
+ var refuse = /* @__PURE__ */ __name((message, reason) => new CliError("validation_error", message, { reason }), "refuse");
1652
+ var RUN_TEXT = /* @__PURE__ */ new Set(["rPr", "t", "tab", "br", "cr", "noBreakHyphen", "softHyphen", "lastRenderedPageBreak"]);
1653
+ var RUN_REASONS = {
1654
+ drawing: "an image or a drawing",
1655
+ pict: "an image or a drawing",
1656
+ object: "an embedded object",
1657
+ fldChar: "a field",
1658
+ instrText: "a field",
1659
+ footnoteReference: "a footnote reference",
1660
+ endnoteReference: "an endnote reference",
1661
+ footnoteRef: "a footnote mark",
1662
+ endnoteRef: "an endnote mark",
1663
+ commentReference: "a comment",
1664
+ annotationRef: "a comment",
1665
+ delText: "a tracked change",
1666
+ delInstrText: "a tracked change",
1667
+ sym: "a symbol",
1668
+ ruby: "ruby text",
1669
+ ptab: "a positional tab",
1670
+ separator: "a footnote separator",
1671
+ continuationSeparator: "a footnote separator"
1672
+ };
1673
+ var PARAGRAPH_REASONS = {
1674
+ ins: "a tracked change",
1675
+ del: "a tracked change",
1676
+ moveFrom: "a tracked change",
1677
+ moveTo: "a tracked change",
1678
+ moveFromRangeStart: "a tracked change",
1679
+ moveFromRangeEnd: "a tracked change",
1680
+ moveToRangeStart: "a tracked change",
1681
+ moveToRangeEnd: "a tracked change",
1682
+ commentRangeStart: "a comment",
1683
+ commentRangeEnd: "a comment",
1684
+ hyperlink: "a hyperlink",
1685
+ fldSimple: "a field",
1686
+ sdt: "a content control",
1687
+ smartTag: "a smart tag",
1688
+ customXml: "custom XML markup",
1689
+ subDoc: "a subdocument",
1690
+ oMath: "an equation",
1691
+ oMathPara: "an equation"
1692
+ };
1693
+ var MARKERS = /* @__PURE__ */ new Set(["bookmarkStart", "bookmarkEnd", "permStart", "permEnd"]);
1694
+ var TRACKED_PROPERTIES = /* @__PURE__ */ new Set(["pPrChange", "rPrChange", "ins", "del", "moveFrom", "moveTo"]);
1695
+ var CONTAINERS = /* @__PURE__ */ new Set(["tbl", "tr", "tc", "sdt", "sdtContent", "customXml"]);
1696
+ var hasTracked = /* @__PURE__ */ __name((element) => !!element?.children.some((child) => TRACKED_PROPERTIES.has(child.local) || hasTracked(child)), "hasTracked");
1697
+ var Document = class _Document {
1698
+ static {
1699
+ __name(this, "Document");
1700
+ }
1701
+ pack;
1702
+ ns;
1703
+ part;
1704
+ found = [];
1705
+ styles = /* @__PURE__ */ new Map();
1706
+ constructor(pack) {
1707
+ this.pack = pack;
1708
+ this.part = pack.part(pack.main(MAIN));
1709
+ const root = this.part.root;
1710
+ this.ns = root.ns;
1711
+ if (root.local !== "document" || !WORD_NAMESPACES.includes(this.ns))
1712
+ throw refuse("the file is not a Word document", "office.wrong_format");
1713
+ const body = childrenOf(root, this.ns, "body")[0];
1714
+ if (!body)
1715
+ throw refuse("the document has no body", "office.wrong_format");
1716
+ this.walk(body, "body", false);
1717
+ const styles = pack.related(this.part.path, "styles");
1718
+ if (styles && pack.has(styles[1].path)) {
1719
+ const part = pack.part(styles[1].path);
1720
+ for (const style of childrenOf(part.root, this.ns, "style")) {
1721
+ const id = attributeOf(style, this.ns, "styleId");
1722
+ const name = childrenOf(style, this.ns, "name")[0];
1723
+ if (id && name)
1724
+ this.styles.set(id, attributeOf(name, this.ns, "val") ?? id);
1725
+ }
1726
+ }
1727
+ }
1728
+ static async open(bytes) {
1729
+ return new _Document(await OfficePackage.open(bytes, "Word document"));
1730
+ }
1731
+ walk(container, location, locked) {
1732
+ for (const child of container.children) {
1733
+ if (child.ns !== this.ns)
1734
+ continue;
1735
+ if (child.local === "p")
1736
+ this.found.push({ element: child, location, lockedControl: locked });
1737
+ else if (CONTAINERS.has(child.local)) {
1738
+ const properties = child.local === "sdt" ? childrenOf(child, this.ns, "sdtPr")[0] : void 0;
1739
+ const lock = properties && childrenOf(properties, this.ns, "lock")[0];
1740
+ const lockValue = lock && attributeOf(lock, this.ns, "val");
1741
+ const controlLocked = !!properties && (lockValue === "contentLocked" || lockValue === "sdtContentLocked" || properties.children.some((entry) => entry.local === "dataBinding"));
1742
+ this.walk(child, child.local === "tbl" ? "table" : location, locked || controlLocked);
1743
+ }
1744
+ }
1745
+ }
1746
+ raw(element) {
1747
+ return this.part.text.slice(element.start, element.end);
1748
+ }
1749
+ /** Why a paragraph cannot be rewritten, or undefined when it holds only plain runs. */
1750
+ reasonOf(found) {
1751
+ if (found.lockedControl)
1752
+ return "it sits in a locked or data-bound content control";
1753
+ for (const child of found.element.children) {
1754
+ if (child.ns !== this.ns)
1755
+ return child.local === "AlternateContent" ? "an image or a drawing" : `<${child.name}>`;
1756
+ if (child.local === "pPr") {
1757
+ if (hasTracked(child))
1758
+ return "a tracked change";
1759
+ continue;
1760
+ }
1761
+ if (child.local === "proofErr" || MARKERS.has(child.local))
1762
+ continue;
1763
+ if (child.local !== "r")
1764
+ return PARAGRAPH_REASONS[child.local] ?? `<${child.name}>`;
1765
+ for (const part of child.children) {
1766
+ if (part.ns !== this.ns)
1767
+ return part.local === "AlternateContent" ? "an image or a drawing" : `<${part.name}>`;
1768
+ if (part.local === "rPr" && hasTracked(part))
1769
+ return "a tracked change";
1770
+ if (part.local === "br" && ["page", "column"].includes(attributeOf(part, this.ns, "type") ?? ""))
1771
+ return "a page or column break";
1772
+ if (!RUN_TEXT.has(part.local))
1773
+ return RUN_REASONS[part.local] ?? `<${part.name}>`;
1774
+ }
1775
+ }
1776
+ return void 0;
1777
+ }
1778
+ textOf(element) {
1779
+ let text = "";
1780
+ for (const child of element.children) {
1781
+ if (child.ns !== this.ns)
1782
+ continue;
1783
+ if (child.local === "t")
1784
+ text += contentText(this.part.text.slice(child.openEnd, child.closeStart));
1785
+ else if (child.local === "tab")
1786
+ text += " ";
1787
+ else if (child.local === "br" || child.local === "cr")
1788
+ text += "\n";
1789
+ else if (child.local === "noBreakHyphen")
1790
+ text += "\u2011";
1791
+ else if (child.local === "softHyphen")
1792
+ text += "\xAD";
1793
+ else if (!["pPr", "rPr", "del", "moveFrom", "drawing", "pict", "object", "instrText"].includes(child.local))
1794
+ text += this.textOf(child);
1795
+ }
1796
+ return text;
1797
+ }
1798
+ runs(element) {
1799
+ return childrenOf(element, this.ns, "r");
1800
+ }
1801
+ /** The formatting a rewritten paragraph's single run takes: the first run that holds text. */
1802
+ firstRunProperties(element) {
1803
+ const runs = this.runs(element);
1804
+ const run = runs.find((candidate) => this.textOf(candidate) !== "") ?? runs[0];
1805
+ const properties = run && childrenOf(run, this.ns, "rPr")[0];
1806
+ return properties ? this.raw(properties) : "";
1807
+ }
1808
+ mixed(element) {
1809
+ const formats = new Set(this.runs(element).filter((run) => this.textOf(run) !== "").map((run) => {
1810
+ const properties = childrenOf(run, this.ns, "rPr")[0];
1811
+ return properties ? this.raw(properties) : "";
1812
+ }));
1813
+ return formats.size > 1;
1814
+ }
1815
+ paragraphs() {
1816
+ return this.found.map((found, index) => {
1817
+ const element = found.element;
1818
+ const properties = childrenOf(element, this.ns, "pPr")[0];
1819
+ const styleElement = properties && childrenOf(properties, this.ns, "pStyle")[0];
1820
+ const styleId = styleElement && attributeOf(styleElement, this.ns, "val");
1821
+ const reason = this.reasonOf(found);
1822
+ const style = styleId && this.styles.get(styleId);
1823
+ return {
1824
+ index,
1825
+ text: this.textOf(element),
1826
+ ...styleId ? { styleId } : {},
1827
+ ...style ? { style } : {},
1828
+ location: found.location,
1829
+ editable: reason === void 0,
1830
+ ...reason === void 0 ? {} : {
1831
+ reason: reason.startsWith("<") ? `unsupported element ${reason}` : reason.startsWith("it ") ? reason : `it holds ${reason}`
1832
+ },
1833
+ mixedFormatting: this.mixed(element)
1834
+ };
1835
+ });
1836
+ }
1837
+ /** The paragraph properties without a section break, which must not be copied into a new paragraph. */
1838
+ propertiesForCopy(element) {
1839
+ const properties = childrenOf(element, this.ns, "pPr")[0];
1840
+ if (!properties)
1841
+ return "";
1842
+ if (hasTracked(properties))
1843
+ throw refuse("the paragraph to copy the style from holds a tracked change", "office.tracked_change");
1844
+ let raw = this.raw(properties);
1845
+ for (const section of childrenOf(properties, this.ns, "sectPr").reverse())
1846
+ raw = raw.slice(0, section.start - properties.start) + raw.slice(section.end - properties.start);
1847
+ return raw;
1848
+ }
1849
+ runsXml(element, text, runProperties) {
1850
+ if (!text)
1851
+ return "";
1852
+ const r = qualified(element, "r");
1853
+ const t = qualified(element, "t");
1854
+ const content = text.split(/(\n|\t)/).filter((piece) => piece !== "").map((piece) => piece === "\n" ? `<${qualified(element, "br")}/>` : piece === " " ? `<${qualified(element, "tab")}/>` : `<${t} xml:space="preserve">${escapeText(piece)}</${t}>`).join("");
1855
+ return `<${r}>${runProperties}${content}</${r}>`;
1856
+ }
1857
+ rewritten(element, text) {
1858
+ const properties = childrenOf(element, this.ns, "pPr")[0];
1859
+ const markers = element.children.filter((child) => child.ns === this.ns && MARKERS.has(child.local));
1860
+ const starts = markers.filter((marker) => marker.local.endsWith("Start")).map((marker) => this.raw(marker));
1861
+ const ends = markers.filter((marker) => marker.local.endsWith("End")).map((marker) => this.raw(marker));
1862
+ return `${openTag(this.part.text, element)}${properties ? this.raw(properties) : ""}${starts.join("")}${this.runsXml(element, text, this.firstRunProperties(element))}${ends.join("")}</${element.name}>`;
1863
+ }
1864
+ };
1865
+ var readDocxParagraphs = /* @__PURE__ */ __name(async (bytes) => (await Document.open(bytes)).paragraphs(), "readDocxParagraphs");
1866
+ var normalized = /* @__PURE__ */ __name((text) => text.replace(/\r\n?/g, "\n"), "normalized");
1867
+ var editDocxParagraphs = /* @__PURE__ */ __name(async (bytes, edits) => {
1868
+ const document = await Document.open(bytes);
1869
+ const { found } = document;
1870
+ const infos = document.paragraphs();
1871
+ const check = /* @__PURE__ */ __name((index, what) => {
1872
+ if (!Number.isInteger(index) || index < 0 || index >= found.length)
1873
+ throw refuse(`${what} ${index} does not exist; the document has ${found.length} paragraphs`, "office.no_paragraph");
1874
+ return found[index];
1875
+ }, "check");
1876
+ const editable = /* @__PURE__ */ __name((index, action) => {
1877
+ const info = infos[index];
1878
+ if (!info.editable)
1879
+ throw refuse(`paragraph ${index} cannot be ${action}: ${info.reason}`, "office.unsafe_paragraph");
1880
+ }, "editable");
1881
+ const touched = /* @__PURE__ */ new Set();
1882
+ const once = /* @__PURE__ */ __name((index) => {
1883
+ if (touched.has(index))
1884
+ throw refuse(`paragraph ${index} is changed twice in one call`, "office.duplicate_edit");
1885
+ touched.add(index);
1886
+ }, "once");
1887
+ const splices = [];
1888
+ const replaced = [];
1889
+ const deleted = [];
1890
+ const collapsed = [];
1891
+ const expected = infos.map((info) => info.text);
1892
+ const insertedAfter = /* @__PURE__ */ new Map();
1893
+ let inserted = 0;
1894
+ for (const edit of edits) {
1895
+ if ("delete" in edit) {
1896
+ const target = check(edit.delete, "paragraph");
1897
+ once(edit.delete);
1898
+ editable(edit.delete, "deleted");
1899
+ const properties = childrenOf(target.element, document.ns, "pPr")[0];
1900
+ if (properties && childrenOf(properties, document.ns, "sectPr").length)
1901
+ throw refuse(`paragraph ${edit.delete} ends a section; deleting it would merge two sections`, "office.section_break");
1902
+ if (target.element.children.some((child) => MARKERS.has(child.local)))
1903
+ throw refuse(`paragraph ${edit.delete} holds a bookmark that a cross-reference may point at`, "office.bookmark");
1904
+ splices.push({ start: target.element.start, end: target.element.end, text: "" });
1905
+ deleted.push(edit.delete);
1906
+ expected[edit.delete] = void 0;
1907
+ } else if ("index" in edit) {
1908
+ const target = check(edit.index, "paragraph");
1909
+ once(edit.index);
1910
+ editable(edit.index, "replaced");
1911
+ const text = normalized(edit.text);
1912
+ splices.push({
1913
+ start: target.element.start,
1914
+ end: target.element.end,
1915
+ text: document.rewritten(target.element, text)
1916
+ });
1917
+ replaced.push(edit.index);
1918
+ if (infos[edit.index].mixedFormatting)
1919
+ collapsed.push(edit.index);
1920
+ expected[edit.index] = text;
1921
+ } else {
1922
+ if (edit.insertAfter !== -1)
1923
+ check(edit.insertAfter, "paragraph");
1924
+ if (!found.length)
1925
+ throw refuse("the document has no paragraph to insert next to", "office.no_paragraph");
1926
+ const neighbour = found[Math.max(0, edit.insertAfter)];
1927
+ if (neighbour.lockedControl)
1928
+ throw refuse(`paragraph ${edit.insertAfter} sits in a locked content control`, "office.unsafe_paragraph");
1929
+ const source = check(edit.styleFrom ?? Math.max(0, edit.insertAfter), "styleFrom paragraph").element;
1930
+ const element = neighbour.element;
1931
+ const text = normalized(edit.text);
1932
+ const p = qualified(element, "p");
1933
+ const xml = `<${p}>${document.propertiesForCopy(source)}${document.runsXml(element, text, document.firstRunProperties(source))}</${p}>`;
1934
+ const at = edit.insertAfter === -1 ? element.start : element.end;
1935
+ splices.push({ start: at, end: at, text: xml });
1936
+ insertedAfter.set(edit.insertAfter, [...insertedAfter.get(edit.insertAfter) ?? [], text]);
1937
+ inserted++;
1938
+ }
1939
+ }
1940
+ const containers = new Set(deleted.map((index) => found[index]?.element.parent));
1941
+ for (const container of containers) {
1942
+ if (!container || !["tc", "body"].includes(container.local))
1943
+ continue;
1944
+ const blocks = container.children.filter((child) => child.ns === document.ns && ["p", "tbl", "sdt", "customXml"].includes(child.local));
1945
+ const remaining = blocks.filter((block) => !deleted.includes(found.findIndex((entry) => entry.element === block)));
1946
+ const addsAtEnd = found.some((entry, index) => insertedAfter.has(index) && entry.element === blocks.at(-1));
1947
+ if (!addsAtEnd && remaining.at(-1)?.local !== "p")
1948
+ throw refuse(`${container.local === "tc" ? "a table cell" : "the document"} must end with a paragraph; this delete would leave it without one`, "office.last_paragraph");
1949
+ }
1950
+ if (!edits.length)
1951
+ return { bytes: bytes.slice(), replaced, inserted, deleted, collapsed };
1952
+ document.pack.write(document.part, splices);
1953
+ const output = document.pack.build();
1954
+ const after = (await readDocxParagraphs(output)).map((paragraph) => paragraph.text);
1955
+ const want = [
1956
+ ...insertedAfter.get(-1) ?? [],
1957
+ ...expected.flatMap((text, index) => [...text === void 0 ? [] : [text], ...insertedAfter.get(index) ?? []])
1958
+ ];
1959
+ if (after.length !== want.length || after.some((text, index) => text !== want[index]))
1960
+ throw new Error("the edited document does not read back as written");
1961
+ return { bytes: output, replaced, inserted, deleted, collapsed };
1962
+ }, "editDocxParagraphs");
1963
+
1964
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/office/xlsx.js
1965
+ var MAIN2 = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
1966
+ var SHEET_NAMESPACES = [
1967
+ "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
1968
+ "http://purl.oclc.org/ooxml/spreadsheetml/main"
1969
+ ];
1970
+ var CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
1971
+ var PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
1972
+ var AFTER_CALC = [
1973
+ "oleSize",
1974
+ "customWorkbookViews",
1975
+ "pivotCaches",
1976
+ "smartTagPr",
1977
+ "smartTagTypes",
1978
+ "webPublishing",
1979
+ "fileRecoveryPr",
1980
+ "webPublishObjects",
1981
+ "extLst"
1982
+ ];
1983
+ var MAX_ROW = 1048576;
1984
+ var MAX_COLUMN = 16384;
1985
+ var refuse2 = /* @__PURE__ */ __name((message, reason) => new CliError("validation_error", message, { reason }), "refuse");
1986
+ var parseAddress = /* @__PURE__ */ __name((address) => {
1987
+ const match = /^([A-Z]{1,3})([1-9]\d{0,6})$/.exec(address.toUpperCase());
1988
+ const column = match ? [...match[1]].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0) : 0;
1989
+ const row = Number(match?.[2]);
1990
+ if (!match || column > MAX_COLUMN || row > MAX_ROW)
1991
+ throw refuse2(`${address} is not a cell address like B7`, "office.invalid_cell");
1992
+ return { row, column };
1993
+ }, "parseAddress");
1994
+ var parseRange = /* @__PURE__ */ __name((range) => {
1995
+ const [from, to = from] = range.split(":");
1996
+ const start = parseAddress(from);
1997
+ const end = parseAddress(to);
1998
+ return {
1999
+ top: Math.min(start.row, end.row),
2000
+ bottom: Math.max(start.row, end.row),
2001
+ left: Math.min(start.column, end.column),
2002
+ right: Math.max(start.column, end.column)
2003
+ };
2004
+ }, "parseRange");
2005
+ var Workbook = class _Workbook {
2006
+ static {
2007
+ __name(this, "Workbook");
2008
+ }
2009
+ pack;
2010
+ path;
2011
+ ns;
2012
+ workbook;
2013
+ sheets;
2014
+ strings;
2015
+ /** Whether each shared string is one plain `t`, so a new cell may point at it without taking rich runs along. */
2016
+ plainStrings;
2017
+ sharedPath;
2018
+ calcChain;
2019
+ constructor(pack, path) {
2020
+ this.pack = pack;
2021
+ this.path = path;
2022
+ this.workbook = pack.part(path);
2023
+ this.ns = this.workbook.root.ns;
2024
+ if (this.workbook.root.local !== "workbook" || !SHEET_NAMESPACES.includes(this.ns))
2025
+ throw refuse2("the file is not an Excel workbook", "office.wrong_format");
2026
+ const rels = pack.relationships(path);
2027
+ const sheetsElement = childrenOf(this.workbook.root, this.ns, "sheets")[0];
2028
+ this.sheets = (sheetsElement ? childrenOf(sheetsElement, this.ns, "sheet") : []).map((sheet) => {
2029
+ const id = attributeOf(sheet, REL, "id") ?? attributeOf(sheet, STRICT_REL, "id") ?? "";
2030
+ const target = rels.get(id);
2031
+ if (!target?.type.endsWith("/worksheet"))
2032
+ throw refuse2("a sheet of the workbook is not a worksheet (a chart sheet or a missing part)", "office.wrong_format");
2033
+ return { name: attributeOf(sheet, "", "name") ?? "", path: target.path };
2034
+ });
2035
+ const shared = pack.related(path, "sharedStrings");
2036
+ this.sharedPath = shared && pack.has(shared[1].path) ? shared[1].path : void 0;
2037
+ const sharedPart = this.sharedPath ? pack.part(this.sharedPath) : void 0;
2038
+ const entries = sharedPart ? childrenOf(sharedPart.root, this.ns, "si") : [];
2039
+ this.strings = entries.map((entry) => sharedText(entry, this.ns, sharedPart?.text ?? ""));
2040
+ this.plainStrings = entries.map((entry) => entry.children.length === 1 && entry.children[0]?.local === "t");
2041
+ const chain = pack.related(path, "calcChain");
2042
+ if (chain)
2043
+ this.calcChain = { id: chain[0], path: chain[1].path };
2044
+ }
2045
+ static async open(bytes) {
2046
+ const pack = await OfficePackage.open(bytes, "workbook");
2047
+ return new _Workbook(pack, pack.main(MAIN2));
2048
+ }
2049
+ sheet(name) {
2050
+ const found = this.sheets.find((sheet) => sheet.name === name);
2051
+ if (!found)
2052
+ throw refuse2(`the workbook has no sheet "${name}"; it has ${this.sheets.map((sheet) => `"${sheet.name}"`).join(", ")}`, "office.no_sheet");
2053
+ return found;
2054
+ }
2055
+ };
2056
+ var sharedText = /* @__PURE__ */ __name((entry, ns, text) => {
2057
+ const parts = [];
2058
+ const visit = /* @__PURE__ */ __name((element) => {
2059
+ for (const child of element.children) {
2060
+ if (child.ns !== ns || child.local === "rPh")
2061
+ continue;
2062
+ if (child.local === "t")
2063
+ parts.push(contentText(text.slice(child.openEnd, child.closeStart)));
2064
+ else
2065
+ visit(child);
2066
+ }
2067
+ }, "visit");
2068
+ visit(entry);
2069
+ return parts.join("");
2070
+ }, "sharedText");
2071
+ var rowsOf = /* @__PURE__ */ __name((sheetData, ns) => {
2072
+ let previous = 0;
2073
+ return childrenOf(sheetData, ns, "row").map((row) => {
2074
+ const raw = attributeOf(row, "", "r");
2075
+ const number2 = raw ? Number(raw) : previous + 1;
2076
+ previous = number2;
2077
+ let column = 0;
2078
+ const cells = childrenOf(row, ns, "c").map((cell) => {
2079
+ const reference = attributeOf(cell, "", "r");
2080
+ if (reference) {
2081
+ const address = parseAddress(reference);
2082
+ if (address.row !== number2)
2083
+ throw refuse2(`cell ${reference} sits in row ${number2}`, "office.wrong_format");
2084
+ column = address.column;
2085
+ } else
2086
+ column++;
2087
+ return { element: cell, row: number2, column };
2088
+ });
2089
+ return { element: row, row: number2, explicit: raw !== void 0, cells };
2090
+ });
2091
+ }, "rowsOf");
2092
+ var cellOf = /* @__PURE__ */ __name((workbook, text, node) => {
2093
+ const { ns } = workbook;
2094
+ const element = node.element;
2095
+ const type = attributeOf(element, "", "t") ?? "n";
2096
+ const inner = /* @__PURE__ */ __name((local2) => {
2097
+ const child = childrenOf(element, ns, local2)[0];
2098
+ return child ? contentText(text.slice(child.openEnd, child.closeStart)) : void 0;
2099
+ }, "inner");
2100
+ const saved = inner("v");
2101
+ const formulaElement = childrenOf(element, ns, "f")[0];
2102
+ const formula = formulaElement ? contentText(text.slice(formulaElement.openEnd, formulaElement.closeStart)) : void 0;
2103
+ let value = null;
2104
+ let kind = "empty";
2105
+ if (type === "inlineStr") {
2106
+ const is = childrenOf(element, ns, "is")[0];
2107
+ value = is ? descendants(is, ns, "t").filter((t) => t.parent?.local !== "rPh").map((t) => contentText(text.slice(t.openEnd, t.closeStart))).join("") : "";
2108
+ kind = "string";
2109
+ } else if (saved !== void 0) {
2110
+ if (type === "s") {
2111
+ const string2 = workbook.strings[Number(saved)];
2112
+ if (!/^\d+$/.test(saved) || string2 === void 0)
2113
+ throw refuse2(`cell ${columnName(node.column)}${node.row} points at a missing shared string`, "office.wrong_format");
2114
+ value = string2;
2115
+ kind = "string";
2116
+ } else if (type === "str") {
2117
+ value = saved;
2118
+ kind = "string";
2119
+ } else if (type === "b") {
2120
+ value = saved === "1" || saved === "true";
2121
+ kind = "boolean";
2122
+ } else if (type === "e") {
2123
+ value = saved;
2124
+ kind = "error";
2125
+ } else if (type === "d") {
2126
+ value = saved;
2127
+ kind = "date";
2128
+ } else if (saved !== "") {
2129
+ value = Number(saved);
2130
+ kind = "number";
2131
+ }
2132
+ }
2133
+ return {
2134
+ address: `${columnName(node.column)}${node.row}`,
2135
+ row: node.row,
2136
+ column: node.column,
2137
+ value,
2138
+ type: kind,
2139
+ ...formulaElement ? { formula: formula ?? "" } : {},
2140
+ style: Number(attributeOf(element, "", "s") ?? 0)
2141
+ };
2142
+ }, "cellOf");
2143
+ var sheetDataOf = /* @__PURE__ */ __name((part, ns) => {
2144
+ if (part.root.local !== "worksheet" || part.root.ns !== ns)
2145
+ throw refuse2(`${part.path} is not a worksheet`, "office.wrong_format");
2146
+ const sheetData = childrenOf(part.root, ns, "sheetData")[0];
2147
+ if (!sheetData)
2148
+ throw refuse2(`${part.path} has no cell data`, "office.wrong_format");
2149
+ return sheetData;
2150
+ }, "sheetDataOf");
2151
+ var readXlsxCells = /* @__PURE__ */ __name(async (bytes, options = {}) => {
2152
+ const workbook = await Workbook.open(bytes);
2153
+ const range = options.range ? parseRange(options.range) : void 0;
2154
+ const wanted = options.sheet === void 0 ? workbook.sheets : [workbook.sheet(options.sheet)];
2155
+ return wanted.map((sheet) => {
2156
+ const part = workbook.pack.part(sheet.path);
2157
+ const cells = rowsOf(sheetDataOf(part, workbook.ns), workbook.ns).flatMap((row) => row.cells).filter((cell) => !range || cell.row >= range.top && cell.row <= range.bottom && cell.column >= range.left && cell.column <= range.right).map((cell) => cellOf(workbook, part.text, cell));
2158
+ return { name: sheet.name, cells };
2159
+ });
2160
+ }, "readXlsxCells");
2161
+ var SharedStrings = class {
2162
+ static {
2163
+ __name(this, "SharedStrings");
2164
+ }
2165
+ workbook;
2166
+ added = [];
2167
+ references = 0;
2168
+ plain = /* @__PURE__ */ new Map();
2169
+ constructor(workbook) {
2170
+ this.workbook = workbook;
2171
+ workbook.strings.forEach((value, index) => {
2172
+ if (workbook.plainStrings[index] && !this.plain.has(value))
2173
+ this.plain.set(value, index);
2174
+ });
2175
+ }
2176
+ index(value) {
2177
+ this.references++;
2178
+ const known = this.plain.get(value);
2179
+ if (known !== void 0)
2180
+ return known;
2181
+ const index = this.workbook.strings.length + this.added.length;
2182
+ this.added.push(value);
2183
+ this.plain.set(value, index);
2184
+ return index;
2185
+ }
2186
+ release() {
2187
+ this.references--;
2188
+ }
2189
+ write() {
2190
+ const path = this.workbook.sharedPath;
2191
+ if (!path || !this.added.length && !this.references)
2192
+ return;
2193
+ const part = this.workbook.pack.part(path);
2194
+ const root = part.root;
2195
+ const si = qualified(root, "si");
2196
+ const t = qualified(root, "t");
2197
+ const entries = this.added.map((value) => `<${si}><${t} xml:space="preserve">${escapeText(value)}</${t}></${si}>`).join("");
2198
+ let tag = openTag(part.text, root);
2199
+ const count2 = attributeOf(root, "", "count");
2200
+ const unique = attributeOf(root, "", "uniqueCount");
2201
+ if (count2 !== void 0)
2202
+ tag = withAttribute(tag, "count", String(Math.max(0, Number(count2) + this.references)));
2203
+ if (unique !== void 0)
2204
+ tag = withAttribute(tag, "uniqueCount", String(Number(unique) + this.added.length));
2205
+ const splices = [{ start: root.start, end: root.openEnd, text: tag }];
2206
+ if (isSelfClosing(part.text, root))
2207
+ splices.push({ start: root.openEnd, end: root.openEnd, text: `${entries}</${root.name}>` });
2208
+ else
2209
+ splices.push({ start: root.closeStart, end: root.closeStart, text: entries });
2210
+ this.workbook.pack.write(part, splices);
2211
+ }
2212
+ };
2213
+ var valueXml = /* @__PURE__ */ __name((cell, value, strings) => {
2214
+ const v = qualified(cell, "v");
2215
+ if (value === null)
2216
+ return { type: void 0, content: "" };
2217
+ if (typeof value === "boolean")
2218
+ return { type: "b", content: `<${v}>${value ? 1 : 0}</${v}>` };
2219
+ if (typeof value === "number") {
2220
+ if (!Number.isFinite(value))
2221
+ throw refuse2("a cell number must be finite", "office.invalid_value");
2222
+ return { type: void 0, content: `<${v}>${String(value)}</${v}>` };
2223
+ }
2224
+ if (strings)
2225
+ return { type: "s", content: `<${v}>${strings.index(value)}</${v}>` };
2226
+ const is = qualified(cell, "is");
2227
+ const t = qualified(cell, "t");
2228
+ return { type: "inlineStr", content: `<${is}><${t} xml:space="preserve">${escapeText(value)}</${t}></${is}>` };
2229
+ }, "valueXml");
2230
+ var cellTag = /* @__PURE__ */ __name((text, cell, type) => {
2231
+ let tag = withoutAttribute(withoutAttribute(startTag(text, cell), "t"), "cm");
2232
+ if (type)
2233
+ tag = withAttribute(tag, "t", type);
2234
+ return tag.replace(/\s*\/\s*>$/, ">");
2235
+ }, "cellTag");
2236
+ var arrayRanges = /* @__PURE__ */ __name((rows, ns, text) => rows.flatMap((row) => row.cells.flatMap((cell) => {
2237
+ const formula = childrenOf(cell.element, ns, "f")[0];
2238
+ const ref = formula && attributeOf(formula, "", "ref");
2239
+ return formula && ref && attributeOf(formula, "", "t") === "array" ? [{ master: cell, range: parseRange(ref), text: text.slice(formula.start, formula.end) }] : [];
2240
+ })), "arrayRanges");
2241
+ var tableLabels = /* @__PURE__ */ __name((workbook, sheet) => {
2242
+ const { pack } = workbook;
2243
+ if (!pack.has(sheet.path.replace(/([^/]+)$/, "_rels/$1.rels")))
2244
+ return [];
2245
+ return [...pack.relationships(sheet.path).values()].filter((entry) => entry.type.endsWith("/table") && pack.has(entry.path)).flatMap((entry) => {
2246
+ const table = pack.part(entry.path).root;
2247
+ const ref = attributeOf(table, "", "ref");
2248
+ if (!ref)
2249
+ return [];
2250
+ const range = parseRange(ref);
2251
+ const name = attributeOf(table, "", "displayName") ?? attributeOf(table, "", "name") ?? "";
2252
+ const header = Number(attributeOf(table, "", "headerRowCount") ?? 1);
2253
+ const totals = Number(attributeOf(table, "", "totalsRowCount") ?? 0);
2254
+ return [
2255
+ ...header > 0 ? [{ ...range, bottom: range.top + header - 1, kind: "header cell", table: name }] : [],
2256
+ ...totals > 0 ? [{ ...range, top: range.bottom - totals + 1, kind: "totals cell", table: name }] : []
2257
+ ];
2258
+ });
2259
+ }, "tableLabels");
2260
+ var editSheet = /* @__PURE__ */ __name((workbook, sheet, planned, options, strings) => {
2261
+ const { ns, pack } = workbook;
2262
+ const part = pack.part(sheet.path);
2263
+ const { text } = part;
2264
+ const sheetData = sheetDataOf(part, ns);
2265
+ const rows = rowsOf(sheetData, ns);
2266
+ const arrays = arrayRanges(rows, ns, text);
2267
+ for (const label of tableLabels(workbook, sheet))
2268
+ for (const item of planned)
2269
+ if (item.row >= label.top && item.row <= label.bottom && item.column >= label.left && item.column <= label.right)
2270
+ throw refuse2(`${sheet.name}!${item.address} is a ${label.kind} of the table "${label.table}", whose part repeats the text; change it in Excel`, "office.table_header");
2271
+ const splices = [];
2272
+ const changed = [];
2273
+ let formulaRemoved = false;
2274
+ const byRow = /* @__PURE__ */ new Map();
2275
+ for (const item of planned)
2276
+ byRow.set(item.row, [...byRow.get(item.row) ?? [], item]);
2277
+ const newCell = /* @__PURE__ */ __name((item, style) => {
2278
+ const { type, content } = valueXml(sheetData, item.edit.value, strings);
2279
+ const c = qualified(sheetData, "c");
2280
+ const attributes = `r="${item.address}"${style ? ` s="${style}"` : ""}${type ? ` t="${type}"` : ""}`;
2281
+ return content ? `<${c} ${attributes}>${content}</${c}>` : `<${c} ${attributes}/>`;
2282
+ }, "newCell");
2283
+ for (const [rowNumber, items] of [...byRow].sort(([a], [b]) => a - b)) {
2284
+ items.sort((a, b) => a.column - b.column);
2285
+ const row = rows.find((candidate) => candidate.row === rowNumber);
2286
+ if (!row) {
2287
+ if (rows.some((candidate) => !candidate.explicit))
2288
+ throw refuse2(`${sheet.name} has rows without numbers, so row ${rowNumber} cannot be added`, "office.implicit_rows");
2289
+ const next = rows.find((candidate) => candidate.row > rowNumber);
2290
+ const r = qualified(sheetData, "row");
2291
+ const xml = `<${r} r="${rowNumber}">${items.map((item) => newCell(item)).join("")}</${r}>`;
2292
+ for (const item of items)
2293
+ changed.push({ sheet: sheet.name, cell: item.address, before: null, after: item.edit.value, created: true });
2294
+ if (next)
2295
+ splices.push({ start: next.element.start, end: next.element.start, text: xml });
2296
+ else if (isSelfClosing(text, sheetData))
2297
+ splices.push({
2298
+ start: sheetData.start,
2299
+ end: sheetData.end,
2300
+ text: `${openTag(text, sheetData)}${xml}</${sheetData.name}>`
2301
+ });
2302
+ else
2303
+ splices.push({ start: sheetData.closeStart, end: sheetData.closeStart, text: xml });
2304
+ continue;
2305
+ }
2306
+ const inserts = [];
2307
+ const rowStyle = attributeOf(row.element, "", "customFormat") === "1" ? attributeOf(row.element, "", "s") : void 0;
2308
+ for (const item of items) {
2309
+ const existing = row.cells.find((cell) => cell.column === item.column);
2310
+ if (!existing) {
2311
+ if (row.cells.some((cell) => attributeOf(cell.element, "", "r") === void 0))
2312
+ throw refuse2(`row ${rowNumber} of ${sheet.name} has cells without addresses, so ${item.address} cannot be added`, "office.implicit_cells");
2313
+ const next = row.cells.find((cell) => cell.column > item.column);
2314
+ inserts.push({ at: next ? next.element.start : -1, xml: newCell(item, rowStyle) });
2315
+ changed.push({ sheet: sheet.name, cell: item.address, before: null, after: item.edit.value, created: true });
2316
+ continue;
2317
+ }
2318
+ const before = cellOf(workbook, text, existing);
2319
+ const element = existing.element;
2320
+ if (attributeOf(element, "", "vm") !== void 0)
2321
+ throw refuse2(`${sheet.name}!${item.address} holds a picture or a linked data type, which this editor does not replace`, "office.rich_value");
2322
+ const formula = childrenOf(element, ns, "f")[0];
2323
+ const array2 = arrays.find((entry) => item.row >= entry.range.top && item.row <= entry.range.bottom && item.column >= entry.range.left && item.column <= entry.range.right && (entry.range.top !== entry.range.bottom || entry.range.left !== entry.range.right));
2324
+ if (array2)
2325
+ throw refuse2(`${sheet.name}!${item.address} is part of an array formula; change it in Excel`, "office.array_formula");
2326
+ if (formula) {
2327
+ if (!options.overwriteFormulas)
2328
+ throw refuse2(`${sheet.name}!${item.address} holds the formula =${before.formula}; pass overwriteFormulas to replace it with a value`, "office.formula_cell");
2329
+ if (attributeOf(formula, "", "t") === "shared" && attributeOf(formula, "", "ref") !== void 0)
2330
+ throw refuse2(`${sheet.name}!${item.address} holds a formula that other cells share; replacing it would break theirs`, "office.shared_formula");
2331
+ formulaRemoved = true;
2332
+ }
2333
+ if (attributeOf(element, "", "t") === "s" && strings)
2334
+ strings.release();
2335
+ const { type, content } = valueXml(element, item.edit.value, strings);
2336
+ const extra = childrenOf(element, ns, "extLst").map((child) => text.slice(child.start, child.end)).join("");
2337
+ const tag = cellTag(text, element, type);
2338
+ splices.push({ start: element.start, end: element.end, text: `${tag}${content}${extra}</${element.name}>` });
2339
+ changed.push({
2340
+ sheet: sheet.name,
2341
+ cell: item.address,
2342
+ before: before.value,
2343
+ after: item.edit.value,
2344
+ created: false
2345
+ });
2346
+ }
2347
+ if (inserts.length) {
2348
+ const tail = inserts.filter((insert) => insert.at < 0).map((insert) => insert.xml).join("");
2349
+ for (const insert of inserts.filter((entry) => entry.at >= 0))
2350
+ splices.push({ start: insert.at, end: insert.at, text: insert.xml });
2351
+ if (tail) {
2352
+ if (isSelfClosing(text, row.element))
2353
+ splices.push({
2354
+ start: row.element.start,
2355
+ end: row.element.end,
2356
+ text: `${openTag(text, row.element)}${tail}</${row.element.name}>`
2357
+ });
2358
+ else
2359
+ splices.push({ start: row.element.closeStart, end: row.element.closeStart, text: tail });
2360
+ }
2361
+ }
2362
+ }
2363
+ const created = changed.filter((entry) => entry.created).map((entry) => parseAddress(entry.cell));
2364
+ const dimension = childrenOf(part.root, ns, "dimension")[0];
2365
+ const ref = dimension && attributeOf(dimension, "", "ref");
2366
+ if (dimension && ref && created.length) {
2367
+ const current = parseRange(ref);
2368
+ const grown = created.reduce((box, cell) => ({
2369
+ top: Math.min(box.top, cell.row),
2370
+ bottom: Math.max(box.bottom, cell.row),
2371
+ left: Math.min(box.left, cell.column),
2372
+ right: Math.max(box.right, cell.column)
2373
+ }), current);
2374
+ if (grown.top !== current.top || grown.bottom !== current.bottom || grown.left !== current.left || grown.right !== current.right) {
2375
+ const a1 = `${columnName(grown.left)}${grown.top}`;
2376
+ const b2 = `${columnName(grown.right)}${grown.bottom}`;
2377
+ splices.push({
2378
+ start: dimension.start,
2379
+ end: dimension.openEnd,
2380
+ text: withAttribute(startTag(text, dimension), "ref", a1 === b2 ? a1 : `${a1}:${b2}`)
2381
+ });
2382
+ }
2383
+ }
2384
+ pack.write(part, splices);
2385
+ return { changed, formulaRemoved };
2386
+ }, "editSheet");
2387
+ var markRecalculation = /* @__PURE__ */ __name((workbook) => {
2388
+ const { workbook: part, ns } = workbook;
2389
+ const { root, text } = part;
2390
+ const calcPr = childrenOf(root, ns, "calcPr")[0];
2391
+ if (calcPr) {
2392
+ if (attributeOf(calcPr, "", "fullCalcOnLoad") === "1")
2393
+ return;
2394
+ workbook.pack.write(part, [
2395
+ { start: calcPr.start, end: calcPr.openEnd, text: withAttribute(startTag(text, calcPr), "fullCalcOnLoad", "1") }
2396
+ ]);
2397
+ return;
2398
+ }
2399
+ const next = root.children.find((child) => child.ns === ns && AFTER_CALC.includes(child.local));
2400
+ const xml = `<${qualified(root, "calcPr")} fullCalcOnLoad="1"/>`;
2401
+ const at = next ? next.start : root.closeStart;
2402
+ workbook.pack.write(part, [{ start: at, end: at, text: xml }]);
2403
+ }, "markRecalculation");
2404
+ var dropCalcChain = /* @__PURE__ */ __name((workbook) => {
2405
+ const chain = workbook.calcChain;
2406
+ if (!chain)
2407
+ return false;
2408
+ const { pack } = workbook;
2409
+ const relsPath = workbook.path.replace(/([^/]+)$/, "_rels/$1.rels");
2410
+ const rels = pack.part(relsPath);
2411
+ const relation = childrenOf(rels.root, PACKAGE_REL, "Relationship").find((entry) => attributeOf(entry, "", "Id") === chain.id);
2412
+ if (relation)
2413
+ pack.write(rels, [{ start: relation.start, end: relation.end, text: "" }]);
2414
+ const types = pack.part("[Content_Types].xml");
2415
+ const override = childrenOf(types.root, CONTENT_TYPES, "Override").find((entry) => attributeOf(entry, "", "PartName") === `/${chain.path}`);
2416
+ if (override)
2417
+ pack.write(types, [{ start: override.start, end: override.end, text: "" }]);
2418
+ if (pack.has(chain.path))
2419
+ pack.remove(chain.path);
2420
+ return true;
2421
+ }, "dropCalcChain");
2422
+ var same = /* @__PURE__ */ __name((left, right) => left === right || left === "" && right === null, "same");
2423
+ var editXlsxCells = /* @__PURE__ */ __name(async (bytes, edits, options = {}) => {
2424
+ const workbook = await Workbook.open(bytes);
2425
+ const bySheet = /* @__PURE__ */ new Map();
2426
+ const seen = /* @__PURE__ */ new Set();
2427
+ for (const edit of edits) {
2428
+ const sheet = workbook.sheet(edit.sheet);
2429
+ const { row, column } = parseAddress(edit.cell);
2430
+ const address = `${columnName(column)}${row}`;
2431
+ const key = `${sheet.name}!${address}`;
2432
+ if (seen.has(key))
2433
+ throw refuse2(`${key} is edited twice in one call`, "office.duplicate_edit");
2434
+ seen.add(key);
2435
+ bySheet.set(sheet, [...bySheet.get(sheet) ?? [], { edit, row, column, address }]);
2436
+ }
2437
+ if (!edits.length)
2438
+ return { bytes: bytes.slice(), changed: [], calcChainDropped: false };
2439
+ const strings = workbook.sharedPath ? new SharedStrings(workbook) : void 0;
2440
+ let changed = [];
2441
+ let formulaRemoved = false;
2442
+ for (const [sheet, planned] of bySheet) {
2443
+ const result = editSheet(workbook, sheet, planned, options, strings);
2444
+ changed = changed.concat(result.changed);
2445
+ formulaRemoved ||= result.formulaRemoved;
2446
+ }
2447
+ strings?.write();
2448
+ markRecalculation(workbook);
2449
+ const calcChainDropped = formulaRemoved && dropCalcChain(workbook);
2450
+ const output = workbook.pack.build();
2451
+ await verify(output, changed);
2452
+ return { bytes: output, changed, calcChainDropped };
2453
+ }, "editXlsxCells");
2454
+ var verify = /* @__PURE__ */ __name(async (output, changed) => {
2455
+ const sheets = await readXlsxCells(output);
2456
+ for (const entry of changed) {
2457
+ const cell = sheets.find((sheet) => sheet.name === entry.sheet)?.cells.find((candidate) => candidate.address === entry.cell);
2458
+ if (!same(cell?.value ?? null, entry.after) || cell?.formula !== void 0)
2459
+ throw new Error(`the edited workbook does not read back ${entry.sheet}!${entry.cell} as written`);
2460
+ }
2461
+ await readSpreadsheet(output, "xlsx");
2462
+ }, "verify");
2463
+
2464
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/file-update.js
2465
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2466
+ import { tmpdir } from "node:os";
2467
+ import { join } from "node:path";
2468
+ var SHA256 = /^[0-9a-f]{64}$/u;
2469
+ var EXTRACTED = /\.(pdf|docx|xlsx)$/iu;
2470
+ var sha256Of = /* @__PURE__ */ __name((input, flag = "--expected-fingerprint") => {
2471
+ const hash = input?.toLowerCase();
2472
+ if (hash !== void 0 && !SHA256.test(hash))
2473
+ throw new CliError("validation_error", `${flag} takes a 64-character sha256`, { param: flag });
2474
+ return hash;
2475
+ }, "sha256Of");
2476
+ var replacedOf = /* @__PURE__ */ __name((done, versions) => done.replaced ? {
2477
+ sha256: done.replaced.sha256,
2478
+ ...versions.dir ? { kept_at: join(versions.dir, "objects", done.replaced.sha256) } : {}
2479
+ } : null, "replacedOf");
2480
+ var newText = /* @__PURE__ */ __name(async (input, text) => {
2481
+ if (text !== void 0)
2482
+ return text;
2483
+ if (!input || input.isTTY)
2484
+ throw new CliError("validation_error", "give the new text with --text or on stdin", { param: "--text" });
2485
+ const read = await bufferedInput(input, { maxBytes: MAX_BUFFERED_INPUT });
2486
+ if (read.length === 0)
2487
+ throw new CliError("validation_error", "stdin gave no text; give the new text with --text or on stdin", {
2488
+ param: "--text"
2489
+ });
2490
+ return read.toString("utf8");
2491
+ }, "newText");
2492
+ var addFileUpdateCommandDefinition = /* @__PURE__ */ __name((files, helpers) => {
2493
+ const { prefix, place } = wordsOf(helpers.words);
2494
+ const group = files.name();
2495
+ const deleteKey = helpers.deleteKey ?? "files.delete";
2496
+ return examples(annotate(files.command("update"), { effects: REMOTE_WRITE, offline: false }).summary(`replace a ${place} file's text, or create a text file`).description(`replace a ${place} file's text, or create a text file. A file already there is replaced only with --expected-fingerprint, the sha256 read from it; it asks as ${deleteKey} does. The file is checked just before the write, and what it replaced is kept on this computer. Write back only a whole plain-text file: a text cut with truncated: true would replace the whole file, and a .pdf, .docx or .xlsx is refused`).argument("<path>", `the file on ${place}`).option("--text <text>", "the file's new text; without it, the text is read from stdin").option("--expected-fingerprint <hash>", "the sha256 the file had when it was read; required when it exists"), [
2497
+ `${prefix} ${group} update /notes.md --text "# Notes"`,
2498
+ `${prefix} ${group} update /notes.md --text "# Notes" --expected-fingerprint 9f86d081\u2026`
2499
+ ]).action(async function(input, args) {
2500
+ const expected = sha256Of(args.expectedFingerprint);
2501
+ const path = helpers.path(input);
2502
+ if (EXTRACTED.test(path))
2503
+ throw new CliError("validation_error", `${path} is not a plain-text file; change a .docx with ${group} documents update and a .xlsx with ${group} sheets update, where a CLI has them`, { reason: "file.not-plain-text" });
2504
+ const text = await newText(helpers.stdin(), args.text);
2505
+ const answer = await helpers.write(expected ? [deleteKey] : [], async ({ target, versions, signal }) => {
2506
+ const folder = await mkdtemp(join(tmpdir(), "wirecat-update-"));
2507
+ try {
2508
+ const from = join(folder, "text");
2509
+ await writeFile(from, text, { mode: 384 });
2510
+ const done = await guardedFileWrite({
2511
+ target,
2512
+ versions,
2513
+ path,
2514
+ from,
2515
+ reread: helpers.reread(input),
2516
+ ...expected ? { expected } : {},
2517
+ ...signal ? { signal } : {}
2518
+ });
2519
+ return {
2520
+ path,
2521
+ sha256: done.file.sha256 ?? null,
2522
+ replaced: replacedOf(done, versions)
2523
+ };
2524
+ } finally {
2525
+ await rm(folder, { recursive: true, force: true });
2526
+ }
2527
+ }, this);
2528
+ helpers.output(itemOf(answer), this);
2529
+ });
2530
+ }, "addFileUpdateCommandDefinition");
2531
+ var addFileUpdateCommand = honoursDryRun(sharedCommand(addFileUpdateCommandDefinition));
2532
+
2533
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/file-edit.js
2534
+ var MAX_OFFICE_BYTES = 64 * 1024 * 1024;
2535
+ var sha256 = /* @__PURE__ */ __name((bytes) => createHash("sha256").update(bytes).digest("hex"), "sha256");
2536
+ var inTemp = /* @__PURE__ */ __name(async (act) => {
2537
+ const folder = await mkdtemp2(join2(tmpdir2(), "wirecat-office-"));
2538
+ try {
2539
+ return await act(folder);
2540
+ } finally {
2541
+ await rm2(folder, { recursive: true, force: true });
2542
+ }
2543
+ }, "inTemp");
2544
+ var downloaded = /* @__PURE__ */ __name(({ target, signal }, path) => inTemp(async (folder) => {
2545
+ const into = join2(folder, "file");
2546
+ await target.download(path, into, signal);
2547
+ const { size } = await stat(into);
2548
+ if (size > MAX_OFFICE_BYTES)
2549
+ throw new CliError("validation_error", `${path} is ${size} bytes; an Office file is read up to 64 MiB`, {
2550
+ reason: "file.too-large"
2551
+ });
2552
+ const bytes = new Uint8Array(await readFile(into));
2553
+ return { bytes, sha256: sha256(bytes) };
2554
+ }), "downloaded");
2555
+ var jsonOf = /* @__PURE__ */ __name((input, flag, schema2, shape) => {
2556
+ let parsed;
2557
+ try {
2558
+ parsed = JSON.parse(input);
2559
+ } catch {
2560
+ throw new CliError("validation_error", `${flag} is not JSON; give ${shape}`, { param: flag });
2561
+ }
2562
+ const checked = safeParse(schema2, parsed);
2563
+ if (!checked.success)
2564
+ throw new CliError("validation_error", `${flag} takes ${shape}`, { param: flag });
2565
+ return checked.output;
2566
+ }, "jsonOf");
2567
+ var ADDRESS = /^([A-Z]{1,3})([1-9]\d{0,6})$/u;
2568
+ var CELLS = /^[A-Z]{1,3}[1-9]\d*(:[A-Z]{1,3}[1-9]\d*)?$/iu;
2569
+ var columnName2 = /* @__PURE__ */ __name((column) => {
2570
+ let name = "";
2571
+ for (let left = column; left > 0; left = Math.floor((left - 1) / 26))
2572
+ name = String.fromCharCode(65 + (left - 1) % 26) + name;
2573
+ return name;
2574
+ }, "columnName");
2575
+ var cornerOf = /* @__PURE__ */ __name((address) => {
2576
+ const match = ADDRESS.exec(address.toUpperCase());
2577
+ if (!match)
2578
+ throw new CliError("validation_error", `${address} is not a cell like B7`, { reason: "office.invalid_cell" });
2579
+ const letters = match[1];
2580
+ return {
2581
+ column: [...letters].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0),
2582
+ row: Number(match[2])
2583
+ };
2584
+ }, "cornerOf");
2585
+ var sheetRangeOf = /* @__PURE__ */ __name((input) => {
2586
+ if (!input)
2587
+ return {};
2588
+ const bang = input.lastIndexOf("!");
2589
+ const quoted = /* @__PURE__ */ __name((name) => /^'.*'$/u.test(name) ? name.slice(1, -1).replaceAll("''", "'") : name, "quoted");
2590
+ if (bang >= 0) {
2591
+ const range = input.slice(bang + 1);
2592
+ return { sheet: quoted(input.slice(0, bang)), ...range ? { range } : {} };
2593
+ }
2594
+ return CELLS.test(input) ? { range: input } : { sheet: quoted(input) };
2595
+ }, "sheetRangeOf");
2596
+ var VALUES = pipe(array(pipe(array(union([string(), number(), boolean(), null_()])), minLength(1))), minLength(1));
2597
+ var VALUES_SHAPE = 'rows of cell values as JSON, such as [["Total", 42], [null, true]]';
2598
+ var cellEditsOf = /* @__PURE__ */ __name((sheet, range, values) => {
2599
+ const [from, to] = range.split(":");
2600
+ const start = cornerOf(from);
2601
+ if (to !== void 0) {
2602
+ const end = cornerOf(to);
2603
+ const rows = end.row - start.row + 1;
2604
+ const columns = end.column - start.column + 1;
2605
+ if (rows < 1 || columns < 1 || values.length !== rows || values.some((row) => row.length !== columns))
2606
+ throw new CliError("validation_error", `${range} is ${rows} rows by ${columns} columns; --values must have that shape, or name only its first cell`, { param: "--values" });
2607
+ }
2608
+ return values.flatMap((row, down) => row.map((value, across) => ({ sheet, cell: `${columnName2(start.column + across)}${start.row + down}`, value })));
2609
+ }, "cellEditsOf");
2610
+ var PAYLOAD = pipe(array(union([
2611
+ strictObject({ index: pipe(number(), integer()), text: string() }),
2612
+ strictObject({
2613
+ insert_after: pipe(number(), integer()),
2614
+ text: string(),
2615
+ style_from: optional(pipe(number(), integer()))
2616
+ }),
2617
+ strictObject({ delete: pipe(number(), integer()) })
2618
+ ])), minLength(1));
2619
+ var PAYLOAD_SHAPE = 'paragraph edits as JSON: [{"index": 3, "text": "\u2026"}, {"insert_after": 5, "text": "\u2026"}, {"delete": 7}]';
2620
+ var docxEditsOf = /* @__PURE__ */ __name((payload) => payload.map((edit) => {
2621
+ if ("insert_after" in edit)
2622
+ return {
2623
+ insertAfter: edit.insert_after,
2624
+ text: edit.text,
2625
+ ...edit.style_from === void 0 ? {} : { styleFrom: edit.style_from }
2626
+ };
2627
+ return edit;
2628
+ }), "docxEditsOf");
2629
+ var addFileEditCommandsDefinition = /* @__PURE__ */ __name((files, helpers) => {
2630
+ const { prefix, place } = wordsOf(helpers.words);
2631
+ const group = files.name();
2632
+ const deleteKey = helpers.deleteKey ?? "files.delete";
2633
+ const show = /* @__PURE__ */ __name((kind, input) => `${prefix} ${group} ${kind} show ${input}`, "show");
2634
+ const editInPlace = /* @__PURE__ */ __name(async (command, kind, input, fingerprint, edit) => {
2635
+ const reread = show(kind, input);
2636
+ const expected = sha256Of(fingerprint);
2637
+ if (expected === void 0)
2638
+ throw new CliError("validation_error", `read the file first (${reread}) and pass its sha256 as --expected-fingerprint`, {
2639
+ param: "--expected-fingerprint"
2640
+ });
2641
+ const path = helpers.path(input);
2642
+ const answer = await helpers.write([deleteKey], async (port) => {
2643
+ const read = await downloaded(port, path);
2644
+ if (read.sha256 !== expected)
2645
+ throw remoteChanged(path, "changed since it was read", reread);
2646
+ const edited = await edit(read.bytes);
2647
+ return inTemp(async (folder) => {
2648
+ const from = join2(folder, "edited");
2649
+ await writeFile2(from, edited.bytes, { mode: 384 });
2650
+ const { target, versions, signal } = port;
2651
+ const done = await guardedFileWrite({
2652
+ target,
2653
+ versions,
2654
+ path,
2655
+ from,
2656
+ expected,
2657
+ reread,
2658
+ ...signal ? { signal } : {}
2659
+ });
2660
+ return { path, sha256: done.file.sha256 ?? null, replaced: replacedOf(done, versions), ...edited.answer };
2661
+ });
2662
+ }, command);
2663
+ helpers.output(itemOf(answer), command);
2664
+ }, "editInPlace");
2665
+ const readOffice = /* @__PURE__ */ __name(async (command, input, answer) => {
2666
+ const path = helpers.path(input);
2667
+ const item = await helpers.read(async (port) => {
2668
+ const read = await downloaded(port, path);
2669
+ return { path, sha256: read.sha256, ...await answer(read.bytes) };
2670
+ }, command);
2671
+ helpers.output(itemOf(item), command);
2672
+ }, "readOffice");
2673
+ const sheets = annotate(files.command("sheets"), { effects: REMOTE_READ }).description(`the cells of an Excel workbook (.xlsx) on ${place}, read and changed in place`);
2674
+ examples(annotate(sheets.command("show"), { effects: REMOTE_READ, offline: false }).summary("show a workbook's cells and the sha256 to edit them at").description("show a workbook's stored cells, each with its value, type, formula and format, and the file's sha256 to pass as --expected-fingerprint to sheets update. Formulas show the value Excel saved last").argument("<path>", `the .xlsx file on ${place}`).argument("[range]", "the cells to show: Sheet1!A1:C10, a sheet's name, or A1:C10 on every sheet; all without it"), [`${prefix} ${group} sheets show /budget.xlsx "Sheet1!A1:C10"`, `${prefix} ${group} sheets show /budget.xlsx`]).action(async function(input, range) {
2675
+ const wanted = sheetRangeOf(range);
2676
+ await readOffice(this, input, async (bytes) => ({
2677
+ sheets: (await readXlsxCells(bytes, wanted)).map((sheet) => ({
2678
+ name: sheet.name,
2679
+ cells: sheet.cells.map((cell) => ({
2680
+ address: cell.address,
2681
+ row: cell.row,
2682
+ column: cell.column,
2683
+ value: cell.value,
2684
+ type: cell.type,
2685
+ ...cell.formula === void 0 ? {} : { formula: cell.formula },
2686
+ style: cell.style
2687
+ }))
2688
+ }))
2689
+ }));
2690
+ });
2691
+ examples(annotate(sheets.command("update"), { effects: REMOTE_WRITE, offline: false }).summary("write values into a workbook's cells, at the sha256 it was read at").description(`write values into a workbook's cells in place: the rest of the file, its formatting and its other sheets stay as they are. It needs --expected-fingerprint from sheets show and asks as ${deleteKey} does; what it replaced is kept on this computer (see history). A text is written as text, even one that starts with =. A formula cell is refused unless --replace`).argument("<path>", `the .xlsx file on ${place}`).argument("<range>", "where the values go: Sheet1!B2:C3, or its first cell Sheet1!B2; the sheet may be left out when there is one").option("--values <json>", "the cell values as JSON rows; null empties a cell").option("--expected-fingerprint <hash>", "the sha256 sheets show gave for the file").option("--replace", "replace a formula with the value instead of refusing it"), [
2692
+ `${prefix} ${group} sheets update /budget.xlsx "Sheet1!B2:C2" --values '[[120, "paid"]]' --expected-fingerprint 9f86d081\u2026`
2693
+ ]).action(async function(input, range, args) {
2694
+ if (args.values === void 0)
2695
+ throw new CliError("validation_error", `give the cells' values with --values: ${VALUES_SHAPE}`, {
2696
+ param: "--values"
2697
+ });
2698
+ const values = jsonOf(args.values, "--values", VALUES, VALUES_SHAPE);
2699
+ const wanted = sheetRangeOf(range);
2700
+ if (wanted.range === void 0)
2701
+ throw new CliError("validation_error", `${range} names no cell; give one like Sheet1!B2`, {
2702
+ reason: "office.invalid_cell"
2703
+ });
2704
+ cellEditsOf("", wanted.range, values);
2705
+ await editInPlace(this, "sheets", input, args.expectedFingerprint, async (bytes) => {
2706
+ let sheet = wanted.sheet;
2707
+ if (sheet === void 0) {
2708
+ const names = (await readXlsxCells(bytes, { range: "A1" })).map((one) => one.name);
2709
+ if (names.length !== 1)
2710
+ throw new CliError("validation_error", `the workbook has ${names.length} sheets (${names.map((name) => `"${name}"`).join(", ")}); name one, like ${names[0] ?? "Sheet1"}!${wanted.range}`, { reason: "office.no_sheet" });
2711
+ sheet = names[0];
2712
+ }
2713
+ try {
2714
+ const done = await editXlsxCells(bytes, cellEditsOf(sheet, wanted.range, values), {
2715
+ overwriteFormulas: args.replace === true
2716
+ });
2717
+ return {
2718
+ bytes: done.bytes,
2719
+ answer: {
2720
+ changed: done.changed,
2721
+ calc_chain_dropped: done.calcChainDropped,
2722
+ warnings: done.calcChainDropped ? ["a formula was replaced, so Excel rebuilds the workbook's calculation order when it opens it"] : []
2723
+ }
2724
+ };
2725
+ } catch (error) {
2726
+ if (isCliError(error) && error.details?.reason === "office.formula_cell")
2727
+ throw new CliError("validation_error", error.message.replace("pass overwriteFormulas", "pass --replace"), error.details);
2728
+ throw error;
2729
+ }
2730
+ });
2731
+ });
2732
+ const documents = annotate(files.command("documents"), { effects: REMOTE_READ }).description(`the paragraphs of a Word document (.docx) on ${place}, read and changed in place`);
2733
+ examples(annotate(documents.command("show"), { effects: REMOTE_READ, offline: false }).summary("show a document's paragraphs and the sha256 to edit them at").description("show a Word document's paragraphs by index, with their style, whether each can be edited and why not, and the file's sha256 to pass as --expected-fingerprint to documents update").argument("<path>", `the .docx file on ${place}`), [`${prefix} ${group} documents show /report.docx`]).action(async function(input) {
2734
+ await readOffice(this, input, async (bytes) => ({
2735
+ paragraphs: (await readDocxParagraphs(bytes)).map((paragraph) => ({
2736
+ index: paragraph.index,
2737
+ text: paragraph.text,
2738
+ ...paragraph.styleId === void 0 ? {} : { style_id: paragraph.styleId },
2739
+ ...paragraph.style === void 0 ? {} : { style: paragraph.style },
2740
+ location: paragraph.location,
2741
+ editable: paragraph.editable,
2742
+ ...paragraph.reason === void 0 ? {} : { reason: paragraph.reason },
2743
+ mixed_formatting: paragraph.mixedFormatting
2744
+ }))
2745
+ }));
2746
+ });
2747
+ examples(annotate(documents.command("update"), { effects: REMOTE_WRITE, offline: false }).summary("replace, insert or delete paragraphs, at the sha256 it was read at").description(`replace, insert or delete a Word document's paragraphs in place; the rest of the file stays as it is. Indexes are the ones documents show gave. It needs --expected-fingerprint from documents show and asks as ${deleteKey} does; what it replaced is kept on this computer (see history). A paragraph that is not editable is refused with its reason, and a replaced one with mixed formatting takes its first run's`).argument("<path>", `the .docx file on ${place}`).option("--payload <json>", "the edits as JSON: {index, text}, {insert_after, text, style_from?} or {delete}").option("--expected-fingerprint <hash>", "the sha256 documents show gave for the file"), [
2748
+ `${prefix} ${group} documents update /report.docx --payload '[{"index": 2, "text": "Revenue grew 12%."}]' --expected-fingerprint 9f86d081\u2026`
2749
+ ]).action(async function(input, args) {
2750
+ if (args.payload === void 0)
2751
+ throw new CliError("validation_error", `give the edits with --payload: ${PAYLOAD_SHAPE}`, { param: "--payload" });
2752
+ const edits = docxEditsOf(jsonOf(args.payload, "--payload", PAYLOAD, PAYLOAD_SHAPE));
2753
+ await editInPlace(this, "documents", input, args.expectedFingerprint, async (bytes) => {
2754
+ const done = await editDocxParagraphs(bytes, edits);
2755
+ return {
2756
+ bytes: done.bytes,
2757
+ answer: {
2758
+ paragraphs: { replaced: done.replaced, inserted: done.inserted, deleted: done.deleted },
2759
+ warnings: done.collapsed.map((index) => `paragraph ${index} had mixed formatting; its new text has its first run's formatting`)
2760
+ }
2761
+ };
2762
+ });
2763
+ });
2764
+ examples(annotate(files.command("history"), { effects: REMOTE_READ, offline: false }).summary("list the earlier versions of a file kept on this computer").description(`list what the writes and syncs of this profile replaced in a file, newest last. Each entry's version is the sha256 of the content it replaced, kept on this computer while available is true; ${group} restore puts it back`).argument("<path>", `the file on ${place}`), [`${prefix} ${group} history /budget.xlsx`]).action(async function(input) {
2765
+ const path = helpers.path(input);
2766
+ const item = await helpers.read(async ({ versions }) => ({
2767
+ path,
2768
+ versions: versions.list(path).map((event) => ({
2769
+ at: event.at,
2770
+ event: event.event,
2771
+ direction: event.direction,
2772
+ version: event.old ?? null,
2773
+ available: event.available,
2774
+ ...event.new === void 0 ? {} : { new: event.new },
2775
+ ...event.size === void 0 ? {} : { size: event.size },
2776
+ ...event.to === void 0 ? {} : { to: event.to },
2777
+ ...event.oldIn === void 0 ? {} : { old_in: event.oldIn }
2778
+ }))
2779
+ }), this);
2780
+ helpers.output(itemOf(item), this);
2781
+ });
2782
+ const trash = helpers.restoreFromTrash;
2783
+ examples(annotate(files.command("restore"), { effects: REMOTE_WRITE, offline: false }).summary(trash ? "bring a file back from the trash, or put back a version kept here" : "put back a version of a file kept here").description(`${trash ? `with no version, bring a file or folder back from ${place}'s trash. With one, put` : "put"} back a version history lists: it is written as ${group} update writes, so a file there needs --expected-fingerprint, asks as ${deleteKey} does, and is kept first`).argument("<path>", trash ? `the file on ${place}, or its path in the trash` : `the file on ${place}`).argument(trash ? "[version]" : "<version>", "the version's sha256, from history").option("--expected-fingerprint <hash>", "the sha256 the file has now; required when it exists"), [`${prefix} ${group} restore /budget.xlsx 2c26b46b\u2026 --expected-fingerprint 9f86d081\u2026`]).action(async function(input, versionInput, args) {
2784
+ if (versionInput === void 0) {
2785
+ if (!trash)
2786
+ throw new CliError("validation_error", `give the version from ${group} history`, { param: "version" });
2787
+ helpers.output(itemOf(await trash(input, this)), this);
2788
+ return;
2789
+ }
2790
+ const version = sha256Of(versionInput, "the version");
2791
+ const expected = sha256Of(args.expectedFingerprint);
2792
+ const path = helpers.path(input);
2793
+ const reread = helpers.reread(input);
2794
+ const answer = await helpers.write(expected ? [deleteKey] : [], async ({ target, versions, signal }) => inTemp(async (folder) => {
2795
+ const from = join2(folder, "version");
2796
+ if (!await versions.write(version, from))
2797
+ throw new CliError("not_found", `version ${version} of ${path} is no longer kept here; see ${group} history`, {
2798
+ reason: "item.not-found"
2799
+ });
2800
+ const done = await guardedFileWrite({
2801
+ target,
2802
+ versions,
2803
+ path,
2804
+ from,
2805
+ reread,
2806
+ direction: "restored",
2807
+ ...expected ? { expected } : {},
2808
+ ...signal ? { signal } : {}
2809
+ });
2810
+ return { path, sha256: done.file.sha256 ?? null, restored: version, replaced: replacedOf(done, versions) };
2811
+ }), this);
2812
+ helpers.output(itemOf(answer), this);
2813
+ });
2814
+ addFileUpdateCommand(files, helpers);
2815
+ }, "addFileEditCommandsDefinition");
2816
+ var addFileEditCommands = honoursDryRun(sharedCommand(addFileEditCommandsDefinition));
2817
+
2818
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/manifest/manifest.js
2819
+ var dotPath = pipe(string(), regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dot path into the answer, such as data.id"));
2820
+ var scalar = union([string(), number(), boolean()]);
2821
+ var callEntries = {
2822
+ operation: pipe(string(), minLength(1)),
2823
+ path: optional(record(string(), string())),
2824
+ query: optional(record(string(), scalar)),
2825
+ body: optional(unknown()),
2826
+ items: optional(dotPath)
2827
+ };
2828
+ var fileMap = strictObject({
2829
+ id: dotPath,
2830
+ name: dotPath,
2831
+ parent: optional(dotPath),
2832
+ parents: optional(dotPath),
2833
+ url: optional(dotPath),
2834
+ modifiedAt: optional(dotPath),
2835
+ createdAt: optional(dotPath),
2836
+ version: optional(dotPath),
2837
+ trashed: optional(dotPath),
2838
+ mime: optional(dotPath),
2839
+ folder: optional(strictObject({
2840
+ path: dotPath,
2841
+ is: scalar,
2842
+ mime: optional(strictObject({ folder: string(), file: string() }))
2843
+ }))
2844
+ });
2845
+ var schema = strictObject({
2846
+ provider: pipe(string(), regex(/^[a-z][a-z0-9-]*$/, "lower-case letters, digits and dashes")),
2847
+ identity: strictObject({ ...callEntries, id: union([dotPath, pipe(array(dotPath), minLength(1))]) }),
2848
+ get: optional(strictObject({ ...callEntries, map: fileMap })),
2849
+ children: optional(strictObject({ ...callEntries, map: optional(fileMap) })),
2850
+ changes: optional(strictObject({
2851
+ ...callEntries,
2852
+ since: picklist(["iso", "ms", "seconds"]),
2853
+ time: dotPath,
2854
+ overlapMs: optional(pipe(number(), integer(), minValue(0))),
2855
+ map: optional(fileMap)
2856
+ })),
2857
+ content: optional(strictObject({ ...callEntries, markdown: dotPath })),
2858
+ reread: optional(strictObject({ missing: dotPath })),
2859
+ reads: optional(record(pipe(string(), regex(/^[a-z][A-Za-z0-9]*$/, "a camelCase name")), strictObject(callEntries)))
2860
+ });
2861
+
2862
+ // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.128.0_commander@15.0.0_esbuild@0.28.2_typ_a55806ccf2eb39d6be3eaf4c54d1a60a/node_modules/@wirecat/cli-core/dist/cli/documents/manifest/source.js
2863
+ var OVERLAP_MS = 10 * 6e4;
2864
+
2865
+ // dist/list-queries.js
2866
+ var registry2 = /* @__PURE__ */ __name((entity, schema2, native, examples2) => ({
2867
+ entity,
2868
+ backend: "native",
2869
+ fields: queryFieldsOf(schema2, { native, examples: examples2 }).map((field) => field.native ? { ...field, operators: ["term", "phrase"] } : field)
2870
+ }), "registry");
2871
+ var sessionRow = strictObject({
2872
+ profile: string(),
2873
+ selected_folders: number(),
2874
+ storage: picklist(["keyring", "file"])
2875
+ });
2876
+ var fileRow = looseObject({
2877
+ id: optional(string()),
2878
+ name: optional(string()),
2879
+ trashed: optional(boolean()),
2880
+ modified_time: optional(isoTime),
2881
+ created_time: optional(isoTime),
2882
+ viewed_by_me_time: optional(isoTime)
2883
+ });
2884
+ var transcriptRow = strictObject({
2885
+ id: string(),
2886
+ name: string(),
2887
+ url: string(),
2888
+ owned_by_me: nullable(boolean()),
2889
+ modified_at: nullable(string())
2890
+ });
2891
+ var TRANSCRIPTS_QUERY = registry2("drive_transcript", transcriptRow, ["owned_by_me"], {
2892
+ owned_by_me: "owned_by_me:false"
2893
+ });
2894
+ var SESSIONS_QUERY = registry2("drive_session", sessionRow, ["profile", "storage"], {
2895
+ profile: "profile:personal",
2896
+ storage: "storage:keyring"
2897
+ });
2898
+ var FILES_QUERY = {
2899
+ entity: "drive_remote_file",
2900
+ backend: "native",
2901
+ fields: queryFieldsOf(fileRow, {
2902
+ native: ["name", "trashed", "modified_time", "created_time", "viewed_by_me_time"],
2903
+ examples: {
2904
+ name: 'name:"Example plan"',
2905
+ trashed: "trashed:false",
2906
+ modified_time: "modified_time>=2026-01-01",
2907
+ created_time: "created_time>=2026-01-01",
2908
+ viewed_by_me_time: "viewed_by_me_time>=2026-01-01"
2909
+ }
2910
+ }).map((field) => field.native ? { ...field, operators: field.type === "time" ? ["term", "range"] : ["term", "phrase"] } : field),
2911
+ defaults: ["trashed:false"]
2912
+ };
2913
+ var bindQuery2 = /* @__PURE__ */ __name((command, query, schema2) => answerEntity(withQuery(command, query), query.entity, schema2), "bindQuery");
2914
+ var termsOf2 = /* @__PURE__ */ __name((words, query, command) => Object.fromEntries(queryTerms(words, query, command)), "termsOf");
2915
+ var quote = /* @__PURE__ */ __name((value) => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`, "quote");
2916
+ var driveFileQuery = /* @__PURE__ */ __name((words, timezone) => {
2917
+ const ast = listQuery(typedQuery(words), FILES_QUERY, "files list");
2918
+ const zone = timezoneOf(timezone);
2919
+ const column = {
2920
+ modified_time: "modifiedTime",
2921
+ created_time: "createdTime",
2922
+ viewed_by_me_time: "viewedByMeTime"
2923
+ };
2924
+ const render = /* @__PURE__ */ __name((node) => {
2925
+ if (node.kind === "boolean") {
2926
+ if (node.clauses.some((clause) => clause.occur !== "must"))
2927
+ queryError("query.unsupported-operator", node.span, "files list accepts AND terms only");
2928
+ return node.clauses.map((clause) => render(clause.node)).join(" and ");
2929
+ }
2930
+ if (node.field === "name")
2931
+ return `name = ${quote(node.value)}`;
2932
+ if (node.field === "trashed")
2933
+ return `trashed = ${node.value.toLowerCase()}`;
2934
+ const range = dateRange(node.value, node.operator === "range" ? node.upper ?? "*" : node.value, node.lower_inclusive ?? true, node.upper_inclusive ?? true, zone, node.span);
2935
+ return [
2936
+ range.lower === void 0 ? void 0 : `${column[node.field]} ${range.lower_inclusive ? ">=" : ">"} ${quote(new Date(range.lower).toISOString())}`,
2937
+ range.upper === void 0 ? void 0 : `${column[node.field]} ${range.upper_inclusive ? "<=" : "<"} ${quote(new Date(range.upper).toISOString())}`
2938
+ ].filter(Boolean).join(" and ");
2939
+ }, "render");
2940
+ return { query: ast ? render(ast.root) : "trashed = false", timezone: zone };
2941
+ }, "driveFileQuery");
2942
+
2943
+ // dist/transcripts.js
2944
+ var TRANSCRIPT_MODES = ["include", "skip", "exclude"];
2945
+ var folded = /* @__PURE__ */ __name((text) => text.normalize("NFC").toLowerCase(), "folded");
2946
+ var isTranscript = /* @__PURE__ */ __name((words) => (file) => file.mime === DOC && !file.trashed && words.some((word) => folded(file.name).includes(folded(word))), "isTranscript");
2947
+ var transcriptsDriveQuery = /* @__PURE__ */ __name((words) => {
2948
+ const longest = /* @__PURE__ */ __name((phrase) => phrase.trim().split(/\s+/).reduce((a, b) => b.length > a.length ? b : a, ""), "longest");
2949
+ const asked = [...new Set(words.map(longest).filter(Boolean))];
2950
+ return `mimeType = '${DOC}' and trashed = false and (${asked.map((word) => `name contains ${quote(word)}`).join(" or ")})`;
2951
+ }, "transcriptsDriveQuery");
2952
+ var findTranscripts = /* @__PURE__ */ __name(async (search, words) => {
2953
+ if (!search)
2954
+ throw new CliError("configuration_error", "finding transcripts needs a signed-in Google account");
2955
+ const matches = isTranscript(words);
2956
+ return (await search(transcriptsDriveQuery(words))).filter(matches);
2957
+ }, "findTranscripts");
2958
+ var transcriptQuery = /* @__PURE__ */ __name((mode, words, search) => {
2959
+ if (mode === void 0 || mode === "skip")
2960
+ return void 0;
2961
+ const key = JSON.stringify([...new Set(words.map(folded))].sort());
2962
+ const query = { key, mode, matches: isTranscript(words) };
2963
+ return mode === "include" ? { ...query, list: /* @__PURE__ */ __name(() => findTranscripts(search, words), "list") } : query;
2964
+ }, "transcriptQuery");
2965
+
2966
+ // dist/config.js
2967
+ var Common = {
2968
+ ...AI_ENTRIES,
2969
+ permissions: optional(record(string(), picklist(LEVELS))),
2970
+ max_text_chars: optional(pipe(number(), integer(), minValue(1), maxValue(MAX_TEXT_CHARS))),
2971
+ google_client_id: optional(pipe(string(), trim(), minLength(1))),
2972
+ ...DOCUMENT_HISTORY_SETTINGS.profile
2973
+ };
2974
+ var RunSettings = {
2975
+ record: optional(boolean()),
2976
+ keep_runs_for_days: optional(pipe(number(), integer(), minValue(1))),
2977
+ keep_successful_runs_for_days: optional(pipe(number(), integer(), minValue(1))),
2978
+ runs_size_limit_mb: optional(pipe(number(), integer(), minValue(1))),
2979
+ record_input: optional(union([boolean(), literal("failed")]))
2980
+ };
2981
+ var DEFAULT_ADD_PROFILES = 5;
2982
+ var MOST_ADD_PROFILES = 50;
2983
+ var AcrossProfiles = {
2984
+ max_add_profiles: optional(pipe(number(), integer(), minValue(1), maxValue(MOST_ADD_PROFILES)))
2985
+ };
2986
+ var SharedDefaults = {
2987
+ limit: optional(pipe(number(), integer(), minValue(1))),
2988
+ sends_per_hour: optional(pipe(number(), integer(), minValue(0))),
2989
+ update_check: optional(boolean()),
2990
+ skill_hint: optional(boolean())
2991
+ };
2992
+ var DEFAULTS_ONLY = /* @__PURE__ */ new Set([
2993
+ ...Object.keys(RunSettings),
2994
+ ...Object.keys(AcrossProfiles),
2995
+ "update_check",
2996
+ "skill_hint"
2997
+ ]);
2998
+ var Transcripts = {
2999
+ transcripts: optional(picklist(TRANSCRIPT_MODES)),
3000
+ transcript_words: optional(pipe(array(pipe(string(), trim(), minLength(1), maxLength(100))), minLength(1), maxLength(50)))
3001
+ };
3002
+ var PROFILE_ONLY = /* @__PURE__ */ new Set(["picture_search", ...Object.keys(Transcripts)]);
3003
+ var SETTING_NAMES = /* @__PURE__ */ new Set([...Object.keys(Common), ...PROFILE_ONLY, ...DEFAULTS_ONLY]);
3004
+ var Mirror = strictObject({
3005
+ id: pipe(string(), regex(/^[a-z0-9-]{1,40}$/)),
3006
+ path: pipe(string(), minLength(1)),
3007
+ folder: pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/))
3008
+ });
3009
+ var Profile = strictObject({
3010
+ principal: string(),
3011
+ roots: optional(array(pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/))), []),
3012
+ mirrors: optional(array(Mirror)),
3013
+ storage: picklist(["keyring", "file"]),
3014
+ picture_search: optional(boolean()),
3015
+ ...Transcripts,
3016
+ ...Common
3017
+ });
3018
+ var ConfigSchema = strictObject({
3019
+ profiles: optional(record(string(), Profile), {}),
3020
+ defaults: optional(strictObject({ ...Common, ...RunSettings, ...AcrossProfiles, ...SharedDefaults }))
3021
+ });
3022
+ var keyOf = /* @__PURE__ */ __name((path) => {
3023
+ if (path[0] !== "api" || path[1] === void 0)
3024
+ return commandPathKey(path);
3025
+ if (["call", "list", "show"].includes(path[1]))
3026
+ return null;
3027
+ const operation = operations.find((one) => one.command === path[1]);
3028
+ return operation ? `api.${operation.id}` : commandPathKey(path);
3029
+ }, "keyOf");
3030
+ var permissions = commandPermissions({ keyOf, extra: [...permissionKeys([])], defaults: DEFAULT_LEVELS });
3031
+ var configuration = settingsFor(DRIVE_APP, {
3032
+ configRepair: false,
3033
+ // drive's own schema decides what the file may hold, so `doctor` names a profile that lacks its principal.
3034
+ schema: ConfigSchema,
3035
+ profile: {
3036
+ principal: optional(string()),
3037
+ roots: optional(array(pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/)))),
3038
+ mirrors: optional(array(Mirror)),
3039
+ storage: optional(picklist(["keyring", "file"])),
3040
+ max_text_chars: Common.max_text_chars,
3041
+ google_client_id: Common.google_client_id,
3042
+ ...DOCUMENT_HISTORY_SETTINGS.profile,
3043
+ ...Transcripts
3044
+ },
3045
+ settings: [
3046
+ {
3047
+ key: "max_text_chars",
3048
+ default: MAX_TEXT_CHARS,
3049
+ description: "the most characters of text one file may have to be imported"
3050
+ },
3051
+ {
3052
+ key: "max_add_profiles",
3053
+ default: DEFAULT_ADD_PROFILES,
3054
+ description: "the most profiles documents add may try for one document"
3055
+ },
3056
+ ...DOCUMENT_HISTORY_SETTINGS.settings
3057
+ ],
3058
+ permissions
3059
+ });
3060
+ var paths = /* @__PURE__ */ __name((env) => resolvePaths({ appName: "drive-cli", prefix: "DRIVE", env }), "paths");
3061
+ var configPath = /* @__PURE__ */ __name((env) => join3(paths(env).config, "config.json"), "configPath");
3062
+ var TOOL = "drive";
3063
+ var isNode = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isNode");
3064
+ var withoutIncomplete = /* @__PURE__ */ __name((raw, issues) => {
3065
+ const incomplete = new Set(issues.flatMap((issue) => issue.kind === "missing_setting" && issue.profile ? [issue.profile] : []));
3066
+ if (!incomplete.size || !isNode(raw) || !isNode(raw.profiles))
3067
+ return void 0;
3068
+ return {
3069
+ ...raw,
3070
+ profiles: Object.fromEntries(Object.entries(raw.profiles).filter(([name]) => !incomplete.has(name)))
3071
+ };
3072
+ }, "withoutIncomplete");
3073
+ var examine = /* @__PURE__ */ __name((text, file, knownPermissions) => {
3074
+ const check = /* @__PURE__ */ __name((body) => checkConfigText(body, {
3075
+ file,
3076
+ tool: TOOL,
3077
+ schema: ConfigSchema,
3078
+ repair: false,
3079
+ ...knownPermissions ? { knownPermissions } : {}
3080
+ }), "check");
3081
+ const first = check(text);
3082
+ if (first.issues.some((issue) => issue.kind === "invalid_json"))
3083
+ return { raw: {}, config: { profiles: {} }, issues: first.issues };
3084
+ const raw = JSON.parse(text);
3085
+ if (first.config)
3086
+ return { raw, config: first.config, issues: first.issues };
3087
+ const rest = withoutIncomplete(raw, first.issues);
3088
+ const second = rest && check(JSON.stringify(rest));
3089
+ return {
3090
+ raw,
3091
+ config: second?.config ?? { profiles: {} },
3092
+ // Saved permissions are checked only in what loads, and the first pass loaded nothing.
3093
+ issues: [...first.issues, ...(second?.issues ?? []).filter((issue) => issue.kind === "unknown_permission")]
3094
+ };
3095
+ }, "examine");
3096
+ var inspectConfig = /* @__PURE__ */ __name((env, knownPermissions) => {
3097
+ const path = configPath(env);
3098
+ let text;
3099
+ try {
3100
+ text = readFileSync2(path, "utf8");
3101
+ } catch {
3102
+ return { path, found: false, raw: {}, config: { profiles: {} }, issues: [] };
3103
+ }
3104
+ return { path, found: true, ...examine(text, path, knownPermissions) };
3105
+ }, "inspectConfig");
3106
+ var configIssues = /* @__PURE__ */ __name((raw, file, knownPermissions) => examine(JSON.stringify(raw), file, knownPermissions).issues, "configIssues");
3107
+ var refusal = /* @__PURE__ */ __name((issues) => new CliError("configuration_error", issueMessage(issues)), "refusal");
3108
+ var readConfig = /* @__PURE__ */ __name((env, knownPermissions) => {
3109
+ const { config, issues } = inspectConfig(env, knownPermissions);
3110
+ if (issues.length)
3111
+ throw refusal(issues);
3112
+ return config;
3113
+ }, "readConfig");
3114
+ var writeConfig = /* @__PURE__ */ __name((env, config) => {
3115
+ const [issue] = configIssues(config, "drive settings");
3116
+ if (issue)
3117
+ throw new CliError("configuration_error", `drive settings: ${issue.profile === void 0 ? "" : `profile ${issue.profile}: `}${issue.what}`);
3118
+ saveConfigFile(configPath(env), withDefaults(parse(ConfigSchema, config)));
3119
+ }, "writeConfig");
3120
+ var withDefaults = /* @__PURE__ */ __name((raw, except = []) => withSettingDefaults(isNode(raw) && !Object.hasOwn(raw, "defaults") ? { ...raw, defaults: {} } : raw, configuration.declaredSettings.filter(({ key }) => !except.includes(key))).config, "withDefaults");
3121
+ var profileName = usableProfileName;
3122
+ var fileId = /* @__PURE__ */ __name((input) => {
3123
+ let id = input;
3124
+ if (input.startsWith("https://")) {
3125
+ const url = new URL(input);
3126
+ if (url.hostname !== "drive.google.com" && url.hostname !== "docs.google.com")
3127
+ throw new CliError("validation_error", "use a Google Drive/Docs URL or file ID");
3128
+ id = url.pathname.match(/\/(?:folders|d)\/([^/]+)/)?.[1] ?? "";
3129
+ }
3130
+ if (!/^[A-Za-z0-9_-]{1,200}$/.test(id))
3131
+ throw new CliError("validation_error", "invalid Google file ID");
3132
+ return id;
3133
+ }, "fileId");
3134
+ var unknownProfile = /* @__PURE__ */ __name((name, profiles) => new CliError("not_found", profiles.length ? `no profile ${name} here \u2014 profiles here: ${profiles.join(", ")}; a new one signs in with drive ${name} session start` : `no profiles here yet; create one with drive ${name} session start`, { reason: "profile.unknown", profiles }), "unknownProfile");
3135
+ var activeProfile = /* @__PURE__ */ __name((env, name) => {
3136
+ const config = readConfig(env);
3137
+ const profile = config.profiles[profileName(name)];
3138
+ if (!profile)
3139
+ throw unknownProfile(name, Object.keys(config.profiles).sort());
3140
+ return profile;
3141
+ }, "activeProfile");
3142
+ var checkTextLimit = /* @__PURE__ */ __name((value) => {
3143
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1)
3144
+ throw new CliError("validation_error", "max_text_chars must be a positive whole number of characters");
3145
+ if (value > MAX_TEXT_CHARS)
3146
+ throw new CliError("validation_error", `max_text_chars can be at most ${MAX_TEXT_CHARS}: the document readers return at most that many characters`);
3147
+ return value;
3148
+ }, "checkTextLimit");
3149
+ var textLimit = /* @__PURE__ */ __name((env, name) => activeProfile(env, name).max_text_chars ?? readConfig(env).defaults?.max_text_chars ?? MAX_TEXT_CHARS, "textLimit");
3150
+ var keepVersions = /* @__PURE__ */ __name((env, name) => keepVersionsForDays({ configured: activeProfile(env, name), shared: readConfig(env).defaults ?? {} }), "keepVersions");
3151
+ var transcriptsOf = /* @__PURE__ */ __name((env, name) => {
3152
+ const profile = activeProfile(env, name);
3153
+ return { mode: profile.transcripts, words: profile.transcript_words ?? [...TRANSCRIPT_WORDS] };
3154
+ }, "transcriptsOf");
3155
+ var pictureSearch = /* @__PURE__ */ __name((env, name) => activeProfile(env, name).picture_search ?? false, "pictureSearch");
3156
+ var googleAppOf = /* @__PURE__ */ __name((env, { file, clientId, profile } = {}) => {
3157
+ const own = file || clientId || env.DRIVE_GOOGLE_CLIENT_ID;
3158
+ const config = own ? void 0 : readConfig(env);
3159
+ const configClientId = (profile === void 0 ? void 0 : config?.profiles[profileName(profile)]?.google_client_id) ?? config?.defaults?.google_client_id;
3160
+ return googleApp({ env, prefix: "DRIVE", clientFile: file, clientId, configClientId });
3161
+ }, "googleAppOf");
3162
+ var application = /* @__PURE__ */ __name((env, choice = {}) => googleAppOf(env, choice).client, "application");
3163
+ var selectedFolders = /* @__PURE__ */ __name((env, profile, filter = {}) => activeProfile(env, profile).roots.flatMap((id) => filter.id === void 0 || id === filter.id ? [{ id }] : []), "selectedFolders");
3164
+ var configuredSessions = /* @__PURE__ */ __name((env, filter, knownPermissions) => Object.entries(readConfig(env, knownPermissions).profiles).flatMap(([name, row]) => (filter.profile === void 0 || filter.profile === name) && (filter.storage === void 0 || filter.storage === row.storage) ? [{ profile: name, selected_folders: row.roots.length, storage: row.storage }] : []), "configuredSessions");
3165
+ var maxAddProfiles = /* @__PURE__ */ __name((env) => readConfig(env).defaults?.max_add_profiles ?? DEFAULT_ADD_PROFILES, "maxAddProfiles");
3166
+ var checkAddProfiles = /* @__PURE__ */ __name((value) => {
3167
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MOST_ADD_PROFILES)
3168
+ throw new CliError("validation_error", `max_add_profiles is a whole number from 1 to ${MOST_ADD_PROFILES}`);
3169
+ return value;
3170
+ }, "checkAddProfiles");
3171
+ var profileLocked = /* @__PURE__ */ __name((lock, named) => new CliError("permission_error", `this process is locked to profile ${lock} (DRIVE_PROFILE_LOCK) \u2014 ${named} is refused`, {
3172
+ reason: "profile.locked"
3173
+ }), "profileLocked");
3174
+ var profileRequired = /* @__PURE__ */ __name((choices, how = "drive <profile> \u2026") => new CliError("validation_error", choices.length ? `name a profile: ${how} \u2014 profiles here: ${choices.join(", ")} (or set DRIVE_PROFILE)` : "no profiles here yet; create one with drive personal session start (any name in place of personal)", { reason: "profile.required", profiles: [...choices] }), "profileRequired");
3175
+
3176
+ export {
3177
+ oauthClientReport,
3178
+ factItem,
3179
+ memoryItem,
3180
+ CATALOG_FIELDS,
3181
+ addDocumentCatalogCommands,
3182
+ addLocalDocumentCommands,
3183
+ addDocumentFolderCommands,
3184
+ addDocumentHistoryCommands,
3185
+ addDocumentKnowledgeCommands,
3186
+ addDocumentMirrorCommands,
3187
+ addDocumentSearchCommand,
3188
+ addDocumentSyncCommands,
3189
+ permissionKeys,
3190
+ permissionNames,
3191
+ DEFAULT_LEVELS,
3192
+ methodPolicyKeys,
3193
+ sessionRow,
3194
+ fileRow,
3195
+ transcriptRow,
3196
+ TRANSCRIPTS_QUERY,
3197
+ SESSIONS_QUERY,
3198
+ FILES_QUERY,
3199
+ bindQuery2 as bindQuery,
3200
+ termsOf2 as termsOf,
3201
+ driveFileQuery,
3202
+ findTranscripts,
3203
+ transcriptQuery,
3204
+ DEFAULTS_ONLY,
3205
+ PROFILE_ONLY,
3206
+ SETTING_NAMES,
3207
+ configuration,
3208
+ paths,
3209
+ configPath,
3210
+ inspectConfig,
3211
+ configIssues,
3212
+ refusal,
3213
+ readConfig,
3214
+ writeConfig,
3215
+ withDefaults,
3216
+ profileName,
3217
+ fileId,
3218
+ unknownProfile,
3219
+ activeProfile,
3220
+ checkTextLimit,
3221
+ textLimit,
3222
+ keepVersions,
3223
+ transcriptsOf,
3224
+ pictureSearch,
3225
+ googleAppOf,
3226
+ application,
3227
+ selectedFolders,
3228
+ configuredSessions,
3229
+ maxAddProfiles,
3230
+ checkAddProfiles,
3231
+ profileLocked,
3232
+ profileRequired
3233
+ };