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.
- package/README.md +25 -14
- package/dist/chunk-23TDEBGZ.js +71 -0
- package/dist/chunk-25T3GVS7.js +425 -0
- package/dist/chunk-2BBELGHY.js +11 -0
- package/dist/chunk-2EOL5PZL.js +208 -0
- package/dist/chunk-2GAB36IE.js +26 -0
- package/dist/chunk-2OLS7V66.js +2440 -0
- package/dist/chunk-2QFO2URB.js +179 -0
- package/dist/chunk-2QWPQRSU.js +254 -0
- package/dist/chunk-2YPAPAR3.js +184 -0
- package/dist/chunk-2ZAG5372.js +33 -0
- package/dist/chunk-32IKAIZC.js +12507 -0
- package/dist/chunk-34AZEGYW.js +95 -0
- package/dist/chunk-34JQYQCA.js +175 -0
- package/dist/chunk-34ZISPAO.js +67 -0
- package/dist/chunk-3AAAARE6.js +46 -0
- package/dist/chunk-3AJ6Q3OY.js +510 -0
- package/dist/chunk-3B2CHX7M.js +884 -0
- package/dist/chunk-3BUFORRX.js +59 -0
- package/dist/chunk-3QLHYYFK.js +30 -0
- package/dist/chunk-3RXBMYKZ.js +140 -0
- package/dist/chunk-3TFNIJWS.js +52 -0
- package/dist/chunk-3W3IPDFP.js +119 -0
- package/dist/chunk-3WMS7SEE.js +417 -0
- package/dist/chunk-435ZNSZ3.js +23 -0
- package/dist/chunk-4AQ5NINV.js +39 -0
- package/dist/chunk-4GVEJ5FK.js +168 -0
- package/dist/chunk-4GXAO3UY.js +262 -0
- package/dist/chunk-4L2ZZM4Q.js +332 -0
- package/dist/chunk-4LPDG57B.js +17 -0
- package/dist/chunk-4NN3XQQT.js +223 -0
- package/dist/chunk-4QZEZME7.js +54 -0
- package/dist/chunk-4R6CSC3S.js +38 -0
- package/dist/chunk-4RHXTL3W.js +514 -0
- package/dist/chunk-4SJMPTVQ.js +18 -0
- package/dist/chunk-4VY7G6TX.js +114 -0
- package/dist/chunk-5642PBF7.js +124 -0
- package/dist/chunk-5B6TVO4A.js +33 -0
- package/dist/chunk-5BJLDUPL.js +62 -0
- package/dist/chunk-5HMFFJWU.js +19 -0
- package/dist/chunk-5IKLK33T.js +69 -0
- package/dist/chunk-5NQ5FFMX.js +44 -0
- package/dist/chunk-5QNNW5L6.js +176 -0
- package/dist/chunk-5SM5UAWN.js +239 -0
- package/dist/chunk-5WYJTA6O.js +74 -0
- package/dist/chunk-5ZSR2Y5T.js +227 -0
- package/dist/chunk-5ZWUM5GH.js +39 -0
- package/dist/chunk-64E7D4HY.js +364 -0
- package/dist/chunk-6CK466BC.js +99 -0
- package/dist/chunk-6ES45HHO.js +138 -0
- package/dist/chunk-6HYEZFGL.js +277 -0
- package/dist/chunk-6Y7HLXGW.js +29 -0
- package/dist/chunk-6YKK4FYR.js +258 -0
- package/dist/chunk-74WNMLMS.js +117 -0
- package/dist/chunk-7AULZ7OD.js +55 -0
- package/dist/chunk-7DOKGSUN.js +101 -0
- package/dist/chunk-7IH5LTIZ.js +195 -0
- package/dist/chunk-7ISTS5NS.js +21 -0
- package/dist/chunk-7NMUTGOW.js +527 -0
- package/dist/chunk-7PNHUZEL.js +153 -0
- package/dist/chunk-7TSQLONI.js +88 -0
- package/dist/chunk-AE7TOLD5.js +30 -0
- package/dist/chunk-AEMHSXKA.js +130 -0
- package/dist/chunk-AKRYTS2D.js +211 -0
- package/dist/chunk-AMNSE36L.js +59 -0
- package/dist/chunk-AZVD74ZV.js +23 -0
- package/dist/chunk-B35DVOTK.js +1981 -0
- package/dist/chunk-B4HNJRAH.js +626 -0
- package/dist/chunk-B5WYPPHS.js +13 -0
- package/dist/chunk-BBOVDXQM.js +59 -0
- package/dist/chunk-BD3ECZLK.js +62 -0
- package/dist/chunk-BDGSOT74.js +4578 -0
- package/dist/chunk-BF5VEOPK.js +31 -0
- package/dist/chunk-BFFRW4XH.js +47 -0
- package/dist/chunk-BFPC6PEW.js +208 -0
- package/dist/chunk-BGEMY2JJ.js +376 -0
- package/dist/chunk-BISGNHKD.js +35 -0
- package/dist/chunk-BMRAEBRY.js +21 -0
- package/dist/chunk-BNTXAZXW.js +127 -0
- package/dist/chunk-BOQBXGSN.js +75 -0
- package/dist/chunk-BTJDSTQP.js +213 -0
- package/dist/chunk-BUOPJQP5.js +218 -0
- package/dist/chunk-BXFJS65Q.js +52 -0
- package/dist/chunk-BXPQFSX5.js +59 -0
- package/dist/chunk-C57LIWNY.js +1269 -0
- package/dist/chunk-C6YVCCWR.js +74 -0
- package/dist/chunk-CAADDF6M.js +167 -0
- package/dist/chunk-CBANJFBO.js +69 -0
- package/dist/chunk-CERF3RIB.js +597 -0
- package/dist/chunk-COAS5ETR.js +46 -0
- package/dist/chunk-CQ7J6UQ7.js +78 -0
- package/dist/chunk-CRUVYGO2.js +26 -0
- package/dist/chunk-CVFVFRGN.js +58 -0
- package/dist/chunk-D2UK66HM.js +37 -0
- package/dist/chunk-D2W7SA4R.js +18 -0
- package/dist/chunk-DA44ZENT.js +501 -0
- package/dist/chunk-DAJ76TOC.js +99 -0
- package/dist/chunk-DCZ6CIUM.js +147 -0
- package/dist/chunk-DF35KMXM.js +1314 -0
- package/dist/chunk-DGASQT26.js +151 -0
- package/dist/chunk-DJT57C5P.js +55 -0
- package/dist/chunk-DKDPZTD3.js +44 -0
- package/dist/chunk-DQYVQ2N7.js +77 -0
- package/dist/chunk-DRTP2RTY.js +266 -0
- package/dist/chunk-DW2BMUKY.js +61 -0
- package/dist/chunk-DW5T5ZVU.js +307 -0
- package/dist/chunk-DXKNDNFC.js +164 -0
- package/dist/chunk-DZEQ7UYR.js +291 -0
- package/dist/chunk-E4F4OUAC.js +463 -0
- package/dist/chunk-EE4B6A7W.js +69 -0
- package/dist/chunk-EISKIYWG.js +23 -0
- package/dist/chunk-EKAQK7UQ.js +235 -0
- package/dist/chunk-EOBTJV32.js +123 -0
- package/dist/chunk-ESF3DIZY.js +325 -0
- package/dist/chunk-EVOHOZ4U.js +45 -0
- package/dist/chunk-EXN4KHLB.js +110 -0
- package/dist/chunk-F252T6Y3.js +78 -0
- package/dist/chunk-F3DP4ZA2.js +40 -0
- package/dist/chunk-F6F47QAY.js +58 -0
- package/dist/chunk-FA3Y23ZW.js +57 -0
- package/dist/chunk-FBKXE4EJ.js +640 -0
- package/dist/chunk-FCGEB3H6.js +23 -0
- package/dist/chunk-FF7ZVYJF.js +3732 -0
- package/dist/chunk-FFGKN6L3.js +39 -0
- package/dist/chunk-FFGU4GCC.js +94 -0
- package/dist/chunk-FSFDAOVP.js +74 -0
- package/dist/chunk-FT5TX7OX.js +1573 -0
- package/dist/chunk-G3QP67Z7.js +232 -0
- package/dist/chunk-G5ORJKV2.js +179 -0
- package/dist/chunk-GFNC62PE.js +111 -0
- package/dist/chunk-GGK43Q3N.js +67 -0
- package/dist/chunk-GGYKY4GF.js +11537 -0
- package/dist/chunk-GGYNHGNJ.js +55 -0
- package/dist/chunk-GLY7RM3C.js +354 -0
- package/dist/chunk-GQBZU6EO.js +20 -0
- package/dist/chunk-GSXENUZL.js +9 -0
- package/dist/chunk-GTOAT5D3.js +40 -0
- package/dist/chunk-GWCMDPQU.js +1007 -0
- package/dist/chunk-GXYSMYHJ.js +152 -0
- package/dist/chunk-GYMAI5NY.js +14 -0
- package/dist/chunk-H2VZMKPE.js +30 -0
- package/dist/chunk-H4THUNBM.js +2091 -0
- package/dist/chunk-HGRVSNUZ.js +361 -0
- package/dist/chunk-HI4VY473.js +27 -0
- package/dist/chunk-HOJRSD3Q.js +447 -0
- package/dist/chunk-HRX25W35.js +82 -0
- package/dist/chunk-HSE4AQYV.js +55 -0
- package/dist/chunk-HU5SSUFX.js +383 -0
- package/dist/chunk-I3GDBJLH.js +196 -0
- package/dist/chunk-I75EDU75.js +684 -0
- package/dist/chunk-IBA7DMIO.js +20 -0
- package/dist/chunk-IC6N4NZA.js +231 -0
- package/dist/chunk-IF43HIGV.js +284 -0
- package/dist/chunk-IGZ6C2MC.js +439 -0
- package/dist/chunk-IMLTL2MY.js +192 -0
- package/dist/chunk-IMZL6SGR.js +33 -0
- package/dist/chunk-IS4USJPY.js +516 -0
- package/dist/chunk-ISFSPN2F.js +82 -0
- package/dist/chunk-IXE7GTFI.js +55 -0
- package/dist/chunk-IZ77QJQG.js +36 -0
- package/dist/chunk-J2PACWRQ.js +34 -0
- package/dist/chunk-J6EGFVQX.js +180 -0
- package/dist/chunk-JEKOD43D.js +22 -0
- package/dist/chunk-JGIWATSG.js +30 -0
- package/dist/chunk-JYBONKD4.js +43 -0
- package/dist/chunk-K2NLG2HK.js +454 -0
- package/dist/chunk-KCQ4TBLS.js +164 -0
- package/dist/chunk-KD5KIVMS.js +176 -0
- package/dist/chunk-KHW6TX6I.js +63 -0
- package/dist/chunk-KI5GZFCE.js +520 -0
- package/dist/chunk-KN34B7NO.js +105 -0
- package/dist/chunk-KYUHIFP3.js +136 -0
- package/dist/chunk-KZL5VS4B.js +300 -0
- package/dist/chunk-L3VW3QIH.js +48 -0
- package/dist/chunk-LA6MG4ET.js +2110 -0
- package/dist/chunk-LAVFOA3S.js +66 -0
- package/dist/chunk-LB4OA77N.js +13 -0
- package/dist/chunk-LBFRF2K4.js +196 -0
- package/dist/chunk-LM6EIA4B.js +93 -0
- package/dist/chunk-LPCNRGJ7.js +692 -0
- package/dist/chunk-LSLNL5T3.js +168 -0
- package/dist/chunk-LVRRWP4W.js +568 -0
- package/dist/chunk-LWCFBRHL.js +33 -0
- package/dist/chunk-LXFTMGZZ.js +166 -0
- package/dist/chunk-M33LVA4M.js +151 -0
- package/dist/chunk-M3FO5UMK.js +4944 -0
- package/dist/chunk-M5QNDBAY.js +66 -0
- package/dist/chunk-M6ND6KBE.js +1291 -0
- package/dist/chunk-M7H3WQTE.js +76 -0
- package/dist/chunk-MCBRVPA7.js +191 -0
- package/dist/chunk-MCSDWZET.js +91 -0
- package/dist/chunk-MDT5XDXL.js +289 -0
- package/dist/chunk-MJG3IQY4.js +91 -0
- package/dist/chunk-MOU3N2UL.js +44 -0
- package/dist/chunk-MP4KZOQC.js +3451 -0
- package/dist/chunk-MPAJ446F.js +66 -0
- package/dist/chunk-MVJZZ6AL.js +16 -0
- package/dist/chunk-MXS6S2PY.js +253 -0
- package/dist/chunk-N3SFDYM7.js +291 -0
- package/dist/chunk-NAOX3JUB.js +13 -0
- package/dist/chunk-NEKKIBCX.js +283 -0
- package/dist/chunk-NKDATMEM.js +133 -0
- package/dist/chunk-NR4FMC4K.js +395 -0
- package/dist/chunk-NSOHOJBR.js +221 -0
- package/dist/chunk-NTDB6QKF.js +29 -0
- package/dist/chunk-NWEYRBWK.js +25 -0
- package/dist/chunk-O2YSNYWD.js +23 -0
- package/dist/chunk-O3EW7LAY.js +54 -0
- package/dist/chunk-O7BNJIXU.js +366 -0
- package/dist/chunk-OARL2NXZ.js +116 -0
- package/dist/chunk-OHKZUEJW.js +351 -0
- package/dist/chunk-OKU45BXA.js +647 -0
- package/dist/chunk-OL4JBD3J.js +59 -0
- package/dist/chunk-OLUO5DDR.js +192 -0
- package/dist/chunk-OQ245JLA.js +196 -0
- package/dist/chunk-P72UZAQI.js +289 -0
- package/dist/chunk-PAL2ENB6.js +20 -0
- package/dist/chunk-PAXYQZH7.js +53 -0
- package/dist/chunk-PDPEM5VW.js +51 -0
- package/dist/chunk-PEWCDI2C.js +668 -0
- package/dist/chunk-PGZ54EDX.js +27 -0
- package/dist/chunk-PRWVLDZF.js +73 -0
- package/dist/chunk-PSQQ75VJ.js +52 -0
- package/dist/chunk-PUOVIFHW.js +118 -0
- package/dist/chunk-PWBF2X3V.js +107 -0
- package/dist/chunk-PWXII6HF.js +43 -0
- package/dist/chunk-Q35VLJRT.js +80 -0
- package/dist/chunk-QJP7EYGL.js +128 -0
- package/dist/chunk-QPQKX2MK.js +8836 -0
- package/dist/chunk-QQRLPY25.js +1053 -0
- package/dist/chunk-QUS4ER2W.js +407 -0
- package/dist/chunk-QYHI3YET.js +29 -0
- package/dist/chunk-QYRU2UQI.js +32 -0
- package/dist/chunk-R6XVVQGC.js +13 -0
- package/dist/chunk-R7QN6ONS.js +483 -0
- package/dist/chunk-RD23MPGC.js +221 -0
- package/dist/chunk-RDDWQBEM.js +185 -0
- package/dist/chunk-RDLLDYFO.js +104 -0
- package/dist/chunk-RE4TGORR.js +84 -0
- package/dist/chunk-RJLHVYQY.js +217 -0
- package/dist/chunk-RJLPTWHW.js +905 -0
- package/dist/chunk-RKUVLRZI.js +295 -0
- package/dist/chunk-ROGXPGYR.js +37 -0
- package/dist/chunk-RSZGEL5U.js +163 -0
- package/dist/chunk-RVUOIJXN.js +909 -0
- package/dist/chunk-RW7F4JRP.js +11 -0
- package/dist/chunk-S4UO3AO3.js +53 -0
- package/dist/chunk-S5JAAF6S.js +585 -0
- package/dist/chunk-SNU37TQI.js +56 -0
- package/dist/chunk-SQVUDO2O.js +31 -0
- package/dist/chunk-SYVHIYQT.js +66 -0
- package/dist/chunk-SZBQMTG2.js +85 -0
- package/dist/chunk-T5VCXA3J.js +25 -0
- package/dist/chunk-TK6NSP56.js +30 -0
- package/dist/chunk-TKWVMA6L.js +22 -0
- package/dist/chunk-TQDKJHWX.js +59 -0
- package/dist/chunk-TQDM7S5N.js +127 -0
- package/dist/chunk-TULAXS77.js +23 -0
- package/dist/chunk-TVT45XNH.js +4625 -0
- package/dist/chunk-TWCVV2JO.js +467 -0
- package/dist/chunk-U4DKAD6S.js +47 -0
- package/dist/chunk-UA5K2BTI.js +564 -0
- package/dist/chunk-UAMKCMOK.js +40 -0
- package/dist/chunk-UBMVADBF.js +51 -0
- package/dist/chunk-UFQ5A5PW.js +645 -0
- package/dist/chunk-UOD2SOLL.js +1301 -0
- package/dist/chunk-UTSB4LOW.js +156 -0
- package/dist/chunk-UVXNIUTN.js +412 -0
- package/dist/chunk-UXVPXYPE.js +90 -0
- package/dist/chunk-UYEEMIWR.js +374 -0
- package/dist/chunk-VBGM5ZBW.js +54 -0
- package/dist/chunk-VEWPCZPG.js +762 -0
- package/dist/chunk-VIRDLZ5E.js +108 -0
- package/dist/chunk-VMPO7WKN.js +52 -0
- package/dist/chunk-W2NVSDO5.js +5122 -0
- package/dist/chunk-W3YYPBEA.js +176 -0
- package/dist/chunk-W5AYOICN.js +280 -0
- package/dist/chunk-W5GZOIUF.js +27 -0
- package/dist/chunk-WHKNLZ3C.js +76 -0
- package/dist/chunk-WKBEPPQ5.js +1409 -0
- package/dist/chunk-WM3Z6QKQ.js +151 -0
- package/dist/chunk-WMI2TPMA.js +31 -0
- package/dist/chunk-WNX5VD7S.js +150 -0
- package/dist/chunk-WOVTYST3.js +60 -0
- package/dist/chunk-WPB5WEZJ.js +546 -0
- package/dist/chunk-WUO5EOAT.js +44 -0
- package/dist/chunk-WWLJMP6D.js +133 -0
- package/dist/chunk-WZMLH3XP.js +58 -0
- package/dist/chunk-WZYVLUVQ.js +79 -0
- package/dist/chunk-X2OCPVU5.js +135 -0
- package/dist/chunk-X3CL6DTR.js +95 -0
- package/dist/chunk-X6WF7JEV.js +354 -0
- package/dist/chunk-XAHGBPWT.js +44 -0
- package/dist/chunk-XCKQ5BM2.js +228 -0
- package/dist/chunk-XIBYREEY.js +106 -0
- package/dist/chunk-XKW5NDMR.js +378 -0
- package/dist/chunk-XRDALAO3.js +100 -0
- package/dist/chunk-XUP22EAS.js +41 -0
- package/dist/chunk-XWAC3MKW.js +243 -0
- package/dist/chunk-Y3R7JMXB.js +59 -0
- package/dist/chunk-Y54LTP4W.js +82 -0
- package/dist/chunk-Y7UECI4M.js +99 -0
- package/dist/chunk-YACGDFHC.js +47 -0
- package/dist/chunk-YHNIQPKY.js +71 -0
- package/dist/chunk-YMBR6HYP.js +111 -0
- package/dist/chunk-YMCH3L2S.js +26 -0
- package/dist/chunk-Z4ZU6T7V.js +99 -0
- package/dist/chunk-ZDPF67ZZ.js +173 -0
- package/dist/chunk-ZFC2Q67K.js +101 -0
- package/dist/chunk-ZGHNNSCT.js +114 -0
- package/dist/chunk-ZGX3ERAT.js +173 -0
- package/dist/chunk-ZI3YHEBY.js +37 -0
- package/dist/chunk-ZN7G6JLS.js +639 -0
- package/dist/chunk-ZNPFQMXT.js +47 -0
- package/dist/chunk-ZOU3LV4U.js +63 -0
- package/dist/chunk-ZT7B4H2V.js +117 -0
- package/dist/chunk-ZZCBDNZI.js +58 -0
- package/dist/cli.js +498 -112593
- package/dist/computer-tools.js +36642 -21258
- package/dist/harness-catalog.cjs +88 -43
- package/dist/index.js +1 -1
- package/dist/local-model-supervisor.cjs +555 -0
- package/package.json +3 -4
|
@@ -0,0 +1,2440 @@
|
|
|
1
|
+
import { createRequire as __clikcodeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __clikcodeCreateRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
RUNTIME_BUILDS,
|
|
5
|
+
ensureRuntime,
|
|
6
|
+
noRuntimeReason,
|
|
7
|
+
selectRuntimeBuild
|
|
8
|
+
} from "./chunk-2QWPQRSU.js";
|
|
9
|
+
import {
|
|
10
|
+
discoverHuggingFaceModels,
|
|
11
|
+
ensureModelFile,
|
|
12
|
+
ensureModelWeights,
|
|
13
|
+
formatBytes,
|
|
14
|
+
missingBytes,
|
|
15
|
+
weightCapacityBytes,
|
|
16
|
+
weightFiles
|
|
17
|
+
} from "./chunk-IS4USJPY.js";
|
|
18
|
+
import {
|
|
19
|
+
defineTool
|
|
20
|
+
} from "./chunk-2BBELGHY.js";
|
|
21
|
+
import {
|
|
22
|
+
gatewayStepOptions
|
|
23
|
+
} from "./chunk-QYHI3YET.js";
|
|
24
|
+
import {
|
|
25
|
+
turnCancelledError
|
|
26
|
+
} from "./chunk-4LPDG57B.js";
|
|
27
|
+
import {
|
|
28
|
+
getApiKeyForUrl,
|
|
29
|
+
getApiUrl
|
|
30
|
+
} from "./chunk-TQDM7S5N.js";
|
|
31
|
+
import {
|
|
32
|
+
allLocalModels,
|
|
33
|
+
catalogModel
|
|
34
|
+
} from "./chunk-TQDKJHWX.js";
|
|
35
|
+
import {
|
|
36
|
+
gatewaySubscriptionsOn,
|
|
37
|
+
subscriptionsHeader
|
|
38
|
+
} from "./chunk-GQBZU6EO.js";
|
|
39
|
+
import {
|
|
40
|
+
footprintsFile,
|
|
41
|
+
localModelsHome,
|
|
42
|
+
measurementsFile,
|
|
43
|
+
preferencesFile,
|
|
44
|
+
safeName,
|
|
45
|
+
serversDir,
|
|
46
|
+
startCatalogRefresh
|
|
47
|
+
} from "./chunk-PEWCDI2C.js";
|
|
48
|
+
import {
|
|
49
|
+
harnessCommand
|
|
50
|
+
} from "./chunk-NWEYRBWK.js";
|
|
51
|
+
import {
|
|
52
|
+
sleep
|
|
53
|
+
} from "./chunk-YMCH3L2S.js";
|
|
54
|
+
import {
|
|
55
|
+
CLIKCODE_VERSION
|
|
56
|
+
} from "./chunk-NAOX3JUB.js";
|
|
57
|
+
import {
|
|
58
|
+
objectOrEmpty,
|
|
59
|
+
updateJsonFile
|
|
60
|
+
} from "./chunk-PAXYQZH7.js";
|
|
61
|
+
import {
|
|
62
|
+
pidIsAlive,
|
|
63
|
+
tryLease
|
|
64
|
+
} from "./chunk-4L2ZZM4Q.js";
|
|
65
|
+
import {
|
|
66
|
+
diagnostic,
|
|
67
|
+
lifecycle,
|
|
68
|
+
quiet
|
|
69
|
+
} from "./chunk-RDDWQBEM.js";
|
|
70
|
+
|
|
71
|
+
// src/local-models/read-budget.ts
|
|
72
|
+
var READING_SLOWDOWN_PER_TOKEN = 9e-5;
|
|
73
|
+
var WORKING_READ_SECONDS = 120;
|
|
74
|
+
function readableTokens(promptPerSecond, seconds = WORKING_READ_SECONDS) {
|
|
75
|
+
if (!(promptPerSecond > 0) || !(seconds > 0)) return 0;
|
|
76
|
+
const k = READING_SLOWDOWN_PER_TOKEN;
|
|
77
|
+
return Math.floor((Math.sqrt(1 + 2 * k * promptPerSecond * seconds) - 1) / k);
|
|
78
|
+
}
|
|
79
|
+
function localReadableTokens(measuredPromptPerSecond) {
|
|
80
|
+
return measuredPromptPerSecond && measuredPromptPerSecond > 0 ? readableTokens(measuredPromptPerSecond) : void 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/agent/on-demand-tools.ts
|
|
84
|
+
var LOAD_TOOLS = "load_tools";
|
|
85
|
+
var CORE_TOOLS = /* @__PURE__ */ new Set(["read_file", "grep", "glob", "bash", "apply_patch", "edit_file", "write_file", "ask_user", "skill", "read_context", "list_dir", "multi_edit", "todo_write", "enter_plan_mode", "exit_plan_mode", "notebook_edit"]);
|
|
86
|
+
function exposeSpecialists(tools, smallWindow = false) {
|
|
87
|
+
const core = smallWindow ? /* @__PURE__ */ new Set(["read_context"]) : CORE_TOOLS;
|
|
88
|
+
const deferred = tools.filter((tool) => !tool.mcp && !core.has(tool.name) && tool.name !== "load_mcp_tools" && tool.name !== LOAD_TOOLS);
|
|
89
|
+
if (!deferred.length) return { all: [...tools], advertised: (_items) => [...tools] };
|
|
90
|
+
const names = new Set(deferred.map((tool) => tool.name));
|
|
91
|
+
const loader = defineTool({
|
|
92
|
+
name: LOAD_TOOLS,
|
|
93
|
+
class: "meta",
|
|
94
|
+
description: `Load specialist tool schemas before using them. All loaded tools retain their normal permissions. Available: ${deferred.map((tool) => smallWindow ? tool.name : `${tool.name}: ${tool.description.split(/\n|\. |, /)[0].slice(0, 60)}`).join("; ")}`,
|
|
95
|
+
parameters: { type: "object", additionalProperties: false, required: ["tools"], properties: { tools: { type: "array", minItems: 1, items: { type: "string", enum: [...names] } } } },
|
|
96
|
+
label: (args) => `Load ${args.tools.join(", ")}`,
|
|
97
|
+
run: async (args) => {
|
|
98
|
+
const unknown = args.tools.filter((name) => !names.has(name));
|
|
99
|
+
return unknown.length ? { output: `Unknown tools: ${unknown.join(", ")}. Available: ${[...names].join(", ")}`, isError: true } : { output: `Loaded ${args.tools.join(", ")}. Their schemas are available on your next step.` };
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
const all = [...tools.filter((tool) => tool.name !== LOAD_TOOLS), loader];
|
|
103
|
+
return {
|
|
104
|
+
all,
|
|
105
|
+
advertised(items) {
|
|
106
|
+
const loaded = /* @__PURE__ */ new Set();
|
|
107
|
+
for (const item of items) {
|
|
108
|
+
if (item.type !== "tool_call") continue;
|
|
109
|
+
loaded.add(item.name);
|
|
110
|
+
if (item.name === LOAD_TOOLS && Array.isArray(item.args.tools)) {
|
|
111
|
+
for (const name of item.args.tools) if (typeof name === "string") loaded.add(name);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return all.filter((tool) => !names.has(tool.name) || loaded.has(tool.name));
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/agent/context-view.ts
|
|
120
|
+
var UNKNOWN_CONTEXT_WINDOW = 32768;
|
|
121
|
+
var MIN_CONTEXT_SCALE = 0.5;
|
|
122
|
+
var DEFAULT_OUTPUT_CEILING = 16384;
|
|
123
|
+
var ContextFitError = class extends Error {
|
|
124
|
+
constructor(inputTokens, contextWindow) {
|
|
125
|
+
super(`ClikCode's instructions, tools and your message need about ${inputTokens.toLocaleString()} tokens (counting room for a reply), but this model's context window is ${contextWindow.toLocaleString()}. A deployment of this model with a larger window (32,000 or more) fixes this, or pick another model. Your conversation is saved and nothing was cut. The counts are estimates.`);
|
|
126
|
+
this.inputTokens = inputTokens;
|
|
127
|
+
this.contextWindow = contextWindow;
|
|
128
|
+
}
|
|
129
|
+
inputTokens;
|
|
130
|
+
contextWindow;
|
|
131
|
+
code = "CONTEXT_BUDGET_EXCEEDED";
|
|
132
|
+
kind = "other";
|
|
133
|
+
};
|
|
134
|
+
function estimateRequestTokens(system, items, tools) {
|
|
135
|
+
let bytes = Buffer.byteLength(system) + Buffer.byteLength(JSON.stringify(tools));
|
|
136
|
+
let images = 0;
|
|
137
|
+
for (const item of items) {
|
|
138
|
+
if (item.type === "text" || item.type === "tool_result") {
|
|
139
|
+
const { images: pictures, ...text } = item;
|
|
140
|
+
bytes += Buffer.byteLength(JSON.stringify(text));
|
|
141
|
+
images += pictures?.length ?? 0;
|
|
142
|
+
} else bytes += Buffer.byteLength(JSON.stringify(item));
|
|
143
|
+
}
|
|
144
|
+
return Math.ceil(bytes / 3) + items.length * 8 + tools.length * 8 + images * 1600 + 32;
|
|
145
|
+
}
|
|
146
|
+
function responseReserve(window, maximum) {
|
|
147
|
+
return Math.min(maximum ?? 16384, Math.max(128, Math.floor(window / 5)));
|
|
148
|
+
}
|
|
149
|
+
function learnScale(current, reportedPromptTokens, estimate) {
|
|
150
|
+
if (!reportedPromptTokens || !(estimate > 0)) return current;
|
|
151
|
+
return Math.max(MIN_CONTEXT_SCALE, current * reportedPromptTokens / estimate * 1.1);
|
|
152
|
+
}
|
|
153
|
+
function outputRoom(window, requestTokens, ceiling) {
|
|
154
|
+
const left = window - requestTokens - Math.max(128, Math.ceil(window * 0.05));
|
|
155
|
+
return Math.max(128, Math.min(ceiling ?? DEFAULT_OUTPUT_CEILING, left));
|
|
156
|
+
}
|
|
157
|
+
function excerpt(text, limit, reference) {
|
|
158
|
+
if (text.length <= limit) return text;
|
|
159
|
+
const end = Math.floor(limit / 3);
|
|
160
|
+
return `${text.slice(0, limit - end)}
|
|
161
|
+
[Excerpt; read_context ${reference} for the complete text.]
|
|
162
|
+
${text.slice(-end)}`;
|
|
163
|
+
}
|
|
164
|
+
var HARNESS_NOTE = /^\[(?:background (?:agent|shell|task)\b|harness\]|Stop hook\]|SubagentStop hook\])/;
|
|
165
|
+
function isHarnessNote(item) {
|
|
166
|
+
return item.type === "text" && item.role === "user" && (item.source === "harness" || HARNESS_NOTE.test(item.text));
|
|
167
|
+
}
|
|
168
|
+
var isUserRequest = (item) => item.type === "text" && item.role === "user" && !isHarnessNote(item);
|
|
169
|
+
function groups(items) {
|
|
170
|
+
const result = [];
|
|
171
|
+
let latestUser = items.length - 1;
|
|
172
|
+
while (latestUser >= 0) {
|
|
173
|
+
const item = items[latestUser];
|
|
174
|
+
if (isUserRequest(item)) break;
|
|
175
|
+
latestUser--;
|
|
176
|
+
}
|
|
177
|
+
for (const [index, item] of items.entries()) {
|
|
178
|
+
const boundary = item.type === "summary" || item.type === "text" && item.role === "user";
|
|
179
|
+
const required = index === latestUser;
|
|
180
|
+
let group = result.at(-1);
|
|
181
|
+
const afterResult = group?.items.some((entry) => entry.type === "tool_result");
|
|
182
|
+
if (!group || boundary || group.required || group.items[0]?.type === "text" && group.items[0].role === "user" || afterResult && item.type !== "tool_result") {
|
|
183
|
+
group = { start: index, items: [], required };
|
|
184
|
+
result.push(group);
|
|
185
|
+
}
|
|
186
|
+
group.items.push(item);
|
|
187
|
+
}
|
|
188
|
+
return result;
|
|
189
|
+
}
|
|
190
|
+
function shrinkArgs(args, limit, reference) {
|
|
191
|
+
const cut = (value, depth) => {
|
|
192
|
+
if (typeof value === "string") return value.length > limit ? excerpt(value, limit, reference) : value;
|
|
193
|
+
if (depth >= 3) return value;
|
|
194
|
+
if (Array.isArray(value)) {
|
|
195
|
+
const kept = value.slice(0, 8).map((entry) => cut(entry, depth + 1));
|
|
196
|
+
return value.length > 8 ? [...kept, `[... ${value.length - 8} more; read_context ${reference} for all of them.]`] : kept;
|
|
197
|
+
}
|
|
198
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cut(entry, depth + 1)]));
|
|
199
|
+
return value;
|
|
200
|
+
};
|
|
201
|
+
return cut(args, 0);
|
|
202
|
+
}
|
|
203
|
+
function textOf(items) {
|
|
204
|
+
return items.map((item) => item.type === "text" || item.type === "summary" || item.type === "reasoning" ? item.text : item.type === "tool_result" ? item.output : JSON.stringify(item.args)).join("\n");
|
|
205
|
+
}
|
|
206
|
+
var TAIL_NOTE = "[Working context: older work in this conversation is outside this view, to keep the model's first read short. The current user request remains verbatim. Everything earlier remains in the retained history: use read_context to search it before relying on missing details. Excerpts are not complete evidence.]";
|
|
207
|
+
var TAIL_NOTE_ITEM = { type: "text", role: "assistant", text: TAIL_NOTE };
|
|
208
|
+
var TAIL_STEP_SHARE = 0.5;
|
|
209
|
+
var PIN_SHARE = 0.25;
|
|
210
|
+
function stableTail(input, windowBudget, readBudget, options = {}) {
|
|
211
|
+
const all = groups(input.items);
|
|
212
|
+
const requiredAt = all.findIndex((group) => group.required);
|
|
213
|
+
if (requiredAt < 0) return void 0;
|
|
214
|
+
const empty = estimateRequestTokens("", [], []);
|
|
215
|
+
const tokensOf = (items) => Math.ceil((estimateRequestTokens("", items, []) - empty) * input.scale);
|
|
216
|
+
const tokens = all.map((group) => tokensOf(group.items));
|
|
217
|
+
const before = [];
|
|
218
|
+
const itemsFrom = new Array(all.length + 1).fill(0);
|
|
219
|
+
let running = 0;
|
|
220
|
+
for (const index of all.keys()) {
|
|
221
|
+
before.push(running);
|
|
222
|
+
running += tokens[index];
|
|
223
|
+
}
|
|
224
|
+
for (let index = all.length - 1; index >= 0; index -= 1) itemsFrom[index] = itemsFrom[index + 1] + all[index].items.length;
|
|
225
|
+
const total = running;
|
|
226
|
+
const fixed = Math.ceil(estimateRequestTokens(input.system, [TAIL_NOTE_ITEM], input.tools) * input.scale);
|
|
227
|
+
const pinned = (from) => {
|
|
228
|
+
if (!options.pinRequests) return [];
|
|
229
|
+
const out = [];
|
|
230
|
+
let used = 0;
|
|
231
|
+
for (const group of all.slice(0, from)) {
|
|
232
|
+
const first = group.items[0];
|
|
233
|
+
if (!first || !isUserRequest(first)) continue;
|
|
234
|
+
const cost = tokensOf([first]);
|
|
235
|
+
if (used + cost > readBudget * PIN_SHARE) continue;
|
|
236
|
+
used += cost;
|
|
237
|
+
out.push(first);
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
};
|
|
241
|
+
const pinnedCost = (from) => tokensOf(pinned(from));
|
|
242
|
+
const tail = (from) => fixed + total - before[from] + (options.pinRequests ? pinnedCost(from) : 0);
|
|
243
|
+
const fits = (from) => tail(from) <= readBudget && itemsFrom[from] + 1 + pinned(from).length <= input.maxItems;
|
|
244
|
+
const step = Math.max(1, Math.floor(readBudget * TAIL_STEP_SHARE));
|
|
245
|
+
let cut = requiredAt;
|
|
246
|
+
let at = 0;
|
|
247
|
+
for (let grid = 1; ; grid += 1) {
|
|
248
|
+
while (at < requiredAt && before[at] < grid * step) at += 1;
|
|
249
|
+
if (at >= requiredAt) break;
|
|
250
|
+
if (fits(at)) {
|
|
251
|
+
cut = at;
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (tail(cut) > windowBudget) return void 0;
|
|
256
|
+
if (cut === 0) return { items: input.items, tools: input.tools, estimatedTokens: Math.ceil(estimateRequestTokens(input.system, input.items, input.tools) * input.scale), omittedGroups: 0 };
|
|
257
|
+
const kept = all.slice(cut).flatMap((group) => group.items);
|
|
258
|
+
const view = [...pinned(cut), TAIL_NOTE_ITEM, ...kept];
|
|
259
|
+
return { items: view, tools: input.tools, estimatedTokens: Math.ceil(estimateRequestTokens(input.system, view, input.tools) * input.scale), omittedGroups: cut };
|
|
260
|
+
}
|
|
261
|
+
function fitContext(input) {
|
|
262
|
+
const windowKnown = Boolean(input.window && input.window > 0);
|
|
263
|
+
const window = windowKnown ? input.window : UNKNOWN_CONTEXT_WINDOW;
|
|
264
|
+
const reserve = input.outputReserve ?? responseReserve(window);
|
|
265
|
+
const budget = Math.max(0, window - reserve - Math.max(128, Math.ceil(window * 0.05)));
|
|
266
|
+
const scale = Math.max(MIN_CONTEXT_SCALE, input.scale ?? 1);
|
|
267
|
+
const cost = (items, tools) => Math.ceil(estimateRequestTokens(input.system, items, tools) * scale);
|
|
268
|
+
const maxItems = input.maxItems ?? 1500;
|
|
269
|
+
const initial = cost(input.items, input.tools);
|
|
270
|
+
if (input.readBudget && input.readBudget > 0 && initial > input.readBudget) {
|
|
271
|
+
const tail = stableTail({ ...input, scale, maxItems }, budget, input.readBudget);
|
|
272
|
+
if (tail) return tail;
|
|
273
|
+
} else if ((initial > budget || input.items.length > maxItems) && budget > 0) {
|
|
274
|
+
const tail = stableTail({ ...input, scale, maxItems }, budget, budget, { pinRequests: true });
|
|
275
|
+
if (tail) return tail;
|
|
276
|
+
}
|
|
277
|
+
if (initial <= budget && input.items.length <= maxItems) return { items: input.items, tools: input.tools, estimatedTokens: initial, omittedGroups: 0 };
|
|
278
|
+
const all = groups(input.items);
|
|
279
|
+
const selected = new Set(all.filter((group) => group.required));
|
|
280
|
+
const optional = all.filter((group) => !group.required);
|
|
281
|
+
const last = optional.at(-1);
|
|
282
|
+
const taskStart = all.find((group) => group.required)?.start ?? -1;
|
|
283
|
+
const recent = [...optional].reverse();
|
|
284
|
+
if (last && last.start > taskStart) selected.add(last);
|
|
285
|
+
const latestEvidence = recent.find((group) => group.start > taskStart && group.items.some((item) => item.type === "tool_result"));
|
|
286
|
+
if (latestEvidence) selected.add(latestEvidence);
|
|
287
|
+
const latestReply = recent.find((group) => group.start > taskStart && group.items.some((item) => item.type === "text" && item.role === "assistant"));
|
|
288
|
+
if (latestReply) selected.add(latestReply);
|
|
289
|
+
const query = textOf(input.items.filter(isUserRequest).slice(-2)).toLowerCase();
|
|
290
|
+
const words = new Set((query.match(/[\p{L}\p{N}_./-]{3,}/gu) ?? []).slice(-128));
|
|
291
|
+
const ranked = optional.filter((group) => !selected.has(group)).map((group, index) => {
|
|
292
|
+
const text = textOf(group.items).toLowerCase();
|
|
293
|
+
let relevance = 0;
|
|
294
|
+
for (const word of words) if (text.includes(word)) relevance++;
|
|
295
|
+
return { group, score: (group.items.some(isUserRequest) ? 100 : 0) + relevance * 2 + index / Math.max(1, optional.length) };
|
|
296
|
+
}).sort((a, b) => b.score - a.score);
|
|
297
|
+
const prepare = (group, limit2) => group.items.map((item, offset) => {
|
|
298
|
+
if (group.required) return item;
|
|
299
|
+
const reference = item.type === "tool_result" ? `source=tool id=${JSON.stringify(item.id)}` : `source=history id="item:${group.start + offset}"`;
|
|
300
|
+
if (item.type === "tool_result") return { ...item, output: excerpt(item.output, limit2, reference) };
|
|
301
|
+
if (item.type === "text") return { ...item, text: excerpt(item.text, limit2, reference) };
|
|
302
|
+
if (item.type === "tool_call") return { ...item, args: shrinkArgs(item.args, limit2, reference) };
|
|
303
|
+
return item;
|
|
304
|
+
});
|
|
305
|
+
const materialize = (limit2) => {
|
|
306
|
+
const kept = all.filter((group) => selected.has(group));
|
|
307
|
+
const items = kept.flatMap((group) => prepare(group, limit2));
|
|
308
|
+
const referenced = new Set(items.flatMap((item) => item.type === "tool_call" ? [item.name] : []));
|
|
309
|
+
const essential = /* @__PURE__ */ new Set([...CORE_TOOLS, "load_tools", "load_mcp_tools", ...input.requiredTools ?? []]);
|
|
310
|
+
for (const item of last?.items ?? []) {
|
|
311
|
+
if (item.type === "tool_call" && (item.name === "load_tools" || item.name === "load_mcp_tools") && Array.isArray(item.args.tools)) {
|
|
312
|
+
for (const name of item.args.tools) if (typeof name === "string") essential.add(name);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const canReload = input.tools.some((tool) => tool.name === "load_tools" || tool.name === "load_mcp_tools");
|
|
316
|
+
const tools = input.tools.filter((tool) => !canReload || referenced.has(tool.name) || essential.has(tool.name));
|
|
317
|
+
const omitted = all.length - kept.length;
|
|
318
|
+
const note = { type: "text", role: "assistant", text: `[Working context: ${omitted} older work group(s) are outside this view. The current user request remains verbatim. Earlier requests and evidence remain in the retained history. Use read_context to search the complete retained history and tool results before relying on missing details. Excerpts are not complete evidence.]` };
|
|
319
|
+
return { items: omitted ? [note, ...items] : items, tools, omittedGroups: omitted };
|
|
320
|
+
};
|
|
321
|
+
let limit = Math.max(256, Math.min(4096, Math.floor(window / (4 * scale))));
|
|
322
|
+
let view = materialize(limit);
|
|
323
|
+
while ((cost(view.items, view.tools) > budget || view.items.length > maxItems) && limit > 256) {
|
|
324
|
+
limit = Math.max(256, Math.floor(limit / 2));
|
|
325
|
+
view = materialize(limit);
|
|
326
|
+
}
|
|
327
|
+
for (const group of [latestReply, latestEvidence, last]) {
|
|
328
|
+
if (!(cost(view.items, view.tools) > budget || view.items.length > maxItems)) break;
|
|
329
|
+
if (!group || group.required || !selected.has(group)) continue;
|
|
330
|
+
selected.delete(group);
|
|
331
|
+
view = materialize(limit);
|
|
332
|
+
}
|
|
333
|
+
if (windowKnown && (cost(view.items, view.tools) > budget || view.items.length > maxItems)) throw new ContextFitError(cost(view.items, view.tools) + reserve, window);
|
|
334
|
+
let used = cost(view.items, view.tools);
|
|
335
|
+
let count = view.items.length;
|
|
336
|
+
const declared = new Set(view.tools.map((tool) => tool.name));
|
|
337
|
+
const empty = estimateRequestTokens("", [], []);
|
|
338
|
+
for (const { group } of ranked) {
|
|
339
|
+
const items = prepare(group, limit);
|
|
340
|
+
const referenced = new Set(items.flatMap((item) => item.type === "tool_call" ? [item.name] : []));
|
|
341
|
+
const addedTools = input.tools.filter((tool) => referenced.has(tool.name) && !declared.has(tool.name));
|
|
342
|
+
const extra = Math.ceil((estimateRequestTokens("", items, addedTools) - empty + 4) * scale);
|
|
343
|
+
if (count + items.length <= maxItems && used + extra <= budget) {
|
|
344
|
+
selected.add(group);
|
|
345
|
+
used += extra;
|
|
346
|
+
count += items.length;
|
|
347
|
+
for (const tool of addedTools) declared.add(tool.name);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
view = materialize(limit);
|
|
351
|
+
return { ...view, estimatedTokens: cost(view.items, view.tools) };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// src/agent/models/gateway-client.ts
|
|
355
|
+
var GATEWAY_KEEPALIVE_MS = 15e3;
|
|
356
|
+
var STREAM_IDLE_TIMEOUT_MS = GATEWAY_KEEPALIVE_MS * 8;
|
|
357
|
+
var OBSERVED_GAP_MULTIPLE = 4;
|
|
358
|
+
function streamSilenceLimit(base, longestGapMs) {
|
|
359
|
+
return Math.max(base, OBSERVED_GAP_MULTIPLE * longestGapMs);
|
|
360
|
+
}
|
|
361
|
+
async function readWithin(reader, ms, label) {
|
|
362
|
+
if (!ms || ms <= 0) return reader.read();
|
|
363
|
+
let timer;
|
|
364
|
+
try {
|
|
365
|
+
return await Promise.race([
|
|
366
|
+
reader.read(),
|
|
367
|
+
new Promise((_resolve, reject) => {
|
|
368
|
+
timer = setTimeout(() => reject(new ModelClientError(`${label} sent nothing for ${Math.round(ms / 1e3)}s; the connection was dropped`, { kind: "other", code: "incomplete_stream" })), ms);
|
|
369
|
+
})
|
|
370
|
+
]);
|
|
371
|
+
} finally {
|
|
372
|
+
if (timer) clearTimeout(timer);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
var ModelClientError = class extends Error {
|
|
376
|
+
kind;
|
|
377
|
+
statusCode;
|
|
378
|
+
code;
|
|
379
|
+
/** Seconds. */
|
|
380
|
+
retryAfter;
|
|
381
|
+
constructor(message, details) {
|
|
382
|
+
super(message);
|
|
383
|
+
this.name = "ModelClientError";
|
|
384
|
+
this.kind = details.kind;
|
|
385
|
+
if (details.statusCode !== void 0) this.statusCode = details.statusCode;
|
|
386
|
+
if (details.code !== void 0) this.code = details.code;
|
|
387
|
+
if (details.retryAfter !== void 0) this.retryAfter = details.retryAfter;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
391
|
+
if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
392
|
+
if (typeof value !== "string" || !value.trim()) return void 0;
|
|
393
|
+
if (/^\d+(?:\.\d+)?$/.test(value.trim())) return Number(value.trim());
|
|
394
|
+
const date = Date.parse(value);
|
|
395
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
|
|
396
|
+
}
|
|
397
|
+
var SseParser = class {
|
|
398
|
+
decoder = new TextDecoder("utf-8");
|
|
399
|
+
buffer = "";
|
|
400
|
+
data = [];
|
|
401
|
+
event;
|
|
402
|
+
sawBom = false;
|
|
403
|
+
push(chunk) {
|
|
404
|
+
this.buffer += typeof chunk === "string" ? chunk : this.decoder.decode(chunk, { stream: true });
|
|
405
|
+
if (!this.sawBom) {
|
|
406
|
+
this.sawBom = true;
|
|
407
|
+
if (this.buffer.charCodeAt(0) === 65279) this.buffer = this.buffer.slice(1);
|
|
408
|
+
}
|
|
409
|
+
const events = [];
|
|
410
|
+
for (; ; ) {
|
|
411
|
+
const match = /\r\n|\n|\r/.exec(this.buffer);
|
|
412
|
+
if (!match) break;
|
|
413
|
+
if (match[0] === "\r" && match.index === this.buffer.length - 1) break;
|
|
414
|
+
const line = this.buffer.slice(0, match.index);
|
|
415
|
+
this.buffer = this.buffer.slice(match.index + match[0].length);
|
|
416
|
+
const event = this.line(line);
|
|
417
|
+
if (event) events.push(event);
|
|
418
|
+
}
|
|
419
|
+
return events;
|
|
420
|
+
}
|
|
421
|
+
/** End of stream: an unterminated final event is still delivered. */
|
|
422
|
+
flush() {
|
|
423
|
+
this.buffer += this.decoder.decode();
|
|
424
|
+
const events = [];
|
|
425
|
+
if (this.buffer) {
|
|
426
|
+
const event = this.line(this.buffer.replace(/\r$/, ""));
|
|
427
|
+
if (event) events.push(event);
|
|
428
|
+
this.buffer = "";
|
|
429
|
+
}
|
|
430
|
+
const last = this.line("");
|
|
431
|
+
if (last) events.push(last);
|
|
432
|
+
return events;
|
|
433
|
+
}
|
|
434
|
+
line(line) {
|
|
435
|
+
if (line === "") {
|
|
436
|
+
if (!this.data.length) {
|
|
437
|
+
this.event = void 0;
|
|
438
|
+
return void 0;
|
|
439
|
+
}
|
|
440
|
+
const event = { data: this.data.join("\n"), ...this.event ? { event: this.event } : {} };
|
|
441
|
+
this.data = [];
|
|
442
|
+
this.event = void 0;
|
|
443
|
+
return event;
|
|
444
|
+
}
|
|
445
|
+
if (line.startsWith(":")) return void 0;
|
|
446
|
+
const colon = line.indexOf(":");
|
|
447
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
448
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
449
|
+
if (field === "data") this.data.push(value);
|
|
450
|
+
else if (field === "event") this.event = value;
|
|
451
|
+
return void 0;
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
// src/agent/models/openai-client.ts
|
|
456
|
+
var FIRST_CHUNK_TIMEOUT_MS = 30 * 6e4;
|
|
457
|
+
function toChatMessages(system, items, vision, model) {
|
|
458
|
+
const out = [{ role: "system", content: system }];
|
|
459
|
+
const pushUser = (text, images = []) => {
|
|
460
|
+
const parts = [{ type: "text", text }, ...vision ? images.map((image) => ({ type: "image_url", image_url: { url: `data:${image.mimeType};base64,${image.data}` } })) : []];
|
|
461
|
+
const last = out[out.length - 1];
|
|
462
|
+
if (last?.role === "user") {
|
|
463
|
+
const previous = typeof last.content === "string" ? [{ type: "text", text: last.content }] : last.content;
|
|
464
|
+
last.content = [...previous, ...parts];
|
|
465
|
+
} else out.push({ role: "user", content: parts });
|
|
466
|
+
};
|
|
467
|
+
const assistant = () => {
|
|
468
|
+
const last = out[out.length - 1];
|
|
469
|
+
if (last?.role === "assistant") return last;
|
|
470
|
+
const created = { role: "assistant", content: null };
|
|
471
|
+
out.push(created);
|
|
472
|
+
return created;
|
|
473
|
+
};
|
|
474
|
+
let toolImages = [];
|
|
475
|
+
const flushToolImages = () => {
|
|
476
|
+
if (!toolImages.length) return;
|
|
477
|
+
const shown = toolImages;
|
|
478
|
+
toolImages = [];
|
|
479
|
+
pushUser(`[${shown.length === 1 ? "Image" : "Images"} from the tool results above: ${shown.map((image, index) => image.name ?? `image ${index + 1}`).join(", ")}]`, shown);
|
|
480
|
+
};
|
|
481
|
+
for (const item of items) {
|
|
482
|
+
if (item.type !== "tool_result") flushToolImages();
|
|
483
|
+
if (item.type === "summary") pushUser(`Summary of the earlier conversation:
|
|
484
|
+
${item.text}`);
|
|
485
|
+
else if (item.type === "reasoning") {
|
|
486
|
+
if (item.model !== model) continue;
|
|
487
|
+
const detail = item.redactedData ? { type: "reasoning.encrypted", data: item.redactedData } : item.signature ? { type: "reasoning.text", text: item.text, signature: item.signature } : void 0;
|
|
488
|
+
if (detail) (assistant().reasoning_details ??= []).push(detail);
|
|
489
|
+
} else if (item.type === "text" && item.role === "user") pushUser(item.text, item.images);
|
|
490
|
+
else if (item.type === "text") {
|
|
491
|
+
const message = assistant();
|
|
492
|
+
if (message.tool_calls?.length) out.push({ role: "assistant", content: item.text });
|
|
493
|
+
else message.content = message.content ? `${message.content}
|
|
494
|
+
|
|
495
|
+
${item.text}` : item.text;
|
|
496
|
+
} else if (item.type === "tool_call") {
|
|
497
|
+
const message = assistant();
|
|
498
|
+
(message.tool_calls ??= []).push({ id: item.id, type: "function", function: { name: item.name, arguments: JSON.stringify(item.args) } });
|
|
499
|
+
} else {
|
|
500
|
+
out.push({ role: "tool", tool_call_id: item.id, content: item.isError ? `Error: ${item.output}` : item.output });
|
|
501
|
+
if (vision && item.images?.length) toolImages.push(...item.images);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
flushToolImages();
|
|
505
|
+
for (const message of out) {
|
|
506
|
+
if (message.role === "user" && Array.isArray(message.content) && message.content.every((part) => part.type === "text")) {
|
|
507
|
+
message.content = message.content.map((part) => part.text).join("\n\n");
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return out;
|
|
511
|
+
}
|
|
512
|
+
function toolsBody(tools, toolChoice) {
|
|
513
|
+
if (!tools.length) return {};
|
|
514
|
+
return {
|
|
515
|
+
tools: tools.map((tool) => ({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } })),
|
|
516
|
+
...toolChoice ? { tool_choice: toolChoice } : {}
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
function parseToolArguments(raw) {
|
|
520
|
+
const text = raw.trim();
|
|
521
|
+
if (!text) return { args: {} };
|
|
522
|
+
const attempts = [text, text.replace(/^```(?:json)?\s*|\s*```$/g, "").replace(/,\s*([}\]])/g, "$1")];
|
|
523
|
+
let failure = "";
|
|
524
|
+
for (const attempt of attempts) {
|
|
525
|
+
try {
|
|
526
|
+
const value = JSON.parse(attempt);
|
|
527
|
+
const parsed = typeof value === "string" ? JSON.parse(value) : value;
|
|
528
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return { args: parsed };
|
|
529
|
+
failure = `got ${Array.isArray(parsed) ? "an array" : parsed === null ? "null" : typeof parsed}`;
|
|
530
|
+
} catch (error) {
|
|
531
|
+
failure ||= error instanceof Error ? error.message : String(error);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return { args: {}, error: `${failure}; received: ${text.length > 300 ? `${text.slice(0, 300)}\u2026` : text}` };
|
|
535
|
+
}
|
|
536
|
+
function completedArguments(raw) {
|
|
537
|
+
const text = raw.trim();
|
|
538
|
+
if (!text.startsWith("{")) return {};
|
|
539
|
+
const whole = parseToolArguments(text);
|
|
540
|
+
if (!whole.error) return whole.args;
|
|
541
|
+
const ends = [];
|
|
542
|
+
let depth = 0;
|
|
543
|
+
let inString = false;
|
|
544
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
545
|
+
const char = text[index];
|
|
546
|
+
if (inString) {
|
|
547
|
+
if (char === "\\") index += 1;
|
|
548
|
+
else if (char === '"') inString = false;
|
|
549
|
+
} else if (char === '"') inString = true;
|
|
550
|
+
else if (char === "{" || char === "[") depth += 1;
|
|
551
|
+
else if (char === "}" || char === "]") depth -= 1;
|
|
552
|
+
else if (char === "," && depth === 1) ends.push(index);
|
|
553
|
+
}
|
|
554
|
+
for (const end of ends.reverse()) {
|
|
555
|
+
try {
|
|
556
|
+
const value = JSON.parse(`${text.slice(0, end)}}`);
|
|
557
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value;
|
|
558
|
+
} catch {
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return {};
|
|
562
|
+
}
|
|
563
|
+
var STOP_REASONS = { stop: "stop", tool_calls: "tool-calls", function_call: "tool-calls", length: "length", content_filter: "content-filter" };
|
|
564
|
+
function isContextOverflow(status, code, message) {
|
|
565
|
+
if (code === "context_length_exceeded" || code === "exceed_context_size_error") return true;
|
|
566
|
+
return status === 400 && /context (?:length|size|window)|maximum context|too many tokens|exceeds? the available context/i.test(message);
|
|
567
|
+
}
|
|
568
|
+
var QUOTA_CODES = /* @__PURE__ */ new Set(["insufficient_quota", "insufficient_credits"]);
|
|
569
|
+
var AUTH_CODES = /* @__PURE__ */ new Set(["invalid_api_key", "authentication_error", "unauthorized", "invalid_token"]);
|
|
570
|
+
var THROTTLE_CODES = /* @__PURE__ */ new Set(["rate_limit_exceeded", "rate_limit_error"]);
|
|
571
|
+
function numberOf(value) {
|
|
572
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
573
|
+
}
|
|
574
|
+
var InlineThinkFilter = class {
|
|
575
|
+
buffer = "";
|
|
576
|
+
thinking = false;
|
|
577
|
+
push(chunk, onText) {
|
|
578
|
+
this.buffer += chunk;
|
|
579
|
+
for (; ; ) {
|
|
580
|
+
if (this.thinking) {
|
|
581
|
+
const end = this.buffer.indexOf("</think>");
|
|
582
|
+
if (end >= 0) {
|
|
583
|
+
this.buffer = this.buffer.slice(end + "</think>".length);
|
|
584
|
+
this.thinking = false;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
const keep2 = this.suffixPrefixLength(this.buffer, "</think>");
|
|
588
|
+
const safe2 = this.buffer.slice(0, this.buffer.length - keep2);
|
|
589
|
+
this.buffer = this.buffer.slice(safe2.length);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const start = this.buffer.indexOf("<think>");
|
|
593
|
+
if (start >= 0) {
|
|
594
|
+
if (start) onText(this.buffer.slice(0, start));
|
|
595
|
+
this.buffer = this.buffer.slice(start + "<think>".length);
|
|
596
|
+
this.thinking = true;
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
const keep = this.suffixPrefixLength(this.buffer, "<think>");
|
|
600
|
+
const safe = this.buffer.slice(0, this.buffer.length - keep);
|
|
601
|
+
if (safe) onText(safe);
|
|
602
|
+
this.buffer = this.buffer.slice(safe.length);
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
/** Flush ordinary trailing text; an unterminated reasoning block stays hidden. */
|
|
607
|
+
finish(onText) {
|
|
608
|
+
if (!this.thinking && this.buffer) onText(this.buffer);
|
|
609
|
+
this.buffer = "";
|
|
610
|
+
}
|
|
611
|
+
suffixPrefixLength(text, token) {
|
|
612
|
+
const max = Math.min(text.length, token.length - 1);
|
|
613
|
+
for (let size = max; size > 0; size--) if (text.endsWith(token.slice(0, size))) return size;
|
|
614
|
+
return 0;
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
var OpenAIModelClient = class {
|
|
618
|
+
constructor(options) {
|
|
619
|
+
this.options = options;
|
|
620
|
+
this.acceptsImages = options.vision === true;
|
|
621
|
+
this.contextHints = {
|
|
622
|
+
...options.hosted ? { hosted: true } : {},
|
|
623
|
+
...options.contextWindow ? { contextWindow: options.contextWindow } : {},
|
|
624
|
+
...options.promptPerSecond ? { promptPerSecond: options.promptPerSecond } : {},
|
|
625
|
+
...options.readableTokens ? { readableTokens: options.readableTokens } : {}
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
options;
|
|
629
|
+
/** Set by the Gateway client (for-session.ts): how the start of the user's own model is going. */
|
|
630
|
+
startStatus;
|
|
631
|
+
acceptsImages;
|
|
632
|
+
contextHints;
|
|
633
|
+
/** The window the server said it serves, from an earlier step. */
|
|
634
|
+
servedWindow;
|
|
635
|
+
get label() {
|
|
636
|
+
return this.options.label ?? "The model server";
|
|
637
|
+
}
|
|
638
|
+
/** `max_tokens` for this request: the room the caller worked out, within the model's own limit. The caller (the
|
|
639
|
+
* agent loop) has already fitted the request to the window; this does not judge it again and refuse. A caller that
|
|
640
|
+
* worked out no room gets what is left of the window. */
|
|
641
|
+
maxTokens(request) {
|
|
642
|
+
const ceiling = this.options.maxOutputTokens;
|
|
643
|
+
if (request.maxOutputTokens !== void 0) return Math.min(request.maxOutputTokens, ceiling ?? Infinity);
|
|
644
|
+
const window = this.servedWindow ?? this.options.contextWindow;
|
|
645
|
+
if (!window) return ceiling;
|
|
646
|
+
return outputRoom(window, estimateRequestTokens(request.system, request.items, request.tools), ceiling);
|
|
647
|
+
}
|
|
648
|
+
describe(message, details) {
|
|
649
|
+
return this.options.describeError?.({ ...details, message }) ?? message;
|
|
650
|
+
}
|
|
651
|
+
endpoint() {
|
|
652
|
+
const base = this.options.baseUrl.replace(/\/+$/, "");
|
|
653
|
+
return `${base.endsWith("/v1") ? base : `${base}/v1`}/chat/completions`;
|
|
654
|
+
}
|
|
655
|
+
async step(request) {
|
|
656
|
+
const { options } = this;
|
|
657
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
658
|
+
const messages = toChatMessages(request.system, request.items, this.acceptsImages, options.model);
|
|
659
|
+
const tools = toolsBody(request.tools, request.toolChoice);
|
|
660
|
+
const maxTokens = this.maxTokens(request);
|
|
661
|
+
let response;
|
|
662
|
+
const requestedAt = Date.now();
|
|
663
|
+
try {
|
|
664
|
+
response = await doFetch(this.endpoint(), {
|
|
665
|
+
method: "POST",
|
|
666
|
+
headers: {
|
|
667
|
+
accept: "text/event-stream",
|
|
668
|
+
"content-type": "application/json",
|
|
669
|
+
...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {},
|
|
670
|
+
...options.headers
|
|
671
|
+
},
|
|
672
|
+
body: JSON.stringify({
|
|
673
|
+
...options.body,
|
|
674
|
+
model: options.model,
|
|
675
|
+
messages,
|
|
676
|
+
...tools,
|
|
677
|
+
stream: true,
|
|
678
|
+
// Without this OpenAI sends no usage at all on a stream; servers that
|
|
679
|
+
// report usage anyway (llama-server) accept and ignore it.
|
|
680
|
+
stream_options: { include_usage: true },
|
|
681
|
+
...maxTokens ? { max_tokens: maxTokens } : {}
|
|
682
|
+
}),
|
|
683
|
+
...request.signal ? { signal: request.signal } : {}
|
|
684
|
+
});
|
|
685
|
+
} catch (error) {
|
|
686
|
+
if (request.signal?.aborted) throw turnCancelledError();
|
|
687
|
+
lifecycle("model.request", { label: this.label, model: options.model, ms: Date.now() - requestedAt, outcome: "unreachable" });
|
|
688
|
+
throw new ModelClientError(`Could not reach ${this.label} at ${options.baseUrl}: ${error instanceof Error ? error.message : String(error)}`, { kind: "other" });
|
|
689
|
+
}
|
|
690
|
+
lifecycle("model.request", { label: this.label, model: options.model, status: response.status, ms: Date.now() - requestedAt });
|
|
691
|
+
if (!response.ok) throw await this.httpError(response);
|
|
692
|
+
const requestId = response.headers.get("x-request-id")?.trim() || void 0;
|
|
693
|
+
const withRequestId = (message) => requestId ? `${message} [request ${requestId}]` : message;
|
|
694
|
+
if (!response.body) throw new ModelClientError(`${this.label} returned an empty response`, { kind: "other", statusCode: response.status });
|
|
695
|
+
const parser = new SseParser();
|
|
696
|
+
let text = "";
|
|
697
|
+
const pending = [];
|
|
698
|
+
const byIndex = /* @__PURE__ */ new Map();
|
|
699
|
+
let usage = {};
|
|
700
|
+
let stopReason;
|
|
701
|
+
let done = false;
|
|
702
|
+
let servedModel;
|
|
703
|
+
let servedWindow;
|
|
704
|
+
let timings;
|
|
705
|
+
const blocks = [];
|
|
706
|
+
const inlineThink = options.privateReasoning ? new InlineThinkFilter() : void 0;
|
|
707
|
+
const emitText = (chunk) => {
|
|
708
|
+
if (chunk) {
|
|
709
|
+
text += chunk;
|
|
710
|
+
request.onTextDelta(chunk);
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
const handle = (event) => {
|
|
714
|
+
if (!event.data) return;
|
|
715
|
+
if (event.data.trim() === "[DONE]") {
|
|
716
|
+
done = true;
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
let frame;
|
|
720
|
+
try {
|
|
721
|
+
frame = JSON.parse(event.data);
|
|
722
|
+
} catch {
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (!frame || typeof frame !== "object") return;
|
|
726
|
+
if (frame.error) {
|
|
727
|
+
const error = typeof frame.error === "object" ? frame.error : { message: frame.error };
|
|
728
|
+
const message = typeof error.message === "string" && error.message ? error.message : `${this.label} reported an error`;
|
|
729
|
+
const code = typeof error.code === "string" ? error.code : typeof error.type === "string" ? error.type : void 0;
|
|
730
|
+
const loopCode = isContextOverflow(400, code, message) ? "CONTEXT_TOO_LARGE" : code && THROTTLE_CODES.has(code) ? "MODEL_RATE_LIMITED" : code ? options.errorCodes?.[code] : void 0;
|
|
731
|
+
const retryAfter = parseRetryAfter(error.retry_after);
|
|
732
|
+
const kind = code && QUOTA_CODES.has(code) ? "quota" : code && AUTH_CODES.has(code) ? "auth" : "other";
|
|
733
|
+
const described = this.describe(`${this.label}: ${message}`, { ...code ? { code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} });
|
|
734
|
+
throw new ModelClientError(withRequestId(described), { kind, ...loopCode ? { code: loopCode } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} });
|
|
735
|
+
}
|
|
736
|
+
const window = numberOf(frame.context_window) ?? numberOf(frame.context_length);
|
|
737
|
+
if (window) {
|
|
738
|
+
servedWindow = window;
|
|
739
|
+
this.servedWindow = window;
|
|
740
|
+
}
|
|
741
|
+
if (typeof frame.model === "string" && frame.model && frame.model !== servedModel) {
|
|
742
|
+
servedModel = frame.model;
|
|
743
|
+
request.onServedModel?.(servedModel, servedWindow);
|
|
744
|
+
}
|
|
745
|
+
if (frame.usage && typeof frame.usage === "object") usage = { ...usage, ...usageFrom(frame.usage) };
|
|
746
|
+
if (frame.timings && typeof frame.timings === "object") timings = frame.timings;
|
|
747
|
+
const choice = Array.isArray(frame.choices) ? frame.choices[0] : void 0;
|
|
748
|
+
if (!choice) return;
|
|
749
|
+
const delta = choice.delta && typeof choice.delta === "object" ? choice.delta : {};
|
|
750
|
+
if (typeof delta.content === "string" && delta.content) {
|
|
751
|
+
if (inlineThink) inlineThink.push(delta.content, emitText);
|
|
752
|
+
else emitText(delta.content);
|
|
753
|
+
}
|
|
754
|
+
const reasoning = typeof delta.reasoning_content === "string" ? delta.reasoning_content : typeof delta.reasoning === "string" ? delta.reasoning : "";
|
|
755
|
+
if (reasoning && !options.privateReasoning) request.onReasoningDelta?.(reasoning);
|
|
756
|
+
if (Array.isArray(delta.reasoning_details)) {
|
|
757
|
+
for (const raw of delta.reasoning_details) {
|
|
758
|
+
if (!raw || typeof raw !== "object") continue;
|
|
759
|
+
if (raw.type === "reasoning.encrypted" && typeof raw.data === "string" && raw.data) blocks.push({ text: "", redactedData: raw.data, model: options.model });
|
|
760
|
+
else if (raw.type === "reasoning.text" && typeof raw.signature === "string" && raw.signature) blocks.push({ text: typeof raw.text === "string" ? raw.text : "", signature: raw.signature, model: options.model });
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
764
|
+
for (const raw of delta.tool_calls) {
|
|
765
|
+
if (!raw || typeof raw !== "object") continue;
|
|
766
|
+
const fn = raw.function && typeof raw.function === "object" ? raw.function : {};
|
|
767
|
+
const id = typeof raw.id === "string" && raw.id ? raw.id : void 0;
|
|
768
|
+
const index = numberOf(raw.index);
|
|
769
|
+
let call = index !== void 0 ? byIndex.get(index) : (id ? pending.find((entry) => entry.id === id) : void 0) ?? (id ? void 0 : pending[pending.length - 1]);
|
|
770
|
+
if (!call) {
|
|
771
|
+
call = { name: "", arguments: "" };
|
|
772
|
+
pending.push(call);
|
|
773
|
+
if (index !== void 0) byIndex.set(index, call);
|
|
774
|
+
}
|
|
775
|
+
if (id && !call.id) call.id = id;
|
|
776
|
+
if (typeof fn.name === "string" && fn.name && call.name !== fn.name) call.name = call.name && !fn.name.startsWith(call.name) ? `${call.name}${fn.name}` : fn.name;
|
|
777
|
+
if (typeof fn.arguments === "string") call.arguments += fn.arguments;
|
|
778
|
+
else if (fn.arguments && typeof fn.arguments === "object" && !Array.isArray(fn.arguments)) call.argsObject = fn.arguments;
|
|
779
|
+
if (call.name && request.onToolCallDelta) {
|
|
780
|
+
call.shownId ??= call.id ?? `call_${pending.indexOf(call) + 1}_${Date.now().toString(36)}`;
|
|
781
|
+
request.onToolCallDelta({ id: call.shownId, name: call.name, arguments: call.argsObject && !call.arguments.trim() ? JSON.stringify(call.argsObject) : call.arguments });
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (typeof choice.finish_reason === "string" && choice.finish_reason) stopReason = STOP_REASONS[choice.finish_reason] ?? choice.finish_reason;
|
|
786
|
+
};
|
|
787
|
+
const reader = response.body.getReader();
|
|
788
|
+
try {
|
|
789
|
+
let started = false;
|
|
790
|
+
let longestGap = 0;
|
|
791
|
+
for (; ; ) {
|
|
792
|
+
const base = started ? options.idleTimeoutMs ?? STREAM_IDLE_TIMEOUT_MS : options.firstChunkTimeoutMs ?? FIRST_CHUNK_TIMEOUT_MS;
|
|
793
|
+
const limit = started ? streamSilenceLimit(base, longestGap) : base;
|
|
794
|
+
const readAt = Date.now();
|
|
795
|
+
const { done: ended, value } = await readWithin(reader, limit, this.label);
|
|
796
|
+
if (started) longestGap = Math.max(longestGap, Date.now() - readAt);
|
|
797
|
+
started = true;
|
|
798
|
+
if (ended) break;
|
|
799
|
+
if (value) for (const event of parser.push(value)) handle(event);
|
|
800
|
+
}
|
|
801
|
+
for (const event of parser.flush()) handle(event);
|
|
802
|
+
} catch (error) {
|
|
803
|
+
await reader.cancel().catch(quiet("agent/models/openai-client"));
|
|
804
|
+
if (request.signal?.aborted) throw turnCancelledError();
|
|
805
|
+
if (error instanceof ModelClientError) throw error;
|
|
806
|
+
throw new ModelClientError(`${this.label} stream failed: ${error instanceof Error ? error.message : String(error)}`, { kind: "other" });
|
|
807
|
+
}
|
|
808
|
+
inlineThink?.finish(emitText);
|
|
809
|
+
if (stopReason === void 0 && !done) throw new ModelClientError(`${this.label} stream ended before the answer finished`, { kind: "other", code: "incomplete_stream" });
|
|
810
|
+
if (timings) {
|
|
811
|
+
const prompt = numberOf(timings.prompt_n);
|
|
812
|
+
const cached = numberOf(timings.cache_n);
|
|
813
|
+
if (usage.input === void 0 && prompt !== void 0) usage.input = prompt + (cached ?? 0);
|
|
814
|
+
if (usage.output === void 0 && numberOf(timings.predicted_n) !== void 0) usage.output = timings.predicted_n;
|
|
815
|
+
if (usage.cached === void 0 && cached) usage.cached = cached;
|
|
816
|
+
}
|
|
817
|
+
const toolCalls = pending.filter((call) => call.name).map((call, offset) => {
|
|
818
|
+
const id = call.shownId ?? call.id ?? `call_${offset + 1}_${Date.now().toString(36)}`;
|
|
819
|
+
if (call.argsObject && !call.arguments.trim()) return { id, name: call.name, args: call.argsObject };
|
|
820
|
+
const parsed = parseToolArguments(call.arguments);
|
|
821
|
+
return { id, name: call.name, args: parsed.args, ...parsed.error ? { argumentsError: parsed.error } : {} };
|
|
822
|
+
});
|
|
823
|
+
return {
|
|
824
|
+
text,
|
|
825
|
+
toolCalls,
|
|
826
|
+
stopReason: stopReason ?? (toolCalls.length ? "tool-calls" : "stop"),
|
|
827
|
+
usage,
|
|
828
|
+
...blocks.length ? { reasoning: blocks } : {},
|
|
829
|
+
...servedModel ? { servedModel } : {},
|
|
830
|
+
...servedWindow ?? options.contextWindow ? { contextWindow: servedWindow ?? options.contextWindow } : {}
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
async httpError(response) {
|
|
834
|
+
const status = response.status;
|
|
835
|
+
let message = `${this.label} returned HTTP ${status}`;
|
|
836
|
+
let code;
|
|
837
|
+
let retryAfter = parseRetryAfter(response.headers.get("retry-after"));
|
|
838
|
+
let raw = "";
|
|
839
|
+
try {
|
|
840
|
+
raw = await response.text();
|
|
841
|
+
} catch {
|
|
842
|
+
}
|
|
843
|
+
try {
|
|
844
|
+
const body = JSON.parse(raw);
|
|
845
|
+
const nested = body.error && typeof body.error === "object" ? body.error : void 0;
|
|
846
|
+
retryAfter ??= parseRetryAfter(nested?.retry_after);
|
|
847
|
+
const detail = nested?.message ?? body.message ?? (typeof body.error === "string" ? body.error : void 0);
|
|
848
|
+
if (typeof detail === "string" && detail) message = `${message}: ${detail}`;
|
|
849
|
+
const rawCode = nested?.code ?? body.code ?? nested?.type;
|
|
850
|
+
if (typeof rawCode === "string") code = rawCode;
|
|
851
|
+
else if (typeof rawCode === "number") code = String(rawCode);
|
|
852
|
+
} catch {
|
|
853
|
+
if (raw.trim()) message = `${message}: ${raw.trim().slice(0, 500)}`;
|
|
854
|
+
}
|
|
855
|
+
const kind = status === 401 || status === 403 && code && AUTH_CODES.has(code) ? "auth" : status === 402 || code && QUOTA_CODES.has(code) ? "quota" : "other";
|
|
856
|
+
if (code && !message.includes(code)) message = `${message} (${code})`;
|
|
857
|
+
if (status === 402 && this.options.creditHint) message = `${message} ${this.options.creditHint}`;
|
|
858
|
+
message = this.describe(message, { status, ...code ? { code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} });
|
|
859
|
+
const requestId = response.headers.get("x-request-id")?.trim();
|
|
860
|
+
if (requestId) message = `${message} [request ${requestId}]`;
|
|
861
|
+
const loopCode = isContextOverflow(status, code, message) ? "CONTEXT_TOO_LARGE" : kind !== "quota" && (status === 429 || code && THROTTLE_CODES.has(code)) ? "MODEL_RATE_LIMITED" : code ? this.options.errorCodes?.[code] : void 0;
|
|
862
|
+
return new ModelClientError(message, { kind, statusCode: status, ...loopCode ? { code: loopCode } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} });
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
function usageFrom(raw) {
|
|
866
|
+
const out = {};
|
|
867
|
+
const input = numberOf(raw.prompt_tokens);
|
|
868
|
+
const output = numberOf(raw.completion_tokens);
|
|
869
|
+
const promptDetails = raw.prompt_tokens_details && typeof raw.prompt_tokens_details === "object" ? raw.prompt_tokens_details : {};
|
|
870
|
+
const completionDetails = raw.completion_tokens_details && typeof raw.completion_tokens_details === "object" ? raw.completion_tokens_details : {};
|
|
871
|
+
const cached = numberOf(promptDetails.cached_tokens);
|
|
872
|
+
const reasoning = numberOf(completionDetails.reasoning_tokens);
|
|
873
|
+
const costDetails = raw.cost_details && typeof raw.cost_details === "object" ? raw.cost_details : {};
|
|
874
|
+
const cost = numberOf(raw.cost);
|
|
875
|
+
const upstream = numberOf(costDetails.upstream_inference_cost);
|
|
876
|
+
const unbilled = raw.billed === false && cost !== void 0;
|
|
877
|
+
if (cost !== void 0 || upstream !== void 0) out.costMicroUsd = Math.round((unbilled ? cost : (cost ?? 0) + (upstream ?? 0)) * 1e6);
|
|
878
|
+
const split = raw.cost_breakdown && typeof raw.cost_breakdown === "object" ? raw.cost_breakdown : {};
|
|
879
|
+
const metered = numberOf(split.metered);
|
|
880
|
+
const gpu = numberOf(split.gpu);
|
|
881
|
+
if (metered !== void 0 && metered >= 0) out.meteredMicroUsd = Math.round(metered * 1e6);
|
|
882
|
+
if (gpu !== void 0 && gpu >= 0) out.gpuMicroUsd = Math.round(gpu * 1e6);
|
|
883
|
+
if (input !== void 0) out.input = input;
|
|
884
|
+
if (output !== void 0) out.output = output;
|
|
885
|
+
if (cached !== void 0) out.cached = cached;
|
|
886
|
+
if (reasoning !== void 0) out.reasoning = reasoning;
|
|
887
|
+
return out;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// src/local-models/index.ts
|
|
891
|
+
import { mkdir as mkdir3, readdir as readdir2, readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
892
|
+
import { delimiter as delimiter2, dirname as dirname2, join as join4 } from "node:path";
|
|
893
|
+
|
|
894
|
+
// src/local-models/shared/budget.ts
|
|
895
|
+
var GIB = 1024 ** 3;
|
|
896
|
+
var MIB = 1024 ** 2;
|
|
897
|
+
function memoryBuffer(totalRamBytes) {
|
|
898
|
+
return Math.min(8 * GIB, Math.max(Math.min(4 * GIB, totalRamBytes / 4), totalRamBytes * 0.12));
|
|
899
|
+
}
|
|
900
|
+
function startMargin(totalRamBytes) {
|
|
901
|
+
return Math.min(2 * GIB, Math.max(1 * GIB, totalRamBytes * 0.02));
|
|
902
|
+
}
|
|
903
|
+
function vramReserve(vramBytes) {
|
|
904
|
+
return Math.max(512 * MIB, vramBytes * 0.1);
|
|
905
|
+
}
|
|
906
|
+
function usableGpus(hardware) {
|
|
907
|
+
const candidates = hardware.gpus.filter((gpu) => gpu.backend === "metal" || (gpu.integrated ? (gpu.addressableBytes ?? 0) > 0 : gpu.vramBytes > 0) && (gpu.backend !== "vulkan" || hardware.vulkanLoader));
|
|
908
|
+
for (const backend of ["metal", "cuda", "rocm", "vulkan"]) {
|
|
909
|
+
const matching = candidates.filter((gpu) => gpu.backend === backend);
|
|
910
|
+
if (matching.length) return matching;
|
|
911
|
+
}
|
|
912
|
+
return [];
|
|
913
|
+
}
|
|
914
|
+
function memoryBudget(hardware) {
|
|
915
|
+
const buffer = memoryBuffer(hardware.totalRamBytes);
|
|
916
|
+
const reserve = buffer + startMargin(hardware.totalRamBytes);
|
|
917
|
+
const ramBytes = Math.max(0, hardware.availableRamBytes - reserve);
|
|
918
|
+
const devices = usableGpus(hardware);
|
|
919
|
+
if (!devices.length) return { ramBytes, bufferBytes: buffer, ramReserveBytes: reserve };
|
|
920
|
+
const backend = devices[0].backend;
|
|
921
|
+
if (devices[0].unified) {
|
|
922
|
+
return {
|
|
923
|
+
ramBytes,
|
|
924
|
+
bufferBytes: buffer,
|
|
925
|
+
ramReserveBytes: reserve,
|
|
926
|
+
gpu: { backend, bytes: Math.min(ramBytes, hardware.totalRamBytes * 0.7, devices[0].addressableBytes ?? Infinity), devices, unified: true, fitTargetMib: Math.round(buffer / MIB) }
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
const bytes = devices.reduce((sum, gpu) => sum + Math.max(0, (gpu.freeVramBytes ?? gpu.vramBytes) - vramReserve(gpu.vramBytes)), 0);
|
|
930
|
+
const fitTargetMib = Math.round(Math.max(...devices.map((gpu) => vramReserve(gpu.vramBytes))) / MIB);
|
|
931
|
+
return { ramBytes, bufferBytes: buffer, ramReserveBytes: reserve, gpu: { backend, bytes, devices, unified: false, fitTargetMib } };
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// src/local-models/shared/fit.ts
|
|
935
|
+
var GIB2 = 1024 ** 3;
|
|
936
|
+
var CACHE_ELEMENT_BYTES = { f16: 2, q8_0: 34 / 32 };
|
|
937
|
+
function checkpoints(context) {
|
|
938
|
+
return Math.min(32, Math.floor(context / 8192));
|
|
939
|
+
}
|
|
940
|
+
function kvCacheBytesFor(kv, context, elementBytes, parallel) {
|
|
941
|
+
const full = kv.layers * kv.kvHeads * (kv.keyLength + kv.valueLength) * elementBytes * context;
|
|
942
|
+
const sliding = kv.sliding ? kv.sliding.layers * kv.sliding.kvHeads * (kv.sliding.keyLength + kv.sliding.valueLength) * elementBytes * Math.min(context, (kv.sliding.window + 512) * parallel) : 0;
|
|
943
|
+
const recurrent = (kv.recurrentStateBytes ?? 0) * parallel * (1 + checkpoints(context));
|
|
944
|
+
return full + sliding + recurrent;
|
|
945
|
+
}
|
|
946
|
+
function kvCacheBytes(kv, context, cacheType, parallel) {
|
|
947
|
+
return kvCacheBytesFor(kv, context, CACHE_ELEMENT_BYTES[cacheType], parallel);
|
|
948
|
+
}
|
|
949
|
+
function runtimeOverheadBytes(weightBytes) {
|
|
950
|
+
return 0.75 * GIB2 + weightBytes * 0.02;
|
|
951
|
+
}
|
|
952
|
+
function chooseCacheType(budgetBytes, weightBytes) {
|
|
953
|
+
return budgetBytes - weightBytes >= 16 * GIB2 ? "f16" : "q8_0";
|
|
954
|
+
}
|
|
955
|
+
var MIN_CONTEXT = 16384;
|
|
956
|
+
var PROMPT_CACHE_ALLOWANCE = 2 * GIB2;
|
|
957
|
+
function contextsToTry(model, requested) {
|
|
958
|
+
if (requested) return [Math.min(requested, model.maxContext)];
|
|
959
|
+
const list = /* @__PURE__ */ new Set();
|
|
960
|
+
for (let context = model.maxContext; context >= MIN_CONTEXT; context = Math.floor(context / 2)) list.add(context);
|
|
961
|
+
if (model.defaultContext >= MIN_CONTEXT && model.defaultContext <= model.maxContext) list.add(model.defaultContext);
|
|
962
|
+
if (!list.size) list.add(Math.min(model.defaultContext, model.maxContext));
|
|
963
|
+
return [...list].sort((left, right) => right - left);
|
|
964
|
+
}
|
|
965
|
+
function measuredNeed(model, footprints, context, cacheType, parallel, vision) {
|
|
966
|
+
const candidates = (footprints ?? []).filter((item) => item.mmap === false && item.parallel === parallel && item.anonBytes > 0 && item.context > 0);
|
|
967
|
+
if (!candidates.length) return void 0;
|
|
968
|
+
const distance = (item) => (item.cacheType === cacheType ? 0 : 100) + (item.vision === vision ? 0 : 10) + Math.abs(Math.log2(context / item.context));
|
|
969
|
+
const nearest = candidates.reduce((best, item) => distance(item) < distance(best) ? item : best);
|
|
970
|
+
const projector = model.projector?.sizeBytes ?? 0;
|
|
971
|
+
const itemType = nearest.cacheType === "q8_0" ? "q8_0" : "f16";
|
|
972
|
+
return nearest.anonBytes + nearest.fileBytes + kvCacheBytes(model.kv, context, cacheType, parallel) - kvCacheBytes(model.kv, nearest.context, itemType, parallel) + (Number(vision) - Number(nearest.vision)) * projector;
|
|
973
|
+
}
|
|
974
|
+
function fitModel(model, budget, options = {}) {
|
|
975
|
+
const parallel = options.parallel ?? (budget.gpu && !budget.gpu.unified ? 4 : 2);
|
|
976
|
+
const weightBytes = model.weights.sizeBytes + (options.vision && model.projector ? model.projector.sizeBytes : 0);
|
|
977
|
+
const overhead = runtimeOverheadBytes(weightBytes);
|
|
978
|
+
const vision = Boolean(options.vision && model.projector);
|
|
979
|
+
const extra = (context) => !options.context && context > model.defaultContext;
|
|
980
|
+
const allowance = (context) => extra(context) ? PROMPT_CACHE_ALLOWANCE : 0;
|
|
981
|
+
let smallest;
|
|
982
|
+
const cpuCacheTypes = ["f16", "q8_0"];
|
|
983
|
+
for (const cpuCacheType of cpuCacheTypes) for (const context of contextsToTry(model, options.context)) {
|
|
984
|
+
const gpu = budget.gpu;
|
|
985
|
+
if (gpu?.unified) {
|
|
986
|
+
const cacheType2 = chooseCacheType(gpu.bytes, weightBytes);
|
|
987
|
+
const needBytes2 = weightBytes + kvCacheBytes(model.kv, context, cacheType2, parallel) + overhead;
|
|
988
|
+
const fit2 = { fits: needBytes2 + allowance(context) <= gpu.bytes, placement: "gpu", context, cacheType: cacheType2, weightBytes, needBytes: needBytes2, gpuBytes: needBytes2, parallel };
|
|
989
|
+
if (fit2.fits) return fit2;
|
|
990
|
+
if (!extra(context) && gpu.bytes >= needBytes2 * 0.25 && needBytes2 <= budget.ramBytes) {
|
|
991
|
+
return { fits: true, placement: "gpu-partial", context, cacheType: cacheType2, weightBytes, needBytes: needBytes2, gpuBytes: gpu.bytes, parallel };
|
|
992
|
+
}
|
|
993
|
+
smallest = fit2;
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
if (gpu && gpu.bytes > 0) {
|
|
997
|
+
const cacheType2 = chooseCacheType(gpu.bytes, weightBytes);
|
|
998
|
+
const needBytes2 = weightBytes + kvCacheBytes(model.kv, context, cacheType2, parallel) + overhead;
|
|
999
|
+
if (needBytes2 <= gpu.bytes) {
|
|
1000
|
+
return { fits: true, placement: "gpu", context, cacheType: cacheType2, weightBytes, needBytes: needBytes2, gpuBytes: needBytes2, parallel };
|
|
1001
|
+
}
|
|
1002
|
+
if (extra(context)) continue;
|
|
1003
|
+
if (gpu.bytes >= needBytes2 * 0.25 && needBytes2 - gpu.bytes <= budget.ramBytes) {
|
|
1004
|
+
return { fits: true, placement: "gpu-partial", context, cacheType: cacheType2, weightBytes, needBytes: needBytes2, gpuBytes: gpu.bytes, parallel };
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
const cacheType = cpuCacheType;
|
|
1008
|
+
const measured = measuredNeed(model, options.footprints, context, cacheType, parallel, vision);
|
|
1009
|
+
const needBytes = measured ?? weightBytes + kvCacheBytes(model.kv, context, cacheType, parallel) + overhead;
|
|
1010
|
+
const fit = {
|
|
1011
|
+
fits: needBytes + allowance(context) <= budget.ramBytes,
|
|
1012
|
+
placement: "cpu",
|
|
1013
|
+
context,
|
|
1014
|
+
cacheType,
|
|
1015
|
+
weightBytes,
|
|
1016
|
+
needBytes,
|
|
1017
|
+
gpuBytes: 0,
|
|
1018
|
+
parallel,
|
|
1019
|
+
...measured !== void 0 ? { measured: true } : {}
|
|
1020
|
+
};
|
|
1021
|
+
if (fit.fits) return fit;
|
|
1022
|
+
smallest = fit;
|
|
1023
|
+
}
|
|
1024
|
+
const where = budget.gpu?.unified ? "unified memory" : "RAM";
|
|
1025
|
+
const room = budget.gpu?.unified ? budget.gpu.bytes : budget.ramBytes;
|
|
1026
|
+
return {
|
|
1027
|
+
...smallest,
|
|
1028
|
+
fits: false,
|
|
1029
|
+
reason: `needs ${gb(smallest.needBytes)} at ${Math.round(smallest.context / 1024)}K context; ${gb(room)} of ${where} is free for models`
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
function gb(bytes) {
|
|
1033
|
+
return `${(bytes / 1e9).toFixed(1)} GB`;
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// src/local-models/shared/speed.ts
|
|
1037
|
+
var MIN_PROMPT_PER_SECOND = 50;
|
|
1038
|
+
var MIN_GENERATE_PER_SECOND = 8;
|
|
1039
|
+
var CPU_PROMPT_RATE = [
|
|
1040
|
+
[/IQ[1-3]/i, 79],
|
|
1041
|
+
[/Q3_K/i, 136],
|
|
1042
|
+
[/Q[45]_K|Q4_0|Q4_1|MXFP4|Q4\b/i, 264],
|
|
1043
|
+
[/Q[68]/i, 200],
|
|
1044
|
+
[/BF16|F16/i, 60]
|
|
1045
|
+
];
|
|
1046
|
+
var CPU_WEIGHT_BANDWIDTH = 4e10;
|
|
1047
|
+
function appleBandwidth(cpuModel) {
|
|
1048
|
+
const peak = /ultra/i.test(cpuModel) ? 8e11 : /max/i.test(cpuModel) ? 4e11 : /pro/i.test(cpuModel) ? 2e11 : 1e11;
|
|
1049
|
+
return peak * 0.75;
|
|
1050
|
+
}
|
|
1051
|
+
function cpuPromptRate(quantization) {
|
|
1052
|
+
return CPU_PROMPT_RATE.find(([pattern]) => pattern.test(quantization))?.[1] ?? 150;
|
|
1053
|
+
}
|
|
1054
|
+
function bytesPerToken(model) {
|
|
1055
|
+
return model.activeWeightBytes ?? model.weights.sizeBytes * Math.min(1, model.activeParamsB / model.totalParamsB);
|
|
1056
|
+
}
|
|
1057
|
+
function speedAtContext(model, hardware, fit, measured, gpu) {
|
|
1058
|
+
const shallow = estimateSpeed(model, hardware, fit, gpu);
|
|
1059
|
+
const base = measured?.promptPerSecond && measured.generatePerSecond ? { promptPerSecond: measured.promptPerSecond, generatePerSecond: measured.generatePerSecond } : shallow;
|
|
1060
|
+
const depth = Math.floor(fit.context * 0.8);
|
|
1061
|
+
if (fit.placement !== "cpu") {
|
|
1062
|
+
if (!gpu?.integrated || gpu.backend === "metal") return base;
|
|
1063
|
+
return { promptPerSecond: base.promptPerSecond / (1 + 29e-6 * depth), generatePerSecond: base.generatePerSecond / (1 + 67e-7 * depth) };
|
|
1064
|
+
}
|
|
1065
|
+
const fullKvWork = model.kv.layers * model.kv.kvHeads * model.kv.keyLength;
|
|
1066
|
+
const headRatio = model.architecture === "gemma4" || model.architecture === "gpt-oss" ? 8 : 4;
|
|
1067
|
+
const fullQWork = fullKvWork * headRatio;
|
|
1068
|
+
const cores = Math.max(1, Math.min(8, hardware.physicalCores));
|
|
1069
|
+
const effectiveCores = cores * (1 - 0.3267 * (cores - 1) / 7);
|
|
1070
|
+
const promptExtraSeconds = 0.49697 * (fullQWork / 1e4) * (depth / 1e6) / effectiveCores;
|
|
1071
|
+
const generateExtraSeconds = 0.056167 * (fullKvWork / 1e4) * (depth ** 1.5 / 1e6) * (8 / cores);
|
|
1072
|
+
return {
|
|
1073
|
+
promptPerSecond: 1 / (1 / base.promptPerSecond + promptExtraSeconds),
|
|
1074
|
+
generatePerSecond: 1 / (1 / base.generatePerSecond + generateExtraSeconds)
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
function estimatedTurnSeconds(speed) {
|
|
1078
|
+
return 2e3 / speed.promptPerSecond + 300 / speed.generatePerSecond;
|
|
1079
|
+
}
|
|
1080
|
+
function firstReplySeconds(speed) {
|
|
1081
|
+
const promptSeconds = 4e3 / speed.promptPerSecond;
|
|
1082
|
+
return {
|
|
1083
|
+
brief: promptSeconds + 300 / speed.generatePerSecond,
|
|
1084
|
+
long: promptSeconds + 1e3 / speed.generatePerSecond
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
function estimateSpeed(model, hardware, fit, gpuDevice) {
|
|
1088
|
+
const active = Math.max(0.1, model.activeParamsB);
|
|
1089
|
+
const cpu = {
|
|
1090
|
+
promptPerSecond: cpuPromptRate(model.quantization) * hardware.physicalCores / 8 / active,
|
|
1091
|
+
generatePerSecond: CPU_WEIGHT_BANDWIDTH / Math.max(1, bytesPerToken(model))
|
|
1092
|
+
};
|
|
1093
|
+
if (fit.placement === "cpu") return cpu;
|
|
1094
|
+
const gpuBackend = gpuDevice?.backend;
|
|
1095
|
+
const integratedX86 = Boolean(gpuDevice?.integrated) && gpuBackend !== "metal";
|
|
1096
|
+
const bandwidth = gpuBackend === "metal" ? appleBandwidth(hardware.cpuModel) : integratedX86 ? 55e9 : 3e11;
|
|
1097
|
+
const gpu = {
|
|
1098
|
+
promptPerSecond: (gpuBackend === "metal" ? bandwidth / 75e9 * 1600 : integratedX86 ? 1300 : 2e4) / active,
|
|
1099
|
+
generatePerSecond: bandwidth / Math.max(1, bytesPerToken(model))
|
|
1100
|
+
};
|
|
1101
|
+
if (fit.placement === "gpu") return gpu;
|
|
1102
|
+
const share = Math.min(1, fit.gpuBytes / fit.needBytes);
|
|
1103
|
+
const blend = (onGpu, onCpu) => 1 / (share / onGpu + (1 - share) / onCpu);
|
|
1104
|
+
return { promptPerSecond: blend(gpu.promptPerSecond, cpu.promptPerSecond), generatePerSecond: blend(gpu.generatePerSecond, cpu.generatePerSecond) };
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// src/local-models/shared/rank.ts
|
|
1108
|
+
var MAX_DEEP_TURN_SECONDS = 2e3 / MIN_PROMPT_PER_SECOND + 300 / MIN_GENERATE_PER_SECOND;
|
|
1109
|
+
var MAX_FIRST_REPLY_SECONDS = 90;
|
|
1110
|
+
var DEEP_TIME_MARGIN = 1.15;
|
|
1111
|
+
function fitForConversation(model, hardware, budget, measured, footprints) {
|
|
1112
|
+
const memoryFit = fitModel(model, budget, { footprints });
|
|
1113
|
+
const tuned = memoryFit.placement === "cpu" || memoryFit.placement === "gpu" && Boolean(budget.gpu?.unified);
|
|
1114
|
+
if (!memoryFit.fits || !tuned) return memoryFit;
|
|
1115
|
+
let smallest = memoryFit;
|
|
1116
|
+
let workingWindow;
|
|
1117
|
+
const workingMinimum = Math.min(32768, model.maxContext);
|
|
1118
|
+
for (const context of contextsToTry(model)) {
|
|
1119
|
+
const fit = fitModel(model, budget, { context, footprints });
|
|
1120
|
+
if (!fit.fits || fit.placement !== memoryFit.placement) continue;
|
|
1121
|
+
if (fit.cacheType !== memoryFit.cacheType) continue;
|
|
1122
|
+
const room = budget.ramBytes - fit.needBytes;
|
|
1123
|
+
if (context > model.defaultContext && room < PROMPT_CACHE_ALLOWANCE) continue;
|
|
1124
|
+
smallest = fit;
|
|
1125
|
+
if (context >= workingMinimum) workingWindow = fit;
|
|
1126
|
+
const speed = speedAtContext(model, hardware, fit, measured, budget.gpu?.devices[0]);
|
|
1127
|
+
if (estimatedTurnSeconds(speed) * DEEP_TIME_MARGIN <= MAX_DEEP_TURN_SECONDS && (context >= workingMinimum || !workingWindow)) return fit;
|
|
1128
|
+
}
|
|
1129
|
+
return workingWindow ?? smallest;
|
|
1130
|
+
}
|
|
1131
|
+
function meetsBar(speed) {
|
|
1132
|
+
return speed.toolCalls !== false && (speed.promptPerSecond ?? 0) >= MIN_PROMPT_PER_SECOND && (speed.generatePerSecond ?? 0) >= MIN_GENERATE_PER_SECOND;
|
|
1133
|
+
}
|
|
1134
|
+
function rankModels(catalog, hardware, budget, measurements, footprints = {}) {
|
|
1135
|
+
const ranked = catalog.map((model) => {
|
|
1136
|
+
const measured = measurements[model.id];
|
|
1137
|
+
const fit = fitForConversation(model, hardware, budget, measured, footprints[model.id] ?? []);
|
|
1138
|
+
const estimate = speedAtContext(model, hardware, fit, void 0, budget.gpu?.devices[0]);
|
|
1139
|
+
const speed = speedAtContext(model, hardware, fit, measured, budget.gpu?.devices[0]);
|
|
1140
|
+
const shallow = measured?.promptPerSecond && measured.generatePerSecond ? { promptPerSecond: measured.promptPerSecond, generatePerSecond: measured.generatePerSecond } : estimateSpeed(model, hardware, fit, budget.gpu?.devices[0]);
|
|
1141
|
+
const firstReply = firstReplySeconds(shallow);
|
|
1142
|
+
return {
|
|
1143
|
+
model,
|
|
1144
|
+
fit,
|
|
1145
|
+
estimate,
|
|
1146
|
+
speed,
|
|
1147
|
+
firstReply,
|
|
1148
|
+
passes: fit.fits && measured?.toolCalls !== false && estimatedTurnSeconds(speed) * DEEP_TIME_MARGIN <= MAX_DEEP_TURN_SECONDS && firstReply.long <= MAX_FIRST_REPLY_SECONDS,
|
|
1149
|
+
...measured ? { measured } : {}
|
|
1150
|
+
};
|
|
1151
|
+
});
|
|
1152
|
+
const responseCost = (row) => Math.max(
|
|
1153
|
+
row.firstReply.long / MAX_FIRST_REPLY_SECONDS,
|
|
1154
|
+
estimatedTurnSeconds(row.speed) * DEEP_TIME_MARGIN / MAX_DEEP_TURN_SECONDS
|
|
1155
|
+
);
|
|
1156
|
+
const viable = ranked.filter((row) => row.fit.fits && row.measured?.toolCalls !== false);
|
|
1157
|
+
const quickestFirst = Math.min(...viable.map((row) => row.firstReply.long));
|
|
1158
|
+
const quickestDeep = Math.min(...viable.map((row) => estimatedTurnSeconds(row.speed)));
|
|
1159
|
+
const group = (row) => row.passes ? 0 : !row.fit.fits ? 4 : row.measured?.toolCalls === false ? 3 : row.firstReply.long <= quickestFirst * 1.15 && estimatedTurnSeconds(row.speed) <= quickestDeep * 1.15 ? 1 : 2;
|
|
1160
|
+
return ranked.sort((left, right) => group(left) - group(right) || (group(left) <= 1 ? right.model.quality - left.model.quality : group(left) <= 3 ? responseCost(left) - responseCost(right) : left.fit.needBytes - right.fit.needBytes));
|
|
1161
|
+
}
|
|
1162
|
+
function chooseModel(ranked, pick) {
|
|
1163
|
+
if (pick) {
|
|
1164
|
+
const row = ranked.find((item) => item.model.id === pick);
|
|
1165
|
+
if (!row) throw new Error(`${pick} is not a ClikCode Local model.`);
|
|
1166
|
+
if (!row.fit.fits) throw new Error(`${row.model.label} does not fit on this machine: ${row.fit.reason}.`);
|
|
1167
|
+
return {
|
|
1168
|
+
row,
|
|
1169
|
+
...!row.passes ? { notice: row.measured?.toolCalls === false ? `${row.model.label} did not make a tool call in its local check, so coding-agent tasks may fail.` : `${row.model.label} may take about ${Math.round(row.firstReply.brief)}\u2013${Math.round(row.firstReply.long)} seconds for its first reply after loading; longer replies take longer.` } : {}
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
const [best] = ranked;
|
|
1173
|
+
if (!best || !best.fit.fits) throw new Error("No ClikCode Local model fits in the memory this machine has free.");
|
|
1174
|
+
if (best.passes) return { row: best };
|
|
1175
|
+
return {
|
|
1176
|
+
row: best,
|
|
1177
|
+
notice: `No local model is estimated to meet both response-speed targets here; ${best.model.label} is the highest-ranked coding model near the quickest that fits (about ${Math.round(best.firstReply.brief)}\u2013${Math.round(best.firstReply.long)} seconds for its first reply after loading).`
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// src/local-models/hardware.ts
|
|
1182
|
+
import { execFile } from "node:child_process";
|
|
1183
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
1184
|
+
import { cpus, freemem, totalmem } from "node:os";
|
|
1185
|
+
import { join } from "node:path";
|
|
1186
|
+
var GIB3 = 1024 ** 3;
|
|
1187
|
+
var MIB2 = 1024 ** 2;
|
|
1188
|
+
function parseLinuxMeminfo(text) {
|
|
1189
|
+
const field = (name) => {
|
|
1190
|
+
const match = new RegExp(`^${name}:\\s+(\\d+)\\s*kB`, "m").exec(text);
|
|
1191
|
+
return match ? Number(match[1]) * 1024 : void 0;
|
|
1192
|
+
};
|
|
1193
|
+
const available = field("MemAvailable") ?? sumDefined(field("MemFree"), field("Cached"), field("Buffers"));
|
|
1194
|
+
return { totalBytes: field("MemTotal"), availableBytes: available };
|
|
1195
|
+
}
|
|
1196
|
+
function sumDefined(...values) {
|
|
1197
|
+
return values.some((value) => value === void 0) ? void 0 : values.reduce((sum, value) => sum + value, 0);
|
|
1198
|
+
}
|
|
1199
|
+
function parseCpuinfoPhysicalCores(text) {
|
|
1200
|
+
const cores = /* @__PURE__ */ new Set();
|
|
1201
|
+
for (const block of text.split(/\n\s*\n/)) {
|
|
1202
|
+
const core = /^core id\s*:\s*(\d+)/m.exec(block)?.[1];
|
|
1203
|
+
if (core === void 0) continue;
|
|
1204
|
+
cores.add(`${/^physical id\s*:\s*(\d+)/m.exec(block)?.[1] ?? "0"}:${core}`);
|
|
1205
|
+
}
|
|
1206
|
+
return cores.size || void 0;
|
|
1207
|
+
}
|
|
1208
|
+
function parseVmStat(text) {
|
|
1209
|
+
const pageSize = Number(/page size of (\d+) bytes/.exec(text)?.[1] ?? 4096);
|
|
1210
|
+
const pages = (label) => Number(new RegExp(`^Pages ${label}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? 0);
|
|
1211
|
+
const total = pages("free") + pages("inactive") + pages("speculative") + pages("purgeable");
|
|
1212
|
+
return total > 0 ? total * pageSize : void 0;
|
|
1213
|
+
}
|
|
1214
|
+
function parseNvidiaSmi(text) {
|
|
1215
|
+
const gpus = [];
|
|
1216
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1217
|
+
const [name, total, free, driver] = line.split(",").map((part) => part.trim());
|
|
1218
|
+
if (!name || !Number.isFinite(Number(total)) || !total) continue;
|
|
1219
|
+
gpus.push({
|
|
1220
|
+
name,
|
|
1221
|
+
vendor: "nvidia",
|
|
1222
|
+
backend: "cuda",
|
|
1223
|
+
vramBytes: Number(total) * MIB2,
|
|
1224
|
+
...Number.isFinite(Number(free)) && free ? { freeVramBytes: Number(free) * MIB2 } : {},
|
|
1225
|
+
unified: false,
|
|
1226
|
+
integrated: false,
|
|
1227
|
+
...driver ? { driverVersion: driver } : {}
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
return gpus;
|
|
1231
|
+
}
|
|
1232
|
+
function parseRocmSmi(text) {
|
|
1233
|
+
let parsed;
|
|
1234
|
+
try {
|
|
1235
|
+
parsed = JSON.parse(text);
|
|
1236
|
+
} catch {
|
|
1237
|
+
return [];
|
|
1238
|
+
}
|
|
1239
|
+
const gpus = [];
|
|
1240
|
+
for (const [card, fields] of Object.entries(parsed)) {
|
|
1241
|
+
if (!/^card\d+/.test(card) || typeof fields !== "object") continue;
|
|
1242
|
+
const total = Number(fields["VRAM Total Memory (B)"]);
|
|
1243
|
+
const used = Number(fields["VRAM Total Used Memory (B)"]);
|
|
1244
|
+
if (!Number.isFinite(total) || total <= 0) continue;
|
|
1245
|
+
gpus.push({
|
|
1246
|
+
name: fields["Card Series"] || fields["Card series"] || fields["Card SKU"] || card,
|
|
1247
|
+
vendor: "amd",
|
|
1248
|
+
backend: "rocm",
|
|
1249
|
+
vramBytes: total,
|
|
1250
|
+
...Number.isFinite(used) ? { freeVramBytes: Math.max(0, total - used) } : {},
|
|
1251
|
+
unified: false,
|
|
1252
|
+
integrated: false
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
return gpus;
|
|
1256
|
+
}
|
|
1257
|
+
function parseAmdSmi(text) {
|
|
1258
|
+
let parsed;
|
|
1259
|
+
try {
|
|
1260
|
+
parsed = JSON.parse(text);
|
|
1261
|
+
} catch {
|
|
1262
|
+
return [];
|
|
1263
|
+
}
|
|
1264
|
+
const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed.gpu_data) ? parsed.gpu_data : [];
|
|
1265
|
+
const bytes = (field) => {
|
|
1266
|
+
if (!field || typeof field !== "object") return void 0;
|
|
1267
|
+
const { value, unit } = field;
|
|
1268
|
+
const number = Number(value);
|
|
1269
|
+
if (!Number.isFinite(number)) return void 0;
|
|
1270
|
+
const scale = /^GB$/i.test(String(unit)) ? GIB3 : /^KB$/i.test(String(unit)) ? 1024 : /^B$/i.test(String(unit)) ? 1 : MIB2;
|
|
1271
|
+
return number * scale;
|
|
1272
|
+
};
|
|
1273
|
+
const gpus = [];
|
|
1274
|
+
for (const entry of list) {
|
|
1275
|
+
const total = bytes(entry?.mem_usage?.total_vram);
|
|
1276
|
+
if (!total) continue;
|
|
1277
|
+
const free = bytes(entry.mem_usage?.free_vram);
|
|
1278
|
+
gpus.push({
|
|
1279
|
+
name: `AMD GPU ${entry.gpu ?? gpus.length}`,
|
|
1280
|
+
vendor: "amd",
|
|
1281
|
+
backend: "rocm",
|
|
1282
|
+
vramBytes: total,
|
|
1283
|
+
...free !== void 0 ? { freeVramBytes: free } : {},
|
|
1284
|
+
unified: false,
|
|
1285
|
+
integrated: false
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
return gpus;
|
|
1289
|
+
}
|
|
1290
|
+
function parseWindowsProbe(text) {
|
|
1291
|
+
let parsed;
|
|
1292
|
+
try {
|
|
1293
|
+
parsed = JSON.parse(text.trim());
|
|
1294
|
+
} catch {
|
|
1295
|
+
return void 0;
|
|
1296
|
+
}
|
|
1297
|
+
const many = (value) => Array.isArray(value) ? value : value ? [value] : [];
|
|
1298
|
+
const processors = many(parsed.cpu);
|
|
1299
|
+
const adapters = many(parsed.gpu);
|
|
1300
|
+
const kib = (value) => Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) * 1024 : void 0;
|
|
1301
|
+
const sum = (key) => processors.length ? processors.reduce((total, cpu) => total + (Number(cpu[key]) || 0), 0) || void 0 : void 0;
|
|
1302
|
+
return {
|
|
1303
|
+
totalRamBytes: kib(parsed.os?.TotalVisibleMemorySize),
|
|
1304
|
+
availableRamBytes: kib(parsed.os?.FreePhysicalMemory),
|
|
1305
|
+
physicalCores: sum("NumberOfCores"),
|
|
1306
|
+
logicalCores: sum("NumberOfLogicalProcessors"),
|
|
1307
|
+
cpuModel: processors[0]?.Name?.trim(),
|
|
1308
|
+
adapters: adapters.filter((adapter) => adapter.Name).map((adapter) => ({
|
|
1309
|
+
name: adapter.Name.trim(),
|
|
1310
|
+
...Number(adapter.AdapterRAM) > 0 ? { ramBytes: Number(adapter.AdapterRAM) } : {}
|
|
1311
|
+
}))
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
function isIntegratedAmd(cpuModel, vramBytes) {
|
|
1315
|
+
return /radeon/i.test(cpuModel) && vramBytes <= 8 * GIB3;
|
|
1316
|
+
}
|
|
1317
|
+
function appleSiliconGpu(cpuModel, totalRamBytes) {
|
|
1318
|
+
return { name: cpuModel || "Apple Silicon", vendor: "apple", backend: "metal", vramBytes: totalRamBytes, unified: true, integrated: true };
|
|
1319
|
+
}
|
|
1320
|
+
function run(command, args, timeoutMs = 8e3) {
|
|
1321
|
+
return new Promise((resolve) => {
|
|
1322
|
+
execFile(command, [...args], { timeout: timeoutMs, windowsHide: true, maxBuffer: 4 * MIB2 }, (error, stdout) => {
|
|
1323
|
+
resolve(error ? void 0 : stdout);
|
|
1324
|
+
});
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
function readText(path) {
|
|
1328
|
+
try {
|
|
1329
|
+
return readFileSync(path, "utf8");
|
|
1330
|
+
} catch {
|
|
1331
|
+
return void 0;
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
function linuxSysfsGpus(cpuModel) {
|
|
1335
|
+
const gpus = [];
|
|
1336
|
+
let cards = [];
|
|
1337
|
+
try {
|
|
1338
|
+
cards = readdirSync("/sys/class/drm").filter((name) => /^card\d+$/.test(name));
|
|
1339
|
+
} catch {
|
|
1340
|
+
return gpus;
|
|
1341
|
+
}
|
|
1342
|
+
for (const card of cards) {
|
|
1343
|
+
const device = join("/sys/class/drm", card, "device");
|
|
1344
|
+
const vendor = readText(join(device, "vendor"))?.trim();
|
|
1345
|
+
if (!/^0x03/.test(readText(join(device, "class"))?.trim() ?? "")) continue;
|
|
1346
|
+
if (vendor === "0x1002") {
|
|
1347
|
+
const total = Number(readText(join(device, "mem_info_vram_total")));
|
|
1348
|
+
const used = Number(readText(join(device, "mem_info_vram_used")));
|
|
1349
|
+
if (!Number.isFinite(total) || total <= 0) continue;
|
|
1350
|
+
const integrated = isIntegratedAmd(cpuModel, total);
|
|
1351
|
+
gpus.push({
|
|
1352
|
+
name: integrated ? `${cpuModel.replace(/.*w\/\s*/i, "") || "AMD integrated graphics"}` : `AMD GPU (${card})`,
|
|
1353
|
+
vendor: "amd",
|
|
1354
|
+
backend: "vulkan",
|
|
1355
|
+
vramBytes: total,
|
|
1356
|
+
...Number.isFinite(used) ? { freeVramBytes: Math.max(0, total - used) } : {},
|
|
1357
|
+
unified: integrated,
|
|
1358
|
+
integrated
|
|
1359
|
+
});
|
|
1360
|
+
} else if (vendor === "0x8086") {
|
|
1361
|
+
gpus.push({ name: "Intel graphics", vendor: "intel", backend: "vulkan", vramBytes: 0, unified: true, integrated: true });
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
return gpus;
|
|
1365
|
+
}
|
|
1366
|
+
function linuxVulkanLoader() {
|
|
1367
|
+
const directories = ["/usr/lib/x86_64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/usr/lib64", "/usr/lib", "/usr/local/lib", "/lib/x86_64-linux-gnu"];
|
|
1368
|
+
return directories.some((directory) => existsSync(join(directory, "libvulkan.so.1")));
|
|
1369
|
+
}
|
|
1370
|
+
async function nvidiaGpus() {
|
|
1371
|
+
const output = await run("nvidia-smi", ["--query-gpu=name,memory.total,memory.free,driver_version", "--format=csv,noheader,nounits"]);
|
|
1372
|
+
return output ? parseNvidiaSmi(output) : [];
|
|
1373
|
+
}
|
|
1374
|
+
async function amdToolGpus() {
|
|
1375
|
+
const rocm = await run("rocm-smi", ["--showmeminfo", "vram", "--showproductname", "--json"]);
|
|
1376
|
+
if (rocm) {
|
|
1377
|
+
const gpus = parseRocmSmi(rocm);
|
|
1378
|
+
if (gpus.length) return gpus;
|
|
1379
|
+
}
|
|
1380
|
+
const amd = await run("amd-smi", ["metric", "--mem-usage", "--json"]);
|
|
1381
|
+
return amd ? parseAmdSmi(amd) : [];
|
|
1382
|
+
}
|
|
1383
|
+
async function probeLinux() {
|
|
1384
|
+
const memory = parseLinuxMeminfo(readText("/proc/meminfo") ?? "");
|
|
1385
|
+
const cpuinfo = readText("/proc/cpuinfo") ?? "";
|
|
1386
|
+
const cpuModel = /^model name\s*:\s*(.+)$/m.exec(cpuinfo)?.[1]?.trim() ?? cpus()[0]?.model ?? "";
|
|
1387
|
+
const nvidia = await nvidiaGpus();
|
|
1388
|
+
const amdTool = await amdToolGpus();
|
|
1389
|
+
const sysfs = linuxSysfsGpus(cpuModel).filter((gpu) => gpu.vendor !== "amd" || !amdTool.length);
|
|
1390
|
+
const amd = amdTool.map((gpu) => isIntegratedAmd(cpuModel, gpu.vramBytes) ? { ...gpu, integrated: true, unified: true } : gpu);
|
|
1391
|
+
return {
|
|
1392
|
+
cpuModel,
|
|
1393
|
+
physicalCores: parseCpuinfoPhysicalCores(cpuinfo),
|
|
1394
|
+
totalRamBytes: memory.totalBytes,
|
|
1395
|
+
availableRamBytes: memory.availableBytes,
|
|
1396
|
+
gpus: [...nvidia, ...amd, ...sysfs],
|
|
1397
|
+
vulkanLoader: linuxVulkanLoader()
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
async function probeMac() {
|
|
1401
|
+
const sysctl = async (name) => (await run("sysctl", ["-n", name]))?.trim();
|
|
1402
|
+
const cpuModel = await sysctl("machdep.cpu.brand_string") ?? cpus()[0]?.model ?? "";
|
|
1403
|
+
const totalRamBytes = Number(await sysctl("hw.memsize")) || totalmem();
|
|
1404
|
+
const vmStat = await run("vm_stat", []);
|
|
1405
|
+
const physical = Number(await sysctl("hw.physicalcpu"));
|
|
1406
|
+
return {
|
|
1407
|
+
cpuModel,
|
|
1408
|
+
physicalCores: physical > 0 ? physical : void 0,
|
|
1409
|
+
totalRamBytes,
|
|
1410
|
+
availableRamBytes: vmStat ? parseVmStat(vmStat) : void 0,
|
|
1411
|
+
gpus: process.arch === "arm64" ? [appleSiliconGpu(cpuModel, totalRamBytes)] : [],
|
|
1412
|
+
vulkanLoader: false
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
var WINDOWS_PROBE_SCRIPT = [
|
|
1416
|
+
"$os = Get-CimInstance Win32_OperatingSystem | Select-Object TotalVisibleMemorySize,FreePhysicalMemory;",
|
|
1417
|
+
"$cpu = Get-CimInstance Win32_Processor | Select-Object Name,NumberOfCores,NumberOfLogicalProcessors;",
|
|
1418
|
+
"$gpu = Get-CimInstance Win32_VideoController | Select-Object Name,AdapterRAM;",
|
|
1419
|
+
"@{ os = $os; cpu = $cpu; gpu = $gpu } | ConvertTo-Json -Compress -Depth 4"
|
|
1420
|
+
].join(" ");
|
|
1421
|
+
async function probeWindows() {
|
|
1422
|
+
const output = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROBE_SCRIPT], 2e4);
|
|
1423
|
+
const probe = output ? parseWindowsProbe(output) : void 0;
|
|
1424
|
+
const nvidia = await nvidiaGpus();
|
|
1425
|
+
const others = (probe?.adapters ?? []).filter((adapter) => !/nvidia/i.test(adapter.name) && !/microsoft basic|remote display/i.test(adapter.name)).map((adapter) => {
|
|
1426
|
+
const amd = /amd|radeon/i.test(adapter.name);
|
|
1427
|
+
const integrated = /intel/i.test(adapter.name) || amd && isIntegratedAmd(probe?.cpuModel ?? "", adapter.ramBytes ?? 0);
|
|
1428
|
+
return {
|
|
1429
|
+
name: adapter.name,
|
|
1430
|
+
vendor: amd ? "amd" : /intel/i.test(adapter.name) ? "intel" : "other",
|
|
1431
|
+
backend: "vulkan",
|
|
1432
|
+
vramBytes: adapter.ramBytes ?? 0,
|
|
1433
|
+
unified: integrated,
|
|
1434
|
+
integrated
|
|
1435
|
+
};
|
|
1436
|
+
});
|
|
1437
|
+
const system32 = join(process.env.SystemRoot ?? "C:\\Windows", "System32");
|
|
1438
|
+
return {
|
|
1439
|
+
cpuModel: probe?.cpuModel,
|
|
1440
|
+
physicalCores: probe?.physicalCores,
|
|
1441
|
+
totalRamBytes: probe?.totalRamBytes,
|
|
1442
|
+
availableRamBytes: probe?.availableRamBytes,
|
|
1443
|
+
gpus: [...nvidia, ...others],
|
|
1444
|
+
vulkanLoader: existsSync(join(system32, "vulkan-1.dll"))
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
function guessPhysicalCores(logical, arch) {
|
|
1448
|
+
return arch === "x64" && logical >= 4 ? Math.max(1, Math.floor(logical / 2)) : logical;
|
|
1449
|
+
}
|
|
1450
|
+
async function probeHardware() {
|
|
1451
|
+
const logicalCores = Math.max(1, cpus().length);
|
|
1452
|
+
const found = process.platform === "linux" ? await probeLinux() : process.platform === "darwin" ? await probeMac() : process.platform === "win32" ? await probeWindows() : {};
|
|
1453
|
+
const totalRamBytes = found.totalRamBytes ?? totalmem();
|
|
1454
|
+
return {
|
|
1455
|
+
platform: process.platform,
|
|
1456
|
+
arch: process.arch,
|
|
1457
|
+
cpuModel: found.cpuModel || cpus()[0]?.model || "unknown CPU",
|
|
1458
|
+
physicalCores: Math.min(logicalCores, found.physicalCores ?? guessPhysicalCores(logicalCores, process.arch)),
|
|
1459
|
+
logicalCores,
|
|
1460
|
+
totalRamBytes,
|
|
1461
|
+
// os.freemem() is MemFree on Linux -- too low -- but it is the only
|
|
1462
|
+
// figure left if the proper one could not be read.
|
|
1463
|
+
availableRamBytes: Math.min(totalRamBytes, found.availableRamBytes ?? freemem()),
|
|
1464
|
+
gpus: found.gpus ?? [],
|
|
1465
|
+
vulkanLoader: found.vulkanLoader ?? false
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// src/local-models/gpu-reach.ts
|
|
1470
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
1471
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
1472
|
+
import { delimiter, dirname, join as join2 } from "node:path";
|
|
1473
|
+
var MIB3 = 1024 ** 2;
|
|
1474
|
+
function parseListedDevices(text) {
|
|
1475
|
+
const devices = [];
|
|
1476
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1477
|
+
const match = /^\s*Vulkan\d+:\s*(.+?)\s*\((\d+) MiB, \d+ MiB free\)\s*$/.exec(line);
|
|
1478
|
+
if (match) devices.push({ name: match[1], totalBytes: Number(match[2]) * MIB3 });
|
|
1479
|
+
}
|
|
1480
|
+
return devices;
|
|
1481
|
+
}
|
|
1482
|
+
function matchDevice(gpu, devices) {
|
|
1483
|
+
if (devices.length === 1) return devices[0];
|
|
1484
|
+
const words = (text) => text.toLowerCase().replace(/\(tm\)|\(r\)/g, "").split(/[^a-z0-9]+/).filter(Boolean);
|
|
1485
|
+
const wanted = words(gpu.name);
|
|
1486
|
+
const found = devices.filter((device) => {
|
|
1487
|
+
const have = new Set(words(device.name));
|
|
1488
|
+
return wanted.every((word) => have.has(word));
|
|
1489
|
+
});
|
|
1490
|
+
return found.length === 1 ? found[0] : void 0;
|
|
1491
|
+
}
|
|
1492
|
+
function unknownReach(hardware) {
|
|
1493
|
+
return hardware.vulkanLoader ? hardware.gpus.filter((gpu) => gpu.integrated && gpu.vendor === "amd" && gpu.backend === "vulkan" && !gpu.addressableBytes) : [];
|
|
1494
|
+
}
|
|
1495
|
+
function vulkanBuild(hardware) {
|
|
1496
|
+
return RUNTIME_BUILDS.find((build) => build.platform === hardware.platform && build.arch === hardware.arch && build.backend === "vulkan");
|
|
1497
|
+
}
|
|
1498
|
+
function reachFile() {
|
|
1499
|
+
return join2(localModelsHome(), "gpu-reach.json");
|
|
1500
|
+
}
|
|
1501
|
+
function reachKey(build, gpu) {
|
|
1502
|
+
return `${build.key}|${gpu.name}|${gpu.driverVersion ?? ""}`;
|
|
1503
|
+
}
|
|
1504
|
+
async function readReach() {
|
|
1505
|
+
return JSON.parse(await readFile(reachFile(), "utf8").catch(() => "{}"));
|
|
1506
|
+
}
|
|
1507
|
+
function withReach(hardware, build, known) {
|
|
1508
|
+
return {
|
|
1509
|
+
...hardware,
|
|
1510
|
+
gpus: hardware.gpus.map((gpu) => {
|
|
1511
|
+
const reach = unknownReach(hardware).includes(gpu) ? known[reachKey(build, gpu)] : void 0;
|
|
1512
|
+
return reach ? { ...gpu, addressableBytes: reach } : gpu;
|
|
1513
|
+
})
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
async function withKnownReach(hardware) {
|
|
1517
|
+
const build = vulkanBuild(hardware);
|
|
1518
|
+
if (!build || !unknownReach(hardware).length) return hardware;
|
|
1519
|
+
return withReach(hardware, build, await readReach());
|
|
1520
|
+
}
|
|
1521
|
+
function listDevices(serverPath) {
|
|
1522
|
+
const variable = process.platform === "win32" ? "PATH" : process.platform === "darwin" ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH";
|
|
1523
|
+
const directory = dirname(serverPath);
|
|
1524
|
+
return new Promise((resolve) => {
|
|
1525
|
+
execFile2(serverPath, ["--list-devices"], {
|
|
1526
|
+
timeout: 6e4,
|
|
1527
|
+
windowsHide: true,
|
|
1528
|
+
env: { ...process.env, [variable]: [directory, process.env[variable] ?? ""].filter(Boolean).join(delimiter) }
|
|
1529
|
+
}, (_error, stdout, stderr) => resolve(`${stdout}
|
|
1530
|
+
${stderr}`));
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
async function learnGpuReach(hardware, progress) {
|
|
1534
|
+
const build = vulkanBuild(hardware);
|
|
1535
|
+
if (!build) return hardware;
|
|
1536
|
+
const known = await readReach();
|
|
1537
|
+
const missing = unknownReach(hardware).filter((gpu) => known[reachKey(build, gpu)] === void 0);
|
|
1538
|
+
if (missing.length) {
|
|
1539
|
+
progress?.({ message: "checking the integrated GPU\u2026" });
|
|
1540
|
+
const runtime = await ensureRuntime(build, progress);
|
|
1541
|
+
const devices = parseListedDevices(await listDevices(runtime.serverPath));
|
|
1542
|
+
for (const gpu of missing) known[reachKey(build, gpu)] = matchDevice(gpu, devices)?.totalBytes ?? 0;
|
|
1543
|
+
await mkdir(dirname(reachFile()), { recursive: true });
|
|
1544
|
+
await writeFile(reachFile(), JSON.stringify(known));
|
|
1545
|
+
}
|
|
1546
|
+
return withReach(hardware, build, known);
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
// src/local-models/launch.ts
|
|
1550
|
+
import { createServer } from "node:net";
|
|
1551
|
+
import http from "node:http";
|
|
1552
|
+
function threadPlan(hardware) {
|
|
1553
|
+
const reserve = hardware.physicalCores <= 4 && hardware.physicalCores > 1 ? 1 : 0;
|
|
1554
|
+
const threads = Math.max(1, hardware.physicalCores - reserve);
|
|
1555
|
+
const threadsBatch = Math.max(threads, Math.min(hardware.logicalCores - reserve, Math.floor(threads * 1.5)));
|
|
1556
|
+
return { threads, threadsBatch };
|
|
1557
|
+
}
|
|
1558
|
+
function usesMmap(placement) {
|
|
1559
|
+
return placement !== "cpu";
|
|
1560
|
+
}
|
|
1561
|
+
function buildServerArgs(input) {
|
|
1562
|
+
const { fit } = input;
|
|
1563
|
+
const args = [
|
|
1564
|
+
"--host",
|
|
1565
|
+
"127.0.0.1",
|
|
1566
|
+
"--port",
|
|
1567
|
+
String(input.port),
|
|
1568
|
+
"-m",
|
|
1569
|
+
input.modelPath,
|
|
1570
|
+
"-a",
|
|
1571
|
+
input.alias,
|
|
1572
|
+
"-c",
|
|
1573
|
+
String(fit.context),
|
|
1574
|
+
"-np",
|
|
1575
|
+
String(fit.parallel),
|
|
1576
|
+
// One KV pool shared by the slots. Without it llama.cpp splits -c
|
|
1577
|
+
// evenly (-np 2 at 64K gave each slot 32K), and a conversation would
|
|
1578
|
+
// overflow at half the context this engine reports.
|
|
1579
|
+
"--kv-unified",
|
|
1580
|
+
"--jinja",
|
|
1581
|
+
"-fa",
|
|
1582
|
+
"on",
|
|
1583
|
+
"-t",
|
|
1584
|
+
String(input.threads.threads),
|
|
1585
|
+
"-tb",
|
|
1586
|
+
String(input.threads.threadsBatch),
|
|
1587
|
+
"-ctk",
|
|
1588
|
+
fit.cacheType,
|
|
1589
|
+
"-ctv",
|
|
1590
|
+
fit.cacheType,
|
|
1591
|
+
"--cache-ram",
|
|
1592
|
+
String(input.cacheRamMib),
|
|
1593
|
+
"--no-webui"
|
|
1594
|
+
];
|
|
1595
|
+
if (input.projectorPath) args.push("--mmproj", input.projectorPath);
|
|
1596
|
+
if (!usesMmap(fit.placement)) args.push("--load-mode", "none");
|
|
1597
|
+
if (fit.placement === "gpu") args.push("-ngl", "all");
|
|
1598
|
+
else if (fit.placement === "gpu-partial") args.push("-ngl", "auto", "--fit", "on", "--fit-target", String(input.fitTargetMib ?? 1024));
|
|
1599
|
+
else args.push("-ngl", "0");
|
|
1600
|
+
return args;
|
|
1601
|
+
}
|
|
1602
|
+
var AVOIDED_PORTS = /* @__PURE__ */ new Set([8080, 8091, 8092]);
|
|
1603
|
+
async function freePort() {
|
|
1604
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
1605
|
+
const port = await new Promise((resolve, reject) => {
|
|
1606
|
+
const server = createServer();
|
|
1607
|
+
server.once("error", reject);
|
|
1608
|
+
server.listen(0, "127.0.0.1", () => {
|
|
1609
|
+
const address = server.address();
|
|
1610
|
+
const chosen = typeof address === "object" && address ? address.port : 0;
|
|
1611
|
+
server.close(() => resolve(chosen));
|
|
1612
|
+
});
|
|
1613
|
+
});
|
|
1614
|
+
if (port && !AVOIDED_PORTS.has(port)) return port;
|
|
1615
|
+
}
|
|
1616
|
+
throw new Error("Could not find a free local port for the model server.");
|
|
1617
|
+
}
|
|
1618
|
+
function httpJson(port, method, path, body, timeoutMs = 1e4) {
|
|
1619
|
+
return new Promise((resolve) => {
|
|
1620
|
+
const payload = body === void 0 ? void 0 : JSON.stringify(body);
|
|
1621
|
+
const req = http.request({
|
|
1622
|
+
host: "127.0.0.1",
|
|
1623
|
+
port,
|
|
1624
|
+
method,
|
|
1625
|
+
path,
|
|
1626
|
+
timeout: timeoutMs,
|
|
1627
|
+
headers: payload ? { "content-type": "application/json", "content-length": Buffer.byteLength(payload) } : {}
|
|
1628
|
+
}, (res) => {
|
|
1629
|
+
let text = "";
|
|
1630
|
+
res.on("data", (chunk) => {
|
|
1631
|
+
text += chunk.toString();
|
|
1632
|
+
});
|
|
1633
|
+
res.on("end", () => {
|
|
1634
|
+
let json;
|
|
1635
|
+
try {
|
|
1636
|
+
json = JSON.parse(text);
|
|
1637
|
+
} catch {
|
|
1638
|
+
}
|
|
1639
|
+
resolve({ status: res.statusCode ?? 0, json, text });
|
|
1640
|
+
});
|
|
1641
|
+
});
|
|
1642
|
+
req.on("timeout", () => req.destroy());
|
|
1643
|
+
req.on("error", () => resolve({ status: 0, text: "" }));
|
|
1644
|
+
if (payload) req.write(payload);
|
|
1645
|
+
req.end();
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
async function waitForHealth(port, stillRunning, onWait, limitMs = 15 * 6e4) {
|
|
1649
|
+
const started = Date.now();
|
|
1650
|
+
while (Date.now() - started < limitMs) {
|
|
1651
|
+
const reply = await httpJson(port, "GET", "/health", void 0, 5e3);
|
|
1652
|
+
if (reply.status === 200) return;
|
|
1653
|
+
if (!stillRunning()) throw new Error("the model server exited while loading");
|
|
1654
|
+
onWait(Math.round((Date.now() - started) / 1e3));
|
|
1655
|
+
await sleep(1e3);
|
|
1656
|
+
}
|
|
1657
|
+
throw new Error(`the model server did not become ready within ${Math.round(limitMs / 6e4)} minutes`);
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
// src/local-models/lifecycle.ts
|
|
1661
|
+
import { execFile as execFile3, spawn } from "node:child_process";
|
|
1662
|
+
import { existsSync as existsSync2, readdirSync as readdirSync2, rmSync } from "node:fs";
|
|
1663
|
+
import { mkdir as mkdir2, readdir, readFile as readFile2, rm, writeFile as writeFile2 } from "node:fs/promises";
|
|
1664
|
+
import { join as join3 } from "node:path";
|
|
1665
|
+
import { fileURLToPath } from "node:url";
|
|
1666
|
+
function commandLine(pid) {
|
|
1667
|
+
return new Promise((resolve) => {
|
|
1668
|
+
if (process.platform === "linux") {
|
|
1669
|
+
readFile2(`/proc/${pid}/cmdline`).then((buffer) => resolve(buffer.toString().replace(/\0/g, " ")), () => resolve(""));
|
|
1670
|
+
return;
|
|
1671
|
+
}
|
|
1672
|
+
const [command, args] = process.platform === "win32" ? ["powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`]] : ["ps", ["-o", "command=", "-p", String(pid)]];
|
|
1673
|
+
execFile3(command, args, { timeout: 1e4, windowsHide: true }, (_error, stdout) => resolve(stdout ?? ""));
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
function serverDir(modelId) {
|
|
1677
|
+
return join3(serversDir(), safeName(modelId));
|
|
1678
|
+
}
|
|
1679
|
+
function leasesDir(modelId) {
|
|
1680
|
+
return join3(serverDir(modelId), "leases");
|
|
1681
|
+
}
|
|
1682
|
+
function leaseFile(directory, sessionId, turn = false) {
|
|
1683
|
+
return join3(directory, `${process.pid}-${turn ? "turn-" : ""}${safeName(sessionId)}.json`);
|
|
1684
|
+
}
|
|
1685
|
+
var isTurnLease = (name) => /^\d+-turn-/.test(name);
|
|
1686
|
+
async function writeLeaseFile(directory, sessionId, turn = false) {
|
|
1687
|
+
await mkdir2(directory, { recursive: true });
|
|
1688
|
+
await writeFile2(leaseFile(directory, sessionId, turn), JSON.stringify({ pid: process.pid, session: sessionId, ...turn ? { turn: true } : {}, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
1689
|
+
}
|
|
1690
|
+
async function leaseHeld(directory, options = {}) {
|
|
1691
|
+
const suffix = options.sessionId === void 0 ? "" : `-${safeName(options.sessionId)}.json`;
|
|
1692
|
+
for (const name of await readdir(directory).catch(() => [])) {
|
|
1693
|
+
if (!name.endsWith(suffix)) continue;
|
|
1694
|
+
if (options.sessionId !== void 0 && isTurnLease(name)) continue;
|
|
1695
|
+
const pid = Number(name.slice(0, name.indexOf("-")));
|
|
1696
|
+
if (!(options.elsewhere && pid === process.pid) && pidIsAlive(pid)) return true;
|
|
1697
|
+
}
|
|
1698
|
+
return false;
|
|
1699
|
+
}
|
|
1700
|
+
function removeOwnLeasesSync(directory) {
|
|
1701
|
+
let names = [];
|
|
1702
|
+
try {
|
|
1703
|
+
names = readdirSync2(directory);
|
|
1704
|
+
} catch {
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
for (const name of names) if (name.startsWith(`${process.pid}-`)) rmSync(join3(directory, name), { force: true });
|
|
1708
|
+
}
|
|
1709
|
+
async function writeLease(modelId, sessionId) {
|
|
1710
|
+
await writeLeaseFile(leasesDir(modelId), sessionId);
|
|
1711
|
+
}
|
|
1712
|
+
async function writeTurnLease(modelId, sessionId) {
|
|
1713
|
+
await writeLeaseFile(leasesDir(modelId), sessionId, true);
|
|
1714
|
+
}
|
|
1715
|
+
async function sessionHeldElsewhere(modelId, sessionId) {
|
|
1716
|
+
return leaseHeld(leasesDir(modelId), { sessionId, elsewhere: true });
|
|
1717
|
+
}
|
|
1718
|
+
async function heldByLiveProcess(modelId) {
|
|
1719
|
+
return leaseHeld(leasesDir(modelId));
|
|
1720
|
+
}
|
|
1721
|
+
async function removeLeases(sessionId, keep) {
|
|
1722
|
+
for (const model of await readdir(serversDir()).catch(() => [])) {
|
|
1723
|
+
if (model === (keep && safeName(keep))) continue;
|
|
1724
|
+
await rm(leaseFile(join3(serversDir(), model, "leases"), sessionId), { force: true });
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
async function removeTurnLeases(sessionId, keep) {
|
|
1728
|
+
for (const model of await readdir(serversDir()).catch(() => [])) {
|
|
1729
|
+
if (model === (keep && safeName(keep))) continue;
|
|
1730
|
+
await rm(leaseFile(join3(serversDir(), model, "leases"), sessionId, true), { force: true });
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
function removeAllOwnLeasesSync() {
|
|
1734
|
+
let models = [];
|
|
1735
|
+
try {
|
|
1736
|
+
models = readdirSync2(serversDir());
|
|
1737
|
+
} catch {
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1740
|
+
for (const model of models) removeOwnLeasesSync(join3(serversDir(), model, "leases"));
|
|
1741
|
+
}
|
|
1742
|
+
async function readServerRecord(modelId) {
|
|
1743
|
+
try {
|
|
1744
|
+
return JSON.parse(await readFile2(join3(serverDir(modelId), "supervisor.json"), "utf8"));
|
|
1745
|
+
} catch {
|
|
1746
|
+
return void 0;
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
async function sweepOrphan(modelId) {
|
|
1750
|
+
const record = await readServerRecord(modelId);
|
|
1751
|
+
if (!record || pidIsAlive(record.supervisorPid)) return;
|
|
1752
|
+
if (pidIsAlive(record.serverPid) && /llama-server/.test(await commandLine(record.serverPid))) {
|
|
1753
|
+
await killTree(record.serverPid);
|
|
1754
|
+
}
|
|
1755
|
+
await rm(join3(serverDir(modelId), "supervisor.json"), { force: true });
|
|
1756
|
+
}
|
|
1757
|
+
async function killTree(pid) {
|
|
1758
|
+
if (process.platform === "win32") {
|
|
1759
|
+
await new Promise((resolve) => execFile3("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve()));
|
|
1760
|
+
return;
|
|
1761
|
+
}
|
|
1762
|
+
try {
|
|
1763
|
+
process.kill(pid, "SIGTERM");
|
|
1764
|
+
} catch {
|
|
1765
|
+
return;
|
|
1766
|
+
}
|
|
1767
|
+
for (let waited = 0; waited < 1e4 && pidIsAlive(pid); waited += 250) await sleep(250);
|
|
1768
|
+
if (pidIsAlive(pid)) {
|
|
1769
|
+
try {
|
|
1770
|
+
process.kill(pid, "SIGKILL");
|
|
1771
|
+
} catch {
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
async function withModelLock(lock, work, waiting) {
|
|
1776
|
+
const started = Date.now();
|
|
1777
|
+
let lease;
|
|
1778
|
+
for (; ; ) {
|
|
1779
|
+
if (waiting.signal?.aborted) throw new Error("The download was cancelled.");
|
|
1780
|
+
lease = await tryLease(lock);
|
|
1781
|
+
if (lease) break;
|
|
1782
|
+
if (waiting.timeoutMs !== void 0 && Date.now() - started > waiting.timeoutMs) throw new Error(waiting.timedOut ?? "Timed out waiting for a lock.");
|
|
1783
|
+
await sleep(500);
|
|
1784
|
+
}
|
|
1785
|
+
try {
|
|
1786
|
+
return await work();
|
|
1787
|
+
} finally {
|
|
1788
|
+
await lease.release();
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
async function withStartLock(modelId, work, timeoutMs = 20 * 6e4) {
|
|
1792
|
+
await mkdir2(serverDir(modelId), { recursive: true });
|
|
1793
|
+
return withModelLock(join3(serverDir(modelId), "start.lock"), work, { timeoutMs, timedOut: `Timed out waiting for another ClikCode process to start ${modelId}.` });
|
|
1794
|
+
}
|
|
1795
|
+
async function withDownloadLock(modelId, work, signal) {
|
|
1796
|
+
await mkdir2(serverDir(modelId), { recursive: true });
|
|
1797
|
+
return withModelLock(join3(serverDir(modelId), "download.lock"), work, { ...signal ? { signal } : {} });
|
|
1798
|
+
}
|
|
1799
|
+
function memoryStopFile(modelId) {
|
|
1800
|
+
return join3(serverDir(modelId), "memory-stop.json");
|
|
1801
|
+
}
|
|
1802
|
+
function supervisorEntry() {
|
|
1803
|
+
const candidates = [
|
|
1804
|
+
process.env.CLIKCODE_SUPERVISOR_ENTRY,
|
|
1805
|
+
fileURLToPath(new URL("./local-model-supervisor.cjs", import.meta.url)),
|
|
1806
|
+
fileURLToPath(new URL("../../dist/local-model-supervisor.cjs", import.meta.url))
|
|
1807
|
+
];
|
|
1808
|
+
const found = candidates.find((candidate) => candidate && existsSync2(candidate));
|
|
1809
|
+
if (!found) throw new Error("The local model supervisor is not built (dist/local-model-supervisor.cjs); run the build.");
|
|
1810
|
+
return found;
|
|
1811
|
+
}
|
|
1812
|
+
async function startSupervisor(config) {
|
|
1813
|
+
await mkdir2(config.dir, { recursive: true });
|
|
1814
|
+
await rm(join3(config.dir, "supervisor.json"), { force: true });
|
|
1815
|
+
const configFile = join3(config.dir, "supervisor-config.json");
|
|
1816
|
+
await writeFile2(configFile, JSON.stringify(config));
|
|
1817
|
+
const child = spawn(process.execPath, [supervisorEntry(), configFile], {
|
|
1818
|
+
cwd: config.dir,
|
|
1819
|
+
detached: true,
|
|
1820
|
+
stdio: "ignore",
|
|
1821
|
+
windowsHide: true,
|
|
1822
|
+
// Whatever flags started ClikCode (a loader, an inspector) are not the
|
|
1823
|
+
// supervisor's.
|
|
1824
|
+
env: { ...process.env, NODE_OPTIONS: "" }
|
|
1825
|
+
});
|
|
1826
|
+
child.unref();
|
|
1827
|
+
for (let waited = 0; waited < 3e4; waited += 200) {
|
|
1828
|
+
const record = await readServerRecord(config.modelId);
|
|
1829
|
+
if (record && record.supervisorPid === child.pid) return record;
|
|
1830
|
+
if (child.exitCode !== null) break;
|
|
1831
|
+
await sleep(200);
|
|
1832
|
+
}
|
|
1833
|
+
throw new Error(`The local model supervisor did not start. See ${join3(config.dir, "supervisor.log")}.`);
|
|
1834
|
+
}
|
|
1835
|
+
async function stopServer(modelId) {
|
|
1836
|
+
const record = await readServerRecord(modelId);
|
|
1837
|
+
if (!record) return;
|
|
1838
|
+
if (pidIsAlive(record.supervisorPid)) {
|
|
1839
|
+
if (process.platform === "win32") {
|
|
1840
|
+
await killTree(record.serverPid);
|
|
1841
|
+
}
|
|
1842
|
+
try {
|
|
1843
|
+
process.kill(record.supervisorPid, "SIGTERM");
|
|
1844
|
+
} catch {
|
|
1845
|
+
}
|
|
1846
|
+
for (let waited = 0; waited < 15e3 && pidIsAlive(record.supervisorPid); waited += 250) await sleep(250);
|
|
1847
|
+
}
|
|
1848
|
+
await sweepOrphan(modelId);
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
// src/local-models/measure.ts
|
|
1852
|
+
import { createHash } from "node:crypto";
|
|
1853
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
1854
|
+
function machineKey(hardware, runtimeKey) {
|
|
1855
|
+
const identity = [
|
|
1856
|
+
hardware.cpuModel,
|
|
1857
|
+
hardware.physicalCores,
|
|
1858
|
+
hardware.logicalCores,
|
|
1859
|
+
Math.round(hardware.totalRamBytes / 1024 ** 3),
|
|
1860
|
+
...hardware.gpus.map((gpu) => `${gpu.name}:${Math.round(gpu.vramBytes / 1024 ** 3)}`),
|
|
1861
|
+
runtimeKey
|
|
1862
|
+
].join("|");
|
|
1863
|
+
return createHash("sha256").update(identity).digest("hex").slice(0, 16);
|
|
1864
|
+
}
|
|
1865
|
+
async function readStore() {
|
|
1866
|
+
try {
|
|
1867
|
+
return JSON.parse(await readFile3(measurementsFile(), "utf8"));
|
|
1868
|
+
} catch {
|
|
1869
|
+
return {};
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
async function readMeasurements(machine) {
|
|
1873
|
+
return (await readStore())[machine] ?? {};
|
|
1874
|
+
}
|
|
1875
|
+
async function latestMeasurement(modelId) {
|
|
1876
|
+
let latest;
|
|
1877
|
+
for (const byModel of Object.values(await readStore())) {
|
|
1878
|
+
const entry = byModel?.[modelId];
|
|
1879
|
+
if (entry && (!latest || String(entry.at) > String(latest.at))) latest = entry;
|
|
1880
|
+
}
|
|
1881
|
+
return latest;
|
|
1882
|
+
}
|
|
1883
|
+
async function writeMeasurement(machine, modelId, measurement) {
|
|
1884
|
+
await updateJsonFile(
|
|
1885
|
+
measurementsFile(),
|
|
1886
|
+
(raw) => objectOrEmpty(raw),
|
|
1887
|
+
(store) => ({ ...store, [machine]: { ...store[machine], [modelId]: measurement } })
|
|
1888
|
+
);
|
|
1889
|
+
}
|
|
1890
|
+
function footprintKey(config) {
|
|
1891
|
+
return `${config.context}|${config.cacheType}|${config.parallel}|${config.vision ? "vision" : "text"}`;
|
|
1892
|
+
}
|
|
1893
|
+
async function readFootprints(machine, modelIds) {
|
|
1894
|
+
const result = {};
|
|
1895
|
+
for (const modelId of modelIds) {
|
|
1896
|
+
let store = {};
|
|
1897
|
+
try {
|
|
1898
|
+
store = JSON.parse(await readFile3(footprintsFile(modelId), "utf8"));
|
|
1899
|
+
} catch {
|
|
1900
|
+
}
|
|
1901
|
+
const entries = Object.values(store[machine] ?? {}).filter((entry) => entry && typeof entry.anonBytes === "number");
|
|
1902
|
+
if (entries.length) result[modelId] = entries;
|
|
1903
|
+
}
|
|
1904
|
+
return result;
|
|
1905
|
+
}
|
|
1906
|
+
function measurementPrompt() {
|
|
1907
|
+
const numbers = Array.from({ length: 240 }, (_, index) => `${index * 7 + 3}`).join(", ");
|
|
1908
|
+
return `Here is a list of numbers: ${numbers}.
|
|
1909
|
+
Describe the pattern in these numbers in a few sentences.`;
|
|
1910
|
+
}
|
|
1911
|
+
var NO_THINKING = { chat_template_kwargs: { enable_thinking: false }, reasoning_effort: "low" };
|
|
1912
|
+
function positive(value) {
|
|
1913
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
1914
|
+
}
|
|
1915
|
+
async function measureServer(port, alias) {
|
|
1916
|
+
const speed = await httpJson(port, "POST", "/v1/chat/completions", {
|
|
1917
|
+
model: alias,
|
|
1918
|
+
max_tokens: 64,
|
|
1919
|
+
temperature: 0,
|
|
1920
|
+
cache_prompt: false,
|
|
1921
|
+
...NO_THINKING,
|
|
1922
|
+
messages: [{ role: "user", content: measurementPrompt() }]
|
|
1923
|
+
}, 10 * 6e4);
|
|
1924
|
+
const timings = speed.json?.timings;
|
|
1925
|
+
const tool = await httpJson(port, "POST", "/v1/chat/completions", {
|
|
1926
|
+
model: alias,
|
|
1927
|
+
max_tokens: 512,
|
|
1928
|
+
temperature: 0,
|
|
1929
|
+
...NO_THINKING,
|
|
1930
|
+
messages: [{ role: "user", content: "What time is it right now? Use the get_time tool." }],
|
|
1931
|
+
tools: [{ type: "function", function: { name: "get_time", description: "Returns the current time", parameters: { type: "object", properties: {} } } }],
|
|
1932
|
+
tool_choice: "auto"
|
|
1933
|
+
}, 10 * 6e4);
|
|
1934
|
+
const calls = tool.json?.choices?.[0]?.message?.tool_calls ?? [];
|
|
1935
|
+
const promptPerSecond = positive(timings?.prompt_per_second);
|
|
1936
|
+
const generatePerSecond = positive(timings?.predicted_per_second);
|
|
1937
|
+
return {
|
|
1938
|
+
...promptPerSecond ? { promptPerSecond } : {},
|
|
1939
|
+
...generatePerSecond ? { generatePerSecond } : {},
|
|
1940
|
+
toolCalls: calls.some((call) => call.function?.name === "get_time"),
|
|
1941
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1942
|
+
};
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
// src/local-models/memory-steps.ts
|
|
1946
|
+
function contextLabel(tokens) {
|
|
1947
|
+
return `${Math.round(tokens / 1024)}K`;
|
|
1948
|
+
}
|
|
1949
|
+
function shrinkNotice(event) {
|
|
1950
|
+
if (event?.action !== "shrink" || !event.toContext) return void 0;
|
|
1951
|
+
const label = catalogModel(event.modelId)?.label ?? event.modelId;
|
|
1952
|
+
return `${label} was restarted at ${contextLabel(event.toContext)} context (from ${contextLabel(event.fromContext)}) to leave memory for other programs: ${event.reason}.`;
|
|
1953
|
+
}
|
|
1954
|
+
function stopNotice(stops, chosen, fit) {
|
|
1955
|
+
const last = stops.at(-1);
|
|
1956
|
+
if (!last) return void 0;
|
|
1957
|
+
const label = catalogModel(last.modelId)?.label ?? last.modelId;
|
|
1958
|
+
const when = new Date(last.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
1959
|
+
const stopped = `${label} was stopped at ${when} to leave memory for other programs (${last.reason}).`;
|
|
1960
|
+
if (!fit) return stopped;
|
|
1961
|
+
if (last.modelId === chosen.id) return `${stopped} Restarted with ${contextLabel(fit.context)} context, which fits what is free now.`;
|
|
1962
|
+
return `${stopped} Chose ${chosen.label} at ${contextLabel(fit.context)} context because it fits what is free now.`;
|
|
1963
|
+
}
|
|
1964
|
+
function shrinkSteps(model, fit, cacheRamMib, vision, args) {
|
|
1965
|
+
const steps = [];
|
|
1966
|
+
const step = (context) => ({
|
|
1967
|
+
context,
|
|
1968
|
+
cacheRamMib: 0,
|
|
1969
|
+
kvBytes: kvCacheBytes(model.kv, context, fit.cacheType, fit.parallel),
|
|
1970
|
+
args: args(context, 0),
|
|
1971
|
+
footprintKey: footprintKey({ context, cacheType: fit.cacheType, parallel: fit.parallel, vision })
|
|
1972
|
+
});
|
|
1973
|
+
if (cacheRamMib > 0) steps.push(step(fit.context));
|
|
1974
|
+
for (let context = Math.floor(fit.context / 2); context >= MIN_CONTEXT; context = Math.floor(context / 2)) steps.push(step(context));
|
|
1975
|
+
return steps;
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
// src/local-models/index.ts
|
|
1979
|
+
var IDLE_MS = 15 * 6e4;
|
|
1980
|
+
async function downloaded(modelId) {
|
|
1981
|
+
const model = catalogModel(modelId);
|
|
1982
|
+
return Boolean(model) && await missingBytes(weightFiles(model)) === 0;
|
|
1983
|
+
}
|
|
1984
|
+
async function readPreference() {
|
|
1985
|
+
try {
|
|
1986
|
+
return JSON.parse(await readFile4(preferencesFile(), "utf8")).modelId;
|
|
1987
|
+
} catch {
|
|
1988
|
+
return void 0;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
async function setLocalModelPreference(modelId) {
|
|
1992
|
+
if (!modelId) {
|
|
1993
|
+
await rm2(preferencesFile(), { force: true });
|
|
1994
|
+
return;
|
|
1995
|
+
}
|
|
1996
|
+
if (!catalogModel(modelId)) throw new Error(`${modelId} is not a model this computer can run.`);
|
|
1997
|
+
await mkdir3(dirname2(preferencesFile()), { recursive: true });
|
|
1998
|
+
await writeFile3(preferencesFile(), JSON.stringify({ modelId, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
1999
|
+
}
|
|
2000
|
+
async function viewMachine(probed) {
|
|
2001
|
+
startCatalogRefresh();
|
|
2002
|
+
const hardware = probed ?? await withKnownReach(await probeHardware());
|
|
2003
|
+
const budget = memoryBudget(hardware);
|
|
2004
|
+
const build = selectRuntimeBuild(hardware, budget.gpu);
|
|
2005
|
+
if (!build) throw new Error(noRuntimeReason(hardware));
|
|
2006
|
+
const effective = budget.gpu && build.backend !== budget.gpu.backend ? { ...budget, gpu: void 0 } : budget;
|
|
2007
|
+
const machine = machineKey(hardware, build.key);
|
|
2008
|
+
return {
|
|
2009
|
+
hardware,
|
|
2010
|
+
budget: effective,
|
|
2011
|
+
build,
|
|
2012
|
+
machine,
|
|
2013
|
+
measurements: await readMeasurements(machine),
|
|
2014
|
+
footprints: await readFootprints(machine, allLocalModels().map((model) => model.id))
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
async function prefetchLocalModel(modelId, progress, signal) {
|
|
2018
|
+
if (!catalogModel(modelId)) throw new Error(`${modelId} is not a model this computer can run.`);
|
|
2019
|
+
progress({ stage: "probe", message: "checking this machine\u2026" });
|
|
2020
|
+
const view = await viewMachine(await learnGpuReach(await probeHardware(), (update) => progress({ stage: "runtime", ...update })));
|
|
2021
|
+
const choice = chooseModel(rankModels(allLocalModels(), view.hardware, view.budget, view.measurements, view.footprints), modelId);
|
|
2022
|
+
await ensureRuntime(view.build, (update) => progress({ stage: "runtime", ...update }));
|
|
2023
|
+
await ensureModelWeights(choice.row.model, (update) => progress({ stage: "download", ...update }), signal);
|
|
2024
|
+
}
|
|
2025
|
+
async function liveServer(modelId) {
|
|
2026
|
+
const record = await readServerRecord(modelId);
|
|
2027
|
+
if (!record || !pidIsAlive(record.supervisorPid)) return void 0;
|
|
2028
|
+
if (!record.restarting && !pidIsAlive(record.serverPid)) return void 0;
|
|
2029
|
+
return record;
|
|
2030
|
+
}
|
|
2031
|
+
async function runningModels() {
|
|
2032
|
+
const records = [];
|
|
2033
|
+
for (const name of await readdir2(serversDir()).catch(() => [])) {
|
|
2034
|
+
const model = allLocalModels().find((item) => item.id === name);
|
|
2035
|
+
const record = model ? await liveServer(model.id) : void 0;
|
|
2036
|
+
if (record) records.push(record);
|
|
2037
|
+
}
|
|
2038
|
+
return records;
|
|
2039
|
+
}
|
|
2040
|
+
function logTail(modelId) {
|
|
2041
|
+
return readFile4(join4(serverDir(modelId), "server.log"), "utf8").then((text) => text.trim().split(/\r?\n/).slice(-8).join("\n"), () => "");
|
|
2042
|
+
}
|
|
2043
|
+
function describe(model, measured) {
|
|
2044
|
+
if (!measured) return void 0;
|
|
2045
|
+
const notes = [];
|
|
2046
|
+
if (!measured.toolCalls) notes.push(`${model.label} did not make a tool call when asked, so tools may not work with it.`);
|
|
2047
|
+
if (!meetsBar(measured)) {
|
|
2048
|
+
notes.push(`Near empty context ${model.label} reads about ${Math.round(measured.promptPerSecond ?? 0)} tokens/s and writes ${Math.round(measured.generatePerSecond ?? 0)}; replies will be slow.`);
|
|
2049
|
+
}
|
|
2050
|
+
return notes.length ? notes.join(" ") : void 0;
|
|
2051
|
+
}
|
|
2052
|
+
async function takeMemoryStops() {
|
|
2053
|
+
const events = [];
|
|
2054
|
+
for (const model of allLocalModels()) {
|
|
2055
|
+
const file = memoryStopFile(model.id);
|
|
2056
|
+
const event = await readFile4(file, "utf8").then((text) => JSON.parse(text), () => void 0);
|
|
2057
|
+
if (!event) continue;
|
|
2058
|
+
await rm2(file, { force: true });
|
|
2059
|
+
events.push(event);
|
|
2060
|
+
}
|
|
2061
|
+
return events.sort((left, right) => left.at.localeCompare(right.at));
|
|
2062
|
+
}
|
|
2063
|
+
async function ensureLocalModel(options) {
|
|
2064
|
+
const progress = options.progress ?? (() => {
|
|
2065
|
+
});
|
|
2066
|
+
const take = (modelId) => options.forTurn ? writeTurnLease(modelId, options.sessionId) : writeLease(modelId, options.sessionId);
|
|
2067
|
+
const dropOthers = (keep) => options.forTurn ? removeTurnLeases(options.sessionId, keep) : removeLeases(options.sessionId, keep);
|
|
2068
|
+
if (options.modelId && (options.allowDownload || await downloaded(options.modelId))) await setLocalModelPreference(options.modelId);
|
|
2069
|
+
const preferred = options.modelId ? void 0 : await readPreference();
|
|
2070
|
+
const pick = options.modelId ?? (preferred && await downloaded(preferred) ? preferred : void 0);
|
|
2071
|
+
const running = pick ? [await liveServer(pick)].filter((record2) => Boolean(record2)) : await runningModels();
|
|
2072
|
+
let joinable = running.sort((left, right) => (catalogModel(right.modelId)?.quality ?? 0) - (catalogModel(left.modelId)?.quality ?? 0))[0];
|
|
2073
|
+
let healthy = Boolean(joinable) && (await httpJson(joinable.port, "GET", "/health", void 0, 3e3)).status === 200;
|
|
2074
|
+
if (joinable && !healthy && joinable.restarting) {
|
|
2075
|
+
const restarting = joinable;
|
|
2076
|
+
const label = catalogModel(restarting.modelId)?.label ?? restarting.modelId;
|
|
2077
|
+
healthy = await waitForHealth(
|
|
2078
|
+
restarting.port,
|
|
2079
|
+
() => pidIsAlive(restarting.supervisorPid),
|
|
2080
|
+
(seconds) => progress({ stage: "start", message: `${label} is restarting smaller to leave memory for other programs\u2026 ${seconds}s` })
|
|
2081
|
+
).then(() => true, () => false);
|
|
2082
|
+
joinable = await liveServer(restarting.modelId);
|
|
2083
|
+
}
|
|
2084
|
+
if (joinable && healthy) {
|
|
2085
|
+
if (options.forTurn || !await sessionHeldElsewhere(joinable.modelId, options.sessionId)) await take(joinable.modelId);
|
|
2086
|
+
await dropOthers(joinable.modelId);
|
|
2087
|
+
const notice2 = shrinkNotice(joinable.memoryEvent);
|
|
2088
|
+
const speed2 = (await latestMeasurement(joinable.modelId))?.promptPerSecond;
|
|
2089
|
+
return {
|
|
2090
|
+
baseUrl: `http://127.0.0.1:${joinable.port}/v1`,
|
|
2091
|
+
model: joinable.alias,
|
|
2092
|
+
contextWindow: joinable.context,
|
|
2093
|
+
...speed2 ? { promptPerSecond: speed2 } : {},
|
|
2094
|
+
...notice2 ? { notice: notice2 } : {}
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
if (joinable && !healthy) {
|
|
2098
|
+
const leaving = joinable;
|
|
2099
|
+
const label = catalogModel(leaving.modelId)?.label ?? leaving.modelId;
|
|
2100
|
+
const deadline = Date.now() + 6e4;
|
|
2101
|
+
while (pidIsAlive(leaving.supervisorPid) && Date.now() < deadline) {
|
|
2102
|
+
progress({ stage: "start", message: `waiting for the previous ${label} to finish stopping\u2026` });
|
|
2103
|
+
await sleep(500);
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
for (const leftover of await runningModels()) {
|
|
2107
|
+
if (leftover.modelId === joinable?.modelId || await heldByLiveProcess(leftover.modelId)) continue;
|
|
2108
|
+
progress({ stage: "start", message: `stopping ${catalogModel(leftover.modelId)?.label ?? leftover.modelId}, which nothing is using\u2026` });
|
|
2109
|
+
await stopServer(leftover.modelId);
|
|
2110
|
+
}
|
|
2111
|
+
progress({ stage: "probe", message: "checking this machine\u2026" });
|
|
2112
|
+
const view = await viewMachine(await learnGpuReach(await probeHardware(), (update) => progress({ stage: "runtime", ...update })));
|
|
2113
|
+
const stops = await takeMemoryStops();
|
|
2114
|
+
const ranked = rankModels(allLocalModels(), view.hardware, view.budget, view.measurements, view.footprints);
|
|
2115
|
+
const eligible = pick ? ranked : (await Promise.all(ranked.map(async (row) => ({ row, bytes: await missingBytes(weightFiles(row.model)) })))).filter(({ bytes }) => bytes === 0).map(({ row }) => row);
|
|
2116
|
+
let choice;
|
|
2117
|
+
try {
|
|
2118
|
+
choice = chooseModel(eligible, pick);
|
|
2119
|
+
} catch (error) {
|
|
2120
|
+
const stopped = ranked[0] ? stopNotice(stops, ranked[0].model, void 0) : void 0;
|
|
2121
|
+
if (!pick && !eligible.length) throw new Error("Choose a model for this computer with /model before its first download.");
|
|
2122
|
+
throw stopped ? new Error(`${stopped} ${error.message}`) : error;
|
|
2123
|
+
}
|
|
2124
|
+
const model = choice.row.model;
|
|
2125
|
+
let startedFit;
|
|
2126
|
+
const record = await withStartLock(model.id, async () => {
|
|
2127
|
+
const started = await liveServer(model.id);
|
|
2128
|
+
if (started) {
|
|
2129
|
+
await take(model.id);
|
|
2130
|
+
return started;
|
|
2131
|
+
}
|
|
2132
|
+
await sweepOrphan(model.id);
|
|
2133
|
+
const vision = Boolean(options.vision && model.projector);
|
|
2134
|
+
const fit = !options.context && !vision ? choice.row.fit : fitModel(model, view.budget, {
|
|
2135
|
+
...options.context ? { context: options.context } : { context: choice.row.fit.context },
|
|
2136
|
+
vision,
|
|
2137
|
+
footprints: view.footprints[model.id] ?? []
|
|
2138
|
+
});
|
|
2139
|
+
if (!fit.fits) throw new Error(`${model.label} would exceed the memory this machine can spare: ${fit.reason}.`);
|
|
2140
|
+
startedFit = fit;
|
|
2141
|
+
if (!options.allowDownload && await missingBytes([...weightFiles(model), ...vision && model.projector ? [model.projector] : []])) {
|
|
2142
|
+
throw new Error(`${model.label} is not downloaded. Open /model and confirm its download first.`);
|
|
2143
|
+
}
|
|
2144
|
+
const runtime = await ensureRuntime(view.build, (update) => progress({ stage: "runtime", ...update }));
|
|
2145
|
+
const modelPath = await ensureModelWeights(model, (update) => progress({ stage: "download", ...update }), options.signal);
|
|
2146
|
+
const projectorPath = options.vision && model.projector ? await ensureModelFile(model.projector, (update) => progress({ stage: "download", ...update }), options.signal) : void 0;
|
|
2147
|
+
await take(model.id);
|
|
2148
|
+
try {
|
|
2149
|
+
const port = await freePort();
|
|
2150
|
+
const ramPart = fit.needBytes - fit.gpuBytes;
|
|
2151
|
+
const cacheRamMib = Math.max(0, Math.min(2048, Math.floor((view.budget.ramBytes - ramPart) / 1024 ** 2)));
|
|
2152
|
+
const argsFor = (context, cacheRam) => buildServerArgs({
|
|
2153
|
+
modelPath,
|
|
2154
|
+
...projectorPath ? { projectorPath } : {},
|
|
2155
|
+
port,
|
|
2156
|
+
alias: model.id,
|
|
2157
|
+
fit: { ...fit, context },
|
|
2158
|
+
threads: threadPlan(view.hardware),
|
|
2159
|
+
cacheRamMib: cacheRam,
|
|
2160
|
+
...view.budget.gpu ? { fitTargetMib: view.budget.gpu.fitTargetMib } : {}
|
|
2161
|
+
});
|
|
2162
|
+
const args = argsFor(fit.context, cacheRamMib);
|
|
2163
|
+
const watched = fit.placement === "cpu" || Boolean(view.budget.gpu?.unified);
|
|
2164
|
+
const libraryVariable = process.platform === "win32" ? "PATH" : process.platform === "darwin" ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH";
|
|
2165
|
+
progress({ stage: "start", message: `starting ${model.label}\u2026` });
|
|
2166
|
+
const started2 = await startSupervisor({
|
|
2167
|
+
modelId: model.id,
|
|
2168
|
+
alias: model.id,
|
|
2169
|
+
context: fit.context,
|
|
2170
|
+
port,
|
|
2171
|
+
command: runtime.serverPath,
|
|
2172
|
+
args,
|
|
2173
|
+
env: { [libraryVariable]: [runtime.directory, process.env[libraryVariable] ?? ""].filter(Boolean).join(delimiter2) },
|
|
2174
|
+
dir: serverDir(model.id),
|
|
2175
|
+
idleMs: IDLE_MS,
|
|
2176
|
+
pollMs: 2e3,
|
|
2177
|
+
...watched ? {
|
|
2178
|
+
memory: {
|
|
2179
|
+
bufferBytes: view.budget.bufferBytes,
|
|
2180
|
+
sampleMs: 2e3,
|
|
2181
|
+
footprintsFile: footprintsFile(model.id),
|
|
2182
|
+
machine: view.machine,
|
|
2183
|
+
cacheType: fit.cacheType,
|
|
2184
|
+
parallel: fit.parallel,
|
|
2185
|
+
vision,
|
|
2186
|
+
mmap: usesMmap(fit.placement),
|
|
2187
|
+
current: {
|
|
2188
|
+
context: fit.context,
|
|
2189
|
+
cacheRamMib,
|
|
2190
|
+
kvBytes: kvCacheBytes(model.kv, fit.context, fit.cacheType, fit.parallel),
|
|
2191
|
+
footprintKey: footprintKey({ context: fit.context, cacheType: fit.cacheType, parallel: fit.parallel, vision })
|
|
2192
|
+
},
|
|
2193
|
+
shrinks: shrinkSteps(model, fit, cacheRamMib, vision, argsFor)
|
|
2194
|
+
}
|
|
2195
|
+
} : {}
|
|
2196
|
+
});
|
|
2197
|
+
await waitForHealth(
|
|
2198
|
+
port,
|
|
2199
|
+
() => pidIsAlive(started2.supervisorPid),
|
|
2200
|
+
(seconds) => progress({ stage: "start", message: `loading ${model.label}\u2026 ${seconds}s` })
|
|
2201
|
+
);
|
|
2202
|
+
return started2;
|
|
2203
|
+
} catch (error) {
|
|
2204
|
+
await dropOthers();
|
|
2205
|
+
await stopServer(model.id);
|
|
2206
|
+
const tail = await logTail(model.id);
|
|
2207
|
+
throw new Error(`${model.label} did not start: ${error.message}${tail ? `
|
|
2208
|
+
${tail}` : ""}`);
|
|
2209
|
+
}
|
|
2210
|
+
});
|
|
2211
|
+
await dropOthers(model.id);
|
|
2212
|
+
await waitForHealth(
|
|
2213
|
+
record.port,
|
|
2214
|
+
() => pidIsAlive(record.supervisorPid),
|
|
2215
|
+
(seconds) => progress({ stage: "start", message: `loading ${model.label}\u2026 ${seconds}s` })
|
|
2216
|
+
);
|
|
2217
|
+
let measured = view.measurements[model.id];
|
|
2218
|
+
if (!measured) {
|
|
2219
|
+
progress({ stage: "measure", message: `measuring ${model.label} on this machine\u2026` });
|
|
2220
|
+
measured = await measureServer(record.port, record.alias);
|
|
2221
|
+
await writeMeasurement(view.machine, model.id, measured);
|
|
2222
|
+
}
|
|
2223
|
+
const notice = [stopNotice(stops, model, startedFit ?? { context: record.context }), choice.notice, describe(model, measured)].filter(Boolean).join(" ") || void 0;
|
|
2224
|
+
const speed = (await latestMeasurement(model.id))?.promptPerSecond;
|
|
2225
|
+
return {
|
|
2226
|
+
baseUrl: `http://127.0.0.1:${record.port}/v1`,
|
|
2227
|
+
model: record.alias,
|
|
2228
|
+
contextWindow: record.context,
|
|
2229
|
+
...speed ? { promptPerSecond: speed } : {},
|
|
2230
|
+
...notice ? { notice } : {}
|
|
2231
|
+
};
|
|
2232
|
+
}
|
|
2233
|
+
async function releaseLocalModel(sessionId) {
|
|
2234
|
+
await removeLeases(sessionId);
|
|
2235
|
+
}
|
|
2236
|
+
async function releaseLocalModelTurn(sessionId) {
|
|
2237
|
+
await removeTurnLeases(sessionId);
|
|
2238
|
+
}
|
|
2239
|
+
async function holdRunningLocalModel(sessionId, modelId) {
|
|
2240
|
+
const record = modelId ? await liveServer(modelId) : (await runningModels())[0];
|
|
2241
|
+
if (!record) return false;
|
|
2242
|
+
await writeLease(record.modelId, sessionId);
|
|
2243
|
+
await removeLeases(sessionId, record.modelId);
|
|
2244
|
+
return true;
|
|
2245
|
+
}
|
|
2246
|
+
var exitHookInstalled = false;
|
|
2247
|
+
function releaseLocalModelsOnExit() {
|
|
2248
|
+
if (exitHookInstalled) return;
|
|
2249
|
+
exitHookInstalled = true;
|
|
2250
|
+
process.once("exit", removeAllOwnLeasesSync);
|
|
2251
|
+
}
|
|
2252
|
+
function placementLabel(row, view) {
|
|
2253
|
+
const gpu = view.budget.gpu?.backend.toUpperCase();
|
|
2254
|
+
return row.fit.placement === "cpu" ? "CPU" : row.fit.placement === "gpu" ? gpu ?? "GPU" : `${gpu ?? "GPU"}+CPU`;
|
|
2255
|
+
}
|
|
2256
|
+
async function localModelChoices(query) {
|
|
2257
|
+
const initial = await viewMachine();
|
|
2258
|
+
await discoverHuggingFaceModels(weightCapacityBytes(initial.hardware), query ? { query } : {});
|
|
2259
|
+
const view = await viewMachine();
|
|
2260
|
+
const rows = [];
|
|
2261
|
+
for (const row of rankModels(allLocalModels(), view.hardware, view.budget, view.measurements, view.footprints)) {
|
|
2262
|
+
if (!row.fit.fits) continue;
|
|
2263
|
+
const downloadBytes = await missingBytes(weightFiles(row.model));
|
|
2264
|
+
const basis = row.fit.placement === "cpu" ? "estimated at 80% context" : "short-context estimate; deep GPU speed unverified";
|
|
2265
|
+
const speed = row.measured?.promptPerSecond ? `${basis}: ${Math.round(row.speed.promptPerSecond)} tok/s reading, ${Math.round(row.speed.generatePerSecond)} writing (calibrated after a short run)${row.measured.toolCalls ? "" : ", no tool calls"}` : `${basis}: ${Math.round(row.speed.promptPerSecond)} tok/s reading, ${Math.round(row.speed.generatePerSecond)} writing`;
|
|
2266
|
+
const first = row.firstReply;
|
|
2267
|
+
const firstLabel = `first reply ~${Math.round(first.brief)}\u2013${Math.round(first.long)}s after loading`;
|
|
2268
|
+
const parts = [
|
|
2269
|
+
placementLabel(row, view),
|
|
2270
|
+
firstLabel,
|
|
2271
|
+
speed,
|
|
2272
|
+
`${Math.round(row.fit.context / 1024)}K context`,
|
|
2273
|
+
...row.model.discovered ? [`Hugging Face ${row.model.weights.repo}`, "tool use unverified"] : []
|
|
2274
|
+
];
|
|
2275
|
+
parts.push(downloadBytes ? `${formatBytes(downloadBytes)} download` : "downloaded");
|
|
2276
|
+
const writing = Math.round(row.speed.generatePerSecond);
|
|
2277
|
+
const brief = [
|
|
2278
|
+
downloadBytes ? `${formatBytes(downloadBytes)} download` : "downloaded",
|
|
2279
|
+
writing > 0 ? `~${writing} tok/s` : "",
|
|
2280
|
+
// The one caveat that changes a choice: a coding agent needs tool calls, and a model found on Hugging Face has not shown it can.
|
|
2281
|
+
...row.model.discovered ? ["tool use unverified"] : []
|
|
2282
|
+
].filter(Boolean).join(" \xB7 ");
|
|
2283
|
+
rows.push({ id: row.model.id, label: row.model.label, repo: row.model.weights.repo, detail: parts.join(" \xB7 "), brief, fits: row.fit.fits, recommended: row.passes, downloadBytes });
|
|
2284
|
+
}
|
|
2285
|
+
return rows;
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
// src/agent/models/for-session.ts
|
|
2289
|
+
function gatewayConnection(config) {
|
|
2290
|
+
const baseUrl = getApiUrl(config).replace(/\/$/, "");
|
|
2291
|
+
const apiKey = getApiKeyForUrl(config, baseUrl);
|
|
2292
|
+
if (!apiKey) throw new Error(`ClikDeploy Gateway is not connected; run \`${harnessCommand()} gateway login\` first`);
|
|
2293
|
+
return { baseUrl, apiKey };
|
|
2294
|
+
}
|
|
2295
|
+
var GATEWAY_ERROR_CODES = {
|
|
2296
|
+
rate_limit_exceeded: "MODEL_RATE_LIMITED",
|
|
2297
|
+
upstream_error: "MODEL_ERROR",
|
|
2298
|
+
model_busy: "MODEL_BUSY",
|
|
2299
|
+
capacity_busy: "MODEL_BUSY",
|
|
2300
|
+
internal_error: "INTERNAL_ERROR",
|
|
2301
|
+
context_length_exceeded: "CONTEXT_TOO_LARGE",
|
|
2302
|
+
model_not_found: "MODEL_UNAVAILABLE",
|
|
2303
|
+
no_model_available: "NO_MODEL_AVAILABLE",
|
|
2304
|
+
gateway_disabled: "CLIKCODE_DISABLED",
|
|
2305
|
+
insufficient_credits: "AI_CREDIT_EXHAUSTED",
|
|
2306
|
+
// The user's own model, waking or loading on its GPU (ClikDeploy compute): waited for, not an error.
|
|
2307
|
+
model_starting: "MODEL_STARTING"
|
|
2308
|
+
};
|
|
2309
|
+
function gatewayErrorMessage(error) {
|
|
2310
|
+
const command = harnessCommand();
|
|
2311
|
+
const wait = error.retryAfter === void 0 ? "Try again in a minute." : `Try again in ${error.retryAfter < 90 ? `${Math.ceil(error.retryAfter)}s` : `${Math.ceil(error.retryAfter / 60)} min`}.`;
|
|
2312
|
+
const hint = {
|
|
2313
|
+
insufficient_credits: `Run \`${command} gateway credit\` to add credit.`,
|
|
2314
|
+
rate_limit_exceeded: wait,
|
|
2315
|
+
model_not_found: "Pick another model with /model, or let the Gateway choose (Automatic).",
|
|
2316
|
+
no_model_available: "No model can take this request right now: try again shortly, or pick one with /model.",
|
|
2317
|
+
gateway_disabled: "ClikDeploy Gateway is turned off for this account; switch provider with /model meanwhile."
|
|
2318
|
+
}[error.code ?? (error.status === 402 ? "insufficient_credits" : error.status === 429 ? "rate_limit_exceeded" : "")];
|
|
2319
|
+
return hint ? `${error.message} ${hint}` : void 0;
|
|
2320
|
+
}
|
|
2321
|
+
function gatewayModelClient(input) {
|
|
2322
|
+
const client = new OpenAIModelClient({
|
|
2323
|
+
baseUrl: input.baseUrl.replace(/\/+$/, ""),
|
|
2324
|
+
apiKey: input.apiKey,
|
|
2325
|
+
model: input.model ?? "auto",
|
|
2326
|
+
label: "ClikDeploy Gateway",
|
|
2327
|
+
privateReasoning: true,
|
|
2328
|
+
hosted: true,
|
|
2329
|
+
headers: {
|
|
2330
|
+
"x-client": `clikcode/${CLIKCODE_VERSION}`,
|
|
2331
|
+
...input.sessionId ? { "x-session-id": input.sessionId } : {},
|
|
2332
|
+
...subscriptionsHeader(input.subscriptions ?? true)
|
|
2333
|
+
},
|
|
2334
|
+
errorCodes: GATEWAY_ERROR_CODES,
|
|
2335
|
+
// A hosted model starts answering in seconds: the long first-chunk wait
|
|
2336
|
+
// is for a CPU reading a deep prompt, not for a stalled connection. The
|
|
2337
|
+
// Gateway sends a `: keepalive` comment every 15s while a step is open,
|
|
2338
|
+
// and every byte of one restarts the clock (gateway-client.ts readWithin),
|
|
2339
|
+
// so a step thinking or writing a long call is never cut and resent.
|
|
2340
|
+
firstChunkTimeoutMs: STREAM_IDLE_TIMEOUT_MS,
|
|
2341
|
+
describeError: gatewayErrorMessage,
|
|
2342
|
+
...input.contextWindow ? { contextWindow: input.contextWindow } : {},
|
|
2343
|
+
...input.maxOutput ? { maxOutputTokens: input.maxOutput } : {},
|
|
2344
|
+
...input.vision ? { vision: true } : {},
|
|
2345
|
+
...input.options && Object.keys(input.options).length ? { body: input.options } : {},
|
|
2346
|
+
...input.fetchImpl ? { fetchImpl: input.fetchImpl } : {}
|
|
2347
|
+
});
|
|
2348
|
+
const model = input.model;
|
|
2349
|
+
if (model) client.startStatus = async () => (await import("./chunk-DKDPZTD3.js")).ownModelStatus(model, { timeoutMs: 4e3 }).then((status) => status.start);
|
|
2350
|
+
return client;
|
|
2351
|
+
}
|
|
2352
|
+
async function gatewayModelFacts(session, config) {
|
|
2353
|
+
try {
|
|
2354
|
+
const { savedGatewayModels, gatewayModels, sameGatewayModel } = await import("./chunk-BXPQFSX5.js");
|
|
2355
|
+
let list = await savedGatewayModels({ config });
|
|
2356
|
+
const fetchedNow = !list;
|
|
2357
|
+
if (!list) list = await gatewayModels({ config }).catch(quiet("agent/models/for-session"));
|
|
2358
|
+
let auto = list?.auto ?? null;
|
|
2359
|
+
const id = session.model ?? void 0;
|
|
2360
|
+
let model = id ? list?.models.find((entry) => entry.id === id) ?? list?.models.find((entry) => sameGatewayModel(entry.id, id)) : void 0;
|
|
2361
|
+
if (id && !model && !fetchedNow) {
|
|
2362
|
+
list = await gatewayModels({ config });
|
|
2363
|
+
const wanted = session.model ?? void 0;
|
|
2364
|
+
model = wanted ? list.models.find((entry) => entry.id === wanted) ?? list.models.find((entry) => sameGatewayModel(entry.id, wanted)) : void 0;
|
|
2365
|
+
auto = list.auto;
|
|
2366
|
+
}
|
|
2367
|
+
const facts = id ? model : auto;
|
|
2368
|
+
return {
|
|
2369
|
+
...id ? { id } : {},
|
|
2370
|
+
...facts?.contextWindow ? { contextWindow: facts.contextWindow } : {},
|
|
2371
|
+
...facts?.maxOutput ? { maxOutput: facts.maxOutput } : {},
|
|
2372
|
+
...facts?.vision ? { vision: true } : {}
|
|
2373
|
+
};
|
|
2374
|
+
} catch {
|
|
2375
|
+
return session.model ? { id: session.model } : {};
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
var LOCAL_MODEL_LABEL = "The local model";
|
|
2379
|
+
async function modelClientForSession(session, config, local = {}) {
|
|
2380
|
+
if (session.route === "gateway") {
|
|
2381
|
+
const { baseUrl, apiKey } = gatewayConnection(config);
|
|
2382
|
+
const { id: modelId, ...facts } = await gatewayModelFacts(session, config);
|
|
2383
|
+
return gatewayModelClient({
|
|
2384
|
+
baseUrl,
|
|
2385
|
+
apiKey,
|
|
2386
|
+
sessionId: session.id,
|
|
2387
|
+
...session.model ? { model: session.model } : {},
|
|
2388
|
+
...facts,
|
|
2389
|
+
options: gatewayStepOptions(session, modelId),
|
|
2390
|
+
subscriptions: gatewaySubscriptionsOn(config)
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
if (session.route === "clikcode-local") {
|
|
2394
|
+
releaseLocalModelsOnExit();
|
|
2395
|
+
const endpoint = await ensureLocalModel({
|
|
2396
|
+
...session.model ? { modelId: session.model } : {},
|
|
2397
|
+
sessionId: session.id,
|
|
2398
|
+
...local.progress ? { progress: local.progress } : {},
|
|
2399
|
+
...local.forTurn ? { forTurn: true } : {}
|
|
2400
|
+
});
|
|
2401
|
+
if (endpoint.notice) diagnostic("local-model.notice", endpoint.notice);
|
|
2402
|
+
if (!session.model) session.model = endpoint.model;
|
|
2403
|
+
return new OpenAIModelClient({
|
|
2404
|
+
// The engine's URL ends in /v1 and the client appends /v1 itself.
|
|
2405
|
+
baseUrl: endpoint.baseUrl.replace(/\/v1\/?$/, ""),
|
|
2406
|
+
model: endpoint.model,
|
|
2407
|
+
contextWindow: endpoint.contextWindow,
|
|
2408
|
+
label: LOCAL_MODEL_LABEL,
|
|
2409
|
+
// The cache is part of the local-turn contract, not a server default:
|
|
2410
|
+
// unchanged history should be read once, on every supported machine.
|
|
2411
|
+
body: { cache_prompt: true },
|
|
2412
|
+
...endpoint.promptPerSecond ? { promptPerSecond: endpoint.promptPerSecond } : {},
|
|
2413
|
+
// What a conversation carried in may hold: what this model reads in about two minutes, not what its window could carry.
|
|
2414
|
+
...localReadableTokens(endpoint.promptPerSecond) ? { readableTokens: localReadableTokens(endpoint.promptPerSecond) } : {}
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
throw new Error(`a ${session.route} session runs a vendor harness, not ClikCode's own agent`);
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
export {
|
|
2421
|
+
exposeSpecialists,
|
|
2422
|
+
UNKNOWN_CONTEXT_WINDOW,
|
|
2423
|
+
ContextFitError,
|
|
2424
|
+
responseReserve,
|
|
2425
|
+
learnScale,
|
|
2426
|
+
outputRoom,
|
|
2427
|
+
fitContext,
|
|
2428
|
+
completedArguments,
|
|
2429
|
+
withDownloadLock,
|
|
2430
|
+
prefetchLocalModel,
|
|
2431
|
+
ensureLocalModel,
|
|
2432
|
+
releaseLocalModel,
|
|
2433
|
+
releaseLocalModelTurn,
|
|
2434
|
+
holdRunningLocalModel,
|
|
2435
|
+
releaseLocalModelsOnExit,
|
|
2436
|
+
localModelChoices,
|
|
2437
|
+
gatewayConnection,
|
|
2438
|
+
gatewayModelClient,
|
|
2439
|
+
modelClientForSession
|
|
2440
|
+
};
|