clikcode 1.0.3 → 1.0.5

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 (323) hide show
  1. package/README.md +25 -14
  2. package/dist/chunk-23TDEBGZ.js +71 -0
  3. package/dist/chunk-25T3GVS7.js +425 -0
  4. package/dist/chunk-2BBELGHY.js +11 -0
  5. package/dist/chunk-2EOL5PZL.js +208 -0
  6. package/dist/chunk-2GAB36IE.js +26 -0
  7. package/dist/chunk-2OLS7V66.js +2440 -0
  8. package/dist/chunk-2QFO2URB.js +179 -0
  9. package/dist/chunk-2QWPQRSU.js +254 -0
  10. package/dist/chunk-2YPAPAR3.js +184 -0
  11. package/dist/chunk-2ZAG5372.js +33 -0
  12. package/dist/chunk-32IKAIZC.js +12507 -0
  13. package/dist/chunk-34AZEGYW.js +95 -0
  14. package/dist/chunk-34JQYQCA.js +175 -0
  15. package/dist/chunk-34ZISPAO.js +67 -0
  16. package/dist/chunk-3AAAARE6.js +46 -0
  17. package/dist/chunk-3AJ6Q3OY.js +510 -0
  18. package/dist/chunk-3B2CHX7M.js +884 -0
  19. package/dist/chunk-3BUFORRX.js +59 -0
  20. package/dist/chunk-3QLHYYFK.js +30 -0
  21. package/dist/chunk-3RXBMYKZ.js +140 -0
  22. package/dist/chunk-3TFNIJWS.js +52 -0
  23. package/dist/chunk-3W3IPDFP.js +119 -0
  24. package/dist/chunk-3WMS7SEE.js +417 -0
  25. package/dist/chunk-435ZNSZ3.js +23 -0
  26. package/dist/chunk-4AQ5NINV.js +39 -0
  27. package/dist/chunk-4GVEJ5FK.js +168 -0
  28. package/dist/chunk-4GXAO3UY.js +262 -0
  29. package/dist/chunk-4L2ZZM4Q.js +332 -0
  30. package/dist/chunk-4LPDG57B.js +17 -0
  31. package/dist/chunk-4NN3XQQT.js +223 -0
  32. package/dist/chunk-4QZEZME7.js +54 -0
  33. package/dist/chunk-4R6CSC3S.js +38 -0
  34. package/dist/chunk-4RHXTL3W.js +514 -0
  35. package/dist/chunk-4SJMPTVQ.js +18 -0
  36. package/dist/chunk-4VY7G6TX.js +114 -0
  37. package/dist/chunk-5642PBF7.js +124 -0
  38. package/dist/chunk-5B6TVO4A.js +33 -0
  39. package/dist/chunk-5BJLDUPL.js +62 -0
  40. package/dist/chunk-5HMFFJWU.js +19 -0
  41. package/dist/chunk-5IKLK33T.js +69 -0
  42. package/dist/chunk-5NQ5FFMX.js +44 -0
  43. package/dist/chunk-5QNNW5L6.js +176 -0
  44. package/dist/chunk-5SM5UAWN.js +239 -0
  45. package/dist/chunk-5WYJTA6O.js +74 -0
  46. package/dist/chunk-5ZSR2Y5T.js +227 -0
  47. package/dist/chunk-5ZWUM5GH.js +39 -0
  48. package/dist/chunk-64E7D4HY.js +364 -0
  49. package/dist/chunk-6CK466BC.js +99 -0
  50. package/dist/chunk-6ES45HHO.js +138 -0
  51. package/dist/chunk-6HYEZFGL.js +277 -0
  52. package/dist/chunk-6Y7HLXGW.js +29 -0
  53. package/dist/chunk-6YKK4FYR.js +258 -0
  54. package/dist/chunk-74WNMLMS.js +117 -0
  55. package/dist/chunk-7AULZ7OD.js +55 -0
  56. package/dist/chunk-7DOKGSUN.js +101 -0
  57. package/dist/chunk-7IH5LTIZ.js +195 -0
  58. package/dist/chunk-7ISTS5NS.js +21 -0
  59. package/dist/chunk-7NMUTGOW.js +527 -0
  60. package/dist/chunk-7PNHUZEL.js +153 -0
  61. package/dist/chunk-7TSQLONI.js +88 -0
  62. package/dist/chunk-AE7TOLD5.js +30 -0
  63. package/dist/chunk-AEMHSXKA.js +130 -0
  64. package/dist/chunk-AKRYTS2D.js +211 -0
  65. package/dist/chunk-AMNSE36L.js +59 -0
  66. package/dist/chunk-AZVD74ZV.js +23 -0
  67. package/dist/chunk-B35DVOTK.js +1981 -0
  68. package/dist/chunk-B4HNJRAH.js +626 -0
  69. package/dist/chunk-B5WYPPHS.js +13 -0
  70. package/dist/chunk-BBOVDXQM.js +59 -0
  71. package/dist/chunk-BD3ECZLK.js +62 -0
  72. package/dist/chunk-BDGSOT74.js +4578 -0
  73. package/dist/chunk-BF5VEOPK.js +31 -0
  74. package/dist/chunk-BFFRW4XH.js +47 -0
  75. package/dist/chunk-BFPC6PEW.js +208 -0
  76. package/dist/chunk-BGEMY2JJ.js +376 -0
  77. package/dist/chunk-BISGNHKD.js +35 -0
  78. package/dist/chunk-BMRAEBRY.js +21 -0
  79. package/dist/chunk-BNTXAZXW.js +127 -0
  80. package/dist/chunk-BOQBXGSN.js +75 -0
  81. package/dist/chunk-BTJDSTQP.js +213 -0
  82. package/dist/chunk-BUOPJQP5.js +218 -0
  83. package/dist/chunk-BXFJS65Q.js +52 -0
  84. package/dist/chunk-BXPQFSX5.js +59 -0
  85. package/dist/chunk-C57LIWNY.js +1269 -0
  86. package/dist/chunk-C6YVCCWR.js +74 -0
  87. package/dist/chunk-CAADDF6M.js +167 -0
  88. package/dist/chunk-CBANJFBO.js +69 -0
  89. package/dist/chunk-CERF3RIB.js +597 -0
  90. package/dist/chunk-COAS5ETR.js +46 -0
  91. package/dist/chunk-CQ7J6UQ7.js +78 -0
  92. package/dist/chunk-CRUVYGO2.js +26 -0
  93. package/dist/chunk-CVFVFRGN.js +58 -0
  94. package/dist/chunk-D2UK66HM.js +37 -0
  95. package/dist/chunk-D2W7SA4R.js +18 -0
  96. package/dist/chunk-DA44ZENT.js +501 -0
  97. package/dist/chunk-DAJ76TOC.js +99 -0
  98. package/dist/chunk-DCZ6CIUM.js +147 -0
  99. package/dist/chunk-DF35KMXM.js +1314 -0
  100. package/dist/chunk-DGASQT26.js +151 -0
  101. package/dist/chunk-DJT57C5P.js +55 -0
  102. package/dist/chunk-DKDPZTD3.js +44 -0
  103. package/dist/chunk-DQYVQ2N7.js +77 -0
  104. package/dist/chunk-DRTP2RTY.js +266 -0
  105. package/dist/chunk-DW2BMUKY.js +61 -0
  106. package/dist/chunk-DW5T5ZVU.js +307 -0
  107. package/dist/chunk-DXKNDNFC.js +164 -0
  108. package/dist/chunk-DZEQ7UYR.js +291 -0
  109. package/dist/chunk-E4F4OUAC.js +463 -0
  110. package/dist/chunk-EE4B6A7W.js +69 -0
  111. package/dist/chunk-EISKIYWG.js +23 -0
  112. package/dist/chunk-EKAQK7UQ.js +235 -0
  113. package/dist/chunk-EOBTJV32.js +123 -0
  114. package/dist/chunk-ESF3DIZY.js +325 -0
  115. package/dist/chunk-EVOHOZ4U.js +45 -0
  116. package/dist/chunk-EXN4KHLB.js +110 -0
  117. package/dist/chunk-F252T6Y3.js +78 -0
  118. package/dist/chunk-F3DP4ZA2.js +40 -0
  119. package/dist/chunk-F6F47QAY.js +58 -0
  120. package/dist/chunk-FA3Y23ZW.js +57 -0
  121. package/dist/chunk-FBKXE4EJ.js +640 -0
  122. package/dist/chunk-FCGEB3H6.js +23 -0
  123. package/dist/chunk-FF7ZVYJF.js +3732 -0
  124. package/dist/chunk-FFGKN6L3.js +39 -0
  125. package/dist/chunk-FFGU4GCC.js +94 -0
  126. package/dist/chunk-FSFDAOVP.js +74 -0
  127. package/dist/chunk-FT5TX7OX.js +1573 -0
  128. package/dist/chunk-G3QP67Z7.js +232 -0
  129. package/dist/chunk-G5ORJKV2.js +179 -0
  130. package/dist/chunk-GFNC62PE.js +111 -0
  131. package/dist/chunk-GGK43Q3N.js +67 -0
  132. package/dist/chunk-GGYKY4GF.js +11537 -0
  133. package/dist/chunk-GGYNHGNJ.js +55 -0
  134. package/dist/chunk-GLY7RM3C.js +354 -0
  135. package/dist/chunk-GQBZU6EO.js +20 -0
  136. package/dist/chunk-GSXENUZL.js +9 -0
  137. package/dist/chunk-GTOAT5D3.js +40 -0
  138. package/dist/chunk-GWCMDPQU.js +1007 -0
  139. package/dist/chunk-GXYSMYHJ.js +152 -0
  140. package/dist/chunk-GYMAI5NY.js +14 -0
  141. package/dist/chunk-H2VZMKPE.js +30 -0
  142. package/dist/chunk-H4THUNBM.js +2091 -0
  143. package/dist/chunk-HGRVSNUZ.js +361 -0
  144. package/dist/chunk-HI4VY473.js +27 -0
  145. package/dist/chunk-HOJRSD3Q.js +447 -0
  146. package/dist/chunk-HRX25W35.js +82 -0
  147. package/dist/chunk-HSE4AQYV.js +55 -0
  148. package/dist/chunk-HU5SSUFX.js +383 -0
  149. package/dist/chunk-I3GDBJLH.js +196 -0
  150. package/dist/chunk-I75EDU75.js +684 -0
  151. package/dist/chunk-IBA7DMIO.js +20 -0
  152. package/dist/chunk-IC6N4NZA.js +231 -0
  153. package/dist/chunk-IF43HIGV.js +284 -0
  154. package/dist/chunk-IGZ6C2MC.js +439 -0
  155. package/dist/chunk-IMLTL2MY.js +192 -0
  156. package/dist/chunk-IMZL6SGR.js +33 -0
  157. package/dist/chunk-IS4USJPY.js +516 -0
  158. package/dist/chunk-ISFSPN2F.js +82 -0
  159. package/dist/chunk-IXE7GTFI.js +55 -0
  160. package/dist/chunk-IZ77QJQG.js +36 -0
  161. package/dist/chunk-J2PACWRQ.js +34 -0
  162. package/dist/chunk-J6EGFVQX.js +180 -0
  163. package/dist/chunk-JEKOD43D.js +22 -0
  164. package/dist/chunk-JGIWATSG.js +30 -0
  165. package/dist/chunk-JYBONKD4.js +43 -0
  166. package/dist/chunk-K2NLG2HK.js +454 -0
  167. package/dist/chunk-KCQ4TBLS.js +164 -0
  168. package/dist/chunk-KD5KIVMS.js +176 -0
  169. package/dist/chunk-KHW6TX6I.js +63 -0
  170. package/dist/chunk-KI5GZFCE.js +520 -0
  171. package/dist/chunk-KN34B7NO.js +105 -0
  172. package/dist/chunk-KYUHIFP3.js +136 -0
  173. package/dist/chunk-KZL5VS4B.js +300 -0
  174. package/dist/chunk-L3VW3QIH.js +48 -0
  175. package/dist/chunk-LA6MG4ET.js +2110 -0
  176. package/dist/chunk-LAVFOA3S.js +66 -0
  177. package/dist/chunk-LB4OA77N.js +13 -0
  178. package/dist/chunk-LBFRF2K4.js +196 -0
  179. package/dist/chunk-LM6EIA4B.js +93 -0
  180. package/dist/chunk-LPCNRGJ7.js +692 -0
  181. package/dist/chunk-LSLNL5T3.js +168 -0
  182. package/dist/chunk-LVRRWP4W.js +568 -0
  183. package/dist/chunk-LWCFBRHL.js +33 -0
  184. package/dist/chunk-LXFTMGZZ.js +166 -0
  185. package/dist/chunk-M33LVA4M.js +151 -0
  186. package/dist/chunk-M3FO5UMK.js +4944 -0
  187. package/dist/chunk-M5QNDBAY.js +66 -0
  188. package/dist/chunk-M6ND6KBE.js +1291 -0
  189. package/dist/chunk-M7H3WQTE.js +76 -0
  190. package/dist/chunk-MCBRVPA7.js +191 -0
  191. package/dist/chunk-MCSDWZET.js +91 -0
  192. package/dist/chunk-MDT5XDXL.js +289 -0
  193. package/dist/chunk-MJG3IQY4.js +91 -0
  194. package/dist/chunk-MOU3N2UL.js +44 -0
  195. package/dist/chunk-MP4KZOQC.js +3451 -0
  196. package/dist/chunk-MPAJ446F.js +66 -0
  197. package/dist/chunk-MVJZZ6AL.js +16 -0
  198. package/dist/chunk-MXS6S2PY.js +253 -0
  199. package/dist/chunk-N3SFDYM7.js +291 -0
  200. package/dist/chunk-NAOX3JUB.js +13 -0
  201. package/dist/chunk-NEKKIBCX.js +283 -0
  202. package/dist/chunk-NKDATMEM.js +133 -0
  203. package/dist/chunk-NR4FMC4K.js +395 -0
  204. package/dist/chunk-NSOHOJBR.js +221 -0
  205. package/dist/chunk-NTDB6QKF.js +29 -0
  206. package/dist/chunk-NWEYRBWK.js +25 -0
  207. package/dist/chunk-O2YSNYWD.js +23 -0
  208. package/dist/chunk-O3EW7LAY.js +54 -0
  209. package/dist/chunk-O7BNJIXU.js +366 -0
  210. package/dist/chunk-OARL2NXZ.js +116 -0
  211. package/dist/chunk-OHKZUEJW.js +351 -0
  212. package/dist/chunk-OKU45BXA.js +647 -0
  213. package/dist/chunk-OL4JBD3J.js +59 -0
  214. package/dist/chunk-OLUO5DDR.js +192 -0
  215. package/dist/chunk-OQ245JLA.js +196 -0
  216. package/dist/chunk-P72UZAQI.js +289 -0
  217. package/dist/chunk-PAL2ENB6.js +20 -0
  218. package/dist/chunk-PAXYQZH7.js +53 -0
  219. package/dist/chunk-PDPEM5VW.js +51 -0
  220. package/dist/chunk-PEWCDI2C.js +668 -0
  221. package/dist/chunk-PGZ54EDX.js +27 -0
  222. package/dist/chunk-PRWVLDZF.js +73 -0
  223. package/dist/chunk-PSQQ75VJ.js +52 -0
  224. package/dist/chunk-PUOVIFHW.js +118 -0
  225. package/dist/chunk-PWBF2X3V.js +107 -0
  226. package/dist/chunk-PWXII6HF.js +43 -0
  227. package/dist/chunk-Q35VLJRT.js +80 -0
  228. package/dist/chunk-QJP7EYGL.js +128 -0
  229. package/dist/chunk-QPQKX2MK.js +8836 -0
  230. package/dist/chunk-QQRLPY25.js +1053 -0
  231. package/dist/chunk-QUS4ER2W.js +407 -0
  232. package/dist/chunk-QYHI3YET.js +29 -0
  233. package/dist/chunk-QYRU2UQI.js +32 -0
  234. package/dist/chunk-R6XVVQGC.js +13 -0
  235. package/dist/chunk-R7QN6ONS.js +483 -0
  236. package/dist/chunk-RD23MPGC.js +221 -0
  237. package/dist/chunk-RDDWQBEM.js +185 -0
  238. package/dist/chunk-RDLLDYFO.js +104 -0
  239. package/dist/chunk-RE4TGORR.js +84 -0
  240. package/dist/chunk-RJLHVYQY.js +217 -0
  241. package/dist/chunk-RJLPTWHW.js +905 -0
  242. package/dist/chunk-RKUVLRZI.js +295 -0
  243. package/dist/chunk-ROGXPGYR.js +37 -0
  244. package/dist/chunk-RSZGEL5U.js +163 -0
  245. package/dist/chunk-RVUOIJXN.js +909 -0
  246. package/dist/chunk-RW7F4JRP.js +11 -0
  247. package/dist/chunk-S4UO3AO3.js +53 -0
  248. package/dist/chunk-S5JAAF6S.js +585 -0
  249. package/dist/chunk-SNU37TQI.js +56 -0
  250. package/dist/chunk-SQVUDO2O.js +31 -0
  251. package/dist/chunk-SYVHIYQT.js +66 -0
  252. package/dist/chunk-SZBQMTG2.js +85 -0
  253. package/dist/chunk-T5VCXA3J.js +25 -0
  254. package/dist/chunk-TK6NSP56.js +30 -0
  255. package/dist/chunk-TKWVMA6L.js +22 -0
  256. package/dist/chunk-TQDKJHWX.js +59 -0
  257. package/dist/chunk-TQDM7S5N.js +127 -0
  258. package/dist/chunk-TULAXS77.js +23 -0
  259. package/dist/chunk-TVT45XNH.js +4625 -0
  260. package/dist/chunk-TWCVV2JO.js +467 -0
  261. package/dist/chunk-U4DKAD6S.js +47 -0
  262. package/dist/chunk-UA5K2BTI.js +564 -0
  263. package/dist/chunk-UAMKCMOK.js +40 -0
  264. package/dist/chunk-UBMVADBF.js +51 -0
  265. package/dist/chunk-UFQ5A5PW.js +645 -0
  266. package/dist/chunk-UOD2SOLL.js +1301 -0
  267. package/dist/chunk-UTSB4LOW.js +156 -0
  268. package/dist/chunk-UVXNIUTN.js +412 -0
  269. package/dist/chunk-UXVPXYPE.js +90 -0
  270. package/dist/chunk-UYEEMIWR.js +374 -0
  271. package/dist/chunk-VBGM5ZBW.js +54 -0
  272. package/dist/chunk-VEWPCZPG.js +762 -0
  273. package/dist/chunk-VIRDLZ5E.js +108 -0
  274. package/dist/chunk-VMPO7WKN.js +52 -0
  275. package/dist/chunk-W2NVSDO5.js +5122 -0
  276. package/dist/chunk-W3YYPBEA.js +176 -0
  277. package/dist/chunk-W5AYOICN.js +280 -0
  278. package/dist/chunk-W5GZOIUF.js +27 -0
  279. package/dist/chunk-WHKNLZ3C.js +76 -0
  280. package/dist/chunk-WKBEPPQ5.js +1409 -0
  281. package/dist/chunk-WM3Z6QKQ.js +151 -0
  282. package/dist/chunk-WMI2TPMA.js +31 -0
  283. package/dist/chunk-WNX5VD7S.js +150 -0
  284. package/dist/chunk-WOVTYST3.js +60 -0
  285. package/dist/chunk-WPB5WEZJ.js +546 -0
  286. package/dist/chunk-WUO5EOAT.js +44 -0
  287. package/dist/chunk-WWLJMP6D.js +133 -0
  288. package/dist/chunk-WZMLH3XP.js +58 -0
  289. package/dist/chunk-WZYVLUVQ.js +79 -0
  290. package/dist/chunk-X2OCPVU5.js +135 -0
  291. package/dist/chunk-X3CL6DTR.js +95 -0
  292. package/dist/chunk-X6WF7JEV.js +354 -0
  293. package/dist/chunk-XAHGBPWT.js +44 -0
  294. package/dist/chunk-XCKQ5BM2.js +228 -0
  295. package/dist/chunk-XIBYREEY.js +106 -0
  296. package/dist/chunk-XKW5NDMR.js +378 -0
  297. package/dist/chunk-XRDALAO3.js +100 -0
  298. package/dist/chunk-XUP22EAS.js +41 -0
  299. package/dist/chunk-XWAC3MKW.js +243 -0
  300. package/dist/chunk-Y3R7JMXB.js +59 -0
  301. package/dist/chunk-Y54LTP4W.js +82 -0
  302. package/dist/chunk-Y7UECI4M.js +99 -0
  303. package/dist/chunk-YACGDFHC.js +47 -0
  304. package/dist/chunk-YHNIQPKY.js +71 -0
  305. package/dist/chunk-YMBR6HYP.js +111 -0
  306. package/dist/chunk-YMCH3L2S.js +26 -0
  307. package/dist/chunk-Z4ZU6T7V.js +99 -0
  308. package/dist/chunk-ZDPF67ZZ.js +173 -0
  309. package/dist/chunk-ZFC2Q67K.js +101 -0
  310. package/dist/chunk-ZGHNNSCT.js +114 -0
  311. package/dist/chunk-ZGX3ERAT.js +173 -0
  312. package/dist/chunk-ZI3YHEBY.js +37 -0
  313. package/dist/chunk-ZN7G6JLS.js +639 -0
  314. package/dist/chunk-ZNPFQMXT.js +47 -0
  315. package/dist/chunk-ZOU3LV4U.js +63 -0
  316. package/dist/chunk-ZT7B4H2V.js +117 -0
  317. package/dist/chunk-ZZCBDNZI.js +58 -0
  318. package/dist/cli.js +498 -112593
  319. package/dist/computer-tools.js +36642 -21258
  320. package/dist/harness-catalog.cjs +88 -43
  321. package/dist/index.js +1 -1
  322. package/dist/local-model-supervisor.cjs +555 -0
  323. package/package.json +3 -4
@@ -0,0 +1,909 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ cloneData,
5
+ sameData
6
+ } from "./chunk-KHW6TX6I.js";
7
+ import {
8
+ withFileLock
9
+ } from "./chunk-4L2ZZM4Q.js";
10
+ import {
11
+ atomicWriteFile,
12
+ ensurePrivateDirectory
13
+ } from "./chunk-F6F47QAY.js";
14
+ import {
15
+ lifecycle,
16
+ quiet,
17
+ swallowed
18
+ } from "./chunk-RDDWQBEM.js";
19
+ import {
20
+ safeRecordFileName,
21
+ sessionFilePath,
22
+ sessionLegacyBackupPath,
23
+ sessionLockPath,
24
+ sessionLogPath,
25
+ sessionLoggedPath,
26
+ sessionPendingPath,
27
+ sessionTurnPath,
28
+ sessionsDirectory
29
+ } from "./chunk-MPAJ446F.js";
30
+
31
+ // src/session/store/chat-log.ts
32
+ import { randomBytes } from "node:crypto";
33
+ import { constants } from "node:fs";
34
+ import { open, readFile, stat, unlink } from "node:fs/promises";
35
+ var LOG_VERSION = 2;
36
+ var STATS = { fullReads: 0, tailReads: 0, appends: 0, rewrites: 0, bytesRead: 0 };
37
+ var cache = /* @__PURE__ */ new Map();
38
+ function deepFreeze(value) {
39
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return;
40
+ Object.freeze(value);
41
+ for (const item of Object.values(value)) deepFreeze(item);
42
+ }
43
+ function generationPrefix(gen) {
44
+ return `{"v":${LOG_VERSION},"gen":${JSON.stringify(gen)}`;
45
+ }
46
+ function headerLine(gen, id) {
47
+ return `${generationPrefix(gen)},"id":${JSON.stringify(id)}}
48
+ `;
49
+ }
50
+ var GEN_PREFIX_BYTES = 64;
51
+ function applyLines(into, text, first) {
52
+ let lines = text.split("\n");
53
+ lines.pop();
54
+ if (first && lines.length) {
55
+ const header = parseLine(lines[0]);
56
+ if (header && "v" in header) {
57
+ into.gen = typeof header.gen === "string" ? header.gen : "";
58
+ into.foreign = header.v !== LOG_VERSION;
59
+ lines = lines.slice(1);
60
+ }
61
+ }
62
+ for (const line of lines) {
63
+ if (!line.trim()) continue;
64
+ const record = parseLine(line);
65
+ if (!record || record.add !== void 0 && !Array.isArray(record.add)) {
66
+ into.skipped += 1;
67
+ continue;
68
+ }
69
+ if (record.add) {
70
+ into.hasMessages = true;
71
+ for (const message of record.add) if (message && typeof message === "object") into.added.push(message);
72
+ }
73
+ if (record.p !== void 0) into.pending = record.p && typeof record.p === "object" ? record.p : void 0;
74
+ if (record.legacy && typeof record.legacy === "object") into.legacy = record.legacy;
75
+ }
76
+ }
77
+ function parseLine(line) {
78
+ try {
79
+ const value = JSON.parse(line);
80
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
81
+ } catch {
82
+ return void 0;
83
+ }
84
+ }
85
+ async function readRange(handle, from, length) {
86
+ const buffer = Buffer.allocUnsafe(length);
87
+ let done = 0;
88
+ while (done < length) {
89
+ const { bytesRead } = await handle.read(buffer, done, length - done, from + done);
90
+ if (bytesRead === 0) break;
91
+ done += bytesRead;
92
+ }
93
+ STATS.bytesRead += done;
94
+ return done === length ? buffer : buffer.subarray(0, done);
95
+ }
96
+ async function loadChatLog(id) {
97
+ const path = sessionLogPath(id);
98
+ const handle = await open(path, "r").catch((error) => {
99
+ if (error.code === "ENOENT") return void 0;
100
+ throw error;
101
+ });
102
+ if (!handle) {
103
+ cache.delete(path);
104
+ return void 0;
105
+ }
106
+ try {
107
+ const info = await handle.stat();
108
+ const cached = cache.get(path);
109
+ if (cached && cached.ino === info.ino && cached.size === info.size && cached.mtimeMs === info.mtimeMs) return cached;
110
+ let log;
111
+ if (cached && cached.ino === info.ino && info.size > cached.size && cached.gen && (await readRange(handle, 0, GEN_PREFIX_BYTES)).toString("utf8").startsWith(generationPrefix(cached.gen))) {
112
+ log = await readTail(handle, cached, info);
113
+ } else log = await readWhole(handle, info);
114
+ if (log.skipped > (cached?.gen === log.gen ? cached.skipped : 0)) lifecycle("store.log-damaged", { session: id, skipped: log.skipped });
115
+ cache.set(path, log);
116
+ return log;
117
+ } finally {
118
+ await handle.close();
119
+ }
120
+ }
121
+ async function readWhole(handle, info) {
122
+ STATS.fullReads += 1;
123
+ const bytes = await readRange(handle, 0, info.size);
124
+ const end = bytes.lastIndexOf(10) + 1;
125
+ const building = { gen: "", foreign: false, added: [], hasMessages: false, pending: void 0, legacy: void 0, skipped: 0 };
126
+ applyLines(building, bytes.toString("utf8", 0, end), true);
127
+ deepFreeze(building.added);
128
+ return {
129
+ gen: building.gen,
130
+ messages: Object.freeze(building.added),
131
+ hasMessages: building.hasMessages,
132
+ pending: building.pending,
133
+ legacy: building.legacy,
134
+ foreign: building.foreign,
135
+ ino: info.ino,
136
+ mtimeMs: info.mtimeMs,
137
+ size: bytes.length,
138
+ consumed: end,
139
+ skipped: building.skipped
140
+ };
141
+ }
142
+ async function readTail(handle, cached, info) {
143
+ STATS.tailReads += 1;
144
+ const bytes = await readRange(handle, cached.consumed, info.size - cached.consumed);
145
+ const end = bytes.lastIndexOf(10) + 1;
146
+ const building = {
147
+ gen: cached.gen,
148
+ foreign: cached.foreign,
149
+ added: [],
150
+ hasMessages: cached.hasMessages,
151
+ pending: cached.pending,
152
+ legacy: cached.legacy,
153
+ skipped: cached.skipped
154
+ };
155
+ applyLines(building, bytes.toString("utf8", 0, end), false);
156
+ deepFreeze(building.added);
157
+ return {
158
+ gen: cached.gen,
159
+ // A new array (the one readers hold is frozen); its messages are shared.
160
+ messages: building.added.length ? Object.freeze([...cached.messages, ...building.added]) : cached.messages,
161
+ hasMessages: building.hasMessages,
162
+ pending: building.pending,
163
+ legacy: building.legacy,
164
+ foreign: cached.foreign,
165
+ ino: info.ino,
166
+ mtimeMs: info.mtimeMs,
167
+ size: cached.consumed + bytes.length,
168
+ consumed: cached.consumed + end,
169
+ skipped: building.skipped
170
+ };
171
+ }
172
+ function recordLine(record) {
173
+ return `${JSON.stringify(record)}
174
+ `;
175
+ }
176
+ async function appendChatLog(id, log, records, options) {
177
+ if (log.foreign) throw new Error(`the history of conversation ${id} was written by a newer ClikCode; this one does not change it`);
178
+ if (!records.length) return;
179
+ const text = (log.consumed === log.size ? "" : "\n") + records.map(recordLine).join("");
180
+ const handle = await open(sessionLogPath(id), constants.O_WRONLY | constants.O_APPEND);
181
+ try {
182
+ await handle.writeFile(text);
183
+ if (options.durable) await handle.sync();
184
+ } finally {
185
+ await handle.close();
186
+ }
187
+ STATS.appends += 1;
188
+ }
189
+ function chatLogText(id, content) {
190
+ const parts = [headerLine(randomBytes(8).toString("hex"), id)];
191
+ if (content.legacy) parts.push(recordLine({ legacy: content.legacy }));
192
+ if (content.messages) {
193
+ if (!content.messages.length) parts.push(recordLine({ add: [] }));
194
+ for (const message of content.messages) parts.push(`{"add":[${JSON.stringify(message)}]}
195
+ `);
196
+ }
197
+ if (content.pending) parts.push(recordLine({ p: content.pending }));
198
+ return parts.join("");
199
+ }
200
+ async function writeChatLog(id, content) {
201
+ await atomicWriteFile(sessionLogPath(id), chatLogText(id, content));
202
+ STATS.rewrites += 1;
203
+ }
204
+ function parseChatLog(text) {
205
+ const end = text.lastIndexOf("\n") + 1;
206
+ const building = { gen: "", foreign: false, added: [], hasMessages: false, pending: void 0, legacy: void 0, skipped: 0 };
207
+ applyLines(building, text.slice(0, end), true);
208
+ return { messages: building.added, hasMessages: building.hasMessages, pending: building.pending, legacy: building.legacy, skipped: building.skipped + (end < text.length ? 1 : 0) };
209
+ }
210
+ var pendingCache = /* @__PURE__ */ new Map();
211
+ async function storePendingFile(id, turn) {
212
+ const path = sessionPendingPath(id);
213
+ await atomicWriteFile(path, JSON.stringify(turn), { durable: false });
214
+ const info = await stat(path).catch(quiet("session/store/chat-log"));
215
+ if (info) pendingCache.set(path, { ino: info.ino, mtimeMs: info.mtimeMs, size: info.size, turn });
216
+ else pendingCache.delete(path);
217
+ }
218
+ async function loadPendingFile(id) {
219
+ const path = sessionPendingPath(id);
220
+ const info = await stat(path).catch(quiet("session/store/chat-log"));
221
+ if (!info) {
222
+ pendingCache.delete(path);
223
+ return void 0;
224
+ }
225
+ const cached = pendingCache.get(path);
226
+ if (cached && cached.ino === info.ino && cached.mtimeMs === info.mtimeMs && cached.size === info.size) return cached.turn;
227
+ try {
228
+ const turn = JSON.parse(await readFile(path, "utf8"));
229
+ if (!turn || typeof turn !== "object" || typeof turn.startedAt !== "string") return void 0;
230
+ pendingCache.set(path, { ino: info.ino, mtimeMs: info.mtimeMs, size: info.size, turn });
231
+ return turn;
232
+ } catch {
233
+ return void 0;
234
+ }
235
+ }
236
+ async function removePendingFile(id) {
237
+ const path = sessionPendingPath(id);
238
+ pendingCache.delete(path);
239
+ await unlink(path).catch((error) => {
240
+ if (error.code !== "ENOENT") throw error;
241
+ });
242
+ }
243
+ var logged = /* @__PURE__ */ new Set();
244
+ async function markLogged(id) {
245
+ const path = sessionLoggedPath(id);
246
+ if (logged.has(path)) return;
247
+ try {
248
+ await (await open(path, "wx", 384)).close();
249
+ } catch (error) {
250
+ if (error.code !== "EEXIST") return;
251
+ }
252
+ logged.add(path);
253
+ }
254
+ async function hadLog(id) {
255
+ const path = sessionLoggedPath(id);
256
+ if (logged.has(path)) return true;
257
+ if (!await stat(path).then(() => true, () => false)) return false;
258
+ logged.add(path);
259
+ return true;
260
+ }
261
+ async function unmarkLogged(id) {
262
+ const path = sessionLoggedPath(id);
263
+ logged.delete(path);
264
+ await unlink(path).catch((error) => {
265
+ if (error.code !== "ENOENT") throw error;
266
+ });
267
+ }
268
+ async function removeChatLog(id) {
269
+ cache.delete(sessionLogPath(id));
270
+ await unlink(sessionLogPath(id)).catch((error) => {
271
+ if (error.code !== "ENOENT") throw error;
272
+ });
273
+ await removePendingFile(id);
274
+ }
275
+ async function chatLogId(path) {
276
+ const handle = await open(path, "r").catch(quiet("session/store/chat-log"));
277
+ if (!handle) return void 0;
278
+ try {
279
+ const head = (await readRange(handle, 0, 4096)).toString("utf8");
280
+ const line = head.slice(0, head.indexOf("\n"));
281
+ const header = parseLine(line);
282
+ return typeof header?.id === "string" ? header.id : void 0;
283
+ } finally {
284
+ await handle.close();
285
+ }
286
+ }
287
+
288
+ // src/session/store/transcripts.ts
289
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
290
+ import { constants as constants2 } from "node:fs";
291
+ import { copyFile, link, open as open2, readdir as readdir2, readFile as readFile3, rename as rename2, stat as stat3, unlink as unlink3 } from "node:fs/promises";
292
+ import { dirname, join as join2 } from "node:path";
293
+
294
+ // src/session/store/records.ts
295
+ import { readFile as readFile2, readdir, rename, stat as stat2, unlink as unlink2 } from "node:fs/promises";
296
+ import { join } from "node:path";
297
+ var fileCache = /* @__PURE__ */ new Map();
298
+ var turnCache = /* @__PURE__ */ new Map();
299
+ async function fileIdentity(path) {
300
+ const info = await stat2(path).catch(quiet("session/store/records"));
301
+ return info ? `${info.ino}:${info.size}:${info.mtimeMs}` : void 0;
302
+ }
303
+ async function loadLegacyFile(id) {
304
+ const path = sessionFilePath(id);
305
+ const info = await stat2(path).catch(quiet("session/store/records"));
306
+ if (!info) {
307
+ fileCache.delete(path);
308
+ return void 0;
309
+ }
310
+ const cached = fileCache.get(path);
311
+ if (cached && cached.ino === info.ino && cached.mtimeMs === info.mtimeMs && cached.ctimeMs === info.ctimeMs && cached.size === info.size) {
312
+ return cached.file;
313
+ }
314
+ let raw;
315
+ try {
316
+ raw = await readFile2(path, "utf8");
317
+ } catch (error) {
318
+ if (error.code === "ENOENT") return void 0;
319
+ throw error;
320
+ }
321
+ let file;
322
+ try {
323
+ const parsed = JSON.parse(raw);
324
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not a session record");
325
+ file = parsed;
326
+ } catch {
327
+ await rename(path, `${path}.corrupt-${Date.now()}`).catch(quiet("session/store/records"));
328
+ fileCache.delete(path);
329
+ return void 0;
330
+ }
331
+ fileCache.set(path, { ino: info.ino, mtimeMs: info.mtimeMs, ctimeMs: info.ctimeMs, size: info.size, file });
332
+ return file;
333
+ }
334
+ async function loadTurnFile(id) {
335
+ const path = sessionTurnPath(id);
336
+ const info = await stat2(path).catch(quiet("session/store/records"));
337
+ if (!info) {
338
+ turnCache.delete(path);
339
+ return void 0;
340
+ }
341
+ const cached = turnCache.get(path);
342
+ if (cached && cached.ino === info.ino && cached.mtimeMs === info.mtimeMs && cached.ctimeMs === info.ctimeMs && cached.size === info.size) {
343
+ return cached.turn;
344
+ }
345
+ try {
346
+ const turn = JSON.parse(await readFile2(path, "utf8"));
347
+ if (!turn || typeof turn !== "object" || typeof turn.startedAt !== "string") return void 0;
348
+ turnCache.set(path, { ino: info.ino, mtimeMs: info.mtimeMs, ctimeMs: info.ctimeMs, size: info.size, turn });
349
+ return turn;
350
+ } catch {
351
+ return void 0;
352
+ }
353
+ }
354
+ function continuesTurn(stored, turn) {
355
+ return turn.startedAt === stored.startedAt && turn.prompt === stored.prompt && turn.updatedAt >= stored.updatedAt;
356
+ }
357
+ async function legacyPendingTurn(id, file) {
358
+ if (!file.pendingTurn) return void 0;
359
+ const turn = await loadTurnFile(id);
360
+ return turn && continuesTurn(file.pendingTurn, turn) ? turn : file.pendingTurn;
361
+ }
362
+ var materialized = /* @__PURE__ */ new WeakMap();
363
+ async function materializedMessages(file, seen, walk = { cycle: false }) {
364
+ const ref = file.transcriptRef;
365
+ if (!ref) return file.messages;
366
+ let parentMessages;
367
+ if (!seen.has(ref.sessionId)) {
368
+ seen.add(ref.sessionId);
369
+ const parent = await loadLegacyFile(ref.sessionId);
370
+ parentMessages = parent ? await materializedMessages(parent, seen, walk) : void 0;
371
+ } else walk.cycle = true;
372
+ const cached = materialized.get(file);
373
+ if (cached && !walk.cycle && cached.from === parentMessages) return cached.messages;
374
+ const messages = [...(parentMessages ?? []).slice(0, ref.uptoIndex), ...file.messages ?? []];
375
+ if (!walk.cycle) materialized.set(file, { from: parentMessages, messages });
376
+ return messages;
377
+ }
378
+ function deepFreeze2(value) {
379
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return;
380
+ Object.freeze(value);
381
+ for (const item of Object.values(value)) deepFreeze2(item);
382
+ }
383
+ function isStubNote(message) {
384
+ return message.storedInLog === true;
385
+ }
386
+ var withoutStub = /* @__PURE__ */ new WeakMap();
387
+ async function readLegacyTranscript(id) {
388
+ const file = await loadLegacyFile(id);
389
+ if (!file) return void 0;
390
+ let messages = await materializedMessages(file, /* @__PURE__ */ new Set([id]));
391
+ if (messages) {
392
+ deepFreeze2(messages);
393
+ if (messages.some(isStubNote)) {
394
+ const all = messages;
395
+ messages = withoutStub.get(all) ?? Object.freeze(all.filter((message) => !isStubNote(message)));
396
+ withoutStub.set(all, messages);
397
+ }
398
+ }
399
+ return { file, messages, pendingTurn: await legacyPendingTurn(id, file) };
400
+ }
401
+ async function giveLegacyChildrenTheirCopy(parentId, withChildLock) {
402
+ const rewritten = [];
403
+ for (const id of await listStoredSessionIds()) {
404
+ if (id === parentId) continue;
405
+ const peek = await loadLegacyFile(id);
406
+ if (peek?.transcriptRef?.sessionId !== parentId) continue;
407
+ await withChildLock(id, async () => {
408
+ const file = await loadLegacyFile(id);
409
+ if (file?.transcriptRef?.sessionId !== parentId) return;
410
+ const messages = await materializedMessages(file, /* @__PURE__ */ new Set([id]));
411
+ const { transcriptRef: _dropped, ...rest } = file;
412
+ await storeLegacyFile(id, { ...rest, messages: [...messages ?? []] });
413
+ rewritten.push(id);
414
+ });
415
+ }
416
+ return rewritten;
417
+ }
418
+ async function storeLegacyFile(id, file) {
419
+ const path = sessionFilePath(id);
420
+ await atomicWriteFile(path, JSON.stringify(file));
421
+ const info = await stat2(path).catch(quiet("session/store/records"));
422
+ if (info) fileCache.set(path, { ino: info.ino, mtimeMs: info.mtimeMs, ctimeMs: info.ctimeMs, size: info.size, file });
423
+ else fileCache.delete(path);
424
+ }
425
+ async function removeIfThere(path) {
426
+ await unlink2(path).catch((error) => {
427
+ if (error.code !== "ENOENT") throw error;
428
+ });
429
+ }
430
+ async function removeLegacyFiles(id) {
431
+ fileCache.delete(sessionFilePath(id));
432
+ turnCache.delete(sessionTurnPath(id));
433
+ await removeIfThere(sessionFilePath(id));
434
+ await removeIfThere(sessionTurnPath(id));
435
+ for (const name of await readdir(sessionsDirectory()).catch(() => [])) {
436
+ if (isLegacyBackupOf(id, name)) await removeIfThere(join(sessionsDirectory(), name));
437
+ }
438
+ }
439
+ function isLegacyBackupOf(id, name) {
440
+ const base = sessionLegacyBackupPath(id).slice(sessionsDirectory().length + 1);
441
+ return name === base || name.startsWith(`${base}-`) && /^\d+$/.test(name.slice(base.length + 1));
442
+ }
443
+ var DIGEST_STEM = /^h-[0-9a-f]{64}$/;
444
+ async function listStoredSessionIds() {
445
+ const names = await readdir(sessionsDirectory()).catch(() => []);
446
+ const ids = /* @__PURE__ */ new Set();
447
+ for (const name of names) {
448
+ const suffix = name.endsWith(".json") ? ".json" : name.endsWith(".jsonl") ? ".jsonl" : void 0;
449
+ if (!suffix) continue;
450
+ const stem = name.slice(0, -suffix.length);
451
+ const path = join(sessionsDirectory(), name);
452
+ if (!DIGEST_STEM.test(stem) && safeRecordFileName(stem) === stem) {
453
+ ids.add(stem);
454
+ continue;
455
+ }
456
+ if (suffix === ".jsonl") {
457
+ const id = await chatLogId(path);
458
+ if (id !== void 0) ids.add(id);
459
+ continue;
460
+ }
461
+ const cached = fileCache.get(path);
462
+ if (cached) {
463
+ ids.add(cached.file.id);
464
+ continue;
465
+ }
466
+ try {
467
+ const parsed = JSON.parse(await readFile2(path, "utf8"));
468
+ if (typeof parsed.id === "string") ids.add(parsed.id);
469
+ } catch (error) {
470
+ swallowed("session/store/records", error);
471
+ }
472
+ }
473
+ return [...ids];
474
+ }
475
+
476
+ // src/session/store/transcripts.ts
477
+ function transcriptOf(session) {
478
+ return {
479
+ ...session.messages !== void 0 ? { messages: session.messages } : {},
480
+ ...session.pendingTurn !== void 0 ? { pendingTurn: session.pendingTurn } : {}
481
+ };
482
+ }
483
+ var ConversationLogMissingError = class extends Error {
484
+ constructor(sessionId) {
485
+ super(`The stored history of conversation ${sessionId} is missing. ClikCode will not rebuild it from an older copy. Run \`clikcode sessions audit\` to see what survives, then \`clikcode sessions repair ${sessionId}\`.`);
486
+ this.sessionId = sessionId;
487
+ this.name = "ConversationLogMissingError";
488
+ }
489
+ sessionId;
490
+ };
491
+ async function openLog(id) {
492
+ const log = await loadChatLog(id);
493
+ if (log) await markLogged(id);
494
+ return log;
495
+ }
496
+ async function refuseLostLog(id) {
497
+ if (await hadLog(id)) {
498
+ lifecycle("store.log-missing", { session: id });
499
+ throw new ConversationLogMissingError(id);
500
+ }
501
+ }
502
+ function withSessionLock(id, run) {
503
+ return withFileLock(sessionLockPath(id), run);
504
+ }
505
+ function sameMessage(left, right) {
506
+ return !!left && !!right && (left === right || left.role === right.role && left.content === right.content && sameData(left, right));
507
+ }
508
+ function commonPrefixLength(left, right) {
509
+ if (left === right) return left.length;
510
+ const limit = Math.min(left.length, right.length);
511
+ let index = 0;
512
+ while (index < limit && sameMessage(left[index], right[index])) index += 1;
513
+ return index;
514
+ }
515
+ function extendsHistory(prefix, list) {
516
+ return list.length >= prefix.length && commonPrefixLength(prefix, list) === prefix.length;
517
+ }
518
+ function mergeTranscripts(base, next, disk) {
519
+ const before = base.messages ?? [];
520
+ const mine = next.messages ?? [];
521
+ const theirs = disk.messages ?? [];
522
+ const iAppended = commonPrefixLength(before, mine) === before.length;
523
+ const theyAppended = commonPrefixLength(before, theirs) === before.length;
524
+ let messages;
525
+ if (theyAppended && theirs.length === before.length) messages = next.messages;
526
+ else if (iAppended) {
527
+ const ours = mine.slice(before.length);
528
+ const theirAppends = theyAppended ? theirs.slice(before.length) : [];
529
+ messages = [...theirs, ...ours.slice(commonPrefixLength(theirAppends, ours))];
530
+ } else if (theyAppended) messages = [...mine, ...theirs.slice(before.length)];
531
+ else messages = next.messages;
532
+ const pendingTurn = sameData(base.pendingTurn, next.pendingTurn) ? disk.pendingTurn : next.pendingTurn;
533
+ if (messages === next.messages && pendingTurn === next.pendingTurn) return next;
534
+ return {
535
+ ...messages !== void 0 ? { messages } : {},
536
+ ...pendingTurn !== void 0 ? { pendingTurn } : {}
537
+ };
538
+ }
539
+ var positions = /* @__PURE__ */ new WeakMap();
540
+ var digests = /* @__PURE__ */ new WeakMap();
541
+ function messagesDigest(messages, count = messages.length) {
542
+ const known = digests.get(messages);
543
+ if (known?.count === count) return known.digest;
544
+ const hash = createHash("sha256");
545
+ for (let index = 0; index < count; index += 1) hash.update(JSON.stringify(messages[index])).update("\n");
546
+ const digest = hash.digest("hex");
547
+ digests.set(messages, { count, digest });
548
+ return digest;
549
+ }
550
+ function pendingDigest(turn) {
551
+ return createHash("sha256").update(JSON.stringify(turn ?? null)).digest("hex");
552
+ }
553
+ var EMPTY_BASE = { count: 0, digest: messagesDigest([]), pending: pendingDigest(void 0), at: 0 };
554
+ async function readLegacySteady(id) {
555
+ const path = sessionFilePath(id);
556
+ let identity = await fileIdentity(path) ?? null;
557
+ for (let attempt = 0; ; attempt += 1) {
558
+ const legacy = identity === null ? void 0 : await readLegacyTranscript(id);
559
+ const after = await fileIdentity(path) ?? null;
560
+ if (after === identity) return { identity, legacy, steady: true };
561
+ if (attempt >= 4) return { identity: after, legacy, steady: false };
562
+ identity = after;
563
+ }
564
+ }
565
+ var intakes = /* @__PURE__ */ new WeakMap();
566
+ async function legacyIntake(id, log) {
567
+ const known = log.legacy?.file ?? null;
568
+ const now = await fileIdentity(sessionFilePath(id)) ?? null;
569
+ if (now === known) return void 0;
570
+ const memo = intakes.get(log);
571
+ if (memo && memo.identity === now) return memo.intake;
572
+ const { identity, legacy, steady } = await readLegacySteady(id);
573
+ if (identity === known) return void 0;
574
+ const base = log.legacy ?? { file: null, ...EMPTY_BASE };
575
+ const theirs = legacy?.messages ?? [];
576
+ let add = [];
577
+ if (!legacy) {
578
+ } else if (theirs.length >= base.count && messagesDigest(theirs, base.count) === base.digest) {
579
+ const gained = theirs.slice(base.count);
580
+ const since = log.messages.slice(Math.min(base.at, log.messages.length));
581
+ add = gained.slice(commonPrefixLength(since, gained));
582
+ } else {
583
+ add = theirs.slice(commonPrefixLength(log.messages, theirs));
584
+ lifecycle("store.legacy-diverged", { session: id, legacyMessages: theirs.length, logMessages: log.messages.length, takenIn: add.length });
585
+ }
586
+ const theirTurn = legacy?.pendingTurn;
587
+ const turnChanged = legacy !== void 0 && pendingDigest(theirTurn) !== base.pending;
588
+ const intake = {
589
+ add,
590
+ steady,
591
+ ...turnChanged ? { pending: { turn: theirTurn } } : {},
592
+ // A file that went away keeps what was taken in of it: should that build
593
+ // write it again (its copy, plus anything new), only the new is taken in.
594
+ base: legacy ? { file: identity, count: theirs.length, digest: messagesDigest(theirs), pending: pendingDigest(theirTurn), at: log.messages.length + add.length } : { ...base, file: identity }
595
+ };
596
+ if (identity !== null && steady) intakes.set(log, { identity, intake });
597
+ return intake;
598
+ }
599
+ var views = /* @__PURE__ */ new WeakMap();
600
+ function logView(log, intake) {
601
+ if (!intake) {
602
+ if (log.hasMessages && !positions.has(log.messages)) positions.set(log.messages, { gen: log.gen, end: log.messages.length });
603
+ return { messages: log.hasMessages ? log.messages : void 0, pending: log.pending };
604
+ }
605
+ const known = views.get(log);
606
+ if (known?.intake === intake) return known.view;
607
+ const view = {
608
+ messages: intake.add.length ? Object.freeze([...log.messages, ...intake.add]) : log.hasMessages || intake.base.count ? log.messages : void 0,
609
+ pending: intake.pending ? intake.pending.turn : log.pending
610
+ };
611
+ views.set(log, { intake, view });
612
+ return view;
613
+ }
614
+ async function streamedTurn(id, pending) {
615
+ if (!pending) return void 0;
616
+ const streamed = await loadPendingFile(id);
617
+ return streamed && continuesTurn(pending, streamed) ? streamed : pending;
618
+ }
619
+ async function readSessionTranscript(id) {
620
+ const log = await openLog(id);
621
+ if (!log) {
622
+ await refuseLostLog(id);
623
+ const legacy = await readLegacyTranscript(id);
624
+ if (!legacy) return {};
625
+ return {
626
+ ...legacy.messages !== void 0 ? { messages: legacy.messages } : {},
627
+ ...legacy.pendingTurn !== void 0 ? { pendingTurn: cloneData(legacy.pendingTurn) } : {}
628
+ };
629
+ }
630
+ const view = logView(log, await legacyIntake(id, log));
631
+ const pendingTurn = await streamedTurn(id, view.pending);
632
+ return {
633
+ ...view.messages !== void 0 ? { messages: view.messages } : {},
634
+ ...pendingTurn !== void 0 ? { pendingTurn: cloneData(pendingTurn) } : {}
635
+ };
636
+ }
637
+ function transcriptPosition(messages) {
638
+ const at = positions.get(messages);
639
+ return at && at.end === messages.length ? { ...at } : void 0;
640
+ }
641
+ async function readTranscriptAt(id, at) {
642
+ const log = await openLog(id);
643
+ if (!log || log.gen !== at.gen || log.messages.length < at.end) return void 0;
644
+ return log.messages.slice(0, at.end);
645
+ }
646
+ async function readStoredPendingTurn(id) {
647
+ const log = await openLog(id);
648
+ if (!log) {
649
+ await refuseLostLog(id);
650
+ return (await readLegacyTranscript(id))?.pendingTurn;
651
+ }
652
+ return streamedTurn(id, logView(log, await legacyIntake(id, log)).pending);
653
+ }
654
+ async function transcriptIdentity(id) {
655
+ const log = await fileIdentity(sessionLogPath(id));
656
+ const own = await fileIdentity(sessionFilePath(id));
657
+ if (log) return `log:${log}|json:${own ?? "-"}`;
658
+ if (!own) return void 0;
659
+ const parts = [`${id}:${own}`];
660
+ const seen = /* @__PURE__ */ new Set([id]);
661
+ let ref = (await loadLegacyFile(id))?.transcriptRef;
662
+ while (ref && !seen.has(ref.sessionId) && seen.size < 64) {
663
+ seen.add(ref.sessionId);
664
+ parts.push(`${ref.sessionId}:${await fileIdentity(sessionFilePath(ref.sessionId)) ?? "-"}`);
665
+ ref = (await loadLegacyFile(ref.sessionId))?.transcriptRef;
666
+ }
667
+ return parts.join("|");
668
+ }
669
+ var MIGRATION_FAULTS = {};
670
+ async function syncDirectory(directory) {
671
+ if (process.platform === "win32") return;
672
+ const handle = await open2(directory, "r").catch(quiet("session/store/transcripts"));
673
+ if (!handle) return;
674
+ try {
675
+ await handle.sync();
676
+ } catch {
677
+ } finally {
678
+ await handle.close();
679
+ }
680
+ }
681
+ async function keepLegacyCopy(id) {
682
+ const source = sessionFilePath(id);
683
+ const sourceInfo = await stat3(source);
684
+ for (let attempt = 0; attempt < 5; attempt += 1) {
685
+ const target = attempt === 0 ? sessionLegacyBackupPath(id) : `${sessionLegacyBackupPath(id)}-${Date.now()}${attempt}`;
686
+ const existing = await stat3(target).catch(quiet("session/store/transcripts"));
687
+ if (existing) {
688
+ if (existing.ino === sourceInfo.ino && existing.dev === sourceInfo.dev) return;
689
+ continue;
690
+ }
691
+ try {
692
+ await link(source, target);
693
+ return;
694
+ } catch (error) {
695
+ const code = error.code;
696
+ if (code === "EEXIST") continue;
697
+ try {
698
+ await copyFile(source, target, constants2.COPYFILE_EXCL);
699
+ return;
700
+ } catch (copyError) {
701
+ if (copyError.code === "EEXIST") continue;
702
+ throw copyError;
703
+ }
704
+ }
705
+ }
706
+ throw new Error(`could not keep a copy of ${source}`);
707
+ }
708
+ async function migrate(id) {
709
+ const fault = MIGRATION_FAULTS.at ?? (() => void 0);
710
+ fault("read");
711
+ const { identity, legacy, steady } = await readLegacySteady(id);
712
+ if (!steady) throw new Error(`${sessionFilePath(id)} kept changing while it was read; the conversation stays in it until the next write`);
713
+ if (!legacy || identity === null) return void 0;
714
+ const messages = legacy.messages;
715
+ const pending = legacy.pendingTurn;
716
+ const base = { file: identity, count: messages?.length ?? 0, digest: messagesDigest(messages ?? []), pending: pendingDigest(pending), at: messages?.length ?? 0 };
717
+ const path = sessionLogPath(id);
718
+ const temporary = `${path}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`;
719
+ const started = Date.now();
720
+ let placed = false;
721
+ try {
722
+ await ensurePrivateDirectory(dirname(path));
723
+ fault("write");
724
+ const handle = await open2(temporary, "wx", 384);
725
+ try {
726
+ await handle.writeFile(chatLogText(id, { ...messages ? { messages } : {}, ...pending ? { pending } : {}, legacy: base }));
727
+ fault("sync");
728
+ await handle.sync();
729
+ } finally {
730
+ await handle.close();
731
+ }
732
+ fault("verify");
733
+ const back = parseChatLog(await readFile3(temporary, "utf8"));
734
+ if (back.skipped || back.hasMessages !== (messages !== void 0) || !sameData(back.messages, messages ?? []) || !sameData(back.pending, pending) || !sameData(back.legacy, base)) {
735
+ throw new Error(`the history of conversation ${id} did not read back as written; it stays in ${sessionFilePath(id)}`);
736
+ }
737
+ fault("backup");
738
+ await keepLegacyCopy(id);
739
+ fault("rename");
740
+ await rename2(temporary, path);
741
+ placed = true;
742
+ } finally {
743
+ if (!placed) await unlink3(temporary).catch(quiet("session/store/transcripts"));
744
+ }
745
+ fault("placed");
746
+ await syncDirectory(dirname(path));
747
+ const log = await openLog(id);
748
+ if (!log) throw new Error(`the history of conversation ${id} vanished as it was moved`);
749
+ if (messages && log.messages.length === messages.length) positions.set(messages, { gen: log.gen, end: messages.length });
750
+ lifecycle("store.migrated", { session: id, messages: messages?.length ?? 0, bytes: log.size, ms: Date.now() - started });
751
+ return log;
752
+ }
753
+ var STUB_NOTE = "This conversation is stored in a newer format that this version of ClikCode cannot read. Update ClikCode to see it and go on with it.";
754
+ async function writeStub(id) {
755
+ const path = sessionFilePath(id);
756
+ const stub = { v: 1, id, messages: [{ role: "assistant", content: STUB_NOTE, storedInLog: true }] };
757
+ const temporary = `${path}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`;
758
+ try {
759
+ const handle = await open2(temporary, "wx", 384);
760
+ try {
761
+ await handle.writeFile(JSON.stringify(stub));
762
+ } finally {
763
+ await handle.close();
764
+ }
765
+ await link(temporary, path);
766
+ } catch (error) {
767
+ if (error.code !== "EEXIST") lifecycle("store.stub-failed", { session: id, error: error.message });
768
+ } finally {
769
+ await unlink3(temporary).catch(quiet("session/store/transcripts"));
770
+ }
771
+ return fileIdentity(path);
772
+ }
773
+ function changedTurn(before, after) {
774
+ return !sameData(before, after);
775
+ }
776
+ async function commit(id, log, record) {
777
+ if (record.add === void 0 && record.p === void 0 && record.legacy === void 0) return;
778
+ const durable = (record.add?.length ?? 0) > 0 || record.p === null || record.legacy !== void 0;
779
+ await appendChatLog(id, log, [record], { durable });
780
+ if (record.p !== void 0) await removePendingFile(id);
781
+ }
782
+ async function storeTranscript(id, next, base) {
783
+ let log = await openLog(id);
784
+ if (!log) await refuseLostLog(id);
785
+ log ??= await migrate(id);
786
+ if (!log) {
787
+ if (next.messages === void 0 && next.pendingTurn === void 0) return;
788
+ await writeChatLog(id, { ...next.messages ? { messages: next.messages } : {}, ...next.pendingTurn ? { pending: next.pendingTurn } : {} });
789
+ const born = await openLog(id);
790
+ if (born && next.messages) positions.set(next.messages, { gen: born.gen, end: next.messages.length });
791
+ const stub = await writeStub(id);
792
+ if (born && stub) await commit(id, born, { legacy: { file: stub, ...EMPTY_BASE, at: born.messages.length } });
793
+ return;
794
+ }
795
+ if (log.foreign) throw new Error(`the history of conversation ${id} was written by a newer ClikCode; this one does not change it`);
796
+ const intake = await legacyIntake(id, log);
797
+ if (intake && !intake.steady) throw new Error(`${sessionFilePath(id)} kept changing while it was read; nothing was written`);
798
+ if (intake) {
799
+ await commit(id, log, {
800
+ ...intake.add.length ? { add: intake.add } : {},
801
+ ...intake.pending ? { p: intake.pending.turn ?? null } : {},
802
+ legacy: intake.base
803
+ });
804
+ log = await loadChatLog(id);
805
+ }
806
+ const nextMessages = next.messages;
807
+ const at = base?.messages ? positions.get(base.messages) : void 0;
808
+ if (base?.messages && nextMessages && at && at.gen === log.gen && at.end <= log.messages.length && extendsHistory(base.messages, nextMessages)) {
809
+ const ours = nextMessages.slice(base.messages.length);
810
+ const add = ours.slice(commonPrefixLength(log.messages.slice(at.end), ours));
811
+ await commit(id, log, {
812
+ ...add.length ? { add } : {},
813
+ ...changedTurn(base.pendingTurn, next.pendingTurn) ? { p: next.pendingTurn ?? null } : {}
814
+ });
815
+ positions.set(nextMessages, { gen: log.gen, end: log.messages.length + add.length });
816
+ return;
817
+ }
818
+ const disk = {
819
+ ...log.hasMessages ? { messages: log.messages } : {},
820
+ ...log.pending ? { pendingTurn: log.pending } : {}
821
+ };
822
+ let merged = base ? mergeTranscripts(base, next, disk) : next;
823
+ if (merged.messages === void 0 && disk.messages !== void 0) merged = { ...merged, messages: disk.messages };
824
+ const diskMessages = log.messages;
825
+ const mergedMessages = merged.messages;
826
+ if (mergedMessages ? extendsHistory(diskMessages, mergedMessages) : !log.hasMessages) {
827
+ const add = mergedMessages ? mergedMessages.slice(diskMessages.length) : void 0;
828
+ await commit(id, log, {
829
+ ...add && (add.length || !log.hasMessages) ? { add } : {},
830
+ ...changedTurn(log.pending, merged.pendingTurn) ? { p: merged.pendingTurn ?? null } : {}
831
+ });
832
+ if (mergedMessages && mergedMessages === nextMessages) positions.set(nextMessages, { gen: log.gen, end: diskMessages.length + (add?.length ?? 0) });
833
+ return;
834
+ }
835
+ const legacy = log.legacy ? { ...log.legacy, at: Math.min(log.legacy.at, mergedMessages?.length ?? 0) } : void 0;
836
+ await writeChatLog(id, { ...mergedMessages ? { messages: mergedMessages } : {}, ...merged.pendingTurn ? { pending: merged.pendingTurn } : {}, ...legacy ? { legacy } : {} });
837
+ await removePendingFile(id);
838
+ const rewritten = await loadChatLog(id);
839
+ if (rewritten && mergedMessages && mergedMessages === nextMessages) positions.set(nextMessages, { gen: rewritten.gen, end: nextMessages.length });
840
+ }
841
+ async function writeSessionTranscript(_held, id, next, options = {}) {
842
+ await withSessionLock(id, () => storeTranscript(id, next, options.base));
843
+ }
844
+ function writeOwnTranscript(id, next, base, listed, options) {
845
+ return withSessionLock(id, async () => {
846
+ if (!await listed()) return false;
847
+ if (options.journalOnly && await storeStreamedTurn(id, next, base)) return true;
848
+ await storeTranscript(id, next, base);
849
+ return true;
850
+ });
851
+ }
852
+ async function storeStreamedTurn(id, next, base) {
853
+ const turn = next.pendingTurn;
854
+ if (!turn || next.messages !== base.messages || turn.startedAt !== base.pendingTurn?.startedAt) return false;
855
+ const log = await openLog(id);
856
+ if (!log || log.foreign || !log.pending || log.pending.startedAt !== turn.startedAt || log.pending.prompt !== turn.prompt) return false;
857
+ await storePendingFile(id, turn);
858
+ return true;
859
+ }
860
+ async function deleteSessionTranscript(_held, id) {
861
+ await giveLegacyChildrenTheirCopy(id, withSessionLock);
862
+ await withSessionLock(id, async () => {
863
+ await removeChatLog(id);
864
+ await removePendingFile(id);
865
+ await removeLegacyFiles(id);
866
+ await unmarkLogged(id);
867
+ });
868
+ }
869
+ async function replaceTranscriptFromEvidence(id, messages, backupDir) {
870
+ return withSessionLock(id, async () => {
871
+ await ensurePrivateDirectory(backupDir);
872
+ const own = safeRecordFileName(id);
873
+ const backedUp = [];
874
+ for (const name of await readdir2(sessionsDirectory())) {
875
+ if (!name.startsWith(`${own}.`) || name.endsWith(".lock") || name.endsWith(".tmp")) continue;
876
+ await copyFile(join2(sessionsDirectory(), name), join2(backupDir, name));
877
+ backedUp.push(name);
878
+ }
879
+ const log = await loadChatLog(id);
880
+ const { identity, legacy, steady } = await readLegacySteady(id);
881
+ let taken;
882
+ if (legacy && steady && identity !== null) {
883
+ const old = legacy.messages ?? [];
884
+ taken = { file: identity, count: old.length, digest: messagesDigest(old), pending: pendingDigest(legacy.pendingTurn), at: messages.length };
885
+ } else if (log?.legacy) taken = { ...log.legacy, at: Math.min(log.legacy.at, messages.length) };
886
+ await writeChatLog(id, {
887
+ messages: [...messages],
888
+ ...log?.pending ? { pending: log.pending } : {},
889
+ ...taken ? { legacy: taken } : {}
890
+ });
891
+ await markLogged(id);
892
+ return { backedUp };
893
+ });
894
+ }
895
+
896
+ export {
897
+ loadChatLog,
898
+ transcriptOf,
899
+ ConversationLogMissingError,
900
+ readSessionTranscript,
901
+ transcriptPosition,
902
+ readTranscriptAt,
903
+ readStoredPendingTurn,
904
+ transcriptIdentity,
905
+ writeSessionTranscript,
906
+ writeOwnTranscript,
907
+ deleteSessionTranscript,
908
+ replaceTranscriptFromEvidence
909
+ };