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,4578 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ runSharedComputerTool
5
+ } from "./chunk-5IKLK33T.js";
6
+ import {
7
+ BUILD_WATCH_MS,
8
+ RETIRE_QUIET_MS
9
+ } from "./chunk-RW7F4JRP.js";
10
+ import {
11
+ turnNeedsWindow
12
+ } from "./chunk-PAL2ENB6.js";
13
+ import {
14
+ createAgentsCommand,
15
+ readConversationSubagent
16
+ } from "./chunk-5642PBF7.js";
17
+ import {
18
+ LiveSettings,
19
+ SignInEnded,
20
+ TurnRecorder,
21
+ discardInterruptedTurn,
22
+ disposeSessionState,
23
+ existingSessionAgents,
24
+ formatShellNotifications,
25
+ hasThreadToCompact,
26
+ holdResourceNote,
27
+ markFailedTurn,
28
+ preserveInterruptedTurn,
29
+ reconcileAgents,
30
+ runSessionTurn,
31
+ runningShellCount,
32
+ sessionCompactionMechanism,
33
+ sessionState,
34
+ shutdownLanguageServers,
35
+ stopBackgroundShell,
36
+ takeShellNotifications
37
+ } from "./chunk-32IKAIZC.js";
38
+ import "./chunk-Y3R7JMXB.js";
39
+ import {
40
+ askPrivateChoice,
41
+ askPrivateLogin
42
+ } from "./chunk-E4F4OUAC.js";
43
+ import "./chunk-OHKZUEJW.js";
44
+ import {
45
+ pingPromptCache,
46
+ recordInvocation,
47
+ sessionTurnTransport,
48
+ turnEnvironment
49
+ } from "./chunk-M6ND6KBE.js";
50
+ import "./chunk-LM6EIA4B.js";
51
+ import {
52
+ routeMcpServers
53
+ } from "./chunk-WZMLH3XP.js";
54
+ import {
55
+ prepareMcp,
56
+ releaseMcp
57
+ } from "./chunk-UVXNIUTN.js";
58
+ import "./chunk-RDLLDYFO.js";
59
+ import "./chunk-74WNMLMS.js";
60
+ import "./chunk-GLY7RM3C.js";
61
+ import "./chunk-X2OCPVU5.js";
62
+ import "./chunk-T5VCXA3J.js";
63
+ import "./chunk-BTJDSTQP.js";
64
+ import {
65
+ loginComputerPage,
66
+ loginOutcomeMessage
67
+ } from "./chunk-W2NVSDO5.js";
68
+ import "./chunk-EXN4KHLB.js";
69
+ import {
70
+ LoginError,
71
+ uniqueLabels
72
+ } from "./chunk-BNTXAZXW.js";
73
+ import "./chunk-LAVFOA3S.js";
74
+ import "./chunk-2GAB36IE.js";
75
+ import "./chunk-WOVTYST3.js";
76
+ import "./chunk-3RXBMYKZ.js";
77
+ import "./chunk-34JQYQCA.js";
78
+ import "./chunk-JYBONKD4.js";
79
+ import "./chunk-MCSDWZET.js";
80
+ import "./chunk-BOQBXGSN.js";
81
+ import "./chunk-DAJ76TOC.js";
82
+ import "./chunk-KCQ4TBLS.js";
83
+ import "./chunk-FBKXE4EJ.js";
84
+ import "./chunk-DW2BMUKY.js";
85
+ import "./chunk-B4HNJRAH.js";
86
+ import "./chunk-OQ245JLA.js";
87
+ import "./chunk-25T3GVS7.js";
88
+ import "./chunk-4GXAO3UY.js";
89
+ import "./chunk-SNU37TQI.js";
90
+ import "./chunk-XAHGBPWT.js";
91
+ import "./chunk-FT5TX7OX.js";
92
+ import "./chunk-7NMUTGOW.js";
93
+ import "./chunk-FFGU4GCC.js";
94
+ import "./chunk-DXKNDNFC.js";
95
+ import {
96
+ sessionHarness
97
+ } from "./chunk-2EOL5PZL.js";
98
+ import "./chunk-UYEEMIWR.js";
99
+ import {
100
+ ABANDONED_WORK_MS,
101
+ closePersistentTransport,
102
+ hasHeldVendorProcess,
103
+ hasPersistentTransport,
104
+ isVendorRefusalSaid,
105
+ observeSessionAccount,
106
+ outOfTurnRecorder,
107
+ persistentWorkRunning,
108
+ reapPersistentCommands,
109
+ refusalEndingReply,
110
+ runningVendorAgents,
111
+ setOutOfTurnHandler,
112
+ setRetiredWorkListener,
113
+ setVendorBackgroundTurnHandler,
114
+ setWorkEndedHandler,
115
+ stopHeldVendorProcess,
116
+ whenHeldVendorGone
117
+ } from "./chunk-TVT45XNH.js";
118
+ import "./chunk-K2NLG2HK.js";
119
+ import "./chunk-EOBTJV32.js";
120
+ import "./chunk-7AULZ7OD.js";
121
+ import "./chunk-UA5K2BTI.js";
122
+ import {
123
+ isUsageExhaustedMessage,
124
+ matchesVendorTurn,
125
+ resumeStep
126
+ } from "./chunk-IF43HIGV.js";
127
+ import "./chunk-7TSQLONI.js";
128
+ import {
129
+ quotaRetryHint
130
+ } from "./chunk-2YPAPAR3.js";
131
+ import "./chunk-WNX5VD7S.js";
132
+ import "./chunk-UTSB4LOW.js";
133
+ import "./chunk-WM3Z6QKQ.js";
134
+ import "./chunk-LA6MG4ET.js";
135
+ import "./chunk-N3SFDYM7.js";
136
+ import "./chunk-4RHXTL3W.js";
137
+ import {
138
+ gatewayModels
139
+ } from "./chunk-W5AYOICN.js";
140
+ import "./chunk-2OLS7V66.js";
141
+ import "./chunk-2QWPQRSU.js";
142
+ import "./chunk-IS4USJPY.js";
143
+ import "./chunk-2BBELGHY.js";
144
+ import "./chunk-QYHI3YET.js";
145
+ import {
146
+ isTurnCancelled,
147
+ turnCancelledError
148
+ } from "./chunk-4LPDG57B.js";
149
+ import "./chunk-TQDM7S5N.js";
150
+ import "./chunk-TQDKJHWX.js";
151
+ import "./chunk-GQBZU6EO.js";
152
+ import "./chunk-RE4TGORR.js";
153
+ import "./chunk-DCZ6CIUM.js";
154
+ import {
155
+ claudeSessionStore,
156
+ locateNativeSessionFile,
157
+ placeArtifact
158
+ } from "./chunk-M3FO5UMK.js";
159
+ import "./chunk-CERF3RIB.js";
160
+ import "./chunk-QQRLPY25.js";
161
+ import "./chunk-DA44ZENT.js";
162
+ import "./chunk-F252T6Y3.js";
163
+ import "./chunk-XWAC3MKW.js";
164
+ import "./chunk-CVFVFRGN.js";
165
+ import "./chunk-QJP7EYGL.js";
166
+ import "./chunk-ESF3DIZY.js";
167
+ import {
168
+ stripJsonc,
169
+ vendorConfigFiles,
170
+ vendorSources
171
+ } from "./chunk-R7QN6ONS.js";
172
+ import "./chunk-ZN7G6JLS.js";
173
+ import {
174
+ nativeProfileEnvironment
175
+ } from "./chunk-ZGX3ERAT.js";
176
+ import "./chunk-PEWCDI2C.js";
177
+ import "./chunk-TULAXS77.js";
178
+ import {
179
+ FrameDecoder,
180
+ MOVED_REASON,
181
+ cancelOriginFields,
182
+ encodeFrame,
183
+ isTranscriptActivity
184
+ } from "./chunk-UBMVADBF.js";
185
+ import {
186
+ COMPACTING,
187
+ COMPACT_REQUEST,
188
+ NOTHING_TO_COMPACT,
189
+ compactAt,
190
+ compactFailedLine,
191
+ isCompactRequest,
192
+ noteContextAfterCompaction,
193
+ readState,
194
+ shouldCompact
195
+ } from "./chunk-MXS6S2PY.js";
196
+ import "./chunk-BISGNHKD.js";
197
+ import {
198
+ writeState
199
+ } from "./chunk-RKUVLRZI.js";
200
+ import "./chunk-BGEMY2JJ.js";
201
+ import "./chunk-XCKQ5BM2.js";
202
+ import "./chunk-NWEYRBWK.js";
203
+ import {
204
+ deliverTyped,
205
+ typedSettings
206
+ } from "./chunk-TWCVV2JO.js";
207
+ import "./chunk-PDPEM5VW.js";
208
+ import "./chunk-WWLJMP6D.js";
209
+ import {
210
+ isClikCodeAgent,
211
+ isGatewayService
212
+ } from "./chunk-CRUVYGO2.js";
213
+ import {
214
+ LEGACY_INTERRUPTED_TURN_REQUEST,
215
+ MarkSequencer,
216
+ consumeSessionTurn,
217
+ enqueueSessionTurn,
218
+ remapOffset,
219
+ setUserWaiting,
220
+ settledThought,
221
+ stepThought,
222
+ upsertMark,
223
+ wrapResourceNote
224
+ } from "./chunk-FF7ZVYJF.js";
225
+ import "./chunk-IMLTL2MY.js";
226
+ import {
227
+ mergeBackgroundWork
228
+ } from "./chunk-BUOPJQP5.js";
229
+ import {
230
+ normalizeActivityEvent,
231
+ subAgentSteerPlan,
232
+ thoughtLabel
233
+ } from "./chunk-3B2CHX7M.js";
234
+ import {
235
+ transcriptPosition
236
+ } from "./chunk-RVUOIJXN.js";
237
+ import {
238
+ CONVERSATION_HANDOFF_REASON,
239
+ announceWorkerReady,
240
+ conversationHandoffRequested,
241
+ currentWorkerBuild,
242
+ generateWorkerToken,
243
+ liveWorkerRecords,
244
+ removeWorkerRecord,
245
+ socketPathFor,
246
+ sweepWorkersDirectory,
247
+ takeConversation,
248
+ takeWorkerReadyFd,
249
+ watchHandoffRequest,
250
+ workerIsReachable,
251
+ workerRecordCount,
252
+ workerRecordWrittenAt,
253
+ workersDirectory,
254
+ writeWorkerRecord
255
+ } from "./chunk-QUS4ER2W.js";
256
+ import "./chunk-DQYVQ2N7.js";
257
+ import {
258
+ localHarnessForCommand
259
+ } from "./chunk-KYUHIFP3.js";
260
+ import "./chunk-RSZGEL5U.js";
261
+ import "./chunk-NKDATMEM.js";
262
+ import "./chunk-DF35KMXM.js";
263
+ import "./chunk-ZT7B4H2V.js";
264
+ import "./chunk-OL4JBD3J.js";
265
+ import "./chunk-IGZ6C2MC.js";
266
+ import {
267
+ beginTurnClock,
268
+ endTurnClock,
269
+ markTurn
270
+ } from "./chunk-4NN3XQQT.js";
271
+ import "./chunk-4AQ5NINV.js";
272
+ import "./chunk-WPB5WEZJ.js";
273
+ import "./chunk-GYMAI5NY.js";
274
+ import {
275
+ failureText
276
+ } from "./chunk-CQ7J6UQ7.js";
277
+ import "./chunk-XKW5NDMR.js";
278
+ import "./chunk-W3YYPBEA.js";
279
+ import "./chunk-XIBYREEY.js";
280
+ import "./chunk-EE4B6A7W.js";
281
+ import "./chunk-WZYVLUVQ.js";
282
+ import "./chunk-O3EW7LAY.js";
283
+ import "./chunk-KHW6TX6I.js";
284
+ import {
285
+ closeAllOwnedPages,
286
+ computerPage,
287
+ openComputerPage
288
+ } from "./chunk-MP4KZOQC.js";
289
+ import "./chunk-PWBF2X3V.js";
290
+ import {
291
+ AGENT_GROUP,
292
+ COMMAND_GROUP,
293
+ WORKER_PID_ENV,
294
+ bestLabel,
295
+ commandLabel,
296
+ createCommandSweep,
297
+ findCommands,
298
+ groupPids,
299
+ installSystemdRunShim,
300
+ readProc,
301
+ separateFromForeground
302
+ } from "./chunk-HU5SSUFX.js";
303
+ import "./chunk-AKRYTS2D.js";
304
+ import "./chunk-4GVEJ5FK.js";
305
+ import "./chunk-O7BNJIXU.js";
306
+ import "./chunk-MCBRVPA7.js";
307
+ import "./chunk-RJLHVYQY.js";
308
+ import {
309
+ sleep
310
+ } from "./chunk-YMCH3L2S.js";
311
+ import {
312
+ allSavedLogins,
313
+ removeSavedLogin
314
+ } from "./chunk-I75EDU75.js";
315
+ import "./chunk-JGIWATSG.js";
316
+ import "./chunk-5B6TVO4A.js";
317
+ import "./chunk-NAOX3JUB.js";
318
+ import "./chunk-4QZEZME7.js";
319
+ import {
320
+ source_default
321
+ } from "./chunk-LVRRWP4W.js";
322
+ import {
323
+ Conf
324
+ } from "./chunk-GGYKY4GF.js";
325
+ import {
326
+ computerEnabled
327
+ } from "./chunk-5SM5UAWN.js";
328
+ import "./chunk-PAXYQZH7.js";
329
+ import "./chunk-CAADDF6M.js";
330
+ import "./chunk-G3QP67Z7.js";
331
+ import {
332
+ tryLease
333
+ } from "./chunk-4L2ZZM4Q.js";
334
+ import {
335
+ atomicWriteFile
336
+ } from "./chunk-F6F47QAY.js";
337
+ import {
338
+ diagnostic,
339
+ lifecycle,
340
+ lifecycleLogPath,
341
+ quiet,
342
+ swallowed
343
+ } from "./chunk-RDDWQBEM.js";
344
+ import {
345
+ safeRecordFileName,
346
+ stateDirectory
347
+ } from "./chunk-MPAJ446F.js";
348
+ import "./chunk-CBANJFBO.js";
349
+ import "./chunk-PWXII6HF.js";
350
+
351
+ // src/worker/cache-keepwarm.ts
352
+ import { randomUUID } from "node:crypto";
353
+ import { readdir, readFile, rm, writeFile } from "node:fs/promises";
354
+ import { basename, join } from "node:path";
355
+ var KEEP_WARM_FOR_MS = 4 * 60 * 60 * 1e3;
356
+ var PING_EVERY_MS = 55 * 60 * 1e3;
357
+ var KEEP_WARM_ABOVE_TOKENS = 1e5;
358
+ var MAX_KEEP_WARM_PINGS = 4;
359
+ var PING_TIMEOUT_MS = 2 * 60 * 1e3;
360
+ function cachePingEffective(usage, contextUsed) {
361
+ const read = usage.cacheRead ?? 0;
362
+ return read >= Math.floor(contextUsed / 2) && read > (usage.cacheWrite ?? 0);
363
+ }
364
+ function keepsWarm(session) {
365
+ if (!session?.nativeSessionId || !session.workspace || !session.accountId) return false;
366
+ const harness = sessionHarness(session);
367
+ if (harness?.command !== "claude" || sessionTurnTransport(harness, session) !== "acp") return false;
368
+ return (session.lastUsage?.contextUsed ?? 0) >= KEEP_WARM_ABOVE_TOKENS;
369
+ }
370
+ function createKeepWarm(deps) {
371
+ let lastTurnAt;
372
+ let timer;
373
+ let pingController;
374
+ let nextPing = 0;
375
+ let revision = 0;
376
+ const active = () => lastTurnAt !== void 0 && Date.now() - lastTurnAt < KEEP_WARM_FOR_MS;
377
+ const stop = () => {
378
+ revision += 1;
379
+ if (timer) clearTimeout(timer);
380
+ timer = void 0;
381
+ pingController?.abort();
382
+ pingController = void 0;
383
+ const was = lastTurnAt !== void 0;
384
+ lastTurnAt = void 0;
385
+ if (was) deps.changed();
386
+ };
387
+ const arm = () => {
388
+ if (timer) clearTimeout(timer);
389
+ if (!active()) {
390
+ stop();
391
+ return;
392
+ }
393
+ while (nextPing < MAX_KEEP_WARM_PINGS && lastTurnAt + (nextPing + 1) * PING_EVERY_MS <= Date.now()) nextPing += 1;
394
+ const due = nextPing < MAX_KEEP_WARM_PINGS ? lastTurnAt + (nextPing + 1) * PING_EVERY_MS : lastTurnAt + KEEP_WARM_FOR_MS;
395
+ timer = setTimeout(() => {
396
+ void fire();
397
+ }, Math.max(0, due - Date.now()));
398
+ timer.unref?.();
399
+ };
400
+ const fire = async () => {
401
+ timer = void 0;
402
+ if (!active()) {
403
+ stop();
404
+ return;
405
+ }
406
+ if (nextPing >= MAX_KEEP_WARM_PINGS) {
407
+ stop();
408
+ return;
409
+ }
410
+ const current = revision;
411
+ nextPing += 1;
412
+ if (!deps.busy()) {
413
+ const controller = new AbortController();
414
+ pingController = controller;
415
+ const timeout = setTimeout(() => controller.abort(), PING_TIMEOUT_MS);
416
+ timeout.unref?.();
417
+ try {
418
+ const eligible = await (deps.ping ?? ping)(deps.sessionId, controller.signal);
419
+ if (!eligible && current === revision) {
420
+ stop();
421
+ return;
422
+ }
423
+ } catch (error) {
424
+ if (current === revision) diagnostic("worker.cache-ping", error instanceof Error ? error.message : String(error));
425
+ } finally {
426
+ clearTimeout(timeout);
427
+ if (pingController === controller) pingController = void 0;
428
+ }
429
+ }
430
+ if (current !== revision) return;
431
+ arm();
432
+ };
433
+ return {
434
+ async turnEnded(lastHarness) {
435
+ if (lastHarness !== "claude") {
436
+ stop();
437
+ return;
438
+ }
439
+ const current = ++revision;
440
+ const session = await (deps.readSession?.() ?? readState({ transcripts: [] }).then((state) => state.sessions.find((item) => item.id === deps.sessionId))).catch(quiet("worker/cache-keepwarm"));
441
+ if (current !== revision) return;
442
+ if (!keepsWarm(session)) {
443
+ stop();
444
+ return;
445
+ }
446
+ const starting = lastTurnAt === void 0;
447
+ lastTurnAt = Date.now();
448
+ nextPing = 0;
449
+ arm();
450
+ if (starting) deps.changed();
451
+ },
452
+ active,
453
+ stop
454
+ };
455
+ }
456
+ async function ping(sessionId, signal) {
457
+ if (signal.aborted) return false;
458
+ const state = await readState({ transcripts: [] });
459
+ const session = state.sessions.find((item) => item.id === sessionId);
460
+ const account = session?.accountId ? state.accounts.find((item) => item.id === session.accountId) : void 0;
461
+ const harness = sessionHarness(session);
462
+ if (!session || !account || !harness || !keepsWarm(session)) return false;
463
+ const nativeId = session.nativeSessionId;
464
+ const environment = turnEnvironment(harness, account, "ask");
465
+ const source = await locateNativeSessionFile(harness, nativeId, session.workspace, environment);
466
+ if (!source || !basename(source.path).includes(nativeId) || signal.aborted) return false;
467
+ const copyId = randomUUID();
468
+ const copy = join(source.path, "..", basename(source.path).replace(nativeId, copyId));
469
+ const started = Date.now();
470
+ let usage = {};
471
+ try {
472
+ await writeFile(copy, (await readFile(source.path, "utf8")).replaceAll(nativeId, copyId), { mode: 384 });
473
+ if (signal.aborted) return false;
474
+ usage = await pingPromptCache({ harness, account, session, copyId, model: session.model ?? null, effort: session.effort, environment, signal, onUsage: (reported) => {
475
+ usage = reported;
476
+ } });
477
+ const effective = cachePingEffective(usage, session.lastUsage?.contextUsed ?? KEEP_WARM_ABOVE_TOKENS);
478
+ lifecycle("worker.cache-ping", { ms: Date.now() - started, effective, ...usage });
479
+ return effective;
480
+ } finally {
481
+ try {
482
+ if ([usage.input, usage.output, usage.cacheRead, usage.cacheWrite, usage.totalTokens, usage.costUsd].some((value) => (value ?? 0) > 0)) {
483
+ recordInvocation(state, {
484
+ kind: "maintenance",
485
+ sessionId,
486
+ accountId: account.id,
487
+ provider: harness.provider,
488
+ model: session.model,
489
+ startedAt: started,
490
+ usage: { ...usage, totalTokens: usage.totalTokens ?? (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0) }
491
+ });
492
+ await writeState(state);
493
+ }
494
+ } finally {
495
+ await rm(copy, { force: true });
496
+ if (account.nativeProfile?.path) await removeNamed(account.nativeProfile.path, copyId, 3);
497
+ }
498
+ }
499
+ }
500
+ async function removeNamed(root, id, depth) {
501
+ for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
502
+ const path = join(root, entry.name);
503
+ if (entry.name.includes(id)) await rm(path, { recursive: true, force: true });
504
+ else if (entry.isDirectory() && depth > 1) await removeNamed(path, id, depth - 1);
505
+ }
506
+ }
507
+
508
+ // src/harness/retired-mcp.ts
509
+ import { copyFile, readdir as readdir2, readFile as readFile2, stat, writeFile as writeFile2 } from "node:fs/promises";
510
+ import { existsSync } from "node:fs";
511
+ import { homedir } from "node:os";
512
+ import { join as join2 } from "node:path";
513
+ var RETIRED = /* @__PURE__ */ new Set(["conversations-mcp", "npx-mcp", "swarm-mcp"]);
514
+ var PASS = "v2";
515
+ var STAMP = `${[...RETIRED].sort().join(" ")} ${PASS}`;
516
+ var CLIKCODE_LAUNCHER = /(?:^|[\\/])clikcode(?:\.cmd|\.exe)?$|[\\/]clikcode[^\\/]*[\\/](?:dist[\\/])?index\.js$|[\\/]release[\\/]dist[\\/]index\.js$/;
517
+ function isRecord(value) {
518
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
519
+ }
520
+ function stringsOf(value, depth = 0) {
521
+ if (typeof value === "string") return [value];
522
+ if (depth > 3) return [];
523
+ if (Array.isArray(value)) return value.flatMap((item) => stringsOf(item, depth + 1));
524
+ if (isRecord(value)) return Object.values(value).flatMap((item) => stringsOf(item, depth + 1));
525
+ return [];
526
+ }
527
+ function launchesRetired(spec) {
528
+ const all = stringsOf(spec);
529
+ return all.some((text) => RETIRED.has(text)) && all.some((text) => CLIKCODE_LAUNCHER.test(text));
530
+ }
531
+ function readJson(text) {
532
+ try {
533
+ return JSON.parse(text);
534
+ } catch {
535
+ }
536
+ try {
537
+ return JSON.parse(stripJsonc(text));
538
+ } catch {
539
+ return void 0;
540
+ }
541
+ }
542
+ function stripRetiredJson(text, key) {
543
+ const root = readJson(text);
544
+ if (!isRecord(root)) return void 0;
545
+ const tables = [];
546
+ if (key?.length) {
547
+ let table = root;
548
+ for (const part of key) table = isRecord(table) ? table[part] : void 0;
549
+ if (isRecord(table)) tables.push(table);
550
+ } else {
551
+ for (const name of ["mcpServers", "servers", "mcp"]) if (isRecord(root[name])) tables.push(root[name]);
552
+ }
553
+ const removed = [];
554
+ for (const table of tables) {
555
+ for (const [name, spec] of Object.entries(table)) {
556
+ if (!launchesRetired(spec)) continue;
557
+ removed.push(name);
558
+ delete table[name];
559
+ }
560
+ }
561
+ return removed.length ? { text: `${JSON.stringify(root, null, 2)}
562
+ `, removed } : void 0;
563
+ }
564
+ function serverRoot(header) {
565
+ const match = /^\[mcp_servers\.(.+)]$/.exec(header.trim());
566
+ if (!match) return void 0;
567
+ const rest = match[1];
568
+ if (rest.startsWith('"') || rest.startsWith("'")) {
569
+ const end = rest.indexOf(rest[0], 1);
570
+ return end > 1 ? rest.slice(1, end) : void 0;
571
+ }
572
+ return rest.split(".")[0];
573
+ }
574
+ function stripRetiredToml(text) {
575
+ const lines = text.split("\n");
576
+ const starts = [];
577
+ for (let index = 0; index < lines.length; index += 1) if (/^\s*\[/.test(lines[index])) starts.push(index);
578
+ if (!starts.length) return void 0;
579
+ starts.push(lines.length);
580
+ const retiredRoots = /* @__PURE__ */ new Set();
581
+ for (let section = 0; section < starts.length - 1; section += 1) {
582
+ const root = serverRoot(lines[starts[section]]);
583
+ if (!root || root.includes(".")) continue;
584
+ const body = lines.slice(starts[section], starts[section + 1]).join("\n");
585
+ const quoted = [...body.matchAll(/["']([^"'\n]+)["']/g)].map((match) => match[1]);
586
+ if (quoted.some((text2) => RETIRED.has(text2)) && quoted.some((text2) => CLIKCODE_LAUNCHER.test(text2))) retiredRoots.add(root);
587
+ }
588
+ if (!retiredRoots.size) return void 0;
589
+ const drop = /* @__PURE__ */ new Set();
590
+ for (let section = 0; section < starts.length - 1; section += 1) {
591
+ const root = serverRoot(lines[starts[section]]);
592
+ if (!root || !retiredRoots.has(root)) continue;
593
+ for (let line = starts[section]; line < starts[section + 1]; line += 1) drop.add(line);
594
+ }
595
+ const kept = lines.filter((_, index) => !drop.has(index));
596
+ while (kept.length && kept[kept.length - 1] === "" && kept[kept.length - 2] === "") kept.pop();
597
+ const next = kept.join("\n");
598
+ return { text: text.endsWith("\n") ? next.endsWith("\n") ? next : `${next}
599
+ ` : next.replace(/\n$/, ""), removed: [...retiredRoots] };
600
+ }
601
+ var CONFIGS = /* @__PURE__ */ new Set(["mcp.json", ".claude.json", "claude.json", "config.toml", "mcp_config.json", "cline_mcp_settings.json"]);
602
+ async function walkConfigs(directory, depth = 0) {
603
+ if (depth > 4) return [];
604
+ const names = await readdir2(directory, { withFileTypes: true }).catch(() => []);
605
+ const found = [];
606
+ for (const entry of names) {
607
+ if (entry.name === "node_modules" || entry.name === "plugins" || entry.name === "updates") continue;
608
+ const path = join2(directory, entry.name);
609
+ if (entry.isDirectory()) found.push(...await walkConfigs(path, depth + 1));
610
+ else if (CONFIGS.has(entry.name)) found.push(path);
611
+ }
612
+ return found;
613
+ }
614
+ async function rewrite(path, text) {
615
+ await atomicWriteFile(path, text, { directory: "vendor", mode: (await stat(path)).mode & 511 });
616
+ }
617
+ async function targets(stateDir, home) {
618
+ const found = /* @__PURE__ */ new Map();
619
+ try {
620
+ for (const source of vendorSources()) {
621
+ if (source.format === "yaml") continue;
622
+ for (const path of await vendorConfigFiles(source, home ?? join2(stateDir, ".no-home"), stateDir)) {
623
+ if (!found.has(path)) found.set(path, { path, format: source.format, key: source.key });
624
+ }
625
+ }
626
+ } catch (error) {
627
+ lifecycle("mcp.retired", { error: `catalog unavailable: ${error instanceof Error ? error.message.slice(0, 160) : String(error)}` });
628
+ }
629
+ const profiles = join2(stateDir, "profiles");
630
+ for (const command of await readdir2(profiles).catch(() => [])) {
631
+ for (const account of await readdir2(join2(profiles, command)).catch(() => [])) {
632
+ for (const path of await walkConfigs(join2(profiles, command, account))) {
633
+ if (!found.has(path)) found.set(path, { path, format: path.endsWith(".toml") ? "toml" : "json" });
634
+ }
635
+ }
636
+ }
637
+ return [...found.values()];
638
+ }
639
+ async function dropRetiredVendorMcp(stateDir, home) {
640
+ const stampPath = join2(stateDir, "retired-mcp.txt");
641
+ if (await readFile2(stampPath, "utf8").then((text) => text.trim() === STAMP, () => false)) return 0;
642
+ const profiles = join2(stateDir, "profiles");
643
+ const removed = [];
644
+ let changed = 0;
645
+ for (const target of await targets(stateDir, home)) {
646
+ try {
647
+ const text = await readFile2(target.path, "utf8").catch(quiet("harness/retired-mcp"));
648
+ if (!text || ![...RETIRED].some((name) => text.includes(name))) continue;
649
+ const stripped = target.format === "toml" ? stripRetiredToml(text) : stripRetiredJson(text, target.key);
650
+ if (!stripped) continue;
651
+ if (!target.path.startsWith(profiles) && !existsSync(`${target.path}.pre-retired-mcp`)) await copyFile(target.path, `${target.path}.pre-retired-mcp`);
652
+ await rewrite(target.path, stripped.text);
653
+ removed.push(...stripped.removed);
654
+ changed += 1;
655
+ } catch (error) {
656
+ lifecycle("mcp.retired", { error: error instanceof Error ? error.message.slice(0, 160) : String(error), file: target.path.split(/[\\/]/).slice(-2).join("/") });
657
+ }
658
+ }
659
+ await writeFile2(stampPath, `${STAMP}
660
+ `, "utf8").catch(quiet("harness/retired-mcp"));
661
+ if (removed.length) lifecycle("mcp.retired", { removed: removed.length, files: changed, names: [...new Set(removed)].join(",").slice(0, 200) });
662
+ return removed.length;
663
+ }
664
+ function homeForOwnState(stateDir) {
665
+ return stateDir === join2(homedir(), ".clikcode") ? homedir() : void 0;
666
+ }
667
+
668
+ // src/worker/session-worker.ts
669
+ import { statSync as statSync4 } from "node:fs";
670
+ import { unlink as unlink2 } from "node:fs/promises";
671
+ import { hostname } from "node:os";
672
+ import { randomUUID as randomUUID8 } from "node:crypto";
673
+
674
+ // src/worker/subagent-recovery.ts
675
+ import { dirname, join as join3, relative } from "node:path";
676
+ import { stat as stat2 } from "node:fs/promises";
677
+ async function locateAgentTranscript(work, session, account) {
678
+ if (session.nativeHarness !== "claude" || !account || !session.nativeSessionId || !session.workspace || !/^[\w-]+$/.test(work.id)) return void 0;
679
+ const environment = nativeProfileEnvironment(account.nativeProfile);
680
+ const root = claudeSessionStore.root(environment);
681
+ if (!root) return void 0;
682
+ const parent = await claudeSessionStore.locate(root, work.nativeSessionId ?? session.nativeSessionId, session.workspace, environment);
683
+ if (!parent) return void 0;
684
+ const file = join3(parent.path.slice(0, -".jsonl".length), "subagents", `agent-${work.id}.jsonl`);
685
+ return await stat2(file).then((entry) => entry.isFile(), () => false) ? file : void 0;
686
+ }
687
+ async function carryBlockedSubagent(work, session, source, target) {
688
+ if (source && target && source.id === target.id) return await locateAgentTranscript(work, session, source) !== void 0;
689
+ if (session.nativeHarness !== "claude" || !source || !target || source.id === target.id || !session.nativeSessionId || !session.workspace || !/^[\w-]+$/.test(work.id)) return false;
690
+ const from = nativeProfileEnvironment(source.nativeProfile);
691
+ const to = nativeProfileEnvironment(target.nativeProfile);
692
+ const sourceRoot = claudeSessionStore.root(from);
693
+ const targetRoot = claudeSessionStore.root(to);
694
+ if (!sourceRoot || !targetRoot) return false;
695
+ if (sourceRoot === targetRoot) return true;
696
+ const parent = await claudeSessionStore.locate(sourceRoot, work.nativeSessionId ?? session.nativeSessionId, session.workspace, from);
697
+ if (!parent) return false;
698
+ const sourceDir = join3(parent.path.slice(0, -".jsonl".length), "subagents");
699
+ const targetDir = join3(targetRoot, relative(sourceRoot, dirname(parent.path)), session.nativeSessionId, "subagents");
700
+ const transcript = `agent-${work.id}.jsonl`;
701
+ if (!await stat2(join3(sourceDir, transcript)).then((entry) => entry.isFile(), () => false)) return false;
702
+ const metadata = `agent-${work.id}.meta.json`;
703
+ if (await stat2(join3(sourceDir, metadata)).then((entry) => entry.isFile(), () => false)) {
704
+ await placeArtifact(join3(sourceDir, metadata), join3(targetDir, metadata));
705
+ }
706
+ return placeArtifact(join3(sourceDir, transcript), join3(targetDir, transcript));
707
+ }
708
+
709
+ // src/worker/handed-off-work.ts
710
+ function formatEndedWork(ended, native = /* @__PURE__ */ new Set()) {
711
+ return ended.map((work) => {
712
+ const tail = work.tail.replace(/\s+$/, "");
713
+ if (work.kind === "command") return `[background command ${work.id} finished] ${work.label}
714
+ ${tail || "(no output)"}`;
715
+ if (work.outcome === "finished") return `[background agent ${work.id} finished] ${work.label}
716
+ ${tail || "(it gave no result)"}`;
717
+ const why = work.failure?.text ?? (tail || "it stopped before it finished");
718
+ const resume = native.has(work.id) ? `Resume the existing native agent ${JSON.stringify(work.id)} on this account using SendMessage (to that agent ID) or the agent tool's resume control. Its prior history must be preserved; do not launch a duplicate from scratch.` : "Start a replacement agent on the current account to carry this unfinished work on.";
719
+ const context = work.outputFile ? `Its saved transcript is ${JSON.stringify(work.outputFile)}. Read it in bounded sections and give the replacement its prior context and progress. Continue from the last unfinished step; do not repeat completed actions.` : "Preserve its recorded progress and completed actions when continuing; do not repeat completed work.";
720
+ const task = `${resume}
721
+ ${context}${tail ? `
722
+ Progress before interruption:
723
+ ${tail}` : ""}` + (work.prompt ? `
724
+ Original task:
725
+ ${work.prompt}` : `
726
+ Use the recorded task description: ${work.label}`);
727
+ return `[background agent ${work.id} was cut off: ${why}] ${work.label}
728
+ ${task}`;
729
+ }).join("\n\n");
730
+ }
731
+ function createWorkEndedHandler(ctx) {
732
+ return (ended, from) => {
733
+ if (!ended.length) return;
734
+ lifecycle("worker.work-ended", { count: ended.length, cut: ended.filter((work) => work.outcome === "cut-off").length, account: from.accountId?.slice(0, 8) });
735
+ void (async () => {
736
+ const native = /* @__PURE__ */ new Set();
737
+ const cut = ended.filter((work) => work.kind === "agent" && work.outcome === "cut-off");
738
+ if (cut.length) {
739
+ const state = await readState({ transcripts: [] });
740
+ const session = state.sessions.find((entry) => entry.id === ctx.sessionId);
741
+ if (session) {
742
+ const source = state.accounts.find((entry) => entry.id === from.accountId);
743
+ const target = state.accounts.find((entry) => entry.id === session.accountId);
744
+ for (const work of cut) {
745
+ const carried = await carryBlockedSubagent(work, session, source, target).catch((error) => {
746
+ diagnostic("worker.subagent-carry-failed", error instanceof Error ? error.message : String(error));
747
+ return false;
748
+ });
749
+ if (carried) native.add(work.id);
750
+ }
751
+ }
752
+ }
753
+ await ctx.io.recordNotificationText(formatEndedWork(ended, native), true);
754
+ ctx.io.broadcastQueueChanged();
755
+ if (!ctx.turnRunning) await ctx.queue.drainQueue();
756
+ })().catch((error) => diagnostic("worker.work-ended-undelivered", error instanceof Error ? error.message : String(error))).finally(() => ctx.idle.scheduleIdleExit());
757
+ };
758
+ }
759
+ async function recordInterruptedAgents(ctx, agents) {
760
+ const running = agents.filter((work) => work.kind === "agent");
761
+ if (!running.length) return 0;
762
+ const state = await readState({ transcripts: [] });
763
+ const session = state.sessions.find((entry) => entry.id === ctx.sessionId);
764
+ const account = state.accounts.find((entry) => entry.id === session?.accountId);
765
+ const ended = [];
766
+ const native = /* @__PURE__ */ new Set();
767
+ for (const work of running) {
768
+ const file = session ? await locateAgentTranscript(work, session, account).catch(quiet("worker/handed-off-work")) : void 0;
769
+ if (file) native.add(work.id);
770
+ ended.push({ ...work, outcome: "cut-off", tail: "ClikCode closed the process running it before it finished.", ...file ? { outputFile: file } : {} });
771
+ }
772
+ lifecycle("worker.agents.interrupted", { count: ended.length, resumable: native.size, agents: ended.map((work) => work.id).join(",") });
773
+ await ctx.io.recordNotificationText(formatEndedWork(ended, native), true);
774
+ return ended.length;
775
+ }
776
+
777
+ // src/worker/broadcast-observer.ts
778
+ import { randomUUID as randomUUID2 } from "node:crypto";
779
+ var LIVE_THOUGHT_CHARS = 1e3;
780
+ var MAX_UNREAD_BYTES = 16 * 1024 * 1024;
781
+ var readsSaved = /* @__PURE__ */ new WeakSet();
782
+ function windowReadsSaved(socket) {
783
+ readsSaved.add(socket);
784
+ }
785
+ function forWindow(socket, event) {
786
+ if (event.type !== "snapshot" || !event.session.messages || !readsSaved.has(socket)) return event;
787
+ const at = transcriptPosition(event.session.messages);
788
+ if (!at) return event;
789
+ const { messages, ...rest } = event.session;
790
+ return { ...event, session: rest, saved: { count: messages.length, ...at } };
791
+ }
792
+ function sendEvent(socket, event) {
793
+ if (socket.destroyed) return;
794
+ if (socket.writableLength > MAX_UNREAD_BYTES) {
795
+ socket.destroy();
796
+ return;
797
+ }
798
+ socket.write(encodeFrame(forWindow(socket, event)));
799
+ }
800
+ var BroadcastObserver = class {
801
+ clients = /* @__PURE__ */ new Set();
802
+ /** Mirrors exactly what a client would have painted, so `snapshot()` can
803
+ * hand a late attacher the same thing an already-attached client already
804
+ * sees -- not a re-derivation, a read of the one copy this class owns. */
805
+ liveText = "";
806
+ waitingLabel = "";
807
+ /** True once ANY
808
+ * visible content -- an answer token or a tool activity line -- has
809
+ * streamed for the turn currently in flight. What a cancel handler needs
810
+ * to decide between preserveInterruptedTurn (something real to keep) and
811
+ * discardInterruptedTurn (nothing happened yet, safe to drop entirely). */
812
+ outputStarted = false;
813
+ /** What the running turn was started with (see WorkerEvent's waiting-start). */
814
+ livePrompt;
815
+ /** The running turn is the vendor's own background work (waiting-start `vendorWork`). */
816
+ liveVendorWork = false;
817
+ liveSteerable = false;
818
+ /** Vendor background tasks continue after the parent turn ends. */
819
+ backgroundLevel;
820
+ /** The running turn's tool rows and plan, so a window joining it mid-way
821
+ * draws those too, not only its text. */
822
+ liveActivities = [];
823
+ /** Top-level calls started and not yet finished, by call id: what a held steer is waiting behind. */
824
+ openCalls = /* @__PURE__ */ new Map();
825
+ livePlan = [];
826
+ /** The rest of what an attached window has drawn, so a joining one draws it
827
+ * too: the turn's settled thoughts, plan, notices and approval outcomes
828
+ * (the same marks the journal keeps), the thought being had, the turn's
829
+ * phase and usage so far. */
830
+ liveMarks = [];
831
+ liveThought;
832
+ livePhase;
833
+ liveUsage;
834
+ liveBackground;
835
+ /** The turn's one counter: rows are numbered once, when first seen
836
+ * (turn/turn-marks.ts). The journal's own once it is bound, so a row has
837
+ * the same number on the screen and in the saved turn. */
838
+ sequencer = new MarkSequencer();
839
+ journal;
840
+ /** The turn and the session spool can both report one clerk event. */
841
+ seenActivity = /* @__PURE__ */ new Map();
842
+ /** Each open request is kept WITH the event that asked it, so a client
843
+ * attaching later is asked too (reofferPending). They used to go only to
844
+ * whoever was attached at that moment: a turn waiting on an approval with
845
+ * nobody watching waited forever, and reattaching showed nothing to answer. */
846
+ pendingApprovals = /* @__PURE__ */ new Map();
847
+ pendingQuestions = /* @__PURE__ */ new Map();
848
+ /** A sign-in belongs to the conversation, and runs in ONE window showing
849
+ * it: its `runner`. Every window it reached used to start its own vendor
850
+ * login (two links, two codes, of which only one could work), and a window
851
+ * that had moved to another conversation kept it where no one showing this
852
+ * one could answer it. The turn's sender runs it first; a runner that stops
853
+ * showing the conversation releases it, and the first window showing it to
854
+ * claim it runs it next (`sign-in-pending`, `sign-in-claim`). */
855
+ pendingSignIns = /* @__PURE__ */ new Map();
856
+ /** The window that sent the running turn: a sign-in it needs is offered to
857
+ * it first. Undefined for a turn the worker started itself (a queued
858
+ * message drained after its window closed). */
859
+ turnSender;
860
+ noteTurnSender(socket) {
861
+ this.turnSender = socket;
862
+ }
863
+ /** Told when the oldest approval still waiting changes (undefined: none
864
+ * waits). The worker records it beside its runtime record, so another
865
+ * process can say a conversation is waiting on the user without
866
+ * attaching to it. */
867
+ onAwaitingApproval;
868
+ /** Told when the background work the vendor reports changes (undefined: none). Recorded beside the runtime record like an approval. */
869
+ onBackgroundWork;
870
+ /** The conversation this worker runs: its turn's time waiting on the
871
+ * user is kept under it (turn/user-wait.ts). */
872
+ sessionId;
873
+ /** Approvals and sign-ins open: the turn waits on the user while any is. */
874
+ userWaitChanged() {
875
+ if (this.sessionId) setUserWaiting(this.sessionId, this.pendingApprovals.size + this.pendingQuestions.size + this.pendingSignIns.size > 0);
876
+ }
877
+ awaitingSince = /* @__PURE__ */ new Map();
878
+ announceAwaiting() {
879
+ const first = this.pendingApprovals.entries().next().done ? this.pendingQuestions.entries().next() : this.pendingApprovals.entries().next();
880
+ if (first.done) return this.onAwaitingApproval?.(void 0);
881
+ const [id, pending] = first.value;
882
+ const title = pending.event.type === "approval-request" ? pending.event.title : pending.event.type === "question-request" ? pending.event.request.title : "approval";
883
+ return this.onAwaitingApproval?.({ title, since: this.awaitingSince.get(id) ?? (/* @__PURE__ */ new Date()).toISOString() });
884
+ }
885
+ /** When anything last happened here: an event for the windows (sent or not -- the vendor
886
+ * working with no window open still counts), or a window coming or going. A newer build
887
+ * replaces this worker only once this is old enough (worker-idle.ts RETIRE_QUIET_MS). */
888
+ lastActivityAt = Date.now();
889
+ attach(socket) {
890
+ this.lastActivityAt = Date.now();
891
+ this.clients.add(socket);
892
+ }
893
+ /** Sent to a client that just attached, after its snapshot. */
894
+ reofferPending(socket) {
895
+ for (const pending of [...this.pendingApprovals.values(), ...this.pendingQuestions.values()]) sendEvent(socket, pending.event);
896
+ for (const pending of this.pendingSignIns.values()) sendEvent(socket, signInPending(pending.event));
897
+ }
898
+ get pendingRequestCount() {
899
+ return this.pendingApprovals.size + this.pendingQuestions.size + this.pendingSignIns.size;
900
+ }
901
+ detach(socket) {
902
+ if (this.clients.delete(socket)) this.lastActivityAt = Date.now();
903
+ if (this.turnSender === socket) this.turnSender = void 0;
904
+ for (const [id] of this.pendingSignIns) this.releaseSignIn(id, socket);
905
+ }
906
+ get attachedCount() {
907
+ return this.clients.size;
908
+ }
909
+ /** What a freshly-attached client needs painted immediately: the turn in
910
+ * flight, if any, exactly as far along as it has actually gotten. */
911
+ liveSnapshot(session) {
912
+ return this.turnView(session ?? {}).live;
913
+ }
914
+ /** The conversation and the turn in flight, as one consistent picture.
915
+ *
916
+ * While a user turn runs with its journal bound, the conversation's history
917
+ * and journal are the journal's own, in memory: the live view is sent with
918
+ * exactly the record it continues, and only while that record still has the
919
+ * turn in it -- once folded (or with no turn) the turn is in the history and
920
+ * is not also sent live. A disk read could be from either side of a write
921
+ * (the start's, not awaited; the fold's), and a window drew a turn twice, or
922
+ * not at all, into scrollback that cannot be taken back. Before the journal
923
+ * exists, and for the vendor's own work, nothing is saved yet to disagree with. */
924
+ turnView(session) {
925
+ if (!this.waitingLabel) return { session };
926
+ const record = this.liveVendorWork ? void 0 : this.journal?.session;
927
+ if (!record) return { session, live: this.liveView() };
928
+ const { messages: _messages, pendingTurn: _pendingTurn, ...rest } = session;
929
+ const own = {
930
+ ...rest,
931
+ ...record.messages ? { messages: record.messages } : {},
932
+ ...record.pendingTurn ? { pendingTurn: record.pendingTurn } : {}
933
+ };
934
+ return { session: own, ...record.pendingTurn ? { live: this.liveView() } : {} };
935
+ }
936
+ liveView() {
937
+ return {
938
+ text: this.liveText,
939
+ waitingLabel: this.waitingLabel,
940
+ ...this.livePrompt !== void 0 ? { prompt: this.livePrompt } : {},
941
+ ...this.liveVendorWork ? { vendorWork: true } : {},
942
+ ...this.liveSteerable ? { steerable: true } : {},
943
+ activities: [...this.liveActivities],
944
+ plan: [...this.livePlan],
945
+ ...this.livePlan.length ? this.planOffset() : {},
946
+ ...this.liveMarks.length ? { marks: [...this.liveMarks] } : {},
947
+ ...this.liveThought ? { thought: liveThought(this.liveThought) } : {},
948
+ ...this.livePhase ? { phase: this.livePhase } : {},
949
+ ...this.liveUsage ? { usage: this.liveUsage } : {},
950
+ ...this.liveBackground ? { background: { ...this.liveBackground }, ...this.liveBackground.agents ? { pendingBackground: this.liveBackground.agents } : {} } : {}
951
+ };
952
+ }
953
+ planOffset() {
954
+ const plan = this.liveMarks.find((mark) => mark.kind === "plan");
955
+ return plan ? { planOffset: plan.responseOffset } : {};
956
+ }
957
+ /** The whole conversation, and the turn in flight if there is one, for one
958
+ * window -- read synchronously, so no event can fall between what the
959
+ * snapshot holds and what the window is sent after it. */
960
+ snapshotFor(socket, read, account) {
961
+ const { session, live } = this.turnView(read);
962
+ sendEvent(socket, {
963
+ type: "snapshot",
964
+ session,
965
+ ...account ? { account } : {},
966
+ ...live ? { live } : {},
967
+ ...this.backgroundLevel ? { background: this.backgroundLevel } : {}
968
+ });
969
+ }
970
+ /** `decided`: the user chose (a window's answer), as against the vendor
971
+ * withdrawing it. Only a decision leaves a settled row behind. */
972
+ resolveApproval(id, approved, decided = true) {
973
+ const pending = this.pendingApprovals.get(id);
974
+ if (!pending) return;
975
+ this.pendingApprovals.delete(id);
976
+ this.awaitingSince.delete(id);
977
+ this.userWaitChanged();
978
+ pending.resolve(approved);
979
+ this.announceAwaiting();
980
+ const callId = pending.event.type === "approval-request" ? pending.event.callId : void 0;
981
+ const outcome = decided && pending.place ? this.recordOutcome(pending.place, approved === false ? "denied" : "approved", id, callId) : void 0;
982
+ this.broadcast({ type: "request-closed", id, ...outcome ?? {} });
983
+ }
984
+ resolveQuestion(id, result, decided = true) {
985
+ const pending = this.pendingQuestions.get(id);
986
+ if (!pending) return;
987
+ this.pendingQuestions.delete(id);
988
+ this.awaitingSince.delete(id);
989
+ this.userWaitChanged();
990
+ pending.resolve(result);
991
+ this.announceAwaiting();
992
+ const outcome = decided && pending.place ? this.recordOutcome(pending.place, result.kind === "answered" ? "answered" : "denied", id) : void 0;
993
+ this.broadcast({ type: "request-closed", id, ...outcome ?? {} });
994
+ }
995
+ /** The settled row of a decided request, kept at the place it was asked. */
996
+ recordOutcome(place, outcome, id, callId) {
997
+ const call = callId ? { callId } : {};
998
+ this.putMark({ kind: "outcome", id: `outcome:${id}`, seq: place.seq, responseOffset: place.responseOffset, outcome, label: place.label, ...call });
999
+ return { outcome, label: place.label, ...call };
1000
+ }
1001
+ /** Where a request being asked now sits in the turn. */
1002
+ placeOf(label) {
1003
+ return this.waitingLabel ? { seq: this.sequencer.take(), responseOffset: this.liveText.length, label } : void 0;
1004
+ }
1005
+ /** A mark of the turn: kept for a window joining, and handed to the
1006
+ * journal. The copy kept is the merged one (a plan updates in place). */
1007
+ putMark(mark) {
1008
+ if (!this.waitingLabel) return;
1009
+ this.liveMarks = upsertMark(this.liveMarks, mark);
1010
+ const kept = this.liveMarks.find((item) => item.id === mark.id);
1011
+ if (kept) this.journal?.recordMark(kept);
1012
+ }
1013
+ /** The turn's journal exists: from here its counter numbers rows and every
1014
+ * mark goes to it. What the observer made before that is handed over. */
1015
+ bindJournal(journal) {
1016
+ this.journal = journal;
1017
+ if (!journal) return;
1018
+ journal.sequencer.raiseTo(this.sequencer.peek());
1019
+ this.sequencer = journal.sequencer;
1020
+ for (const mark of this.liveMarks) journal.recordMark(mark);
1021
+ if (this.liveThought) journal.setThought(this.liveThought);
1022
+ }
1023
+ /** Where the steer `id` was placed, when the turn has taken it. */
1024
+ steerOrder(id) {
1025
+ return this.journal?.steerOrder(id);
1026
+ }
1027
+ /** The thought being had settles where it began (`Thought for Ns`). */
1028
+ settleLiveThought() {
1029
+ const open = this.liveThought;
1030
+ if (!open) return;
1031
+ this.liveThought = void 0;
1032
+ this.journal?.setThought(void 0);
1033
+ this.putMark(settledThought(open, Date.now()));
1034
+ }
1035
+ /** A hard Stop: nothing the turn asked is answered any more. */
1036
+ rejectPendingRequests() {
1037
+ this.dropPending();
1038
+ }
1039
+ /** A turn's end, whatever it was: nobody is left to answer what it asked. */
1040
+ dropPending() {
1041
+ const hadApprovals = this.pendingApprovals.size > 0 || this.pendingQuestions.size > 0;
1042
+ for (const id of [...this.pendingApprovals.keys(), ...this.pendingQuestions.keys(), ...this.pendingSignIns.keys()]) this.broadcast({ type: "request-closed", id });
1043
+ for (const pending of this.pendingApprovals.values()) pending.resolve(false);
1044
+ this.pendingApprovals.clear();
1045
+ for (const pending of this.pendingQuestions.values()) pending.resolve({ kind: "cancelled" });
1046
+ this.pendingQuestions.clear();
1047
+ this.awaitingSince.clear();
1048
+ if (hadApprovals) this.announceAwaiting();
1049
+ for (const pending of this.pendingSignIns.values()) {
1050
+ pending.unwatch();
1051
+ pending.reject(new SignInEnded("the turn ended", "cancelled"));
1052
+ }
1053
+ this.pendingSignIns.clear();
1054
+ this.turnSender = void 0;
1055
+ this.userWaitChanged();
1056
+ }
1057
+ /** To every attached window, or every one but `except` (sent its own). */
1058
+ broadcast(event, except) {
1059
+ this.lastActivityAt = Date.now();
1060
+ for (const client of this.clients) if (client !== except) sendEvent(client, event);
1061
+ }
1062
+ render(read, account) {
1063
+ const { session, live } = this.turnView(read);
1064
+ this.broadcast({ type: "snapshot", session, ...account ? { account } : {}, ...live ? { live } : {} });
1065
+ }
1066
+ response(text, mode = "append") {
1067
+ if (text) this.outputStarted = true;
1068
+ if (mode === "replace") {
1069
+ const before = this.liveText;
1070
+ if (before !== text) {
1071
+ const at = (offset) => remapOffset(before, text, offset);
1072
+ this.liveActivities = this.liveActivities.map((row) => ({ ...row, responseOffset: at(row.responseOffset) }));
1073
+ this.liveMarks = this.liveMarks.map((mark) => ({ ...mark, responseOffset: at(mark.responseOffset) }));
1074
+ if (this.liveThought) this.liveThought = { ...this.liveThought, responseOffset: at(this.liveThought.responseOffset) };
1075
+ }
1076
+ } else if (text.trim()) {
1077
+ this.settleLiveThought();
1078
+ }
1079
+ this.liveText = mode === "replace" ? text : this.liveText + text;
1080
+ this.broadcast({ type: "delta", text, mode });
1081
+ }
1082
+ /** Sub-agent calls still open: stopping the turn would end them (a vendor harness cancels them with the turn). */
1083
+ openAgentCalls() {
1084
+ return [...this.openCalls.entries()].filter(([, call]) => call.agent).map(([id, call]) => ({ id, label: call.label }));
1085
+ }
1086
+ /** The oldest call still running, and for how long: what a typed message waits behind. */
1087
+ openCall() {
1088
+ let oldest;
1089
+ for (const call of this.openCalls.values()) if (!oldest || call.since < oldest.since) oldest = call;
1090
+ return oldest ? { label: oldest.label, seconds: Math.round((Date.now() - oldest.since) / 1e3), count: this.openCalls.size } : void 0;
1091
+ }
1092
+ activity(message) {
1093
+ this.outputStarted = true;
1094
+ const place = this.waitingLabel ? { seq: this.sequencer.take(), responseOffset: this.liveText.length } : void 0;
1095
+ if (place) this.putMark({ kind: "notice", id: `notice:${place.seq}`, ...place, message });
1096
+ this.broadcast({ type: "note", message, ...place ?? {} });
1097
+ }
1098
+ activityEvent(raw) {
1099
+ const event = this.sequencer.stamp(normalizeActivityEvent(raw));
1100
+ if (event.id) {
1101
+ const key = `${event.id}\0${event.kind}\0${event.parentId ?? ""}\0${event.label}`;
1102
+ const value = JSON.stringify(event);
1103
+ if (this.seenActivity.get(key) === value) return;
1104
+ this.seenActivity.set(key, value);
1105
+ }
1106
+ this.outputStarted = true;
1107
+ if (event.id && !event.parentId) {
1108
+ if (event.kind === "tool-start") this.openCalls.set(event.id, { label: event.label, since: Date.now(), agent: event.agent === true });
1109
+ else if (event.kind === "tool-done" || event.kind === "tool-error") this.openCalls.delete(event.id);
1110
+ }
1111
+ if (this.waitingLabel && !event.parentId) this.foldThought(event);
1112
+ if (this.waitingLabel && isTranscriptActivity(event)) this.liveActivities.push({ event, responseOffset: this.liveText.length });
1113
+ this.broadcast({ type: "activity", event });
1114
+ }
1115
+ /** The turn's own thinking, as a row (standard 4): accumulates by the rule
1116
+ * every surface uses, settles when a call starts, the answer begins or a
1117
+ * new reasoning item takes over. A sub-agent's thinking is its own. */
1118
+ foldThought(event) {
1119
+ if (event.kind === "tool-start") {
1120
+ this.settleLiveThought();
1121
+ return;
1122
+ }
1123
+ if (event.kind !== "thinking") return;
1124
+ const step = stepThought(
1125
+ this.liveThought,
1126
+ this.liveMarks,
1127
+ { label: event.label, ...event.id ? { id: event.id } : {}, seq: event.seq ?? this.sequencer.seqFor(event) },
1128
+ { offset: this.liveText.length, now: Date.now() }
1129
+ );
1130
+ if (step.unchanged) return;
1131
+ if (step.mark) this.putMark(step.mark);
1132
+ if (step.thought !== this.liveThought) {
1133
+ this.liveThought = step.thought;
1134
+ this.journal?.setThought(step.thought);
1135
+ }
1136
+ }
1137
+ phase(message) {
1138
+ if (this.waitingLabel) this.livePhase = message;
1139
+ this.broadcast({ type: "phase", message });
1140
+ }
1141
+ /** The turn's plan: one row, drawn where it first appeared, updated in
1142
+ * place and kept after every step is done (standard 7). */
1143
+ setPlan(entries) {
1144
+ let place;
1145
+ if (this.waitingLabel) {
1146
+ this.livePlan = entries;
1147
+ const kept = this.liveMarks.find((mark) => mark.id === "plan");
1148
+ if (entries.length || kept) {
1149
+ place = kept ?? { seq: this.sequencer.take(), responseOffset: this.liveText.length };
1150
+ this.putMark({ kind: "plan", id: "plan", seq: place.seq, responseOffset: place.responseOffset, entries: entries.map((entry) => ({ ...entry })) });
1151
+ }
1152
+ }
1153
+ this.broadcast({ type: "plan", entries, ...place ? { seq: place.seq, responseOffset: place.responseOffset } : {} });
1154
+ }
1155
+ setBackgroundWork(work) {
1156
+ const level = mergeBackgroundWork(void 0, work ?? {});
1157
+ this.backgroundLevel = level;
1158
+ if (this.waitingLabel) this.liveBackground = level;
1159
+ void this.onBackgroundWork?.(level);
1160
+ this.broadcast({ type: "background", pending: level?.agents ?? 0, ...level ? { work: level } : {} });
1161
+ }
1162
+ setTurnUsage(usage) {
1163
+ if (this.waitingLabel) this.liveUsage = { ...this.liveUsage, ...usage };
1164
+ this.broadcast({ type: "usage", usage });
1165
+ }
1166
+ approval(title, detail, preview, rule, signal, callId) {
1167
+ const id = randomUUID2();
1168
+ if (signal?.aborted) return Promise.resolve(false);
1169
+ signal?.addEventListener("abort", () => {
1170
+ if (this.pendingApprovals.has(id)) {
1171
+ this.resolveApproval(id, false, false);
1172
+ }
1173
+ }, { once: true });
1174
+ const place = this.placeOf(title);
1175
+ const event = {
1176
+ type: "approval-request",
1177
+ id,
1178
+ title,
1179
+ ...detail ? { detail } : {},
1180
+ ...preview ? { preview } : {},
1181
+ ...rule ? { rule } : {},
1182
+ ...callId ? { callId } : {},
1183
+ ...place ? { seq: place.seq, responseOffset: place.responseOffset } : {}
1184
+ };
1185
+ return new Promise((resolveApproval) => {
1186
+ this.pendingApprovals.set(id, { resolve: resolveApproval, event, ...place ? { place } : {} });
1187
+ this.awaitingSince.set(id, (/* @__PURE__ */ new Date()).toISOString());
1188
+ this.userWaitChanged();
1189
+ const recorded = this.announceAwaiting();
1190
+ if (recorded instanceof Promise) void recorded.then(() => {
1191
+ if (this.pendingApprovals.has(id)) this.broadcast(event);
1192
+ });
1193
+ else this.broadcast(event);
1194
+ });
1195
+ }
1196
+ askQuestions(request, signal) {
1197
+ const id = randomUUID2();
1198
+ if (signal?.aborted) return Promise.resolve({ kind: "cancelled" });
1199
+ const place = this.placeOf(request.title);
1200
+ const event = { type: "question-request", id, request, ...place ? { seq: place.seq, responseOffset: place.responseOffset } : {} };
1201
+ signal?.addEventListener("abort", () => {
1202
+ if (this.pendingQuestions.has(id)) this.resolveQuestion(id, { kind: "cancelled" }, false);
1203
+ }, { once: true });
1204
+ return new Promise((resolveQuestion) => {
1205
+ this.pendingQuestions.set(id, { resolve: resolveQuestion, event, ...place ? { place } : {} });
1206
+ this.awaitingSince.set(id, (/* @__PURE__ */ new Date()).toISOString());
1207
+ this.userWaitChanged();
1208
+ const recorded = this.announceAwaiting();
1209
+ if (recorded instanceof Promise) void recorded.then(() => {
1210
+ if (this.pendingQuestions.has(id)) this.broadcast(event);
1211
+ });
1212
+ else this.broadcast(event);
1213
+ });
1214
+ }
1215
+ /** onCancel/onSubmit are part of TurnObserver's shape because a real
1216
+ * TerminalHarnessPrompter needs them for its own key handling, but the
1217
+ * worker never calls them: a client's `cancel`/`steer` commands are
1218
+ * handled directly by session-worker.ts against its own AbortController
1219
+ * and LiveTurnInputBroker for the turn currently running, not through the
1220
+ * observer at all. Accepted and ignored here rather than left off the
1221
+ * signature, so this still satisfies the one interface both a worker and
1222
+ * a real terminal are held to. */
1223
+ startWaiting(message, _onCancel, _onSubmit, _onCommand) {
1224
+ this.startTurn(message);
1225
+ }
1226
+ /** Counts turns started through this observer, user and background alike,
1227
+ * so a turn can tell whether the waiting line is still its own. */
1228
+ generation = 0;
1229
+ get turnGeneration() {
1230
+ return this.generation;
1231
+ }
1232
+ /** The running turn gained or lost a way to take a message into itself. */
1233
+ setSteerable(value) {
1234
+ if (this.liveSteerable === value) return;
1235
+ this.liveSteerable = value;
1236
+ this.broadcast({ type: "steerable", value });
1237
+ }
1238
+ /** startWaiting, naming the prompt the turn runs, for clients following it. */
1239
+ startTurn(message, prompt, vendorWork = false) {
1240
+ this.generation++;
1241
+ this.liveVendorWork = vendorWork;
1242
+ this.liveSteerable = false;
1243
+ this.seenActivity.clear();
1244
+ this.liveText = "";
1245
+ this.waitingLabel = message;
1246
+ this.livePrompt = prompt;
1247
+ this.liveActivities = [];
1248
+ this.livePlan = [];
1249
+ this.resetLiveMarks();
1250
+ this.outputStarted = false;
1251
+ this.broadcast({ type: "waiting-start", message, ...prompt !== void 0 ? { prompt } : {}, ...vendorWork ? { vendorWork: true } : {} });
1252
+ }
1253
+ stopWaiting() {
1254
+ this.endWaiting(false);
1255
+ }
1256
+ /** A new turn's rows are numbered from its own counter; the last one's
1257
+ * journal is no longer this turn's. */
1258
+ resetLiveMarks() {
1259
+ this.liveMarks = [];
1260
+ this.liveThought = void 0;
1261
+ this.livePhase = void 0;
1262
+ this.liveUsage = void 0;
1263
+ this.liveBackground = void 0;
1264
+ this.journal = void 0;
1265
+ this.sequencer = new MarkSequencer();
1266
+ }
1267
+ /** `stopped`: the turn was stopped, not finished -- whichever window
1268
+ * stopped it, every one ends it that way. */
1269
+ endWaiting(stopped) {
1270
+ this.openCalls.clear();
1271
+ this.waitingLabel = "";
1272
+ this.livePrompt = void 0;
1273
+ this.liveVendorWork = false;
1274
+ this.liveSteerable = false;
1275
+ this.liveActivities = [];
1276
+ this.livePlan = [];
1277
+ this.resetLiveMarks();
1278
+ this.dropPending();
1279
+ this.broadcast({ type: "waiting-stop", ...stopped ? { stopped: true } : {} });
1280
+ }
1281
+ /** The turn is over: the conversation as it now stands, then waiting-stop.
1282
+ * The snapshot goes first because a window stops listening at waiting-stop;
1283
+ * it carries no `live`, because nothing is running any more -- a journal it
1284
+ * still holds is an interrupted turn, and a window draws it as one. */
1285
+ endTurn(session, account, stopped = false) {
1286
+ if (session) this.broadcast({ type: "snapshot", session, ...account ? { account } : {}, ...stopped ? { stopped: true } : {} });
1287
+ this.endWaiting(stopped);
1288
+ }
1289
+ get turnOutputStarted() {
1290
+ return this.outputStarted;
1291
+ }
1292
+ /** The turn has an answer the user can see: assistant text, or a tool
1293
+ * row. A thought, and a notice, are not an answer. Esc uses this to
1294
+ * decide whether the prompt comes back or the turn stops. */
1295
+ get turnHasAnswer() {
1296
+ return Boolean(this.liveText.trim()) || this.liveActivities.length > 0;
1297
+ }
1298
+ get liveResponseText() {
1299
+ return this.liveText;
1300
+ }
1301
+ /** The sign-in runs on the client's terminal (see SignInRequest). With no
1302
+ * client attached there is nowhere to run it, so the turn fails with its
1303
+ * authentication error and the user signs in on reattaching. */
1304
+ signIn(request, signal) {
1305
+ if (this.clients.size === 0) return Promise.reject(new SignInEnded(`sign in to ${request.name} needs an open ClikCode window`, "unavailable"));
1306
+ if (signal?.aborted) return Promise.reject(new SignInEnded("stopped", "cancelled"));
1307
+ const id = randomUUID2();
1308
+ const event = { type: "sign-in-request", id, ...request };
1309
+ const runner = this.turnSender && this.clients.has(this.turnSender) ? this.turnSender : void 0;
1310
+ return new Promise((resolve, reject) => {
1311
+ const stop = () => this.settleSignIn(id, new SignInEnded("stopped", "cancelled"));
1312
+ signal?.addEventListener("abort", stop, { once: true });
1313
+ this.pendingSignIns.set(id, { resolve, reject, event, runner, unwatch: () => signal?.removeEventListener("abort", stop) });
1314
+ this.userWaitChanged();
1315
+ this.broadcast(signInPending(event));
1316
+ if (runner) sendEvent(runner, event);
1317
+ });
1318
+ }
1319
+ /** A window showing the conversation will run the sign-in: it does, unless one already is. */
1320
+ claimSignIn(id, socket) {
1321
+ const pending = this.pendingSignIns.get(id);
1322
+ if (!pending || pending.runner && this.clients.has(pending.runner) || !this.clients.has(socket)) return;
1323
+ pending.runner = socket;
1324
+ sendEvent(socket, pending.event);
1325
+ }
1326
+ /** The window running the sign-in stopped showing the conversation (or
1327
+ * closed): every window is told it waits, and one showing it claims it. */
1328
+ releaseSignIn(id, socket) {
1329
+ const pending = this.pendingSignIns.get(id);
1330
+ if (!pending || pending.runner !== socket) return;
1331
+ pending.runner = void 0;
1332
+ this.broadcast(signInPending(pending.event), socket);
1333
+ }
1334
+ /** The window running the sign-in says how it ended. Only that window's
1335
+ * word counts: another window, or one that has since released it, is
1336
+ * ignored. */
1337
+ answerSignIn(id, socket, answer = {}) {
1338
+ if (this.pendingSignIns.get(id)?.runner !== socket) return;
1339
+ this.settleSignIn(id, answer.error === void 0 ? void 0 : new SignInEnded(answer.error, answer.outcome ?? "failed"));
1340
+ }
1341
+ settleSignIn(id, failure) {
1342
+ const pending = this.pendingSignIns.get(id);
1343
+ if (!pending) return;
1344
+ this.pendingSignIns.delete(id);
1345
+ pending.unwatch();
1346
+ this.userWaitChanged();
1347
+ this.broadcast({ type: "request-closed", id });
1348
+ if (failure) pending.reject(failure);
1349
+ else pending.resolve();
1350
+ }
1351
+ };
1352
+ var signInPending = (event) => ({ type: "sign-in-pending", id: event.id, name: event.name });
1353
+ var liveThought = (open) => ({
1354
+ ...open.id === void 0 ? {} : { id: open.id },
1355
+ text: open.text.length > LIVE_THOUGHT_CHARS ? `\u2026${open.text.slice(-(LIVE_THOUGHT_CHARS - 1))}` : open.text,
1356
+ ...open.heading ? { heading: open.heading } : {},
1357
+ seq: open.seq,
1358
+ responseOffset: open.responseOffset,
1359
+ startedAt: open.startedAtMs
1360
+ });
1361
+
1362
+ // src/worker/vendor-background.ts
1363
+ var BACKGROUND_TURN_LABEL = "background work";
1364
+ var NOTIFICATION_RETRY_PROMPT = "A background task finished while your usage limit was reached, so its notification went unanswered. Check what the finished background tasks reported and carry on from there.";
1365
+ function splitRefusal(text, now = Date.now()) {
1366
+ const refusal = refusalEndingReply(text);
1367
+ if (!refusal) return void 0;
1368
+ const resetsAt = quotaRetryHint(new Error(refusal), now);
1369
+ return { prose: text.trimEnd().slice(0, text.trimEnd().length - refusal.length).trimEnd(), refusal, ...resetsAt ? { resetsAt } : {} };
1370
+ }
1371
+ function backgroundTurnRecord(outcome, finished) {
1372
+ const text = outcome.text.trim();
1373
+ if (text) return text;
1374
+ if (outcome.ended !== "completed") return void 0;
1375
+ const unique = [...new Set(finished.filter((label) => !/^(?:failed )?tool$/i.test(label.trim())))];
1376
+ if (!unique.length) return void 0;
1377
+ return `Background work finished: ${unique.slice(0, 8).join("; ")}${unique.length > 8 ? `; and ${unique.length - 8} more` : ""}.`;
1378
+ }
1379
+ function appendBackgroundRecord(session, record, now) {
1380
+ session.messages = [...session.messages ?? [], { role: "assistant", content: record }];
1381
+ session.updatedAt = now;
1382
+ }
1383
+ function createVendorBackgroundRunner(deps) {
1384
+ const waiting = [];
1385
+ let active;
1386
+ const superseded = [];
1387
+ let saving = Promise.resolve();
1388
+ const persist = (records, change) => {
1389
+ const write = saving.then(async () => {
1390
+ const state = await readState({ transcripts: [deps.sessionId] });
1391
+ const session = state.sessions.find((item) => item.id === deps.sessionId);
1392
+ if (!session) return void 0;
1393
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1394
+ for (const record of records) appendBackgroundRecord(session, record, now);
1395
+ change?.(session, now);
1396
+ await writeState(state);
1397
+ return session;
1398
+ });
1399
+ saving = write.catch(quiet("worker/vendor-background"));
1400
+ return write;
1401
+ };
1402
+ const markAccountSpent = async (refusal) => {
1403
+ const accountId = (await readState({ transcripts: [] })).sessions.find((item) => item.id === deps.sessionId)?.nativeThreadAccountId;
1404
+ if (!accountId) return;
1405
+ await observeSessionAccount({ sessionId: deps.sessionId, accountId, evidence: { vendorError: true, text: refusal }, source: "background-turn" });
1406
+ };
1407
+ const saveSuperseded = () => {
1408
+ if (!superseded.length) return Promise.resolve(void 0);
1409
+ return persist(superseded.splice(0)).catch(quiet("worker/vendor-background"));
1410
+ };
1411
+ const run = async (turn) => {
1412
+ active = turn;
1413
+ void deps.runningChanged?.((/* @__PURE__ */ new Date()).toISOString());
1414
+ lifecycle("worker.background.start", { transport: turn.transport, reason: turn.reason });
1415
+ deps.changed();
1416
+ const { observer } = deps;
1417
+ const finished = [];
1418
+ let level;
1419
+ const recorder = new TurnRecorder(BACKGROUND_TURN_LABEL, "reported");
1420
+ recorder.start();
1421
+ observer.startTurn(BACKGROUND_TURN_LABEL, void 0, true);
1422
+ const generation = observer.turnGeneration;
1423
+ const owned = () => observer.turnGeneration === generation && !deps.userTurnRunning();
1424
+ const sink = {
1425
+ onResponseDelta: (text, mode) => observer.response(text, mode ?? "append"),
1426
+ onActivity: (event) => {
1427
+ if (event.kind === "tool-done" || event.kind === "tool-error") finished.push(`${event.kind === "tool-error" ? "failed " : ""}${event.label}`);
1428
+ recorder.add(event);
1429
+ observer.activityEvent(event);
1430
+ },
1431
+ onThought: (text, id) => observer.activityEvent({ kind: "thinking", label: thoughtLabel(text), ...id ? { id } : {} }),
1432
+ onUsage: (usage) => observer.setTurnUsage(usage),
1433
+ onBackgroundWork: (update) => {
1434
+ level = mergeBackgroundWork(level, update);
1435
+ observer.setBackgroundWork?.(level);
1436
+ },
1437
+ onPhase: (phase) => observer.phase(phase),
1438
+ onPlan: (entries) => observer.setPlan(entries),
1439
+ onApproval: async (title, detail, preview, signal, callId) => await observer.approval(title, detail, preview, void 0, signal, callId) !== false,
1440
+ onNotice: (message) => diagnostic("vendor.notice", message),
1441
+ ...observer.askQuestions ? { onQuestion: (request, signal) => observer.askQuestions(request, signal) } : {}
1442
+ };
1443
+ turn.attach(sink);
1444
+ try {
1445
+ const outcome = await turn.finished;
1446
+ lifecycle("worker.background.end", { ended: outcome.ended });
1447
+ const refused = splitRefusal(outcome.text);
1448
+ const prose = refused ? backgroundTurnRecord({ ...outcome, text: refused.prose }, finished) : backgroundTurnRecord(outcome, finished);
1449
+ const refusalRow = refused ? `${refused.refusal}${refused.resetsAt ? " The notification will be retried after the reset." : ""}` : void 0;
1450
+ const record = prose ?? refusalRow;
1451
+ if (refused) {
1452
+ lifecycle("worker.background.refused", { refusal: refused.refusal.slice(0, 200), ...refused.resetsAt ? { resetsAt: refused.resetsAt } : {} });
1453
+ if (owned()) observer.response(refused.prose, "replace");
1454
+ }
1455
+ if (record) await recorder.finish(stateDirectory(), deps.sessionId).catch(quiet("worker/vendor-background"));
1456
+ const records = [...prose ? [prose] : [], ...refusalRow ? [refusalRow] : []];
1457
+ const park = refused?.resetsAt ? (session2, now) => {
1458
+ session2.resumeAt ??= { at: refused.resetsAt, prompt: NOTIFICATION_RETRY_PROMPT, setAt: now };
1459
+ } : void 0;
1460
+ if (!owned()) {
1461
+ superseded.push(...records);
1462
+ if (park) void persist([], park).then(() => deps.resumeParked?.()).catch(quiet("worker/vendor-background"));
1463
+ if (refused) void markAccountSpent(refused.refusal);
1464
+ return;
1465
+ }
1466
+ const session = records.length || park ? await persist(records, park).catch(quiet("worker/vendor-background")) : void 0;
1467
+ if (park) deps.resumeParked?.();
1468
+ if (refused) void markAccountSpent(refused.refusal);
1469
+ if (observer.turnGeneration !== generation) return;
1470
+ observer.endTurn(session);
1471
+ } finally {
1472
+ active = void 0;
1473
+ void deps.runningChanged?.(void 0);
1474
+ deps.changed();
1475
+ next();
1476
+ }
1477
+ };
1478
+ const next = () => {
1479
+ if (active || deps.userTurnRunning()) return;
1480
+ const turn = waiting.shift();
1481
+ if (turn) void run(turn);
1482
+ };
1483
+ return {
1484
+ handle: (turn) => {
1485
+ waiting.push(turn);
1486
+ next();
1487
+ },
1488
+ get busy() {
1489
+ return Boolean(active) || waiting.length > 0;
1490
+ },
1491
+ settled: () => saving.then(() => void 0),
1492
+ saveSuperseded,
1493
+ userTurnEnded: () => {
1494
+ void saveSuperseded();
1495
+ next();
1496
+ }
1497
+ };
1498
+ }
1499
+
1500
+ // src/worker/resume-wait.ts
1501
+ async function takeResumeAt(sessionId) {
1502
+ const state = await readState({ transcripts: [] });
1503
+ const session = state.sessions.find((item) => item.id === sessionId);
1504
+ const parked = session?.resumeAt;
1505
+ if (!session || !parked) return void 0;
1506
+ delete session.resumeAt;
1507
+ await writeState(state);
1508
+ return parked;
1509
+ }
1510
+ function createResumeWaiter(host) {
1511
+ const now = host.now ?? Date.now;
1512
+ let timer;
1513
+ let pending = false;
1514
+ let chain = Promise.resolve();
1515
+ const serial = (step) => {
1516
+ chain = chain.then(step, step).catch((error) => {
1517
+ host.notice(`Could not resume after the reset: ${error instanceof Error ? error.message : String(error)}`);
1518
+ });
1519
+ return chain;
1520
+ };
1521
+ const setPending = (next) => {
1522
+ if (pending === next) return;
1523
+ pending = next;
1524
+ host.changed();
1525
+ };
1526
+ const clearTimer = () => {
1527
+ if (timer) clearTimeout(timer);
1528
+ timer = void 0;
1529
+ };
1530
+ const look = async () => {
1531
+ clearTimer();
1532
+ const state = await readState({ transcripts: [] });
1533
+ const session = state.sessions.find((item) => item.id === host.sessionId);
1534
+ const parked = session?.resumeAt;
1535
+ if (!session || !parked) {
1536
+ setPending(false);
1537
+ return;
1538
+ }
1539
+ setPending(true);
1540
+ if (host.turnRunning()) return;
1541
+ const step = resumeStep(parked, state.accounts, session.provider, now(), matchesVendorTurn);
1542
+ if (typeof step === "object") {
1543
+ timer = setTimeout(() => {
1544
+ void serial(look);
1545
+ }, step.wait);
1546
+ return;
1547
+ }
1548
+ const taken = await takeResumeAt(host.sessionId);
1549
+ setPending(false);
1550
+ if (!taken) return;
1551
+ if (step === "give-up") {
1552
+ await host.restore(taken.prompt);
1553
+ host.notice("Stopped waiting for the reset: no account could take the turn an hour after it. Your message is back, unsent.");
1554
+ return;
1555
+ }
1556
+ await host.send(taken.prompt);
1557
+ };
1558
+ return {
1559
+ check: () => serial(look),
1560
+ // The user's own Esc or new message: nothing is said.
1561
+ cancel: () => serial(async () => {
1562
+ clearTimer();
1563
+ await takeResumeAt(host.sessionId);
1564
+ setPending(false);
1565
+ }),
1566
+ get pending() {
1567
+ return pending;
1568
+ },
1569
+ stop: clearTimer
1570
+ };
1571
+ }
1572
+
1573
+ // src/worker/resource-guard.ts
1574
+ import { mkdirSync, readFileSync as readFileSync2, rmSync, statfsSync, writeFileSync as writeFileSync2 } from "node:fs";
1575
+ import { join as join5 } from "node:path";
1576
+
1577
+ // src/worker/resource-probes.ts
1578
+ import { execFile } from "node:child_process";
1579
+ import { promisify } from "node:util";
1580
+ import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
1581
+ import { freemem, totalmem } from "node:os";
1582
+ import { join as join4 } from "node:path";
1583
+ var execFileAsync = promisify(execFile);
1584
+ var isWorker = (command) => !!command && /\ssession-worker\s/.test(` ${command} `);
1585
+ var STALL_CRITICAL_PERCENT = 10;
1586
+ function readNumber(path) {
1587
+ try {
1588
+ const text = readFileSync(path, "utf8").trim();
1589
+ return text === "max" ? void 0 : Number(text);
1590
+ } catch {
1591
+ return void 0;
1592
+ }
1593
+ }
1594
+ function statField(dir, name) {
1595
+ try {
1596
+ return Number(new RegExp(`^${name} (\\d+)`, "m").exec(readFileSync(join4(dir, "memory.stat"), "utf8"))?.[1] ?? 0);
1597
+ } catch {
1598
+ return 0;
1599
+ }
1600
+ }
1601
+ function processFreeable(pid) {
1602
+ try {
1603
+ const stat3 = readFileSync(`/proc/${pid}/smaps_rollup`, "utf8");
1604
+ const kb = (name) => Number(new RegExp(`^${name}:\\s*(\\d+)`, "m").exec(stat3)?.[1] ?? 0);
1605
+ return (kb("Pss_Anon") + kb("SwapPss")) * 1024;
1606
+ } catch {
1607
+ return 0;
1608
+ }
1609
+ }
1610
+ function cgroupFreeable(dir) {
1611
+ const chargedHere = statField(dir, "anon") + (readNumber(join4(dir, "memory.swap.current")) ?? 0);
1612
+ const residentProcesses = groupPids(dir).reduce((sum, pid) => sum + processFreeable(pid), 0);
1613
+ return Math.max(chargedHere, residentProcesses);
1614
+ }
1615
+ function sampleSlice(sliceDir) {
1616
+ try {
1617
+ const meminfo = readFileSync("/proc/meminfo", "utf8");
1618
+ const field = (name) => Number(new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(meminfo)?.[1] ?? 0) * 1024;
1619
+ const ceilings = [readNumber(join4(sliceDir, "memory.high")), readNumber(join4(sliceDir, "memory.max"))].filter((value) => !!value);
1620
+ let stalled = 0;
1621
+ try {
1622
+ stalled = Number(/^full avg10=([\d.]+)/m.exec(readFileSync(join4(sliceDir, "memory.pressure"), "utf8"))?.[1]) || 0;
1623
+ } catch {
1624
+ }
1625
+ return {
1626
+ total: field("MemTotal"),
1627
+ available: field("MemAvailable"),
1628
+ used: statField(sliceDir, "anon") + statField(sliceDir, "shmem") + statField(sliceDir, "kernel"),
1629
+ ...ceilings.length ? { ceiling: Math.min(...ceilings) } : {},
1630
+ critical: stalled >= STALL_CRITICAL_PERCENT
1631
+ };
1632
+ } catch {
1633
+ return void 0;
1634
+ }
1635
+ }
1636
+ function workerPidFromEnv(envText) {
1637
+ const value = envText.split("\0").find((entry) => entry.startsWith(`${WORKER_PID_ENV}=`))?.slice(WORKER_PID_ENV.length + 1);
1638
+ return value && /^\d+$/.test(value) ? Number(value) : void 0;
1639
+ }
1640
+ function sliceInventory(sliceDir, read = readProc, remembered, readEnv = readProcessEnv) {
1641
+ let names = [];
1642
+ try {
1643
+ names = readdirSync(sliceDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
1644
+ } catch {
1645
+ return { units: [], workers: [] };
1646
+ }
1647
+ const units = [];
1648
+ const workers = [];
1649
+ for (const name of names) {
1650
+ const dir = join4(sliceDir, name);
1651
+ if (!name.startsWith("clikcode-worker-")) continue;
1652
+ const divided = (() => {
1653
+ try {
1654
+ return statSync(join4(dir, AGENT_GROUP)).isDirectory();
1655
+ } catch {
1656
+ return false;
1657
+ }
1658
+ })();
1659
+ const agentPids = groupPids(divided ? join4(dir, AGENT_GROUP) : dir);
1660
+ const worker = agentPids.find((pid) => isWorker(read(pid)?.command));
1661
+ if (worker === void 0) continue;
1662
+ workers.push(worker);
1663
+ if (!divided) continue;
1664
+ for (const group of readdirSync(dir).filter((child) => COMMAND_GROUP.test(child))) {
1665
+ const groupDir = join4(dir, group);
1666
+ const infos = groupPids(groupDir).map(read).filter((entry) => !!entry);
1667
+ const rootPid = Number(group.slice(4));
1668
+ const root = infos.find((entry) => entry.pid === rootPid) ?? read(rootPid);
1669
+ const saved = remembered && dir === remembered.scopeDir ? remembered.labels.get(group) : void 0;
1670
+ units.push({ kind: "command", target: { cgroup: groupDir }, owner: worker, label: bestLabel(root, infos.filter((entry) => entry.pid !== rootPid), saved) || group, freeable: cgroupFreeable(groupDir) });
1671
+ }
1672
+ }
1673
+ for (const name of names) {
1674
+ if (!/^run-.*\.(scope|service)$/.test(name)) continue;
1675
+ const dir = join4(sliceDir, name);
1676
+ const pids = groupPids(dir);
1677
+ const tagged = pids.map(readEnv).map((text) => text ? workerPidFromEnv(text) : void 0).find((pid) => pid !== void 0);
1678
+ if (tagged === void 0) continue;
1679
+ const infos = pids.map(read).filter((entry) => !!entry);
1680
+ units.push({
1681
+ kind: "command",
1682
+ target: { cgroup: dir },
1683
+ ...workers.includes(tagged) ? { owner: tagged } : {},
1684
+ label: bestLabel(void 0, infos) || name,
1685
+ freeable: cgroupFreeable(dir)
1686
+ });
1687
+ }
1688
+ return { units, workers };
1689
+ }
1690
+ function readProcessEnv(pid) {
1691
+ try {
1692
+ return readFileSync(join4("/proc", String(pid), "environ"), "utf8");
1693
+ } catch {
1694
+ return void 0;
1695
+ }
1696
+ }
1697
+ function cgroupProbe(sliceDir, remembered) {
1698
+ return {
1699
+ sample: () => sampleSlice(sliceDir),
1700
+ inventory: () => sliceInventory(sliceDir, readProc, remembered),
1701
+ stop: (target) => {
1702
+ if (!("cgroup" in target)) return false;
1703
+ try {
1704
+ writeFileSync(join4(target.cgroup, "cgroup.kill"), "1");
1705
+ return true;
1706
+ } catch {
1707
+ return false;
1708
+ }
1709
+ }
1710
+ };
1711
+ }
1712
+ function parsePs(output) {
1713
+ const entries = [];
1714
+ for (const line of output.split("\n")) {
1715
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
1716
+ if (!match) continue;
1717
+ entries.push({ pid: Number(match[1]), ppid: Number(match[2]), bytes: Number(match[3]) * 1024, exe: match[4].split("/").pop().toLowerCase(), command: match[5] ?? "" });
1718
+ }
1719
+ return entries;
1720
+ }
1721
+ function parseWindowsProcesses(output) {
1722
+ try {
1723
+ const parsed = JSON.parse(output);
1724
+ const rows = Array.isArray(parsed) ? parsed : [parsed];
1725
+ return rows.flatMap((row) => {
1726
+ if (!row || typeof row !== "object") return [];
1727
+ const item = row;
1728
+ if (!Number.isInteger(item.ProcessId) || !Number.isInteger(item.ParentProcessId) || typeof item.Name !== "string") return [];
1729
+ const startedAt = windowsStartedAt(item.CreationDate);
1730
+ return [{
1731
+ pid: Number(item.ProcessId),
1732
+ ppid: Number(item.ParentProcessId),
1733
+ bytes: Number(item.WorkingSetSize) || 0,
1734
+ exe: item.Name.toLowerCase().replace(/\.exe$/, ""),
1735
+ command: typeof item.CommandLine === "string" ? item.CommandLine : "",
1736
+ ...startedAt ? { startedAt } : {}
1737
+ }];
1738
+ });
1739
+ } catch {
1740
+ return [];
1741
+ }
1742
+ }
1743
+ var WINDOWS_TABLE = '$ErrorActionPreference="SilentlyContinue"; Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ ProcessId=$_.ProcessId; ParentProcessId=$_.ParentProcessId; WorkingSetSize=[int64]$_.WorkingSetSize; Name=$_.Name; CommandLine=$_.CommandLine; CreationDate=$(if($_.CreationDate){$_.CreationDate.ToUniversalTime().ToString("o")}) } } | ConvertTo-Json -Compress -Depth 3';
1744
+ function windowsStartedAt(value) {
1745
+ if (typeof value !== "string" || !value) return void 0;
1746
+ const wrapped = /^\/Date\((-?\d+)\)\/$/.exec(value);
1747
+ if (wrapped) {
1748
+ const parsed = new Date(Number(wrapped[1]));
1749
+ return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString();
1750
+ }
1751
+ return Number.isFinite(Date.parse(value)) ? value : void 0;
1752
+ }
1753
+ async function readProcessTable(platform = process.platform) {
1754
+ try {
1755
+ const command = platform === "win32" ? "powershell.exe" : "ps";
1756
+ const args = platform === "win32" ? ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TABLE] : ["-axo", "pid=,ppid=,rss=,ucomm=,args="];
1757
+ const { stdout } = await execFileAsync(command, args, { encoding: "utf8", timeout: platform === "win32" ? 15e3 : 1e4, windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
1758
+ return platform === "win32" ? parseWindowsProcesses(stdout) : parsePs(stdout);
1759
+ } catch {
1760
+ return [];
1761
+ }
1762
+ }
1763
+ function tableInventory(entries) {
1764
+ const children = /* @__PURE__ */ new Map();
1765
+ const byPid = new Map(entries.map((entry) => [entry.pid, entry]));
1766
+ for (const entry of entries) {
1767
+ const parent = byPid.get(entry.ppid);
1768
+ if (parent?.startedAt && entry.startedAt && Date.parse(entry.startedAt) < Date.parse(parent.startedAt)) continue;
1769
+ children.set(entry.ppid, [...children.get(entry.ppid) ?? [], entry]);
1770
+ }
1771
+ const bytesOf = new Map(entries.map((entry) => [entry.pid, entry.bytes]));
1772
+ const units = [];
1773
+ const workers = [];
1774
+ for (const worker of entries.filter((entry) => isWorker(entry.command))) {
1775
+ workers.push(worker.pid);
1776
+ const tree = [];
1777
+ const stack = [...children.get(worker.pid) ?? []];
1778
+ while (stack.length) {
1779
+ const next = stack.pop();
1780
+ tree.push(next);
1781
+ stack.push(...children.get(next.pid) ?? []);
1782
+ }
1783
+ for (const command of findCommands(tree)) {
1784
+ units.push({
1785
+ kind: "command",
1786
+ target: {
1787
+ pids: command.pids,
1788
+ root: command.root.pid,
1789
+ command: command.root.command,
1790
+ ...entries.find((entry) => entry.pid === command.root.pid)?.startedAt ? { startedAt: entries.find((entry) => entry.pid === command.root.pid).startedAt } : {}
1791
+ },
1792
+ owner: worker.pid,
1793
+ label: commandLabel(command.root.command),
1794
+ freeable: command.pids.reduce((sum, pid) => sum + (bytesOf.get(pid) ?? 0), 0)
1795
+ });
1796
+ }
1797
+ }
1798
+ return { units, workers };
1799
+ }
1800
+ function parseVmStat(output) {
1801
+ const pageSize = Number(/page size of (\d+) bytes/i.exec(output)?.[1]);
1802
+ if (!pageSize) return void 0;
1803
+ const pages = (name) => Number(new RegExp(`^Pages ${name}:\\s*([\\d.]+)`, "m").exec(output)?.[1]?.replace(/\./g, "") ?? 0);
1804
+ return (pages("free") + pages("inactive") + pages("speculative") + pages("purgeable")) * pageSize;
1805
+ }
1806
+ async function macPressure() {
1807
+ let level = NaN, pressure = NaN;
1808
+ try {
1809
+ const { stdout } = await execFileAsync("sysctl", ["-n", "kern.memorystatus_level", "kern.memorystatus_vm_pressure_level"], { encoding: "utf8", timeout: 5e3 });
1810
+ [level, pressure] = stdout.trim().split(/\s+/).map(Number);
1811
+ } catch {
1812
+ }
1813
+ if (Number.isFinite(level) && level >= 0 && level <= 100) return { availableBytes: totalmem() * level / 100, critical: pressure === 4 };
1814
+ try {
1815
+ const { stdout } = await execFileAsync("vm_stat", [], { encoding: "utf8", timeout: 5e3 });
1816
+ const availableBytes = parseVmStat(stdout);
1817
+ return { ...availableBytes === void 0 ? {} : { availableBytes }, critical: pressure === 4 };
1818
+ } catch {
1819
+ return { critical: pressure === 4 };
1820
+ }
1821
+ }
1822
+ function processProbe(platform = process.platform, options = {}) {
1823
+ const readTable = options.readTable ?? (() => readProcessTable(platform));
1824
+ return {
1825
+ sample: options.readMemory ?? (async () => {
1826
+ const total = totalmem();
1827
+ const mac = platform === "darwin" ? await macPressure() : void 0;
1828
+ if (platform === "darwin" && mac?.availableBytes === void 0) return void 0;
1829
+ const available = mac?.availableBytes ?? freemem();
1830
+ return { total, available, used: total - available, critical: mac?.critical ?? false };
1831
+ }),
1832
+ inventory: async () => tableInventory(await readTable()),
1833
+ stop: async (target) => {
1834
+ if (!("pids" in target)) return false;
1835
+ const current = tableInventory(await readTable());
1836
+ const stillThere = current.units.find((unit) => "pids" in unit.target && unit.target.root === target.root && unit.target.command === target.command && unit.target.startedAt === target.startedAt && unit.target.pids.length === target.pids.length && unit.target.pids.every((pid) => target.pids.includes(pid)));
1837
+ if (!stillThere) return false;
1838
+ if (options.stopTree) return options.stopTree(target);
1839
+ if (platform === "win32") {
1840
+ try {
1841
+ await execFileAsync("taskkill", ["/PID", String(target.root), "/T", "/F"], { timeout: 1e4, windowsHide: true });
1842
+ return true;
1843
+ } catch {
1844
+ return false;
1845
+ }
1846
+ }
1847
+ let stopped = false;
1848
+ for (const pid of target.pids) {
1849
+ try {
1850
+ process.kill(pid, "SIGKILL");
1851
+ stopped = true;
1852
+ } catch {
1853
+ }
1854
+ }
1855
+ return stopped;
1856
+ }
1857
+ };
1858
+ }
1859
+
1860
+ // src/worker/resource-guard.ts
1861
+ var GIB = 2 ** 30;
1862
+ var TICK_MS = 2e3;
1863
+ var NUDGE_AT = 0.85;
1864
+ var NUDGE_REARM_BELOW = 0.75;
1865
+ var SETTLE_MS = 15e3;
1866
+ var STOP_INTERVAL_MS = 2e4;
1867
+ var EFFECTIVE_SHARE = 0.25;
1868
+ var SLICE_CEILING_SHARE = 0.97;
1869
+ function desktopReserve(total) {
1870
+ return Math.max(4 * GIB, total * 0.08);
1871
+ }
1872
+ function agentBudget(sample) {
1873
+ const byMachine = sample.used + sample.available - desktopReserve(sample.total);
1874
+ const bySlice = sample.ceiling ? sample.ceiling * SLICE_CEILING_SHARE : Infinity;
1875
+ const limit = Math.max(0, Math.min(byMachine, bySlice));
1876
+ const ratio = limit > 0 ? sample.used / limit : Infinity;
1877
+ return { used: sample.used, limit, ratio: sample.critical ? Math.max(ratio, 1) : ratio };
1878
+ }
1879
+ function worthStopping(unit, budget) {
1880
+ return unit.freeable >= Math.max(GIB, budget.limit * 0.03);
1881
+ }
1882
+ function decideAction(budget, inventory) {
1883
+ if (budget.ratio < NUDGE_AT || !inventory.workers.length) return { kind: "none" };
1884
+ const bySize = [...inventory.units].sort((a, b) => b.freeable - a.freeable);
1885
+ const commands = bySize.filter((unit) => unit.kind === "command");
1886
+ const owned = commands.filter((unit) => unit.owner !== void 0);
1887
+ if (budget.ratio >= 1) {
1888
+ const command = commands.find((unit) => worthStopping(unit, budget));
1889
+ if (command) return { kind: "stop", worker: command.owner ?? Math.min(...inventory.workers), unit: command };
1890
+ }
1891
+ const largest = owned[0];
1892
+ if (!largest) return { kind: "nudge", worker: Math.min(...inventory.workers) };
1893
+ return worthStopping(largest, budget) ? { kind: "nudge", worker: largest.owner, unit: largest } : { kind: "nudge", worker: largest.owner };
1894
+ }
1895
+ var gb = (bytes) => `${(bytes / GIB).toFixed(1)} GB`;
1896
+ function nudgeNote(budget, conversations, unit) {
1897
+ return [
1898
+ `Memory is getting tight: agents are using ${gb(budget.used)} of ${gb(budget.limit)} available to them across ${conversations} conversation${conversations === 1 ? "" : "s"}.`,
1899
+ unit ? `Your \`${unit.label}\` holds about ${gb(unit.freeable)}.` : "",
1900
+ unit ? "Continue the task with less memory: run targeted tests, use fewer parallel workers, or finish and close this command before starting another large one. Choose the smallest change that fits your work." : "Continue the task. For your next heavy step, use targeted tests, fewer parallel workers, or a smaller batch. If none applies, keep working; no command in this conversation was identified as the cause."
1901
+ ].filter(Boolean).join(" ");
1902
+ }
1903
+ function stopNote(budget, conversations, unit, platform = process.platform) {
1904
+ const how = platform === "win32" ? "terminated by ClikCode (taskkill)" : "killed by ClikCode (SIGKILL)";
1905
+ return `ClikCode stopped \`${unit.label}\` and its child processes because it held about ${gb(unit.freeable)} while agents used ${gb(budget.used)} of ${gb(budget.limit)} across ${conversations} conversations. It was ${how} for resource pressure, not a test failure. Continue the task with targeted tests, fewer workers, or smaller runs; do not rerun the same command unchanged.`;
1906
+ }
1907
+ function marker() {
1908
+ return join5(stateDirectory(), "resource-guard.last-stop");
1909
+ }
1910
+ function ineffectiveMarker() {
1911
+ return join5(stateDirectory(), "resource-guard.ineffective");
1912
+ }
1913
+ function lastStopAt() {
1914
+ try {
1915
+ return Number(readFileSync2(marker(), "utf8")) || 0;
1916
+ } catch {
1917
+ return 0;
1918
+ }
1919
+ }
1920
+ function ineffective() {
1921
+ try {
1922
+ return readFileSync2(ineffectiveMarker(), "utf8").length > 0;
1923
+ } catch {
1924
+ return false;
1925
+ }
1926
+ }
1927
+ function ramTmpNote() {
1928
+ try {
1929
+ if (!/^tmpfs \/tmp /m.test(readFileSync2("/proc/mounts", "utf8"))) return "";
1930
+ const stat3 = statfsSync("/tmp");
1931
+ const used = Number(stat3.bsize) * (Number(stat3.blocks) - Number(stat3.bavail));
1932
+ if (!(used >= 4 * GIB)) return "";
1933
+ return ` /tmp is RAM here and holds about ${gb(used)}; remove only temporary files you created and no longer need. Stopping a command does not free those files.`;
1934
+ } catch {
1935
+ return "";
1936
+ }
1937
+ }
1938
+ function startResourceGuard(options) {
1939
+ const { sessionId, deliver } = options;
1940
+ const probe = options.probe ?? (options.sliceDir ? cgroupProbe(options.sliceDir, options.remembered) : processProbe());
1941
+ let nudged = false;
1942
+ let pending;
1943
+ const tick = async () => {
1944
+ const sample = await probe.sample();
1945
+ if (!sample) return;
1946
+ const budget = agentBudget(sample);
1947
+ if (pending && Date.now() - pending.at >= SETTLE_MS) {
1948
+ const freed = pending.before - budget.used;
1949
+ const effective = freed >= pending.unit.freeable * EFFECTIVE_SHARE;
1950
+ lifecycle("resource.effect", { session: sessionId, label: pending.unit.label, held: pending.unit.freeable, freed, effective });
1951
+ if (!effective) writeFileSync2(ineffectiveMarker(), String(Date.now()));
1952
+ pending = void 0;
1953
+ }
1954
+ if (budget.ratio < NUDGE_REARM_BELOW) {
1955
+ nudged = false;
1956
+ try {
1957
+ rmSync(ineffectiveMarker(), { force: true });
1958
+ } catch (error) {
1959
+ swallowed("worker/resource-guard", error);
1960
+ }
1961
+ }
1962
+ if (budget.ratio < NUDGE_AT || Date.now() - lastStopAt() < STOP_INTERVAL_MS || pending) return;
1963
+ const inventory = await probe.inventory();
1964
+ const action = decideAction(budget, inventory);
1965
+ if (action.kind === "none") return;
1966
+ const conversations = inventory.workers.length;
1967
+ if (action.kind === "stop" && !ineffective()) {
1968
+ if (!await probe.stop(action.unit.target)) return;
1969
+ try {
1970
+ mkdirSync(stateDirectory(), { recursive: true });
1971
+ writeFileSync2(marker(), String(Date.now()));
1972
+ } catch (error) {
1973
+ swallowed("worker/resource-guard", error);
1974
+ }
1975
+ pending = { unit: action.unit, before: budget.used, at: Date.now() };
1976
+ lifecycle("resource.stop", { session: sessionId, kind: action.unit.kind, label: action.unit.label, held: action.unit.freeable, used: budget.used, limit: budget.limit });
1977
+ if (action.unit.owner !== void 0) deliver(stopNote(budget, conversations, action.unit) + ramTmpNote(), action.unit.owner);
1978
+ } else if (!nudged) {
1979
+ nudged = true;
1980
+ lifecycle("resource.nudge", { session: sessionId, ...action.unit ? { label: action.unit.label, held: action.unit.freeable } : {}, used: budget.used, limit: budget.limit });
1981
+ deliver(nudgeNote(budget, conversations, action.unit) + ramTmpNote(), action.worker);
1982
+ }
1983
+ };
1984
+ let running = false;
1985
+ const timer = setInterval(() => {
1986
+ if (running) return;
1987
+ running = true;
1988
+ void tick().catch((error) => lifecycle("resource.error", { session: sessionId, message: error instanceof Error ? error.message : String(error) })).finally(() => {
1989
+ running = false;
1990
+ });
1991
+ }, TICK_MS);
1992
+ timer.unref();
1993
+ return () => clearInterval(timer);
1994
+ }
1995
+
1996
+ // src/worker/conversation-tmp.ts
1997
+ import { mkdirSync as mkdirSync2 } from "node:fs";
1998
+ import { join as join6 } from "node:path";
1999
+ function useConversationTmp(sessionId) {
2000
+ const dir = join6(stateDirectory(), "t", sessionId.slice(0, 8));
2001
+ try {
2002
+ mkdirSync2(dir, { recursive: true, mode: 448 });
2003
+ } catch {
2004
+ return void 0;
2005
+ }
2006
+ process.env.TMPDIR = dir;
2007
+ if (process.platform === "win32") {
2008
+ process.env.TMP = dir;
2009
+ process.env.TEMP = dir;
2010
+ }
2011
+ return dir;
2012
+ }
2013
+
2014
+ // src/worker/disk-watch.ts
2015
+ import { existsSync as existsSync2, statfsSync as statfsSync2, statSync as statSync2 } from "node:fs";
2016
+ var GIB2 = 2 ** 30;
2017
+ var CHECK_MS = 3e4;
2018
+ var CLEAR_MARGIN = 1.25;
2019
+ var tightBelow = (total) => Math.max(20 * GIB2, total * 0.1);
2020
+ var criticalBelow = (total) => Math.max(5 * GIB2, total * 0.03);
2021
+ var severity = { ok: 0, tight: 1, critical: 2 };
2022
+ function nextLevel(previous, reading) {
2023
+ const critical = reading.free < criticalBelow(reading.total);
2024
+ const tight = reading.free < tightBelow(reading.total);
2025
+ let level = critical ? "critical" : tight ? "tight" : "ok";
2026
+ if (previous === "critical" && level !== "critical" && reading.free < criticalBelow(reading.total) * CLEAR_MARGIN) level = "critical";
2027
+ if (previous !== "ok" && level === "ok" && reading.free < tightBelow(reading.total) * CLEAR_MARGIN) level = "tight";
2028
+ return level;
2029
+ }
2030
+ var gb2 = (bytes) => `${(bytes / GIB2).toFixed(1)} GB`;
2031
+ function diskNote(level, reading, hasDocker) {
2032
+ const used = Math.round((1 - reading.free / reading.total) * 100);
2033
+ const where = `${gb2(reading.free)} free of ${gb2(reading.total)} (${used}% used) on the drive holding ${reading.path}`;
2034
+ const docker = hasDocker ? " or remove stopped containers you started and no longer need with `docker rm -fv` so their volumes go too" : "";
2035
+ return level === "critical" ? `Disk is almost full: ${where}. Keep working on read-only or targeted steps while you free space: remove build output or temp files you created and no longer need${docker}. Then retry the smallest necessary write; a large write may fail until space is freed.` : `Disk is getting tight: ${where}. Continue the task while reducing new writes: reuse existing output, choose a smaller build or download, or remove build output and temp files you created and no longer need${docker}. Pick a concrete step that fits your work.`;
2036
+ }
2037
+ function readDisk(path) {
2038
+ try {
2039
+ const stat3 = statfsSync2(path);
2040
+ const size = Number(stat3.bsize);
2041
+ return { path, device: String(statSync2(path).dev), total: size * Number(stat3.blocks), free: size * Number(stat3.bavail) };
2042
+ } catch {
2043
+ return void 0;
2044
+ }
2045
+ }
2046
+ function startDiskWatch(options) {
2047
+ const read = options.read ?? readDisk;
2048
+ const hasDocker = options.hasDocker ?? (process.platform !== "win32" && existsSync2("/var/run/docker.sock"));
2049
+ const paths = [...new Set(options.paths.filter((path) => !!path))];
2050
+ const levels = /* @__PURE__ */ new Map();
2051
+ const tick = () => {
2052
+ const seen = /* @__PURE__ */ new Set();
2053
+ for (const path of paths) {
2054
+ const reading = read(path);
2055
+ if (!reading || seen.has(reading.device) || reading.total <= 0) continue;
2056
+ seen.add(reading.device);
2057
+ const previous = levels.get(reading.device) ?? "ok";
2058
+ const level = nextLevel(previous, reading);
2059
+ levels.set(reading.device, level);
2060
+ if (severity[level] <= severity[previous] || level === "ok") continue;
2061
+ lifecycle("disk.nudge", { session: options.sessionId, level, path: reading.path, free: reading.free, total: reading.total });
2062
+ options.deliver(diskNote(level, reading, hasDocker));
2063
+ }
2064
+ };
2065
+ tick();
2066
+ const timer = setInterval(tick, options.intervalMs ?? CHECK_MS);
2067
+ timer.unref();
2068
+ return () => clearInterval(timer);
2069
+ }
2070
+
2071
+ // src/worker/io-guard.ts
2072
+ import { mkdirSync as mkdirSync3, readdirSync as readdirSync2, readFileSync as readFileSync3, realpathSync, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync3 } from "node:fs";
2073
+ import { join as join7 } from "node:path";
2074
+ var MIB = 2 ** 20;
2075
+ var TICK_MS2 = 5e3;
2076
+ var WARN_PRESSURE = 5;
2077
+ var STOP_PRESSURE = 15;
2078
+ var CLEAR_PRESSURE = 2;
2079
+ var MIN_BYTES_PER_SECOND = 16 * MIB;
2080
+ var MIN_IOPS = 1e3;
2081
+ var MIN_MACHINE_SHARE = 0.5;
2082
+ var STOP_AFTER_MS = 2e4;
2083
+ var STOP_COOLDOWN_MS = 6e4;
2084
+ var SETTLE_MS2 = 3e4;
2085
+ var GLOBAL_WARN_COOLDOWN_MS = 24 * 60 * 6e4;
2086
+ var OWNED_WARN_COOLDOWN_MS = 30 * 6e4;
2087
+ var REARM_AFTER_CLEAR_MS = 5 * 6e4;
2088
+ function parseIoStat(value) {
2089
+ const result = /* @__PURE__ */ new Map();
2090
+ for (const line of value.split("\n")) {
2091
+ const [device, ...fields] = line.trim().split(/\s+/);
2092
+ if (!/^\d+:\d+$/.test(device ?? "")) continue;
2093
+ const numbers = new Map(fields.map((field) => field.split("=")));
2094
+ const number = (key) => Number(numbers.get(key) ?? 0);
2095
+ const bytes = number("rbytes") + number("wbytes");
2096
+ const operations = number("rios") + number("wios");
2097
+ if (Number.isFinite(bytes) && Number.isFinite(operations)) result.set(device, { bytes, operations });
2098
+ }
2099
+ return result;
2100
+ }
2101
+ function ioDelta(before, after) {
2102
+ const result = /* @__PURE__ */ new Map();
2103
+ for (const [device, current] of after) {
2104
+ const previous = before.get(device);
2105
+ if (!previous || current.bytes < previous.bytes || current.operations < previous.operations) continue;
2106
+ result.set(device, { bytes: current.bytes - previous.bytes, operations: current.operations - previous.operations });
2107
+ }
2108
+ return result;
2109
+ }
2110
+ function ioPressure(text) {
2111
+ const value = Number(/^full\s+avg10=([\d.]+)/m.exec(text)?.[1]);
2112
+ return Number.isFinite(value) ? value : void 0;
2113
+ }
2114
+ function ioSomePressure(text) {
2115
+ const value = Number(/^some\s+avg10=([\d.]+)/m.exec(text)?.[1]);
2116
+ return Number.isFinite(value) ? value : void 0;
2117
+ }
2118
+ function ioCandidate(previous, current) {
2119
+ const seconds = (current.at - previous.at) / 1e3;
2120
+ if (seconds < 1 || seconds > 30) return void 0;
2121
+ const machine = ioDelta(previous.machine, current.machine);
2122
+ let best;
2123
+ for (const command of current.commands) {
2124
+ if (command.stalled < WARN_PRESSURE) continue;
2125
+ const old = previous.commands.find((entry) => entry.path === command.path && entry.identity === command.identity);
2126
+ if (!old) continue;
2127
+ for (const [device, activity] of ioDelta(old.counters, command.counters)) {
2128
+ const total = machine.get(device);
2129
+ if (!total || total.bytes <= 0 || activity.bytes > total.bytes) continue;
2130
+ const candidate = {
2131
+ command,
2132
+ device,
2133
+ bytesPerSecond: activity.bytes / seconds,
2134
+ operationsPerSecond: activity.operations / seconds,
2135
+ machineShare: activity.bytes / total.bytes
2136
+ };
2137
+ if ((candidate.bytesPerSecond >= MIN_BYTES_PER_SECOND || candidate.operationsPerSecond >= MIN_IOPS) && candidate.machineShare >= MIN_MACHINE_SHARE && (!best || candidate.bytesPerSecond > best.bytesPerSecond)) best = candidate;
2138
+ }
2139
+ }
2140
+ return best;
2141
+ }
2142
+ var physicalDevices = /* @__PURE__ */ new Map();
2143
+ function isPhysicalDevice(device) {
2144
+ const cached = physicalDevices.get(device);
2145
+ if (cached !== void 0) return cached;
2146
+ let physical = false;
2147
+ try {
2148
+ physical = !realpathSync(join7("/sys/dev/block", device)).includes("/virtual/");
2149
+ } catch {
2150
+ }
2151
+ physicalDevices.set(device, physical);
2152
+ return physical;
2153
+ }
2154
+ function readCounters(path) {
2155
+ try {
2156
+ const counters = parseIoStat(readFileSync3(path, "utf8"));
2157
+ for (const device of counters.keys()) {
2158
+ if (!isPhysicalDevice(device)) counters.delete(device);
2159
+ }
2160
+ return counters;
2161
+ } catch {
2162
+ return void 0;
2163
+ }
2164
+ }
2165
+ function parseDiskstats(text) {
2166
+ const result = /* @__PURE__ */ new Map();
2167
+ for (const line of text.split("\n")) {
2168
+ const fields = line.trim().split(/\s+/);
2169
+ if (fields.length < 10 || !/^\d+$/.test(fields[0] ?? "") || !/^\d+$/.test(fields[1] ?? "")) continue;
2170
+ const bytes = (Number(fields[5]) + Number(fields[9])) * 512;
2171
+ const operations = Number(fields[3]) + Number(fields[7]);
2172
+ if (Number.isFinite(bytes) && Number.isFinite(operations)) result.set(`${fields[0]}:${fields[1]}`, { bytes, operations });
2173
+ }
2174
+ return result;
2175
+ }
2176
+ function readReading(scopeDir, labels, now) {
2177
+ try {
2178
+ const pressure = ioPressure(readFileSync3("/proc/pressure/io", "utf8"));
2179
+ const machine = parseDiskstats(readFileSync3("/proc/diskstats", "utf8"));
2180
+ if (pressure === void 0 || !machine) return void 0;
2181
+ const commands = [];
2182
+ for (const name of readdirSync2(scopeDir).filter((name2) => COMMAND_GROUP.test(name2))) {
2183
+ const path = join7(scopeDir, name);
2184
+ try {
2185
+ const counters = readCounters(join7(path, "io.stat"));
2186
+ if (!counters) continue;
2187
+ const stalled = ioSomePressure(readFileSync3(join7(path, "io.pressure"), "utf8"));
2188
+ if (stalled === void 0) continue;
2189
+ const stat3 = statSync3(path);
2190
+ commands.push({ path, label: labels.get(name) || name, identity: `${stat3.dev}:${stat3.ino}`, counters, stalled });
2191
+ } catch {
2192
+ }
2193
+ }
2194
+ return { pressure, machine, commands, at: now };
2195
+ } catch {
2196
+ return void 0;
2197
+ }
2198
+ }
2199
+ var gbps = (bytesPerSecond) => `${(bytesPerSecond / MIB).toFixed(0)} MiB/s`;
2200
+ function ioNudge(candidate, pressure) {
2201
+ return `Disk I/O is stalling the machine (${pressure.toFixed(0)}% full stall time). Your \`${candidate.command.label}\` is issuing about ${gbps(candidate.bytesPerSecond)} on the busy device. Continue the task with less disk I/O: run only the needed targets, use fewer parallel jobs, or reuse existing build output. Choose a specific change for this command and keep working; this warning does not ask you to pause.`;
2202
+ }
2203
+ function ioGlobalNudge(pressure) {
2204
+ return `Disk I/O is stalling the machine (${pressure.toFixed(0)}% full stall time). ClikCode has not identified a command in this conversation as the cause. Continue the task. If you started an external build or container, check that job and reduce its parallel jobs or stop only redundant work you own. For your next disk-heavy step, run narrower targets, reuse existing output, or use a smaller batch. If none applies, keep working and do not claim your work caused the stall. This warning does not ask you to pause.`;
2205
+ }
2206
+ function ioStopNote(candidate, pressure) {
2207
+ return `ClikCode stopped \`${candidate.command.label}\` and its child processes after sustained disk I/O stalls (${pressure.toFixed(0)}% full stall time). It was issuing about ${gbps(candidate.bytesPerSecond)} and over half of the device's I/O. Continue the task with fewer parallel jobs, narrower targets, or reused build output; do not rerun the same command unchanged.`;
2208
+ }
2209
+ function lastStopPath() {
2210
+ return join7(stateDirectory(), "io-guard.last-stop");
2211
+ }
2212
+ function ineffectivePath() {
2213
+ return join7(stateDirectory(), "io-guard.ineffective");
2214
+ }
2215
+ function warningPath(sessionId, kind) {
2216
+ return join7(stateDirectory(), "io-guard-warnings", `${safeRecordFileName(sessionId)}.${kind}`);
2217
+ }
2218
+ function fileTime(path) {
2219
+ try {
2220
+ return Number(readFileSync3(path, "utf8")) || 0;
2221
+ } catch {
2222
+ return 0;
2223
+ }
2224
+ }
2225
+ function warningDue(sessionId, kind, at) {
2226
+ const path = warningPath(sessionId, kind);
2227
+ const last = fileTime(path);
2228
+ const cooldown = kind === "global" ? GLOBAL_WARN_COOLDOWN_MS : OWNED_WARN_COOLDOWN_MS;
2229
+ if (last > 0 && at >= last && at - last < cooldown) return false;
2230
+ try {
2231
+ mkdirSync3(join7(stateDirectory(), "io-guard-warnings"), { recursive: true, mode: 448 });
2232
+ writeFileSync3(path, String(at), { mode: 384 });
2233
+ } catch (error) {
2234
+ swallowed("worker/io-guard", error);
2235
+ }
2236
+ return true;
2237
+ }
2238
+ function startIoGuard(options) {
2239
+ const now = options.now ?? Date.now;
2240
+ const read = options.read ?? ((at) => readReading(options.scopeDir, options.labels, at));
2241
+ const stop = options.stop ?? ((path) => {
2242
+ try {
2243
+ writeFileSync3(join7(path, "cgroup.kill"), "1");
2244
+ return true;
2245
+ } catch {
2246
+ return false;
2247
+ }
2248
+ });
2249
+ let previous;
2250
+ let highSince;
2251
+ let candidateSince;
2252
+ let candidatePath;
2253
+ let clearSince;
2254
+ let pending;
2255
+ const tick = () => {
2256
+ const current = read(now());
2257
+ if (!current) {
2258
+ previous = void 0;
2259
+ highSince = void 0;
2260
+ candidateSince = void 0;
2261
+ candidatePath = void 0;
2262
+ return;
2263
+ }
2264
+ if (pending && current.at - pending.at >= SETTLE_MS2) {
2265
+ const improved = current.pressure < CLEAR_PRESSURE || current.pressure <= pending.pressure / 2;
2266
+ lifecycle("io.effect", { session: options.sessionId, before: pending.pressure, after: current.pressure, improved });
2267
+ if (!improved) {
2268
+ try {
2269
+ mkdirSync3(stateDirectory(), { recursive: true });
2270
+ writeFileSync3(ineffectivePath(), String(current.at));
2271
+ } catch (error) {
2272
+ swallowed("worker/io-guard", error);
2273
+ }
2274
+ }
2275
+ pending = void 0;
2276
+ }
2277
+ if (current.pressure < CLEAR_PRESSURE) {
2278
+ clearSince ??= current.at;
2279
+ if (current.at - clearSince >= REARM_AFTER_CLEAR_MS) {
2280
+ for (const kind of ["global", "owned"]) {
2281
+ try {
2282
+ rmSync2(warningPath(options.sessionId, kind), { force: true });
2283
+ } catch (error) {
2284
+ swallowed("worker/io-guard", error);
2285
+ }
2286
+ }
2287
+ }
2288
+ highSince = void 0;
2289
+ try {
2290
+ rmSync2(ineffectivePath(), { force: true });
2291
+ } catch (error) {
2292
+ swallowed("worker/io-guard", error);
2293
+ }
2294
+ } else clearSince = void 0;
2295
+ if (current.pressure >= STOP_PRESSURE) highSince ??= current.at;
2296
+ else highSince = void 0;
2297
+ const hadBaseline = !!previous;
2298
+ const candidate = previous ? ioCandidate(previous, current) : void 0;
2299
+ previous = current;
2300
+ if (!hadBaseline) return;
2301
+ if (candidate && candidate.command.path === candidatePath) candidateSince ??= current.at;
2302
+ else {
2303
+ candidatePath = candidate?.command.path;
2304
+ candidateSince = candidate ? current.at : void 0;
2305
+ }
2306
+ if (current.pressure < WARN_PRESSURE) return;
2307
+ if (candidate && warningDue(options.sessionId, "owned", current.at)) {
2308
+ lifecycle("io.nudge", { session: options.sessionId, label: candidate.command.label, pressure: current.pressure, bytesPerSecond: candidate.bytesPerSecond });
2309
+ options.deliver(ioNudge(candidate, current.pressure));
2310
+ } else if (!candidate && warningDue(options.sessionId, "global", current.at)) {
2311
+ lifecycle("io.nudge", { session: options.sessionId, pressure: current.pressure });
2312
+ options.deliver(ioGlobalNudge(current.pressure));
2313
+ }
2314
+ if (!candidate) return;
2315
+ const lastStop = fileTime(lastStopPath());
2316
+ if (highSince === void 0 || current.at - highSince < STOP_AFTER_MS || candidateSince === void 0 || current.at - candidateSince < STOP_AFTER_MS || pending || lastStop > 0 && current.at - lastStop < STOP_COOLDOWN_MS || fileTime(ineffectivePath())) return;
2317
+ let identity;
2318
+ try {
2319
+ const stat3 = statSync3(candidate.command.path);
2320
+ identity = `${stat3.dev}:${stat3.ino}`;
2321
+ if (!readFileSync3(join7(candidate.command.path, "cgroup.procs"), "utf8").trim()) return;
2322
+ } catch {
2323
+ return;
2324
+ }
2325
+ if (identity !== candidate.command.identity || !stop(candidate.command.path)) return;
2326
+ try {
2327
+ mkdirSync3(stateDirectory(), { recursive: true });
2328
+ writeFileSync3(lastStopPath(), String(current.at));
2329
+ } catch (error) {
2330
+ swallowed("worker/io-guard", error);
2331
+ }
2332
+ pending = { pressure: current.pressure, at: current.at };
2333
+ lifecycle("io.stop", { session: options.sessionId, label: candidate.command.label, pressure: current.pressure, bytesPerSecond: candidate.bytesPerSecond, machineShare: candidate.machineShare });
2334
+ options.deliver(ioStopNote(candidate, current.pressure));
2335
+ };
2336
+ const timer = setInterval(() => {
2337
+ try {
2338
+ tick();
2339
+ } catch (error) {
2340
+ lifecycle("io.error", { session: options.sessionId, message: error instanceof Error ? error.message : String(error) });
2341
+ }
2342
+ }, options.intervalMs ?? TICK_MS2);
2343
+ timer.unref();
2344
+ return () => clearInterval(timer);
2345
+ }
2346
+
2347
+ // src/worker/idle-services.ts
2348
+ import { readFileSync as readFileSync4, readdirSync as readdirSync3 } from "node:fs";
2349
+ import { join as join8 } from "node:path";
2350
+ var GIB3 = 2 ** 30;
2351
+ var HOUR_MS = 60 * 60 * 1e3;
2352
+ var MIN_AGE_MS = 12 * HOUR_MS;
2353
+ var WATCH_MS = 30 * 60 * 1e3;
2354
+ var IDLE_CPU = 0.01;
2355
+ var MIN_HELD = 256 * 2 ** 20;
2356
+ var CHECK_MS2 = 10 * 60 * 1e3;
2357
+ var CLOCK_TICKS = 100;
2358
+ function isIdle(reading, since, now) {
2359
+ if (reading.ageMs < MIN_AGE_MS || reading.held < MIN_HELD || !since || now - since.at < WATCH_MS) return false;
2360
+ const used = (reading.cpuUsec - since.cpuUsec) / 1e3;
2361
+ return used / (now - since.at) < IDLE_CPU;
2362
+ }
2363
+ function idleServiceNote(reading) {
2364
+ const hours = Math.floor(reading.ageMs / HOUR_MS);
2365
+ return `The service ${reading.unit} that you started ${hours} hours ago has used almost no CPU for the last half hour and holds ${(reading.held / GIB3).toFixed(1)} GB of the memory agents share. If your task is done with it, stop it: \`systemctl --user stop ${reading.unit}\`. If it is still needed, ignore this; you will not be told again.`;
2366
+ }
2367
+ var fileText = (path) => {
2368
+ try {
2369
+ return readFileSync4(path, "utf8");
2370
+ } catch {
2371
+ return void 0;
2372
+ }
2373
+ };
2374
+ function ownerOf(pids) {
2375
+ for (const pid of pids) {
2376
+ const env = fileText(`/proc/${pid}/environ`);
2377
+ const found = env?.split("\0").find((entry) => entry.startsWith(`${WORKER_PID_ENV}=`));
2378
+ if (found) return Number(found.slice(WORKER_PID_ENV.length + 1)) || void 0;
2379
+ }
2380
+ return void 0;
2381
+ }
2382
+ function ageOf(pid, now) {
2383
+ const stat3 = fileText(`/proc/${pid}/stat`);
2384
+ const boot = /^btime (\d+)/m.exec(fileText("/proc/stat") ?? "");
2385
+ if (!stat3 || !boot) return void 0;
2386
+ const start = Number(stat3.slice(stat3.lastIndexOf(")") + 2).split(" ")[19]);
2387
+ return Number.isFinite(start) ? now - (Number(boot[1]) * 1e3 + start / CLOCK_TICKS * 1e3) : void 0;
2388
+ }
2389
+ function readServices(sliceDir, now) {
2390
+ const readings = [];
2391
+ let names;
2392
+ try {
2393
+ names = readdirSync3(sliceDir).filter((name) => name.endsWith(".service"));
2394
+ } catch {
2395
+ return readings;
2396
+ }
2397
+ for (const unit of names) {
2398
+ const dir = join8(sliceDir, unit);
2399
+ const pids = (fileText(join8(dir, "cgroup.procs")) ?? "").split("\n").filter(Boolean);
2400
+ if (!pids.length) continue;
2401
+ const ageMs2 = ageOf(pids[0], now);
2402
+ const held = Number(fileText(join8(dir, "memory.current")));
2403
+ const cpu = /^usage_usec (\d+)/m.exec(fileText(join8(dir, "cpu.stat")) ?? "");
2404
+ if (ageMs2 === void 0 || !Number.isFinite(held) || !cpu) continue;
2405
+ readings.push({ unit, owner: ownerOf(pids), ageMs: ageMs2, held, cpuUsec: Number(cpu[1]) });
2406
+ }
2407
+ return readings;
2408
+ }
2409
+ function startIdleServices(options) {
2410
+ const read = options.read ?? readServices;
2411
+ const clock = options.now ?? Date.now;
2412
+ const watched = /* @__PURE__ */ new Map();
2413
+ const told = /* @__PURE__ */ new Set();
2414
+ const tick = () => {
2415
+ const now = clock();
2416
+ const live = /* @__PURE__ */ new Set();
2417
+ for (const reading of read(options.sliceDir, now)) {
2418
+ live.add(reading.unit);
2419
+ if (reading.owner !== process.pid) continue;
2420
+ const since = watched.get(reading.unit);
2421
+ if (!since) {
2422
+ watched.set(reading.unit, { cpuUsec: reading.cpuUsec, at: now });
2423
+ continue;
2424
+ }
2425
+ if (!told.has(reading.unit) && isIdle(reading, since, now)) {
2426
+ told.add(reading.unit);
2427
+ lifecycle("service.idle", { session: options.sessionId, unit: reading.unit, held: reading.held, ageMs: reading.ageMs });
2428
+ options.deliver(idleServiceNote(reading));
2429
+ }
2430
+ if (now - since.at >= WATCH_MS) watched.set(reading.unit, { cpuUsec: reading.cpuUsec, at: now });
2431
+ }
2432
+ for (const unit of [...watched.keys()]) if (!live.has(unit)) {
2433
+ watched.delete(unit);
2434
+ told.delete(unit);
2435
+ }
2436
+ };
2437
+ tick();
2438
+ const timer = setInterval(tick, options.intervalMs ?? CHECK_MS2);
2439
+ timer.unref();
2440
+ return () => clearInterval(timer);
2441
+ }
2442
+
2443
+ // src/worker/state-sweep.ts
2444
+ import { lstat, readdir as readdir3, readlink, rm as rm2, utimes, writeFile as writeFile3 } from "node:fs/promises";
2445
+ import { join as join9, sep } from "node:path";
2446
+ var DAY_MS = 24 * 60 * 60 * 1e3;
2447
+ var TMP_MAX_AGE_MS = 3 * DAY_MS;
2448
+ var TMP_MAX_AGE_BLIND_MS = 7 * DAY_MS;
2449
+ var NOTE_MAX_AGE_MS = 7 * DAY_MS;
2450
+ var SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1e3;
2451
+ var SWEEP_MIN_GAP_MS = 60 * 60 * 1e3;
2452
+ var FIRST_SWEEP_DELAY_MS = 6e4;
2453
+ async function pathsInUse(root) {
2454
+ let pids;
2455
+ try {
2456
+ pids = (await readdir3("/proc")).filter((name) => /^\d+$/.test(name));
2457
+ } catch {
2458
+ return void 0;
2459
+ }
2460
+ const prefix = root.endsWith(sep) ? root : `${root}${sep}`;
2461
+ const found = /* @__PURE__ */ new Set();
2462
+ const check = async (link) => {
2463
+ try {
2464
+ const target = await readlink(link);
2465
+ if (target.startsWith(prefix)) found.add(target);
2466
+ } catch {
2467
+ }
2468
+ };
2469
+ for (const pid of pids) {
2470
+ await check(`/proc/${pid}/cwd`);
2471
+ let fds = [];
2472
+ try {
2473
+ fds = await readdir3(`/proc/${pid}/fd`);
2474
+ } catch {
2475
+ }
2476
+ await Promise.all(fds.map((fd) => check(`/proc/${pid}/fd/${fd}`)));
2477
+ }
2478
+ return [...found];
2479
+ }
2480
+ function inUse(used, entry) {
2481
+ return used.some((path) => path === entry || path.startsWith(`${entry}${sep}`));
2482
+ }
2483
+ async function directories(path) {
2484
+ try {
2485
+ return (await readdir3(path, { withFileTypes: true })).filter((item) => item.isDirectory()).map((item) => item.name);
2486
+ } catch {
2487
+ return [];
2488
+ }
2489
+ }
2490
+ async function ageMs(path, now) {
2491
+ try {
2492
+ return now - (await lstat(path)).mtimeMs;
2493
+ } catch {
2494
+ return void 0;
2495
+ }
2496
+ }
2497
+ async function sweepState(options = {}) {
2498
+ const now = options.now ?? Date.now();
2499
+ const home = stateDirectory();
2500
+ const marker2 = join9(home, "state-sweep.last");
2501
+ const last = await ageMs(marker2, now);
2502
+ if (!options.force && last !== void 0 && last < SWEEP_MIN_GAP_MS) return { ran: false, removed: 0 };
2503
+ try {
2504
+ await writeFile3(marker2, String(now));
2505
+ await utimes(marker2, new Date(now), new Date(now));
2506
+ } catch {
2507
+ return { ran: false, removed: 0 };
2508
+ }
2509
+ let removed = 0;
2510
+ const remove = async (path) => {
2511
+ try {
2512
+ await rm2(path, { recursive: true, force: true });
2513
+ removed += 1;
2514
+ } catch {
2515
+ }
2516
+ };
2517
+ const tmpRoot = join9(home, "t");
2518
+ const used = await (options.used ?? pathsInUse)(tmpRoot);
2519
+ const maxAge = used ? TMP_MAX_AGE_MS : TMP_MAX_AGE_BLIND_MS;
2520
+ for (const conversation of await directories(tmpRoot)) {
2521
+ const dir = join9(tmpRoot, conversation);
2522
+ let entries = [];
2523
+ try {
2524
+ entries = await readdir3(dir);
2525
+ } catch {
2526
+ continue;
2527
+ }
2528
+ for (const name of entries) {
2529
+ const entry = join9(dir, name);
2530
+ const age = await ageMs(entry, now);
2531
+ if (age === void 0 || age < maxAge) continue;
2532
+ if (used && inUse(used, entry)) continue;
2533
+ await remove(entry);
2534
+ }
2535
+ }
2536
+ for (const root of ["resource-notes", "io-guard-warnings"]) {
2537
+ const path = join9(home, root);
2538
+ try {
2539
+ for (const name of await readdir3(path)) {
2540
+ const age = await ageMs(join9(path, name), now);
2541
+ if (age !== void 0 && age >= NOTE_MAX_AGE_MS) await remove(join9(path, name));
2542
+ }
2543
+ } catch {
2544
+ }
2545
+ }
2546
+ removed += await sweepWorkersDirectory(now).catch(() => 0);
2547
+ lifecycle("state.sweep", { removed });
2548
+ return { ran: true, removed };
2549
+ }
2550
+ function startStateSweep() {
2551
+ const run = () => {
2552
+ void sweepState().catch((error) => lifecycle("state.sweep.error", { message: error instanceof Error ? error.message : String(error) }));
2553
+ };
2554
+ const first = setTimeout(run, FIRST_SWEEP_DELAY_MS);
2555
+ const every = setInterval(run, SWEEP_INTERVAL_MS);
2556
+ first.unref();
2557
+ every.unref();
2558
+ return () => {
2559
+ clearTimeout(first);
2560
+ clearInterval(every);
2561
+ };
2562
+ }
2563
+
2564
+ // src/worker/guardian.ts
2565
+ import { connect } from "node:net";
2566
+ import { join as join10 } from "node:path";
2567
+ var GUARDIAN_CHECK_MS = 1e4;
2568
+ function guardianLeasePath() {
2569
+ return join10(workersDirectory(), "guardian.lease");
2570
+ }
2571
+ function startGuardian(options) {
2572
+ const lockPath = options.lockPath ?? guardianLeasePath();
2573
+ let lease;
2574
+ let stopGuards;
2575
+ let checking = false;
2576
+ let stopped = false;
2577
+ const check = async () => {
2578
+ if (checking || stopped) return;
2579
+ checking = true;
2580
+ try {
2581
+ if (lease) {
2582
+ if (await lease.held()) return;
2583
+ lifecycle("worker.guardian", { held: false });
2584
+ stopGuards?.();
2585
+ stopGuards = void 0;
2586
+ lease = void 0;
2587
+ return;
2588
+ }
2589
+ const taken = await tryLease(lockPath);
2590
+ if (!taken) return;
2591
+ if (stopped) {
2592
+ await taken.release();
2593
+ return;
2594
+ }
2595
+ lease = taken;
2596
+ lifecycle("worker.guardian", { held: true });
2597
+ stopGuards = options.guard();
2598
+ } finally {
2599
+ checking = false;
2600
+ }
2601
+ };
2602
+ void check().catch(quiet("worker/guardian"));
2603
+ const timer = setInterval(() => {
2604
+ void check().catch(quiet("worker/guardian"));
2605
+ }, options.checkMs ?? GUARDIAN_CHECK_MS);
2606
+ timer.unref();
2607
+ return async () => {
2608
+ stopped = true;
2609
+ clearInterval(timer);
2610
+ stopGuards?.();
2611
+ stopGuards = void 0;
2612
+ await lease?.release();
2613
+ lease = void 0;
2614
+ };
2615
+ }
2616
+ async function sendResourceNote(workerPid, note) {
2617
+ const record = (await liveWorkerRecords()).find((item) => item.pid === workerPid);
2618
+ if (!record) return;
2619
+ await new Promise((resolveSent) => {
2620
+ const socket = connect(record.socketPath);
2621
+ const done = () => {
2622
+ clearTimeout(timer);
2623
+ socket.destroy();
2624
+ resolveSent();
2625
+ };
2626
+ const timer = setTimeout(done, 2e3);
2627
+ socket.on("connect", () => {
2628
+ socket.end(encodeFrame({ type: "resource-note", token: record.token, note }));
2629
+ });
2630
+ socket.on("close", done);
2631
+ socket.on("error", done);
2632
+ });
2633
+ }
2634
+
2635
+ // src/worker/stuck-watchdog.ts
2636
+ import { Worker } from "node:worker_threads";
2637
+ var BEAT_MS = 5e3;
2638
+ var STUCK_MS = 3 * 6e4;
2639
+ var WATCHDOG_THREAD = `
2640
+ const { workerData } = require('node:worker_threads');
2641
+ const { appendFileSync } = require('node:fs');
2642
+ const beats = new Int32Array(workerData.beats);
2643
+ let seen = Atomics.load(beats, 0);
2644
+ let since = Date.now();
2645
+ setInterval(() => {
2646
+ const now = Atomics.load(beats, 0);
2647
+ if (now !== seen) { seen = now; since = Date.now(); return; }
2648
+ if (Date.now() - since < workerData.stuckMs) return;
2649
+ try {
2650
+ appendFileSync(workerData.log, JSON.stringify({
2651
+ stuckForMs: Date.now() - since, t: new Date().toISOString(), pid: process.pid,
2652
+ role: 'worker', session: workerData.sessionId, event: 'worker.stuck',
2653
+ }) + '\\n');
2654
+ } catch {}
2655
+ process.kill(process.pid, 'SIGKILL');
2656
+ }, workerData.checkMs);
2657
+ `;
2658
+ function startStuckWatchdog(sessionId, options = {}) {
2659
+ const stuckMs = options.stuckMs ?? STUCK_MS;
2660
+ const beatMs = options.beatMs ?? BEAT_MS;
2661
+ const beats = new Int32Array(new SharedArrayBuffer(4));
2662
+ const beat = setInterval(() => {
2663
+ Atomics.add(beats, 0, 1);
2664
+ }, beatMs);
2665
+ beat.unref();
2666
+ let log = "";
2667
+ try {
2668
+ log = lifecycleLogPath();
2669
+ } catch {
2670
+ }
2671
+ const thread = new Worker(WATCHDOG_THREAD, {
2672
+ eval: true,
2673
+ workerData: { beats: beats.buffer, stuckMs, checkMs: Math.min(1e4, Math.max(50, Math.floor(stuckMs / 6))), log, sessionId },
2674
+ // The fixed watchdog script uses only a few MB, but Node/V8 needs more
2675
+ // headroom while creating its isolate. A tiny heap limit can abort the
2676
+ // entire session process before its socket is ready (SIGILL in OS::Abort).
2677
+ // The agent slice bounds the process; no user code runs in this thread.
2678
+ stdout: false,
2679
+ stderr: false
2680
+ });
2681
+ thread.unref();
2682
+ thread.on("error", () => void 0);
2683
+ return () => {
2684
+ clearInterval(beat);
2685
+ void thread.terminate();
2686
+ };
2687
+ }
2688
+
2689
+ // src/worker/worker-io.ts
2690
+ import { randomUUID as randomUUID3 } from "node:crypto";
2691
+ function createWorkerIo(ctx) {
2692
+ const { observer, sessionId } = ctx;
2693
+ const currentSessionAndAccount = async () => {
2694
+ const latest = await readState({ transcripts: [sessionId] });
2695
+ const found = latest.sessions.find((item) => item.id === sessionId);
2696
+ if (!found) throw new Error(`AI session "${sessionId}" was not found`);
2697
+ const nativeAccount = found.accountId ? latest.accounts.find((item) => item.id === found.accountId) : void 0;
2698
+ const account = nativeAccount?.label;
2699
+ return { session: found, account, nativeAccount };
2700
+ };
2701
+ const note = (message) => observer.activity(message);
2702
+ const broadcastQueueChanged = () => {
2703
+ observer.broadcast({ type: "queue-changed" });
2704
+ showEveryWindow();
2705
+ };
2706
+ const showEveryWindow = () => {
2707
+ if (!ctx.turnRunning) return;
2708
+ const controller = ctx.activeController;
2709
+ void currentSessionAndAccount().then(({ session: current, account }) => {
2710
+ if (!ctx.turnRunning || ctx.activeController !== controller) return;
2711
+ observer.render(current, account);
2712
+ }).catch(quiet("worker/worker-io"));
2713
+ };
2714
+ const recordNotifications = async (notes) => {
2715
+ if (notes.length) await recordNotificationText(formatShellNotifications(notes));
2716
+ };
2717
+ const recordNotificationText = async (text, durable = false) => {
2718
+ if (!text) return;
2719
+ const latest = await readState({ transcripts: [sessionId] });
2720
+ const found = latest.sessions.find((item) => item.id === sessionId);
2721
+ if (!found) return;
2722
+ const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
2723
+ enqueueSessionTurn(found, { id: randomUUID3(), text, submittedAt, kind: "notification", ...durable ? { durable: true } : {} }, submittedAt);
2724
+ await writeState(latest);
2725
+ };
2726
+ return { currentSessionAndAccount, note, broadcastQueueChanged, showEveryWindow, recordNotifications, recordNotificationText };
2727
+ }
2728
+
2729
+ // src/worker/idle-decisions.ts
2730
+ function idleDecision(input) {
2731
+ if (input.workRunning) return input.now - (input.workSince ?? input.now) < input.ceilingMs ? "recheck" : "stop-work";
2732
+ return input.workSince !== void 0 ? "fresh-idle" : "exit";
2733
+ }
2734
+ function startsSuccessor(owed, reason) {
2735
+ return owed && reason !== "SIGTERM" && reason !== "SIGINT";
2736
+ }
2737
+ function vendorIdleDecision(input) {
2738
+ if (!input.transportOpen || input.turnRunning) return "none";
2739
+ if (input.idleForMs < input.closeAfterMs) return "later";
2740
+ if (input.backgroundTurn || input.vendorWork || input.pendingRequests > 0) return "later";
2741
+ return "close";
2742
+ }
2743
+
2744
+ // src/worker/worker-idle.ts
2745
+ var IDLE_EXIT_MS = Number(process.env.CLIKCODE_WORKER_IDLE_EXIT_MS) > 0 ? Number(process.env.CLIKCODE_WORKER_IDLE_EXIT_MS) : 30 * 60 * 1e3;
2746
+ var ABANDONED_SHELL_MS = ABANDONED_WORK_MS;
2747
+ var VENDOR_WORK_RECHECK_MS = 30 * 1e3;
2748
+ var VENDOR_IDLE_CLOSE_MS = 15 * 60 * 1e3;
2749
+ var DEFAULT_MAX_WORKERS = 8;
2750
+ var OVER_CAP_REASON = "too many conversations open: the least recently used one let its worker go (the next message starts it again)";
2751
+ var HELD = {
2752
+ turn: "a turn is running",
2753
+ vendorBackground: "vendor background work is running",
2754
+ vendorWork: "the vendor is still running work it started",
2755
+ agents: "background agents are running",
2756
+ notification: "a notification is on its way to the model",
2757
+ wakeup: "a scheduled wakeup is pending",
2758
+ quotaWait: "waiting for a quota reset",
2759
+ heldVendor: "a vendor is still finishing its background work",
2760
+ shell: "a background shell is running",
2761
+ cacheWarm: "keeping the prompt cache warm",
2762
+ queuedTurn: "a queued message is about to be sent"
2763
+ };
2764
+ function createIdleControl(ctx) {
2765
+ const { observer, sessionId, agentSession } = ctx;
2766
+ const heldReason = (scope) => {
2767
+ const retire = scope === "retire";
2768
+ if (ctx.turnRunning || ctx.submitsInFlight > 0 || retire && ctx.draining) return HELD.turn;
2769
+ if (ctx.vendorBackground.busy || ctx.outOfTurn.active) return HELD.vendorBackground;
2770
+ if (!retire && observer.attachedCount > 0) return `${observer.attachedCount} window(s) attached`;
2771
+ if (retire && vendorWorkSince !== void 0) return HELD.vendorWork;
2772
+ if (existingSessionAgents(agentSession)?.running()) return HELD.agents;
2773
+ if (agentSession.notifications.length) return HELD.notification;
2774
+ if (!retire && ctx.queuedUserTurn) return HELD.queuedTurn;
2775
+ if (agentSession.wakeups.size) return HELD.wakeup;
2776
+ if (!retire && ctx.resumeWaiter.pending) return HELD.quotaWait;
2777
+ if (hasHeldVendorProcess(sessionId)) return HELD.heldVendor;
2778
+ if (runningShellCount(agentSession) > 0) return HELD.shell;
2779
+ if (!retire && ctx.keepWarm?.active()) return HELD.cacheWarm;
2780
+ return void 0;
2781
+ };
2782
+ const retireBlocker = () => heldReason("retire");
2783
+ let reapingForRetire = false;
2784
+ const reapStaleForRetire = () => {
2785
+ const held = retireBlocker();
2786
+ const background = held === HELD.vendorBackground || held === HELD.vendorWork || held === HELD.shell;
2787
+ const wanted = ctx.retireWhenIdle || Boolean(ctx.spawnedBuild && currentWorkerBuild() && currentWorkerBuild() !== ctx.spawnedBuild);
2788
+ if (reapingForRetire || !wanted || !background || ctx.turnRunning || ctx.submitsInFlight > 0) return;
2789
+ reapingForRetire = true;
2790
+ void reapPersistentCommands(sessionId, "stale", "replacing for the newer build").then((reaped) => {
2791
+ if (reaped.length) {
2792
+ const timer = setTimeout(() => scheduleIdleExit(), 3e3);
2793
+ timer.unref();
2794
+ }
2795
+ }).catch(quiet("worker/worker-idle")).finally(() => {
2796
+ reapingForRetire = false;
2797
+ });
2798
+ };
2799
+ const leaveIfStaleBuild = () => {
2800
+ if (!ctx.spawnedBuild || observer.attachedCount > 0) return;
2801
+ if (retireBlocker()) {
2802
+ reapStaleForRetire();
2803
+ return;
2804
+ }
2805
+ const live = currentWorkerBuild();
2806
+ if (!live || live === ctx.spawnedBuild) return;
2807
+ retireIfFree();
2808
+ };
2809
+ let retireCheck;
2810
+ let quietTimer;
2811
+ const quietLeft = () => Math.max(0, observer.lastActivityAt + RETIRE_QUIET_MS - Date.now());
2812
+ const retireIfFree = () => {
2813
+ const left = quietLeft();
2814
+ if (left > 0) {
2815
+ noteIdle("held: replacing for the newer build once it is quiet");
2816
+ if (!quietTimer) {
2817
+ quietTimer = setTimeout(() => {
2818
+ quietTimer = void 0;
2819
+ if (ctx.retireWhenIdle) retireIfFree();
2820
+ else leaveIfStaleBuild();
2821
+ }, left);
2822
+ quietTimer.unref();
2823
+ }
2824
+ return;
2825
+ }
2826
+ retireCheck ??= (async () => {
2827
+ const running = await persistentWorkRunning(sessionId);
2828
+ if (retireBlocker() || quietLeft() > 0) return;
2829
+ if (running) {
2830
+ noteIdle("held: retiring once the vendor's work ends");
2831
+ return;
2832
+ }
2833
+ void ctx.shutdown("replaced by a newer ClikCode build");
2834
+ })().catch(quiet("worker/worker-idle")).finally(() => {
2835
+ retireCheck = void 0;
2836
+ });
2837
+ };
2838
+ let awaitingHeldVendor = false;
2839
+ let idleState = "";
2840
+ const noteIdle = (state) => {
2841
+ if (state === idleState) return;
2842
+ idleState = state;
2843
+ lifecycle("worker.idle", { state });
2844
+ };
2845
+ const scheduleIdleExit = () => {
2846
+ if (ctx.idleTimer) clearTimeout(ctx.idleTimer);
2847
+ ctx.idleTimer = void 0;
2848
+ const held = heldReason("idle");
2849
+ noteIdle(held ? `held: ${held}` : `idle: exits in ${Math.round(IDLE_EXIT_MS / 1e3)}s`);
2850
+ if (ctx.retireWhenIdle && !retireBlocker()) retireIfFree();
2851
+ else if (ctx.retireWhenIdle) reapStaleForRetire();
2852
+ else leaveIfStaleBuild();
2853
+ if (held === HELD.heldVendor) {
2854
+ if (!awaitingHeldVendor) {
2855
+ awaitingHeldVendor = true;
2856
+ void whenHeldVendorGone(sessionId).then(() => {
2857
+ awaitingHeldVendor = false;
2858
+ scheduleIdleExit();
2859
+ });
2860
+ }
2861
+ return;
2862
+ }
2863
+ if (held === HELD.shell) {
2864
+ const oldest = Math.min(...[...agentSession.shells.values()].filter((shell) => shell.status === "running").map((shell) => shell.startedAt));
2865
+ ctx.idleTimer = setTimeout(stopAbandonedShells, Math.max(0, oldest + ABANDONED_SHELL_MS - Date.now()));
2866
+ ctx.idleTimer.unref();
2867
+ return;
2868
+ }
2869
+ if (held) return;
2870
+ ctx.idleTimer = setTimeout(() => {
2871
+ void idleReached();
2872
+ }, IDLE_EXIT_MS);
2873
+ ctx.idleTimer.unref();
2874
+ };
2875
+ let vendorUsedAt = Date.now();
2876
+ let vendorIdleTimer;
2877
+ const armVendorIdle = (delayMs) => {
2878
+ if (vendorIdleTimer) clearTimeout(vendorIdleTimer);
2879
+ vendorIdleTimer = setTimeout(() => {
2880
+ vendorIdleTimer = void 0;
2881
+ void vendorIdleReached();
2882
+ }, delayMs);
2883
+ vendorIdleTimer.unref();
2884
+ };
2885
+ const vendorUsed = () => {
2886
+ vendorUsedAt = Date.now();
2887
+ armVendorIdle(VENDOR_IDLE_CLOSE_MS);
2888
+ };
2889
+ const vendorIdleReached = async () => {
2890
+ const work = await persistentWorkRunning(sessionId);
2891
+ const idleForMs = Date.now() - vendorUsedAt;
2892
+ const decision = vendorIdleDecision({
2893
+ transportOpen: hasPersistentTransport(sessionId),
2894
+ turnRunning: ctx.turnRunning || ctx.draining,
2895
+ backgroundTurn: ctx.vendorBackground.busy,
2896
+ vendorWork: work || hasHeldVendorProcess(sessionId),
2897
+ pendingRequests: observer.pendingRequestCount,
2898
+ idleForMs,
2899
+ closeAfterMs: VENDOR_IDLE_CLOSE_MS
2900
+ });
2901
+ if (decision === "none") return;
2902
+ if (decision === "later") {
2903
+ armVendorIdle(idleForMs < VENDOR_IDLE_CLOSE_MS ? VENDOR_IDLE_CLOSE_MS - idleForMs : VENDOR_WORK_RECHECK_MS);
2904
+ return;
2905
+ }
2906
+ lifecycle("vendor.idle-close", { idleMs: idleForMs, clients: observer.attachedCount });
2907
+ await closePersistentTransport(sessionId);
2908
+ };
2909
+ let vendorWorkSince;
2910
+ const idleReached = async () => {
2911
+ ctx.idleTimer = void 0;
2912
+ if (ctx.homeGone()) {
2913
+ void ctx.shutdown("its ClikCode home was removed");
2914
+ return;
2915
+ }
2916
+ const running = await persistentWorkRunning(sessionId);
2917
+ if (ctx.idleTimer || ctx.turnRunning || ctx.draining || observer.attachedCount > 0 || ctx.resumeWaiter.pending) return;
2918
+ const decision = idleDecision({ workRunning: running, workSince: vendorWorkSince, now: Date.now(), ceilingMs: ABANDONED_SHELL_MS });
2919
+ noteIdle(decision === "recheck" ? "held: the vendor is still running work it started" : `idle reached: ${decision}`);
2920
+ if (decision === "recheck") {
2921
+ vendorWorkSince ??= Date.now();
2922
+ ctx.idleTimer = setTimeout(() => {
2923
+ void idleReached();
2924
+ }, VENDOR_WORK_RECHECK_MS);
2925
+ ctx.idleTimer.unref();
2926
+ return;
2927
+ }
2928
+ vendorWorkSince = void 0;
2929
+ if (decision === "stop-work") {
2930
+ void ctx.shutdown("the work was still running 24 hours after it started, with no ClikCode window open");
2931
+ return;
2932
+ }
2933
+ if (decision === "fresh-idle") {
2934
+ scheduleIdleExit();
2935
+ return;
2936
+ }
2937
+ void ctx.shutdown("idle timeout");
2938
+ };
2939
+ const stopAbandonedShells = () => {
2940
+ const cutoff = Date.now() - ABANDONED_SHELL_MS;
2941
+ for (const shell of agentSession.shells.values()) {
2942
+ if (shell.status === "running" && shell.startedAt <= cutoff) stopBackgroundShell(shell, "still running 24 hours after it started, with no ClikCode window open");
2943
+ }
2944
+ scheduleIdleExit();
2945
+ };
2946
+ const maxWorkers = () => {
2947
+ const configured = Number(process.env.CLIKCODE_MAX_WORKERS) || Number(ctx.config.get("maxWorkers"));
2948
+ return Number.isInteger(configured) && configured > 0 ? configured : DEFAULT_MAX_WORKERS;
2949
+ };
2950
+ let capCheck;
2951
+ const leaveIfOverCap = () => {
2952
+ capCheck ??= (async () => {
2953
+ const cap = maxWorkers();
2954
+ if (ctx.shuttingDown || await workerRecordCount() <= cap) return;
2955
+ if (retireBlocker() || heldReason("idle") === HELD.queuedTurn || ctx.resumeWaiter.pending || quietLeft() > 0) return;
2956
+ if ([...ctx.connections.values()].some((connection) => connection.attached && !connection.reattaches)) return;
2957
+ const records = await liveWorkerRecords();
2958
+ if (records.length <= cap) return;
2959
+ const idle = records.filter((record) => !record.runningTurn && !record.background && !record.awaitingApproval);
2960
+ const used = await Promise.all(idle.map(async (record) => ({ record, at: await workerRecordWrittenAt(record.sessionId) ?? 0 })));
2961
+ used.sort((left, right) => left.at - right.at);
2962
+ const leaving = used.slice(0, records.length - cap).map((entry) => entry.record.sessionId);
2963
+ if (!leaving.includes(sessionId)) return;
2964
+ if (retireBlocker() || quietLeft() > 0) return;
2965
+ lifecycle("worker.over-cap", { workers: records.length, cap, clients: observer.attachedCount });
2966
+ void ctx.shutdown(OVER_CAP_REASON);
2967
+ })().catch(quiet("worker/worker-idle")).finally(() => {
2968
+ capCheck = void 0;
2969
+ });
2970
+ return capCheck;
2971
+ };
2972
+ return { heldReason, retireBlocker, quietLeft, retireIfFree, leaveIfStaleBuild, leaveIfOverCap, noteIdle, scheduleIdleExit, vendorUsed };
2973
+ }
2974
+
2975
+ // src/worker/worker-queue.ts
2976
+ import { randomUUID as randomUUID6 } from "node:crypto";
2977
+
2978
+ // src/worker/consume-queued.ts
2979
+ var fileIo = { readState: (sessionId) => readState({ transcripts: [sessionId] }), writeState: (state) => writeState(state) };
2980
+ async function consumeQueuedTurn(sessionId, queuedTurnId, io = fileIo, attempts = 3, backoffMs = 100) {
2981
+ let lastError;
2982
+ for (let attempt = 1; attempt <= attempts; attempt++) {
2983
+ try {
2984
+ const state = await io.readState(sessionId);
2985
+ const found = state.sessions.find((item) => item.id === sessionId);
2986
+ if (!found || !consumeSessionTurn(found, queuedTurnId)) return "gone";
2987
+ await io.writeState(state);
2988
+ return "consumed";
2989
+ } catch (error) {
2990
+ lastError = error;
2991
+ if (attempt < attempts) await sleep(backoffMs * attempt);
2992
+ }
2993
+ }
2994
+ throw lastError;
2995
+ }
2996
+
2997
+ // src/worker/worker-turn.ts
2998
+ import { randomUUID as randomUUID5 } from "node:crypto";
2999
+
3000
+ // src/turn/live-input.ts
3001
+ import { randomUUID as randomUUID4 } from "node:crypto";
3002
+ var LiveTurnInputBroker = class {
3003
+ ledger;
3004
+ ledgerReady;
3005
+ resolveLedgerReady;
3006
+ port;
3007
+ /** Settles when the port goes away, so an offer nobody answers cannot hold the broker. */
3008
+ portGone = new Promise(() => void 0);
3009
+ resolvePortGone;
3010
+ /** One thing at a time: a submit, a delivery pass, a take-back's check. */
3011
+ tail = Promise.resolve();
3012
+ /** The message being offered to the turn now: too late to take back. */
3013
+ delivering;
3014
+ delivered = /* @__PURE__ */ new Set();
3015
+ afterDelivery;
3016
+ steerableChanged;
3017
+ constructor() {
3018
+ this.ledgerReady = new Promise((resolve) => {
3019
+ this.resolveLedgerReady = resolve;
3020
+ });
3021
+ }
3022
+ bindLedger(ledger) {
3023
+ this.ledger = ledger;
3024
+ this.resolveLedgerReady();
3025
+ }
3026
+ /** Told when a waiting message later goes into the turn (not on the submit that queued it), so every
3027
+ * window can redraw the queue and the turn. */
3028
+ onLaterDelivery(handler) {
3029
+ this.afterDelivery = handler;
3030
+ }
3031
+ /** Told when the turn gains or loses a way to take a message in, so every window knows whether Enter again can. */
3032
+ onSteerableChange(handler) {
3033
+ this.steerableChanged = handler;
3034
+ }
3035
+ /** The turn's way of taking a message in, or none (the turn ended, or its agent has none). */
3036
+ setSteerPort(port) {
3037
+ this.resolvePortGone?.();
3038
+ this.port = port;
3039
+ try {
3040
+ this.steerableChanged?.(port !== void 0);
3041
+ } catch {
3042
+ }
3043
+ if (!port) return;
3044
+ this.portGone = new Promise((resolve) => {
3045
+ this.resolvePortGone = () => resolve("gone");
3046
+ });
3047
+ port.onWindow = () => {
3048
+ void this.run(() => this.deliver(true));
3049
+ };
3050
+ void this.run(() => this.deliver(true));
3051
+ }
3052
+ /** Whether the running turn has a way to take a message in. */
3053
+ get steerable() {
3054
+ return this.port !== void 0;
3055
+ }
3056
+ /** A note from ClikCode itself for the model only (turn/resource-notes.ts): offered like a message, never
3057
+ * journaled, queued or shown. True once it is in the turn; false when it is not a moment it can be or
3058
+ * nothing running could take it, and the caller keeps it for the next turn. */
3059
+ async steerNote(text) {
3060
+ const submission = { id: randomUUID4(), text, submittedAt: (/* @__PURE__ */ new Date()).toISOString(), kind: "note" };
3061
+ return this.run(async () => this.port ? this.offer(this.port, submission) : false);
3062
+ }
3063
+ /** Every pass that was running has finished. Awaited before the turn's journal is completed, so a message
3064
+ * is either in this turn or still queued for the next. */
3065
+ async settled() {
3066
+ await this.tail.catch(quiet("turn/live-input"));
3067
+ }
3068
+ /** Release submissions if setup failed before the ledger could bind. The UI restores their text instead of waiting forever. */
3069
+ close() {
3070
+ this.setSteerPort(void 0);
3071
+ if (!this.ledger) {
3072
+ this.ledger = {
3073
+ queue: () => Promise.reject(new Error("turn ended before live input was ready")),
3074
+ nextSteer: () => void 0,
3075
+ oldestMessage: () => void 0,
3076
+ delivered: () => Promise.reject(new Error("turn ended before live input was ready")),
3077
+ mark: () => Promise.resolve(false),
3078
+ remove: () => Promise.resolve(false)
3079
+ };
3080
+ this.resolveLedgerReady();
3081
+ }
3082
+ }
3083
+ /** The user is taking a waiting message back. `running`: it is being put into the turn this moment, so it stays. */
3084
+ async takeBack(id) {
3085
+ if (this.delivering === id) return "running";
3086
+ await this.ledgerReady;
3087
+ return await this.ledger.remove(id) ? "removed" : "gone";
3088
+ }
3089
+ /** Enter again, nothing typed: the oldest message waiting goes into the turn now if the turn can take it now.
3090
+ * It is never forced: a call in the way is waited for, not cut. */
3091
+ async sendNow() {
3092
+ await this.ledgerReady;
3093
+ return this.run(async () => {
3094
+ const next = this.ledger.oldestMessage();
3095
+ if (!next) return void 0;
3096
+ if (!this.port) return { submission: next, steered: false };
3097
+ if (!await this.ledger.mark(next.id)) return { submission: next, steered: false };
3098
+ await this.deliver(false);
3099
+ return { submission: next, steered: this.delivered.has(next.id) };
3100
+ });
3101
+ }
3102
+ /** `id` is the one the composer already shows the message under, so the saved copy -- a queued turn, or a
3103
+ * steer recorded on the turn -- is matched to that row by identity instead of by its words.
3104
+ * `steer`: into the running turn when it can take it, else at its next opening; false waits for the turn to end. */
3105
+ async submit(raw, id = randomUUID4(), options) {
3106
+ const text = raw.trim();
3107
+ if (!text) throw new Error("message is empty");
3108
+ const submission = { id, text, submittedAt: (/* @__PURE__ */ new Date()).toISOString() };
3109
+ await this.ledgerReady;
3110
+ return this.run(async () => {
3111
+ const ledger = this.ledger;
3112
+ if (options.steer && this.port && !ledger.nextSteer()) {
3113
+ this.delivering = id;
3114
+ let taken = false;
3115
+ try {
3116
+ taken = await this.offer(this.port, submission);
3117
+ } finally {
3118
+ this.delivering = void 0;
3119
+ }
3120
+ if (taken) {
3121
+ try {
3122
+ await ledger.delivered(submission);
3123
+ this.delivered.add(id);
3124
+ return { disposition: "steered", submission };
3125
+ } catch {
3126
+ }
3127
+ }
3128
+ }
3129
+ await ledger.queue(submission, options.steer);
3130
+ if (options.steer) await this.deliver(false);
3131
+ if (this.delivered.has(id)) return { disposition: "steered", submission };
3132
+ return { disposition: "queued", submission };
3133
+ });
3134
+ }
3135
+ run(job) {
3136
+ const next = this.tail.then(job, job);
3137
+ this.tail = next.catch(quiet("turn/live-input"));
3138
+ return next;
3139
+ }
3140
+ /** Offers one message; a refusal, an error or the port going away all leave it where it is. */
3141
+ async offer(port, submission) {
3142
+ try {
3143
+ const gone = this.portGone.then(() => new Promise((resolve) => setImmediate(() => resolve("gone"))));
3144
+ const taken = await Promise.race([port.offer(submission.text, submission), gone]);
3145
+ return taken === true;
3146
+ } catch {
3147
+ return false;
3148
+ }
3149
+ }
3150
+ /** Puts waiting messages into the turn, oldest first, until one is refused. `later`: not the submit that queued them. */
3151
+ async deliver(later) {
3152
+ const ledger = this.ledger;
3153
+ const port = this.port;
3154
+ if (!ledger || !port) return;
3155
+ let any = false;
3156
+ for (; ; ) {
3157
+ const next = ledger.nextSteer();
3158
+ if (!next) break;
3159
+ this.delivering = next.id;
3160
+ let taken = false;
3161
+ try {
3162
+ taken = await this.offer(port, next);
3163
+ } finally {
3164
+ this.delivering = void 0;
3165
+ }
3166
+ if (!taken) break;
3167
+ try {
3168
+ await ledger.delivered(next);
3169
+ } catch (error) {
3170
+ quiet("turn/live-input")(error);
3171
+ break;
3172
+ }
3173
+ this.delivered.add(next.id);
3174
+ any = true;
3175
+ }
3176
+ if (later && any) try {
3177
+ this.afterDelivery?.();
3178
+ } catch {
3179
+ }
3180
+ }
3181
+ };
3182
+
3183
+ // src/worker/worker-turn.ts
3184
+ var CLOSE_WAIT_MS = 2e3;
3185
+ async function pendingSteerCount(sessionId) {
3186
+ const state = await readState({ transcripts: [sessionId] }).catch(quiet("worker/worker-turn"));
3187
+ return state?.sessions.find((entry) => entry.id === sessionId)?.pendingTurn?.steers?.length ?? 0;
3188
+ }
3189
+ async function takeUnsentHeldSteers(sessionId) {
3190
+ const state = await readState({ transcripts: [sessionId] }).catch(quiet("worker/worker-turn"));
3191
+ const session = state?.sessions.find((entry) => entry.id === sessionId);
3192
+ if (!state || !session) return [];
3193
+ const held = (session.queuedTurns ?? []).filter((entry) => entry.steer === true && entry.kind !== "command" && entry.kind !== "notification");
3194
+ if (!held.length) return [];
3195
+ for (const entry of held) consumeSessionTurn(session, entry.id);
3196
+ await writeState(state);
3197
+ return held.map((entry) => entry.text);
3198
+ }
3199
+ function markTurnRunning(ctx) {
3200
+ ctx.turnRunning = true;
3201
+ ctx.turnStartedAt = (/* @__PURE__ */ new Date()).toISOString();
3202
+ void ctx.onTurnRunningChange?.(ctx.turnStartedAt);
3203
+ }
3204
+ function releaseTurnControls(ctx) {
3205
+ ctx.activeController = void 0;
3206
+ ctx.activeLiveInput = void 0;
3207
+ ctx.activeSubmissions = void 0;
3208
+ ctx.activeRestoreDraft = void 0;
3209
+ ctx.stopAnnounced = false;
3210
+ ctx.turnWorkDone = false;
3211
+ if (ctx.stopEscalation) clearTimeout(ctx.stopEscalation);
3212
+ ctx.stopEscalation = void 0;
3213
+ ctx.forceStop = void 0;
3214
+ }
3215
+ function markTurnOver(ctx) {
3216
+ ctx.turnRunning = false;
3217
+ ctx.turnStartedAt = void 0;
3218
+ void ctx.onTurnRunningChange?.(void 0);
3219
+ }
3220
+ function createTurnRunner(ctx) {
3221
+ const { observer, sessionId, config, agentSession } = ctx;
3222
+ const { currentSessionAndAccount } = ctx.io;
3223
+ const settleCancelledTurn = async (command) => {
3224
+ const steered = await pendingSteerCount(sessionId) > 0;
3225
+ const answered = observer.turnHasAnswer || steered;
3226
+ const heldBack = await takeUnsentHeldSteers(sessionId).catch(() => []);
3227
+ const restoreTo = answered ? void 0 : ctx.activeRestoreDraft;
3228
+ if (answered) await preserveInterruptedTurn(sessionId, command.text, observer.liveResponseText, true);
3229
+ else await discardInterruptedTurn(sessionId, command.text);
3230
+ const target = ctx.activeRestoreDraft;
3231
+ const back = [...restoreTo ? [command.text] : [], ...heldBack].join("\n");
3232
+ if (back) {
3233
+ if (target && !target.destroyed) sendEvent(target, { type: "restore-draft", text: back });
3234
+ else if (heldBack.length) observer.broadcast({ type: "restore-draft", text: heldBack.join("\n") });
3235
+ }
3236
+ };
3237
+ const settleFailedTurn = async (command, error, resumed) => {
3238
+ const message = error instanceof Error ? error.message : String(error);
3239
+ const heldBack = await takeUnsentHeldSteers(sessionId).catch(() => []);
3240
+ if (heldBack.length) observer.broadcast({ type: "restore-draft", text: heldBack.join("\n") });
3241
+ await markFailedTurn(sessionId, command.text).catch((saveError) => {
3242
+ lifecycle("worker.turn.failed-journal-error", { message: saveError instanceof Error ? saveError.message : String(saveError) });
3243
+ });
3244
+ const said = !isUsageExhaustedMessage(message);
3245
+ if (said && isCompactRequest(command.text)) observer.activity(message === NOTHING_TO_COMPACT ? message : compactFailedLine(failureText(message)));
3246
+ else if (said) observer.activity(source_default.red(`Error: ${failureText(message)}`));
3247
+ observer.broadcast({ type: "turn-error", message, ...said ? { said: true } : {} });
3248
+ if (resumed && isUsageExhaustedMessage(message)) diagnostic("worker.resume-still-exhausted", message);
3249
+ if (command.queuedTurnId) {
3250
+ await consumeQueuedTurn(sessionId, command.queuedTurnId).catch((consumeError) => {
3251
+ ctx.stalledQueuedTurnId = command.queuedTurnId;
3252
+ diagnostic("worker.queue-stalled", consumeError instanceof Error ? consumeError.message : String(consumeError));
3253
+ });
3254
+ }
3255
+ };
3256
+ const compactIfDue = async (turnStarted) => {
3257
+ const state = await readState({ transcripts: [sessionId] });
3258
+ const session = state.sessions.find((item) => item.id === sessionId);
3259
+ const harness = session && !isClikCodeAgent(session) && session.nativeHarness ? localHarnessForCommand(session.nativeHarness) : void 0;
3260
+ if (!session || !harness) return false;
3261
+ if (noteContextAfterCompaction(session)) await writeState(state);
3262
+ if (sessionCompactionMechanism(session, harness).kind === "vendor-threshold") return false;
3263
+ if (!hasThreadToCompact(session) || !shouldCompact(session, compactAt(state.globalSettings), turnStarted)) return false;
3264
+ if (ctx.turnRunning || agentSession.notifications.length || ctx.vendorBackground.busy || ctx.outOfTurn.active || session.queuedTurns?.some((entry) => entry.kind === "notification") || await persistentWorkRunning(sessionId)) return false;
3265
+ lifecycle("worker.compact", { context: session.lastUsage?.contextUsed, threshold: compactAt(state.globalSettings) });
3266
+ return ctx.queue.startTurn({ type: "submit", text: COMPACT_REQUEST, echo: false });
3267
+ };
3268
+ const finalizeTurn = async (command, turnId, turnStarted, turnOutcome, lastHarness, liveInput, submissions) => {
3269
+ liveInput.close();
3270
+ releaseTurnControls(ctx);
3271
+ await Promise.allSettled([...submissions]);
3272
+ await ctx.vendorBackground.saveSuperseded().catch(quiet("worker/worker-turn"));
3273
+ const ended = await currentSessionAndAccount().catch(quiet("worker/worker-turn"));
3274
+ markTurnOver(ctx);
3275
+ ctx.lastTurnStopped = turnOutcome === "cancelled";
3276
+ observer.endTurn(ended?.session, ended?.account, turnOutcome === "cancelled");
3277
+ lifecycle("worker.turn.end", { outcome: turnOutcome, ms: Date.now() - turnStarted });
3278
+ void ctx.keepWarm?.turnEnded(turnOutcome === "completed" ? lastHarness : void 0).catch(quiet("worker/worker-turn"));
3279
+ endTurnClock(turnId);
3280
+ ctx.idle.vendorUsed();
3281
+ ctx.activeQueuedTurnId = void 0;
3282
+ ctx.vendorBackground.userTurnEnded();
3283
+ if (observer.attachedCount === 0) void releaseMcp();
3284
+ if (agentSession.notifications.length) void ctx.queue.deliverNotifications();
3285
+ else {
3286
+ const next = async () => {
3287
+ if (turnOutcome === "completed" && !isCompactRequest(command.text) && await compactIfDue(turnStarted)) return;
3288
+ await ctx.queue.drainQueue();
3289
+ };
3290
+ void next().catch(ctx.queue.reportDrainFailure).finally(() => {
3291
+ ctx.idle.scheduleIdleExit();
3292
+ });
3293
+ }
3294
+ ctx.idle.scheduleIdleExit();
3295
+ void ctx.resumeWaiter.check();
3296
+ };
3297
+ return async (command) => {
3298
+ const turnStarted = Date.now();
3299
+ let turnOutcome = "completed";
3300
+ lifecycle("worker.turn.start", { queued: Boolean(command.queuedTurnId), clients: observer.attachedCount });
3301
+ const turnId = command.turnId ?? randomUUID5();
3302
+ beginTurnClock({ turnId, ...command.submittedAt !== void 0 ? { startedAt: command.submittedAt } : {} });
3303
+ if (command.submittedAt === void 0) markTurn("submit");
3304
+ markTurn("accepted", { queued: Boolean(command.queuedTurnId) });
3305
+ const resumed = ctx.resumingTurn;
3306
+ ctx.resumingTurn = false;
3307
+ if (ctx.idleTimer) clearTimeout(ctx.idleTimer);
3308
+ ctx.idleTimer = void 0;
3309
+ const controller = new AbortController();
3310
+ const liveInput = new LiveTurnInputBroker();
3311
+ liveInput.onSteerableChange((steerable) => observer.setSteerable(steerable));
3312
+ liveInput.onLaterDelivery(() => {
3313
+ ctx.io.broadcastQueueChanged();
3314
+ ctx.io.showEveryWindow();
3315
+ });
3316
+ const submissions = /* @__PURE__ */ new Set();
3317
+ ctx.activeController = controller;
3318
+ ctx.activeLiveInput = liveInput;
3319
+ ctx.activeSubmissions = submissions;
3320
+ ctx.turnWorkDone = false;
3321
+ let checkpoint;
3322
+ let closing;
3323
+ const forced = new Promise((_, reject) => {
3324
+ ctx.forceStop = () => {
3325
+ closing ??= checkpoint?.close().catch(quiet("worker/worker-turn")) ?? Promise.resolve();
3326
+ reject(turnCancelledError());
3327
+ };
3328
+ });
3329
+ forced.catch(quiet("worker/worker-turn"));
3330
+ const earlyStop = ctx.pendingCancel;
3331
+ ctx.pendingCancel = void 0;
3332
+ if (earlyStop) {
3333
+ if (earlyStop.restoreDraft) ctx.activeRestoreDraft = earlyStop.restoreDraft;
3334
+ controller.abort();
3335
+ }
3336
+ ctx.keepWarm?.stop();
3337
+ let lastHarness;
3338
+ const outOfTurnStarted = performance.now();
3339
+ if (ctx.outOfTurn.active) await ctx.outOfTurn.settle();
3340
+ const outOfTurnSettleMs = Math.round(performance.now() - outOfTurnStarted);
3341
+ const compacting = isCompactRequest(command.text);
3342
+ observer.startTurn(compacting ? COMPACTING : "working", compacting ? void 0 : command.text);
3343
+ try {
3344
+ const vendorBackgroundStarted = performance.now();
3345
+ await ctx.vendorBackground.settled();
3346
+ const vendorBackgroundSettleMs = Math.round(performance.now() - vendorBackgroundStarted);
3347
+ const warmStarted = performance.now();
3348
+ if (ctx.warming) await ctx.warming;
3349
+ const warmWaitMs = Math.round(performance.now() - warmStarted);
3350
+ if (controller.signal.aborted) throw turnCancelledError();
3351
+ markTurn("worker-ready", { outOfTurnSettleMs, vendorBackgroundSettleMs, warmWaitMs });
3352
+ const running = runSessionTurn(config, sessionId, command.text, controller.signal, {
3353
+ onWorkFinished: () => {
3354
+ ctx.turnWorkDone = true;
3355
+ },
3356
+ onCompletedHarness: (harness) => {
3357
+ lastHarness = harness;
3358
+ },
3359
+ onCheckpoint: (opened) => {
3360
+ checkpoint = opened;
3361
+ if (closing) void opened.close().catch(quiet("worker/worker-turn"));
3362
+ },
3363
+ persistentTransports: true,
3364
+ prompter: observer,
3365
+ liveInput,
3366
+ liveSettings: ctx.liveSettings,
3367
+ ...command.queuedTurnId ? { queuedTurnId: command.queuedTurnId } : {}
3368
+ });
3369
+ running.catch(quiet("worker/worker-turn"));
3370
+ await Promise.race([running, forced]);
3371
+ } catch (error) {
3372
+ const cancelled = isTurnCancelled(error);
3373
+ turnOutcome = cancelled ? "cancelled" : `error: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`;
3374
+ try {
3375
+ if (closing) await Promise.race([closing, new Promise((resolveWait) => {
3376
+ setTimeout(resolveWait, CLOSE_WAIT_MS).unref();
3377
+ })]);
3378
+ if (cancelled) await settleCancelledTurn(command);
3379
+ else await settleFailedTurn(command, error, resumed);
3380
+ } catch (settleError) {
3381
+ observer.broadcast({ type: "turn-error", message: settleError instanceof Error ? settleError.message : String(settleError) });
3382
+ }
3383
+ } finally {
3384
+ await finalizeTurn(command, turnId, turnStarted, turnOutcome, lastHarness, liveInput, submissions);
3385
+ }
3386
+ };
3387
+ }
3388
+
3389
+ // src/worker/worker-queue.ts
3390
+ function createWorkerQueue(ctx) {
3391
+ const { observer, sessionId, agentSession } = ctx;
3392
+ const { currentSessionAndAccount, broadcastQueueChanged, recordNotifications } = ctx.io;
3393
+ const startedAt = Date.now();
3394
+ const deliverNotifications = async () => {
3395
+ try {
3396
+ if (!ctx.turnRunning && agentSession.notifications.length) {
3397
+ await recordNotifications(takeShellNotifications(agentSession));
3398
+ broadcastQueueChanged();
3399
+ await drainQueue();
3400
+ }
3401
+ } catch (error) {
3402
+ diagnostic("worker.notification-undelivered", error instanceof Error ? error.message : String(error));
3403
+ } finally {
3404
+ ctx.idle.scheduleIdleExit();
3405
+ }
3406
+ };
3407
+ const startTurn = (command) => {
3408
+ if (ctx.turnRunning || ctx.shuttingDown) return false;
3409
+ markTurnRunning(ctx);
3410
+ ctx.lastTurnStopped = false;
3411
+ ctx.activeQueuedTurnId = command.queuedTurnId;
3412
+ void ctx.runTurn(command).catch((error) => {
3413
+ releaseTurnControls(ctx);
3414
+ markTurnOver(ctx);
3415
+ ctx.activeQueuedTurnId = void 0;
3416
+ ctx.pendingCancel = void 0;
3417
+ observer.broadcast({ type: "turn-error", message: error instanceof Error ? error.message : String(error) });
3418
+ observer.endTurn();
3419
+ ctx.idle.scheduleIdleExit();
3420
+ });
3421
+ return true;
3422
+ };
3423
+ const reportDrainFailure = (error) => {
3424
+ diagnostic("worker.queue-unreadable", error instanceof Error ? error.message : String(error));
3425
+ };
3426
+ const drainQueue = async () => {
3427
+ if (ctx.turnRunning || ctx.draining) return;
3428
+ ctx.draining = true;
3429
+ try {
3430
+ let { session: current } = await currentSessionAndAccount();
3431
+ while (current.queuedTurns?.[0]?.kind === "notification" && !current.queuedTurns[0].durable && Date.parse(current.queuedTurns[0].submittedAt) < startedAt) {
3432
+ if (await consumeQueuedTurn(sessionId, current.queuedTurns[0].id) === "gone") break;
3433
+ current = (await currentSessionAndAccount()).session;
3434
+ }
3435
+ const head = current.queuedTurns?.[0];
3436
+ ctx.queuedUserTurn = false;
3437
+ if (!head || head.id === ctx.stalledQueuedTurnId) return;
3438
+ if (head.kind !== "notification") {
3439
+ const message = head.kind === void 0;
3440
+ const runnable = message && !ctx.lastTurnStopped && !turnNeedsWindow(current, (await readState({ transcripts: [] })).accounts);
3441
+ ctx.queuedUserTurn = runnable;
3442
+ if (!runnable) {
3443
+ broadcastQueueChanged();
3444
+ return;
3445
+ }
3446
+ }
3447
+ if (startTurn({ type: "submit", text: head.text, echo: true, queuedTurnId: head.id })) observer.noteTurnSender(void 0);
3448
+ ctx.queuedUserTurn = false;
3449
+ } finally {
3450
+ ctx.draining = false;
3451
+ }
3452
+ };
3453
+ const handleSubmit = async (socket, command) => {
3454
+ const follow = () => {
3455
+ void currentSessionAndAccount().then(({ session: current, account }) => observer.snapshotFor(socket, current, account), () => void 0);
3456
+ };
3457
+ if (command.queuedTurnId) {
3458
+ if (command.queuedTurnId === ctx.stalledQueuedTurnId) {
3459
+ sendEvent(socket, { type: "turn-error", message: "This queued message already failed and could not be taken out of the queue; remove it to continue." });
3460
+ sendEvent(socket, { type: "waiting-stop" });
3461
+ return;
3462
+ }
3463
+ if (ctx.turnRunning && ctx.activeQueuedTurnId === command.queuedTurnId) {
3464
+ follow();
3465
+ return;
3466
+ }
3467
+ const { session: current, account } = await currentSessionAndAccount();
3468
+ if (ctx.turnRunning && ctx.activeQueuedTurnId === command.queuedTurnId) {
3469
+ follow();
3470
+ return;
3471
+ }
3472
+ if (!current.queuedTurns?.some((item) => item.id === command.queuedTurnId)) {
3473
+ sendEvent(socket, { type: "snapshot", session: current, ...account ? { account } : {} });
3474
+ sendEvent(socket, { type: "waiting-stop" });
3475
+ return;
3476
+ }
3477
+ }
3478
+ if (!command.queuedTurnId) await ctx.resumeWaiter.cancel();
3479
+ if (ctx.shuttingDown) throw new Error("This conversation's worker is being replaced.");
3480
+ if (startTurn(command)) {
3481
+ observer.noteTurnSender(socket);
3482
+ return;
3483
+ }
3484
+ let queuedTurnId = command.queuedTurnId;
3485
+ if (!queuedTurnId) {
3486
+ queuedTurnId = randomUUID6();
3487
+ const latest = await readState({ transcripts: [sessionId] });
3488
+ const found = latest.sessions.find((item) => item.id === sessionId);
3489
+ if (!found) throw new Error(`AI session "${sessionId}" was not found`);
3490
+ const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
3491
+ enqueueSessionTurn(found, { id: queuedTurnId, text: command.text.trim(), submittedAt }, submittedAt);
3492
+ await writeState(latest);
3493
+ }
3494
+ sendEvent(socket, { type: "submit-queued", queuedTurnId });
3495
+ broadcastQueueChanged();
3496
+ follow();
3497
+ };
3498
+ return { startTurn, drainQueue, handleSubmit, deliverNotifications, reportDrainFailure };
3499
+ }
3500
+
3501
+ // src/agent/computer/login-manager.ts
3502
+ var DONE = "Done";
3503
+ async function manageSavedLogins(observer, stateDir, signal) {
3504
+ let removed = 0;
3505
+ for (; ; ) {
3506
+ const logins = await allSavedLogins(stateDir);
3507
+ if (!logins.length) return removed ? `Removed ${removed} saved login${removed === 1 ? "" : "s"}. None remain.` : "No saved logins.";
3508
+ const labels = uniqueLabels(logins.map((login2) => `${login2.site} \xB7 ${login2.label}`));
3509
+ const picked = await askPrivateChoice(observer, "Saved logins", "Choose a login to remove", [...labels, DONE], signal);
3510
+ const login = picked && picked !== DONE ? logins[labels.indexOf(picked)] : void 0;
3511
+ if (!login) break;
3512
+ const sure = await askPrivateChoice(observer, "Saved logins", "Remove the selected login?", ["Remove", "Keep"], signal);
3513
+ if (sure === "Remove" && await removeSavedLogin(stateDir, login.id)) removed++;
3514
+ }
3515
+ return removed ? `Removed ${removed} saved login${removed === 1 ? "" : "s"}.` : "No saved logins were removed.";
3516
+ }
3517
+
3518
+ // src/worker/computer-tool-calls.ts
3519
+ var KEEP_MS = 10 * 6e4;
3520
+ var ToolCalls = class {
3521
+ constructor(send, keepMs = KEEP_MS) {
3522
+ this.send = send;
3523
+ this.keepMs = keepMs;
3524
+ }
3525
+ send;
3526
+ keepMs;
3527
+ entries = /* @__PURE__ */ new Map();
3528
+ /** Runs `run` for `id` unless it already runs or ran; `socket` hears that it started and, when it ends, its result. The run is
3529
+ * stopped only when every socket waiting on it has closed. */
3530
+ take(socket, id, run) {
3531
+ this.send(socket, { type: "computer-tool-started", id });
3532
+ const known = this.entries.get(id);
3533
+ if (known) {
3534
+ if (known.result) this.send(socket, { type: "computer-tool-result", id, ...known.result });
3535
+ else this.wait(known, socket);
3536
+ return;
3537
+ }
3538
+ const entry = { waiters: /* @__PURE__ */ new Set(), controller: new AbortController() };
3539
+ this.entries.set(id, entry);
3540
+ this.wait(entry, socket);
3541
+ void run(entry.controller.signal).catch((error) => ({ ok: false, output: error instanceof Error ? error.message : String(error) })).then((result) => {
3542
+ entry.result = result;
3543
+ for (const waiter of entry.waiters) if (!waiter.destroyed) this.send(waiter, { type: "computer-tool-result", id, ...result });
3544
+ entry.waiters.clear();
3545
+ const timer = setTimeout(() => {
3546
+ if (this.entries.get(id) === entry) this.entries.delete(id);
3547
+ }, this.keepMs);
3548
+ timer.unref?.();
3549
+ }).catch(quiet("worker/computer-tool-calls"));
3550
+ }
3551
+ wait(entry, socket) {
3552
+ entry.waiters.add(socket);
3553
+ socket.once("close", () => {
3554
+ entry.waiters.delete(socket);
3555
+ if (!entry.result && !entry.waiters.size) entry.controller.abort();
3556
+ });
3557
+ }
3558
+ };
3559
+
3560
+ // src/worker/worker-commands.ts
3561
+ import { homedir as homedir2 } from "node:os";
3562
+
3563
+ // src/worker/worker-live-commands.ts
3564
+ import { randomUUID as randomUUID7 } from "node:crypto";
3565
+ var HARD_STOP_AFTER_MS = 8e3;
3566
+ function stopHoldsForAgents(command) {
3567
+ const trigger = command.origin?.trigger;
3568
+ return trigger === void 0 || trigger === "esc" || trigger === "ctrl-c" || trigger === "editor-stop";
3569
+ }
3570
+ function subAgentStopNote(labels) {
3571
+ const named = labels.slice(0, 4).map((label) => `"${label.slice(0, 50)}"`).join(", ") + (labels.length > 4 ? ` and ${labels.length - 4} more` : "");
3572
+ return `Stop held: ${labels.length} sub-agent${labels.length === 1 ? " is" : "s are"} running (${named}), and stopping the turn would end ${labels.length === 1 ? "it" : "them"}. Press Esc or Ctrl+C again to stop anyway; otherwise nothing was interrupted. Messages you type still steer.`;
3573
+ }
3574
+ function stoppedCommandsNote(commands) {
3575
+ const named = commands.slice(0, 4).map((item) => `${item.pid} "${item.label.replace(/\s+/g, " ").trim().slice(0, 60)}"`).join(", ") + (commands.length > 4 ? ` and ${commands.length - 4} more` : "");
3576
+ return `Stopped ${commands.length} background command${commands.length === 1 ? "" : "s"} and their process groups: ${named}.`;
3577
+ }
3578
+ function createLiveCommands(ctx) {
3579
+ const { observer, sessionId } = ctx;
3580
+ const { currentSessionAndAccount, note, broadcastQueueChanged, showEveryWindow } = ctx.io;
3581
+ const handleUnqueue = async (socket, command) => {
3582
+ const answer = (outcome, message) => {
3583
+ sendEvent(socket, { type: "unqueued", id: command.id, outcome, ...message ? { message } : {} });
3584
+ };
3585
+ if (ctx.activeQueuedTurnId === command.id) {
3586
+ answer("running");
3587
+ return;
3588
+ }
3589
+ const live = ctx.activeLiveInput;
3590
+ try {
3591
+ if (live) {
3592
+ const outcome = await live.takeBack(command.id);
3593
+ if (outcome !== "removed") {
3594
+ answer(outcome);
3595
+ return;
3596
+ }
3597
+ } else {
3598
+ const state = await readState({ transcripts: [sessionId] });
3599
+ const found = state.sessions.find((item) => item.id === sessionId);
3600
+ if (!found || !consumeSessionTurn(found, command.id)) {
3601
+ answer("gone");
3602
+ return;
3603
+ }
3604
+ await writeState(state);
3605
+ }
3606
+ } catch (error) {
3607
+ answer("error", error instanceof Error ? error.message : String(error));
3608
+ return;
3609
+ }
3610
+ answer("removed");
3611
+ observer.broadcast({ type: "queue-changed" });
3612
+ void currentSessionAndAccount().then(({ session: current, account }) => observer.render(current, account)).catch(quiet("worker/worker-live-commands"));
3613
+ return;
3614
+ };
3615
+ const handleSendQueued = async (socket, _command) => {
3616
+ const liveInput = ctx.activeLiveInput;
3617
+ if (!liveInput) return;
3618
+ const handled = (async () => {
3619
+ try {
3620
+ const result = await liveInput.sendNow();
3621
+ if (!result) return;
3622
+ sendEvent(socket, {
3623
+ type: "submission",
3624
+ id: result.submission.id,
3625
+ disposition: result.steered ? "steered" : "queued",
3626
+ ...result.steered ? observer.steerOrder(result.submission.id) ?? {} : {}
3627
+ });
3628
+ broadcastQueueChanged();
3629
+ if (result.steered) showEveryWindow();
3630
+ } catch (error) {
3631
+ note(`Could not send: ${error instanceof Error ? error.message : String(error)}`);
3632
+ }
3633
+ })();
3634
+ ctx.activeSubmissions?.add(handled);
3635
+ await handled;
3636
+ return;
3637
+ };
3638
+ const announceStopping = (restoreTo) => {
3639
+ if (ctx.stopAnnounced) return;
3640
+ ctx.stopAnnounced = true;
3641
+ observer.broadcast({ type: "stopping" }, restoreTo);
3642
+ if (restoreTo) sendEvent(restoreTo, { type: "stopping", restoreDraft: true });
3643
+ };
3644
+ const hardStop = async (command = {}) => {
3645
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "forced" });
3646
+ observer.rejectPendingRequests();
3647
+ await Promise.allSettled([closePersistentTransport(sessionId), stopHeldVendorProcess(sessionId)]);
3648
+ ctx.forceStop?.();
3649
+ };
3650
+ const originFields = cancelOriginFields;
3651
+ let agentStopAsked;
3652
+ const handleCancel = async (socket, command) => {
3653
+ if (ctx.activeController && ctx.turnWorkDone) {
3654
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "nothing (turn work finished)" });
3655
+ sendEvent(socket, { type: "stop-done", nothing: true });
3656
+ return;
3657
+ }
3658
+ if (ctx.activeController) {
3659
+ const agentsOpen = observer.openAgentCalls();
3660
+ if (agentsOpen.length && stopHoldsForAgents(command) && !ctx.stopAnnounced) {
3661
+ if (agentStopAsked !== ctx.activeController) {
3662
+ agentStopAsked = ctx.activeController;
3663
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "held: sub-agents running", agents: agentsOpen.map((agent) => agent.label).join(" | ").slice(0, 300) });
3664
+ note(subAgentStopNote(agentsOpen.map((agent) => agent.label)));
3665
+ return;
3666
+ }
3667
+ }
3668
+ agentStopAsked = void 0;
3669
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "turn" });
3670
+ const repeated = ctx.stopAnnounced && ctx.activeController.signal.aborted;
3671
+ if (command.restoreDraft && !ctx.stopAnnounced) ctx.activeRestoreDraft = socket;
3672
+ announceStopping(ctx.activeRestoreDraft);
3673
+ ctx.activeController.abort();
3674
+ if (repeated) await hardStop(command);
3675
+ else if (!ctx.stopEscalation) {
3676
+ const controller = ctx.activeController;
3677
+ ctx.stopEscalation = setTimeout(() => {
3678
+ ctx.stopEscalation = void 0;
3679
+ if (ctx.activeController === controller) void hardStop();
3680
+ }, HARD_STOP_AFTER_MS);
3681
+ ctx.stopEscalation.unref?.();
3682
+ }
3683
+ return;
3684
+ }
3685
+ if (ctx.submitsInFlight > 0) {
3686
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "pending turn" });
3687
+ const pending = ctx.pendingCancel ?? (ctx.pendingCancel = { restoreDraft: command.restoreDraft ? socket : void 0, askers: /* @__PURE__ */ new Set() });
3688
+ pending.askers.add(socket);
3689
+ announceStopping(pending.restoreDraft);
3690
+ return;
3691
+ }
3692
+ if (hasHeldVendorProcess(sessionId)) {
3693
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "held vendor" });
3694
+ announceStopping(void 0);
3695
+ try {
3696
+ await stopHeldVendorProcess(sessionId);
3697
+ } finally {
3698
+ if (!ctx.turnRunning) ctx.stopAnnounced = false;
3699
+ observer.broadcast({ type: "stop-done" });
3700
+ }
3701
+ return;
3702
+ }
3703
+ if (ctx.vendorBackground.busy || await persistentWorkRunning(sessionId)) {
3704
+ announceStopping(void 0);
3705
+ try {
3706
+ const reaped = await reapPersistentCommands(sessionId, "all", "stopped by the user").catch(() => []);
3707
+ lifecycle("worker.cancel", { ...originFields(command), stopped: "vendor background work", killed: reaped.map(({ command: item, kill }) => `${item.pid} (${kill.how}) ${item.label}`.slice(0, 200)).join(" | ") || "no commands" });
3708
+ if (reaped.length) note(stoppedCommandsNote(reaped.map(({ command: item }) => item)));
3709
+ await Promise.all([closePersistentTransport(sessionId), stopHeldVendorProcess(sessionId)]);
3710
+ } finally {
3711
+ if (!ctx.turnRunning) ctx.stopAnnounced = false;
3712
+ observer.broadcast({ type: "stop-done" });
3713
+ }
3714
+ return;
3715
+ }
3716
+ lifecycle("worker.cancel", { ...originFields(command), stopped: ctx.resumeWaiter.pending ? "reset wait" : "nothing" });
3717
+ try {
3718
+ await ctx.resumeWaiter.cancel();
3719
+ } finally {
3720
+ sendEvent(socket, { type: "stop-done", nothing: true });
3721
+ }
3722
+ return;
3723
+ };
3724
+ const handleSteer = async (socket, command) => {
3725
+ const answer = (disposition, message) => {
3726
+ if (command.id) sendEvent(socket, { type: "submission", id: command.id, disposition, ...message ? { message } : {}, ...disposition === "steered" ? observer.steerOrder(command.id) ?? {} : {} });
3727
+ };
3728
+ if (!ctx.activeLiveInput) {
3729
+ try {
3730
+ const state = await readState({ transcripts: [sessionId] });
3731
+ const session = state.sessions.find((item) => item.id === sessionId);
3732
+ if (!session) throw new Error("conversation not found");
3733
+ const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
3734
+ enqueueSessionTurn(session, { id: command.id ?? randomUUID7(), text: command.text.trim(), submittedAt }, submittedAt);
3735
+ await writeState(state);
3736
+ answer("queued");
3737
+ broadcastQueueChanged();
3738
+ } catch (error) {
3739
+ answer("error", error instanceof Error ? error.message : String(error));
3740
+ }
3741
+ return;
3742
+ }
3743
+ const liveInput = ctx.activeLiveInput;
3744
+ const handled = (async () => {
3745
+ try {
3746
+ const machine = command.mode ? void 0 : await readState({ transcripts: [] }).then((state) => state.globalSettings, () => void 0);
3747
+ const result = await deliverTyped(liveInput, command.text, command.id, typedSettings(command.mode, machine));
3748
+ answer(result.disposition === "steered" ? "steered" : "queued");
3749
+ if (result.disposition !== "steered") broadcastQueueChanged();
3750
+ else showEveryWindow();
3751
+ } catch (error) {
3752
+ const message = error instanceof Error ? error.message : String(error);
3753
+ answer("error", message);
3754
+ if (!command.id) note(`Could not send: ${message}`);
3755
+ }
3756
+ })();
3757
+ ctx.activeSubmissions?.add(handled);
3758
+ await handled;
3759
+ return;
3760
+ };
3761
+ const handleSteerSubagent = async (socket, command) => {
3762
+ const refuse = (message) => {
3763
+ if (command.id) sendEvent(socket, { type: "submission", id: command.id, disposition: "error", message });
3764
+ else note(message);
3765
+ };
3766
+ const { session } = await currentSessionAndAccount();
3767
+ const harness = session.nativeHarness ? localHarnessForCommand(session.nativeHarness) : void 0;
3768
+ if (isClikCodeAgent(session)) {
3769
+ const agents = existingSessionAgents(ctx.agentSession);
3770
+ const id = command.agentId;
3771
+ if (!agents || !id) {
3772
+ refuse("This sub-agent has no running background session.");
3773
+ return;
3774
+ }
3775
+ const result = await agents.send(id, command.text);
3776
+ if (result.isError) refuse(result.output);
3777
+ else if (command.id) sendEvent(socket, { type: "submission", id: command.id, disposition: "steered" });
3778
+ return;
3779
+ }
3780
+ const ref = {
3781
+ id: command.parentId,
3782
+ label: command.label ?? command.parentId,
3783
+ status: "running",
3784
+ harness: harness?.command ?? "unknown",
3785
+ ...command.agentId ? { agentId: command.agentId } : {},
3786
+ read: harness?.subagents?.read ?? "none",
3787
+ steer: harness?.subagents?.steer ?? "none"
3788
+ };
3789
+ const plan = subAgentSteerPlan(ref, harness?.displayName ?? "This harness", ctx.activeLiveInput !== void 0, command.text);
3790
+ if ("refuse" in plan) {
3791
+ refuse(plan.refuse);
3792
+ return;
3793
+ }
3794
+ await handleSteer(socket, { type: "steer", text: plan.steer, ...command.id ? { id: command.id } : {} });
3795
+ };
3796
+ return { handleUnqueue, handleSendQueued, handleCancel, handleSteer, handleSteerSubagent };
3797
+ }
3798
+
3799
+ // src/worker/resource-note-delivery.ts
3800
+ function createResourceNoteDelivery(ctx) {
3801
+ return (note) => {
3802
+ void ctx.io.currentSessionAndAccount().then(() => {
3803
+ const live = ctx.activeLiveInput;
3804
+ if (!live) return holdResourceNote(ctx.sessionId, note);
3805
+ return live.steerNote(wrapResourceNote(note)).then((steered) => {
3806
+ if (!steered) return holdResourceNote(ctx.sessionId, note);
3807
+ return void 0;
3808
+ });
3809
+ }).catch(quiet("worker/resource-note-delivery"));
3810
+ };
3811
+ }
3812
+
3813
+ // src/worker/worker-commands.ts
3814
+ function createCommandHandler(ctx) {
3815
+ const { observer, sessionId, config, token } = ctx;
3816
+ const { currentSessionAndAccount } = ctx.io;
3817
+ const deliverResourceNote = createResourceNoteDelivery(ctx);
3818
+ const live = createLiveCommands(ctx);
3819
+ const agentsCommand = createAgentsCommand(ctx);
3820
+ const prepareForRoute = async () => {
3821
+ const { session: current } = await currentSessionAndAccount();
3822
+ if (!isClikCodeAgent(current)) {
3823
+ if (!ctx.turnRunning) await releaseMcp();
3824
+ return;
3825
+ }
3826
+ prepareMcp(stateDirectory(), routeMcpServers(current, config));
3827
+ if (isGatewayService(current)) void gatewayModels({ config }).catch(quiet("worker/worker-commands"));
3828
+ };
3829
+ const handleAttach = async (socket, command, connection) => {
3830
+ if (command.token !== token) {
3831
+ sendEvent(socket, { type: "attach-rejected", reason: "stale or invalid token" });
3832
+ socket.end();
3833
+ return;
3834
+ }
3835
+ if (command.readsSaved) windowReadsSaved(socket);
3836
+ connection.reattaches = command.reattaches === true;
3837
+ if (ctx.idleTimer) clearTimeout(ctx.idleTimer);
3838
+ ctx.idleTimer = void 0;
3839
+ connection.attaching = currentSessionAndAccount().then(({ session: current, account }) => {
3840
+ if (socket.destroyed) return;
3841
+ connection.attached = true;
3842
+ observer.attach(socket);
3843
+ lifecycle("worker.client.attach", { clients: observer.attachedCount, turnRunning: ctx.turnRunning });
3844
+ observer.snapshotFor(socket, current, account);
3845
+ observer.reofferPending(socket);
3846
+ });
3847
+ await connection.attaching;
3848
+ return;
3849
+ };
3850
+ const handleRetire = async (socket, presented, moved) => {
3851
+ if (presented !== void 0 && presented !== token) {
3852
+ sendEvent(socket, { type: "attach-rejected", reason: "stale or invalid token" });
3853
+ socket.end();
3854
+ return;
3855
+ }
3856
+ const blocker = ctx.idle.retireBlocker() ?? (await persistentWorkRunning(sessionId) ? "the vendor is still running work it started" : ctx.idle.retireBlocker());
3857
+ if (blocker) {
3858
+ ctx.retireWhenIdle = true;
3859
+ sendEvent(socket, { type: "retire-declined", reason: blocker });
3860
+ return;
3861
+ }
3862
+ const quietFor = moved ? 0 : ctx.idle.quietLeft();
3863
+ if (quietFor > 0) {
3864
+ ctx.retireWhenIdle = true;
3865
+ ctx.idle.retireIfFree();
3866
+ sendEvent(socket, { type: "retire-declined", reason: "it was active a moment ago" });
3867
+ return;
3868
+ }
3869
+ const reason = moved ? MOVED_REASON : "replaced by a newer ClikCode build";
3870
+ if (presented !== void 0) sendEvent(socket, { type: "shutdown", reason });
3871
+ void ctx.shutdown(reason);
3872
+ return;
3873
+ };
3874
+ const warm = () => {
3875
+ if (ctx.warming || ctx.turnRunning) return;
3876
+ ctx.warming = (async () => {
3877
+ await prepareForRoute();
3878
+ const { warmVendor } = await import("./chunk-M33LVA4M.js");
3879
+ if (await warmVendor(sessionId)) ctx.idle.vendorUsed();
3880
+ })().catch((error) => {
3881
+ lifecycle("worker.warm.failed", { message: error instanceof Error ? error.message : String(error) });
3882
+ }).finally(() => {
3883
+ ctx.warming = void 0;
3884
+ });
3885
+ };
3886
+ const toolCalls = new ToolCalls(sendEvent);
3887
+ const runComputerTool = (socket, command, connection) => {
3888
+ toolCalls.take(socket, command.id, (signal) => runSharedComputerTool({
3889
+ observer,
3890
+ stateDir: stateDirectory(),
3891
+ homeDir: homedir2(),
3892
+ tool: command.tool,
3893
+ args: command.args,
3894
+ signal,
3895
+ windows: () => observer.attachedCount - (connection.attached ? 1 : 0)
3896
+ }));
3897
+ };
3898
+ return Object.assign(async (socket, command, connection) => {
3899
+ if (command.type === "attach") {
3900
+ await handleAttach(socket, command, connection);
3901
+ return;
3902
+ }
3903
+ if (command.type === "retire" && command.token !== void 0) {
3904
+ await handleRetire(socket, command.token, command.reason === "moved");
3905
+ return;
3906
+ }
3907
+ if (command.type === "resource-note") {
3908
+ if (command.token !== token) {
3909
+ sendEvent(socket, { type: "attach-rejected", reason: "stale or invalid token" });
3910
+ socket.end();
3911
+ return;
3912
+ }
3913
+ deliverResourceNote(command.note);
3914
+ socket.end();
3915
+ return;
3916
+ }
3917
+ if (command.type === "warm") {
3918
+ if (command.token !== token) {
3919
+ sendEvent(socket, { type: "attach-rejected", reason: "stale or invalid token" });
3920
+ socket.end();
3921
+ return;
3922
+ }
3923
+ warm();
3924
+ return;
3925
+ }
3926
+ if (command.type === "computer-tool" && command.token !== void 0) {
3927
+ if (command.token !== token) {
3928
+ sendEvent(socket, { type: "attach-rejected", reason: "stale or invalid token" });
3929
+ socket.end();
3930
+ return;
3931
+ }
3932
+ runComputerTool(socket, command, connection);
3933
+ return;
3934
+ }
3935
+ if (connection.attaching) await connection.attaching.catch(quiet("worker/worker-commands"));
3936
+ if (!connection.attached) return;
3937
+ if (command.type === "submit") {
3938
+ if (ctx.shuttingDown) {
3939
+ sendEvent(socket, { type: "submit-rejected", message: "This conversation's worker is being replaced.", retry: true });
3940
+ return;
3941
+ }
3942
+ ctx.submitsInFlight++;
3943
+ try {
3944
+ await ctx.queue.handleSubmit(socket, command);
3945
+ } catch (error) {
3946
+ const message = error instanceof Error ? error.message : String(error);
3947
+ if (ctx.shuttingDown) sendEvent(socket, { type: "submit-rejected", message, retry: true });
3948
+ else {
3949
+ sendEvent(socket, { type: "submit-rejected", message });
3950
+ sendEvent(socket, { type: "turn-error", message });
3951
+ sendEvent(socket, { type: "waiting-stop" });
3952
+ }
3953
+ } finally {
3954
+ ctx.submitsInFlight--;
3955
+ if (ctx.submitsInFlight === 0 && ctx.pendingCancel) {
3956
+ ctx.pendingCancel = void 0;
3957
+ if (!ctx.activeController) ctx.stopAnnounced = false;
3958
+ observer.broadcast({ type: "stop-done", nothing: true });
3959
+ }
3960
+ }
3961
+ return;
3962
+ }
3963
+ if (command.type === "approval-response") {
3964
+ observer.resolveApproval(command.id, command.approved);
3965
+ return;
3966
+ }
3967
+ if (command.type === "question-response") {
3968
+ observer.resolveQuestion(command.id, command.result);
3969
+ return;
3970
+ }
3971
+ if (command.type === "computer-login") {
3972
+ sendEvent(socket, { type: "computer-login-started", id: command.id });
3973
+ const controller = new AbortController();
3974
+ const cancel = () => controller.abort();
3975
+ socket.once("close", cancel);
3976
+ void (async () => {
3977
+ try {
3978
+ const stateDir = stateDirectory();
3979
+ if (!await computerEnabled(stateDir)) throw new LoginError("Computer use is off.");
3980
+ if (observer.attachedCount < 2) throw new LoginError("No chat window is open to show the prompt. Open this chat in the terminal or VS Code.");
3981
+ if (command.manage) {
3982
+ const message = await manageSavedLogins(observer, stateDir, controller.signal);
3983
+ if (!socket.destroyed) sendEvent(socket, { type: "computer-login-result", id: command.id, ok: true, message });
3984
+ return;
3985
+ }
3986
+ const page = command.url ? await openComputerPage(stateDir) : await computerPage(stateDir);
3987
+ if (command.url) {
3988
+ const url = new URL(command.url);
3989
+ if (url.protocol !== "https:" || url.username || url.password) throw new LoginError("Private login needs an HTTPS website URL without credentials.");
3990
+ await page.goto(url.href, { waitUntil: "domcontentloaded", timeout: 3e4 });
3991
+ }
3992
+ const outcome = await loginComputerPage({
3993
+ stateDir,
3994
+ page,
3995
+ signal: controller.signal,
3996
+ ...command.newAccount ? { newAccount: true } : {},
3997
+ ask: (site, fields, signal) => askPrivateLogin(observer, site, fields, signal)
3998
+ });
3999
+ if (!socket.destroyed) sendEvent(socket, {
4000
+ type: "computer-login-result",
4001
+ id: command.id,
4002
+ ok: outcome !== "unverified" && outcome !== "saved_login_rejected",
4003
+ message: loginOutcomeMessage(outcome)
4004
+ });
4005
+ } catch (error) {
4006
+ if (!socket.destroyed) sendEvent(socket, {
4007
+ type: "computer-login-result",
4008
+ id: command.id,
4009
+ ok: false,
4010
+ message: error instanceof LoginError ? error.message : "Private login did not finish. Check the browser and try again."
4011
+ });
4012
+ } finally {
4013
+ socket.off("close", cancel);
4014
+ }
4015
+ })();
4016
+ return;
4017
+ }
4018
+ if (command.type === "computer-tool") {
4019
+ runComputerTool(socket, command, connection);
4020
+ return;
4021
+ }
4022
+ if (command.type === "sign-in-response") {
4023
+ observer.answerSignIn(command.id, socket, command);
4024
+ return;
4025
+ }
4026
+ if (command.type === "sign-in-claim") {
4027
+ observer.claimSignIn(command.id, socket);
4028
+ return;
4029
+ }
4030
+ if (command.type === "sign-in-release") {
4031
+ observer.releaseSignIn(command.id, socket);
4032
+ return;
4033
+ }
4034
+ if (command.type === "refresh") {
4035
+ void ctx.resumeWaiter.check();
4036
+ const { session: current, account } = await currentSessionAndAccount();
4037
+ observer.render(current, account);
4038
+ return;
4039
+ }
4040
+ if (command.type === "settings-changed") {
4041
+ ctx.liveSettings.apply(command.settings);
4042
+ return;
4043
+ }
4044
+ if (command.type === "read-subagent") {
4045
+ const { session, nativeAccount } = await currentSessionAndAccount();
4046
+ const rows = await readConversationSubagent(session, nativeAccount, command.parentId).catch(() => []);
4047
+ const mode = isClikCodeAgent(session) ? "direct" : session.nativeHarness ? localHarnessForCommand(session.nativeHarness)?.subagents?.steer : "none";
4048
+ sendEvent(socket, { type: "subagent", id: command.id, rows, steer: mode === "direct" ? "direct" : mode === "relay" ? "relay" : "none" });
4049
+ return;
4050
+ }
4051
+ if (command.type === "prepare") {
4052
+ await prepareForRoute();
4053
+ return;
4054
+ }
4055
+ if (command.type === "release") {
4056
+ if (!ctx.turnRunning) await releaseMcp();
4057
+ return;
4058
+ }
4059
+ if (command.type === "retire") {
4060
+ await handleRetire(socket, void 0, command.reason === "moved");
4061
+ return;
4062
+ }
4063
+ if (command.type === "detach") {
4064
+ socket.end();
4065
+ return;
4066
+ }
4067
+ if (command.type === "unqueue") {
4068
+ await live.handleUnqueue(socket, command);
4069
+ return;
4070
+ }
4071
+ if (command.type === "agents") {
4072
+ sendEvent(socket, await agentsCommand(command));
4073
+ return;
4074
+ }
4075
+ if (command.type === "send-queued") {
4076
+ await live.handleSendQueued(socket, command);
4077
+ return;
4078
+ }
4079
+ if (command.type === "cancel") {
4080
+ await live.handleCancel(socket, command);
4081
+ return;
4082
+ }
4083
+ if (command.type === "steer") {
4084
+ await live.handleSteer(socket, command);
4085
+ return;
4086
+ }
4087
+ if (command.type === "steer-subagent") {
4088
+ await live.handleSteerSubagent(socket, command);
4089
+ return;
4090
+ }
4091
+ }, { warm });
4092
+ }
4093
+
4094
+ // src/worker/worker-server.ts
4095
+ import { createServer } from "node:net";
4096
+ function createWorkerServer(ctx, handleCommand) {
4097
+ const { observer, connections } = ctx;
4098
+ return createServer((socket) => {
4099
+ const connection = { socket, frames: new FrameDecoder(), attached: false };
4100
+ connections.set(socket, connection);
4101
+ socket.on("data", (chunk) => {
4102
+ for (const message of connection.frames.push(chunk)) {
4103
+ void handleCommand(socket, message, connection).catch((error) => {
4104
+ const reason = error instanceof Error ? error.message : String(error);
4105
+ lifecycle("worker.command.failed", { type: message.type, message: reason });
4106
+ sendEvent(socket, { type: "note", message: `The conversation's worker could not do that: ${reason}` });
4107
+ });
4108
+ }
4109
+ });
4110
+ socket.on("close", () => {
4111
+ connections.delete(socket);
4112
+ const wasAttached = connection.attached;
4113
+ observer.detach(socket);
4114
+ if (wasAttached) lifecycle("worker.client.detach", { clients: observer.attachedCount, turnRunning: ctx.turnRunning });
4115
+ if (wasAttached && observer.attachedCount === 0 && !ctx.turnRunning) void releaseMcp();
4116
+ ctx.idle.scheduleIdleExit();
4117
+ });
4118
+ socket.on("error", () => socket.destroy());
4119
+ });
4120
+ }
4121
+
4122
+ // src/worker/worker-shutdown.ts
4123
+ import { spawn } from "node:child_process";
4124
+ import { unlink } from "node:fs/promises";
4125
+ var FLUSH_WINDOWS_MS = 1e4;
4126
+ var AGENT_WIND_DOWN_MS = 3e4;
4127
+ var STEP_MS = 15e3;
4128
+ var SHUTDOWN_CEILING_MS = 9e4;
4129
+ async function boundedStep(step, work, ms = STEP_MS) {
4130
+ let timer;
4131
+ const stalled = new Promise((resolve) => {
4132
+ timer = setTimeout(() => {
4133
+ lifecycle("worker.shutdown.stalled", { step, afterMs: ms });
4134
+ resolve();
4135
+ }, ms);
4136
+ timer.unref();
4137
+ });
4138
+ try {
4139
+ await Promise.race([Promise.resolve(work()).then(() => void 0, () => void 0), stalled]);
4140
+ } finally {
4141
+ clearTimeout(timer);
4142
+ }
4143
+ }
4144
+ function createShutdown(ctx) {
4145
+ const { observer, sessionId, token, hold, socketPath, connections } = ctx;
4146
+ let shuttingDown;
4147
+ let currentStep = "start";
4148
+ const shutdown = (reason) => {
4149
+ if (!shuttingDown) {
4150
+ ctx.shuttingDown = true;
4151
+ const ceiling = setTimeout(() => {
4152
+ lifecycle("worker.shutdown.stalled", { step: currentStep, afterMs: SHUTDOWN_CEILING_MS });
4153
+ process.exit(0);
4154
+ }, SHUTDOWN_CEILING_MS);
4155
+ ceiling.unref();
4156
+ shuttingDown = shutdownOnce(reason).catch(() => process.exit(0));
4157
+ }
4158
+ return shuttingDown;
4159
+ };
4160
+ const windDownAgents = async (reason) => {
4161
+ const agents = existingSessionAgents(ctx.agentSession);
4162
+ if (!agents?.runningAgents().length) return;
4163
+ ctx.agentSession.onNotification = void 0;
4164
+ const names = agents.runningAgents().map((agent) => agent.id).join(", ");
4165
+ lifecycle("worker.agents.wind-down", { reason, agents: names });
4166
+ await Promise.race([agents.stopAll(`ClikCode's worker stopped (${reason}); its work is committed to its branch`), new Promise((resolve) => {
4167
+ setTimeout(resolve, AGENT_WIND_DOWN_MS).unref();
4168
+ })]);
4169
+ const owed = takeShellNotifications(ctx.agentSession);
4170
+ ctx.agentSession.notifications.push(...owed.filter((note) => note.kind !== "agent"));
4171
+ await ctx.io.recordNotifications(owed.filter((note) => note.kind === "agent").map((note) => ({ ...note, reason: "interrupted" }))).catch(quiet("worker/worker-shutdown"));
4172
+ };
4173
+ const shutdownOnce = async (reason) => {
4174
+ lifecycle("worker.shutdown", { reason, turnRunning: ctx.turnRunning, clients: observer.attachedCount });
4175
+ currentStep = "out-of-turn settle";
4176
+ await boundedStep(currentStep, () => ctx.outOfTurn?.settle());
4177
+ currentStep = "agent wind-down";
4178
+ await windDownAgents(reason);
4179
+ disposeSessionState(stateDirectory(), sessionId, `ClikCode's worker for this conversation stopped (${reason})`);
4180
+ currentStep = "interrupted agents";
4181
+ await boundedStep(currentStep, async () => {
4182
+ await recordInterruptedAgents(ctx, await runningVendorAgents(sessionId));
4183
+ });
4184
+ currentStep = "vendor close";
4185
+ await boundedStep(currentStep, () => closePersistentTransport());
4186
+ currentStep = "language servers";
4187
+ await boundedStep(currentStep, () => shutdownLanguageServers());
4188
+ await Promise.race([closeAllOwnedPages(stateDirectory()).catch(quiet("worker/worker-shutdown")), new Promise((resolve) => {
4189
+ setTimeout(resolve, 3e3).unref();
4190
+ })]);
4191
+ currentStep = "window flush";
4192
+ const flushed = [];
4193
+ for (const connection of connections.keys()) {
4194
+ sendEvent(connection, { type: "shutdown", reason });
4195
+ connection.end();
4196
+ flushed.push(new Promise((resolve) => {
4197
+ if (connection.destroyed || connection.writableFinished) {
4198
+ resolve();
4199
+ return;
4200
+ }
4201
+ connection.once("finish", resolve);
4202
+ connection.once("close", resolve);
4203
+ connection.once("error", () => resolve());
4204
+ }));
4205
+ }
4206
+ await Promise.race([Promise.all(flushed), new Promise((resolve) => {
4207
+ setTimeout(resolve, FLUSH_WINDOWS_MS).unref();
4208
+ })]);
4209
+ ctx.server.close();
4210
+ currentStep = "record cleanup";
4211
+ observer.onAwaitingApproval = void 0;
4212
+ ctx.keepWarm?.stop();
4213
+ observer.onBackgroundWork = void 0;
4214
+ await ctx.recordWrite;
4215
+ await removeWorkerRecord(sessionId, token).catch(quiet("worker/worker-shutdown"));
4216
+ if (await hold.held()) await unlink(socketPath).catch(quiet("worker/worker-shutdown"));
4217
+ await hold.release().catch(quiet("worker/worker-shutdown"));
4218
+ ctx.resumeWaiter.stop();
4219
+ const successor = startsSuccessor(ctx.resumeWaiter.pending, reason);
4220
+ lifecycle("worker.stopped", { reason, successor });
4221
+ if (successor) startSuccessor();
4222
+ process.exit(0);
4223
+ };
4224
+ const startSuccessor = () => {
4225
+ try {
4226
+ const child = spawn(process.execPath, [process.argv[1], "session-worker", sessionId], { stdio: "ignore", detached: true, windowsHide: true });
4227
+ child.on("error", () => void 0);
4228
+ child.unref();
4229
+ } catch {
4230
+ }
4231
+ };
4232
+ return shutdown;
4233
+ }
4234
+
4235
+ // src/worker/out-of-turn.ts
4236
+ var OUT_OF_TURN_SETTLE_MS = 1500;
4237
+ function createOutOfTurnRelay(ctx) {
4238
+ const record = outOfTurnRecorder(ctx.sessionId);
4239
+ let open;
4240
+ let timer;
4241
+ let saving = Promise.resolve();
4242
+ let pending = 0;
4243
+ let thoughts = 0;
4244
+ const close = () => {
4245
+ if (timer) clearTimeout(timer);
4246
+ timer = void 0;
4247
+ const said = open;
4248
+ open = void 0;
4249
+ if (!said) return saving;
4250
+ pending += 1;
4251
+ saving = saving.then(async () => {
4252
+ if (said.text) await record({ kind: said.kind, text: said.text, mode: "replace" });
4253
+ if (ctx.observer.turnGeneration !== said.generation) return;
4254
+ const { session, account } = await ctx.io.currentSessionAndAccount();
4255
+ if (ctx.observer.turnGeneration === said.generation) ctx.observer.endTurn(session, account);
4256
+ }).catch(quiet("worker/out-of-turn")).finally(() => {
4257
+ pending -= 1;
4258
+ ctx.idle.scheduleIdleExit();
4259
+ });
4260
+ return saving;
4261
+ };
4262
+ const relay = (said) => {
4263
+ const sofar = said.kind === "message" && open?.kind === "message" && said.mode === "append" ? open.text + said.text : said.text;
4264
+ if (said.kind === "message" && isVendorRefusalSaid(sofar)) {
4265
+ if (open?.kind === "message") {
4266
+ if (timer) clearTimeout(timer);
4267
+ timer = void 0;
4268
+ const shown = open;
4269
+ open = void 0;
4270
+ ctx.observer.response("", "replace");
4271
+ if (ctx.observer.turnGeneration === shown.generation) {
4272
+ void ctx.io.currentSessionAndAccount().then(({ session, account }) => {
4273
+ if (ctx.observer.turnGeneration === shown.generation) ctx.observer.endTurn(session, account);
4274
+ }, () => void 0);
4275
+ }
4276
+ }
4277
+ void (async () => {
4278
+ const accountId = (await readState({ transcripts: [] })).sessions.find((item) => item.id === ctx.sessionId)?.nativeThreadAccountId;
4279
+ if (!accountId) return;
4280
+ await observeSessionAccount({ sessionId: ctx.sessionId, accountId, evidence: { vendorError: true, text: sofar }, source: "out-of-turn" });
4281
+ })().catch(quiet("worker/out-of-turn"));
4282
+ return;
4283
+ }
4284
+ if (open && open.kind !== said.kind) void close();
4285
+ if (!open) {
4286
+ ctx.observer.startTurn(said.kind === "thought" ? "thinking" : "writing", void 0, true);
4287
+ open = { kind: said.kind, text: "", generation: ctx.observer.turnGeneration, thoughtId: `out-of-turn-thought-${++thoughts}` };
4288
+ }
4289
+ open.text = said.mode === "replace" ? said.text : open.text + said.text;
4290
+ if (said.kind === "message") ctx.observer.response(said.text, said.mode);
4291
+ else ctx.observer.activityEvent({ kind: "thinking", label: thoughtLabel(open.text), id: open.thoughtId });
4292
+ if (timer) clearTimeout(timer);
4293
+ timer = setTimeout(() => {
4294
+ void close();
4295
+ }, OUT_OF_TURN_SETTLE_MS);
4296
+ timer.unref();
4297
+ };
4298
+ return { relay, get active() {
4299
+ return Boolean(open) || pending > 0;
4300
+ }, settle: close };
4301
+ }
4302
+
4303
+ // src/worker/session-worker.ts
4304
+ var COMMAND_SWEEP_MS = 1e3;
4305
+ var HANDOFF_CHECK_MS = 1e4;
4306
+ var OWN_CONVERSATION_MAX_WAIT_MS = 30 * 60 * 1e3;
4307
+ async function ownConversation(sessionId, maxWaitMs = OWN_CONVERSATION_MAX_WAIT_MS, take = takeConversation) {
4308
+ const deadline = Date.now() + maxWaitMs;
4309
+ for (; ; ) {
4310
+ const taken = await take(sessionId, "worker");
4311
+ if ("hold" in taken) return taken.hold;
4312
+ if (taken.holder.kind === "worker" && taken.holder.host === hostname()) return void 0;
4313
+ if (Date.now() >= deadline) {
4314
+ throw new Error(`the conversation ${sessionId} is still held by a ${taken.holder.kind} (pid ${taken.holder.pid}) after ${Math.round(maxWaitMs / 1e3)}s; the worker did not start`);
4315
+ }
4316
+ await sleep(250);
4317
+ }
4318
+ }
4319
+ function backgroundSignature(value) {
4320
+ return `${value?.agents ?? 0}/${value?.terminals ?? 0}/${value?.workflows ?? 0}/${(value?.commands ?? []).map((item) => `${item.pid}:${item.stale ?? ""}`).join(",")}`;
4321
+ }
4322
+ async function runSessionWorker(sessionId, options = {}) {
4323
+ const readyFd = takeWorkerReadyFd();
4324
+ const config = new Conf({ projectName: "clikcode", configFileMode: 384 });
4325
+ const state = await readState({ transcripts: [sessionId] });
4326
+ const session = state.sessions.find((item) => item.id === sessionId);
4327
+ if (!session) {
4328
+ lifecycle("worker.no-session");
4329
+ return;
4330
+ }
4331
+ void dropRetiredVendorMcp(stateDirectory(), homeForOwnState(stateDirectory())).catch((error) => lifecycle("mcp.retired", { error: error instanceof Error ? error.message.slice(0, 200) : String(error) }));
4332
+ const hold = await ownConversation(sessionId);
4333
+ if (!hold) return;
4334
+ const placement = await separateFromForeground(sessionId);
4335
+ process.env.CLIKCODE_SESSION_ID = sessionId;
4336
+ if (process.platform === "linux" && process.env.CLIKCODE_OWN_SCOPE !== "0") installSystemdRunShim();
4337
+ useConversationTmp(sessionId);
4338
+ const socketPath = socketPathFor(sessionId);
4339
+ if (await workerIsReachable(socketPath)) {
4340
+ await hold.release();
4341
+ return;
4342
+ }
4343
+ await unlink2(socketPath).catch(quiet("worker/session-worker"));
4344
+ const observer = new BroadcastObserver();
4345
+ observer.sessionId = sessionId;
4346
+ const token = generateWorkerToken();
4347
+ const homeIdentity = () => {
4348
+ try {
4349
+ const stat3 = statSync4(stateDirectory());
4350
+ return `${stat3.dev}:${stat3.ino}:${stat3.birthtimeMs}`;
4351
+ } catch {
4352
+ return void 0;
4353
+ }
4354
+ };
4355
+ const startedHome = homeIdentity();
4356
+ const ctx = {
4357
+ sessionId,
4358
+ config,
4359
+ observer,
4360
+ token,
4361
+ hold,
4362
+ socketPath,
4363
+ agentSession: sessionState(stateDirectory(), sessionId),
4364
+ liveSettings: new LiveSettings(session),
4365
+ connections: /* @__PURE__ */ new Map(),
4366
+ homeGone: () => homeIdentity() !== startedHome,
4367
+ spawnedBuild: currentWorkerBuild(),
4368
+ turnRunning: false,
4369
+ activeQueuedTurnId: void 0,
4370
+ draining: false,
4371
+ lastTurnStopped: false,
4372
+ queuedUserTurn: false,
4373
+ stalledQueuedTurnId: void 0,
4374
+ idleTimer: void 0,
4375
+ activeController: void 0,
4376
+ activeLiveInput: void 0,
4377
+ activeSubmissions: void 0,
4378
+ activeRestoreDraft: void 0,
4379
+ submitsInFlight: 0,
4380
+ shuttingDown: false,
4381
+ pendingCancel: void 0,
4382
+ stopAnnounced: false,
4383
+ resumingTurn: false,
4384
+ retireWhenIdle: false,
4385
+ recordWrite: Promise.resolve(),
4386
+ warming: void 0
4387
+ };
4388
+ ctx.io = createWorkerIo(ctx);
4389
+ ctx.vendorBackground = createVendorBackgroundRunner({
4390
+ sessionId,
4391
+ observer,
4392
+ userTurnRunning: () => ctx.turnRunning,
4393
+ runningChanged: (since) => ctx.onBackgroundTurnRunningChange?.(since),
4394
+ resumeParked: () => {
4395
+ void ctx.resumeWaiter.check();
4396
+ },
4397
+ changed: () => {
4398
+ ctx.idle.vendorUsed();
4399
+ ctx.idle.scheduleIdleExit();
4400
+ }
4401
+ });
4402
+ ctx.outOfTurn = createOutOfTurnRelay(ctx);
4403
+ setVendorBackgroundTurnHandler(sessionId, (turn) => {
4404
+ void ctx.outOfTurn.settle().then(() => ctx.vendorBackground.handle(turn));
4405
+ });
4406
+ setOutOfTurnHandler(sessionId, ctx.outOfTurn.relay);
4407
+ setWorkEndedHandler(sessionId, createWorkEndedHandler(ctx));
4408
+ ctx.idle = createIdleControl(ctx);
4409
+ const parkedText = async (prompt) => prompt === LEGACY_INTERRUPTED_TURN_REQUEST ? (await readState({ transcripts: [sessionId] })).sessions.find((item) => item.id === sessionId)?.pendingTurn?.prompt ?? prompt : prompt;
4410
+ ctx.resumeWaiter = createResumeWaiter({
4411
+ sessionId,
4412
+ turnRunning: () => ctx.turnRunning || ctx.draining,
4413
+ notice: ctx.io.note,
4414
+ changed: () => ctx.idle.scheduleIdleExit(),
4415
+ restore: async (prompt) => {
4416
+ const text = await parkedText(prompt);
4417
+ if (ctx.observer.attachedCount > 0) {
4418
+ ctx.observer.broadcast({ type: "restore-draft", text });
4419
+ return;
4420
+ }
4421
+ const latest = await readState({ transcripts: [sessionId] });
4422
+ const found = latest.sessions.find((item) => item.id === sessionId);
4423
+ if (!found) return;
4424
+ const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
4425
+ enqueueSessionTurn(found, { id: randomUUID8(), text: text.trim(), submittedAt }, submittedAt);
4426
+ await writeState(latest);
4427
+ ctx.io.broadcastQueueChanged();
4428
+ },
4429
+ send: async (prompt) => {
4430
+ const text = await parkedText(prompt);
4431
+ ctx.resumingTurn = true;
4432
+ if (!ctx.queue.startTurn({ type: "submit", text, echo: true })) ctx.resumingTurn = false;
4433
+ }
4434
+ });
4435
+ ctx.keepWarm = createKeepWarm({ sessionId, busy: () => ctx.turnRunning || ctx.draining, changed: () => ctx.idle.scheduleIdleExit() });
4436
+ ctx.queue = createWorkerQueue(ctx);
4437
+ ctx.runTurn = createTurnRunner(ctx);
4438
+ ctx.agentSession.onNotification = () => {
4439
+ void ctx.queue.deliverNotifications();
4440
+ };
4441
+ const handleCommand = createCommandHandler(ctx);
4442
+ ctx.server = createWorkerServer(ctx, handleCommand);
4443
+ ctx.shutdown = createShutdown(ctx);
4444
+ let checkingHandoff = false;
4445
+ const checkHandoff = () => {
4446
+ if (checkingHandoff) return;
4447
+ checkingHandoff = true;
4448
+ void (async () => {
4449
+ if (!await conversationHandoffRequested(sessionId)) return;
4450
+ if (ctx.idle.retireBlocker() || await persistentWorkRunning(sessionId)) return;
4451
+ await ctx.shutdown(CONVERSATION_HANDOFF_REASON);
4452
+ })().catch(quiet("worker/session-worker")).finally(() => {
4453
+ checkingHandoff = false;
4454
+ });
4455
+ };
4456
+ setInterval(checkHandoff, HANDOFF_CHECK_MS).unref();
4457
+ watchHandoffRequest(sessionId, checkHandoff);
4458
+ startStuckWatchdog(sessionId);
4459
+ {
4460
+ const deliverNote = createResourceNoteDelivery(ctx);
4461
+ const commands = placement?.divided ? createCommandSweep(placement.scopeDir) : void 0;
4462
+ if (commands) setInterval(() => {
4463
+ try {
4464
+ commands.sweep();
4465
+ } catch {
4466
+ }
4467
+ }, COMMAND_SWEEP_MS).unref();
4468
+ startGuardian({
4469
+ guard: () => {
4470
+ const stopResources = startResourceGuard({
4471
+ sessionId,
4472
+ ...placement?.divided ? { sliceDir: placement.sliceDir, remembered: { scopeDir: placement.scopeDir, labels: commands.labels } } : {},
4473
+ deliver: (note, worker) => {
4474
+ if (worker === process.pid) deliverNote(note);
4475
+ else void sendResourceNote(worker, note).catch(quiet("worker/session-worker"));
4476
+ }
4477
+ });
4478
+ const stopSweep = startStateSweep();
4479
+ return () => {
4480
+ stopResources();
4481
+ stopSweep();
4482
+ };
4483
+ }
4484
+ });
4485
+ if (commands && placement?.scopeDir) startIoGuard({ sessionId, scopeDir: placement.scopeDir, labels: commands.labels, deliver: deliverNote });
4486
+ startDiskWatch({ sessionId, paths: [stateDirectory(), session.workspace], deliver: deliverNote });
4487
+ if (placement?.divided) startIdleServices({ sessionId, sliceDir: placement.sliceDir, deliver: deliverNote });
4488
+ }
4489
+ try {
4490
+ await new Promise((resolveListening, rejectListening) => {
4491
+ ctx.server.once("error", rejectListening);
4492
+ ctx.server.listen(socketPath, resolveListening);
4493
+ });
4494
+ } catch (error) {
4495
+ await hold.release();
4496
+ throw error;
4497
+ }
4498
+ const record = {
4499
+ pid: process.pid,
4500
+ sessionId,
4501
+ socketPath,
4502
+ installationId: state.installationId,
4503
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
4504
+ token,
4505
+ ...currentWorkerBuild() ? { build: currentWorkerBuild() } : {}
4506
+ };
4507
+ await writeWorkerRecord(record);
4508
+ announceWorkerReady(readyFd);
4509
+ void reconcileAgents(stateDirectory(), sessionId).then(async (reports) => {
4510
+ if (!reports.length) return;
4511
+ await ctx.io.recordNotifications(reports.map((entry) => ({ kind: "agent", shellId: entry.id, command: entry.label, tail: entry.report, reason: "interrupted", at: Date.now() })));
4512
+ await ctx.queue.deliverNotifications();
4513
+ }).catch(quiet("worker/session-worker"));
4514
+ let awaiting;
4515
+ let background;
4516
+ let runningTurn;
4517
+ let backgroundTurn;
4518
+ const rewriteRecord = () => {
4519
+ ctx.recordWrite = ctx.recordWrite.then(() => writeWorkerRecord({ ...record, ...awaiting ? { awaitingApproval: awaiting } : {}, ...background ? { background } : {}, ...runningTurn ?? backgroundTurn ? { runningTurn: runningTurn ?? backgroundTurn } : {} }, { existing: true })).catch(quiet("worker/session-worker"));
4520
+ return ctx.recordWrite;
4521
+ };
4522
+ ctx.onTurnRunningChange = async (since) => {
4523
+ runningTurn = since ? { since } : void 0;
4524
+ await rewriteRecord();
4525
+ };
4526
+ ctx.onBackgroundTurnRunningChange = async (since) => {
4527
+ backgroundTurn = since ? { since } : void 0;
4528
+ await rewriteRecord();
4529
+ };
4530
+ observer.onAwaitingApproval = (awaitingApproval) => {
4531
+ awaiting = awaitingApproval;
4532
+ return rewriteRecord();
4533
+ };
4534
+ let liveWork;
4535
+ let leftWork;
4536
+ const backgroundChanged = () => {
4537
+ const sum = { agents: (liveWork?.agents ?? 0) + (leftWork?.agents ?? 0), terminals: (liveWork?.terminals ?? 0) + (leftWork?.terminals ?? 0), workflows: liveWork?.workflows ?? 0 };
4538
+ const counts = Object.fromEntries(Object.entries(sum).filter(([, count]) => count > 0));
4539
+ const commands = sum.terminals && liveWork?.commands?.length ? liveWork.commands : void 0;
4540
+ const work = Object.keys(counts).length ? { ...counts, ...commands ? { commands } : {} } : void 0;
4541
+ if (backgroundSignature(work) === backgroundSignature(background)) return void 0;
4542
+ background = work ? { ...work, since: background?.since ?? (/* @__PURE__ */ new Date()).toISOString() } : void 0;
4543
+ return rewriteRecord();
4544
+ };
4545
+ observer.onBackgroundWork = (work) => {
4546
+ liveWork = work;
4547
+ return backgroundChanged();
4548
+ };
4549
+ setRetiredWorkListener(sessionId, (work) => {
4550
+ leftWork = work;
4551
+ void backgroundChanged();
4552
+ ctx.idle.scheduleIdleExit();
4553
+ });
4554
+ process.on("SIGTERM", () => {
4555
+ void ctx.shutdown("SIGTERM");
4556
+ });
4557
+ process.on("SIGINT", () => {
4558
+ void ctx.shutdown("SIGINT");
4559
+ });
4560
+ ctx.idle.scheduleIdleExit();
4561
+ const buildWatch = setInterval(() => {
4562
+ if (ctx.homeGone()) {
4563
+ void ctx.shutdown("its ClikCode home was removed");
4564
+ return;
4565
+ }
4566
+ ctx.idle.leaveIfStaleBuild();
4567
+ void ctx.idle.leaveIfOverCap();
4568
+ }, BUILD_WATCH_MS);
4569
+ buildWatch.unref();
4570
+ if (options.warm) handleCommand.warm();
4571
+ void ctx.queue.drainQueue().catch(ctx.queue.reportDrainFailure);
4572
+ void ctx.resumeWaiter.check();
4573
+ }
4574
+ export {
4575
+ backgroundSignature,
4576
+ ownConversation,
4577
+ runSessionWorker
4578
+ };