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,277 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ registerTunedModel
5
+ } from "./chunk-7DOKGSUN.js";
6
+ import {
7
+ LLAMA_CPP_TAG
8
+ } from "./chunk-2QWPQRSU.js";
9
+ import "./chunk-IS4USJPY.js";
10
+ import "./chunk-TQDKJHWX.js";
11
+ import {
12
+ fineTuneDir
13
+ } from "./chunk-PEWCDI2C.js";
14
+ import "./chunk-TULAXS77.js";
15
+ import "./chunk-F6F47QAY.js";
16
+ import {
17
+ quiet
18
+ } from "./chunk-RDDWQBEM.js";
19
+ import "./chunk-MPAJ446F.js";
20
+ import "./chunk-CBANJFBO.js";
21
+ import "./chunk-PWXII6HF.js";
22
+
23
+ // src/local-models/finetune-local.ts
24
+ import { spawn } from "node:child_process";
25
+ import { availableParallelism } from "node:os";
26
+ import { copyFile, mkdir, rm, stat, writeFile } from "node:fs/promises";
27
+ import { basename, join } from "node:path";
28
+ var LOCAL_TRAINER_IMAGE = "python:3.12-bookworm";
29
+ var LOCAL_TRAINER_PY = String.raw`"""CPU LoRA fine-tune: the trainer a CPU task runs (training/cpu-trainer.ts).
30
+
31
+ Reads FT_CONFIG (base64 JSON), the dataset at DATASET_PATH, trains a LoRA adapter on the CPU, merges it into the base weights and
32
+ saves them half-precision under OUT_DIR/merged. Its log is the trainer log contract (parseTrainingProgress): a {'loss': L, 'epoch': E}
33
+ line per step, a N/M [ step counter with a percent bar, and nothing printed as Traceback unless it failed.
34
+ """
35
+ import base64, csv, json, math, os, sys, time
36
+
37
+ import torch
38
+ from transformers import AutoModelForCausalLM, AutoTokenizer
39
+ from peft import LoraConfig, get_peft_model
40
+
41
+ cfg = json.loads(base64.b64decode(os.environ["FT_CONFIG"]).decode("utf-8"))
42
+ hp = cfg["hyperparams"]
43
+ base = cfg["baseModelId"]
44
+ fmt = cfg.get("datasetFormat", "JSONL_TEXT")
45
+ dataset_path = os.environ.get("DATASET_PATH", "/tmp/dataset.jsonl")
46
+ out_dir = os.environ.get("OUT_DIR", "/out/run")
47
+ seq_len = int(hp.get("sequenceLen", 1024))
48
+ epochs = int(hp.get("epochs", 1))
49
+ lr = float(hp.get("learningRate", 2e-4))
50
+ rank = int(hp.get("loraRank", 16))
51
+ alpha = int(hp.get("loraAlpha", rank * 2))
52
+ token = os.environ.get("HF_TOKEN") or None
53
+
54
+
55
+ def usable_cpus():
56
+ """The CPUs this process may use: its affinity, capped by a container's CPU quota (os.cpu_count() sees the whole host)."""
57
+ n = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 1)
58
+ try:
59
+ quota, period = open("/sys/fs/cgroup/cpu.max").read().split()
60
+ if quota != "max":
61
+ n = min(n, max(1, int(int(quota) / int(period))))
62
+ except (OSError, ValueError):
63
+ pass
64
+ return max(1, n)
65
+
66
+
67
+ torch.set_num_threads(usable_cpus())
68
+ torch.manual_seed(0)
69
+
70
+ print(f"[ft] cpu-trainer: {base}, LoRA rank {rank}, {epochs} epoch(s), {torch.get_num_threads()} threads", flush=True)
71
+ tok = AutoTokenizer.from_pretrained(base, token=token)
72
+ if tok.pad_token is None:
73
+ tok.pad_token = tok.eos_token
74
+
75
+
76
+ def rows():
77
+ with open(dataset_path, newline="", encoding="utf-8") as fh:
78
+ if fmt == "CSV":
79
+ yield from csv.DictReader(fh)
80
+ else:
81
+ for line in fh:
82
+ line = line.strip()
83
+ if line:
84
+ yield json.loads(line)
85
+
86
+
87
+ def text_of(row):
88
+ if isinstance(row.get("messages"), list):
89
+ if getattr(tok, "chat_template", None):
90
+ return tok.apply_chat_template(row["messages"], tokenize=False)
91
+ return "\n".join(f"{m.get('role', 'user')}: {m.get('content', '')}" for m in row["messages"])
92
+ if "prompt" in row and "completion" in row:
93
+ return f"{row['prompt']}{row['completion']}"
94
+ return str(row.get("text") or next(iter(row.values()), ""))
95
+
96
+
97
+ examples = []
98
+ for row in rows():
99
+ ids = tok(text_of(row), truncation=True, max_length=seq_len, return_tensors="pt")["input_ids"][0]
100
+ if len(ids) > 1:
101
+ examples.append(ids)
102
+ if not examples:
103
+ print("[ft] the dataset has no usable rows", file=sys.stderr, flush=True)
104
+ sys.exit(2)
105
+
106
+ model = AutoModelForCausalLM.from_pretrained(base, torch_dtype=torch.float32, token=token)
107
+ model = get_peft_model(model, LoraConfig(r=rank, lora_alpha=alpha, lora_dropout=0.05, target_modules="all-linear", task_type="CAUSAL_LM"))
108
+ model.train()
109
+ opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
110
+
111
+ total = len(examples) * epochs
112
+ step = 0
113
+ started = time.time()
114
+ for epoch in range(epochs):
115
+ order = torch.randperm(len(examples)).tolist()
116
+ for index in order:
117
+ ids = examples[index].unsqueeze(0)
118
+ loss = model(input_ids=ids, labels=ids).loss
119
+ loss.backward()
120
+ opt.step()
121
+ opt.zero_grad()
122
+ step += 1
123
+ done = step / total
124
+ elapsed = time.time() - started
125
+ eta = elapsed / step * (total - step)
126
+ bar = "#" * int(done * 10)
127
+ print(f"{int(done * 100):3d}%|{bar:<10}| {step}/{total} [{int(elapsed // 60):02d}:{int(elapsed % 60):02d}<{int(eta // 60):02d}:{int(eta % 60):02d}, {elapsed / step:.1f}s/it]", flush=True)
128
+ print("{'loss': %.4f, 'learning_rate': %g, 'epoch': %.2f}" % (loss.item(), lr, step / len(examples)), flush=True)
129
+
130
+ print("[ft] Merging the adapter into the base weights", flush=True)
131
+ model = model.merge_and_unload().to(torch.float16)
132
+ merged = os.path.join(out_dir, "merged")
133
+ os.makedirs(merged, exist_ok=True)
134
+ model.save_pretrained(merged, safe_serialization=True)
135
+ tok.save_pretrained(merged)
136
+ print(f"[ft] saved {merged}", flush=True)
137
+ `;
138
+ var HF_REPO = /^[\w.-]+\/[\w.-]+$/;
139
+ function trainerConfig(input, datasetPath) {
140
+ const rank = input.loraRank ?? 8;
141
+ return {
142
+ baseModelId: input.base,
143
+ datasetFormat: datasetPath.toLowerCase().endsWith(".csv") ? "CSV" : "JSONL_TEXT",
144
+ hyperparams: { epochs: input.epochs ?? 2, loraRank: rank, loraAlpha: rank * 2, learningRate: 2e-4, sequenceLen: 512 }
145
+ };
146
+ }
147
+ function containerScript(tag = LLAMA_CPP_TAG) {
148
+ return [
149
+ "set -e",
150
+ // The container runs as root, so what it writes is root's: on EVERY exit, a failure included, hand the output and the caches back to the
151
+ // user (found live: a failed run's scratch and the model cache could not be deleted by the user who ran them).
152
+ `trap 'chown -R "$HOST_UID:$HOST_GID" /out /cache 2>/dev/null || true' EXIT`,
153
+ "export HF_HOME=/cache/hf PIP_CACHE_DIR=/cache/pip",
154
+ "mkdir -p /out/run",
155
+ 'echo "[ft] installing the trainer libraries"',
156
+ "pip install -q torch --index-url https://download.pytorch.org/whl/cpu",
157
+ // The whole tag, not one script: the converter imports a package beside it (found live: "No module named 'conversion'"), and gguf-py
158
+ // from the same tag is the writer that converter was made for.
159
+ `git clone -q --depth 1 --branch ${tag} https://github.com/ggml-org/llama.cpp /tmp/llama.cpp`,
160
+ "pip install -q transformers peft accelerate numpy sentencepiece protobuf /tmp/llama.cpp/gguf-py",
161
+ "DATASET_PATH=/in/dataset OUT_DIR=/out/run python -u /trainer/cpu_trainer.py",
162
+ 'echo "[ft] converting to GGUF"',
163
+ // Without the speculative-decoding (MTP) layer: the trainer loads the text model only, so the merged weights have none, and a file that
164
+ // declares one it lacks does not load (found live: "tensor 'blk.24.attn_norm.weight' not found"). Not every architecture takes the flag.
165
+ 'CONVERT="python /tmp/llama.cpp/convert_hf_to_gguf.py /out/run/merged --outfile /out/model.gguf --outtype q8_0"',
166
+ "$CONVERT --no-mtp || $CONVERT",
167
+ "rm -rf /out/run",
168
+ "echo CLIK_TRAINING_COMPLETE"
169
+ ].join("\n");
170
+ }
171
+ function dockerRunArgs(input) {
172
+ return [
173
+ "run",
174
+ "--rm",
175
+ "--name",
176
+ input.name,
177
+ "--cpus",
178
+ String(Math.max(1, input.cpus)),
179
+ "-v",
180
+ `${join(input.workDir, "in")}:/in:ro`,
181
+ "-v",
182
+ `${join(input.workDir, "out")}:/out`,
183
+ "-v",
184
+ `${join(input.workDir, "trainer")}:/trainer:ro`,
185
+ "-v",
186
+ `${input.cacheDir}:/cache`,
187
+ "-e",
188
+ `FT_CONFIG=${Buffer.from(JSON.stringify(input.config), "utf8").toString("base64")}`,
189
+ "-e",
190
+ `HOST_UID=${input.uid}`,
191
+ "-e",
192
+ `HOST_GID=${input.gid}`,
193
+ ...input.hfToken ? ["-e", `HF_TOKEN=${input.hfToken}`] : [],
194
+ LOCAL_TRAINER_IMAGE,
195
+ "bash",
196
+ "-c",
197
+ containerScript()
198
+ ];
199
+ }
200
+ function runDocker(args, onLine) {
201
+ return new Promise((resolve, reject) => {
202
+ const child = spawn("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
203
+ let carry = "";
204
+ const feed = (chunk) => {
205
+ const lines = (carry + chunk.toString("utf8")).split(/\r?\n|\r/);
206
+ carry = lines.pop() ?? "";
207
+ for (const line of lines) if (line.trim()) onLine(line);
208
+ };
209
+ child.stdout.on("data", feed);
210
+ child.stderr.on("data", feed);
211
+ child.once("error", (error) => reject(error.code === "ENOENT" ? new Error("Docker is needed to fine-tune on this computer and was not found. Install Docker, or fine-tune in the cloud with `finetune --cloud`.") : error));
212
+ child.once("close", (code) => {
213
+ if (carry.trim()) onLine(carry);
214
+ resolve(code ?? 1);
215
+ });
216
+ });
217
+ }
218
+ function worthShowing(line) {
219
+ return /^\[ft\]/.test(line) || /\d+\/\d+ \[/.test(line) || /CLIK_TRAINING_COMPLETE|Traceback|Error/.test(line);
220
+ }
221
+ async function fineTuneLocalModel(input, deps = {}) {
222
+ if (!HF_REPO.test(input.base)) throw new Error("--base must be a Hugging Face model repo, e.g. Qwen/Qwen2.5-0.5B-Instruct (the original weights, not a GGUF).");
223
+ if (!(await stat(input.dataset).catch(quiet("local-models/finetune-local")))?.isFile()) throw new Error(`No dataset file at ${input.dataset}.`);
224
+ if (input.epochs !== void 0 && (!Number.isInteger(input.epochs) || input.epochs < 1 || input.epochs > 10)) throw new Error("--epochs must be a whole number from 1 to 10");
225
+ const progress = deps.progress ?? ((line) => {
226
+ process.stderr.write(`${line}
227
+ `);
228
+ });
229
+ const docker = deps.docker ?? runDocker;
230
+ const register = deps.register ?? ((registration) => registerTunedModel(registration));
231
+ const now = deps.now ?? Date.now;
232
+ const started = now();
233
+ const root = deps.workRoot ?? fineTuneDir();
234
+ const workDir = join(root, `run-${input.name}-${started}`);
235
+ const cacheDir = join(root, "cache");
236
+ await Promise.all(["in", "out", "trainer"].map((dir) => mkdir(join(workDir, dir), { recursive: true })));
237
+ await mkdir(join(cacheDir, "hf"), { recursive: true });
238
+ await mkdir(join(cacheDir, "pip"), { recursive: true });
239
+ try {
240
+ await copyFile(input.dataset, join(workDir, "in", "dataset"));
241
+ await writeFile(join(workDir, "trainer", "cpu_trainer.py"), LOCAL_TRAINER_PY);
242
+ progress(`fine-tuning ${input.base} on this computer (CPU): ${basename(input.dataset)}`);
243
+ const args = dockerRunArgs({
244
+ name: `clikcode-finetune-${input.name}`,
245
+ workDir,
246
+ cacheDir,
247
+ cpus: availableParallelism(),
248
+ config: trainerConfig(input, input.dataset),
249
+ uid: process.getuid?.() ?? 0,
250
+ gid: process.getgid?.() ?? 0,
251
+ ...process.env.HF_TOKEN ? { hfToken: process.env.HF_TOKEN } : {}
252
+ });
253
+ const lines = [];
254
+ const code = await docker(args, (line) => {
255
+ lines.push(line);
256
+ if (lines.length > 40) lines.shift();
257
+ if (worthShowing(line)) progress(line.trim());
258
+ });
259
+ if (code !== 0) throw new Error(`The fine-tune failed (docker exit ${code}). The last output:
260
+ ${lines.slice(-8).join("\n")}`);
261
+ const gguf = join(workDir, "out", "model.gguf");
262
+ if (!(await stat(gguf).catch(quiet("local-models/finetune-local")))?.isFile()) throw new Error("The fine-tune finished without a GGUF to register.");
263
+ progress("registering the model");
264
+ const model = await register({ name: input.name, ggufPath: gguf, ...input.license ? { license: input.license } : {} });
265
+ return { model, seconds: Math.round((now() - started) / 1e3) };
266
+ } finally {
267
+ await rm(workDir, { recursive: true, force: true }).catch(quiet("local-models/finetune-local"));
268
+ }
269
+ }
270
+ export {
271
+ LOCAL_TRAINER_IMAGE,
272
+ LOCAL_TRAINER_PY,
273
+ containerScript,
274
+ dockerRunArgs,
275
+ fineTuneLocalModel,
276
+ trainerConfig
277
+ };
@@ -0,0 +1,29 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ callbacksReachable,
5
+ completeLoginUrl,
6
+ extractLoginUrl,
7
+ hasLocalDisplay,
8
+ loginLinkLine,
9
+ loginUrlNotice,
10
+ openLoginUrl
11
+ } from "./chunk-RE4TGORR.js";
12
+ import "./chunk-DCZ6CIUM.js";
13
+ import {
14
+ shortenLoginUrl
15
+ } from "./chunk-4AQ5NINV.js";
16
+ import "./chunk-WPB5WEZJ.js";
17
+ import "./chunk-GYMAI5NY.js";
18
+ import "./chunk-G3QP67Z7.js";
19
+ import "./chunk-PWXII6HF.js";
20
+ export {
21
+ callbacksReachable,
22
+ completeLoginUrl,
23
+ extractLoginUrl,
24
+ hasLocalDisplay,
25
+ loginLinkLine,
26
+ loginUrlNotice,
27
+ openLoginUrl,
28
+ shortenLoginUrl
29
+ };
@@ -0,0 +1,258 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ readState
5
+ } from "./chunk-MXS6S2PY.js";
6
+ import "./chunk-BISGNHKD.js";
7
+ import "./chunk-BGEMY2JJ.js";
8
+ import "./chunk-XCKQ5BM2.js";
9
+ import "./chunk-NWEYRBWK.js";
10
+ import "./chunk-TWCVV2JO.js";
11
+ import "./chunk-PDPEM5VW.js";
12
+ import "./chunk-WWLJMP6D.js";
13
+ import "./chunk-CRUVYGO2.js";
14
+ import "./chunk-FF7ZVYJF.js";
15
+ import "./chunk-IMLTL2MY.js";
16
+ import "./chunk-BUOPJQP5.js";
17
+ import "./chunk-3B2CHX7M.js";
18
+ import "./chunk-RVUOIJXN.js";
19
+ import "./chunk-QUS4ER2W.js";
20
+ import "./chunk-DQYVQ2N7.js";
21
+ import "./chunk-KYUHIFP3.js";
22
+ import "./chunk-RSZGEL5U.js";
23
+ import "./chunk-NKDATMEM.js";
24
+ import "./chunk-CQ7J6UQ7.js";
25
+ import "./chunk-XKW5NDMR.js";
26
+ import "./chunk-W3YYPBEA.js";
27
+ import "./chunk-XIBYREEY.js";
28
+ import "./chunk-EE4B6A7W.js";
29
+ import "./chunk-WZYVLUVQ.js";
30
+ import "./chunk-O3EW7LAY.js";
31
+ import "./chunk-KHW6TX6I.js";
32
+ import {
33
+ AGENT_SLICE,
34
+ COMMAND_GROUP,
35
+ groupPids
36
+ } from "./chunk-HU5SSUFX.js";
37
+ import {
38
+ sleep
39
+ } from "./chunk-YMCH3L2S.js";
40
+ import "./chunk-4QZEZME7.js";
41
+ import "./chunk-LVRRWP4W.js";
42
+ import "./chunk-G3QP67Z7.js";
43
+ import "./chunk-4L2ZZM4Q.js";
44
+ import "./chunk-F6F47QAY.js";
45
+ import "./chunk-RDDWQBEM.js";
46
+ import "./chunk-MPAJ446F.js";
47
+ import "./chunk-CBANJFBO.js";
48
+ import "./chunk-PWXII6HF.js";
49
+
50
+ // src/worker/scope-report.ts
51
+ import { readdirSync } from "node:fs";
52
+ import { join as join2 } from "node:path";
53
+
54
+ // src/worker/cgroup-inspect.ts
55
+ import { readFileSync, writeFileSync } from "node:fs";
56
+ import { join } from "node:path";
57
+ var KEEP = "clikcode:keep";
58
+ var isKept = (commandLine) => !!commandLine && (commandLine.includes(KEEP) || /\bcomputer-host\b/.test(commandLine));
59
+ var boot;
60
+ function bootMs() {
61
+ if (boot !== void 0) return boot;
62
+ try {
63
+ const seconds = Number(/^btime (\d+)/m.exec(readFileSync("/proc/stat", "utf8"))?.[1]);
64
+ return Number.isFinite(seconds) ? boot = seconds * 1e3 : void 0;
65
+ } catch {
66
+ return void 0;
67
+ }
68
+ }
69
+ var realReaders = {
70
+ pids: groupPids,
71
+ startedAt: (pid) => {
72
+ try {
73
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
74
+ const ticks = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]);
75
+ const base = bootMs();
76
+ return Number.isFinite(ticks) && base !== void 0 ? base + ticks / 100 * 1e3 : void 0;
77
+ } catch {
78
+ return void 0;
79
+ }
80
+ },
81
+ commandLine: (pid) => {
82
+ try {
83
+ return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter(Boolean).join(" ");
84
+ } catch {
85
+ return void 0;
86
+ }
87
+ },
88
+ file: (path) => {
89
+ try {
90
+ return readFileSync(path, "utf8");
91
+ } catch {
92
+ return void 0;
93
+ }
94
+ }
95
+ };
96
+ function cgroupFacts(dir, now, read = realReaders) {
97
+ const pids = read.pids(dir);
98
+ let oldest;
99
+ let keep = false;
100
+ let command;
101
+ for (const pid of pids) {
102
+ const started = read.startedAt(pid);
103
+ if (started !== void 0 && (oldest === void 0 || started < oldest)) oldest = started;
104
+ const line = read.commandLine(pid);
105
+ if (isKept(line)) keep = true;
106
+ if (line && !command) command = line;
107
+ }
108
+ const cpu2 = Number(/^usage_usec (\d+)/m.exec(read.file(join(dir, "cpu.stat")) ?? "")?.[1]);
109
+ const memory = Number(read.file(join(dir, "memory.current")));
110
+ const tasks = Number(read.file(join(dir, "pids.current")));
111
+ return {
112
+ pids: pids.length,
113
+ keep,
114
+ ...oldest !== void 0 ? { ageMs: Math.max(0, now - oldest) } : {},
115
+ ...command ? { command } : {},
116
+ ...Number.isFinite(cpu2) ? { cpuUsec: cpu2 } : {},
117
+ ...Number.isFinite(memory) && memory > 0 ? { memoryBytes: memory } : {},
118
+ ...Number.isFinite(tasks) && tasks > 0 ? { tasks } : {}
119
+ };
120
+ }
121
+ function killCgroup(dir) {
122
+ try {
123
+ writeFileSync(join(dir, "cgroup.kill"), "1");
124
+ return true;
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+
130
+ // src/worker/scope-report.ts
131
+ function parseScopeName(unit) {
132
+ const worker = /^clikcode-worker-(.+)-(\d+)\.scope$/.exec(unit);
133
+ if (worker) return { kind: "worker", sessionId: worker[1], workerPid: Number(worker[2]) };
134
+ if (/^clikcode-browser-host[^/]*\.(?:scope|service)$/.test(unit)) return { kind: "browser-host" };
135
+ return { kind: "other" };
136
+ }
137
+ function treePids(dir, read, list = listDirectories) {
138
+ return [...read.pids(dir), ...list(dir).flatMap((child) => treePids(join2(dir, child), read, list))];
139
+ }
140
+ function listDirectories(dir) {
141
+ try {
142
+ return readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
143
+ } catch {
144
+ return [];
145
+ }
146
+ }
147
+ function withTree(dir, read, list, now) {
148
+ const own = cgroupFacts(dir, now, read);
149
+ const pids = treePids(dir, read, list);
150
+ const starts = pids.map((pid) => read.startedAt(pid)).filter((value) => value !== void 0);
151
+ const keep = pids.some((pid) => isKept(read.commandLine(pid)));
152
+ return { ...own, pids: pids.length, keep, ...starts.length ? { ageMs: now - Math.min(...starts) } : {} };
153
+ }
154
+ async function scanSlice(sliceDir, options = {}) {
155
+ const read = options.read ?? realReaders;
156
+ const list = options.list ?? listDirectories;
157
+ const take = (now) => list(sliceDir).filter((name) => /\.(?:scope|service)$/.test(name)).map((unit) => {
158
+ const dir = join2(sliceDir, unit);
159
+ const parsed = parseScopeName(unit);
160
+ const facts = withTree(dir, read, list, now);
161
+ const workerAlive = parsed.workerPid !== void 0 ? (read.commandLine(parsed.workerPid) ?? "").includes("session-worker") : void 0;
162
+ const commands = list(dir).filter((name) => COMMAND_GROUP.test(name)).map((group) => {
163
+ const groupDir = join2(dir, group);
164
+ return { group, dir: groupDir, facts: withTree(groupDir, read, list, now) };
165
+ });
166
+ return {
167
+ unit,
168
+ dir,
169
+ ...parsed,
170
+ facts,
171
+ commands,
172
+ ...parsed.sessionId && options.names?.get(parsed.sessionId) ? { owner: options.names.get(parsed.sessionId) } : {},
173
+ ...workerAlive !== void 0 ? { workerAlive } : {},
174
+ orphaned: parsed.kind === "worker" && workerAlive === false && facts.pids > 0
175
+ };
176
+ });
177
+ const startedAt = options.now ?? Date.now();
178
+ const first = take(startedAt);
179
+ await (options.pause ?? (() => sleep(1e3)))();
180
+ const endedAt = options.now !== void 0 ? options.now + 1e3 : Date.now();
181
+ const second = take(endedAt);
182
+ const percent = (before, after) => before.cpuUsec !== void 0 && after.cpuUsec !== void 0 && endedAt > startedAt ? Math.max(0, (after.cpuUsec - before.cpuUsec) / 1e3 / (endedAt - startedAt) * 100) : void 0;
183
+ return second.map((row) => {
184
+ const before = first.find((item) => item.unit === row.unit);
185
+ const cpuPercent = before ? percent(before.facts, row.facts) : void 0;
186
+ return {
187
+ ...row,
188
+ ...cpuPercent !== void 0 ? { cpuPercent } : {},
189
+ commands: row.commands.map((command) => {
190
+ const earlier = before?.commands.find((item) => item.group === command.group);
191
+ const cpu2 = earlier ? percent(earlier.facts, command.facts) : void 0;
192
+ return { ...command, ...cpu2 !== void 0 ? { cpuPercent: cpu2 } : {} };
193
+ })
194
+ };
195
+ });
196
+ }
197
+ var hours = (ms) => ms >= 36e5 ? `${(ms / 36e5).toFixed(ms >= 36e6 ? 0 : 1)} h` : `${Math.round(ms / 6e4)} min`;
198
+ var gb = (bytes) => bytes === void 0 ? "-" : bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(1)}G` : `${Math.round(bytes / 2 ** 20)}M`;
199
+ var cpu = (value) => value === void 0 ? "-" : `${Math.round(value)}%`;
200
+ function reapTargets(rows) {
201
+ return rows.filter((row) => row.orphaned && !row.facts.keep).map((row) => ({ dir: row.dir, why: "its worker ended", label: row.unit }));
202
+ }
203
+ function renderScopeReport(rows) {
204
+ if (!rows.length) return "No ClikCode scope is running.";
205
+ const lines = [];
206
+ for (const row of [...rows].sort((a, b) => (b.facts.memoryBytes ?? 0) - (a.facts.memoryBytes ?? 0))) {
207
+ const who = row.kind === "worker" ? `session ${row.sessionId.slice(0, 8)}${row.owner ? ` "${row.owner}"` : ""}, worker ${row.workerPid} ${row.workerAlive ? "alive" : "GONE"}` : row.kind === "browser-host" ? "browser host" : "";
208
+ lines.push(`${row.unit}${row.orphaned ? " [ORPHANED: no live worker]" : ""}`);
209
+ lines.push(` ${who ? `${who} \xB7 ` : ""}mem ${gb(row.facts.memoryBytes)} \xB7 tasks ${row.facts.tasks ?? row.facts.pids} \xB7 cpu ${cpu(row.cpuPercent)} \xB7 age ${row.facts.ageMs !== void 0 ? hours(row.facts.ageMs) : "-"}`);
210
+ for (const command of [...row.commands].sort((a, b) => (b.facts.ageMs ?? 0) - (a.facts.ageMs ?? 0)).slice(0, 8)) {
211
+ const text = (command.facts.command ?? "").replace(/\s+/g, " ").slice(0, 70);
212
+ lines.push(` ${command.group} \xB7 age ${command.facts.ageMs !== void 0 ? hours(command.facts.ageMs) : "-"} \xB7 cpu ${cpu(command.cpuPercent)} \xB7 mem ${gb(command.facts.memoryBytes)} \xB7 ${command.facts.keep ? "keep \xB7 " : ""}${text}`);
213
+ }
214
+ if (row.commands.length > 8) lines.push(` ... and ${row.commands.length - 8} more commands`);
215
+ }
216
+ return lines.join("\n");
217
+ }
218
+ function reap(targets, kill = killCgroup) {
219
+ return targets.filter((target) => kill(target.dir)).map((target) => target.label);
220
+ }
221
+
222
+ // src/commands/doctor-scopes.ts
223
+ function agentSliceFor(uid) {
224
+ return `/sys/fs/cgroup/user.slice/user-${uid}.slice/user@${uid}.service/${AGENT_SLICE}`;
225
+ }
226
+ async function aiDoctorScopes(options) {
227
+ if (process.platform !== "linux") {
228
+ process.stdout.write("Scopes are a Linux (systemd) feature; nothing to list here.\n");
229
+ return;
230
+ }
231
+ const names = /* @__PURE__ */ new Map();
232
+ try {
233
+ for (const session of (await readState({ transcripts: [] })).sessions) if (session.name) names.set(session.id, session.name);
234
+ } catch {
235
+ }
236
+ const rows = await scanSlice(agentSliceFor(process.getuid?.() ?? 0), { names });
237
+ process.stdout.write(`${renderScopeReport(rows)}
238
+ `);
239
+ const targets = reapTargets(rows);
240
+ if (!targets.length) {
241
+ process.stdout.write("\nNothing is flagged.\n");
242
+ return;
243
+ }
244
+ process.stdout.write(`
245
+ Flagged (${targets.length}):
246
+ ${targets.map((target) => ` ${target.label}: ${target.why}`).join("\n")}
247
+ `);
248
+ if (!options.reap) {
249
+ process.stdout.write("Run `clikcode doctor scopes --reap` to end these cgroups (and nothing else).\n");
250
+ return;
251
+ }
252
+ const ended = reap(targets);
253
+ process.stdout.write(`Ended ${ended.length} of ${targets.length}: ${ended.join(", ") || "none"}
254
+ `);
255
+ }
256
+ export {
257
+ aiDoctorScopes
258
+ };
@@ -0,0 +1,117 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ openTransport
5
+ } from "./chunk-GLY7RM3C.js";
6
+ import {
7
+ CLIKCODE_VERSION
8
+ } from "./chunk-NAOX3JUB.js";
9
+ import {
10
+ quiet
11
+ } from "./chunk-RDDWQBEM.js";
12
+
13
+ // src/agent/mcp/client.ts
14
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
15
+ var McpClient = class _McpClient {
16
+ constructor(spec, transport, serverName, hasResources = false) {
17
+ this.spec = spec;
18
+ this.transport = transport;
19
+ this.serverName = serverName;
20
+ this.hasResources = hasResources;
21
+ }
22
+ spec;
23
+ transport;
24
+ serverName;
25
+ hasResources;
26
+ /** Opens the transport and completes the handshake, or closes what it
27
+ * opened and throws with the server's own explanation attached. */
28
+ static async connect(spec, options) {
29
+ const transport = openTransport(spec, options, options.fetchImpl, options.auth);
30
+ const onAbort = () => {
31
+ transport.killNow();
32
+ };
33
+ if (options.signal?.aborted) onAbort();
34
+ options.signal?.addEventListener("abort", onAbort, { once: true });
35
+ try {
36
+ const result = await transport.request("initialize", {
37
+ protocolVersion: MCP_PROTOCOL_VERSION,
38
+ // No roots, sampling or elicitation: this client calls tools and reads resources.
39
+ capabilities: {},
40
+ clientInfo: { name: "clikcode", version: CLIKCODE_VERSION }
41
+ }, { timeoutMs: options.timeoutMs });
42
+ if (typeof result.protocolVersion === "string") transport.setProtocolVersion(result.protocolVersion);
43
+ transport.notify("notifications/initialized");
44
+ const serverName = typeof result.serverInfo?.name === "string" ? result.serverInfo.name : spec.name;
45
+ const resources = result.capabilities?.resources;
46
+ return new _McpClient(spec, transport, serverName, Boolean(resources) && typeof resources === "object");
47
+ } catch (error) {
48
+ const detail = transport.detail();
49
+ await transport.close().catch(quiet("agent/mcp/client"));
50
+ throw withDetail(error, detail);
51
+ } finally {
52
+ options.signal?.removeEventListener("abort", onAbort);
53
+ }
54
+ }
55
+ get closed() {
56
+ return this.transport.closed;
57
+ }
58
+ detail() {
59
+ return this.transport.detail();
60
+ }
61
+ /** Every tool, across pages. */
62
+ async listTools(timeoutMs) {
63
+ return (await this.listAll("tools/list", "tools", { timeoutMs })).filter((tool) => typeof tool?.name === "string");
64
+ }
65
+ /** Every resource, across pages. */
66
+ async listResources(options) {
67
+ return (await this.listAll("resources/list", "resources", options)).filter((resource) => typeof resource?.uri === "string");
68
+ }
69
+ async readResource(uri, options) {
70
+ try {
71
+ const result = await this.transport.request("resources/read", { uri }, options);
72
+ return Array.isArray(result.contents) ? result.contents.filter((item) => item && typeof item === "object") : [];
73
+ } catch (error) {
74
+ throw withDetail(error, this.transport.detail());
75
+ }
76
+ }
77
+ /** A paged list method's items. A cursor that repeats would loop forever,
78
+ * so one seen twice ends the listing. */
79
+ async listAll(method, key, options) {
80
+ const items = [];
81
+ const seen = /* @__PURE__ */ new Set();
82
+ let cursor;
83
+ do {
84
+ const page = await this.transport.request(method, cursor ? { cursor } : {}, options).catch((error) => {
85
+ throw withDetail(error, this.transport.detail());
86
+ });
87
+ for (const item of Array.isArray(page[key]) ? page[key] : []) if (item) items.push(item);
88
+ cursor = typeof page.nextCursor === "string" && !seen.has(page.nextCursor) ? page.nextCursor : void 0;
89
+ if (cursor) seen.add(cursor);
90
+ } while (cursor);
91
+ return items;
92
+ }
93
+ async callTool(name, args, options) {
94
+ try {
95
+ return await this.transport.request("tools/call", { name, arguments: args }, options);
96
+ } catch (error) {
97
+ throw withDetail(error, this.transport.detail());
98
+ }
99
+ }
100
+ close() {
101
+ return this.transport.close();
102
+ }
103
+ killNow() {
104
+ this.transport.killNow();
105
+ }
106
+ };
107
+ function withDetail(error, detail) {
108
+ const base = error instanceof Error ? error : new Error(String(error));
109
+ const tail = detail.trim().split("\n").slice(-6).join("\n").slice(-800);
110
+ if (!tail || base.message.includes(tail)) return base;
111
+ return Object.assign(new Error(`${base.message}
112
+ ${tail}`), { name: base.name, code: base.code });
113
+ }
114
+
115
+ export {
116
+ McpClient
117
+ };