clikcode 1.0.4 → 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 +494 -112923
- package/dist/computer-tools.js +36642 -21259
- 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,3451 @@
|
|
|
1
|
+
import { createRequire as __clikcodeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __clikcodeCreateRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
runCli
|
|
5
|
+
} from "./chunk-PWBF2X3V.js";
|
|
6
|
+
import {
|
|
7
|
+
AGENT_SLICE,
|
|
8
|
+
userManagerOwns
|
|
9
|
+
} from "./chunk-HU5SSUFX.js";
|
|
10
|
+
import {
|
|
11
|
+
ACTIVE_MS,
|
|
12
|
+
closeTabsByLabel,
|
|
13
|
+
closeTabsOfOwner,
|
|
14
|
+
readTabRecords,
|
|
15
|
+
sweepTabs,
|
|
16
|
+
writeTabRecord
|
|
17
|
+
} from "./chunk-AKRYTS2D.js";
|
|
18
|
+
import {
|
|
19
|
+
addDeskItem,
|
|
20
|
+
clearDeskInfo,
|
|
21
|
+
deskHeldTargets,
|
|
22
|
+
deskItemAddress,
|
|
23
|
+
deskToken,
|
|
24
|
+
finishDeskItem,
|
|
25
|
+
listDeskItems,
|
|
26
|
+
readDeskInfo,
|
|
27
|
+
tidyDesk,
|
|
28
|
+
writeDeskInfo
|
|
29
|
+
} from "./chunk-4GVEJ5FK.js";
|
|
30
|
+
import {
|
|
31
|
+
contextEgress,
|
|
32
|
+
egressOfPage,
|
|
33
|
+
egressServer,
|
|
34
|
+
pageEgress,
|
|
35
|
+
tunnelManager
|
|
36
|
+
} from "./chunk-O7BNJIXU.js";
|
|
37
|
+
import {
|
|
38
|
+
hideKeyLikeText
|
|
39
|
+
} from "./chunk-MCBRVPA7.js";
|
|
40
|
+
import {
|
|
41
|
+
browserUseConnection,
|
|
42
|
+
stopBrowserUse
|
|
43
|
+
} from "./chunk-RJLHVYQY.js";
|
|
44
|
+
import {
|
|
45
|
+
sleep
|
|
46
|
+
} from "./chunk-YMCH3L2S.js";
|
|
47
|
+
import {
|
|
48
|
+
browserDisplay,
|
|
49
|
+
browserProvider,
|
|
50
|
+
headlessSetting
|
|
51
|
+
} from "./chunk-5SM5UAWN.js";
|
|
52
|
+
import {
|
|
53
|
+
VIRTUAL_DISPLAY_ENV,
|
|
54
|
+
desktopSession,
|
|
55
|
+
hostStatusFile,
|
|
56
|
+
installingMessage,
|
|
57
|
+
launchComputerBrowser,
|
|
58
|
+
liveHostStatus,
|
|
59
|
+
readHostStatus,
|
|
60
|
+
shouldRunHeadless,
|
|
61
|
+
writeHostStatus
|
|
62
|
+
} from "./chunk-CAADDF6M.js";
|
|
63
|
+
import {
|
|
64
|
+
pidIsAlive,
|
|
65
|
+
tryLease
|
|
66
|
+
} from "./chunk-4L2ZZM4Q.js";
|
|
67
|
+
import {
|
|
68
|
+
lifecycle,
|
|
69
|
+
quiet
|
|
70
|
+
} from "./chunk-RDDWQBEM.js";
|
|
71
|
+
import {
|
|
72
|
+
scrubSecrets,
|
|
73
|
+
secretRef,
|
|
74
|
+
sharedState
|
|
75
|
+
} from "./chunk-CBANJFBO.js";
|
|
76
|
+
|
|
77
|
+
// src/agent/computer/browser-host.ts
|
|
78
|
+
import fs5 from "node:fs/promises";
|
|
79
|
+
import path5 from "node:path";
|
|
80
|
+
|
|
81
|
+
// src/agent/computer/page-dialogs.ts
|
|
82
|
+
var tabs = sharedState("page-dialog-state", () => /* @__PURE__ */ new WeakMap());
|
|
83
|
+
var HELD_DIALOG_MS = 12e4;
|
|
84
|
+
var clip = (text) => text.replace(/\s+/g, " ").slice(0, 200);
|
|
85
|
+
var describe = (dialog) => `${dialog.type()}: "${clip(dialog.message())}"`;
|
|
86
|
+
function watchDialogs(page) {
|
|
87
|
+
const known = tabs.get(page);
|
|
88
|
+
if (known) return known;
|
|
89
|
+
const tab = { hold: false, notices: [] };
|
|
90
|
+
tabs.set(page, tab);
|
|
91
|
+
const clear = () => {
|
|
92
|
+
if (tab.pending) {
|
|
93
|
+
clearTimeout(tab.pending.timer);
|
|
94
|
+
tab.pending = void 0;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
page.on("dialog", (dialog) => {
|
|
98
|
+
const fail = quiet("agent/computer/page-dialogs");
|
|
99
|
+
if (tab.policy) {
|
|
100
|
+
tab.policy.seen.push(`${describe(dialog)} (${tab.policy.accept ? "accepted" : "declined"})`);
|
|
101
|
+
void (tab.policy.accept ? dialog.accept() : dialog.dismiss()).catch(fail);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!tab.hold || dialog.type() === "alert") {
|
|
105
|
+
tab.notices.push(`${describe(dialog)} (${dialog.type() === "alert" ? "closed" : "declined"})`);
|
|
106
|
+
void dialog.dismiss().catch(fail);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
clear();
|
|
110
|
+
const timer = setTimeout(() => {
|
|
111
|
+
if (tab.pending?.dialog !== dialog) return;
|
|
112
|
+
tab.pending = void 0;
|
|
113
|
+
tab.notices.push(`${describe(dialog)} (declined after two minutes without an answer)`);
|
|
114
|
+
void dialog.dismiss().catch(fail);
|
|
115
|
+
}, HELD_DIALOG_MS);
|
|
116
|
+
timer.unref?.();
|
|
117
|
+
tab.pending = { dialog, type: dialog.type(), message: clip(dialog.message()), defaultValue: dialog.defaultValue(), timer };
|
|
118
|
+
});
|
|
119
|
+
page.on("close", clear);
|
|
120
|
+
return tab;
|
|
121
|
+
}
|
|
122
|
+
function bindDialogs(page, hold) {
|
|
123
|
+
watchDialogs(page).hold = hold;
|
|
124
|
+
}
|
|
125
|
+
function pendingDialogNote(page) {
|
|
126
|
+
const pending = tabs.get(page)?.pending;
|
|
127
|
+
if (!pending) return void 0;
|
|
128
|
+
const kind = pending.type === "beforeunload" ? 'a "leave this page?" box (beforeunload)' : `a ${pending.type} box`;
|
|
129
|
+
return `The page is showing ${kind}${pending.message ? `: "${pending.message}"` : ""}${pending.type === "prompt" && pending.defaultValue ? ` (default answer "${pending.defaultValue}")` : ""}. It waits for an answer, and nothing else on the page works until then. Answer with the dialog action: accept_dialog true to accept${pending.type === "prompt" ? " (text is the answer to type)" : ""}, or leave it out to dismiss.`;
|
|
130
|
+
}
|
|
131
|
+
var hasPendingDialog = (page) => !!tabs.get(page)?.pending;
|
|
132
|
+
function takeDialogNotices(page) {
|
|
133
|
+
return tabs.get(page)?.notices.splice(0) ?? [];
|
|
134
|
+
}
|
|
135
|
+
async function answerDialog(page, accept, text) {
|
|
136
|
+
const tab = tabs.get(page);
|
|
137
|
+
const pending = tab?.pending;
|
|
138
|
+
if (!tab || !pending) {
|
|
139
|
+
const missed = tab?.notices.splice(0) ?? [];
|
|
140
|
+
return `No dialog is waiting on the page.${missed.length ? ` Since you last looked: ${missed.join("; ")}.` : ""}`;
|
|
141
|
+
}
|
|
142
|
+
clearTimeout(pending.timer);
|
|
143
|
+
tab.pending = void 0;
|
|
144
|
+
if (accept) await pending.dialog.accept(pending.type === "prompt" ? text ?? pending.defaultValue : void 0);
|
|
145
|
+
else await pending.dialog.dismiss();
|
|
146
|
+
return `The ${pending.type} box ("${pending.message}") was ${accept ? `accepted${pending.type === "prompt" ? ` with ${(text ?? pending.defaultValue).length} characters of text` : ""}` : "dismissed"}.`;
|
|
147
|
+
}
|
|
148
|
+
async function settleWaitingDialog(page, accept) {
|
|
149
|
+
const pending = tabs.get(page)?.pending;
|
|
150
|
+
if (!pending) return void 0;
|
|
151
|
+
const accepted = accept && pending.type === "beforeunload";
|
|
152
|
+
return answerDialog(page, accepted);
|
|
153
|
+
}
|
|
154
|
+
async function withDialogs(page, accept, act, linger = 300) {
|
|
155
|
+
const tab = watchDialogs(page);
|
|
156
|
+
const policy = { accept, seen: [] };
|
|
157
|
+
const outer = tab.policy;
|
|
158
|
+
tab.policy = policy;
|
|
159
|
+
try {
|
|
160
|
+
const result = await act();
|
|
161
|
+
if (linger) await page.waitForTimeout(linger);
|
|
162
|
+
return { result, dialogs: policy.seen };
|
|
163
|
+
} finally {
|
|
164
|
+
tab.policy = outer;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function dialogNote(dialogs, accepted) {
|
|
168
|
+
if (!dialogs.length) return "";
|
|
169
|
+
return ` The page showed a browser dialog: ${dialogs.join("; ")}.${accepted ? "" : " To answer yes, click again with accept_dialog true."}`;
|
|
170
|
+
}
|
|
171
|
+
function withDialogNotices(result, page) {
|
|
172
|
+
const notices = takeDialogNotices(page);
|
|
173
|
+
return notices.length ? { ...result, output: `${result.output}
|
|
174
|
+
|
|
175
|
+
Browser dialogs closed without waiting: ${notices.join("; ")}.` } : result;
|
|
176
|
+
}
|
|
177
|
+
function leaveDialogsToWorkers(context) {
|
|
178
|
+
const listen = (page) => {
|
|
179
|
+
page.on("dialog", (dialog) => {
|
|
180
|
+
const timer = setTimeout(() => {
|
|
181
|
+
void dialog.dismiss().catch(quiet("agent/computer/page-dialogs"));
|
|
182
|
+
}, HELD_DIALOG_MS + 3e4);
|
|
183
|
+
timer.unref?.();
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
context.pages().forEach(listen);
|
|
187
|
+
context.on("page", listen);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/agent/computer/browser-janitor.ts
|
|
191
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
192
|
+
import fs from "node:fs/promises";
|
|
193
|
+
import path from "node:path";
|
|
194
|
+
var GIB = 2 ** 30;
|
|
195
|
+
function recycleLimits(env = process.env) {
|
|
196
|
+
const number = (name, fallback) => {
|
|
197
|
+
const value = Number(env[name]);
|
|
198
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
199
|
+
};
|
|
200
|
+
return { renderers: Math.floor(number("CLIKCODE_BROWSER_MAX_RENDERERS", 40)), bytes: number("CLIKCODE_BROWSER_MAX_GB", 6) * GIB, ageMs: number("CLIKCODE_BROWSER_MAX_HOURS", 6) * 36e5 };
|
|
201
|
+
}
|
|
202
|
+
var RESTORE_WITHIN_MS = 10 * 6e4;
|
|
203
|
+
function recycleVerdict(load, limits, lastUsedAt, now) {
|
|
204
|
+
const reasons = [];
|
|
205
|
+
if (load.renderers > limits.renderers) reasons.push(`${load.renderers} renderers over ${limits.renderers}`);
|
|
206
|
+
if (load.bytes > limits.bytes) reasons.push(`${(load.bytes / GIB).toFixed(1)} GB over ${(limits.bytes / GIB).toFixed(1)} GB`);
|
|
207
|
+
if (load.ageMs !== void 0 && load.ageMs > limits.ageMs) reasons.push(`${(load.ageMs / 36e5).toFixed(1)} h old, over ${(limits.ageMs / 36e5).toFixed(1)} h`);
|
|
208
|
+
if (!reasons.length) return void 0;
|
|
209
|
+
const far = load.renderers > limits.renderers * 2 || load.bytes > limits.bytes * 2 || load.ageMs !== void 0 && load.ageMs > limits.ageMs * 1.5;
|
|
210
|
+
if (!far && now - lastUsedAt < ACTIVE_MS) return void 0;
|
|
211
|
+
return reasons.join(", ");
|
|
212
|
+
}
|
|
213
|
+
var realProc = {
|
|
214
|
+
list: () => {
|
|
215
|
+
try {
|
|
216
|
+
return readdirSync("/proc").filter((name) => /^\d+$/.test(name));
|
|
217
|
+
} catch {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
read: (pid, file) => {
|
|
222
|
+
try {
|
|
223
|
+
return readFileSync(`/proc/${pid}/${file}`, "utf8");
|
|
224
|
+
} catch {
|
|
225
|
+
return void 0;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
function measureBrowser(rootPid, proc = realProc, cgroupBytes = ownScopeBytes) {
|
|
230
|
+
const parents = /* @__PURE__ */ new Map();
|
|
231
|
+
for (const name of proc.list()) {
|
|
232
|
+
const stat = proc.read(Number(name), "stat");
|
|
233
|
+
if (!stat) continue;
|
|
234
|
+
const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
|
|
235
|
+
if (Number.isFinite(parent)) parents.set(Number(name), parent);
|
|
236
|
+
}
|
|
237
|
+
const members = /* @__PURE__ */ new Set([rootPid]);
|
|
238
|
+
let grew = true;
|
|
239
|
+
while (grew) {
|
|
240
|
+
grew = false;
|
|
241
|
+
for (const [pid, parent] of parents) if (!members.has(pid) && members.has(parent)) {
|
|
242
|
+
members.add(pid);
|
|
243
|
+
grew = true;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
let renderers = 0;
|
|
247
|
+
let pss = 0;
|
|
248
|
+
for (const pid of members) {
|
|
249
|
+
if (/--type=renderer/.test((proc.read(pid, "cmdline") ?? "").replace(/\0/g, " "))) renderers++;
|
|
250
|
+
const rollup = proc.read(pid, "smaps_rollup");
|
|
251
|
+
const kb = Number(/^Pss:\s+(\d+) kB/m.exec(rollup ?? "")?.[1]);
|
|
252
|
+
if (Number.isFinite(kb)) pss += kb * 1024;
|
|
253
|
+
else {
|
|
254
|
+
const resident = Number((proc.read(pid, "statm") ?? "").split(" ")[1]);
|
|
255
|
+
if (Number.isFinite(resident)) pss += resident * 4096;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const fromScope = cgroupBytes(proc.read(rootPid, "cgroup") ?? "");
|
|
259
|
+
return { renderers, bytes: fromScope ?? pss };
|
|
260
|
+
}
|
|
261
|
+
function ownScopeBytes(cgroupLine) {
|
|
262
|
+
const where = /^0::(.*)$/m.exec(cgroupLine)?.[1];
|
|
263
|
+
if (!where || !/clikcode-browser-host[^/]*\.(?:scope|service)/.test(where)) return void 0;
|
|
264
|
+
const unit = where.slice(0, where.search(/clikcode-browser-host[^/]*\.(?:scope|service)/)) + /clikcode-browser-host[^/]*\.(?:scope|service)/.exec(where)[0];
|
|
265
|
+
const value = Number(readFileSyncOr(`/sys/fs/cgroup${unit}/memory.current`));
|
|
266
|
+
return Number.isFinite(value) && value > 0 ? value : void 0;
|
|
267
|
+
}
|
|
268
|
+
function readFileSyncOr(file) {
|
|
269
|
+
try {
|
|
270
|
+
return readFileSync(file, "utf8");
|
|
271
|
+
} catch {
|
|
272
|
+
return void 0;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
var recycleFile = (stateDir) => path.join(stateDir, "computer", "recycle.json");
|
|
276
|
+
function tabsToRestore(records, now) {
|
|
277
|
+
const seen = /* @__PURE__ */ new Set();
|
|
278
|
+
const saved = [];
|
|
279
|
+
for (const record of [...records].sort((a, b) => b.lastUsedAt - a.lastUsedAt)) {
|
|
280
|
+
if (!record.tab || record.parked || now - record.lastUsedAt > RESTORE_WITHIN_MS || !/^https?:/i.test(record.url ?? "") || seen.has(record.tab)) continue;
|
|
281
|
+
seen.add(record.tab);
|
|
282
|
+
saved.push({ tab: record.tab, url: record.url, ...record.egress ? { egress: record.egress } : {} });
|
|
283
|
+
}
|
|
284
|
+
return saved;
|
|
285
|
+
}
|
|
286
|
+
async function saveRecycle(stateDir, tabs3, now) {
|
|
287
|
+
await fs.writeFile(recycleFile(stateDir), JSON.stringify({ at: now, tabs: tabs3 }), { mode: 384 });
|
|
288
|
+
}
|
|
289
|
+
async function takeRecycle(stateDir, now = Date.now()) {
|
|
290
|
+
try {
|
|
291
|
+
const saved = JSON.parse(await fs.readFile(recycleFile(stateDir), "utf8"));
|
|
292
|
+
await fs.unlink(recycleFile(stateDir)).catch(quiet("agent/computer/browser-janitor"));
|
|
293
|
+
if (typeof saved.at !== "number" || now - saved.at > RESTORE_WITHIN_MS) return [];
|
|
294
|
+
return (saved.tabs ?? []).filter((tab) => typeof tab.tab === "string" && /^https?:/i.test(tab.url));
|
|
295
|
+
} catch {
|
|
296
|
+
return [];
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async function restoreTabs(stateDir, tabs3, host, now = Date.now()) {
|
|
300
|
+
let count = 0;
|
|
301
|
+
for (const saved of tabs3) {
|
|
302
|
+
const id = await (saved.egress ? host.openPage(saved.url, saved.egress) : host.openPage(saved.url)).catch(quiet("agent/computer/browser-janitor"));
|
|
303
|
+
if (!id) continue;
|
|
304
|
+
await writeTabRecord(stateDir, { id, tab: saved.tab, ownerPid: 0, owner: "restored after a browser restart", openedAt: now, lastUsedAt: now, url: saved.url, restoreFor: saved.tab, ...saved.egress ? { egress: saved.egress } : {} });
|
|
305
|
+
count++;
|
|
306
|
+
}
|
|
307
|
+
if (count) lifecycle("browser.restored", { tabs: count });
|
|
308
|
+
return count;
|
|
309
|
+
}
|
|
310
|
+
async function janitorTick(deps) {
|
|
311
|
+
const now = (deps.now ?? Date.now)();
|
|
312
|
+
if (deps.current && !await deps.current().catch(() => true)) {
|
|
313
|
+
lifecycle("browser.host.superseded", { hostPid: deps.hostPid });
|
|
314
|
+
deps.retire?.("this host is no longer the browser host, or its Chrome is gone");
|
|
315
|
+
return "superseded";
|
|
316
|
+
}
|
|
317
|
+
await sweepTabs(deps.stateDir, { now }).catch(quiet("agent/computer/browser-janitor"));
|
|
318
|
+
const measured = (deps.measure ?? (() => measureBrowser(deps.hostPid)))();
|
|
319
|
+
const load = { ...measured, ...measured.ageMs === void 0 && deps.startedAt !== void 0 ? { ageMs: now - deps.startedAt } : {} };
|
|
320
|
+
const records = await readTabRecords(deps.stateDir);
|
|
321
|
+
const lastUsed = records.reduce((latest, record) => Math.max(latest, record.lastUsedAt), 0);
|
|
322
|
+
const reason = recycleVerdict(load, deps.limits ?? recycleLimits(), lastUsed, now);
|
|
323
|
+
if (!reason) return void 0;
|
|
324
|
+
const tabs3 = tabsToRestore(records, now);
|
|
325
|
+
lifecycle("browser.recycle", { reason, renderers: load.renderers, gb: Number((load.bytes / GIB).toFixed(1)), ...load.ageMs !== void 0 ? { hours: Number((load.ageMs / 36e5).toFixed(1)) } : {}, restore: tabs3.length });
|
|
326
|
+
await saveRecycle(deps.stateDir, tabs3, now);
|
|
327
|
+
await deps.recycle();
|
|
328
|
+
return reason;
|
|
329
|
+
}
|
|
330
|
+
var JANITOR_INTERVAL_MS = 3e4;
|
|
331
|
+
function startBrowserJanitor(deps) {
|
|
332
|
+
let running2 = false;
|
|
333
|
+
const started = { ...deps, startedAt: deps.startedAt ?? (deps.now ?? Date.now)() };
|
|
334
|
+
deps = started;
|
|
335
|
+
const timer = setInterval(() => {
|
|
336
|
+
if (running2) return;
|
|
337
|
+
running2 = true;
|
|
338
|
+
void janitorTick(deps).catch(quiet("agent/computer/browser-janitor")).finally(() => {
|
|
339
|
+
running2 = false;
|
|
340
|
+
});
|
|
341
|
+
}, JANITOR_INTERVAL_MS);
|
|
342
|
+
timer.unref();
|
|
343
|
+
return () => clearInterval(timer);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// src/agent/computer/handoff-desk.ts
|
|
347
|
+
import { timingSafeEqual } from "node:crypto";
|
|
348
|
+
import { createServer } from "node:http";
|
|
349
|
+
|
|
350
|
+
// src/agent/computer/handoff-input.ts
|
|
351
|
+
var OUTSIDE = 5e3;
|
|
352
|
+
var finite = (value, max = 2e4) => typeof value === "number" && Number.isFinite(value) && value >= -OUTSIDE && value <= max;
|
|
353
|
+
function cleanPoints(raw) {
|
|
354
|
+
if (!Array.isArray(raw) || raw.length > 5) return void 0;
|
|
355
|
+
const out = [];
|
|
356
|
+
for (const item of raw) {
|
|
357
|
+
if (!Array.isArray(item) || item.length !== 3 || !Number.isInteger(item[0]) || item[0] < 0 || item[0] > 1e6 || !finite(item[1]) || !finite(item[2])) return void 0;
|
|
358
|
+
out.push({ id: item[0], x: item[1], y: item[2] });
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
362
|
+
var KEYS = {
|
|
363
|
+
Enter: { key: "Enter", code: "Enter", vk: 13, text: "\r" },
|
|
364
|
+
Tab: { key: "Tab", code: "Tab", vk: 9 },
|
|
365
|
+
Backspace: { key: "Backspace", code: "Backspace", vk: 8 },
|
|
366
|
+
Delete: { key: "Delete", code: "Delete", vk: 46 },
|
|
367
|
+
Escape: { key: "Escape", code: "Escape", vk: 27 },
|
|
368
|
+
ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", vk: 37 },
|
|
369
|
+
ArrowUp: { key: "ArrowUp", code: "ArrowUp", vk: 38 },
|
|
370
|
+
ArrowRight: { key: "ArrowRight", code: "ArrowRight", vk: 39 },
|
|
371
|
+
ArrowDown: { key: "ArrowDown", code: "ArrowDown", vk: 40 },
|
|
372
|
+
Home: { key: "Home", code: "Home", vk: 36 },
|
|
373
|
+
End: { key: "End", code: "End", vk: 35 },
|
|
374
|
+
PageUp: { key: "PageUp", code: "PageUp", vk: 33 },
|
|
375
|
+
PageDown: { key: "PageDown", code: "PageDown", vk: 34 }
|
|
376
|
+
};
|
|
377
|
+
var keyEvent = (name) => typeof name === "string" && Object.hasOwn(KEYS, name) ? KEYS[name] : void 0;
|
|
378
|
+
var MAX_REPEAT = 400;
|
|
379
|
+
var MAX_TEXT = 4e3;
|
|
380
|
+
function cleanSize(raw) {
|
|
381
|
+
const value = raw;
|
|
382
|
+
if (!value || typeof value !== "object") return void 0;
|
|
383
|
+
const { w, h, dpr } = value;
|
|
384
|
+
if (typeof w !== "number" || typeof h !== "number" || typeof dpr !== "number") return void 0;
|
|
385
|
+
if (!Number.isFinite(w) || !Number.isFinite(h) || !Number.isFinite(dpr)) return void 0;
|
|
386
|
+
return { w: Math.min(2400, Math.max(200, Math.round(w))), h: Math.min(3e3, Math.max(120, Math.round(h))), dpr: Math.min(3, Math.max(1, dpr)) };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// src/agent/computer/handoff-live.ts
|
|
390
|
+
var DESCRIBE_SCRIPT = `(() => {
|
|
391
|
+
if (window.__clikDescribe) return;
|
|
392
|
+
const TEXT = /^(text|search|url|tel|email|password|number)$/;
|
|
393
|
+
const NATIVE = /^(date|time|datetime-local|month|week|color)$/;
|
|
394
|
+
const clean = (text) => String(text || '').replace(/\\s+/g, ' ').trim();
|
|
395
|
+
const label = (e) => clean((e.labels && e.labels[0] && e.labels[0].innerText) || e.getAttribute('aria-label') || e.getAttribute('title') || e.placeholder || e.name).slice(0, 100);
|
|
396
|
+
const common = (e) => ({ label: label(e), required: Boolean(e.required), inputmode: e.inputMode || e.getAttribute('inputmode') || '', autocomplete: e.getAttribute('autocomplete') || '', enterkeyhint: e.enterKeyHint || e.getAttribute('enterkeyhint') || '', maxlength: e.maxLength > 0 ? e.maxLength : 0, placeholder: clean(e.placeholder).slice(0, 80) });
|
|
397
|
+
window.__clikDescribe = (e) => {
|
|
398
|
+
if (!e || e === document.body || e === document.documentElement) return null;
|
|
399
|
+
if (e.tagName === 'SELECT') return { kind: 'select', multiple: e.multiple, required: Boolean(e.required), label: label(e), options: Array.from(e.options).slice(0, 300).map((o) => ({ v: o.value, t: clean(o.text).slice(0, 100), s: o.selected, d: o.disabled })) };
|
|
400
|
+
if (e.tagName === 'TEXTAREA') return { kind: 'text', type: 'textarea', multiline: true, value: e.value.slice(0, 2000), ...common(e) };
|
|
401
|
+
if (e.tagName === 'INPUT') {
|
|
402
|
+
const type = (e.type || 'text').toLowerCase();
|
|
403
|
+
if (TEXT.test(type)) return { kind: 'text', type, value: type === 'password' ? '' : e.value.slice(0, 1000), ...common(e) };
|
|
404
|
+
if (NATIVE.test(type)) return { kind: 'native', type, value: e.value, min: e.min, max: e.max, step: e.step, ...common(e) };
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
if (e.isContentEditable) return { kind: 'text', type: 'editable', multiline: true, value: (e.innerText || '').slice(0, 2000), ...common(e) };
|
|
408
|
+
return null;
|
|
409
|
+
};
|
|
410
|
+
})();`;
|
|
411
|
+
var FIELDS_SCRIPT = `(() => {
|
|
412
|
+
const describe = window.__clikDescribe;
|
|
413
|
+
const v = window.visualViewport;
|
|
414
|
+
if (!describe || !v) return '[]';
|
|
415
|
+
const s = v.scale, ox = v.offsetLeft, oy = v.offsetTop;
|
|
416
|
+
const KIND = /^(text|search|url|tel|email|password|number|date|time|datetime-local|month|week|color)$/;
|
|
417
|
+
const byId = {}, out = [];
|
|
418
|
+
for (const e of document.querySelectorAll('input, textarea, select, [contenteditable=""], [contenteditable="true"]')) {
|
|
419
|
+
if (out.length >= 60) break;
|
|
420
|
+
if (e.disabled || e.readOnly) continue;
|
|
421
|
+
if (e.tagName === 'INPUT' && !KIND.test((e.type || 'text').toLowerCase())) continue;
|
|
422
|
+
const r = e.getBoundingClientRect();
|
|
423
|
+
if (r.width < 4 || r.height < 4) continue;
|
|
424
|
+
const cs = getComputedStyle(e);
|
|
425
|
+
if (cs.visibility === 'hidden' || cs.display === 'none') continue;
|
|
426
|
+
// Something else drawn over it (a dialog, a menu): not a field a tap would reach. Only checked where the field is on screen.
|
|
427
|
+
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
|
|
428
|
+
if (cx >= 0 && cy >= 0 && cx < innerWidth && cy < innerHeight) {
|
|
429
|
+
const top = document.elementFromPoint(cx, cy);
|
|
430
|
+
if (top && top !== e && !e.contains(top) && !top.contains(e) && !(top.closest && top.closest('label') && top.closest('label').control === e)) continue;
|
|
431
|
+
}
|
|
432
|
+
const d = describe(e);
|
|
433
|
+
if (!d) continue;
|
|
434
|
+
if (e.__clikId === undefined) e.__clikId = (window.__clikNext = (window.__clikNext || 0) + 1);
|
|
435
|
+
byId[e.__clikId] = e;
|
|
436
|
+
d.idx = e.__clikId;
|
|
437
|
+
if (d.options && d.options.length > 200) d.options = d.options.slice(0, 200);
|
|
438
|
+
const round = (n) => Math.round(n * 10) / 10;
|
|
439
|
+
out.push({ i: d.idx, x: round((r.left - ox) * s), y: round((r.top - oy) * s), w: round(r.width * s), h: round(r.height * s), d });
|
|
440
|
+
}
|
|
441
|
+
window.__clikFields = byId;
|
|
442
|
+
return JSON.stringify(out);
|
|
443
|
+
})()`;
|
|
444
|
+
var prepareFill = (index) => `((index) => {
|
|
445
|
+
const e = (window.__clikFields || [])[index];
|
|
446
|
+
if (!e) return 'gone';
|
|
447
|
+
if (e.disabled || e.readOnly) return 'locked';
|
|
448
|
+
e.focus();
|
|
449
|
+
try { if (typeof e.select === 'function') e.select(); else if (e.isContentEditable) document.execCommand('selectAll'); } catch (error) { /* a field that cannot select */ }
|
|
450
|
+
return 'ok';
|
|
451
|
+
})(${index})`;
|
|
452
|
+
var setValueExpression = (value, index) => `((value, index) => {
|
|
453
|
+
const e = (index >= 0 && (window.__clikFields || [])[index]) || document.activeElement;
|
|
454
|
+
if (!e || e.disabled) return false;
|
|
455
|
+
if (e.tagName === 'SELECT') {
|
|
456
|
+
const wanted = Array.isArray(value) ? value : [value];
|
|
457
|
+
for (const o of Array.from(e.options)) o.selected = wanted.includes(o.value);
|
|
458
|
+
} else {
|
|
459
|
+
const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e), 'value');
|
|
460
|
+
if (setter && setter.set) setter.set.call(e, String(value)); else e.value = String(value);
|
|
461
|
+
}
|
|
462
|
+
e.dispatchEvent(new Event('input', { bubbles: true }));
|
|
463
|
+
e.dispatchEvent(new Event('change', { bubbles: true }));
|
|
464
|
+
return true;
|
|
465
|
+
})(${JSON.stringify(value)}, ${index})`;
|
|
466
|
+
var SAME_VIEW = { scale: 1, x: 0, y: 0 };
|
|
467
|
+
function toPage(view, x, y) {
|
|
468
|
+
const scale = view.scale > 0.05 && view.scale < 20 ? view.scale : 1;
|
|
469
|
+
return { x: view.x + x / scale, y: view.y + y / scale };
|
|
470
|
+
}
|
|
471
|
+
var READ_VIEW = "({ scale: visualViewport.scale, x: visualViewport.offsetLeft, y: visualViewport.offsetTop })";
|
|
472
|
+
var BUTTONS = ["left", "middle", "right"];
|
|
473
|
+
var FRAME_IDS = 1e6;
|
|
474
|
+
var MAX_FRAMES = 4;
|
|
475
|
+
var HOLD_MS = 350;
|
|
476
|
+
var LiveView = class {
|
|
477
|
+
constructor(page, socket, finish, activity = () => void 0, options = {}) {
|
|
478
|
+
this.page = page;
|
|
479
|
+
this.socket = socket;
|
|
480
|
+
this.finish = finish;
|
|
481
|
+
this.activity = activity;
|
|
482
|
+
this.watch = options.watch === true;
|
|
483
|
+
socket.onMessage((data, binary) => {
|
|
484
|
+
if (!binary) this.accept(String(data));
|
|
485
|
+
});
|
|
486
|
+
socket.onClose(() => {
|
|
487
|
+
void this.stop();
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
page;
|
|
491
|
+
socket;
|
|
492
|
+
finish;
|
|
493
|
+
activity;
|
|
494
|
+
cdp;
|
|
495
|
+
size;
|
|
496
|
+
stopped = false;
|
|
497
|
+
scriptId;
|
|
498
|
+
/** The phone has drawn the last frame it was sent and wants another. */
|
|
499
|
+
ready = true;
|
|
500
|
+
held;
|
|
501
|
+
unstick;
|
|
502
|
+
queue = [];
|
|
503
|
+
draining = false;
|
|
504
|
+
streaming = false;
|
|
505
|
+
/** Chrome side is set up (domains on, field tracking installed): queued messages may run. */
|
|
506
|
+
up = false;
|
|
507
|
+
lastView = SAME_VIEW;
|
|
508
|
+
/** A finger that went down on a frame from another site and has not yet moved: it is a click if it lifts, a scroll if it moves. */
|
|
509
|
+
frames = [];
|
|
510
|
+
foreign;
|
|
511
|
+
/** What the phone's finger is: touch (the page sees a touch screen, laid out for the phone) or a mouse (the page sees a pointer). */
|
|
512
|
+
mode = "touch";
|
|
513
|
+
laidOutAs;
|
|
514
|
+
fieldsTimer;
|
|
515
|
+
lastFields = "";
|
|
516
|
+
/** What happened, for tests and for the phone's status line. */
|
|
517
|
+
stats = { frames: 0, restarts: 0 };
|
|
518
|
+
watch;
|
|
519
|
+
/** Watching: the size of the frames Chrome sends, which changes when the tab's own size does. */
|
|
520
|
+
frameSize = "";
|
|
521
|
+
async start() {
|
|
522
|
+
const cdp = await this.page.context().newCDPSession(this.page);
|
|
523
|
+
this.cdp = cdp;
|
|
524
|
+
cdp.on("Page.screencastFrame", (frame) => {
|
|
525
|
+
void this.onFrame(frame);
|
|
526
|
+
});
|
|
527
|
+
cdp.on("Page.frameNavigated", (event) => {
|
|
528
|
+
if (!event.frame.parentId) this.sendPage(event.frame.url);
|
|
529
|
+
});
|
|
530
|
+
await cdp.send("Page.enable");
|
|
531
|
+
await cdp.send("Runtime.enable");
|
|
532
|
+
const added = await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: DESCRIBE_SCRIPT });
|
|
533
|
+
this.scriptId = added.identifier;
|
|
534
|
+
await cdp.send("Runtime.evaluate", { expression: DESCRIBE_SCRIPT }).catch(quiet("agent/computer/handoff-live"));
|
|
535
|
+
await this.page.bringToFront().catch(quiet("agent/computer/handoff-live"));
|
|
536
|
+
this.sendPage(this.page.url());
|
|
537
|
+
this.up = true;
|
|
538
|
+
void this.drain();
|
|
539
|
+
}
|
|
540
|
+
async stop() {
|
|
541
|
+
if (this.stopped) return;
|
|
542
|
+
this.stopped = true;
|
|
543
|
+
clearTimeout(this.unstick);
|
|
544
|
+
clearTimeout(this.fieldsTimer);
|
|
545
|
+
const cdp = this.cdp;
|
|
546
|
+
if (!cdp) return;
|
|
547
|
+
const quietly = quiet("agent/computer/handoff-live");
|
|
548
|
+
await cdp.send("Page.stopScreencast").catch(quietly);
|
|
549
|
+
if (!this.watch) {
|
|
550
|
+
await cdp.send("Emulation.clearDeviceMetricsOverride").catch(quietly);
|
|
551
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }).catch(quietly);
|
|
552
|
+
}
|
|
553
|
+
if (this.scriptId) await cdp.send("Page.removeScriptToEvaluateOnNewDocument", { identifier: this.scriptId }).catch(quietly);
|
|
554
|
+
await cdp.detach().catch(quietly);
|
|
555
|
+
}
|
|
556
|
+
// ── from the phone ────────────────────────────────────────────────────────
|
|
557
|
+
accept(text) {
|
|
558
|
+
let message;
|
|
559
|
+
try {
|
|
560
|
+
message = JSON.parse(text);
|
|
561
|
+
} catch {
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (!message || typeof message !== "object" || typeof message.t !== "string") return;
|
|
565
|
+
this.activity();
|
|
566
|
+
if (message.t === "ack") {
|
|
567
|
+
this.onAck();
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const last = this.queue.at(-1);
|
|
571
|
+
if (last && (message.t === "touch" && message.k === "m" && last.t === "touch" && last.k === "m" || message.t === "mouse" && message.k === "m" && last.t === "mouse" && last.k === "m" || message.t === "resize" && last.t === "resize" || message.t === "fill" && last.t === "fill" && message.i === last.i)) this.queue[this.queue.length - 1] = message;
|
|
572
|
+
else this.queue.push(message);
|
|
573
|
+
if (this.queue.length > 400) this.queue.splice(0, this.queue.length - 400);
|
|
574
|
+
void this.drain();
|
|
575
|
+
}
|
|
576
|
+
async drain() {
|
|
577
|
+
if (this.draining || !this.up) return;
|
|
578
|
+
this.draining = true;
|
|
579
|
+
try {
|
|
580
|
+
for (let message = this.queue.shift(); message && !this.stopped; message = this.queue.shift()) {
|
|
581
|
+
await this.handle(message).catch(quiet("agent/computer/handoff-live"));
|
|
582
|
+
if (message.t !== "hello" && message.t !== "resize" && message.t !== "done") this.scheduleFields(80);
|
|
583
|
+
}
|
|
584
|
+
} finally {
|
|
585
|
+
this.draining = false;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
async handle(message) {
|
|
589
|
+
const cdp = this.cdp;
|
|
590
|
+
switch (message.t) {
|
|
591
|
+
case "hello":
|
|
592
|
+
case "resize": {
|
|
593
|
+
this.mode = this.watch || message.m === "mouse" ? "mouse" : "touch";
|
|
594
|
+
const size = cleanSize(message);
|
|
595
|
+
if (size) await this.layout(size);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
case "touch": {
|
|
599
|
+
if (this.watch) return;
|
|
600
|
+
const points = cleanPoints(message.p);
|
|
601
|
+
const type = { s: "touchStart", m: "touchMove", e: "touchEnd", c: "touchCancel" }[String(message.k)];
|
|
602
|
+
if (!points || !type) return;
|
|
603
|
+
const view = this.lastView = await this.view();
|
|
604
|
+
const mapped = points.map((point) => ({ ...toPage(view, point.x, point.y), id: point.id }));
|
|
605
|
+
if (type === "touchStart" && points.length === 1 && !this.foreign && await this.overForeignFrame(mapped[0].x, mapped[0].y)) {
|
|
606
|
+
const waiting = { start: { x: mapped[0].x, y: mapped[0].y }, screen: { x: points[0].x, y: points[0].y, id: points[0].id } };
|
|
607
|
+
waiting.timer = setTimeout(() => {
|
|
608
|
+
if (this.foreign !== waiting || waiting.scrolling || waiting.pressed || this.stopped) return;
|
|
609
|
+
waiting.pressed = true;
|
|
610
|
+
void this.pressMouse(waiting.start.x, waiting.start.y, true).catch(quiet("agent/computer/handoff-live"));
|
|
611
|
+
}, HOLD_MS);
|
|
612
|
+
this.foreign = waiting;
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (this.foreign) {
|
|
616
|
+
const waiting = this.foreign;
|
|
617
|
+
if (type === "touchEnd" || type === "touchCancel") {
|
|
618
|
+
this.foreign = void 0;
|
|
619
|
+
clearTimeout(waiting.timer);
|
|
620
|
+
if (waiting.pressed) await this.pressMouse(waiting.start.x, waiting.start.y, false);
|
|
621
|
+
else if (type === "touchEnd" && points.length === 0 && !waiting.scrolling) await this.click(waiting.start.x, waiting.start.y);
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
if (waiting.scrolling || points.length === 1 && Math.hypot(points[0].x - waiting.screen.x, points[0].y - waiting.screen.y) > 10) {
|
|
625
|
+
if (points.length === 1) {
|
|
626
|
+
const from = waiting.last ?? waiting.screen, now = points[0], scale = view.scale > 0.05 ? view.scale : 1;
|
|
627
|
+
if (waiting.pressed) {
|
|
628
|
+
waiting.pressed = false;
|
|
629
|
+
await this.pressMouse(waiting.start.x, waiting.start.y, false);
|
|
630
|
+
}
|
|
631
|
+
waiting.scrolling = true;
|
|
632
|
+
waiting.last = { x: now.x, y: now.y };
|
|
633
|
+
await this.evaluate(`window.scrollBy(${(from.x - now.x) / scale}, ${(from.y - now.y) / scale})`);
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const moved = points.length !== 1;
|
|
638
|
+
if (!moved) return;
|
|
639
|
+
this.foreign = void 0;
|
|
640
|
+
clearTimeout(waiting.timer);
|
|
641
|
+
if (waiting.pressed) await this.pressMouse(waiting.start.x, waiting.start.y, false);
|
|
642
|
+
await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x: waiting.start.x, y: waiting.start.y, id: waiting.screen.id }] });
|
|
643
|
+
}
|
|
644
|
+
await cdp.send("Input.dispatchTouchEvent", { type, touchPoints: mapped });
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
case "mouse": {
|
|
648
|
+
const x = Number(message.x), y = Number(message.y);
|
|
649
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || x < -OUTSIDE || y < -OUTSIDE || x > 2e4 || y > 2e4) return;
|
|
650
|
+
const view = this.lastView = await this.view();
|
|
651
|
+
const at = toPage(view, x, y);
|
|
652
|
+
const button = BUTTONS[Number(message.b)] ?? "left";
|
|
653
|
+
const mask = { left: 1, middle: 4, right: 2 }[button];
|
|
654
|
+
if (message.k === "w") {
|
|
655
|
+
await cdp.send("Input.dispatchMouseEvent", { type: "mouseWheel", x: at.x, y: at.y, deltaX: Math.max(-2e3, Math.min(2e3, Number(message.dx) || 0)), deltaY: Math.max(-2e3, Math.min(2e3, Number(message.dy) || 0)) });
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const type = { d: "mousePressed", u: "mouseReleased", m: "mouseMoved" }[String(message.k)];
|
|
659
|
+
if (!type) return;
|
|
660
|
+
await cdp.send("Input.dispatchMouseEvent", { type, x: at.x, y: at.y, button: type === "mouseMoved" && !message.down ? "none" : button, buttons: type === "mouseReleased" ? 0 : type === "mousePressed" || message.down ? mask : 0, clickCount: type === "mouseMoved" ? 0 : 1 });
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
case "key": {
|
|
664
|
+
const key = keyEvent(message.key);
|
|
665
|
+
if (key) await this.pressKey(key, Math.max(1, Math.min(MAX_REPEAT, Math.floor(Number(message.n) || 1))));
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
case "text": {
|
|
669
|
+
const text = message.s;
|
|
670
|
+
if (typeof text !== "string" || [...text].length !== 1) return;
|
|
671
|
+
await cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: text, text, unmodifiedText: text });
|
|
672
|
+
await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: text });
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
case "fill": {
|
|
676
|
+
const index = Number(message.i), value = message.v;
|
|
677
|
+
if (!Number.isInteger(index) || index < 0 || typeof value !== "string" || value.length > MAX_TEXT) return;
|
|
678
|
+
if (await this.evaluateFor(index, prepareFill) !== "ok") return;
|
|
679
|
+
if (value === "") await this.pressKey(keyEvent("Backspace"), 1);
|
|
680
|
+
else await cdp.send("Input.insertText", { text: value });
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
case "set": {
|
|
684
|
+
const value = message.v;
|
|
685
|
+
const ok = typeof value === "string" ? value.length <= 2e3 : Array.isArray(value) && value.length <= 300 && value.every((item) => typeof item === "string" && item.length <= 2e3);
|
|
686
|
+
if (ok) {
|
|
687
|
+
const index = Number.isInteger(message.i) ? Number(message.i) : -1;
|
|
688
|
+
if (index >= 0) await this.evaluateFor(index, (local) => setValueExpression(value, local));
|
|
689
|
+
else await cdp.send("Runtime.evaluate", { expression: setValueExpression(value, -1) });
|
|
690
|
+
}
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
case "done":
|
|
694
|
+
this.finish();
|
|
695
|
+
return;
|
|
696
|
+
default:
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
// ── to the phone ──────────────────────────────────────────────────────────
|
|
701
|
+
send(message) {
|
|
702
|
+
if (!this.socket.closed) this.socket.send(JSON.stringify(message));
|
|
703
|
+
}
|
|
704
|
+
sendPage(url) {
|
|
705
|
+
let host = "";
|
|
706
|
+
try {
|
|
707
|
+
host = new URL(url).host;
|
|
708
|
+
} catch {
|
|
709
|
+
host = "";
|
|
710
|
+
}
|
|
711
|
+
this.send({ t: "page", host });
|
|
712
|
+
}
|
|
713
|
+
async evaluate(expression) {
|
|
714
|
+
try {
|
|
715
|
+
const result = await this.cdp.send("Runtime.evaluate", { expression, returnByValue: true });
|
|
716
|
+
return result.result?.value;
|
|
717
|
+
} catch {
|
|
718
|
+
return void 0;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
async pressKey(key, times) {
|
|
722
|
+
const cdp = this.cdp;
|
|
723
|
+
for (let i = 0; i < times; i++) {
|
|
724
|
+
await cdp.send("Input.dispatchKeyEvent", { type: key.text ? "keyDown" : "rawKeyDown", key: key.key, code: key.code, windowsVirtualKeyCode: key.vk, nativeVirtualKeyCode: key.vk, ...key.text ? { text: key.text, unmodifiedText: key.text } : {} });
|
|
725
|
+
await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: key.key, code: key.code, windowsVirtualKeyCode: key.vk, nativeVirtualKeyCode: key.vk });
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/** Whether a point of the page is over a frame from another site (its document cannot be read from here). */
|
|
729
|
+
async overForeignFrame(x, y) {
|
|
730
|
+
const result = await this.evaluate(`((x, y) => { const e = document.elementFromPoint(x, y); if (!e || e.tagName !== 'IFRAME') return false; try { return !e.contentDocument; } catch (error) { return true; } })(${x}, ${y})`);
|
|
731
|
+
return result === true;
|
|
732
|
+
}
|
|
733
|
+
async pressMouse(x, y, down) {
|
|
734
|
+
const cdp = this.cdp;
|
|
735
|
+
if (down) await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none", buttons: 0 });
|
|
736
|
+
await cdp.send("Input.dispatchMouseEvent", { type: down ? "mousePressed" : "mouseReleased", x, y, button: "left", buttons: down ? 1 : 0, clickCount: 1 });
|
|
737
|
+
}
|
|
738
|
+
async click(x, y) {
|
|
739
|
+
const cdp = this.cdp;
|
|
740
|
+
await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none", buttons: 0 });
|
|
741
|
+
await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", buttons: 1, clickCount: 1 });
|
|
742
|
+
await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", buttons: 0, clickCount: 1 });
|
|
743
|
+
}
|
|
744
|
+
/** The visual viewport right now, read before each input so a pinch or a pan that just happened is already in the next position. */
|
|
745
|
+
async view() {
|
|
746
|
+
try {
|
|
747
|
+
const result = await this.cdp.send("Runtime.evaluate", { expression: READ_VIEW, returnByValue: true });
|
|
748
|
+
const value = result.result?.value;
|
|
749
|
+
if (value && Number.isFinite(value.scale) && Number.isFinite(value.x) && Number.isFinite(value.y)) return value;
|
|
750
|
+
} catch {
|
|
751
|
+
}
|
|
752
|
+
return this.lastView;
|
|
753
|
+
}
|
|
754
|
+
async layout(size) {
|
|
755
|
+
const cdp = this.cdp;
|
|
756
|
+
const same = this.size && this.size.w === size.w && this.size.h === size.h && this.size.dpr === size.dpr && this.laidOutAs === this.mode;
|
|
757
|
+
this.size = size;
|
|
758
|
+
if (same && this.streaming) return;
|
|
759
|
+
const touch = this.mode === "touch";
|
|
760
|
+
this.laidOutAs = this.mode;
|
|
761
|
+
if (!this.watch) {
|
|
762
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", { width: size.w, height: size.h, deviceScaleFactor: size.dpr, mobile: touch });
|
|
763
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", touch ? { enabled: true, maxTouchPoints: 5 } : { enabled: false });
|
|
764
|
+
}
|
|
765
|
+
const scale = Math.min(size.dpr, 2);
|
|
766
|
+
if (this.streaming) await cdp.send("Page.stopScreencast").catch(quiet("agent/computer/handoff-live"));
|
|
767
|
+
this.held = void 0;
|
|
768
|
+
this.ready = true;
|
|
769
|
+
await cdp.send("Page.startScreencast", { format: "jpeg", quality: 70, maxWidth: Math.round(size.w * scale), maxHeight: Math.round(size.h * scale), everyNthFrame: 1 });
|
|
770
|
+
this.streaming = true;
|
|
771
|
+
this.stats.restarts++;
|
|
772
|
+
if (this.watch) await this.sendTabSize();
|
|
773
|
+
else this.send({ t: "size", w: size.w, h: size.h });
|
|
774
|
+
this.scheduleFields(250);
|
|
775
|
+
}
|
|
776
|
+
/** Watching: the tab's own size in page pixels, which is what the viewer scales the picture from and measures its pointer in. */
|
|
777
|
+
async sendTabSize() {
|
|
778
|
+
const own = await this.evaluate("({ w: innerWidth, h: innerHeight })");
|
|
779
|
+
if (own && own.w > 0 && own.h > 0) this.send({ t: "size", w: own.w, h: own.h });
|
|
780
|
+
}
|
|
781
|
+
/** One frame in flight at a time: Chrome is told a frame was received only once it has gone to the phone, so it paints no faster than the phone draws, and the phone always gets the newest. */
|
|
782
|
+
async onFrame(frame) {
|
|
783
|
+
if (this.stopped || this.socket.closed) return;
|
|
784
|
+
if (this.watch) {
|
|
785
|
+
const now = `${frame.metadata?.deviceWidth}x${frame.metadata?.deviceHeight}`;
|
|
786
|
+
if (now !== this.frameSize) {
|
|
787
|
+
this.frameSize = now;
|
|
788
|
+
void this.sendTabSize();
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
if (!this.ready || this.socket.buffered > 4e5) {
|
|
792
|
+
if (this.held) await this.ackChrome(this.held.sessionId);
|
|
793
|
+
this.held = frame;
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
await this.deliver(frame);
|
|
797
|
+
}
|
|
798
|
+
async deliver(frame) {
|
|
799
|
+
this.ready = false;
|
|
800
|
+
this.stats.frames++;
|
|
801
|
+
this.scheduleFields();
|
|
802
|
+
this.socket.send(Buffer.concat([Buffer.from([1]), Buffer.from(frame.data, "base64")]));
|
|
803
|
+
await this.ackChrome(frame.sessionId);
|
|
804
|
+
clearTimeout(this.unstick);
|
|
805
|
+
this.unstick = setTimeout(() => {
|
|
806
|
+
this.ready = true;
|
|
807
|
+
const held2 = this.held;
|
|
808
|
+
if (held2) {
|
|
809
|
+
this.held = void 0;
|
|
810
|
+
void this.deliver(held2);
|
|
811
|
+
}
|
|
812
|
+
}, 1500);
|
|
813
|
+
}
|
|
814
|
+
onAck() {
|
|
815
|
+
clearTimeout(this.unstick);
|
|
816
|
+
this.ready = true;
|
|
817
|
+
const held2 = this.held;
|
|
818
|
+
if (held2) {
|
|
819
|
+
this.held = void 0;
|
|
820
|
+
void this.deliver(held2);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
/** Tells the phone where the page's fields are, when that changed: after frames (the page moved) and after input. */
|
|
824
|
+
scheduleFields(delay = 140) {
|
|
825
|
+
if (this.fieldsTimer || this.stopped) return;
|
|
826
|
+
this.fieldsTimer = setTimeout(() => {
|
|
827
|
+
this.fieldsTimer = void 0;
|
|
828
|
+
void this.refreshFields();
|
|
829
|
+
}, delay);
|
|
830
|
+
}
|
|
831
|
+
async refreshFields() {
|
|
832
|
+
if (this.stopped || this.socket.closed || !this.cdp) return;
|
|
833
|
+
try {
|
|
834
|
+
const result = await this.cdp.send("Runtime.evaluate", { expression: FIELDS_SCRIPT, returnByValue: true });
|
|
835
|
+
const main = result.result?.value;
|
|
836
|
+
if (typeof main !== "string") return;
|
|
837
|
+
const fields = JSON.parse(main);
|
|
838
|
+
fields.push(...await this.frameFields());
|
|
839
|
+
const text = JSON.stringify(fields);
|
|
840
|
+
if (text === this.lastFields) return;
|
|
841
|
+
this.lastFields = text;
|
|
842
|
+
this.send({ t: "fields", f: fields });
|
|
843
|
+
} catch {
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
/** The fields inside frames (a sign-in box or a CAPTCHA's answer line, often from another site), placed on the phone's screen like the page's own.
|
|
847
|
+
* A field of frame n is numbered n * FRAME_IDS + its number in the frame, so a name reaches the frame it belongs to. */
|
|
848
|
+
async frameFields() {
|
|
849
|
+
const out = [];
|
|
850
|
+
const known = [this.page.mainFrame()];
|
|
851
|
+
const view = await this.view();
|
|
852
|
+
for (const frame of this.page.frames()) {
|
|
853
|
+
if (frame === this.page.mainFrame() || known.length > MAX_FRAMES) continue;
|
|
854
|
+
try {
|
|
855
|
+
const box = await (await frame.frameElement()).boundingBox();
|
|
856
|
+
if (!box || box.width < 4 || box.height < 4) continue;
|
|
857
|
+
await frame.evaluate(DESCRIBE_SCRIPT);
|
|
858
|
+
const list = JSON.parse(await frame.evaluate(FIELDS_SCRIPT));
|
|
859
|
+
const n = known.push(frame) - 1;
|
|
860
|
+
for (const field of list) out.push({ ...field, i: n * FRAME_IDS + field.i, x: Math.round((box.x + field.x - view.x) * view.scale * 10) / 10, y: Math.round((box.y + field.y - view.y) * view.scale * 10) / 10, w: Math.round(field.w * view.scale * 10) / 10, h: Math.round(field.h * view.scale * 10) / 10, d: { ...field.d, idx: n * FRAME_IDS + field.i } });
|
|
861
|
+
} catch {
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
this.frames = known;
|
|
865
|
+
return out;
|
|
866
|
+
}
|
|
867
|
+
/** Runs a script in the frame a field number belongs to, with the number inside that frame. */
|
|
868
|
+
async evaluateFor(index, script) {
|
|
869
|
+
const frame = this.frames[Math.floor(index / FRAME_IDS)];
|
|
870
|
+
const local = index % FRAME_IDS;
|
|
871
|
+
if (!frame) return void 0;
|
|
872
|
+
if (frame === this.page.mainFrame()) return this.evaluate(script(local));
|
|
873
|
+
try {
|
|
874
|
+
return await frame.evaluate(script(local));
|
|
875
|
+
} catch {
|
|
876
|
+
return void 0;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
async ackChrome(sessionId) {
|
|
880
|
+
await this.cdp?.send("Page.screencastFrameAck", { sessionId }).catch(quiet("agent/computer/handoff-live"));
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
// src/agent/computer/handoff-page.ts
|
|
885
|
+
function handoffPage(options = {}) {
|
|
886
|
+
const back = options.back && /^\/[A-Za-z0-9_\-/]{1,200}$/.test(options.back) ? options.back : "";
|
|
887
|
+
const watch = options.watch === true;
|
|
888
|
+
return `<!doctype html><html lang="en"><meta charset="utf-8">
|
|
889
|
+
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
|
|
890
|
+
<meta name="referrer" content="no-referrer"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="theme-color" content="#161b22">
|
|
891
|
+
<title>${watch ? "Watching ClikCode" : "Finish in ClikCode"}</title>
|
|
892
|
+
<style>
|
|
893
|
+
html,body{margin:0;height:100%;background:#0d1117;color:#f2f5f8;font:15px system-ui,-apple-system,sans-serif;overflow:hidden;overscroll-behavior:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}
|
|
894
|
+
#app{position:fixed;left:0;right:0;top:0;height:100%;display:flex;flex-direction:column}
|
|
895
|
+
#bar{display:flex;align-items:center;gap:8px;padding:6px 10px;padding-top:max(6px,env(safe-area-inset-top));background:#161b22;border-bottom:1px solid #30363d;min-height:36px}
|
|
896
|
+
#dot{width:9px;height:9px;border-radius:50%;background:#d29922;flex:none}#dot.on{background:#3fb950}
|
|
897
|
+
#host{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;color:#c9d1d9}
|
|
898
|
+
#ms{font-size:12px;color:#8b949e;font-variant-numeric:tabular-nums}
|
|
899
|
+
button{font:inherit;min-height:34px;border-radius:8px;border:1px solid #484f58;background:#21262d;color:#f0f6fc;padding:0 12px}
|
|
900
|
+
#done{background:#238636;border-color:#2ea043;font-weight:600}
|
|
901
|
+
#stage{flex:1;min-height:0;position:relative;background:#000;overflow:hidden}
|
|
902
|
+
#fit{position:absolute;inset:0;transform-origin:0 0}
|
|
903
|
+
#c{position:absolute;left:0;top:0;touch-action:none;outline:none;background:#000}
|
|
904
|
+
#overlays{position:absolute;inset:0;z-index:4;pointer-events:none}
|
|
905
|
+
#overlays>*{position:absolute;box-sizing:border-box;margin:0;padding:0;border:0;border-radius:0;outline:0;background:transparent;color:transparent;caret-color:transparent;opacity:.01;font-size:16px;pointer-events:auto;touch-action:none;resize:none;-webkit-appearance:none;appearance:none;-webkit-user-select:text;user-select:text}
|
|
906
|
+
#overlays.moving>*{pointer-events:none}
|
|
907
|
+
#veil{position:absolute;inset:0;z-index:6;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,.78);text-align:center;padding:24px;line-height:1.4}
|
|
908
|
+
#veil.on{display:flex}
|
|
909
|
+
@media (max-width:430px){#ms{display:none}}
|
|
910
|
+
</style>
|
|
911
|
+
<div id="app">
|
|
912
|
+
<div id="bar"><span id="dot"></span><span id="host">Connecting\u2026</span><span id="ms"></span>${watch ? '<span id="note" style="font-size:12px;color:#8b949e">Live: ClikCode is working here; your clicks and typing reach the page too</span>' : '<button id="mode" aria-label="Switch between touch and mouse">Mouse</button><button id="done">Done</button>'}</div>
|
|
913
|
+
<div id="stage"><div id="fit"><canvas id="c" tabindex="0"></canvas><div id="overlays"></div></div><div id="veil" class="on"><span id="veilText">Connecting\u2026</span></div></div>
|
|
914
|
+
</div>
|
|
915
|
+
<script>
|
|
916
|
+
(() => {
|
|
917
|
+
const $ = (id) => document.getElementById(id);
|
|
918
|
+
const base = location.pathname.replace(/\\/$/, '');
|
|
919
|
+
const BACK = ${JSON.stringify(back)};
|
|
920
|
+
const WATCH = ${JSON.stringify(watch)};
|
|
921
|
+
const canvas = $('c'), ctx = canvas.getContext('2d', { alpha: false });
|
|
922
|
+
const stage = $('stage'), app = $('app'), overlays = $('overlays'), box = $('fit');
|
|
923
|
+
const T = window.__handoff = { frames: 0, latency: 0, connected: false, ended: false, mode: 'touch', fields: 0, overlays: 0 };
|
|
924
|
+
let ws = null, retry = 0, finished = false, sentAt = 0, lastSize = '';
|
|
925
|
+
|
|
926
|
+
// Touch on a phone or tablet, mouse on a computer; the button beside Done switches, and says what it would switch to.
|
|
927
|
+
let mode = '';
|
|
928
|
+
try { mode = localStorage.getItem('clikcode-handoff-mode') || ''; } catch (error) { /* private browsing */ }
|
|
929
|
+
if (mode !== 'touch' && mode !== 'mouse') mode = matchMedia('(pointer: coarse)').matches ? 'touch' : 'mouse';
|
|
930
|
+
if (WATCH) mode = 'mouse';
|
|
931
|
+
T.mode = mode;
|
|
932
|
+
const showMode = () => { if (!WATCH) $('mode').textContent = mode === 'touch' ? 'Mouse' : 'Touch'; };
|
|
933
|
+
showMode();
|
|
934
|
+
|
|
935
|
+
const veil = (text) => { $('veilText').textContent = text || ''; $('veil').classList.toggle('on', Boolean(text)); };
|
|
936
|
+
const send = (o) => { if (ws && ws.readyState === 1) { ws.send(JSON.stringify(o)); return true; } return false; };
|
|
937
|
+
const input = (o) => { if (!sentAt) sentAt = performance.now(); return send(o); };
|
|
938
|
+
const round1 = (n) => Math.round(n * 10) / 10;
|
|
939
|
+
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
|
|
940
|
+
const el = (tag, className, text) => { const n = document.createElement(tag); if (className) n.className = className; if (text !== undefined) n.textContent = text; return n; };
|
|
941
|
+
|
|
942
|
+
// The app is as tall as what is visible: with the phone's keyboard up that is the area above it, and the page reflows to it.
|
|
943
|
+
const fit = () => { const v = window.visualViewport; if (v) { app.style.height = v.height + 'px'; app.style.top = v.offsetTop + 'px'; } };
|
|
944
|
+
if (window.visualViewport) { visualViewport.addEventListener('resize', fit); visualViewport.addEventListener('scroll', fit); }
|
|
945
|
+
fit();
|
|
946
|
+
let sizeTimer = 0;
|
|
947
|
+
const sendSize = (force) => {
|
|
948
|
+
const w = stage.clientWidth, h = stage.clientHeight;
|
|
949
|
+
if (w < 50 || h < 50) return;
|
|
950
|
+
const o = { t: 'resize', w, h, dpr: Math.min(window.devicePixelRatio || 1, 3), m: mode };
|
|
951
|
+
const key = JSON.stringify(o);
|
|
952
|
+
if (!force && key === lastSize) return;
|
|
953
|
+
lastSize = key;
|
|
954
|
+
if (WATCH) refit(); else { canvas.style.width = w + 'px'; canvas.style.height = h + 'px'; }
|
|
955
|
+
send(o);
|
|
956
|
+
};
|
|
957
|
+
// Watching: the picture is the tab at its own size (tab.w by tab.h page pixels), shrunk to fit the window and centred. K is how much it
|
|
958
|
+
// is shrunk; a position on the screen divided by K is a position in the page. Everywhere else K is 1.
|
|
959
|
+
let K = 1, tab = null;
|
|
960
|
+
const refit = () => {
|
|
961
|
+
if (!tab) return;
|
|
962
|
+
const w = stage.clientWidth, h = stage.clientHeight;
|
|
963
|
+
K = Math.min(1, w / tab.w, h / tab.h);
|
|
964
|
+
box.style.inset = 'auto'; box.style.width = tab.w + 'px'; box.style.height = tab.h + 'px';
|
|
965
|
+
box.style.left = Math.max(0, (w - tab.w * K) / 2) + 'px'; box.style.top = Math.max(0, (h - tab.h * K) / 2) + 'px';
|
|
966
|
+
box.style.transform = 'scale(' + K + ')';
|
|
967
|
+
canvas.style.width = tab.w + 'px'; canvas.style.height = tab.h + 'px';
|
|
968
|
+
T.scale = K;
|
|
969
|
+
};
|
|
970
|
+
new ResizeObserver(() => { clearTimeout(sizeTimer); sizeTimer = setTimeout(() => sendSize(false), 80); }).observe(stage);
|
|
971
|
+
|
|
972
|
+
// \u2500\u2500 frames \u2500\u2500
|
|
973
|
+
let decoding = false, newest = null;
|
|
974
|
+
const drawNewest = async () => {
|
|
975
|
+
decoding = true;
|
|
976
|
+
while (newest) {
|
|
977
|
+
const bytes = newest; newest = null;
|
|
978
|
+
try {
|
|
979
|
+
const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/jpeg' }));
|
|
980
|
+
if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) { canvas.width = bitmap.width; canvas.height = bitmap.height; }
|
|
981
|
+
ctx.drawImage(bitmap, 0, 0);
|
|
982
|
+
if (bitmap.close) bitmap.close();
|
|
983
|
+
T.frames++;
|
|
984
|
+
if (T.frames === 1) veil('');
|
|
985
|
+
if (sentAt) { T.latency = Math.round(performance.now() - sentAt); sentAt = 0; $('ms').textContent = T.latency + ' ms'; }
|
|
986
|
+
} catch (error) { /* a frame that cannot be drawn is skipped */ }
|
|
987
|
+
send({ t: 'ack' });
|
|
988
|
+
}
|
|
989
|
+
decoding = false;
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
// \u2500\u2500 connection \u2500\u2500
|
|
993
|
+
let fields = [];
|
|
994
|
+
const connect = () => {
|
|
995
|
+
ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + base + '/live');
|
|
996
|
+
ws.binaryType = 'arraybuffer';
|
|
997
|
+
ws.onopen = () => { retry = 0; T.connected = true; $('dot').className = 'on'; lastSize = ''; sendSize(true); };
|
|
998
|
+
ws.onclose = async () => {
|
|
999
|
+
T.connected = false; $('dot').className = '';
|
|
1000
|
+
if (finished) return;
|
|
1001
|
+
retry++;
|
|
1002
|
+
let alive = true;
|
|
1003
|
+
try { alive = (await fetch(base + '/ping', { cache: 'no-store' })).status !== 410; } catch (error) { alive = true; }
|
|
1004
|
+
if (!alive) { finished = true; T.ended = true; veil(WATCH ? 'This view has ended. Ask ClikCode to show the tab again.' : 'This link has ended. Ask ClikCode for a new one if you still need it.'); return; }
|
|
1005
|
+
veil('Reconnecting\u2026');
|
|
1006
|
+
setTimeout(connect, Math.min(1000, 150 * retry));
|
|
1007
|
+
};
|
|
1008
|
+
ws.onmessage = (event) => {
|
|
1009
|
+
if (typeof event.data !== 'string') { newest = new Uint8Array(event.data, 1); if (!decoding) drawNewest(); return; }
|
|
1010
|
+
let msg; try { msg = JSON.parse(event.data); } catch (error) { return; }
|
|
1011
|
+
if (msg.t === 'page') $('host').textContent = msg.host || '';
|
|
1012
|
+
else if (msg.t === 'size') { if (WATCH && msg.w > 0 && msg.h > 0) { tab = { w: msg.w, h: msg.h }; refit(); } }
|
|
1013
|
+
else if (msg.t === 'fields') { fields = Array.isArray(msg.f) ? msg.f : []; T.fields = fields.length; syncOverlays(); }
|
|
1014
|
+
else if (msg.t === 'done') { finished = true; T.ended = true; veil('Done. ClikCode will continue.'); if (BACK) setTimeout(() => { location.href = BACK; }, 900); }
|
|
1015
|
+
};
|
|
1016
|
+
};
|
|
1017
|
+
|
|
1018
|
+
// \u2500\u2500 the page's fields, as the phone's own inputs, in place \u2500\u2500
|
|
1019
|
+
// A real input is laid over each field in the picture, so a finger that touches a field lands on an input of the phone itself: the phone
|
|
1020
|
+
// opens its own keyboard (with the field's kind, autofill and Enter key) or its own picker, with nothing for the page to ask it to do. What is
|
|
1021
|
+
// entered is put into the page's field; the picture shows it arrive.
|
|
1022
|
+
const overlay = new Map();
|
|
1023
|
+
const isOverlay = (n) => Boolean(n && n.closest && n.closest('#overlays > *'));
|
|
1024
|
+
const place = (e, f) => { e.style.left = f.x + 'px'; e.style.top = f.y + 'px'; e.style.width = Math.max(f.w, 24) + 'px'; e.style.height = Math.max(f.h, 24) + 'px'; };
|
|
1025
|
+
const signature = (f) => JSON.stringify([f.d.kind, f.d.type || '', f.d.options ? f.d.options.length : 0, f.d.multiline ? 1 : 0, f.d.inputmode || '', f.d.autocomplete || '', f.d.enterkeyhint || '']);
|
|
1026
|
+
const makeOverlay = (f) => {
|
|
1027
|
+
const d = f.d;
|
|
1028
|
+
let e;
|
|
1029
|
+
if (d.kind === 'select') {
|
|
1030
|
+
e = el('select'); e.multiple = Boolean(d.multiple);
|
|
1031
|
+
for (const o of d.options) { const op = el('option', '', o.t || o.v || '\u2014'); op.value = o.v; op.selected = Boolean(o.s); op.disabled = Boolean(o.d); e.appendChild(op); }
|
|
1032
|
+
e.onchange = () => input({ t: 'set', i: f.i, v: d.multiple ? Array.from(e.selectedOptions).map((o) => o.value) : e.value });
|
|
1033
|
+
} else if (d.kind === 'native') {
|
|
1034
|
+
e = el('input'); e.type = d.type; if (d.min) e.min = d.min; if (d.max) e.max = d.max; if (d.step) e.step = d.step; e.value = d.value || '';
|
|
1035
|
+
e.onchange = () => input({ t: 'set', i: f.i, v: e.value });
|
|
1036
|
+
} else {
|
|
1037
|
+
const multiline = Boolean(d.multiline);
|
|
1038
|
+
e = el(multiline ? 'textarea' : 'input');
|
|
1039
|
+
if (!multiline) e.type = d.type === 'editable' ? 'text' : d.type;
|
|
1040
|
+
if (d.inputmode) e.inputMode = d.inputmode;
|
|
1041
|
+
if (d.autocomplete) e.setAttribute('autocomplete', d.autocomplete);
|
|
1042
|
+
if (d.enterkeyhint) e.enterKeyHint = d.enterkeyhint;
|
|
1043
|
+
if (d.maxlength) e.maxLength = d.maxlength;
|
|
1044
|
+
if (['email', 'url', 'password'].includes(d.type)) { e.autocapitalize = 'off'; e.autocorrect = 'off'; e.spellcheck = false; }
|
|
1045
|
+
e.value = d.value || '';
|
|
1046
|
+
e.addEventListener('input', () => input({ t: 'fill', i: f.i, v: e.value }));
|
|
1047
|
+
if (!multiline) e.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); input({ t: 'key', key: 'Enter' }); } });
|
|
1048
|
+
}
|
|
1049
|
+
e.dataset.i = String(f.i); e.dataset.sig = signature(f);
|
|
1050
|
+
return e;
|
|
1051
|
+
};
|
|
1052
|
+
const syncOverlays = () => {
|
|
1053
|
+
const keep = new Set();
|
|
1054
|
+
for (const f of fields) {
|
|
1055
|
+
let e = overlay.get(f.i);
|
|
1056
|
+
// The one being typed in is never replaced or rewritten under the person's finger.
|
|
1057
|
+
if (e && e.dataset.sig !== signature(f) && e !== document.activeElement) { e.remove(); overlay.delete(f.i); e = undefined; }
|
|
1058
|
+
if (!e) { e = makeOverlay(f); overlays.appendChild(e); overlay.set(f.i, e); }
|
|
1059
|
+
place(e, f); keep.add(f.i);
|
|
1060
|
+
if (e === document.activeElement || f.d.type === 'password') continue;
|
|
1061
|
+
if (f.d.kind === 'select') { for (const o of e.options) o.selected = f.d.options.some((x) => x.v === o.value && x.s); }
|
|
1062
|
+
else if (e.value !== (f.d.value || '')) e.value = f.d.value || '';
|
|
1063
|
+
}
|
|
1064
|
+
for (const [i, e] of Array.from(overlay)) if (!keep.has(i) && e !== document.activeElement) { e.remove(); overlay.delete(i); }
|
|
1065
|
+
T.overlays = overlay.size;
|
|
1066
|
+
};
|
|
1067
|
+
const fieldAt = (x, y) => {
|
|
1068
|
+
let best = null;
|
|
1069
|
+
for (const f of fields) {
|
|
1070
|
+
if (x < f.x - 6 || x > f.x + f.w + 6 || y < f.y - 6 || y > f.y + f.h + 6) continue;
|
|
1071
|
+
if (!best || f.w * f.h < best.w * best.h) best = f;
|
|
1072
|
+
}
|
|
1073
|
+
return best;
|
|
1074
|
+
};
|
|
1075
|
+
// A choice or a date is the phone's own picker: the tap is kept from the page (its pop-up would open on the computer, unseen).
|
|
1076
|
+
const holds = (f) => Boolean(f) && (f.d.kind === 'select' || f.d.kind === 'native');
|
|
1077
|
+
|
|
1078
|
+
// \u2500\u2500 touch or mouse, on a phone's screen \u2500\u2500
|
|
1079
|
+
const slots = new Map();
|
|
1080
|
+
const slotOf = (id) => { if (!slots.has(id)) { const used = new Set(slots.values()); let s = 0; while (used.has(s)) s++; slots.set(id, s); } return slots.get(id); };
|
|
1081
|
+
let g = null; // touch mode: the one finger that is down
|
|
1082
|
+
let m = null; // mouse mode: the one finger that is the pointer
|
|
1083
|
+
let two = null; // mouse mode: two fingers (scroll, or a right click)
|
|
1084
|
+
const mid = (list) => ({ x: round1(list.reduce((n, p) => n + p.x, 0) / list.length), y: round1(list.reduce((n, p) => n + p.y, 0) / list.length) });
|
|
1085
|
+
|
|
1086
|
+
const touchMode = (k, list) => {
|
|
1087
|
+
const pts = list.map((p) => [p.id, p.x, p.y]);
|
|
1088
|
+
if (k === 's') {
|
|
1089
|
+
if (list.length === 1) {
|
|
1090
|
+
const f = fieldAt(list[0].x, list[0].y);
|
|
1091
|
+
g = { x: list[0].x, y: list[0].y, t: performance.now(), moved: false, held: holds(f) };
|
|
1092
|
+
if (g.held) return;
|
|
1093
|
+
} else if (g) {
|
|
1094
|
+
if (g.held) { g.held = false; input({ t: 'touch', k: 's', p: [[0, g.x, g.y]] }); }
|
|
1095
|
+
g.moved = true;
|
|
1096
|
+
}
|
|
1097
|
+
input({ t: 'touch', k: 's', p: pts });
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
if (k === 'm') {
|
|
1101
|
+
if (g && !g.moved && list.length === 1 && dist(list[0], g) > 10) {
|
|
1102
|
+
g.moved = true;
|
|
1103
|
+
if (g.held) { g.held = false; input({ t: 'touch', k: 's', p: [[list[0].id, g.x, g.y]] }); }
|
|
1104
|
+
}
|
|
1105
|
+
if (g && g.held) return;
|
|
1106
|
+
input({ t: 'touch', k: 'm', p: pts });
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
if (g && g.held) { g = null; return; }
|
|
1110
|
+
input({ t: 'touch', k, p: pts });
|
|
1111
|
+
if (list.length === 0) g = null;
|
|
1112
|
+
};
|
|
1113
|
+
|
|
1114
|
+
const mouseMode = (k, list) => {
|
|
1115
|
+
const now = performance.now();
|
|
1116
|
+
const press = () => { if (!m || m.pressed || m.held) return; m.pressed = true; input({ t: 'mouse', k: 'd', b: 0, x: m.x, y: m.y }); };
|
|
1117
|
+
if (k === 's') {
|
|
1118
|
+
if (list.length === 1) {
|
|
1119
|
+
const p = list[0], f = fieldAt(p.x, p.y);
|
|
1120
|
+
m = { x: p.x, y: p.y, t: now, pressed: false, moved: false, held: holds(f), timer: 0, last: p };
|
|
1121
|
+
send({ t: 'mouse', k: 'm', x: p.x, y: p.y, down: 0 });
|
|
1122
|
+
// A moment's wait, so a second finger landing (a scroll, a right click) is not first taken for a click.
|
|
1123
|
+
if (!m.held) m.timer = setTimeout(press, 50);
|
|
1124
|
+
} else {
|
|
1125
|
+
if (m) { clearTimeout(m.timer); if (m.pressed) input({ t: 'mouse', k: 'u', b: 0, x: m.last.x, y: m.last.y }); m = null; }
|
|
1126
|
+
two = { mid: mid(list), t: now, moved: 0 };
|
|
1127
|
+
}
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (k === 'm') {
|
|
1131
|
+
if (list.length >= 2 && two) {
|
|
1132
|
+
const c = mid(list), dx = two.mid.x - c.x, dy = two.mid.y - c.y;
|
|
1133
|
+
two.moved += Math.abs(dx) + Math.abs(dy); two.mid = c;
|
|
1134
|
+
if (dx || dy) input({ t: 'mouse', k: 'w', dx, dy, x: c.x, y: c.y });
|
|
1135
|
+
} else if (list.length === 1 && m) {
|
|
1136
|
+
const p = list[0];
|
|
1137
|
+
if (!m.moved && dist(p, m) > 8) { m.moved = true; clearTimeout(m.timer); m.held = false; press(); }
|
|
1138
|
+
if (m.moved) { m.last = p; input({ t: 'mouse', k: 'm', x: p.x, y: p.y, down: 1 }); }
|
|
1139
|
+
}
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
if (two) {
|
|
1143
|
+
if (list.length === 0) {
|
|
1144
|
+
if (k === 'e' && now - two.t < 350 && two.moved < 12) { input({ t: 'mouse', k: 'd', b: 2, x: two.mid.x, y: two.mid.y }); input({ t: 'mouse', k: 'u', b: 2, x: two.mid.x, y: two.mid.y }); }
|
|
1145
|
+
two = null;
|
|
1146
|
+
}
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
if (m && list.length === 0) {
|
|
1150
|
+
clearTimeout(m.timer);
|
|
1151
|
+
if (m.held) { m = null; return; }
|
|
1152
|
+
if (!m.pressed) press();
|
|
1153
|
+
input({ t: 'mouse', k: 'u', b: 0, x: m.last.x, y: m.last.y });
|
|
1154
|
+
m = null;
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
|
|
1158
|
+
// A plain tap on one of the phone's own inputs is left to the phone, which focuses it and opens its keyboard or picker. Anything else is ours:
|
|
1159
|
+
// a drag that starts on a field is a scroll (the input is stepped aside for it), and a tap elsewhere puts the keyboard away.
|
|
1160
|
+
let onField = false, dragged = false, startAt = null;
|
|
1161
|
+
const onTouch = (k) => (event) => {
|
|
1162
|
+
const r = canvas.getBoundingClientRect();
|
|
1163
|
+
const list = Array.from(event.touches).map((t) => ({ id: slotOf(t.identifier), x: round1((t.clientX - r.left) / K), y: round1((t.clientY - r.top) / K) }));
|
|
1164
|
+
if (k === 's') { dragged = false; startAt = list[0] || null; onField = list.length === 1 && isOverlay(event.target); }
|
|
1165
|
+
if (k === 'm' && startAt && !dragged && (list.length > 1 || (list[0] && dist(list[0], startAt) > 10))) dragged = true;
|
|
1166
|
+
if (!(onField && !dragged)) event.preventDefault();
|
|
1167
|
+
if (mode === 'touch') touchMode(k, list); else mouseMode(k, list);
|
|
1168
|
+
if (k === 'e' || k === 'c') {
|
|
1169
|
+
const tapAway = k === 'e' && !dragged && !onField;
|
|
1170
|
+
if (tapAway && document.activeElement && isOverlay(document.activeElement)) document.activeElement.blur();
|
|
1171
|
+
const live = new Set(Array.from(event.touches).map((t) => t.identifier));
|
|
1172
|
+
for (const id of Array.from(slots.keys())) if (!live.has(id)) slots.delete(id);
|
|
1173
|
+
// After a drag the inputs wait a moment, until the page has told the phone where its fields have moved to (a tap on one at its old place would miss).
|
|
1174
|
+
if (list.length === 0) { onField = false; if (dragged) { overlays.classList.add('moving'); setTimeout(() => overlays.classList.remove('moving'), 300); } }
|
|
1175
|
+
}
|
|
1176
|
+
};
|
|
1177
|
+
for (const [name, k] of [['touchstart', 's'], ['touchmove', 'm'], ['touchend', 'e'], ['touchcancel', 'c']]) stage.addEventListener(name, onTouch(k), { passive: false });
|
|
1178
|
+
document.addEventListener('gesturestart', (e) => e.preventDefault());
|
|
1179
|
+
document.body.addEventListener('touchmove', (e) => { if (!(onField && !dragged)) e.preventDefault(); }, { passive: false });
|
|
1180
|
+
|
|
1181
|
+
// A computer's own mouse and keyboard.
|
|
1182
|
+
let down = null, lastMove = 0;
|
|
1183
|
+
const at = (e) => { const r = canvas.getBoundingClientRect(); return { x: round1((e.clientX - r.left) / K), y: round1((e.clientY - r.top) / K) }; };
|
|
1184
|
+
stage.addEventListener('mousedown', (e) => {
|
|
1185
|
+
if (isOverlay(e.target)) return;
|
|
1186
|
+
canvas.focus();
|
|
1187
|
+
const p = at(e), f = fieldAt(p.x, p.y);
|
|
1188
|
+
if (document.activeElement && isOverlay(document.activeElement)) document.activeElement.blur();
|
|
1189
|
+
down = { x: p.x, y: p.y, held: holds(f) && e.button === 0 };
|
|
1190
|
+
if (!down.held) input({ t: 'mouse', k: 'd', b: e.button, ...p });
|
|
1191
|
+
});
|
|
1192
|
+
window.addEventListener('mouseup', (e) => {
|
|
1193
|
+
if (!down) return;
|
|
1194
|
+
const p = at(e), d = down; down = null;
|
|
1195
|
+
if (!d.held) input({ t: 'mouse', k: 'u', b: e.button, ...p });
|
|
1196
|
+
});
|
|
1197
|
+
stage.addEventListener('mousemove', (e) => { const now = performance.now(); if (now - lastMove < 16 || (down && down.held)) return; lastMove = now; send({ t: 'mouse', k: 'm', down: down ? 1 : 0, ...at(e) }); });
|
|
1198
|
+
stage.addEventListener('wheel', (e) => { e.preventDefault(); input({ t: 'mouse', k: 'w', dx: e.deltaX, dy: e.deltaY, ...at(e) }); }, { passive: false });
|
|
1199
|
+
const NAMED = ['Enter', 'Tab', 'Backspace', 'Delete', 'Escape', 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown'];
|
|
1200
|
+
canvas.addEventListener('keydown', (e) => {
|
|
1201
|
+
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
|
1202
|
+
if (NAMED.includes(e.key)) { e.preventDefault(); input({ t: 'key', key: e.key }); }
|
|
1203
|
+
else if (e.key.length === 1) { e.preventDefault(); input({ t: 'text', s: e.key }); }
|
|
1204
|
+
});
|
|
1205
|
+
|
|
1206
|
+
// \u2500\u2500 the bar \u2500\u2500
|
|
1207
|
+
if (!WATCH) {
|
|
1208
|
+
for (const id of ['mode', 'done']) $(id).addEventListener('pointerdown', (e) => e.preventDefault());
|
|
1209
|
+
$('mode').onclick = () => {
|
|
1210
|
+
mode = mode === 'touch' ? 'mouse' : 'touch'; T.mode = mode;
|
|
1211
|
+
try { localStorage.setItem('clikcode-handoff-mode', mode); } catch (error) { /* private browsing */ }
|
|
1212
|
+
showMode();
|
|
1213
|
+
if (m) clearTimeout(m.timer);
|
|
1214
|
+
g = null; m = null; two = null; down = null;
|
|
1215
|
+
lastSize = ''; sendSize(true);
|
|
1216
|
+
};
|
|
1217
|
+
$('done').onclick = () => { send({ t: 'done' }); veil('Finishing\u2026'); };
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
connect();
|
|
1221
|
+
})();
|
|
1222
|
+
</script></html>`;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
// src/agent/computer/ws-lite.ts
|
|
1226
|
+
import { createHash } from "node:crypto";
|
|
1227
|
+
var GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
1228
|
+
var MAX_MESSAGE = 64 * 1024;
|
|
1229
|
+
function acceptKey(key) {
|
|
1230
|
+
return createHash("sha1").update(key + GUID).digest("base64");
|
|
1231
|
+
}
|
|
1232
|
+
function encodeFrame(opcode, payload) {
|
|
1233
|
+
const length = payload.length;
|
|
1234
|
+
const head = length < 126 ? Buffer.alloc(2) : length < 65536 ? Buffer.alloc(4) : Buffer.alloc(10);
|
|
1235
|
+
head[0] = 128 | opcode;
|
|
1236
|
+
if (length < 126) head[1] = length;
|
|
1237
|
+
else if (length < 65536) {
|
|
1238
|
+
head[1] = 126;
|
|
1239
|
+
head.writeUInt16BE(length, 2);
|
|
1240
|
+
} else {
|
|
1241
|
+
head[1] = 127;
|
|
1242
|
+
head.writeBigUInt64BE(BigInt(length), 2);
|
|
1243
|
+
}
|
|
1244
|
+
return Buffer.concat([head, payload]);
|
|
1245
|
+
}
|
|
1246
|
+
var FrameParser = class {
|
|
1247
|
+
constructor(maxPayload = MAX_MESSAGE) {
|
|
1248
|
+
this.maxPayload = maxPayload;
|
|
1249
|
+
}
|
|
1250
|
+
maxPayload;
|
|
1251
|
+
pending = Buffer.alloc(0);
|
|
1252
|
+
push(chunk) {
|
|
1253
|
+
this.pending = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;
|
|
1254
|
+
const frames = [];
|
|
1255
|
+
for (; ; ) {
|
|
1256
|
+
const buffer = this.pending;
|
|
1257
|
+
if (buffer.length < 2) break;
|
|
1258
|
+
const first = buffer[0], second = buffer[1];
|
|
1259
|
+
if (first & 112) throw new Error("reserved bits set");
|
|
1260
|
+
if (!(second & 128)) throw new Error("client frame not masked");
|
|
1261
|
+
let length = second & 127;
|
|
1262
|
+
let offset = 2;
|
|
1263
|
+
if (length === 126) {
|
|
1264
|
+
if (buffer.length < 4) break;
|
|
1265
|
+
length = buffer.readUInt16BE(2);
|
|
1266
|
+
offset = 4;
|
|
1267
|
+
} else if (length === 127) {
|
|
1268
|
+
if (buffer.length < 10) break;
|
|
1269
|
+
const big = buffer.readBigUInt64BE(2);
|
|
1270
|
+
if (big > BigInt(this.maxPayload)) throw new Error("message too large");
|
|
1271
|
+
length = Number(big);
|
|
1272
|
+
offset = 10;
|
|
1273
|
+
}
|
|
1274
|
+
if (length > this.maxPayload) throw new Error("message too large");
|
|
1275
|
+
if (buffer.length < offset + 4 + length) break;
|
|
1276
|
+
const mask = buffer.subarray(offset, offset + 4);
|
|
1277
|
+
const payload = Buffer.from(buffer.subarray(offset + 4, offset + 4 + length));
|
|
1278
|
+
for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
|
|
1279
|
+
frames.push({ fin: Boolean(first & 128), opcode: first & 15, payload });
|
|
1280
|
+
this.pending = buffer.subarray(offset + 4 + length);
|
|
1281
|
+
}
|
|
1282
|
+
return frames;
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
function acceptWebSocket(request, socket, head, options = {}) {
|
|
1286
|
+
const key = request.headers["sec-websocket-key"];
|
|
1287
|
+
const upgrade = String(request.headers.upgrade ?? "").toLowerCase();
|
|
1288
|
+
const version = request.headers["sec-websocket-version"];
|
|
1289
|
+
const refuse = () => {
|
|
1290
|
+
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
|
|
1291
|
+
return void 0;
|
|
1292
|
+
};
|
|
1293
|
+
if (upgrade !== "websocket" || typeof key !== "string" || version !== "13") return refuse();
|
|
1294
|
+
if (options.allowOrigin && !options.allowOrigin(request.headers.origin)) return refuse();
|
|
1295
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r
|
|
1296
|
+
Upgrade: websocket\r
|
|
1297
|
+
Connection: Upgrade\r
|
|
1298
|
+
Sec-WebSocket-Accept: ${acceptKey(key)}\r
|
|
1299
|
+
\r
|
|
1300
|
+
`);
|
|
1301
|
+
const parser = new FrameParser(options.maxPayload);
|
|
1302
|
+
const messageHandlers = [];
|
|
1303
|
+
const closeHandlers = [];
|
|
1304
|
+
let closed = false;
|
|
1305
|
+
const backlog = [];
|
|
1306
|
+
let fragments = [];
|
|
1307
|
+
let fragmentOpcode = 0;
|
|
1308
|
+
let fragmentBytes = 0;
|
|
1309
|
+
const finish = () => {
|
|
1310
|
+
if (closed) return;
|
|
1311
|
+
closed = true;
|
|
1312
|
+
for (const handler of closeHandlers) handler();
|
|
1313
|
+
socket.destroy();
|
|
1314
|
+
};
|
|
1315
|
+
const write = (opcode, payload) => {
|
|
1316
|
+
if (!closed && socket.writable) socket.write(encodeFrame(opcode, payload));
|
|
1317
|
+
};
|
|
1318
|
+
const close = (code = 1e3) => {
|
|
1319
|
+
if (closed) return;
|
|
1320
|
+
const reason = Buffer.alloc(2);
|
|
1321
|
+
reason.writeUInt16BE(code);
|
|
1322
|
+
write(8, reason);
|
|
1323
|
+
finish();
|
|
1324
|
+
};
|
|
1325
|
+
const handle = (frame) => {
|
|
1326
|
+
switch (frame.opcode) {
|
|
1327
|
+
case 8:
|
|
1328
|
+
close();
|
|
1329
|
+
return;
|
|
1330
|
+
case 9:
|
|
1331
|
+
write(10, frame.payload);
|
|
1332
|
+
return;
|
|
1333
|
+
case 10:
|
|
1334
|
+
return;
|
|
1335
|
+
case 0:
|
|
1336
|
+
case 1:
|
|
1337
|
+
case 2: {
|
|
1338
|
+
if (frame.opcode !== 0) {
|
|
1339
|
+
fragments = [];
|
|
1340
|
+
fragmentBytes = 0;
|
|
1341
|
+
fragmentOpcode = frame.opcode;
|
|
1342
|
+
} else if (!fragmentOpcode) throw new Error("unexpected continuation");
|
|
1343
|
+
fragments.push(frame.payload);
|
|
1344
|
+
fragmentBytes += frame.payload.length;
|
|
1345
|
+
if (fragmentBytes > (options.maxPayload ?? MAX_MESSAGE)) throw new Error("message too large");
|
|
1346
|
+
if (!frame.fin) return;
|
|
1347
|
+
const data = Buffer.concat(fragments);
|
|
1348
|
+
const binary = fragmentOpcode === 2;
|
|
1349
|
+
fragments = [];
|
|
1350
|
+
fragmentBytes = 0;
|
|
1351
|
+
fragmentOpcode = 0;
|
|
1352
|
+
const value = binary ? data : data.toString("utf8");
|
|
1353
|
+
if (!messageHandlers.length) {
|
|
1354
|
+
if (backlog.length < 100) backlog.push([value, binary]);
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
for (const handler of messageHandlers) handler(value, binary);
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
default:
|
|
1361
|
+
throw new Error("unknown opcode");
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
const onData = (chunk) => {
|
|
1365
|
+
try {
|
|
1366
|
+
for (const frame of parser.push(chunk)) handle(frame);
|
|
1367
|
+
} catch {
|
|
1368
|
+
close(1002);
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
socket.on("data", onData);
|
|
1372
|
+
socket.on("close", finish);
|
|
1373
|
+
socket.on("error", finish);
|
|
1374
|
+
socket.setNoDelay?.(true);
|
|
1375
|
+
if (head.length) onData(head);
|
|
1376
|
+
return {
|
|
1377
|
+
send: (data) => write(typeof data === "string" ? 1 : 2, typeof data === "string" ? Buffer.from(data, "utf8") : data),
|
|
1378
|
+
close,
|
|
1379
|
+
get buffered() {
|
|
1380
|
+
return socket.writableLength;
|
|
1381
|
+
},
|
|
1382
|
+
get closed() {
|
|
1383
|
+
return closed;
|
|
1384
|
+
},
|
|
1385
|
+
onMessage: (handler) => {
|
|
1386
|
+
messageHandlers.push(handler);
|
|
1387
|
+
for (const [value, binary] of backlog.splice(0)) handler(value, binary);
|
|
1388
|
+
},
|
|
1389
|
+
onClose: (handler) => {
|
|
1390
|
+
closeHandlers.push(handler);
|
|
1391
|
+
}
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// src/agent/computer/handoff-desk.ts
|
|
1396
|
+
var DESK_PORT = 47811;
|
|
1397
|
+
var TIDY_EVERY_MS = 6e4;
|
|
1398
|
+
function sameToken(a, b) {
|
|
1399
|
+
return a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
1400
|
+
}
|
|
1401
|
+
function sameOrigin(origin, host) {
|
|
1402
|
+
if (origin === void 0) return true;
|
|
1403
|
+
try {
|
|
1404
|
+
return new URL(origin).host === host;
|
|
1405
|
+
} catch {
|
|
1406
|
+
return false;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
async function targetId(context, page) {
|
|
1410
|
+
const session = await context.newCDPSession(page);
|
|
1411
|
+
try {
|
|
1412
|
+
return (await session.send("Target.getTargetInfo")).targetInfo.targetId;
|
|
1413
|
+
} catch {
|
|
1414
|
+
return void 0;
|
|
1415
|
+
} finally {
|
|
1416
|
+
await session.detach().catch(quiet("agent/computer/handoff-desk"));
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
async function pagesById(context) {
|
|
1420
|
+
const map = /* @__PURE__ */ new Map();
|
|
1421
|
+
for (const page of context.pages()) {
|
|
1422
|
+
if (page.isClosed()) continue;
|
|
1423
|
+
const id = await targetId(context, page);
|
|
1424
|
+
if (id) map.set(id, page);
|
|
1425
|
+
}
|
|
1426
|
+
return map;
|
|
1427
|
+
}
|
|
1428
|
+
var KIND_SAYS = { captcha: "Human check", code: "Code", "sign-in": "Sign-in", other: "Browser step" };
|
|
1429
|
+
function deskListing(items, now) {
|
|
1430
|
+
return items.filter((item) => item.status === "waiting").map((item) => ({
|
|
1431
|
+
id: item.id,
|
|
1432
|
+
label: item.label,
|
|
1433
|
+
kind: KIND_SAYS[item.kind],
|
|
1434
|
+
...item.note ? { note: item.note } : {},
|
|
1435
|
+
...item.host ? { host: item.host } : {},
|
|
1436
|
+
minutes: Math.max(0, Math.round((now - item.createdAt) / 6e4))
|
|
1437
|
+
}));
|
|
1438
|
+
}
|
|
1439
|
+
function deskListPage() {
|
|
1440
|
+
return `<!doctype html><html lang="en"><meta charset="utf-8">
|
|
1441
|
+
<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><meta name="theme-color" content="#161b22">
|
|
1442
|
+
<title>ClikCode desk</title>
|
|
1443
|
+
<style>
|
|
1444
|
+
html,body{margin:0;background:#0d1117;color:#f2f5f8;font:16px system-ui,-apple-system,sans-serif}
|
|
1445
|
+
main{max-width:560px;margin:0 auto;padding:18px 14px 40px}
|
|
1446
|
+
h1{font-size:18px;margin:6px 0 2px}#sub{color:#8b949e;font-size:14px;margin-bottom:14px}
|
|
1447
|
+
a.item{display:block;text-decoration:none;color:inherit;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:14px;margin:10px 0}
|
|
1448
|
+
a.item:active{background:#21262d}
|
|
1449
|
+
.top{display:flex;justify-content:space-between;gap:10px;align-items:baseline}
|
|
1450
|
+
.label{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
1451
|
+
.kind{flex:none;font-size:12px;color:#0d1117;background:#d29922;border-radius:999px;padding:2px 9px}
|
|
1452
|
+
.note{color:#c9d1d9;font-size:14px;margin-top:6px}.meta{color:#8b949e;font-size:13px;margin-top:6px}
|
|
1453
|
+
#empty{color:#8b949e;padding:30px 0;text-align:center}
|
|
1454
|
+
</style>
|
|
1455
|
+
<main><h1>Waiting on you</h1><div id="sub">Checking\u2026</div><div id="list"></div><div id="empty" hidden>Nothing is waiting. This page updates by itself.</div></main>
|
|
1456
|
+
<script>
|
|
1457
|
+
(() => {
|
|
1458
|
+
const base = location.pathname.replace(/\\/$/, '');
|
|
1459
|
+
const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; };
|
|
1460
|
+
let last = '';
|
|
1461
|
+
const draw = (items) => {
|
|
1462
|
+
const key = JSON.stringify(items);
|
|
1463
|
+
document.title = items.length ? '(' + items.length + ') ClikCode desk' : 'ClikCode desk';
|
|
1464
|
+
document.getElementById('sub').textContent = items.length ? items.length + (items.length === 1 ? ' tab is' : ' tabs are') + ' waiting. Tap one, finish it, tap Done.' : 'All clear.';
|
|
1465
|
+
document.getElementById('empty').hidden = items.length > 0;
|
|
1466
|
+
if (key === last) return;
|
|
1467
|
+
last = key;
|
|
1468
|
+
const list = document.getElementById('list');
|
|
1469
|
+
list.textContent = '';
|
|
1470
|
+
for (const item of items) {
|
|
1471
|
+
const a = el('a', 'item'); a.href = base + '/t/' + encodeURIComponent(item.id) + '/';
|
|
1472
|
+
const top = el('div', 'top'); top.append(el('span', 'label', item.label), el('span', 'kind', item.kind)); a.append(top);
|
|
1473
|
+
if (item.note) a.append(el('div', 'note', item.note));
|
|
1474
|
+
a.append(el('div', 'meta', (item.host ? item.host + ' \xB7 ' : '') + (item.minutes < 1 ? 'just now' : item.minutes + ' min')));
|
|
1475
|
+
list.append(a);
|
|
1476
|
+
}
|
|
1477
|
+
};
|
|
1478
|
+
const load = async () => {
|
|
1479
|
+
try { const r = await fetch(base + '/items', { cache: 'no-store' }); if (r.ok) draw(await r.json()); }
|
|
1480
|
+
catch (error) { document.getElementById('sub').textContent = 'Cannot reach this computer. Retrying\u2026'; }
|
|
1481
|
+
};
|
|
1482
|
+
load(); setInterval(load, 4000);
|
|
1483
|
+
document.addEventListener('visibilitychange', () => { if (!document.hidden) load(); });
|
|
1484
|
+
})();
|
|
1485
|
+
</script></html>`;
|
|
1486
|
+
}
|
|
1487
|
+
async function startHandoffDesk(deps) {
|
|
1488
|
+
const { stateDir, context } = deps;
|
|
1489
|
+
const now = deps.now ?? Date.now;
|
|
1490
|
+
let token = await deskToken(stateDir, { now: now() });
|
|
1491
|
+
const views = /* @__PURE__ */ new Map();
|
|
1492
|
+
const route = (request) => {
|
|
1493
|
+
const [, first, rest] = /^\/([^/?]+)(\/[^?]*)?/.exec(request.url ?? "/") ?? [];
|
|
1494
|
+
return { ok: Boolean(first) && sameToken(first, token), rest: rest ?? "/" };
|
|
1495
|
+
};
|
|
1496
|
+
const waiting = async (id) => (await listDeskItems(stateDir)).find((item) => item.id === id);
|
|
1497
|
+
const server = createServer((request, response) => {
|
|
1498
|
+
void (async () => {
|
|
1499
|
+
const { ok, rest } = route(request);
|
|
1500
|
+
if (!ok || request.method !== "GET") {
|
|
1501
|
+
response.writeHead(404).end();
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
response.setHeader("cache-control", "no-store");
|
|
1505
|
+
const host = request.headers.host ?? "";
|
|
1506
|
+
const socketOrigin = /^[\w.:[\]-]{1,80}$/.test(host) ? ` ws://${host}` : "";
|
|
1507
|
+
const csp = `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src blob: data:; connect-src 'self'${socketOrigin}`;
|
|
1508
|
+
if (rest === "/") {
|
|
1509
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-security-policy": csp }).end(deskListPage());
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
if (rest === "/items") {
|
|
1513
|
+
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(deskListing(await listDeskItems(stateDir), now())));
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
const tab = /^\/t\/([A-Za-z0-9_-]{6,40})(\/ping|\/)?$/.exec(rest);
|
|
1517
|
+
if (tab) {
|
|
1518
|
+
const item = await waiting(tab[1]);
|
|
1519
|
+
if (!item || item.status !== "waiting") {
|
|
1520
|
+
response.writeHead(410, { "content-type": "text/plain; charset=utf-8" }).end("This step is finished.");
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
if (tab[2] === "/ping") {
|
|
1524
|
+
response.writeHead(204).end();
|
|
1525
|
+
return;
|
|
1526
|
+
}
|
|
1527
|
+
if (tab[2] === void 0) {
|
|
1528
|
+
response.writeHead(302, { location: `/${token}/t/${item.id}/` }).end();
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-security-policy": csp }).end(handoffPage({ back: `/${token}/` }));
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1534
|
+
response.writeHead(404).end();
|
|
1535
|
+
})().catch((error) => {
|
|
1536
|
+
quiet("agent/computer/handoff-desk")(error);
|
|
1537
|
+
if (!response.headersSent) response.writeHead(500);
|
|
1538
|
+
response.end();
|
|
1539
|
+
});
|
|
1540
|
+
});
|
|
1541
|
+
server.on("upgrade", (request, socket, head) => {
|
|
1542
|
+
const { ok, rest } = route(request);
|
|
1543
|
+
const tab = /^\/t\/([A-Za-z0-9_-]{6,40})\/live$/.exec(rest);
|
|
1544
|
+
if (!ok || !tab) {
|
|
1545
|
+
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
const id = tab[1];
|
|
1549
|
+
void (async () => {
|
|
1550
|
+
const item = await waiting(id);
|
|
1551
|
+
if (!item || item.status !== "waiting") {
|
|
1552
|
+
socket.end("HTTP/1.1 410 Gone\r\nConnection: close\r\n\r\n");
|
|
1553
|
+
return;
|
|
1554
|
+
}
|
|
1555
|
+
const page = (await pagesById(context)).get(item.targetId);
|
|
1556
|
+
if (!page) {
|
|
1557
|
+
await finishDeskItem(stateDir, id, "closed", now());
|
|
1558
|
+
socket.end("HTTP/1.1 410 Gone\r\nConnection: close\r\n\r\n");
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
const accepted = acceptWebSocket(request, socket, head, { allowOrigin: (origin) => sameOrigin(origin, request.headers.host) });
|
|
1562
|
+
if (!accepted) return;
|
|
1563
|
+
const before = views.get(id);
|
|
1564
|
+
views.delete(id);
|
|
1565
|
+
before?.socket.close(1e3);
|
|
1566
|
+
await before?.view.stop();
|
|
1567
|
+
const view = new LiveView(page, accepted, () => {
|
|
1568
|
+
void finishDeskItem(stateDir, id, "done", now()).then(() => lifecycle("handoff.desk.done", { id, label: item.label, kind: item.kind, waitedMs: now() - item.createdAt })).catch(quiet("agent/computer/handoff-desk"));
|
|
1569
|
+
if (!accepted.closed) accepted.send(JSON.stringify({ t: "done" }));
|
|
1570
|
+
const mine2 = views.get(id);
|
|
1571
|
+
views.delete(id);
|
|
1572
|
+
setTimeout(() => {
|
|
1573
|
+
accepted.close(1e3);
|
|
1574
|
+
void mine2?.view.stop();
|
|
1575
|
+
}, 80);
|
|
1576
|
+
});
|
|
1577
|
+
views.set(id, { socket: accepted, view });
|
|
1578
|
+
accepted.onClose(() => {
|
|
1579
|
+
if (views.get(id)?.socket === accepted) views.delete(id);
|
|
1580
|
+
});
|
|
1581
|
+
await view.start();
|
|
1582
|
+
})().catch((error) => {
|
|
1583
|
+
quiet("agent/computer/handoff-desk")(error);
|
|
1584
|
+
socket.destroy();
|
|
1585
|
+
});
|
|
1586
|
+
});
|
|
1587
|
+
const listen = (port2) => new Promise((resolve) => {
|
|
1588
|
+
const failed = () => {
|
|
1589
|
+
resolve(false);
|
|
1590
|
+
};
|
|
1591
|
+
server.once("error", failed);
|
|
1592
|
+
server.listen(port2, deps.host, () => {
|
|
1593
|
+
server.off("error", failed);
|
|
1594
|
+
resolve(true);
|
|
1595
|
+
});
|
|
1596
|
+
});
|
|
1597
|
+
let up = false;
|
|
1598
|
+
for (const port2 of deps.port !== void 0 ? [deps.port] : [DESK_PORT, DESK_PORT + 1, DESK_PORT + 2, 0]) if (await listen(port2)) {
|
|
1599
|
+
up = true;
|
|
1600
|
+
break;
|
|
1601
|
+
}
|
|
1602
|
+
if (!up) return void 0;
|
|
1603
|
+
const port = server.address().port;
|
|
1604
|
+
await writeDeskInfo(stateDir, { pid: process.pid, host: deps.host, port, token });
|
|
1605
|
+
const rotate = async () => {
|
|
1606
|
+
const fresh = await deskToken(stateDir, { now: now() });
|
|
1607
|
+
if (fresh === token) return;
|
|
1608
|
+
token = fresh;
|
|
1609
|
+
for (const { socket, view } of views.values()) {
|
|
1610
|
+
socket.close(1001);
|
|
1611
|
+
await view.stop().catch(quiet("agent/computer/handoff-desk"));
|
|
1612
|
+
}
|
|
1613
|
+
views.clear();
|
|
1614
|
+
await writeDeskInfo(stateDir, { pid: process.pid, host: deps.host, port, token });
|
|
1615
|
+
lifecycle("handoff.desk.token-rotated", { host: deps.host, port });
|
|
1616
|
+
};
|
|
1617
|
+
const tidy = async () => {
|
|
1618
|
+
await rotate();
|
|
1619
|
+
await tidyDesk(stateDir, new Set((await pagesById(context)).keys()), now());
|
|
1620
|
+
};
|
|
1621
|
+
const timer = setInterval(() => {
|
|
1622
|
+
void tidy().catch(quiet("agent/computer/handoff-desk"));
|
|
1623
|
+
}, TIDY_EVERY_MS);
|
|
1624
|
+
timer.unref();
|
|
1625
|
+
lifecycle("handoff.desk.up", { host: deps.host, port });
|
|
1626
|
+
return {
|
|
1627
|
+
get address() {
|
|
1628
|
+
return `http://${deps.host}:${port}/${token}/`;
|
|
1629
|
+
},
|
|
1630
|
+
async stop() {
|
|
1631
|
+
clearInterval(timer);
|
|
1632
|
+
for (const { socket, view } of views.values()) {
|
|
1633
|
+
socket.close(1001);
|
|
1634
|
+
await view.stop().catch(quiet("agent/computer/handoff-desk"));
|
|
1635
|
+
}
|
|
1636
|
+
views.clear();
|
|
1637
|
+
await clearDeskInfo(stateDir, process.pid);
|
|
1638
|
+
server.close();
|
|
1639
|
+
server.closeAllConnections();
|
|
1640
|
+
}
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
// src/agent/computer/tailnet-handoff.ts
|
|
1645
|
+
import { networkInterfaces } from "node:os";
|
|
1646
|
+
|
|
1647
|
+
// src/agent/computer/browser.ts
|
|
1648
|
+
import { accessSync, constants as fsConstants2, existsSync } from "node:fs";
|
|
1649
|
+
import fs4 from "node:fs/promises";
|
|
1650
|
+
import path4 from "node:path";
|
|
1651
|
+
import { spawn } from "node:child_process";
|
|
1652
|
+
|
|
1653
|
+
// src/agent/computer/browser-host-scope.ts
|
|
1654
|
+
var BROWSER_HOST_UNIT = "clikcode-browser-host";
|
|
1655
|
+
var SIZE = /^(?:\d+(?:\.\d+)?[KMGT]?|infinity)$/i;
|
|
1656
|
+
var setting = (value, fallback) => value && SIZE.test(value.trim()) ? value.trim() : fallback;
|
|
1657
|
+
function browserHostLimits(env = process.env) {
|
|
1658
|
+
const percent = Number(env.CLIKCODE_BROWSER_CPU_PERCENT);
|
|
1659
|
+
return {
|
|
1660
|
+
memoryHigh: setting(env.CLIKCODE_BROWSER_MEMORY_HIGH, "8G"),
|
|
1661
|
+
memoryMax: setting(env.CLIKCODE_BROWSER_MEMORY_MAX, "10G"),
|
|
1662
|
+
tasksMax: setting(env.CLIKCODE_BROWSER_TASKS_MAX, "16384"),
|
|
1663
|
+
cpuQuota: `${Number.isFinite(percent) && percent > 0 ? Math.floor(percent) : 400}%`
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
function browserHostLaunch(hostArgv, context, limits = browserHostLimits(context.env)) {
|
|
1667
|
+
if (context.platform !== "linux" || context.env.CLIKCODE_OWN_SCOPE === "0" || !context.cgroup) return void 0;
|
|
1668
|
+
const runtime = context.env.XDG_RUNTIME_DIR || `/run/user/${context.uid}`;
|
|
1669
|
+
if (!context.busExists(`${runtime}/bus`)) return void 0;
|
|
1670
|
+
const scope = userManagerOwns(context.cgroup);
|
|
1671
|
+
const limitArgs = ["-p", `MemoryHigh=${limits.memoryHigh}`, "-p", `MemoryMax=${limits.memoryMax}`, "-p", `TasksMax=${limits.tasksMax}`, "-p", `CPUQuota=${limits.cpuQuota}`, "-p", "OOMPolicy=continue"];
|
|
1672
|
+
const setenv = scope ? [] : Object.entries(context.env).filter((entry) => typeof entry[1] === "string" && !entry[1].includes("\0")).map(([key, value]) => `--setenv=${key}=${value}`);
|
|
1673
|
+
return {
|
|
1674
|
+
argv: [
|
|
1675
|
+
"systemd-run",
|
|
1676
|
+
"--user",
|
|
1677
|
+
"--quiet",
|
|
1678
|
+
"--collect",
|
|
1679
|
+
...scope ? ["--scope"] : [`--working-directory=${context.cwd}`, "-p", "StandardOutput=null", "-p", "StandardError=null"],
|
|
1680
|
+
`--unit=${BROWSER_HOST_UNIT}`,
|
|
1681
|
+
`--slice=${AGENT_SLICE}`,
|
|
1682
|
+
...limitArgs,
|
|
1683
|
+
...setenv,
|
|
1684
|
+
"--",
|
|
1685
|
+
...hostArgv
|
|
1686
|
+
],
|
|
1687
|
+
env: { ...context.env, XDG_RUNTIME_DIR: runtime },
|
|
1688
|
+
detachesAtOnce: !scope
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
// src/agent/computer/downloads.ts
|
|
1693
|
+
import { constants as fsConstants } from "node:fs";
|
|
1694
|
+
import fs2 from "node:fs/promises";
|
|
1695
|
+
import path2 from "node:path";
|
|
1696
|
+
var tabs2 = sharedState("page-downloads", () => /* @__PURE__ */ new WeakMap());
|
|
1697
|
+
var capturing = sharedState("page-download-capture", () => /* @__PURE__ */ new WeakMap());
|
|
1698
|
+
function holdDownloads(page, on) {
|
|
1699
|
+
capturing.set(page, Math.max(0, (capturing.get(page) ?? 0) + (on ? 1 : -1)));
|
|
1700
|
+
}
|
|
1701
|
+
var RESERVED = /^(?:con|prn|aux|nul|com\d|lpt\d)(?:\..*)?$/i;
|
|
1702
|
+
var MAX_NAME = 120;
|
|
1703
|
+
function safeFileName(suggested) {
|
|
1704
|
+
let name = suggested.replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, "_").replace(/^\.+/, "_").replace(/[. ]+$/, "").trim();
|
|
1705
|
+
if (!name) name = "download";
|
|
1706
|
+
if (RESERVED.test(name)) name = `_${name}`;
|
|
1707
|
+
if (name.length > MAX_NAME) {
|
|
1708
|
+
const ext = path2.extname(name).slice(0, 12);
|
|
1709
|
+
name = name.slice(0, MAX_NAME - ext.length) + ext;
|
|
1710
|
+
}
|
|
1711
|
+
return name;
|
|
1712
|
+
}
|
|
1713
|
+
var chatFolder = (chat) => chat.replace(/[^A-Za-z0-9._-]/g, "_").replace(/^\.+/, "_").slice(0, 80) || "chat";
|
|
1714
|
+
function downloadsRoot(stateDir) {
|
|
1715
|
+
return path2.join(stateDir, "computer", "downloads");
|
|
1716
|
+
}
|
|
1717
|
+
function downloadsDir(stateDir, chat) {
|
|
1718
|
+
return path2.join(downloadsRoot(stateDir), chatFolder(chat || "chat"));
|
|
1719
|
+
}
|
|
1720
|
+
async function freeName(dir, name) {
|
|
1721
|
+
const ext = path2.extname(name);
|
|
1722
|
+
const stem = name.slice(0, name.length - ext.length);
|
|
1723
|
+
for (let n = 0; n < 1e3; n++) {
|
|
1724
|
+
const candidate = path2.join(dir, n === 0 ? name : `${stem} (${n})${ext}`);
|
|
1725
|
+
try {
|
|
1726
|
+
await fs2.access(candidate);
|
|
1727
|
+
} catch {
|
|
1728
|
+
return candidate;
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
return path2.join(dir, `${stem}-${Date.now()}${ext}`);
|
|
1732
|
+
}
|
|
1733
|
+
function downloadsInbox(stateDir) {
|
|
1734
|
+
return path2.join(downloadsRoot(stateDir), ".incoming");
|
|
1735
|
+
}
|
|
1736
|
+
var desks = sharedState("browser-download-desks", () => /* @__PURE__ */ new WeakMap());
|
|
1737
|
+
var MAX_REMEMBERED = 300;
|
|
1738
|
+
var INBOX_KEEP_MS = 24 * 60 * 6e4;
|
|
1739
|
+
async function sweepInbox(inbox, now = Date.now()) {
|
|
1740
|
+
for (const name of await fs2.readdir(inbox).catch(() => [])) {
|
|
1741
|
+
const file = path2.join(inbox, name);
|
|
1742
|
+
const info = await fs2.stat(file).catch(quiet("agent/computer/downloads"));
|
|
1743
|
+
if (info?.isFile() && now - info.mtimeMs > INBOX_KEEP_MS) await fs2.unlink(file).catch(quiet("agent/computer/downloads"));
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
async function serveDownloads(browser, stateDir) {
|
|
1747
|
+
if (desks.has(browser)) return;
|
|
1748
|
+
const inbox = downloadsInbox(stateDir);
|
|
1749
|
+
await fs2.mkdir(inbox, { recursive: true, mode: 448 });
|
|
1750
|
+
const session = await browser.newBrowserCDPSession();
|
|
1751
|
+
const finished = /* @__PURE__ */ new Map();
|
|
1752
|
+
session.on("Browser.downloadProgress", (event) => {
|
|
1753
|
+
if (event.state === "inProgress") return;
|
|
1754
|
+
const { filePath } = event;
|
|
1755
|
+
finished.set(event.guid, { state: event.state, ...filePath ? { filePath } : {}, receivedBytes: event.receivedBytes });
|
|
1756
|
+
while (finished.size > MAX_REMEMBERED) finished.delete(finished.keys().next().value);
|
|
1757
|
+
});
|
|
1758
|
+
const desk = { inbox, finished, assert: async () => {
|
|
1759
|
+
await session.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: inbox, eventsEnabled: true });
|
|
1760
|
+
} };
|
|
1761
|
+
desks.set(browser, desk);
|
|
1762
|
+
await desk.assert();
|
|
1763
|
+
void sweepInbox(inbox).catch(quiet("agent/computer/downloads"));
|
|
1764
|
+
}
|
|
1765
|
+
var deskOf = (page) => {
|
|
1766
|
+
const browser = page.context().browser();
|
|
1767
|
+
return browser ? desks.get(browser) : void 0;
|
|
1768
|
+
};
|
|
1769
|
+
function downloadSource(inbox, guid, reported) {
|
|
1770
|
+
return reported || path2.join(inbox, guid);
|
|
1771
|
+
}
|
|
1772
|
+
var plainReason = (error) => (error instanceof Error ? error.message : String(error)).split("\n")[0].replace(/^download\.\w+:\s*/, "");
|
|
1773
|
+
async function arrivedDownload(page, download) {
|
|
1774
|
+
let named;
|
|
1775
|
+
try {
|
|
1776
|
+
named = await download.path();
|
|
1777
|
+
} catch (error) {
|
|
1778
|
+
throw new Error(`the browser did not finish it (${plainReason(error)})`);
|
|
1779
|
+
}
|
|
1780
|
+
const desk = deskOf(page);
|
|
1781
|
+
if (!desk) return { file: named };
|
|
1782
|
+
const guid = path2.basename(named);
|
|
1783
|
+
for (let waited = 0; waited < 3e3 && !desk.finished.has(guid); waited += 50) await sleep(50);
|
|
1784
|
+
const report = desk.finished.get(guid);
|
|
1785
|
+
desk.finished.delete(guid);
|
|
1786
|
+
return { file: downloadSource(desk.inbox, guid, report?.filePath), ...report?.receivedBytes ? { bytes: report.receivedBytes } : {} };
|
|
1787
|
+
}
|
|
1788
|
+
async function placeFile(source, dir, name) {
|
|
1789
|
+
const ext = path2.extname(name);
|
|
1790
|
+
const stem = name.slice(0, name.length - ext.length);
|
|
1791
|
+
for (let n = 0; n < 1e3; n++) {
|
|
1792
|
+
const target = path2.join(dir, n === 0 ? name : `${stem} (${n})${ext}`);
|
|
1793
|
+
try {
|
|
1794
|
+
await fs2.link(source, target);
|
|
1795
|
+
} catch (error) {
|
|
1796
|
+
const code = error.code;
|
|
1797
|
+
if (code === "EEXIST") continue;
|
|
1798
|
+
try {
|
|
1799
|
+
await fs2.copyFile(source, target, fsConstants.COPYFILE_EXCL);
|
|
1800
|
+
} catch (copyError) {
|
|
1801
|
+
if (copyError.code === "EEXIST") continue;
|
|
1802
|
+
throw copyError;
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
await fs2.unlink(source).catch(quiet("agent/computer/downloads"));
|
|
1806
|
+
return target;
|
|
1807
|
+
}
|
|
1808
|
+
throw new Error(`no free name for ${name} in ${dir}`);
|
|
1809
|
+
}
|
|
1810
|
+
async function claimDownload(source, dir, name, expectedBytes) {
|
|
1811
|
+
const arrived2 = await fs2.stat(source).catch(() => void 0);
|
|
1812
|
+
if (!arrived2?.isFile()) throw new Error(`the browser reported it finished, but no file is at ${source}`);
|
|
1813
|
+
if (arrived2.size === 0) {
|
|
1814
|
+
await fs2.unlink(source).catch(quiet("agent/computer/downloads"));
|
|
1815
|
+
throw new Error("the file arrived empty (0 bytes)");
|
|
1816
|
+
}
|
|
1817
|
+
if (expectedBytes !== void 0 && arrived2.size !== expectedBytes) {
|
|
1818
|
+
await fs2.unlink(source).catch(quiet("agent/computer/downloads"));
|
|
1819
|
+
throw new Error(`the file is incomplete (${arrived2.size} of ${expectedBytes} bytes on disk)`);
|
|
1820
|
+
}
|
|
1821
|
+
await fs2.mkdir(dir, { recursive: true, mode: 448 });
|
|
1822
|
+
const target = await placeFile(source, dir, name);
|
|
1823
|
+
const saved = await fs2.stat(target).catch(() => void 0);
|
|
1824
|
+
if (!saved?.isFile() || saved.size !== arrived2.size) throw new Error(`moving it to ${target} failed (${saved ? `${saved.size} of ${arrived2.size} bytes` : "no file"} there)`);
|
|
1825
|
+
return { name: path2.basename(target), path: target, size: saved.size };
|
|
1826
|
+
}
|
|
1827
|
+
async function save(tab, page, download) {
|
|
1828
|
+
const name = safeFileName(download.suggestedFilename());
|
|
1829
|
+
try {
|
|
1830
|
+
const arrived2 = await arrivedDownload(page, download);
|
|
1831
|
+
tab.fresh.push(await claimDownload(arrived2.file, downloadsDir(tab.stateDir, tab.chat), name, arrived2.bytes));
|
|
1832
|
+
} catch (error) {
|
|
1833
|
+
tab.failed.push(`${name}: ${plainReason(error)}`);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
function watchDownloads(page, stateDir) {
|
|
1837
|
+
if (tabs2.has(page)) return;
|
|
1838
|
+
const tab = { stateDir, chat: "chat", inflight: /* @__PURE__ */ new Set(), fresh: [], failed: [] };
|
|
1839
|
+
tabs2.set(page, tab);
|
|
1840
|
+
page.on("download", (download) => {
|
|
1841
|
+
if (capturing.get(page)) return;
|
|
1842
|
+
const job = save(tab, page, download).finally(() => {
|
|
1843
|
+
tab.inflight.delete(job);
|
|
1844
|
+
});
|
|
1845
|
+
tab.inflight.add(job);
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
function bindDownloads(page, stateDir, chat) {
|
|
1849
|
+
watchDownloads(page, stateDir);
|
|
1850
|
+
const tab = tabs2.get(page);
|
|
1851
|
+
tab.stateDir = stateDir;
|
|
1852
|
+
tab.chat = chat || "chat";
|
|
1853
|
+
void deskOf(page)?.assert().catch(quiet("agent/computer/downloads"));
|
|
1854
|
+
}
|
|
1855
|
+
function sizeText(bytes) {
|
|
1856
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
1857
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
1858
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
1859
|
+
}
|
|
1860
|
+
var describeDownload = (file) => `${file.name} (${sizeText(file.size)}) at ${file.path}`;
|
|
1861
|
+
async function downloadNotes(page, waitMs = 3e4, expectStart = false) {
|
|
1862
|
+
const tab = tabs2.get(page);
|
|
1863
|
+
if (!tab) return [];
|
|
1864
|
+
for (let waited = 0; expectStart && waited < 3e3 && !tab.inflight.size && !tab.fresh.length && !tab.failed.length; waited += 100) await sleep(100);
|
|
1865
|
+
if (tab.inflight.size) await Promise.race([Promise.allSettled([...tab.inflight]), sleep(waitMs)]);
|
|
1866
|
+
const notes = [
|
|
1867
|
+
...tab.fresh.splice(0).map((file) => `Downloaded ${describeDownload(file)}.`),
|
|
1868
|
+
...tab.failed.splice(0).map((why) => `A download failed: ${why}.`)
|
|
1869
|
+
];
|
|
1870
|
+
if (tab.inflight.size) notes.push(`${tab.inflight.size} download${tab.inflight.size === 1 ? " is" : "s are"} still in progress; check with the downloads action.`);
|
|
1871
|
+
return notes;
|
|
1872
|
+
}
|
|
1873
|
+
async function listDownloads(stateDir, chat) {
|
|
1874
|
+
const dir = downloadsDir(stateDir, chat);
|
|
1875
|
+
let names;
|
|
1876
|
+
try {
|
|
1877
|
+
names = await fs2.readdir(dir);
|
|
1878
|
+
} catch {
|
|
1879
|
+
return [];
|
|
1880
|
+
}
|
|
1881
|
+
const files = [];
|
|
1882
|
+
for (const name of names) {
|
|
1883
|
+
try {
|
|
1884
|
+
const file = path2.join(dir, name);
|
|
1885
|
+
const info = await fs2.stat(file);
|
|
1886
|
+
if (info.isFile()) files.push({ name, path: file, size: info.size, modified: info.mtime.toISOString(), at: info.mtimeMs });
|
|
1887
|
+
} catch {
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
return files.sort((a, b) => b.at - a.at).map(({ at: _at, ...file }) => file);
|
|
1891
|
+
}
|
|
1892
|
+
async function describeDownloads(stateDir, chat) {
|
|
1893
|
+
const files = await listDownloads(stateDir, chat);
|
|
1894
|
+
const dir = downloadsDir(stateDir, chat);
|
|
1895
|
+
if (!files.length) return `No downloads yet. Files the browser downloads are saved in ${dir}.`;
|
|
1896
|
+
return `Downloads in ${dir}:
|
|
1897
|
+
${files.slice(0, 50).map((file) => `- ${file.name} (${sizeText(file.size)}, ${file.modified.slice(0, 19)}Z) ${file.path}`).join("\n")}${files.length > 50 ? `
|
|
1898
|
+
(\u2026 ${files.length - 50} older files)` : ""}`;
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
// src/agent/computer/sensitive-fields.ts
|
|
1902
|
+
var CARD_BOX = ["cardnumber", "card-number", "card_number", "ccnumber", "cc-number", "cc_number"].flatMap((word) => [`input[name*="${word}" i]`, `input[id*="${word}" i]`]).join(", ") + ", " + ["cvc", "cvv", "csc", "cvc2", "cvv2", "securitycode", "security-code", "security_code"].flatMap((word) => [`input[name="${word}" i]`, `input[id="${word}" i]`]).join(", ");
|
|
1903
|
+
var SENSITIVE = `input[type="password"], input[autocomplete="one-time-code"], input[autocomplete="current-password"], input[autocomplete="new-password"], input[autocomplete^="cc-"], input[autocomplete*=" cc-"], ${CARD_BOX}`;
|
|
1904
|
+
var MIN_LENGTH = 3;
|
|
1905
|
+
async function sensitiveValues(page) {
|
|
1906
|
+
const values = [];
|
|
1907
|
+
let frames = [];
|
|
1908
|
+
try {
|
|
1909
|
+
frames = page.frames();
|
|
1910
|
+
} catch {
|
|
1911
|
+
return [];
|
|
1912
|
+
}
|
|
1913
|
+
for (const frame of frames) {
|
|
1914
|
+
if (frame.isDetached()) continue;
|
|
1915
|
+
try {
|
|
1916
|
+
values.push(...await frame.locator(SENSITIVE).evaluateAll((nodes) => nodes.map((node) => node.value ?? "")));
|
|
1917
|
+
} catch {
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
return [...new Set(values.filter((value) => value.length >= MIN_LENGTH))];
|
|
1921
|
+
}
|
|
1922
|
+
function keyFieldValuesInPage() {
|
|
1923
|
+
const doc = globalThis.document;
|
|
1924
|
+
const NAMED = /(?:^|[^a-z])(?:api[ _-]?|access[ _-]?|auth[ _-]?|private[ _-]?|client[ _-]?|app[ _-]?)?(?:key|token|secret|credential)s?(?![a-z])/i;
|
|
1925
|
+
const SHAPED = (value) => {
|
|
1926
|
+
if (value.length < 12 || value.length > 600 || !/^[A-Za-z0-9_\-+/=.:~]+$/.test(value) || /^https?:|@/.test(value) || /^\d+$/.test(value)) return false;
|
|
1927
|
+
if (!/[A-Za-z]/.test(value) || !(/\d/.test(value) || value.length >= 20 && /[a-z]/.test(value) && /[A-Z]/.test(value))) return false;
|
|
1928
|
+
return new Set(value).size >= 6;
|
|
1929
|
+
};
|
|
1930
|
+
const out = /* @__PURE__ */ new Set();
|
|
1931
|
+
for (const element of Array.from(doc.querySelectorAll("input, textarea"))) {
|
|
1932
|
+
const type = String(element["type"] ?? "text").toLowerCase();
|
|
1933
|
+
if (["password", "hidden", "checkbox", "radio", "submit", "button", "file", "range", "color", "image", "reset"].includes(type)) continue;
|
|
1934
|
+
const value = String(element["value"] ?? "").trim();
|
|
1935
|
+
if (value.length < 8 || /\s/.test(value) && value.length < 20) continue;
|
|
1936
|
+
const labels = Array.from(element["labels"] ?? []).map((label) => label.textContent ?? "").join(" ");
|
|
1937
|
+
const get = (name) => String(element["getAttribute"].call(element, name) ?? "");
|
|
1938
|
+
const before = (() => {
|
|
1939
|
+
let text = "";
|
|
1940
|
+
let node = element;
|
|
1941
|
+
for (let step = 0; step < 3 && !text.trim(); step++) {
|
|
1942
|
+
text = node.previousSibling?.textContent ?? "";
|
|
1943
|
+
if (!text.trim() && node.parentElement) node = node.parentElement;
|
|
1944
|
+
}
|
|
1945
|
+
return text.trim().slice(-60);
|
|
1946
|
+
})();
|
|
1947
|
+
const hint = [labels, get("aria-label"), get("placeholder"), get("name"), get("id"), get("title"), before].join(" ");
|
|
1948
|
+
const nameBox = /\b(?:name|label|title|description|note|nickname|alias)\b/i.test(hint);
|
|
1949
|
+
const plainWord = /^[A-Za-z][A-Za-z._-]*$/.test(value) && value.length <= 14;
|
|
1950
|
+
if (SHAPED(value) || NAMED.test(hint) && !nameBox && !plainWord) out.add(value);
|
|
1951
|
+
}
|
|
1952
|
+
return [...out];
|
|
1953
|
+
}
|
|
1954
|
+
async function keyFieldValues(page) {
|
|
1955
|
+
try {
|
|
1956
|
+
return await page.evaluate(keyFieldValuesInPage);
|
|
1957
|
+
} catch {
|
|
1958
|
+
return [];
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
function pageSecretsInPage() {
|
|
1962
|
+
const doc = globalThis.document;
|
|
1963
|
+
const LABEL = /key|secret|token|password|passcode|credential|api/i;
|
|
1964
|
+
const norm = (text) => (text ?? "").replace(/\s+/g, " ").trim();
|
|
1965
|
+
const entropy = (text) => {
|
|
1966
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1967
|
+
for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
|
|
1968
|
+
let bits = 0;
|
|
1969
|
+
for (const n of counts.values()) {
|
|
1970
|
+
const p = n / text.length;
|
|
1971
|
+
bits -= p * Math.log2(p);
|
|
1972
|
+
}
|
|
1973
|
+
return bits;
|
|
1974
|
+
};
|
|
1975
|
+
const opaque = (value) => value.length >= 16 && value.length <= 8e3 && /^[A-Za-z0-9_\-+/=.:~]+$/.test(value) && /\d/.test(value) && /[A-Za-z]/.test(value) && entropy(value) >= 3 && !/^https?:|@/.test(value) && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value) && !/^[a-z][a-z-]*\/[\w-]+$/.test(value);
|
|
1976
|
+
const found = /* @__PURE__ */ new Map();
|
|
1977
|
+
const add = (label, raw, labelled) => {
|
|
1978
|
+
const value = norm(raw);
|
|
1979
|
+
if (value.length < 8 || value.length > 8e3 || /\s/.test(value) || /[•●*…]/.test(value) || /^https?:|@/.test(value) || /^\[secret/.test(value)) return;
|
|
1980
|
+
if (labelled && (/\d/.test(value) || value.length >= 20) || opaque(value)) {
|
|
1981
|
+
if (!found.has(value)) found.set(value, norm(label).slice(0, 80));
|
|
1982
|
+
}
|
|
1983
|
+
};
|
|
1984
|
+
for (const table of Array.from(doc.querySelectorAll("table"))) {
|
|
1985
|
+
const rows = Array.from(table.querySelectorAll("tr"));
|
|
1986
|
+
let headers = [];
|
|
1987
|
+
for (const row of rows) {
|
|
1988
|
+
const cells = Array.from(row.children);
|
|
1989
|
+
if (cells.length && cells.every((cell) => cell.tagName === "TH")) {
|
|
1990
|
+
headers = cells.map((cell) => norm(cell.textContent));
|
|
1991
|
+
continue;
|
|
1992
|
+
}
|
|
1993
|
+
cells.forEach((cell, at) => {
|
|
1994
|
+
if (cell.tagName === "TH") return;
|
|
1995
|
+
const candidates = [headers[at] ?? "", at > 0 ? norm(cells[0].textContent) : "", ...cells.filter((other) => other.tagName === "TH" && other !== cell).map((other) => norm(other.textContent))];
|
|
1996
|
+
const label = candidates.find((text) => LABEL.test(text) && text.length <= 60);
|
|
1997
|
+
if (label) {
|
|
1998
|
+
add(label, cell.textContent, true);
|
|
1999
|
+
for (const word of norm(cell.textContent).split(" ")) add(label, word, true);
|
|
2000
|
+
for (const input of Array.from(cell.querySelectorAll("input, textarea, code, pre, span, a"))) add(label, input.value ?? input.textContent, true);
|
|
2001
|
+
}
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
for (const term of Array.from(doc.querySelectorAll('dt, th[scope="row"], label, [class*="label"], strong, b'))) {
|
|
2006
|
+
const label = norm(term.textContent);
|
|
2007
|
+
if (!LABEL.test(label) || label.length > 60) continue;
|
|
2008
|
+
for (let next = term.nextElementSibling, steps = 0; next && steps < 2; next = next.nextElementSibling, steps++) {
|
|
2009
|
+
if (term.tagName === "DT" && next.tagName !== "DD") break;
|
|
2010
|
+
add(label, next.value ?? next.textContent, true);
|
|
2011
|
+
for (const inner of Array.from(next.querySelectorAll("input, textarea, code, pre, span"))) add(label, inner.value ?? inner.textContent, true);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
for (const element of Array.from(doc.querySelectorAll("code, pre, samp, kbd, input, textarea"))) {
|
|
2015
|
+
const type = String(element.getAttribute("type") ?? "text").toLowerCase();
|
|
2016
|
+
if (type === "password" || type === "hidden" && !opaque(element.value ?? "")) continue;
|
|
2017
|
+
const text = norm(element.value ?? element.textContent);
|
|
2018
|
+
add("", text, false);
|
|
2019
|
+
const parts = (element.value ?? element.textContent ?? "").trim().split(/\s+/);
|
|
2020
|
+
if (parts.length > 1 && parts.length <= 400) add("", parts.join(""), false);
|
|
2021
|
+
}
|
|
2022
|
+
for (const element of Array.from(doc.querySelectorAll("*")).slice(0, 6e3)) {
|
|
2023
|
+
for (const attribute of Array.from(element.attributes)) {
|
|
2024
|
+
if (!attribute.name.startsWith("data-")) continue;
|
|
2025
|
+
const named = LABEL.test(attribute.name) && !/api-?(?:url|host|base|endpoint)|keyboard|tokenizer/i.test(attribute.name);
|
|
2026
|
+
if (/(?:^|-)(?:id|testid|ref|url|href|src|reactid)$/.test(attribute.name) && !named) continue;
|
|
2027
|
+
add(attribute.name, attribute.value, named && attribute.value.length >= 8 || attribute.value.length >= 20 && opaque(attribute.value));
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
return [...found].map(([value, label]) => ({ value, label }));
|
|
2031
|
+
}
|
|
2032
|
+
async function pageSecrets(page) {
|
|
2033
|
+
const out = /* @__PURE__ */ new Map();
|
|
2034
|
+
let frames = [];
|
|
2035
|
+
try {
|
|
2036
|
+
frames = page.frames();
|
|
2037
|
+
} catch {
|
|
2038
|
+
return [];
|
|
2039
|
+
}
|
|
2040
|
+
for (const frame of frames) {
|
|
2041
|
+
if (frame.isDetached()) continue;
|
|
2042
|
+
try {
|
|
2043
|
+
for (const found of await frame.evaluate(pageSecretsInPage)) if (!out.has(found.value)) out.set(found.value, found.label);
|
|
2044
|
+
} catch {
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
return [...out].map(([value, label]) => ({ value, label }));
|
|
2048
|
+
}
|
|
2049
|
+
async function findLabelledSecret(page, label) {
|
|
2050
|
+
const all = await pageSecrets(page);
|
|
2051
|
+
const words = (label ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
|
2052
|
+
if (!words) return new Set(all.map((item) => item.value)).size === 1 ? all[0].value : void 0;
|
|
2053
|
+
const matches = all.filter((item) => item.label && item.label.toLowerCase().replace(/[^a-z0-9]+/g, " ").includes(words));
|
|
2054
|
+
const distinct = [...new Set(matches.map((item) => item.value))];
|
|
2055
|
+
return distinct.length === 1 ? distinct[0] : void 0;
|
|
2056
|
+
}
|
|
2057
|
+
async function maskSensitive(page, text) {
|
|
2058
|
+
let out = text;
|
|
2059
|
+
for (const value of (await sensitiveValues(page)).sort((a, b) => b.length - a.length)) out = out.split(value).join("[hidden]");
|
|
2060
|
+
const shown = /* @__PURE__ */ new Set([...await keyFieldValues(page), ...(await pageSecrets(page)).map((item) => item.value)]);
|
|
2061
|
+
for (const value of [...shown].sort((a, b) => b.length - a.length)) {
|
|
2062
|
+
const ref = secretRef(value);
|
|
2063
|
+
if (out.includes(value)) out = out.split(value).join(ref);
|
|
2064
|
+
}
|
|
2065
|
+
return out;
|
|
2066
|
+
}
|
|
2067
|
+
function windowMayShowBrowser(browserPids, windowPid) {
|
|
2068
|
+
if (windowPid === void 0 || !browserPids) return true;
|
|
2069
|
+
return browserPids.includes(windowPid);
|
|
2070
|
+
}
|
|
2071
|
+
var BROWSER_CLOSED = /^(?:ClikCode browser|The managed cloud browser) is closed\b/;
|
|
2072
|
+
async function credentialOnScreen(stateDir, windowPid, options = {}) {
|
|
2073
|
+
let pages;
|
|
2074
|
+
try {
|
|
2075
|
+
pages = await (options.listPages ?? allComputerPages)(stateDir);
|
|
2076
|
+
} catch (error) {
|
|
2077
|
+
return !(error instanceof Error && BROWSER_CLOSED.test(error.message));
|
|
2078
|
+
}
|
|
2079
|
+
if (windowPid !== void 0) {
|
|
2080
|
+
const pids = await computerBrowserPids(stateDir).catch(quiet("agent/computer/sensitive-fields"));
|
|
2081
|
+
if (!windowMayShowBrowser(pids, windowPid)) return false;
|
|
2082
|
+
}
|
|
2083
|
+
for (const page of pages) {
|
|
2084
|
+
const values = await sensitiveValues(page).catch(quiet("agent/computer/sensitive-fields"));
|
|
2085
|
+
if (values && !values.length) continue;
|
|
2086
|
+
if (await page.evaluate(() => globalThis.document.visibilityState !== "hidden").catch(() => true)) return true;
|
|
2087
|
+
}
|
|
2088
|
+
return false;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
// src/agent/computer/console-log.ts
|
|
2092
|
+
var KEEP = 200;
|
|
2093
|
+
var MAX_TEXT2 = 600;
|
|
2094
|
+
var logs = sharedState("console-logs", () => /* @__PURE__ */ new WeakMap());
|
|
2095
|
+
var watched = sharedState("console-watched", () => /* @__PURE__ */ new WeakSet());
|
|
2096
|
+
var LEVELS = { error: "error", warning: "warning", info: "info", log: "log", debug: "debug", trace: "debug", assert: "error" };
|
|
2097
|
+
function watchConsole(page) {
|
|
2098
|
+
if (watched.has(page)) return;
|
|
2099
|
+
watched.add(page);
|
|
2100
|
+
const entries = [];
|
|
2101
|
+
logs.set(page, entries);
|
|
2102
|
+
const push = (entry) => {
|
|
2103
|
+
entries.push(entry);
|
|
2104
|
+
if (entries.length > KEEP) entries.splice(0, entries.length - KEEP);
|
|
2105
|
+
};
|
|
2106
|
+
page.on("console", (message) => {
|
|
2107
|
+
const at = message.location();
|
|
2108
|
+
push({ level: LEVELS[message.type()] ?? "log", text: message.text().slice(0, MAX_TEXT2), at: Date.now(), ...at.url ? { where: `${at.url.split("?")[0]}:${at.lineNumber + 1}` } : {} });
|
|
2109
|
+
});
|
|
2110
|
+
page.on("pageerror", (error) => push({ level: "pageerror", text: (error.stack || error.message || String(error)).split("\n").slice(0, 4).join(" | ").slice(0, MAX_TEXT2), at: Date.now() }));
|
|
2111
|
+
}
|
|
2112
|
+
function pickConsole(entries, options = {}) {
|
|
2113
|
+
const order = ["pageerror", "error", "warning", "info", "log", "debug"];
|
|
2114
|
+
const floor = options.level ? order.indexOf(options.level === "warn" ? "warning" : options.level) : -1;
|
|
2115
|
+
const wanted = options.find?.toLowerCase();
|
|
2116
|
+
const kept = entries.filter((entry) => (floor < 0 || order.indexOf(entry.level) <= floor) && (!wanted || entry.text.toLowerCase().includes(wanted)));
|
|
2117
|
+
return kept.slice(-Math.min(Math.max(Math.floor(options.limit ?? 30), 1), KEEP));
|
|
2118
|
+
}
|
|
2119
|
+
function describeConsole(entries, total) {
|
|
2120
|
+
if (!entries.length) return total ? "No console messages match." : "The console is empty: nothing logged and no page errors in this tab.";
|
|
2121
|
+
const lines = entries.map((entry) => `[${entry.level}] ${entry.text}${entry.where ? ` (${entry.where})` : ""}`);
|
|
2122
|
+
return `Console of this tab (${entries.length} of ${total} kept, oldest first):
|
|
2123
|
+
${lines.join("\n")}`;
|
|
2124
|
+
}
|
|
2125
|
+
async function readConsole(page, options = {}) {
|
|
2126
|
+
watchConsole(page);
|
|
2127
|
+
const all = logs.get(page) ?? [];
|
|
2128
|
+
const text = describeConsole(pickConsole(all, options), all.length);
|
|
2129
|
+
if (options.clear) all.length = 0;
|
|
2130
|
+
return hideKeyLikeText(scrubSecrets(await maskSensitive(page, text))).text;
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
// src/agent/computer/egress-host.ts
|
|
2134
|
+
import { createServer as createServer2, connect as netConnect } from "node:net";
|
|
2135
|
+
import fs3 from "node:fs/promises";
|
|
2136
|
+
import path3 from "node:path";
|
|
2137
|
+
var EgressContexts = class {
|
|
2138
|
+
constructor(cdp, server) {
|
|
2139
|
+
this.cdp = cdp;
|
|
2140
|
+
this.server = server;
|
|
2141
|
+
}
|
|
2142
|
+
cdp;
|
|
2143
|
+
server;
|
|
2144
|
+
held = /* @__PURE__ */ new Map();
|
|
2145
|
+
ensure(name) {
|
|
2146
|
+
const previous = this.held.get(name);
|
|
2147
|
+
const next = (async () => {
|
|
2148
|
+
const old = await previous?.catch(quiet("agent/computer/egress-host"));
|
|
2149
|
+
const server = await this.server(name);
|
|
2150
|
+
if (!server) throw new Error(`"${name}" is this computer's own connection: it needs no context.`);
|
|
2151
|
+
const cdp = await this.cdp();
|
|
2152
|
+
if (old && old.server === server && await this.exists(cdp, old.id)) return old;
|
|
2153
|
+
if (old) await cdp.send("Target.disposeBrowserContext", { browserContextId: old.id }).catch(quiet("agent/computer/egress-host"));
|
|
2154
|
+
const made = await cdp.send("Target.createBrowserContext", { disposeOnDetach: false, proxyServer: server });
|
|
2155
|
+
const id = typeof made.browserContextId === "string" ? made.browserContextId : "";
|
|
2156
|
+
if (!id) throw new Error("Chrome did not make the egress context.");
|
|
2157
|
+
lifecycle("browser.egress.context", { egress: name, host: true });
|
|
2158
|
+
return { id, server };
|
|
2159
|
+
})();
|
|
2160
|
+
this.held.set(name, next);
|
|
2161
|
+
next.catch(() => {
|
|
2162
|
+
if (this.held.get(name) === next) this.held.delete(name);
|
|
2163
|
+
});
|
|
2164
|
+
return next;
|
|
2165
|
+
}
|
|
2166
|
+
/** Opens a page at `url` in the egress's context; its target id. */
|
|
2167
|
+
async openPage(name, url) {
|
|
2168
|
+
const { id } = await this.ensure(name);
|
|
2169
|
+
const made = await (await this.cdp()).send("Target.createTarget", { url, browserContextId: id });
|
|
2170
|
+
return typeof made.targetId === "string" ? made.targetId : void 0;
|
|
2171
|
+
}
|
|
2172
|
+
async exists(cdp, id) {
|
|
2173
|
+
const listed = await cdp.send("Target.getBrowserContexts").catch(quiet("agent/computer/egress-host"));
|
|
2174
|
+
return Array.isArray(listed?.browserContextIds) ? listed.browserContextIds.includes(id) : true;
|
|
2175
|
+
}
|
|
2176
|
+
};
|
|
2177
|
+
function rawBrowserCdp(profile) {
|
|
2178
|
+
let open;
|
|
2179
|
+
return () => {
|
|
2180
|
+
open ??= (async () => {
|
|
2181
|
+
const [port, route] = (await fs3.readFile(path3.join(profile, "DevToolsActivePort"), "utf8")).split("\n");
|
|
2182
|
+
const socket = new WebSocket(`ws://127.0.0.1:${Number(port)}${route?.trim()}`);
|
|
2183
|
+
await new Promise((resolve, reject) => {
|
|
2184
|
+
socket.addEventListener("open", () => resolve(), { once: true });
|
|
2185
|
+
socket.addEventListener("error", () => reject(new Error("Could not reach Chrome's debugging socket.")), { once: true });
|
|
2186
|
+
});
|
|
2187
|
+
let next = 0;
|
|
2188
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
2189
|
+
socket.addEventListener("message", (event) => {
|
|
2190
|
+
let message;
|
|
2191
|
+
try {
|
|
2192
|
+
message = JSON.parse(String(event.data));
|
|
2193
|
+
} catch {
|
|
2194
|
+
return;
|
|
2195
|
+
}
|
|
2196
|
+
const pending = message.id !== void 0 ? waiting.get(message.id) : void 0;
|
|
2197
|
+
if (!pending) return;
|
|
2198
|
+
waiting.delete(message.id);
|
|
2199
|
+
if (message.error) pending.reject(new Error(message.error.message ?? "CDP error"));
|
|
2200
|
+
else pending.resolve(message.result ?? {});
|
|
2201
|
+
});
|
|
2202
|
+
socket.addEventListener("close", () => {
|
|
2203
|
+
open = void 0;
|
|
2204
|
+
for (const pending of waiting.values()) pending.reject(new Error("Chrome's debugging socket closed."));
|
|
2205
|
+
waiting.clear();
|
|
2206
|
+
});
|
|
2207
|
+
return {
|
|
2208
|
+
send: (method, params = {}) => new Promise((resolve, reject) => {
|
|
2209
|
+
const id = ++next;
|
|
2210
|
+
waiting.set(id, { resolve, reject });
|
|
2211
|
+
socket.send(JSON.stringify({ id, method, params }));
|
|
2212
|
+
setTimeout(() => {
|
|
2213
|
+
if (waiting.delete(id)) reject(new Error(`Chrome did not answer ${method} in time.`));
|
|
2214
|
+
}, 2e4).unref?.();
|
|
2215
|
+
})
|
|
2216
|
+
};
|
|
2217
|
+
})();
|
|
2218
|
+
open.catch(() => {
|
|
2219
|
+
open = void 0;
|
|
2220
|
+
});
|
|
2221
|
+
return open;
|
|
2222
|
+
};
|
|
2223
|
+
}
|
|
2224
|
+
function egressSocketPath(stateDir, pid = process.pid) {
|
|
2225
|
+
return process.platform === "win32" ? `\\\\.\\pipe\\clikcode-egress-${pid}` : path3.join(stateDir, "computer", `egress-${pid}.sock`);
|
|
2226
|
+
}
|
|
2227
|
+
async function serveEgress(socketPath, contexts) {
|
|
2228
|
+
if (process.platform !== "win32") await fs3.unlink(socketPath).catch(quiet("agent/computer/egress-host"));
|
|
2229
|
+
const server = createServer2((client) => {
|
|
2230
|
+
let buffer = "";
|
|
2231
|
+
const onData = (chunk) => {
|
|
2232
|
+
buffer += String(chunk);
|
|
2233
|
+
const end = buffer.indexOf("\n");
|
|
2234
|
+
if (end < 0) {
|
|
2235
|
+
if (buffer.length > 4096) client.destroy();
|
|
2236
|
+
return;
|
|
2237
|
+
}
|
|
2238
|
+
client.off("data", onData);
|
|
2239
|
+
let name = "";
|
|
2240
|
+
try {
|
|
2241
|
+
name = String(JSON.parse(buffer.slice(0, end)).egress ?? "");
|
|
2242
|
+
} catch {
|
|
2243
|
+
name = "";
|
|
2244
|
+
}
|
|
2245
|
+
buffer = "";
|
|
2246
|
+
if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(name)) {
|
|
2247
|
+
client.end(`${JSON.stringify({ error: "An egress name is lower-case letters, digits and dashes." })}
|
|
2248
|
+
`);
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
void contexts.ensure(name).then(
|
|
2252
|
+
(held2) => client.end(`${JSON.stringify(held2)}
|
|
2253
|
+
`),
|
|
2254
|
+
(error) => client.end(`${JSON.stringify({ error: (error instanceof Error ? error.message : String(error)).slice(0, 300) })}
|
|
2255
|
+
`)
|
|
2256
|
+
);
|
|
2257
|
+
};
|
|
2258
|
+
client.on("data", onData);
|
|
2259
|
+
client.on("error", quiet("agent/computer/egress-host"));
|
|
2260
|
+
});
|
|
2261
|
+
await new Promise((resolve, reject) => {
|
|
2262
|
+
server.once("error", reject);
|
|
2263
|
+
server.listen(socketPath, () => {
|
|
2264
|
+
server.off("error", reject);
|
|
2265
|
+
resolve();
|
|
2266
|
+
});
|
|
2267
|
+
});
|
|
2268
|
+
if (process.platform !== "win32") await fs3.chmod(socketPath, 384).catch(quiet("agent/computer/egress-host"));
|
|
2269
|
+
return {
|
|
2270
|
+
stop: async () => {
|
|
2271
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
2272
|
+
if (process.platform !== "win32") await fs3.unlink(socketPath).catch(quiet("agent/computer/egress-host"));
|
|
2273
|
+
}
|
|
2274
|
+
};
|
|
2275
|
+
}
|
|
2276
|
+
async function startEgressService(stateDir, profile, tunnels = tunnelManager(stateDir)) {
|
|
2277
|
+
const contexts = new EgressContexts(rawBrowserCdp(profile), (name) => egressServer(stateDir, name, tunnels));
|
|
2278
|
+
const socket = egressSocketPath(stateDir);
|
|
2279
|
+
const served = await serveEgress(socket, contexts);
|
|
2280
|
+
return { socket, contexts, stop: async () => {
|
|
2281
|
+
await served.stop();
|
|
2282
|
+
tunnels.closeAll();
|
|
2283
|
+
} };
|
|
2284
|
+
}
|
|
2285
|
+
var EgressNotServed = class extends Error {
|
|
2286
|
+
};
|
|
2287
|
+
async function requestHostedContext(stateDir, name, readHostFile = () => fs3.readFile(path3.join(stateDir, "computer", "host.json"), "utf8"), ms = 3e4) {
|
|
2288
|
+
let socketPath;
|
|
2289
|
+
try {
|
|
2290
|
+
socketPath = JSON.parse(await readHostFile()).egressSocket;
|
|
2291
|
+
} catch {
|
|
2292
|
+
socketPath = void 0;
|
|
2293
|
+
}
|
|
2294
|
+
if (typeof socketPath !== "string" || !socketPath) throw new EgressNotServed("The browser host does not serve egress contexts.");
|
|
2295
|
+
return new Promise((resolve, reject) => {
|
|
2296
|
+
const client = netConnect(socketPath);
|
|
2297
|
+
let reply = "";
|
|
2298
|
+
let connected = false;
|
|
2299
|
+
const timer = setTimeout(() => {
|
|
2300
|
+
client.destroy();
|
|
2301
|
+
reject(new Error(`The browser host did not open the egress "${name}" in time.`));
|
|
2302
|
+
}, ms);
|
|
2303
|
+
client.once("connect", () => {
|
|
2304
|
+
connected = true;
|
|
2305
|
+
client.write(`${JSON.stringify({ egress: name })}
|
|
2306
|
+
`);
|
|
2307
|
+
});
|
|
2308
|
+
client.on("data", (chunk) => {
|
|
2309
|
+
reply += String(chunk);
|
|
2310
|
+
});
|
|
2311
|
+
client.once("end", () => {
|
|
2312
|
+
clearTimeout(timer);
|
|
2313
|
+
try {
|
|
2314
|
+
const answer = JSON.parse(reply.trim());
|
|
2315
|
+
if (answer.error) reject(new Error(answer.error));
|
|
2316
|
+
else if (answer.id && answer.server) resolve({ id: answer.id, server: answer.server });
|
|
2317
|
+
else reject(new Error("The browser host gave no egress context."));
|
|
2318
|
+
} catch {
|
|
2319
|
+
reject(new Error("The browser host gave no egress context."));
|
|
2320
|
+
}
|
|
2321
|
+
});
|
|
2322
|
+
client.once("error", (error) => {
|
|
2323
|
+
clearTimeout(timer);
|
|
2324
|
+
reject(connected ? error : new EgressNotServed(`The browser host does not serve egress contexts (${error.code ?? error.message}).`));
|
|
2325
|
+
});
|
|
2326
|
+
});
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
// src/agent/computer/browser.ts
|
|
2330
|
+
var running = sharedState("browser-running", () => /* @__PURE__ */ new Map());
|
|
2331
|
+
async function connect(stateDir) {
|
|
2332
|
+
const file = path4.join(computerProfile(stateDir), "DevToolsActivePort");
|
|
2333
|
+
let port;
|
|
2334
|
+
try {
|
|
2335
|
+
port = Number((await fs4.readFile(file, "utf8")).split("\n")[0]);
|
|
2336
|
+
} catch {
|
|
2337
|
+
return void 0;
|
|
2338
|
+
}
|
|
2339
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
|
|
2340
|
+
try {
|
|
2341
|
+
const { chromium } = await import("playwright-core");
|
|
2342
|
+
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 8e3 });
|
|
2343
|
+
const context = browser.contexts()[0];
|
|
2344
|
+
if (!context) {
|
|
2345
|
+
await browser.close();
|
|
2346
|
+
return void 0;
|
|
2347
|
+
}
|
|
2348
|
+
await serveDownloads(browser, stateDir).catch(quiet("agent/computer/browser"));
|
|
2349
|
+
return { browser, context };
|
|
2350
|
+
} catch {
|
|
2351
|
+
return void 0;
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
async function parentPid(pid) {
|
|
2355
|
+
try {
|
|
2356
|
+
return Number((await fs4.readFile(`/proc/${pid}/stat`, "utf8")).replace(/^.*\)\s+\S+\s+/, "").split(" ")[0]) || 0;
|
|
2357
|
+
} catch {
|
|
2358
|
+
return 0;
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
async function chromeIsHostChild(stateDir, chromePid) {
|
|
2362
|
+
try {
|
|
2363
|
+
const host = Number(JSON.parse(await fs4.readFile(computerHostFile(stateDir), "utf8")).pid);
|
|
2364
|
+
if (!Number.isInteger(host) || host < 2 || !pidIsAlive(host)) return false;
|
|
2365
|
+
return await parentPid(chromePid) === host;
|
|
2366
|
+
} catch {
|
|
2367
|
+
return false;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
var BROWSER_BUSY = "ClikCode browser is busy and did not answer in time (the machine is stalled). Retry shortly; nothing is blocking it.";
|
|
2371
|
+
async function ownChromeAlive(stateDir) {
|
|
2372
|
+
try {
|
|
2373
|
+
const lock = await fs4.readlink(path4.join(computerProfile(stateDir), "SingletonLock"));
|
|
2374
|
+
const pid = Number(lock.match(/-(\d+)$/)?.[1]);
|
|
2375
|
+
if (!pidIsAlive(pid)) return false;
|
|
2376
|
+
return await chromeIsHostChild(stateDir, pid);
|
|
2377
|
+
} catch {
|
|
2378
|
+
return false;
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
async function chromeIsOrphan(chromePid) {
|
|
2382
|
+
const parent = await parentPid(chromePid);
|
|
2383
|
+
if (parent === 1) return true;
|
|
2384
|
+
if (parent < 2) return false;
|
|
2385
|
+
try {
|
|
2386
|
+
return (await fs4.readFile(`/proc/${parent}/comm`, "utf8")).trim() === "systemd";
|
|
2387
|
+
} catch {
|
|
2388
|
+
return false;
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
async function reclaimOrphanChrome(stateDir) {
|
|
2392
|
+
const profile = computerProfile(stateDir);
|
|
2393
|
+
let pid = 0;
|
|
2394
|
+
try {
|
|
2395
|
+
pid = Number((await fs4.readlink(path4.join(profile, "SingletonLock"))).match(/-(\d+)$/)?.[1]);
|
|
2396
|
+
} catch {
|
|
2397
|
+
return true;
|
|
2398
|
+
}
|
|
2399
|
+
if (!pid || !await chromeIsOrphan(pid)) return false;
|
|
2400
|
+
lifecycle("browser.chrome.orphan_reclaimed", { pid });
|
|
2401
|
+
try {
|
|
2402
|
+
process.kill(pid, "SIGTERM");
|
|
2403
|
+
} catch {
|
|
2404
|
+
}
|
|
2405
|
+
for (let wait = 0; wait < 20 && pidIsAlive(pid); wait++) await sleep(250);
|
|
2406
|
+
try {
|
|
2407
|
+
process.kill(pid, "SIGKILL");
|
|
2408
|
+
} catch {
|
|
2409
|
+
}
|
|
2410
|
+
await Promise.all(["SingletonLock", "SingletonSocket", "SingletonCookie"].map((name) => fs4.unlink(path4.join(profile, name)).catch(quiet("agent/computer/browser"))));
|
|
2411
|
+
return true;
|
|
2412
|
+
}
|
|
2413
|
+
async function externalChromeRunning(stateDir) {
|
|
2414
|
+
try {
|
|
2415
|
+
const lock = await fs4.readlink(path4.join(computerProfile(stateDir), "SingletonLock"));
|
|
2416
|
+
const pid = Number(lock.match(/-(\d+)$/)?.[1]);
|
|
2417
|
+
if (!pidIsAlive(pid)) return false;
|
|
2418
|
+
return !await chromeIsHostChild(stateDir, pid);
|
|
2419
|
+
} catch {
|
|
2420
|
+
return false;
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
async function startHost(stateDir) {
|
|
2424
|
+
const dir = path4.join(stateDir, "computer");
|
|
2425
|
+
await fs4.mkdir(dir, { recursive: true, mode: 448 });
|
|
2426
|
+
const lease = await tryLease(path4.join(dir, "host-start.lock"));
|
|
2427
|
+
if (lease) {
|
|
2428
|
+
try {
|
|
2429
|
+
const existing = await connect(stateDir);
|
|
2430
|
+
if (existing) return existing;
|
|
2431
|
+
const working = await liveHostStatus(stateDir);
|
|
2432
|
+
if (working?.state === "installing") throw new Error(installingMessage(working));
|
|
2433
|
+
for (let again = 0; again < 4 && await externalChromeRunning(stateDir); again++) {
|
|
2434
|
+
await sleep(1500);
|
|
2435
|
+
const later = await connect(stateDir);
|
|
2436
|
+
if (later) return later;
|
|
2437
|
+
}
|
|
2438
|
+
if (await externalChromeRunning(stateDir) && !await reclaimOrphanChrome(stateDir)) throw new Error("ClikCode Chrome is open outside ClikCode. Finish that browser step, close its window, and retry.");
|
|
2439
|
+
if (await ownChromeAlive(stateDir)) {
|
|
2440
|
+
for (let again = 0; again < 8; again++) {
|
|
2441
|
+
await sleep(5e3);
|
|
2442
|
+
const later = await connect(stateDir);
|
|
2443
|
+
if (later) return later;
|
|
2444
|
+
}
|
|
2445
|
+
throw new Error(BROWSER_BUSY);
|
|
2446
|
+
}
|
|
2447
|
+
const entry = process.env.CLIKCODE_BROWSER_HOST_ENTRY || process.argv[1];
|
|
2448
|
+
if (!entry) throw new Error("ClikCode could not start its browser host.");
|
|
2449
|
+
const hostArgs = [process.execPath, entry, "computer-host", stateDir];
|
|
2450
|
+
const plain = hiddenDisplayCommand(hostArgs, process.env, process.platform, void 0, {
|
|
2451
|
+
display: await browserDisplay(stateDir),
|
|
2452
|
+
onFallback: () => lifecycle("browser.host.display", { wanted: "visible", used: "hidden", why: "no desktop session" })
|
|
2453
|
+
});
|
|
2454
|
+
const own = browserHostLaunch(plain, { platform: process.platform, env: process.env, cgroup: await fs4.readFile("/proc/self/cgroup", "utf8").catch(() => ""), uid: process.getuid?.() ?? 0, cwd: process.cwd(), busExists: existsSync });
|
|
2455
|
+
await fs4.unlink(hostStatusFile(stateDir)).catch(quiet("agent/computer/browser"));
|
|
2456
|
+
const launch = (argv, env) => {
|
|
2457
|
+
const [command, ...rest] = argv;
|
|
2458
|
+
const started = spawn(command, rest, { detached: true, stdio: "ignore", windowsHide: true, ...env ? { env } : {} });
|
|
2459
|
+
started.once("error", (error) => {
|
|
2460
|
+
startupError = error;
|
|
2461
|
+
});
|
|
2462
|
+
started.unref();
|
|
2463
|
+
return started;
|
|
2464
|
+
};
|
|
2465
|
+
let startupError;
|
|
2466
|
+
let child = launch(own?.argv ?? plain, own?.env);
|
|
2467
|
+
let scoped = own !== void 0;
|
|
2468
|
+
lifecycle("browser.host.start", { scoped, unit: scoped ? BROWSER_HOST_UNIT : void 0 });
|
|
2469
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
2470
|
+
const result = await connect(stateDir);
|
|
2471
|
+
if (result) return result;
|
|
2472
|
+
const status = await readHostStatus(stateDir);
|
|
2473
|
+
if (status?.state === "installing") throw new Error(installingMessage(status));
|
|
2474
|
+
if (status?.state === "failed" && status.text) throw new Error(status.text);
|
|
2475
|
+
const exited = child.exitCode !== null && (child.exitCode !== 0 || !own?.detachesAtOnce);
|
|
2476
|
+
if (scoped && (startupError || exited) && !status) {
|
|
2477
|
+
lifecycle("browser.host.unscoped", { code: child.exitCode ?? void 0 });
|
|
2478
|
+
scoped = false;
|
|
2479
|
+
startupError = void 0;
|
|
2480
|
+
child = launch(plain);
|
|
2481
|
+
} else if (startupError || child.exitCode !== null && !(scoped && own?.detachesAtOnce && child.exitCode === 0)) break;
|
|
2482
|
+
await sleep(200);
|
|
2483
|
+
}
|
|
2484
|
+
const last = await readHostStatus(stateDir);
|
|
2485
|
+
if (last?.state === "failed" && last.text) throw new Error(last.text);
|
|
2486
|
+
throw new Error("ClikCode could not start its browser. Check that Chrome or Edge is installed and the desktop is available.");
|
|
2487
|
+
} finally {
|
|
2488
|
+
await lease.release();
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
for (let attempt = 0; attempt < 110; attempt++) {
|
|
2492
|
+
const result = await connect(stateDir);
|
|
2493
|
+
if (result) return result;
|
|
2494
|
+
const status = await readHostStatus(stateDir);
|
|
2495
|
+
if (status?.state === "installing") throw new Error(installingMessage(status));
|
|
2496
|
+
if (status?.state === "failed" && status.text) throw new Error(status.text);
|
|
2497
|
+
await sleep(200);
|
|
2498
|
+
}
|
|
2499
|
+
throw new Error("ClikCode Chrome could not start.");
|
|
2500
|
+
}
|
|
2501
|
+
var cloudRunKey = (stateDir) => `${stateDir}\0\0cloud`;
|
|
2502
|
+
async function browserFor(stateDir, start, cloud = false) {
|
|
2503
|
+
const runKey = cloud ? cloudRunKey(stateDir) : stateDir;
|
|
2504
|
+
let opening = running.get(runKey);
|
|
2505
|
+
if (!opening) {
|
|
2506
|
+
opening = (async () => {
|
|
2507
|
+
if (cloud) {
|
|
2508
|
+
const remote = await browserUseConnection(stateDir, start);
|
|
2509
|
+
if (remote) return remote;
|
|
2510
|
+
throw new Error("The managed cloud browser is closed. Open a URL with browser_use first.");
|
|
2511
|
+
}
|
|
2512
|
+
const current = await connect(stateDir);
|
|
2513
|
+
if (current) return current;
|
|
2514
|
+
if (!start) throw new Error("ClikCode browser is closed. Open a URL with browser_use first.");
|
|
2515
|
+
return startHost(stateDir);
|
|
2516
|
+
})();
|
|
2517
|
+
running.set(runKey, opening);
|
|
2518
|
+
void opening.then(({ browser }) => {
|
|
2519
|
+
browser.on("disconnected", () => {
|
|
2520
|
+
if (running.get(runKey) === opening) running.delete(runKey);
|
|
2521
|
+
});
|
|
2522
|
+
if (cloud) watchCloudIdle(stateDir);
|
|
2523
|
+
}).catch(quiet("agent/computer/browser"));
|
|
2524
|
+
opening.catch(() => {
|
|
2525
|
+
if (running.get(runKey) === opening) running.delete(runKey);
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
return opening;
|
|
2529
|
+
}
|
|
2530
|
+
var owned = sharedState("browser-owned", () => /* @__PURE__ */ new Map());
|
|
2531
|
+
var ownerKey = (stateDir, tab) => tab ? `${stateDir}\0${tab}` : stateDir;
|
|
2532
|
+
var cloudOwners = sharedState("browser-cloud-owners", () => /* @__PURE__ */ new Set());
|
|
2533
|
+
var cloudPages = sharedState("browser-cloud-pages", () => /* @__PURE__ */ new WeakSet());
|
|
2534
|
+
var cloudUsedAt = sharedState("browser-cloud-used", () => /* @__PURE__ */ new Map());
|
|
2535
|
+
var cloudTimers = sharedState("browser-cloud-timers", () => /* @__PURE__ */ new Map());
|
|
2536
|
+
function cloudIdleMs(env = process.env) {
|
|
2537
|
+
const minutes = Number(env.CLIKCODE_CLOUD_BROWSER_IDLE_MINUTES);
|
|
2538
|
+
return (Number.isFinite(minutes) && minutes >= 1 ? Math.min(minutes, 55) : 10) * 6e4;
|
|
2539
|
+
}
|
|
2540
|
+
async function onCloud(stateDir, tab) {
|
|
2541
|
+
const provider = await browserProvider(stateDir);
|
|
2542
|
+
return provider === "browser-use" || provider === "auto" && cloudOwners.has(ownerKey(stateDir, tab));
|
|
2543
|
+
}
|
|
2544
|
+
function tabIsInCloud(stateDir, tab) {
|
|
2545
|
+
const page = mine(stateDir, tab);
|
|
2546
|
+
return Boolean(page && cloudPages.has(page));
|
|
2547
|
+
}
|
|
2548
|
+
var inUse = (page) => !page.isClosed() && !/^(?:about:blank|chrome:\/\/newtab\/?|chrome:\/\/new-tab-page\/?)?$/.test(page.url());
|
|
2549
|
+
async function settleCloud(stateDir, force = false) {
|
|
2550
|
+
const runKey = cloudRunKey(stateDir);
|
|
2551
|
+
const opening = running.get(runKey);
|
|
2552
|
+
const connected = await opening?.catch(quiet("agent/computer/browser"));
|
|
2553
|
+
if (connected && !force && connected.context.pages().some(inUse)) return false;
|
|
2554
|
+
if (!connected && !force) return false;
|
|
2555
|
+
running.delete(runKey);
|
|
2556
|
+
const timer = cloudTimers.get(stateDir);
|
|
2557
|
+
if (timer) {
|
|
2558
|
+
clearInterval(timer);
|
|
2559
|
+
cloudTimers.delete(stateDir);
|
|
2560
|
+
}
|
|
2561
|
+
cloudUsedAt.delete(stateDir);
|
|
2562
|
+
await connected?.browser.close().catch(quiet("agent/computer/browser"));
|
|
2563
|
+
await stopBrowserUse(stateDir);
|
|
2564
|
+
return true;
|
|
2565
|
+
}
|
|
2566
|
+
function watchCloudIdle(stateDir) {
|
|
2567
|
+
cloudUsedAt.set(stateDir, Date.now());
|
|
2568
|
+
if (cloudTimers.has(stateDir)) return;
|
|
2569
|
+
const timer = setInterval(() => {
|
|
2570
|
+
if (Date.now() - (cloudUsedAt.get(stateDir) ?? 0) < cloudIdleMs()) return;
|
|
2571
|
+
void closeCloudTabs(stateDir).then(() => settleCloud(stateDir)).catch(quiet("agent/computer/browser"));
|
|
2572
|
+
}, 3e4);
|
|
2573
|
+
timer.unref();
|
|
2574
|
+
cloudTimers.set(stateDir, timer);
|
|
2575
|
+
}
|
|
2576
|
+
async function closeCloudTabs(stateDir) {
|
|
2577
|
+
const all = owned;
|
|
2578
|
+
for (const key of [...all.keys()]) {
|
|
2579
|
+
if (key !== stateDir && !key.startsWith(`${stateDir}\0`)) continue;
|
|
2580
|
+
const pages = all.get(key) ?? [];
|
|
2581
|
+
const cloud = pages.filter((page) => cloudPages.has(page));
|
|
2582
|
+
if (!cloud.length) continue;
|
|
2583
|
+
all.set(key, pages.filter((page) => !cloudPages.has(page)));
|
|
2584
|
+
cloudOwners.delete(key);
|
|
2585
|
+
for (const page of cloud) await page.close().catch(quiet("agent/computer/browser"));
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
function privateAddress(address) {
|
|
2589
|
+
let host;
|
|
2590
|
+
try {
|
|
2591
|
+
host = new URL(address).hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
2592
|
+
} catch {
|
|
2593
|
+
return true;
|
|
2594
|
+
}
|
|
2595
|
+
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".ts.net") || !host.includes(".") && !host.includes(":")) return true;
|
|
2596
|
+
if (/^(?:127\.|10\.|192\.168\.|169\.254\.|0\.)/.test(host) || /^172\.(?:1[6-9]|2\d|3[01])\./.test(host) || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(host)) return true;
|
|
2597
|
+
return host === "::1" || /^f[cd][0-9a-f]{2}:/.test(host) || /^fe80:/.test(host);
|
|
2598
|
+
}
|
|
2599
|
+
async function moveTabToCloud(stateDir, tab) {
|
|
2600
|
+
const provider = await browserProvider(stateDir);
|
|
2601
|
+
if (provider === "local") throw new Error("The managed cloud browser is off. The user turns it on with `clikcode computer browser-use auto` (local first, cloud when asked) after saving its key as the secret `browser-use/api-key`.");
|
|
2602
|
+
const key = ownerKey(stateDir, tab);
|
|
2603
|
+
const current = mine(stateDir, tab);
|
|
2604
|
+
if (current && cloudPages.has(current)) return { page: current, moved: false };
|
|
2605
|
+
const address = current && /^https?:/i.test(current.url()) ? current.url() : void 0;
|
|
2606
|
+
if (address && privateAddress(address)) throw new Error("This page is on this computer or its private network, which a cloud browser cannot reach. It stays in the local browser.");
|
|
2607
|
+
const { context } = await browserFor(stateDir, true, true);
|
|
2608
|
+
const page = await context.newPage();
|
|
2609
|
+
cloudPages.add(page);
|
|
2610
|
+
const local = owned.get(key) ?? [];
|
|
2611
|
+
owned.set(key, []);
|
|
2612
|
+
cloudOwners.add(key);
|
|
2613
|
+
adoptPage(stateDir, page, tab);
|
|
2614
|
+
for (const old of local) await old.close().catch(quiet("agent/computer/browser"));
|
|
2615
|
+
if (address) await page.goto(address, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(quiet("agent/computer/browser"));
|
|
2616
|
+
lifecycle("browser.cloud.tab", { moved: "to-cloud" });
|
|
2617
|
+
return { page, moved: true };
|
|
2618
|
+
}
|
|
2619
|
+
async function moveTabToLocal(stateDir, tab) {
|
|
2620
|
+
if (await browserProvider(stateDir) === "browser-use") throw new Error("Browser Use Cloud is selected for every tab. The user switches back with `clikcode computer browser-use off` or `auto`.");
|
|
2621
|
+
const key = ownerKey(stateDir, tab);
|
|
2622
|
+
const pages = owned.get(key) ?? [];
|
|
2623
|
+
const cloud = pages.filter((page2) => cloudPages.has(page2));
|
|
2624
|
+
if (!cloudOwners.has(key) && !cloud.length) return { page: mine(stateDir, tab), moved: false, stopped: false };
|
|
2625
|
+
const front = mine(stateDir, tab);
|
|
2626
|
+
const address = front && /^https?:/i.test(front.url()) ? front.url() : void 0;
|
|
2627
|
+
owned.set(key, pages.filter((page2) => !cloudPages.has(page2)));
|
|
2628
|
+
chosen.delete(key);
|
|
2629
|
+
cloudOwners.delete(key);
|
|
2630
|
+
for (const page2 of cloud) await page2.close().catch(quiet("agent/computer/browser"));
|
|
2631
|
+
const stopped = await settleCloud(stateDir).catch(() => false);
|
|
2632
|
+
const page = await openComputerPage(stateDir, tab);
|
|
2633
|
+
if (address) await page.goto(address, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(quiet("agent/computer/browser"));
|
|
2634
|
+
lifecycle("browser.cloud.tab", { moved: "to-local", stopped });
|
|
2635
|
+
return { page, moved: true, stopped };
|
|
2636
|
+
}
|
|
2637
|
+
async function stopCloudBrowser(stateDir) {
|
|
2638
|
+
await closeCloudTabs(stateDir);
|
|
2639
|
+
cloudOwners.clear();
|
|
2640
|
+
await settleCloud(stateDir, true);
|
|
2641
|
+
}
|
|
2642
|
+
var egressOwners = sharedState("browser-egress-owners", () => /* @__PURE__ */ new Map());
|
|
2643
|
+
var egressContexts = sharedState("browser-egress-contexts", () => /* @__PURE__ */ new WeakMap());
|
|
2644
|
+
async function bindTabEgress(stateDir, tab, egress) {
|
|
2645
|
+
const key = ownerKey(stateDir, tab);
|
|
2646
|
+
const wanted = egress && egress !== "home" ? egress : void 0;
|
|
2647
|
+
if (egressOwners.get(key) === wanted) return;
|
|
2648
|
+
if (wanted) egressOwners.set(key, wanted);
|
|
2649
|
+
else egressOwners.delete(key);
|
|
2650
|
+
const stale = (owned.get(key) ?? []).filter((page) => !cloudPages.has(page) && egressOfPage(page) !== wanted);
|
|
2651
|
+
if (!stale.length) return;
|
|
2652
|
+
owned.set(key, (owned.get(key) ?? []).filter((page) => !stale.includes(page)));
|
|
2653
|
+
chosen.delete(key);
|
|
2654
|
+
for (const page of stale) await page.close().catch(quiet("agent/computer/browser"));
|
|
2655
|
+
}
|
|
2656
|
+
function tabEgress(stateDir, tab) {
|
|
2657
|
+
return egressOwners.get(ownerKey(stateDir, tab));
|
|
2658
|
+
}
|
|
2659
|
+
async function egressContext(stateDir, connected, name) {
|
|
2660
|
+
const server = await egressServer(stateDir, name);
|
|
2661
|
+
if (!server) return connected.context;
|
|
2662
|
+
let byName = egressContexts.get(connected.browser);
|
|
2663
|
+
if (!byName) {
|
|
2664
|
+
byName = /* @__PURE__ */ new Map();
|
|
2665
|
+
egressContexts.set(connected.browser, byName);
|
|
2666
|
+
}
|
|
2667
|
+
const current = byName.get(name);
|
|
2668
|
+
if (current) {
|
|
2669
|
+
const held2 = await current.catch(quiet("agent/computer/browser"));
|
|
2670
|
+
if (held2 && held2.server === server) return held2.context;
|
|
2671
|
+
if (byName.get(name) !== current) return egressContext(stateDir, connected, name);
|
|
2672
|
+
if (held2) void held2.context.close().catch(quiet("agent/computer/browser"));
|
|
2673
|
+
}
|
|
2674
|
+
const map = byName;
|
|
2675
|
+
const opening = connected.browser.newContext({ proxy: { server } }).then((context) => {
|
|
2676
|
+
contextEgress.set(context, name);
|
|
2677
|
+
context.on("close", () => {
|
|
2678
|
+
if (map.get(name) === opening) map.delete(name);
|
|
2679
|
+
});
|
|
2680
|
+
lifecycle("browser.egress.context", { egress: name });
|
|
2681
|
+
return { context, server };
|
|
2682
|
+
});
|
|
2683
|
+
map.set(name, opening);
|
|
2684
|
+
opening.catch(() => {
|
|
2685
|
+
if (map.get(name) === opening) map.delete(name);
|
|
2686
|
+
});
|
|
2687
|
+
return (await opening).context;
|
|
2688
|
+
}
|
|
2689
|
+
async function pageInHostedContext(connected, browserContextId, ms = 15e3) {
|
|
2690
|
+
const session = await connected.browser.newBrowserCDPSession();
|
|
2691
|
+
const fresh = [];
|
|
2692
|
+
const onPage = (page) => {
|
|
2693
|
+
fresh.push(page);
|
|
2694
|
+
};
|
|
2695
|
+
connected.context.on("page", onPage);
|
|
2696
|
+
try {
|
|
2697
|
+
const before = new Set(connected.context.pages());
|
|
2698
|
+
const { targetId: targetId2 } = await session.send("Target.createTarget", { url: "about:blank", browserContextId });
|
|
2699
|
+
const ids = /* @__PURE__ */ new Map();
|
|
2700
|
+
for (const until = Date.now() + ms; Date.now() < until; await sleep(50)) {
|
|
2701
|
+
for (const page of /* @__PURE__ */ new Set([...fresh, ...connected.context.pages().filter((page2) => !before.has(page2))])) {
|
|
2702
|
+
if (!ids.has(page)) ids.set(page, targetIdOf(page));
|
|
2703
|
+
if (await ids.get(page) === targetId2) return page;
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
await session.send("Target.closeTarget", { targetId: targetId2 }).catch(quiet("agent/computer/browser"));
|
|
2707
|
+
throw new Error("The egress tab did not open in time.");
|
|
2708
|
+
} finally {
|
|
2709
|
+
connected.context.off("page", onPage);
|
|
2710
|
+
await session.detach().catch(quiet("agent/computer/browser"));
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
async function newTabPage(stateDir, connected, egress) {
|
|
2714
|
+
if (!egress) return connected.context.newPage();
|
|
2715
|
+
try {
|
|
2716
|
+
const hosted = await requestHostedContext(stateDir, egress);
|
|
2717
|
+
const page = await pageInHostedContext(connected, hosted.id);
|
|
2718
|
+
pageEgress.set(page, egress);
|
|
2719
|
+
return page;
|
|
2720
|
+
} catch (error) {
|
|
2721
|
+
if (!(error instanceof EgressNotServed)) throw error;
|
|
2722
|
+
lifecycle("browser.egress.unserved", { egress });
|
|
2723
|
+
return (await egressContext(stateDir, connected, egress)).newPage();
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
var chosen = sharedState("browser-chosen", () => /* @__PURE__ */ new Map());
|
|
2727
|
+
function mine(stateDir, tab) {
|
|
2728
|
+
const key = ownerKey(stateDir, tab);
|
|
2729
|
+
const stack = (owned.get(key) ?? []).filter((page) => !page.isClosed());
|
|
2730
|
+
owned.set(key, stack);
|
|
2731
|
+
const picked = chosen.get(key);
|
|
2732
|
+
if (picked && stack.includes(picked)) return picked;
|
|
2733
|
+
chosen.delete(key);
|
|
2734
|
+
return stack.at(-1);
|
|
2735
|
+
}
|
|
2736
|
+
var holders = sharedState("browser-holders", () => /* @__PURE__ */ new WeakMap());
|
|
2737
|
+
var arrived = sharedState("browser-arrived", () => /* @__PURE__ */ new Map());
|
|
2738
|
+
function followOpenedTabs(page) {
|
|
2739
|
+
page.on("popup", (popup) => {
|
|
2740
|
+
const holder = holders.get(page);
|
|
2741
|
+
if (!holder) return;
|
|
2742
|
+
const key = ownerKey(holder.stateDir, holder.tab);
|
|
2743
|
+
if (!(owned.get(key) ?? []).includes(page)) return;
|
|
2744
|
+
adoptPage(holder.stateDir, popup, holder.tab);
|
|
2745
|
+
arrived.set(key, [...arrived.get(key) ?? [], popup]);
|
|
2746
|
+
});
|
|
2747
|
+
}
|
|
2748
|
+
function arrivedPages(stateDir, tab, take = true) {
|
|
2749
|
+
const key = ownerKey(stateDir, tab);
|
|
2750
|
+
const pages = (arrived.get(key) ?? []).filter((page) => !page.isClosed());
|
|
2751
|
+
if (take) arrived.delete(key);
|
|
2752
|
+
return pages;
|
|
2753
|
+
}
|
|
2754
|
+
function adoptPage(stateDir, page, tab) {
|
|
2755
|
+
if (!holders.has(page)) followOpenedTabs(page);
|
|
2756
|
+
holders.set(page, { stateDir, ...tab ? { tab } : {} });
|
|
2757
|
+
if (!cloudPages.has(page) && (owned.get(ownerKey(stateDir, tab)) ?? []).some((other) => cloudPages.has(other) && other.context() === page.context())) cloudPages.add(page);
|
|
2758
|
+
const bound = egressOwners.get(ownerKey(stateDir, tab));
|
|
2759
|
+
if (bound && !cloudPages.has(page) && !egressOfPage(page)) pageEgress.set(page, bound);
|
|
2760
|
+
watchDownloads(page, stateDir);
|
|
2761
|
+
watchDialogs(page);
|
|
2762
|
+
const key = ownerKey(stateDir, tab);
|
|
2763
|
+
owned.set(key, [...(owned.get(key) ?? []).filter((old) => old !== page), page]);
|
|
2764
|
+
chosen.delete(key);
|
|
2765
|
+
watchConsole(page);
|
|
2766
|
+
if (cloudPages.has(page)) cloudUsedAt.set(stateDir, Date.now());
|
|
2767
|
+
else holdTab(stateDir, page, tab);
|
|
2768
|
+
}
|
|
2769
|
+
var held = sharedState("browser-held", () => /* @__PURE__ */ new WeakMap());
|
|
2770
|
+
var WRITE_EVERY_MS = 5e3;
|
|
2771
|
+
var SWEEP_EVERY_MS = 6e4;
|
|
2772
|
+
var lastSweep = sharedState("browser-last-sweep", () => /* @__PURE__ */ new Map());
|
|
2773
|
+
var ownerLabel = () => `worker ${process.pid}${process.env.CLIKCODE_SESSION_ID ? ` (session ${process.env.CLIKCODE_SESSION_ID.slice(0, 8)})` : ""}`;
|
|
2774
|
+
function targetIdOf(page) {
|
|
2775
|
+
return (async () => {
|
|
2776
|
+
const session = await page.context().newCDPSession(page);
|
|
2777
|
+
try {
|
|
2778
|
+
return (await session.send("Target.getTargetInfo")).targetInfo.targetId;
|
|
2779
|
+
} finally {
|
|
2780
|
+
await session.detach().catch(quiet("agent/computer/browser"));
|
|
2781
|
+
}
|
|
2782
|
+
})().catch(quiet("agent/computer/browser"));
|
|
2783
|
+
}
|
|
2784
|
+
async function flushHeld(stateDir, page, entry, force) {
|
|
2785
|
+
const now = Date.now();
|
|
2786
|
+
if (!force && now - entry.written < WRITE_EVERY_MS) return;
|
|
2787
|
+
entry.written = now;
|
|
2788
|
+
const id = await entry.id;
|
|
2789
|
+
if (!id) return;
|
|
2790
|
+
const record = {
|
|
2791
|
+
id,
|
|
2792
|
+
...entry.tab ? { tab: entry.tab } : {},
|
|
2793
|
+
ownerPid: entry.parked ? 0 : process.pid,
|
|
2794
|
+
owner: entry.parked ? `parked by ${ownerLabel()}` : ownerLabel(),
|
|
2795
|
+
openedAt: entry.openedAt,
|
|
2796
|
+
lastUsedAt: entry.lastUsedAt,
|
|
2797
|
+
...page.isClosed() ? {} : { url: page.url() },
|
|
2798
|
+
...entry.parked ? { parked: true } : {},
|
|
2799
|
+
...egressOfPage(page) ? { egress: egressOfPage(page) } : {}
|
|
2800
|
+
};
|
|
2801
|
+
await writeTabRecord(stateDir, record);
|
|
2802
|
+
}
|
|
2803
|
+
function holdTab(stateDir, page, tab) {
|
|
2804
|
+
const now = Date.now();
|
|
2805
|
+
const entry = held.get(page) ?? { id: targetIdOf(page), openedAt: now, lastUsedAt: now, written: 0, parked: false };
|
|
2806
|
+
entry.lastUsedAt = now;
|
|
2807
|
+
entry.parked = false;
|
|
2808
|
+
if (tab) entry.tab = tab;
|
|
2809
|
+
else delete entry.tab;
|
|
2810
|
+
held.set(page, entry);
|
|
2811
|
+
void flushHeld(stateDir, page, entry, true).catch(quiet("agent/computer/browser"));
|
|
2812
|
+
}
|
|
2813
|
+
function touchTab(stateDir, page) {
|
|
2814
|
+
if (cloudPages.has(page)) {
|
|
2815
|
+
cloudUsedAt.set(stateDir, Date.now());
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
const entry = held.get(page);
|
|
2819
|
+
if (entry) {
|
|
2820
|
+
entry.lastUsedAt = Date.now();
|
|
2821
|
+
void flushHeld(stateDir, page, entry, false).catch(quiet("agent/computer/browser"));
|
|
2822
|
+
}
|
|
2823
|
+
const now = Date.now();
|
|
2824
|
+
if (now - (lastSweep.get(stateDir) ?? 0) < SWEEP_EVERY_MS) return;
|
|
2825
|
+
lastSweep.set(stateDir, now);
|
|
2826
|
+
void sweepTabs(stateDir).catch(quiet("agent/computer/browser"));
|
|
2827
|
+
}
|
|
2828
|
+
async function claimRestored(stateDir, context, tab, egress) {
|
|
2829
|
+
if (!tab) return void 0;
|
|
2830
|
+
const record = (await readTabRecords(stateDir)).find((item) => item.restoreFor === tab && item.ownerPid === 0 && item.egress === egress);
|
|
2831
|
+
if (!record) return void 0;
|
|
2832
|
+
for (const page of context.pages()) {
|
|
2833
|
+
if (page.isClosed() || await targetIdOf(page) !== record.id) continue;
|
|
2834
|
+
adoptPage(stateDir, page, tab);
|
|
2835
|
+
return page;
|
|
2836
|
+
}
|
|
2837
|
+
return void 0;
|
|
2838
|
+
}
|
|
2839
|
+
function ownedPages(stateDir, tab) {
|
|
2840
|
+
const current = mine(stateDir, tab);
|
|
2841
|
+
return { pages: [...owned.get(ownerKey(stateDir, tab)) ?? []], current };
|
|
2842
|
+
}
|
|
2843
|
+
async function focusOwnedPage(stateDir, page, tab) {
|
|
2844
|
+
const key = ownerKey(stateDir, tab);
|
|
2845
|
+
if (!(owned.get(key) ?? []).includes(page) || page.isClosed()) throw new Error("That tab is not one of this chat's open tabs.");
|
|
2846
|
+
chosen.set(key, page);
|
|
2847
|
+
await page.bringToFront().catch(quiet("agent/computer/browser"));
|
|
2848
|
+
}
|
|
2849
|
+
async function closeOwnedPage(stateDir, page, tab) {
|
|
2850
|
+
const key = ownerKey(stateDir, tab);
|
|
2851
|
+
if (!(owned.get(key) ?? []).includes(page)) throw new Error("That tab is not one of this chat's open tabs.");
|
|
2852
|
+
owned.set(key, (owned.get(key) ?? []).filter((old) => old !== page));
|
|
2853
|
+
await page.close().catch(quiet("agent/computer/browser"));
|
|
2854
|
+
if (cloudPages.has(page)) await settleCloud(stateDir).catch(quiet("agent/computer/browser"));
|
|
2855
|
+
}
|
|
2856
|
+
async function openNewComputerPage(stateDir, tab) {
|
|
2857
|
+
const cloud = await onCloud(stateDir, tab);
|
|
2858
|
+
const connected = await browserFor(stateDir, true, cloud);
|
|
2859
|
+
const page = await newTabPage(stateDir, connected, cloud ? void 0 : egressOwners.get(ownerKey(stateDir, tab)));
|
|
2860
|
+
if (cloud) cloudPages.add(page);
|
|
2861
|
+
adoptPage(stateDir, page, tab);
|
|
2862
|
+
touchTab(stateDir, page);
|
|
2863
|
+
return page;
|
|
2864
|
+
}
|
|
2865
|
+
async function recoverComputerPage(stateDir, page, tab) {
|
|
2866
|
+
const address = page.url();
|
|
2867
|
+
const within = (work, ms) => new Promise((resolve, reject) => {
|
|
2868
|
+
const timer = setTimeout(() => reject(new Error("recover timed out")), ms);
|
|
2869
|
+
work.then((value) => {
|
|
2870
|
+
clearTimeout(timer);
|
|
2871
|
+
resolve(value);
|
|
2872
|
+
}, (error) => {
|
|
2873
|
+
clearTimeout(timer);
|
|
2874
|
+
reject(error);
|
|
2875
|
+
});
|
|
2876
|
+
});
|
|
2877
|
+
try {
|
|
2878
|
+
await within(page.reload({ timeout: 8e3, waitUntil: "domcontentloaded" }), 1e4);
|
|
2879
|
+
return page;
|
|
2880
|
+
} catch {
|
|
2881
|
+
const fresh = await openNewComputerPage(stateDir, tab);
|
|
2882
|
+
if (/^https?:/i.test(address)) await within(fresh.goto(address, { timeout: 8e3, waitUntil: "domcontentloaded" }), 1e4).catch(quiet("agent/computer/browser"));
|
|
2883
|
+
void page.close({ runBeforeUnload: false }).catch(quiet("agent/computer/browser"));
|
|
2884
|
+
return fresh;
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
async function openComputerPage(stateDir, tab) {
|
|
2888
|
+
const cloud = await onCloud(stateDir, tab);
|
|
2889
|
+
const connected = await browserFor(stateDir, true, cloud);
|
|
2890
|
+
const egress = cloud ? void 0 : egressOwners.get(ownerKey(stateDir, tab));
|
|
2891
|
+
const existing = mine(stateDir, tab) ?? (cloud ? void 0 : await claimRestored(stateDir, connected.context, tab, egress));
|
|
2892
|
+
if (existing) {
|
|
2893
|
+
touchTab(stateDir, existing);
|
|
2894
|
+
return existing;
|
|
2895
|
+
}
|
|
2896
|
+
const page = await newTabPage(stateDir, connected, egress);
|
|
2897
|
+
if (cloud) cloudPages.add(page);
|
|
2898
|
+
adoptPage(stateDir, page, tab);
|
|
2899
|
+
touchTab(stateDir, page);
|
|
2900
|
+
return page;
|
|
2901
|
+
}
|
|
2902
|
+
async function computerPage(stateDir, tab) {
|
|
2903
|
+
const cloud = await onCloud(stateDir, tab);
|
|
2904
|
+
const { context } = await browserFor(stateDir, false, cloud);
|
|
2905
|
+
const page = mine(stateDir, tab) ?? (cloud ? void 0 : await claimRestored(stateDir, context, tab, egressOwners.get(ownerKey(stateDir, tab))));
|
|
2906
|
+
if (page) touchTab(stateDir, page);
|
|
2907
|
+
if (!page) throw new Error("This chat has no open tab. Open a URL with browser_use first.");
|
|
2908
|
+
return page;
|
|
2909
|
+
}
|
|
2910
|
+
async function frontComputerPage(stateDir) {
|
|
2911
|
+
const { context } = await browserFor(stateDir, false, await browserProvider(stateDir) === "browser-use");
|
|
2912
|
+
const open = context.pages().filter((page2) => !page2.isClosed());
|
|
2913
|
+
for (const page2 of open.reverse()) {
|
|
2914
|
+
try {
|
|
2915
|
+
if (await page2.evaluate(() => globalThis.document.visibilityState === "visible")) return page2;
|
|
2916
|
+
} catch {
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
const page = open[0];
|
|
2920
|
+
if (!page) throw new Error("ClikCode browser has no open tab.");
|
|
2921
|
+
return page;
|
|
2922
|
+
}
|
|
2923
|
+
async function computerBrowserPids(stateDir) {
|
|
2924
|
+
try {
|
|
2925
|
+
const { browser } = await browserFor(stateDir, false);
|
|
2926
|
+
const session = await browser.newBrowserCDPSession();
|
|
2927
|
+
try {
|
|
2928
|
+
const { processInfo } = await session.send("SystemInfo.getProcessInfo");
|
|
2929
|
+
return processInfo.map((info) => info.id).filter((id) => Number.isSafeInteger(id) && id > 0);
|
|
2930
|
+
} finally {
|
|
2931
|
+
await session.detach().catch(quiet("agent/computer/browser"));
|
|
2932
|
+
}
|
|
2933
|
+
} catch {
|
|
2934
|
+
return void 0;
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
async function allComputerPages(stateDir) {
|
|
2938
|
+
const { context } = await browserFor(stateDir, false, await browserProvider(stateDir) === "browser-use");
|
|
2939
|
+
return context.pages().filter((page) => !page.isClosed());
|
|
2940
|
+
}
|
|
2941
|
+
async function notDeskHeld(stateDir, pages) {
|
|
2942
|
+
const heldIds = await deskHeldTargets(stateDir).catch(() => /* @__PURE__ */ new Set());
|
|
2943
|
+
if (!heldIds.size) return [...pages];
|
|
2944
|
+
const free = [];
|
|
2945
|
+
for (const page of pages) {
|
|
2946
|
+
if (page.isClosed()) continue;
|
|
2947
|
+
const id = await targetIdOf(page).catch(quiet("agent/computer/browser"));
|
|
2948
|
+
if (!id || !heldIds.has(id)) free.push(page);
|
|
2949
|
+
}
|
|
2950
|
+
return free;
|
|
2951
|
+
}
|
|
2952
|
+
async function putTabOnDesk(stateDir, tab, input) {
|
|
2953
|
+
const info = await readDeskInfo(stateDir);
|
|
2954
|
+
const page = mine(stateDir, tab);
|
|
2955
|
+
if (!info || !page || page.isClosed() || cloudPages.has(page)) return void 0;
|
|
2956
|
+
const targetId2 = await targetIdOf(page).catch(quiet("agent/computer/browser"));
|
|
2957
|
+
if (!targetId2) return void 0;
|
|
2958
|
+
const item = await addDeskItem(stateDir, { targetId: targetId2, url: page.url(), ...input });
|
|
2959
|
+
return { item, address: deskItemAddress(info, item.id) };
|
|
2960
|
+
}
|
|
2961
|
+
async function closeComputerPage(stateDir, tab) {
|
|
2962
|
+
const key = ownerKey(stateDir, tab);
|
|
2963
|
+
const pages = owned.get(key) ?? [];
|
|
2964
|
+
owned.delete(key);
|
|
2965
|
+
chosen.delete(key);
|
|
2966
|
+
for (const page of await notDeskHeld(stateDir, pages)) await page.close().catch(quiet("agent/computer/browser"));
|
|
2967
|
+
cloudOwners.delete(key);
|
|
2968
|
+
if (pages.some((page) => cloudPages.has(page))) await settleCloud(stateDir).catch(quiet("agent/computer/browser"));
|
|
2969
|
+
if (tab) await closeTabsByLabel(stateDir, tab).catch(quiet("agent/computer/browser"));
|
|
2970
|
+
}
|
|
2971
|
+
async function closeAllOwnedPages(stateDir) {
|
|
2972
|
+
const all = owned;
|
|
2973
|
+
for (const key of [...all.keys()]) {
|
|
2974
|
+
if (key !== stateDir && !key.startsWith(`${stateDir}\0`)) continue;
|
|
2975
|
+
const pages = all.get(key) ?? [];
|
|
2976
|
+
all.delete(key);
|
|
2977
|
+
chosen.delete(key);
|
|
2978
|
+
for (const page of await notDeskHeld(stateDir, pages)) await page.close().catch(quiet("agent/computer/browser"));
|
|
2979
|
+
cloudOwners.delete(key);
|
|
2980
|
+
}
|
|
2981
|
+
await settleCloud(stateDir).catch(quiet("agent/computer/browser"));
|
|
2982
|
+
await closeTabsOfOwner(stateDir, process.pid).catch(quiet("agent/computer/browser"));
|
|
2983
|
+
}
|
|
2984
|
+
async function parkComputerPage(stateDir, tab, marker) {
|
|
2985
|
+
const page = mine(stateDir, tab);
|
|
2986
|
+
if (!page) return false;
|
|
2987
|
+
const marked = await page.evaluate((name) => {
|
|
2988
|
+
globalThis.name = name;
|
|
2989
|
+
return true;
|
|
2990
|
+
}, marker).catch(() => false);
|
|
2991
|
+
owned.delete(ownerKey(stateDir, tab));
|
|
2992
|
+
const entry = held.get(page);
|
|
2993
|
+
if (entry) {
|
|
2994
|
+
entry.parked = true;
|
|
2995
|
+
entry.lastUsedAt = Date.now();
|
|
2996
|
+
await flushHeld(stateDir, page, entry, true).catch(quiet("agent/computer/browser"));
|
|
2997
|
+
}
|
|
2998
|
+
return marked;
|
|
2999
|
+
}
|
|
3000
|
+
async function reattachParkedPage(stateDir, tab, marker) {
|
|
3001
|
+
const connected = await browserFor(stateDir, false, await browserProvider(stateDir) === "browser-use").catch(quiet("agent/computer/browser"));
|
|
3002
|
+
if (!connected) return void 0;
|
|
3003
|
+
const egressPages = [...egressContexts.get(connected.browser)?.values() ?? []];
|
|
3004
|
+
const others = (await Promise.all(egressPages.map((opening) => opening.then((held2) => held2.context.pages(), () => [])))).flat();
|
|
3005
|
+
for (const page of [...connected.context.pages(), ...others]) {
|
|
3006
|
+
if (page.isClosed()) continue;
|
|
3007
|
+
const name = await page.evaluate(() => globalThis.name).catch(quiet("agent/computer/browser"));
|
|
3008
|
+
if (name === marker) {
|
|
3009
|
+
adoptPage(stateDir, page, tab);
|
|
3010
|
+
return page;
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
3013
|
+
return void 0;
|
|
3014
|
+
}
|
|
3015
|
+
async function closeParkedPage(stateDir, marker) {
|
|
3016
|
+
const page = await reattachParkedPage(stateDir, `parked-close-${marker}`, marker);
|
|
3017
|
+
if (page) await page.close().catch(quiet("agent/computer/browser"));
|
|
3018
|
+
owned.delete(ownerKey(stateDir, `parked-close-${marker}`));
|
|
3019
|
+
}
|
|
3020
|
+
async function releaseComputerBrowser(stateDir) {
|
|
3021
|
+
await closeCloudTabs(stateDir);
|
|
3022
|
+
await settleCloud(stateDir).catch(quiet("agent/computer/browser"));
|
|
3023
|
+
const cloud = running.get(cloudRunKey(stateDir));
|
|
3024
|
+
running.delete(cloudRunKey(stateDir));
|
|
3025
|
+
await (await cloud?.catch(quiet("agent/computer/browser")))?.browser.close().catch(quiet("agent/computer/browser"));
|
|
3026
|
+
owned.delete(stateDir);
|
|
3027
|
+
const opening = running.get(stateDir);
|
|
3028
|
+
running.delete(stateDir);
|
|
3029
|
+
await (await opening?.catch(quiet("agent/computer/browser")))?.browser.close().catch(quiet("agent/computer/browser"));
|
|
3030
|
+
}
|
|
3031
|
+
async function closeComputerBrowser(stateDir) {
|
|
3032
|
+
await stopCloudBrowser(stateDir).catch(quiet("agent/computer/browser"));
|
|
3033
|
+
owned.delete(stateDir);
|
|
3034
|
+
const opening = running.get(stateDir);
|
|
3035
|
+
running.delete(stateDir);
|
|
3036
|
+
const connected = await opening?.catch(quiet("agent/computer/browser"));
|
|
3037
|
+
await connected?.browser.close().catch(quiet("agent/computer/browser"));
|
|
3038
|
+
try {
|
|
3039
|
+
const record = JSON.parse(await fs4.readFile(computerHostFile(stateDir), "utf8"));
|
|
3040
|
+
if (Number.isSafeInteger(record.pid) && record.pid > 1) {
|
|
3041
|
+
process.kill(record.pid, "SIGTERM");
|
|
3042
|
+
for (let waited = 0; waited < 5e3 && pidIsAlive(record.pid); waited += 100) await sleep(100);
|
|
3043
|
+
}
|
|
3044
|
+
} catch {
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
async function throwawayComputerPage(stateDir) {
|
|
3048
|
+
const { context } = await browserFor(stateDir, true, await browserProvider(stateDir) === "browser-use");
|
|
3049
|
+
return context.newPage();
|
|
3050
|
+
}
|
|
3051
|
+
function hiddenDisplayCommand(command, env = process.env, platform = process.platform, hasXvfb = () => whichSync("xvfb-run"), options = {}) {
|
|
3052
|
+
if (platform !== "linux" || /^(?:1|true|yes|on)$/i.test(env.CLIKCODE_BROWSER_HEADLESS ?? "")) return command;
|
|
3053
|
+
if (env.CLIKCODE_BROWSER_VISIBLE === "1" || options.display === "visible") {
|
|
3054
|
+
const session = desktopSession({ env, platform, ...options.socketExists ? { socketExists: options.socketExists } : {} });
|
|
3055
|
+
if (session) return Object.keys(session).length ? ["env", "-u", VIRTUAL_DISPLAY_ENV, ...Object.entries(session).map(([name, value]) => `${name}=${value}`), ...command] : command;
|
|
3056
|
+
options.onFallback?.();
|
|
3057
|
+
}
|
|
3058
|
+
if (!hasXvfb()) return command;
|
|
3059
|
+
return ["env", "-u", "WAYLAND_DISPLAY", `${VIRTUAL_DISPLAY_ENV}=1`, "xvfb-run", "-a", "-s", "-screen 0 1440x900x24", ...command];
|
|
3060
|
+
}
|
|
3061
|
+
function whichSync(name) {
|
|
3062
|
+
return (process.env.PATH ?? "").split(path4.delimiter).some((dir) => {
|
|
3063
|
+
try {
|
|
3064
|
+
accessSync(path4.join(dir, name), fsConstants2.X_OK);
|
|
3065
|
+
return true;
|
|
3066
|
+
} catch {
|
|
3067
|
+
return false;
|
|
3068
|
+
}
|
|
3069
|
+
});
|
|
3070
|
+
}
|
|
3071
|
+
|
|
3072
|
+
// src/agent/computer/handoff-serve.ts
|
|
3073
|
+
import { randomBytes, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
3074
|
+
import { createServer as createServer3 } from "node:http";
|
|
3075
|
+
function sameToken2(a, b) {
|
|
3076
|
+
return a.length === b.length && timingSafeEqual2(Buffer.from(a), Buffer.from(b));
|
|
3077
|
+
}
|
|
3078
|
+
function sameOrigin2(origin, host) {
|
|
3079
|
+
if (origin === void 0) return true;
|
|
3080
|
+
try {
|
|
3081
|
+
return new URL(origin).host === host;
|
|
3082
|
+
} catch {
|
|
3083
|
+
return false;
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
async function serveLiveView(input) {
|
|
3087
|
+
const token = randomBytes(24).toString("base64url");
|
|
3088
|
+
const watch = input.watch === true;
|
|
3089
|
+
const active = () => {
|
|
3090
|
+
input.onActivity?.();
|
|
3091
|
+
};
|
|
3092
|
+
let over = false;
|
|
3093
|
+
let current;
|
|
3094
|
+
let own = "";
|
|
3095
|
+
const pathOf = (request) => {
|
|
3096
|
+
const [, first, rest] = /^\/([^/?]+)(\/[^?]*)?/.exec(request.url ?? "/") ?? [];
|
|
3097
|
+
return { ...first ? { first } : {}, ...rest ? { rest } : {} };
|
|
3098
|
+
};
|
|
3099
|
+
const allowed = (request) => {
|
|
3100
|
+
const { first } = pathOf(request);
|
|
3101
|
+
return Boolean(first) && sameToken2(first, token) && (!input.ownHostOnly || request.headers.host === own);
|
|
3102
|
+
};
|
|
3103
|
+
const server = createServer3((request, response) => {
|
|
3104
|
+
const { rest } = pathOf(request);
|
|
3105
|
+
if (!allowed(request)) {
|
|
3106
|
+
response.writeHead(404).end();
|
|
3107
|
+
return;
|
|
3108
|
+
}
|
|
3109
|
+
if (over) {
|
|
3110
|
+
response.writeHead(410).end();
|
|
3111
|
+
return;
|
|
3112
|
+
}
|
|
3113
|
+
response.setHeader("cache-control", "no-store");
|
|
3114
|
+
if (request.method === "GET" && rest === "/ping") {
|
|
3115
|
+
response.writeHead(204).end();
|
|
3116
|
+
return;
|
|
3117
|
+
}
|
|
3118
|
+
if (request.method === "GET" && (!rest || rest === "/")) {
|
|
3119
|
+
const host = request.headers.host ?? "";
|
|
3120
|
+
const origin = /^[\w.:[\]-]{1,80}$/.test(host) ? ` ws://${host}` : "";
|
|
3121
|
+
response.writeHead(200, {
|
|
3122
|
+
"content-type": "text/html; charset=utf-8",
|
|
3123
|
+
"content-security-policy": `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src blob: data:; connect-src 'self'${origin}`
|
|
3124
|
+
}).end(handoffPage({ watch }));
|
|
3125
|
+
active();
|
|
3126
|
+
return;
|
|
3127
|
+
}
|
|
3128
|
+
response.writeHead(404).end();
|
|
3129
|
+
});
|
|
3130
|
+
server.on("upgrade", (request, socket, head) => {
|
|
3131
|
+
if (!allowed(request) || pathOf(request).rest !== "/live") {
|
|
3132
|
+
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
|
|
3133
|
+
return;
|
|
3134
|
+
}
|
|
3135
|
+
if (over) {
|
|
3136
|
+
socket.end("HTTP/1.1 410 Gone\r\nConnection: close\r\n\r\n");
|
|
3137
|
+
return;
|
|
3138
|
+
}
|
|
3139
|
+
const accepted = acceptWebSocket(request, socket, head, { allowOrigin: (origin) => sameOrigin2(origin, request.headers.host) });
|
|
3140
|
+
if (!accepted) return;
|
|
3141
|
+
void (async () => {
|
|
3142
|
+
const before = current;
|
|
3143
|
+
current = void 0;
|
|
3144
|
+
before?.socket.close(1e3);
|
|
3145
|
+
await before?.view.stop();
|
|
3146
|
+
const page = await input.page();
|
|
3147
|
+
const view = new LiveView(page, accepted, () => {
|
|
3148
|
+
if (watch) return;
|
|
3149
|
+
over = true;
|
|
3150
|
+
if (!accepted.closed) accepted.send(JSON.stringify({ t: "done" }));
|
|
3151
|
+
input.onDone?.();
|
|
3152
|
+
}, active, { watch });
|
|
3153
|
+
current = { socket: accepted, view, page };
|
|
3154
|
+
accepted.onClose(() => {
|
|
3155
|
+
if (current?.socket === accepted) current = void 0;
|
|
3156
|
+
});
|
|
3157
|
+
if (watch) page.once("close", () => accepted.close(1001));
|
|
3158
|
+
active();
|
|
3159
|
+
await view.start();
|
|
3160
|
+
})().catch((error) => {
|
|
3161
|
+
quiet("agent/computer/handoff-serve")(error);
|
|
3162
|
+
accepted.close(1011);
|
|
3163
|
+
});
|
|
3164
|
+
});
|
|
3165
|
+
await new Promise((resolve, reject) => {
|
|
3166
|
+
server.once("error", reject);
|
|
3167
|
+
server.listen(0, input.host, () => {
|
|
3168
|
+
server.off("error", reject);
|
|
3169
|
+
resolve();
|
|
3170
|
+
});
|
|
3171
|
+
});
|
|
3172
|
+
if (watch) server.unref();
|
|
3173
|
+
own = `${input.host}:${server.address().port}`;
|
|
3174
|
+
return {
|
|
3175
|
+
address: `http://${own}/${token}/`,
|
|
3176
|
+
viewing: () => current && !current.socket.closed ? current.page : void 0,
|
|
3177
|
+
reconnect: () => {
|
|
3178
|
+
current?.socket.close(1001);
|
|
3179
|
+
},
|
|
3180
|
+
end: () => {
|
|
3181
|
+
over = true;
|
|
3182
|
+
},
|
|
3183
|
+
async stop() {
|
|
3184
|
+
over = true;
|
|
3185
|
+
const last = current;
|
|
3186
|
+
current = void 0;
|
|
3187
|
+
await sleep(60);
|
|
3188
|
+
last?.socket.close(1e3);
|
|
3189
|
+
await last?.view.stop();
|
|
3190
|
+
server.close();
|
|
3191
|
+
server.closeAllConnections();
|
|
3192
|
+
}
|
|
3193
|
+
};
|
|
3194
|
+
}
|
|
3195
|
+
|
|
3196
|
+
// src/agent/computer/tailnet-handoff.ts
|
|
3197
|
+
var IDLE_LIMIT = 10 * 6e4;
|
|
3198
|
+
var inTailscaleRange = (address) => {
|
|
3199
|
+
const [a, b] = address.split(".").map(Number);
|
|
3200
|
+
return a === 100 && b >= 64 && b <= 127;
|
|
3201
|
+
};
|
|
3202
|
+
function tailnetAddress(interfaces = networkInterfaces(), confirmed) {
|
|
3203
|
+
let byName;
|
|
3204
|
+
let byConfirmed;
|
|
3205
|
+
for (const [name, list] of Object.entries(interfaces)) {
|
|
3206
|
+
for (const entry of list ?? []) {
|
|
3207
|
+
if (entry.family !== "IPv4" || entry.internal || !inTailscaleRange(entry.address)) continue;
|
|
3208
|
+
if (/^tailscale/i.test(name)) byName ??= entry.address;
|
|
3209
|
+
if (confirmed && entry.address === confirmed) byConfirmed ??= entry.address;
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
return byConfirmed ?? byName;
|
|
3213
|
+
}
|
|
3214
|
+
async function tailscaleIp(signal) {
|
|
3215
|
+
const candidates = process.platform === "darwin" ? ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale"] : ["tailscale"];
|
|
3216
|
+
for (const command of candidates) {
|
|
3217
|
+
const result = await runCli(command, ["ip", "-4"], { timeoutMs: 5e3, maxChars: 1e3, ...signal ? { signal } : {} });
|
|
3218
|
+
if (result.missing) continue;
|
|
3219
|
+
const address = result.code === 0 ? result.text.split(/\s+/).find(inTailscaleRange) : void 0;
|
|
3220
|
+
if (address) return address;
|
|
3221
|
+
}
|
|
3222
|
+
return void 0;
|
|
3223
|
+
}
|
|
3224
|
+
async function findTailnetAddress(options = {}) {
|
|
3225
|
+
const interfaces = options.interfaces ?? networkInterfaces();
|
|
3226
|
+
const byName = tailnetAddress(interfaces);
|
|
3227
|
+
if (byName) return byName;
|
|
3228
|
+
const confirmed = await (options.ask ?? tailscaleIp)(options.signal).catch(quiet("agent/computer/tailnet-handoff"));
|
|
3229
|
+
return confirmed ? tailnetAddress(interfaces, confirmed) : void 0;
|
|
3230
|
+
}
|
|
3231
|
+
async function runTailnetHandoff(input) {
|
|
3232
|
+
let finish;
|
|
3233
|
+
const finished = new Promise((resolve) => {
|
|
3234
|
+
finish = resolve;
|
|
3235
|
+
});
|
|
3236
|
+
let idle;
|
|
3237
|
+
let expire;
|
|
3238
|
+
const expired = new Promise((_, reject) => {
|
|
3239
|
+
expire = reject;
|
|
3240
|
+
});
|
|
3241
|
+
expired.catch(() => void 0);
|
|
3242
|
+
const keepAlive = () => {
|
|
3243
|
+
clearTimeout(idle);
|
|
3244
|
+
idle = setTimeout(() => expire(new Error("The handoff link expired after 10 idle minutes.")), IDLE_LIMIT);
|
|
3245
|
+
};
|
|
3246
|
+
const stopped = new Promise((_, reject) => {
|
|
3247
|
+
input.signal?.addEventListener("abort", () => reject(new Error("Handoff stopped.")), { once: true });
|
|
3248
|
+
});
|
|
3249
|
+
stopped.catch(() => void 0);
|
|
3250
|
+
const server = await serveLiveView({ host: input.host, page: () => computerPage(input.stateDir, input.tab), onDone: finish, onActivity: keepAlive });
|
|
3251
|
+
try {
|
|
3252
|
+
input.onLink(server.address);
|
|
3253
|
+
keepAlive();
|
|
3254
|
+
await Promise.race([finished, expired, stopped]);
|
|
3255
|
+
} finally {
|
|
3256
|
+
clearTimeout(idle);
|
|
3257
|
+
await server.stop();
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
|
|
3261
|
+
// src/agent/computer/browser-host.ts
|
|
3262
|
+
function computerProfile(stateDir) {
|
|
3263
|
+
return path5.join(stateDir, "computer", "chrome");
|
|
3264
|
+
}
|
|
3265
|
+
function computerHostFile(stateDir) {
|
|
3266
|
+
return path5.join(stateDir, "computer", "host.json");
|
|
3267
|
+
}
|
|
3268
|
+
function hostDisplay(options) {
|
|
3269
|
+
return options.headless ? "headless" : options.virtualDisplay ? "hidden" : "visible";
|
|
3270
|
+
}
|
|
3271
|
+
async function runningHostDisplay(stateDir, alive = pidIsAlive) {
|
|
3272
|
+
try {
|
|
3273
|
+
const record = JSON.parse(await fs5.readFile(computerHostFile(stateDir), "utf8"));
|
|
3274
|
+
if (typeof record.pid !== "number" || !alive(record.pid)) return void 0;
|
|
3275
|
+
return record.display === "visible" || record.display === "hidden" || record.display === "headless" ? record.display : void 0;
|
|
3276
|
+
} catch {
|
|
3277
|
+
return void 0;
|
|
3278
|
+
}
|
|
3279
|
+
}
|
|
3280
|
+
function hostChromeArgs(options) {
|
|
3281
|
+
return [
|
|
3282
|
+
"--remote-debugging-address=127.0.0.1",
|
|
3283
|
+
"--remote-debugging-port=0",
|
|
3284
|
+
"--disable-blink-features=AutomationControlled",
|
|
3285
|
+
"--disable-features=FedCm",
|
|
3286
|
+
...options.headless ? ["--window-size=1440,900"] : [],
|
|
3287
|
+
...options.virtualDisplay && !options.headless ? ["--ozone-platform=x11", "--use-gl=angle", "--use-angle=gl-egl"] : []
|
|
3288
|
+
];
|
|
3289
|
+
}
|
|
3290
|
+
async function runComputerHost(stateDir) {
|
|
3291
|
+
const profile = computerProfile(stateDir);
|
|
3292
|
+
await fs5.mkdir(profile, { recursive: true, mode: 448 });
|
|
3293
|
+
await fs5.unlink(hostStatusFile(stateDir)).catch(quiet("agent/computer/browser-host"));
|
|
3294
|
+
await writeHostStatus(stateDir, { pid: process.pid, state: "starting" });
|
|
3295
|
+
const { chromium } = await import("playwright-core");
|
|
3296
|
+
const headless = shouldRunHeadless({ setting: await headlessSetting(stateDir) });
|
|
3297
|
+
const virtualDisplay = process.platform === "linux" && process.env[VIRTUAL_DISPLAY_ENV] === "1";
|
|
3298
|
+
const inbox = downloadsInbox(stateDir);
|
|
3299
|
+
await fs5.mkdir(inbox, { recursive: true, mode: 448 });
|
|
3300
|
+
let context;
|
|
3301
|
+
try {
|
|
3302
|
+
context = await launchComputerBrowser(chromium, profile, {
|
|
3303
|
+
headless,
|
|
3304
|
+
viewport: null,
|
|
3305
|
+
acceptDownloads: true,
|
|
3306
|
+
downloadsPath: inbox,
|
|
3307
|
+
ignoreDefaultArgs: ["--enable-automation"],
|
|
3308
|
+
args: hostChromeArgs({ headless, virtualDisplay })
|
|
3309
|
+
}, stateDir);
|
|
3310
|
+
} catch (error) {
|
|
3311
|
+
await writeHostStatus(stateDir, { pid: process.pid, state: "failed", text: error instanceof Error ? error.message : String(error) });
|
|
3312
|
+
throw error;
|
|
3313
|
+
}
|
|
3314
|
+
leaveDialogsToWorkers(context);
|
|
3315
|
+
const hostFile = computerHostFile(stateDir);
|
|
3316
|
+
const egress = await startEgressService(stateDir, profile).catch(quiet("agent/computer/browser-host"));
|
|
3317
|
+
await writeHostStatus(stateDir, { pid: process.pid, state: "running" });
|
|
3318
|
+
const record = JSON.stringify({ pid: process.pid, display: hostDisplay({ headless, virtualDisplay }), ...egress ? { egressSocket: egress.socket } : {} });
|
|
3319
|
+
try {
|
|
3320
|
+
await fs5.writeFile(hostFile, record, { mode: 384 });
|
|
3321
|
+
const stop = () => {
|
|
3322
|
+
void context.close().catch(quiet("agent/computer/browser-host"));
|
|
3323
|
+
setTimeout(() => process.exit(0), 1e4).unref();
|
|
3324
|
+
};
|
|
3325
|
+
await restoreTabs(stateDir, await takeRecycle(stateDir), {
|
|
3326
|
+
async openPage(url, egressName) {
|
|
3327
|
+
if (egressName) {
|
|
3328
|
+
if (!egress) return void 0;
|
|
3329
|
+
return egress.contexts.openPage(egressName, url);
|
|
3330
|
+
}
|
|
3331
|
+
const page = await context.newPage();
|
|
3332
|
+
const session = await context.newCDPSession(page);
|
|
3333
|
+
try {
|
|
3334
|
+
await page.goto(url, { timeout: 15e3, waitUntil: "domcontentloaded" }).catch(quiet("agent/computer/browser-host"));
|
|
3335
|
+
return (await session.send("Target.getTargetInfo")).targetInfo.targetId;
|
|
3336
|
+
} finally {
|
|
3337
|
+
await session.detach().catch(quiet("agent/computer/browser-host"));
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
}).catch(quiet("agent/computer/browser-host"));
|
|
3341
|
+
const stopJanitor = startBrowserJanitor({
|
|
3342
|
+
stateDir,
|
|
3343
|
+
hostPid: process.pid,
|
|
3344
|
+
recycle: async () => {
|
|
3345
|
+
stop();
|
|
3346
|
+
},
|
|
3347
|
+
// Still the host the workers use, and its Chrome still answers.
|
|
3348
|
+
current: async () => {
|
|
3349
|
+
const named = JSON.parse(await fs5.readFile(hostFile, "utf8").catch(() => "{}"));
|
|
3350
|
+
if (named.pid !== process.pid) return false;
|
|
3351
|
+
const page = context.pages()[0];
|
|
3352
|
+
if (!page) return true;
|
|
3353
|
+
return context.newCDPSession(page).then(async (session) => {
|
|
3354
|
+
await session.detach().catch(quiet("agent/computer/browser-host"));
|
|
3355
|
+
return true;
|
|
3356
|
+
}, () => false);
|
|
3357
|
+
},
|
|
3358
|
+
retire: () => stop()
|
|
3359
|
+
});
|
|
3360
|
+
const tailnet = await findTailnetAddress().catch(quiet("agent/computer/browser-host"));
|
|
3361
|
+
const desk = tailnet ? await startHandoffDesk({ stateDir, host: tailnet, context }).catch(quiet("agent/computer/browser-host")) : void 0;
|
|
3362
|
+
process.once("SIGTERM", stop);
|
|
3363
|
+
process.once("SIGINT", stop);
|
|
3364
|
+
await new Promise((resolve) => context.once("close", resolve));
|
|
3365
|
+
stopJanitor();
|
|
3366
|
+
await desk?.stop().catch(quiet("agent/computer/browser-host"));
|
|
3367
|
+
await egress?.stop().catch(quiet("agent/computer/browser-host"));
|
|
3368
|
+
process.off("SIGTERM", stop);
|
|
3369
|
+
process.off("SIGINT", stop);
|
|
3370
|
+
} finally {
|
|
3371
|
+
try {
|
|
3372
|
+
if (await fs5.readFile(hostFile, "utf8") === record) await fs5.unlink(hostFile);
|
|
3373
|
+
} catch {
|
|
3374
|
+
}
|
|
3375
|
+
await fs5.unlink(hostStatusFile(stateDir)).catch(quiet("agent/computer/browser-host"));
|
|
3376
|
+
await context.close().catch(quiet("agent/computer/browser-host"));
|
|
3377
|
+
}
|
|
3378
|
+
}
|
|
3379
|
+
|
|
3380
|
+
export {
|
|
3381
|
+
bindDialogs,
|
|
3382
|
+
pendingDialogNote,
|
|
3383
|
+
hasPendingDialog,
|
|
3384
|
+
answerDialog,
|
|
3385
|
+
settleWaitingDialog,
|
|
3386
|
+
withDialogs,
|
|
3387
|
+
dialogNote,
|
|
3388
|
+
withDialogNotices,
|
|
3389
|
+
serveLiveView,
|
|
3390
|
+
findTailnetAddress,
|
|
3391
|
+
runTailnetHandoff,
|
|
3392
|
+
holdDownloads,
|
|
3393
|
+
safeFileName,
|
|
3394
|
+
downloadsDir,
|
|
3395
|
+
freeName,
|
|
3396
|
+
arrivedDownload,
|
|
3397
|
+
bindDownloads,
|
|
3398
|
+
sizeText,
|
|
3399
|
+
downloadNotes,
|
|
3400
|
+
describeDownloads,
|
|
3401
|
+
computerProfile,
|
|
3402
|
+
computerHostFile,
|
|
3403
|
+
hostDisplay,
|
|
3404
|
+
runningHostDisplay,
|
|
3405
|
+
hostChromeArgs,
|
|
3406
|
+
runComputerHost,
|
|
3407
|
+
SENSITIVE,
|
|
3408
|
+
sensitiveValues,
|
|
3409
|
+
keyFieldValues,
|
|
3410
|
+
pageSecrets,
|
|
3411
|
+
findLabelledSecret,
|
|
3412
|
+
maskSensitive,
|
|
3413
|
+
credentialOnScreen,
|
|
3414
|
+
watchConsole,
|
|
3415
|
+
readConsole,
|
|
3416
|
+
parentPid,
|
|
3417
|
+
chromeIsHostChild,
|
|
3418
|
+
chromeIsOrphan,
|
|
3419
|
+
cloudIdleMs,
|
|
3420
|
+
tabIsInCloud,
|
|
3421
|
+
privateAddress,
|
|
3422
|
+
moveTabToCloud,
|
|
3423
|
+
moveTabToLocal,
|
|
3424
|
+
stopCloudBrowser,
|
|
3425
|
+
bindTabEgress,
|
|
3426
|
+
tabEgress,
|
|
3427
|
+
pageInHostedContext,
|
|
3428
|
+
arrivedPages,
|
|
3429
|
+
adoptPage,
|
|
3430
|
+
targetIdOf,
|
|
3431
|
+
ownedPages,
|
|
3432
|
+
focusOwnedPage,
|
|
3433
|
+
closeOwnedPage,
|
|
3434
|
+
openNewComputerPage,
|
|
3435
|
+
recoverComputerPage,
|
|
3436
|
+
openComputerPage,
|
|
3437
|
+
computerPage,
|
|
3438
|
+
frontComputerPage,
|
|
3439
|
+
computerBrowserPids,
|
|
3440
|
+
allComputerPages,
|
|
3441
|
+
putTabOnDesk,
|
|
3442
|
+
closeComputerPage,
|
|
3443
|
+
closeAllOwnedPages,
|
|
3444
|
+
parkComputerPage,
|
|
3445
|
+
reattachParkedPage,
|
|
3446
|
+
closeParkedPage,
|
|
3447
|
+
releaseComputerBrowser,
|
|
3448
|
+
closeComputerBrowser,
|
|
3449
|
+
throwawayComputerPage,
|
|
3450
|
+
hiddenDisplayCommand
|
|
3451
|
+
};
|