@reason-machines/cli-linux-x64 0.2.398 → 0.2.402
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/bin/reason +2 -2
- package/bin/runtime/srt/sandbox-runtime.mjs +31 -31
- package/bin/vm-hands/api-credentials-21wv0h6t.js +2 -0
- package/bin/vm-hands/api-e050y588.js +2 -0
- package/bin/vm-hands/{ask-relay-t4m6n3zq.js → ask-relay-zc05zxz4.js} +3 -3
- package/bin/vm-hands/connect-cli-npxeps2h.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-2hzektq4.js → custom-endpoint-device-z400ftnh.js} +1 -1
- package/bin/vm-hands/desktop-account-t2f1aa9e.js +2 -0
- package/bin/vm-hands/{device-workspace-1n8aaz1j.js → device-workspace-ne4269qk.js} +1 -1
- package/bin/vm-hands/hands-worker-source-8621y83c.js +2 -0
- package/bin/vm-hands/{index-58750fwy.js → index-vaq4cqv7.js} +1 -1
- package/bin/vm-hands/{install-receipt-jddye4b2.js → install-receipt-23tf4870.js} +1 -1
- package/bin/vm-hands/local-automation-541wzbef.js +2 -0
- package/bin/vm-hands/local-capabilities-ymex3mmw.js +2 -0
- package/bin/vm-hands/local-desktop-users-4n5g9c2v.js +2 -0
- package/bin/vm-hands/local-display-mac-cqfc5xnc.js +2 -0
- package/bin/vm-hands/local-display-session-7e6wqe5c.js +2 -0
- package/bin/vm-hands/local-pty-session-wyrzfc50.js +2 -0
- package/bin/vm-hands/managed-runtime-f9nnr42a.js +2 -0
- package/bin/vm-hands/{network-contract-h7dq97gc.js → network-contract-hak6865b.js} +1 -1
- package/bin/vm-hands/package-jr4xjp4y.js +2 -0
- package/bin/vm-hands/permissions-pkk45vxx.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-bexqzhq5.js → reason-hands-protocol-ane0wwzb.js} +1 -1
- package/bin/vm-hands/serve-service-fpwme38f.js +2 -0
- package/bin/vm-hands/{status-1md7695q.js → status-sf4634w4.js} +2 -2
- package/bin/vm-hands/version-98dbzrna.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ce3vtmdk.js → vm-hands-entry-lite-0badx5n8.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-k90ysszf.js → vm-hands-entry-lite-0dr3sp75.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-6ffdqdyw.js → vm-hands-entry-lite-0mk8rxqv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-z9y1sb0f.js → vm-hands-entry-lite-0tkwcetg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-shm5nhjk.js → vm-hands-entry-lite-26d4ttdx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jkcbweew.js → vm-hands-entry-lite-2grs67fz.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-n71rv7kv.js → vm-hands-entry-lite-2k459na8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fgdtrsf4.js → vm-hands-entry-lite-2yt333v3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-x64d3bdx.js → vm-hands-entry-lite-399rn7a2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fkkmhfjc.js → vm-hands-entry-lite-400hmvkg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rmaawtgm.js → vm-hands-entry-lite-8v6qhfxc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-09yt840b.js → vm-hands-entry-lite-afjzr3v2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-vz6nt5sc.js → vm-hands-entry-lite-apwve08w.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-3pecyp8y.js → vm-hands-entry-lite-arw53mkf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r67d5w6h.js → vm-hands-entry-lite-b3jmyabq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-04y4b7c6.js → vm-hands-entry-lite-b8bcnenf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bw28d85m.js → vm-hands-entry-lite-bk5acpe9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sqyf9q9z.js → vm-hands-entry-lite-c1rexgd8.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-4yw8vx5h.js → vm-hands-entry-lite-c3e25cks.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-923jmcs3.js → vm-hands-entry-lite-caxtg4j7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-xdfghcd0.js → vm-hands-entry-lite-cwd9y2pv.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-mrw8bv5s.js → vm-hands-entry-lite-dj65hfea.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hkvkfq0z.js → vm-hands-entry-lite-f28ehysx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qxx37a43.js → vm-hands-entry-lite-gbf8h13w.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-gp85aqkt.js +9 -0
- package/bin/vm-hands/{vm-hands-entry-lite-qwxmr70t.js → vm-hands-entry-lite-heehk76b.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-xz9w76j7.js → vm-hands-entry-lite-k9amte6k.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mkrwdts5.js → vm-hands-entry-lite-kaht6v11.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-0kzefw0a.js → vm-hands-entry-lite-kntkyezs.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-m7vam0j2.js +346 -0
- package/bin/vm-hands/{vm-hands-entry-lite-nsbsmrva.js → vm-hands-entry-lite-mwj7bnse.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-zxpa53zd.js → vm-hands-entry-lite-nhhpc9n2.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-h3vmfk68.js → vm-hands-entry-lite-nnrypv7q.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-g7h6wjqy.js → vm-hands-entry-lite-nqvb7a2m.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ew7amfaf.js → vm-hands-entry-lite-qg11k3bf.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mkynexaq.js → vm-hands-entry-lite-rbjky7rd.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rtt2w6c6.js → vm-hands-entry-lite-swwb5mp2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ecgyzbdp.js → vm-hands-entry-lite-wsnr4fx8.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ht482g94.js → vm-hands-entry-lite-wtc8ebkr.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-39wk67c3.js → vm-hands-entry-lite-wts79wdn.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ajmxhzs9.js → vm-hands-entry-lite-x0x1t6gp.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-x914078k.js +11 -0
- package/bin/vm-hands/{vm-hands-entry-lite-0a1ch6wx.js → vm-hands-entry-lite-x96qadgp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-saemagkr.js → vm-hands-entry-lite-xaaxvbk8.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-18kfytsa.js → vm-hands-entry-lite-ysk49bnz.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-4yw77epm.js → vm-hands-entry-lite-yz6a02cp.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-652ckfnw.js → vm-hands-executor-6bm919bz.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-zr3ajywy.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-79x8rs7b.js → vm-hands-runtime-p24enq6p.js} +3 -3
- package/bin/vm-hands/worker-sandbox-mn60tmqv.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-5fk9zhcg.js +0 -2
- package/bin/vm-hands/api-credentials-y4f0h1hq.js +0 -2
- package/bin/vm-hands/connect-cli-vq039qgz.js +0 -2
- package/bin/vm-hands/desktop-account-skdwydhn.js +0 -2
- package/bin/vm-hands/hands-worker-source-2x76smhs.js +0 -2
- package/bin/vm-hands/local-automation-azdzmmhp.js +0 -2
- package/bin/vm-hands/local-capabilities-vvpsze8k.js +0 -2
- package/bin/vm-hands/local-desktop-users-aqjt40m2.js +0 -2
- package/bin/vm-hands/local-display-mac-r6nm1tb1.js +0 -2
- package/bin/vm-hands/local-display-session-061jhxjw.js +0 -2
- package/bin/vm-hands/local-pty-session-ysfq0rq1.js +0 -2
- package/bin/vm-hands/managed-runtime-4rg0bkrp.js +0 -2
- package/bin/vm-hands/package-9c803cqw.js +0 -2
- package/bin/vm-hands/permissions-y7petg2m.js +0 -2
- package/bin/vm-hands/serve-service-bxyvbaf8.js +0 -2
- package/bin/vm-hands/version-r3x5z0dj.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-qv9j0tb5.js +0 -346
- package/bin/vm-hands/vm-hands-entry-lite-wdpx0750.js +0 -11
- package/bin/vm-hands/vm-hands-entry-lite-zd4xbqsv.js +0 -9
- package/bin/vm-hands/vm-hands-op-runner-z3fqtf7t.js +0 -2
- package/bin/vm-hands/worker-sandbox-0bwwxmxz.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Hc as uZ,Ic as lZ,Jc as T4,Kc as O4,Lc as j8,Mc as sZ}from"./vm-hands-entry-lite-fkkmhfjc.js";import{Nc as mZ,Oc as W8,Pc as e9,Qc as _0,Rc as q9,Sc as a0,Zc as F0}from"./vm-hands-entry-lite-xz9w76j7.js";import{ad as L8,bd as B8,cd as oQ}from"./vm-hands-entry-lite-39wk67c3.js";import{Ce as MZ,He as jZ,pf as y9,qf as t0,rf as O8,sf as m0,wf as C0}from"./vm-hands-entry-lite-09yt840b.js";import{Mg as oZ,Sg as Z8,Tg as n8}from"./vm-hands-entry-lite-ht482g94.js";import{Yg as q4}from"./vm-hands-entry-lite-0kzefw0a.js";import{$g as wQ,Fh as h8,Gh as w0,Hh as O0,Ih as r9,Ph as p8,Qh as OZ,Rh as WZ,ch as j9,lh as qZ,mh as CZ,oh as TZ,qh as a9,rh as VZ,sh as HZ,th as v8,wh as o9}from"./vm-hands-entry-lite-k90ysszf.js";import{Ai as tZ,Bi as o8}from"./vm-hands-entry-lite-923jmcs3.js";import{aj as b0}from"./vm-hands-entry-lite-6ffdqdyw.js";import{sj as A8,tj as t9,wj as j4}from"./vm-hands-entry-lite-ecgyzbdp.js";import{Aj as r0,Bj as B9,Cj as H8,Dj as W$,Ej as i0,Fj as u0,Gj as FZ,Rj as A$,xj as D8,yj as o0,zj as _8}from"./vm-hands-entry-lite-3pecyp8y.js";import{Wj as OQ}from"./vm-hands-entry-lite-r67d5w6h.js";import{pk as x}from"./vm-hands-entry-lite-18kfytsa.js";import{vk as C4}from"./vm-hands-entry-lite-mrw8bv5s.js";import{Ak as $8,Bk as DZ,Ck as p$,Dk as _Z,Ek as p9,Hk as M4,Ik as Y9,yk as N4}from"./vm-hands-entry-lite-mkynexaq.js";import{Mk as q}from"./vm-hands-entry-lite-hkvkfq0z.js";import{Nk as l1,Sk as CQ}from"./vm-hands-entry-lite-4yw8vx5h.js";import{execFile as k4}from"child_process";import{createRequire as f4}from"module";import{win32 as u9}from"path";var m4=250,y4=50,g4=250,h4=4194304;function c$($){let Z=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec($??""),Q=Number(Z?.[3]);return Z&&Q<=65535?{address:Z[1]??Z[2],port:Q}:null}function v4($){let Z=[];for(let Q of $.split(/\r?\n/)){let X=Q.trim().split(/\s+/);if(X[0]!=="TCP"||X.length<5)continue;let J=c$(X[1]),Y=c$(X[2]),z=Number(X.at(-1));if(!J||!Y||!Number.isSafeInteger(z)||z<0)continue;Z.push({pid:z,localAddress:J.address,localPort:J.port,remoteAddress:Y.address,remotePort:Y.port,listening:Y.port===0})}return Z}function c4($){if($.localAddress==="0.0.0.0"||$.localAddress==="::")return`*:${$.localPort}`;return $.localAddress.includes(":")?`[${$.localAddress}]:${$.localPort}`:`${$.localAddress}:${$.localPort}`}var w8=($)=>new Promise((Z,Q)=>k4(u9.join(p$("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:$,maxBuffer:h4,encoding:"utf8",windowsHide:!0,env:p9()},(X,J)=>X?Q(X):Z(J)));function _9($){let Z=u9.normalize($.startsWith("\\\\?\\")?$.slice(4):$);return Z.length>3&&Z.endsWith("\\")?Z.slice(0,-1):Z}function d4($,Z){let Q=$.toLowerCase(),X=Z.toLowerCase();return X===Q||X.startsWith(Q.endsWith("\\")?Q:`${Q}\\`)}function u$($,Z,Q){let X=$.cwd(Q),J=X?_9(X):null;return J&&u9.isAbsolute(J)&&d4(Z,J)?J:null}var D9;function l9(){if(D9!==void 0)return D9;if(D9=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let $;try{$=f4(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:Z,ptr:Q}=$,X,J;try{X=$.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[Z.u32,Z.u32],returns:Z.u64},Process32FirstW:{args:[Z.u64,Z.ptr],returns:Z.i32},Process32NextW:{args:[Z.u64,Z.ptr],returns:Z.i32},OpenProcess:{args:[Z.u32,Z.i32,Z.u32],returns:Z.u64},ReadProcessMemory:{args:[Z.u64,Z.u64,Z.ptr,Z.u64,Z.ptr],returns:Z.i32},CloseHandle:{args:[Z.u64],returns:Z.i32}}).symbols,J=$.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[Z.u64,Z.i32,Z.ptr,Z.u32,Z.ptr],returns:Z.i32}}).symbols}catch{return null}let Y=0xFFFF_FFFF_FFFF_FFFFn,z=2,F=1040,G=568,V=(B,H,K)=>{let L=Buffer.alloc(K);return X.ReadProcessMemory(B,H,Q(L),K,null)?L:null};return D9={processes(){let B=BigInt(X.CreateToolhelp32Snapshot(z,0));if(B===Y)throw new q("process_inspection_failed","Reading this computer's processes did not complete.");try{let H=Buffer.alloc(G);H.writeUInt32LE(G,0);let K=Q(H),L=[];for(let U=X.Process32FirstW(B,K);U;U=X.Process32NextW(B,K)){let W=H.toString("utf16le",44,G),j=W.slice(0,W.includes("\x00")?W.indexOf("\x00"):void 0),O=H.readUInt32LE(8);if(O>0)L.push({pid:O,parentPid:H.readUInt32LE(32),command:j.replace(/\.exe$/i,"")||null})}return L}finally{X.CloseHandle(B)}},cwd(B){let H=BigInt(X.OpenProcess(F,0,B));if(H===0n)return null;try{let K=Buffer.alloc(48);if(J.NtQueryInformationProcess(H,0,Q(K),K.length,null)!==0)return null;let L=V(H,K.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),U=L?V(H,L+0x38n,16):null,W=U?.readUInt16LE(0)??0;if(!U||W===0||W%2!==0)return null;return V(H,U.readBigUInt64LE(8),W)?.toString("utf16le")??null}finally{X.CloseHandle(H)}}},D9}function b8($){if(!$)throw new q("process_inspection_failed","Reading this computer's processes is unavailable.");return $}async function l$($,Z){let Q;try{Q=await $(Z)}catch{throw new q("process_inspection_failed","Reading this computer's ports did not complete.")}return v4(Q)}async function A2($,Z=l9()){let Q=b8(Z),X=_9($),J=[];for(let Y of Q.processes()){if(J.length>=m4)break;let z=u$(Q,X,Y.pid);if(z)J.push({pid:Y.pid,command:Y.command,cwd:u9.relative(X,z)||"."})}return{processes:J}}async function x2($,Z=l9(),Q=w8){let X=b8(Z),J=_9($),Y=(await l$(Q,5000)).filter((V)=>V.listening&&V.pid>0).map((V)=>({pid:V.pid,port:V.localPort,address:c4(V)})).sort((V,B)=>V.pid-B.pid||V.port-B.port||(V.address<B.address?-1:V.address>B.address?1:0)),z=[...new Set(Y.map((V)=>V.pid))].slice(0,y4),F=new Set(z.filter((V)=>u$(X,J,V)!==null));if(F.size===0)return{ports:[]};let G=new Map(X.processes().map((V)=>[V.pid,V.command]));return{ports:Y.filter((V)=>F.has(V.pid)).slice(0,g4).map((V)=>({pid:V.pid,command:G.get(V.pid)??null,address:V.address}))}}function d$($,Z){let Q=new Set([Z]);for(let X=!0;X;){X=!1;for(let J of $)if(!Q.has(J.pid)&&Q.has(J.parentPid)&&J.pid!==J.parentPid)Q.add(J.pid),X=!0}return Q}function p4($,Z,Q,X){let J=(Y)=>Y==="127.0.0.1"||Y==="::ffff:127.0.0.1"||Y==="::1";return $.flatMap((Y)=>{if(!Z.has(Y.pid)||Y.localPort!==X)return[];let z=Y.listening&&(J(Y.localAddress)||["0.0.0.0","::"].includes(Y.localAddress)),F=!Y.listening&&J(Y.localAddress)&&J(Y.remoteAddress);if(!z&&!F)return[];let G=`${Y.localAddress}:${Y.localPort}>${Y.remoteAddress}:${Y.remotePort}`;return[{pid:Y.pid,processGroupId:Q,descriptor:String(Y.pid),kernelId:G,state:z?"listen":"established",port:X,peerPort:z?null:Y.remotePort,host:Y.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function s$($,Z,Q=l9(),X=w8){let J=b8(Q),Y=d$(J.processes(),$),z=await l$(X,1000),F=d$(J.processes(),$);return p4(z,new Set([...Y].filter((G)=>F.has(G))),$,Z)}async function I2($,Z=l9(),Q=w8){if(!Z||$.aborted)return!1;let X=Z.processes().some((F)=>F.pid===process.pid),J=Z.cwd(process.pid),Y=J!==null&&_9(J).toLowerCase()===_9(process.cwd()).toLowerCase(),z=await Q(5000).then((F)=>/^\s*TCP\s/m.test(F),()=>!1);return X&&Y&&z&&!$.aborted}var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function s9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Z,Q=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Z&&$<=Q}function i$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function a$($,Z){let Q=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Q.length]),Q,Z])}function R0($){if(!s9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(i$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function d0($,Z){return Object.keys($).every((Q)=>$[Q]===Z[Q])}function x9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Z=decodeURIComponent($);if(Z.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Z))throw Error("preview_path_invalid");return $}function n$($){return Array.isArray($)&&$.length<=64&&$.every((Z)=>Array.isArray(Z)&&Z.length===2&&typeof Z[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Z[0])&&typeof Z[1]==="string"&&Z[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Z[1]))}function A9($,Z=v.chunk){if($.length>Math.ceil(Z/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Q=Buffer.from($,"base64");if(Q.length>Z)throw Error("preview_data_too_large");return Q}function o$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function r$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Z=JSON.parse($);if(!s9(Z))throw Error("preview_frame_invalid");if(Z.type==="hello")return{type:"hello",binding:R0(Z.binding),...P0(Z.messages,v.chunk,v.upload)?{messages:Z.messages}:{},...P0(Z.window,1,v.window)?{window:Z.window}:{},...Z.bytes===!0?{bytes:!0}:{}};if(Z.type==="refused"&&typeof Z.reason==="string"&&/^[a-z_]{1,32}$/.test(Z.reason))return{type:"refused",binding:R0(Z.binding),reason:Z.reason};if(!i$(Z.id))throw Error("preview_frame_invalid");if(Z.type==="end"||Z.type==="cancel"||Z.type==="credit")return{type:Z.type,id:Z.id};if(Z.type==="ws"&&typeof Z.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Z.protocol))return{type:"ws",id:Z.id,protocol:Z.protocol};if(Z.type==="data"&&typeof Z.data==="string"&&typeof Z.binary==="boolean")return A9(Z.data,v.upload),{type:"data",id:Z.id,data:Z.data,binary:Z.binary};if(Z.type==="head"&&P0(Z.status,200,599)&&n$(Z.headers))return{type:"head",id:Z.id,status:Z.status,headers:Z.headers};if(Z.type==="request"&&typeof Z.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Z.method)&&typeof Z.path==="string"&&n$(Z.headers)&&typeof Z.body==="string"&&typeof Z.upgrade==="boolean")return A9(Z.body,v.upload),{type:"request",id:Z.id,method:Z.method,path:x9(Z.path),headers:Z.headers,body:Z.body,upgrade:Z.upgrade};throw Error("preview_frame_invalid")}function k8($){let Z=[...$],Q=new Set(Z.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Z.filter(([J])=>!X.has(J.toLowerCase())&&!Q.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function f8($){let Z;try{return await Promise.race([Promise.resolve().then($).then((Q)=>Q===!0||(Q===!1?!1:void 0),()=>{return}),new Promise((Q)=>{Z=setTimeout(()=>Q(void 0),v.authorizationMs)})])}finally{clearTimeout(Z)}}async function I9($){return await f8($)===!0}function n9($,Z){let Q=new URL($);if(Q.username||Q.password||Q.search||Q.hash||!(Q.protocol==="wss:"||Q.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Q.hostname))||!new RegExp(`^/${Z}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Q.pathname))throw Error("preview_relay_invalid");return Q.href}function t$($){if(!s9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:R0($.binding),deviceRelayUrl:n9($.deviceRelayUrl,"device")}}function e$($){if(!s9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:R0($.binding)}}import{request as n4}from"http";import{pipeline as i4}from"stream";import{constants as m8,createBrotliCompress as a4,createGzip as o4}from"zlib";import{WebSocket as P9}from"ws";import{randomBytes as u4,timingSafeEqual as l4}from"crypto";import{createServer as s4}from"net";var $Z="x-preview-connection";async function ZZ($,Z){if(Z.aborted)throw Error("preview_closed");let Q=u4(32).toString("base64url"),X=new Set,J=!1,Y=s4((G)=>{if(J||Z.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let V=new AbortController;G.once("close",()=>{X.delete(G),V.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let U=B.indexOf(`\r
|
|
2
|
+
import{Jc as uZ,Kc as lZ,Lc as T4,Mc as O4,Nc as j8,Oc as sZ}from"./vm-hands-entry-lite-400hmvkg.js";import{$c as F0,Pc as mZ,Qc as W8,Rc as e9,Sc as _0,Tc as q9,Uc as a0}from"./vm-hands-entry-lite-k9amte6k.js";import{cd as L8,dd as B8,ed as oQ}from"./vm-hands-entry-lite-wts79wdn.js";import{Ee as MZ,Je as jZ,rf as y9,sf as t0,tf as O8,uf as m0,yf as C0}from"./vm-hands-entry-lite-afjzr3v2.js";import{Og as oZ,Ug as Z8,Vg as n8}from"./vm-hands-entry-lite-wtc8ebkr.js";import{_g as q4}from"./vm-hands-entry-lite-kntkyezs.js";import{Hh as h8,Ih as w0,Jh as O0,Kh as r9,Rh as p8,Sh as OZ,Th as WZ,bh as wQ,eh as j9,nh as qZ,oh as CZ,qh as TZ,sh as a9,th as VZ,uh as HZ,vh as v8,yh as o9}from"./vm-hands-entry-lite-0dr3sp75.js";import{Ci as tZ,Di as o8}from"./vm-hands-entry-lite-caxtg4j7.js";import{cj as b0}from"./vm-hands-entry-lite-0mk8rxqv.js";import{vj as A8,wj as t9,zj as j4}from"./vm-hands-entry-lite-wsnr4fx8.js";import{Aj as D8,Bj as o0,Cj as _8,Dj as r0,Ej as B9,Fj as H8,Gj as W$,Hj as i0,Ij as u0,Jj as FZ,Uj as A$}from"./vm-hands-entry-lite-arw53mkf.js";import{Zj as OQ}from"./vm-hands-entry-lite-b3jmyabq.js";import{sk as x}from"./vm-hands-entry-lite-ysk49bnz.js";import{yk as C4}from"./vm-hands-entry-lite-dj65hfea.js";import{Bk as N4,Dk as $8,Ek as DZ,Fk as p$,Gk as _Z,Hk as p9,Kk as M4,Lk as Y9}from"./vm-hands-entry-lite-rbjky7rd.js";import{Pk as q}from"./vm-hands-entry-lite-f28ehysx.js";import{Qk as l1,Vk as CQ}from"./vm-hands-entry-lite-c3e25cks.js";import{execFile as k4}from"child_process";import{createRequire as f4}from"module";import{win32 as u9}from"path";var m4=250,y4=50,g4=250,h4=4194304;function c$($){let Z=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec($??""),Q=Number(Z?.[3]);return Z&&Q<=65535?{address:Z[1]??Z[2],port:Q}:null}function v4($){let Z=[];for(let Q of $.split(/\r?\n/)){let X=Q.trim().split(/\s+/);if(X[0]!=="TCP"||X.length<5)continue;let J=c$(X[1]),Y=c$(X[2]),z=Number(X.at(-1));if(!J||!Y||!Number.isSafeInteger(z)||z<0)continue;Z.push({pid:z,localAddress:J.address,localPort:J.port,remoteAddress:Y.address,remotePort:Y.port,listening:Y.port===0})}return Z}function c4($){if($.localAddress==="0.0.0.0"||$.localAddress==="::")return`*:${$.localPort}`;return $.localAddress.includes(":")?`[${$.localAddress}]:${$.localPort}`:`${$.localAddress}:${$.localPort}`}var w8=($)=>new Promise((Z,Q)=>k4(u9.join(p$("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:$,maxBuffer:h4,encoding:"utf8",windowsHide:!0,env:p9()},(X,J)=>X?Q(X):Z(J)));function _9($){let Z=u9.normalize($.startsWith("\\\\?\\")?$.slice(4):$);return Z.length>3&&Z.endsWith("\\")?Z.slice(0,-1):Z}function d4($,Z){let Q=$.toLowerCase(),X=Z.toLowerCase();return X===Q||X.startsWith(Q.endsWith("\\")?Q:`${Q}\\`)}function u$($,Z,Q){let X=$.cwd(Q),J=X?_9(X):null;return J&&u9.isAbsolute(J)&&d4(Z,J)?J:null}var D9;function l9(){if(D9!==void 0)return D9;if(D9=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let $;try{$=f4(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:Z,ptr:Q}=$,X,J;try{X=$.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[Z.u32,Z.u32],returns:Z.u64},Process32FirstW:{args:[Z.u64,Z.ptr],returns:Z.i32},Process32NextW:{args:[Z.u64,Z.ptr],returns:Z.i32},OpenProcess:{args:[Z.u32,Z.i32,Z.u32],returns:Z.u64},ReadProcessMemory:{args:[Z.u64,Z.u64,Z.ptr,Z.u64,Z.ptr],returns:Z.i32},CloseHandle:{args:[Z.u64],returns:Z.i32}}).symbols,J=$.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[Z.u64,Z.i32,Z.ptr,Z.u32,Z.ptr],returns:Z.i32}}).symbols}catch{return null}let Y=0xFFFF_FFFF_FFFF_FFFFn,z=2,F=1040,G=568,V=(B,H,K)=>{let L=Buffer.alloc(K);return X.ReadProcessMemory(B,H,Q(L),K,null)?L:null};return D9={processes(){let B=BigInt(X.CreateToolhelp32Snapshot(z,0));if(B===Y)throw new q("process_inspection_failed","Reading this computer's processes did not complete.");try{let H=Buffer.alloc(G);H.writeUInt32LE(G,0);let K=Q(H),L=[];for(let U=X.Process32FirstW(B,K);U;U=X.Process32NextW(B,K)){let W=H.toString("utf16le",44,G),j=W.slice(0,W.includes("\x00")?W.indexOf("\x00"):void 0),O=H.readUInt32LE(8);if(O>0)L.push({pid:O,parentPid:H.readUInt32LE(32),command:j.replace(/\.exe$/i,"")||null})}return L}finally{X.CloseHandle(B)}},cwd(B){let H=BigInt(X.OpenProcess(F,0,B));if(H===0n)return null;try{let K=Buffer.alloc(48);if(J.NtQueryInformationProcess(H,0,Q(K),K.length,null)!==0)return null;let L=V(H,K.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),U=L?V(H,L+0x38n,16):null,W=U?.readUInt16LE(0)??0;if(!U||W===0||W%2!==0)return null;return V(H,U.readBigUInt64LE(8),W)?.toString("utf16le")??null}finally{X.CloseHandle(H)}}},D9}function b8($){if(!$)throw new q("process_inspection_failed","Reading this computer's processes is unavailable.");return $}async function l$($,Z){let Q;try{Q=await $(Z)}catch{throw new q("process_inspection_failed","Reading this computer's ports did not complete.")}return v4(Q)}async function A2($,Z=l9()){let Q=b8(Z),X=_9($),J=[];for(let Y of Q.processes()){if(J.length>=m4)break;let z=u$(Q,X,Y.pid);if(z)J.push({pid:Y.pid,command:Y.command,cwd:u9.relative(X,z)||"."})}return{processes:J}}async function x2($,Z=l9(),Q=w8){let X=b8(Z),J=_9($),Y=(await l$(Q,5000)).filter((V)=>V.listening&&V.pid>0).map((V)=>({pid:V.pid,port:V.localPort,address:c4(V)})).sort((V,B)=>V.pid-B.pid||V.port-B.port||(V.address<B.address?-1:V.address>B.address?1:0)),z=[...new Set(Y.map((V)=>V.pid))].slice(0,y4),F=new Set(z.filter((V)=>u$(X,J,V)!==null));if(F.size===0)return{ports:[]};let G=new Map(X.processes().map((V)=>[V.pid,V.command]));return{ports:Y.filter((V)=>F.has(V.pid)).slice(0,g4).map((V)=>({pid:V.pid,command:G.get(V.pid)??null,address:V.address}))}}function d$($,Z){let Q=new Set([Z]);for(let X=!0;X;){X=!1;for(let J of $)if(!Q.has(J.pid)&&Q.has(J.parentPid)&&J.pid!==J.parentPid)Q.add(J.pid),X=!0}return Q}function p4($,Z,Q,X){let J=(Y)=>Y==="127.0.0.1"||Y==="::ffff:127.0.0.1"||Y==="::1";return $.flatMap((Y)=>{if(!Z.has(Y.pid)||Y.localPort!==X)return[];let z=Y.listening&&(J(Y.localAddress)||["0.0.0.0","::"].includes(Y.localAddress)),F=!Y.listening&&J(Y.localAddress)&&J(Y.remoteAddress);if(!z&&!F)return[];let G=`${Y.localAddress}:${Y.localPort}>${Y.remoteAddress}:${Y.remotePort}`;return[{pid:Y.pid,processGroupId:Q,descriptor:String(Y.pid),kernelId:G,state:z?"listen":"established",port:X,peerPort:z?null:Y.remotePort,host:Y.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function s$($,Z,Q=l9(),X=w8){let J=b8(Q),Y=d$(J.processes(),$),z=await l$(X,1000),F=d$(J.processes(),$);return p4(z,new Set([...Y].filter((G)=>F.has(G))),$,Z)}async function I2($,Z=l9(),Q=w8){if(!Z||$.aborted)return!1;let X=Z.processes().some((F)=>F.pid===process.pid),J=Z.cwd(process.pid),Y=J!==null&&_9(J).toLowerCase()===_9(process.cwd()).toLowerCase(),z=await Q(5000).then((F)=>/^\s*TCP\s/m.test(F),()=>!1);return X&&Y&&z&&!$.aborted}var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function s9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Z,Q=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Z&&$<=Q}function i$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function a$($,Z){let Q=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Q.length]),Q,Z])}function R0($){if(!s9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(i$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function d0($,Z){return Object.keys($).every((Q)=>$[Q]===Z[Q])}function x9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Z=decodeURIComponent($);if(Z.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Z))throw Error("preview_path_invalid");return $}function n$($){return Array.isArray($)&&$.length<=64&&$.every((Z)=>Array.isArray(Z)&&Z.length===2&&typeof Z[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Z[0])&&typeof Z[1]==="string"&&Z[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Z[1]))}function A9($,Z=v.chunk){if($.length>Math.ceil(Z/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Q=Buffer.from($,"base64");if(Q.length>Z)throw Error("preview_data_too_large");return Q}function o$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function r$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Z=JSON.parse($);if(!s9(Z))throw Error("preview_frame_invalid");if(Z.type==="hello")return{type:"hello",binding:R0(Z.binding),...P0(Z.messages,v.chunk,v.upload)?{messages:Z.messages}:{},...P0(Z.window,1,v.window)?{window:Z.window}:{},...Z.bytes===!0?{bytes:!0}:{}};if(Z.type==="refused"&&typeof Z.reason==="string"&&/^[a-z_]{1,32}$/.test(Z.reason))return{type:"refused",binding:R0(Z.binding),reason:Z.reason};if(!i$(Z.id))throw Error("preview_frame_invalid");if(Z.type==="end"||Z.type==="cancel"||Z.type==="credit")return{type:Z.type,id:Z.id};if(Z.type==="ws"&&typeof Z.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Z.protocol))return{type:"ws",id:Z.id,protocol:Z.protocol};if(Z.type==="data"&&typeof Z.data==="string"&&typeof Z.binary==="boolean")return A9(Z.data,v.upload),{type:"data",id:Z.id,data:Z.data,binary:Z.binary};if(Z.type==="head"&&P0(Z.status,200,599)&&n$(Z.headers))return{type:"head",id:Z.id,status:Z.status,headers:Z.headers};if(Z.type==="request"&&typeof Z.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Z.method)&&typeof Z.path==="string"&&n$(Z.headers)&&typeof Z.body==="string"&&typeof Z.upgrade==="boolean")return A9(Z.body,v.upload),{type:"request",id:Z.id,method:Z.method,path:x9(Z.path),headers:Z.headers,body:Z.body,upgrade:Z.upgrade};throw Error("preview_frame_invalid")}function k8($){let Z=[...$],Q=new Set(Z.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Z.filter(([J])=>!X.has(J.toLowerCase())&&!Q.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function f8($){let Z;try{return await Promise.race([Promise.resolve().then($).then((Q)=>Q===!0||(Q===!1?!1:void 0),()=>{return}),new Promise((Q)=>{Z=setTimeout(()=>Q(void 0),v.authorizationMs)})])}finally{clearTimeout(Z)}}async function I9($){return await f8($)===!0}function n9($,Z){let Q=new URL($);if(Q.username||Q.password||Q.search||Q.hash||!(Q.protocol==="wss:"||Q.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Q.hostname))||!new RegExp(`^/${Z}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Q.pathname))throw Error("preview_relay_invalid");return Q.href}function t$($){if(!s9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:R0($.binding),deviceRelayUrl:n9($.deviceRelayUrl,"device")}}function e$($){if(!s9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:R0($.binding)}}import{request as n4}from"http";import{pipeline as i4}from"stream";import{constants as m8,createBrotliCompress as a4,createGzip as o4}from"zlib";import{WebSocket as P9}from"ws";import{randomBytes as u4,timingSafeEqual as l4}from"crypto";import{createServer as s4}from"net";var $Z="x-preview-connection";async function ZZ($,Z){if(Z.aborted)throw Error("preview_closed");let Q=u4(32).toString("base64url"),X=new Set,J=!1,Y=s4((G)=>{if(J||Z.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let V=new AbortController;G.once("close",()=>{X.delete(G),V.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let U=B.indexOf(`\r
|
|
3
3
|
\r
|
|
4
4
|
`);if(U<0){if(B.length>16384)G.destroy();return}if(G.pause(),G.off("data",H),U>16384||B.length>v.upload+16384)return G.destroy();K(B,U).catch(()=>G.destroy())};G.on("data",H);async function K(L,U){let W=L.subarray(0,U).toString("latin1").split(`\r
|
|
5
5
|
`),j=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(W.shift()??"");if(!j)throw Error("preview_request_invalid");x9(j[2]);let O=!1,C=0,A=[];for(let T of W){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===$Z){C++;let y=Buffer.from(S[2].trim());O=y.length===Q.length&&l4(y,Buffer.from(Q))}else if(S[1].toLowerCase()!=="host")A.push(T)}if(!O||C!==1||J||V.signal.aborted)throw Error("preview_connection_denied");let R=await $.connect(V.signal);if(J||V.signal.aborted)throw R.destroy(),Error("preview_closed");X.add(R),R.on("error",()=>G.destroy()),R.once("close",()=>{X.delete(R),G.destroy()}),G.once("close",()=>R.destroy()),G.setTimeout(0);let I=[`${j[1]} ${j[2]} HTTP/1.1`,`Host: 127.0.0.1:${R.remotePort}`,...A,"",""].join(`\r
|
|
@@ -302,7 +302,7 @@ async (input) => {
|
|
|
302
302
|
if (!bridge || typeof bridge.evaluate !== "function") throw new Error("Reason Hands browser bridge is not installed");
|
|
303
303
|
return await bridge.evaluate(typeof input === "string" ? input : input && input.code);
|
|
304
304
|
}
|
|
305
|
-
`.trim();import{Buffer as z9}from"buffer";import{randomUUID as A1}from"crypto";class FQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var VQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),GQ=/^hands_[A-Za-z0-9_-]{8,128}$/,x1=2048,HQ=32,WQ=1e4,I1=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function P1($){let Z=$.split("+"),Q=(Z.pop()??"").replace(/^Key/,"").toLowerCase();if(Q==="f12")return!0;if(Z.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(Q))return!0;if(Z.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&Z.includes("Shift")&&Q==="c")return!0;return Z.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(Q)}var R1=($)=>{let Z=$.closest("a[href],area[href]");return{password:$.tagName==="INPUT"&&$.type==="password",executableLink:Boolean(Z&&!/^(https?:|about:blank)/i.test(Z.href))}},UQ={browser:{close:{returns:"void"},contexts:{returns:"context[]"},isConnected:{returns:"json"},version:{returns:"json"}},context:{addCookies:{returns:"void"},addInitScript:{returns:"void"},browser:{returns:"browser"},clearCookies:{returns:"void"},clearPermissions:{returns:"void"},close:{returns:"void"},cookies:{returns:"json"},grantPermissions:{returns:"void"},newPage:{returns:"page"},pages:{returns:"page[]"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setGeolocation:{returns:"void"},setHTTPCredentials:{returns:"void"},setOffline:{returns:"void"},setViewportSize:{returns:"void"},storageState:{returns:"json"},viewportSize:{returns:"json",special:"contextViewportSize"}},page:{addInitScript:{returns:"void"},addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},bringToFront:{returns:"void"},close:{returns:"void"},content:{returns:"json"},context:{returns:"context"},emulateMedia:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},frame:{returns:"frame"},frameLocator:{returns:"frameLocator"},frames:{returns:"frame[]"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goBack:{returns:"void"},goForward:{returns:"void"},goto:{returns:"void"},isClosed:{returns:"json"},locator:{returns:"locator"},mainFrame:{returns:"frame"},opener:{returns:"page"},pdf:{returns:"bytes"},reload:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setContent:{returns:"void"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setInputFiles:{returns:"void"},setViewportSize:{returns:"void"},title:{returns:"json"},url:{returns:"json"},viewportSize:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},locator:{all:{returns:"locator[]"},allInnerTexts:{returns:"json"},allTextContents:{returns:"json"},and:{returns:"locator"},ariaSnapshot:{returns:"json"},blur:{returns:"void"},boundingBox:{returns:"json"},check:{returns:"void"},clear:{returns:"void"},click:{returns:"void"},contentFrame:{returns:"frameLocator"},count:{returns:"json"},dblclick:{returns:"void"},dragTo:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},evaluateAll:{returns:"json",requiresStringSource:!0},fill:{returns:"void"},filter:{returns:"locator"},first:{returns:"locator",special:"property"},focus:{returns:"void"},getAttribute:{returns:"json"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},hover:{returns:"void"},innerHTML:{returns:"json"},innerText:{returns:"json"},inputValue:{returns:"json"},isChecked:{returns:"json"},isEditable:{returns:"json"},isEnabled:{returns:"json"},isHidden:{returns:"json"},isVisible:{returns:"json"},last:{returns:"locator",special:"property"},locator:{returns:"locator"},nth:{returns:"locator"},or:{returns:"locator"},page:{returns:"page"},press:{returns:"void"},pressSequentially:{returns:"void"},scrollIntoViewIfNeeded:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setInputFiles:{returns:"void"},tap:{returns:"void"},textContent:{returns:"json"},type:{returns:"void"},uncheck:{returns:"void"},waitFor:{returns:"void"}},frame:{addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},childFrames:{returns:"frame[]"},content:{returns:"json"},evaluate:{returns:"json",requiresStringSource:!0},frameLocator:{returns:"frameLocator"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goto:{returns:"void"},isDetached:{returns:"json"},locator:{returns:"locator"},name:{returns:"json"},page:{returns:"page"},parentFrame:{returns:"frame"},setContent:{returns:"void"},title:{returns:"json"},url:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},frameLocator:{getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},locator:{returns:"locator"},owner:{returns:"locator"}}};function P($){throw new FQ($)}function K0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let Z=Object.getPrototypeOf($);return Z===Object.prototype||Z===null}function K9($,Z=0,Q={nodes:0}){if(Z>HQ||++Q.nodes>WQ)P("hands_repl_json_too_complex");if($===null||typeof $==="boolean"||typeof $==="string")return;if(typeof $==="number"){if(!Number.isFinite($))P("hands_repl_invalid_json");return}if(Array.isArray($)){for(let X of $)K9(X,Z+1,Q);return}if(!K0($))P("hands_repl_invalid_json");for(let[X,J]of Object.entries($)){if(VQ.has(X))P("hands_repl_invalid_json");K9(J,Z+1,Q)}}function r8($){return typeof $==="string"&&Object.hasOwn(UQ,$)}function E1($){if(!$.endsWith("[]"))return null;let Z=$.slice(0,-2);return r8(Z)?Z:null}function zQ($){return K0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function S1($){return K0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function KQ($){return K0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function J8(){return Object.freeze({$handsRepl:"undefined"})}function w1($){if(!z9.isBuffer($)&&!($ instanceof Uint8Array))P("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:z9.from($).toString("base64")})}function BQ($){if(!k0($.browser)||!k0($.context)||!k0($.page))P("hands_repl_invalid_roots");if(typeof $.a11y!=="function"||typeof $.view!=="function")P("hands_repl_invalid_callbacks");let Z=$.maxHandles??x1;if(!Number.isInteger(Z)||Z<3||Z>1e5)P("hands_repl_invalid_handle_limit");let Q=new Map,X=new WeakMap,J=$.createOpaqueId??A1,Y=(K,L)=>{if(!k0(L))P("hands_repl_expected_target");let U=X.get(L)?.get(K);if(U)return U;if(Q.size>=Z)P("hands_repl_handle_limit");let W="";for(let C=0;C<16;C+=1){let A=`hands_${J()}`;if(GQ.test(A)&&!Q.has(A)){W=A;break}}if(!W)P("hands_repl_invalid_opaque_id");let j=Object.freeze({$handsRepl:"handle",id:W,kind:K});Q.set(W,{kind:K,target:L});let O=X.get(L);if(!O)O=new Map,X.set(L,O);return O.set(K,j),j},z=Object.freeze({browser:Y("browser",$.browser),context:Y("context",$.context),page:Y("page",$.page)}),F=(K)=>{if(!K0(K)||Object.keys(K).length!==3||K.$handsRepl!=="handle"||typeof K.id!=="string"||!GQ.test(K.id)||!r8(K.kind))P("hands_repl_invalid_handle");let L=Q.get(K.id);if(!L||L.kind!==K.kind)P("hands_repl_unknown_handle");return L},G=(K,L=0,U=new Set)=>{if(L>HQ)P("hands_repl_json_too_complex");if(K===void 0)return J8();if(K===null||typeof K==="boolean"||typeof K==="string")return K;if(typeof K==="number"){if(!Number.isFinite(K))P("hands_repl_non_json_result");return K}if(Array.isArray(K)){if(U.has(K))P("hands_repl_cyclic_result");U.add(K);try{return K.map((W)=>G(W,L+1,U))}finally{U.delete(K)}}if(!K0(K))P("hands_repl_non_json_result");if(U.has(K))P("hands_repl_cyclic_result");U.add(K);try{let W=Object.create(null);for(let j of Object.keys(K)){let O=Object.getOwnPropertyDescriptor(K,j);if(!O||!("value"in O))continue;W[j]=G(O.value,L+1,U)}return W}finally{U.delete(K)}},V=(K,L)=>{if(L==="void")return J8();if(L==="json")return G(K);if(L==="bytes")return w1(K);let U=E1(L);if(U){if(!Array.isArray(K))P("hands_repl_expected_target_list");if(U==="context"&&K.some((W)=>W!==$.context))P("hands_repl_foreign_context");return K.map((W)=>Y(U,W))}if(K===null||K===void 0)return J8();if(!r8(L))P("hands_repl_invalid_return_kind");if(L==="context"&&K!==$.context)P("hands_repl_foreign_context");return Y(L,K)},B=(K)=>{if(K0(K)&&K.$handsRepl==="handle")return F(K).target;if(zQ(K))return z9.from(K.base64,"base64");if(S1(K))return;if(KQ(K))P("hands_repl_route_fulfill_only");if(Array.isArray(K))return K.map(B);if(!K0(K))return K;let L=Object.create(null);for(let[U,W]of Object.entries(K))L[U]=B(W);return L};return Object.freeze({roots:z,dispatch:async(K)=>{if(!K0(K)||typeof K.type!=="string")P("hands_repl_invalid_request");if(K.type==="a11y"){let T=K.target===void 0?Q.get(z.page.id):F(K.target);if(!T||T.kind!=="page"&&T.kind!=="locator")P("hands_repl_invalid_a11y_target");return G(await $.a11y(T.target))}if(K.type==="view"){if(K9(K.source),K.options!==void 0)K9(K.options);let T=zQ(K.source)?z9.from(K.source.base64,"base64"):K.source;if($.privateProfile&&!z9.isBuffer(T))P("hands_repl_profile_requires_image_bytes");return G(await $.view(T,K.options))}if(K.type!=="call")P("hands_repl_invalid_request");if(typeof K.method!=="string"||K.method.length===0||K.method.length>128)P("hands_repl_invalid_method");if(VQ.has(K.method))P("hands_repl_forbidden_method");let L=F(K.target),U=K.args??[];if(!Array.isArray(U))P("hands_repl_invalid_arguments");if(K9(U),L.kind==="page"&&K.method==="captureScreenshot"){if(U.length!==0)P("hands_repl_invalid_arguments");if(!$.screenshotExport)P("hands_repl_screenshot_export_unavailable");return G(await $.screenshotExport(L.target))}if(L.kind==="context"&&["startRecording","stopRecording"].includes(K.method)){if(!$.recording||L.target!==$.context)P("hands_repl_recording_unavailable");if(U.length>(K.method==="startRecording"?1:0))P("hands_repl_invalid_arguments");return G(K.method==="startRecording"?await $.recording.start(U[0]):await $.recording.stop())}if($.privateProfile){let T=K.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(T)||L.kind==="browser"&&T==="close"||L.kind==="context"&&T==="close")P("hands_repl_private_profile_method_denied");if(L.kind==="browser"&&T==="contexts")return V([$.context],"context[]");if((T==="screenshot"||T==="pdf")&&K0(U[0])&&(("path"in U[0])||("style"in U[0])))P("hands_repl_private_profile_path_denied");if(T==="goto"){if(typeof U[0]!=="string")P("hands_repl_private_profile_url_denied");try{let S=new URL(U[0]);if(!["http:","https:"].includes(S.protocol)&&U[0]!=="about:blank")P("hands_repl_private_profile_url_denied")}catch{P("hands_repl_private_profile_url_denied")}}if(T==="getAttribute"&&(typeof U[0]!=="string"||!I1.has(U[0].toLowerCase())))P("hands_repl_private_profile_attribute_denied");if(L.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(T)){let S=[L.target];if(T==="allInnerTexts"){let y=Reflect.get(L.target,"all");if(typeof y!=="function")P("hands_repl_private_profile_probe_unavailable");let E=await Reflect.apply(y,L.target,[]);if(!Array.isArray(E)||E.length>WQ||!E.every(k0))P("hands_repl_private_profile_probe_unavailable");S=E}for(let y of S){let E=Reflect.get(y,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,y,[]))P("hands_repl_private_profile_hidden_value_denied")}}if(T==="press"&&typeof U[0]==="string"&&P1(U[0]))P("hands_repl_private_profile_browser_shortcut_denied");if(L.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(T)){let S=Reflect.get(L.target,"evaluate");if(typeof S!=="function")P("hands_repl_private_profile_probe_unavailable");let y=await Reflect.apply(S,L.target,[R1]);if(!K0(y)||typeof y.password!=="boolean"||typeof y.executableLink!=="boolean")P("hands_repl_private_profile_probe_unavailable");if(T==="inputValue"&&y.password)P("hands_repl_private_profile_password_denied");if(T!=="inputValue"&&y.executableLink)P("hands_repl_private_profile_url_denied");if(T==="inputValue"){let E=Reflect.get(L.target,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,L.target,[]))P("hands_repl_private_profile_hidden_value_denied")}}}let W=UQ[L.kind][K.method];if(!W)P("hands_repl_method_not_allowed");if(W.requiresStringSource&&typeof U[0]!=="string")P("hands_repl_string_source_required");if(L.kind==="browser"&&K.method==="contexts")return[z.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(K.method)&&U.some((T)=>K0(T)&&("path"in T)))P("hands_repl_file_path_not_allowed");if(K.method==="goto"&&typeof U[0]==="string"){let T;try{T=new URL(U[0]).protocol}catch{P("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(T))P("hands_repl_file_path_not_allowed")}if(W.special==="contextViewportSize"){let T=Reflect.get(L.target,"pages");if(typeof T!=="function")P("hands_repl_method_unavailable");let S=await Reflect.apply(T,L.target,[]),y=Array.isArray(S)?S[0]:void 0,E=k0(y)?Reflect.get(y,"viewportSize"):void 0;if(typeof E!=="function")return J8();return V(await Reflect.apply(E,y,[]),W.returns)}if(W.special==="property"){let T=Reflect.get(L.target,K.method);return V(typeof T==="function"?Reflect.apply(T,L.target,[]):T,W.returns)}let j=Reflect.get(L.target,K.method);if(typeof j!=="function")P("hands_repl_method_unavailable");if(W.special==="route"){let T=U[1];if(!KQ(T))P("hands_repl_invalid_route_handler");K9(T.options);let S=B(T.options),y=async(M)=>{if(!k0(M))P("hands_repl_invalid_route");let D=Reflect.get(M,"fulfill");if(typeof D!=="function")P("hands_repl_invalid_route");await Reflect.apply(D,M,[S])},E=[B(U[0]??null),y],N=await Reflect.apply(j,L.target,E);return V(N,W.returns)}let O=U.map(B);if(K.method==="setInputFiles"){let T=L.kind==="locator"?0:1,S=async(E)=>{if(typeof E!=="string"){if(!K0(E)||typeof E.name!=="string"||typeof E.mimeType!=="string"||!z9.isBuffer(E.buffer))P("hands_repl_invalid_file_input");return E}if(!$.readWorkspaceFile)P("hands_repl_workspace_required");return $.readWorkspaceFile(E)},y=O[T];O[T]=Array.isArray(y)?await Promise.all(y.map(S)):await S(y)}if(K.method==="goto")await $.beforeNavigation?.();let C=$.actionRecorder?.(),A=await Reflect.apply(j,L.target,O),I={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[K.method];if(I){let T=Reflect.get(L.target,"page"),S=L.kind==="page"?L.target:typeof T==="function"?Reflect.apply(T,L.target,[]):void 0;C?.(I,k0(S)?S:void 0)}return V(A,W.returns)}})}import{isIP as qQ}from"net";import{Resolver as b1}from"dns/promises";import{isIP as G8}from"net";var k1=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function t8($){if(G8($)!==4)return null;let Z=$.split(".");if(Z.length!==4)return null;let Q=0;for(let X of Z){let J=Number(X);if(!Number.isInteger(J)||J<0||J>255)return null;Q=Q*256+J}return Q>>>0}function f1($,Z,Q){let X=t8(Z);if(X===null)return!1;let J=Q===0?0:4294967295<<32-Q>>>0;return($&J)>>>0===(X&J)>>>0}function LQ($){let Z=t8($);if(Z===null)return!0;return k1.some(([Q,X])=>f1(Z,Q,X))}function m1($){if(G8($)!==6)return null;let Z=$.toLowerCase(),Q=Z.indexOf("%");if(Q>=0)Z=Z.slice(0,Q);let X=[],J=Z.lastIndexOf(":"),Y=J>=0?Z.slice(J+1):"";if(Y.includes(".")){let K=t8(Y);if(K===null)return null;X=[K>>>16&65535,K&65535],Z=Z.slice(0,J+1)+"0:0"}let z=Z.split("::");if(z.length>2)return null;let F=(K)=>{if(K==="")return[];let L=[];for(let U of K.split(":")){if(U===""||U.length>4||!/^[0-9a-f]+$/.test(U))return null;L.push(Number.parseInt(U,16))}return L},G=F(z[0]??"");if(G===null)return null;if(z.length===1){let K=G;if(K.length!==8)return null;return X.length>0?K.slice(0,6).concat(X):K}let V=F(z[1]??"");if(V===null)return null;let B=8-G.length-V.length;if(B<0)return null;let H=G.concat(Array(B).fill(0),V);if(H.length!==8)return null;return X.length>0?H.slice(0,6).concat(X):H}function y1($,Z){return`${$>>8&255}.${$&255}.${Z>>8&255}.${Z&255}`}function g1($){let Z=m1($);if(Z===null)return!0;let[Q,X,J]=Z;if((Q&57344)!==8192)return!0;if(Q===8193&&(X&65024)===0)return!0;if(Q===8193&&X===3512)return!0;if(Q===16383&&(X&61440)===0)return!0;if(Q===8194)return LQ(y1(X,J));return!1}function NQ($){return $.replace(/^\[|\]$/g,"")}function Y8($){let Z=NQ($.trim()),Q=G8(Z);if(Q===4)return LQ(Z);if(Q===6)return g1(Z);return!0}function MQ($){if($ instanceof Error&&$.name==="TimeoutError")return"dns_timeout";switch(typeof $==="object"&&$!==null&&"code"in $?$.code:void 0){case"ENOTFOUND":return"dns_not_found";case"ENODATA":return"dns_empty";case"EAI_AGAIN":case"ESERVFAIL":case"ECONNREFUSED":return"dns_temporary";case"ETIMEOUT":case"ETIMEDOUT":return"dns_timeout";default:return"dns_failed"}}var jQ=5000;function h1($){return async(Z,Q)=>{if(Q?.aborted)throw Error("aborted");let X=new b1({timeout:jQ,tries:1});if($)X.setServers($);let J=()=>X.cancel();Q?.addEventListener("abort",J,{once:!0});try{let[Y,z]=await Promise.allSettled([X.resolve4(Z),X.resolve6(Z)]),F=[...Y.status==="fulfilled"?Y.value:[],...z.status==="fulfilled"?z.value:[]];if(F.length>0)return F;let G=[Y,z].flatMap((B)=>B.status==="rejected"?[B.reason]:[]);throw G.find((B)=>["dns_temporary","dns_timeout"].includes(MQ(B)))??G[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{Q?.removeEventListener("abort",J)}}}var v1=h1();async function c1($,Z,Q,X){if(X?.aborted)throw Error("aborted");let J=new AbortController,Y,z,F=Z($,J.signal);F.catch(()=>{});try{return await Promise.race([F,new Promise((G,V)=>{if(Y=setTimeout(()=>V(new DOMException("DNS lookup timed out","TimeoutError")),Q),X)z=()=>V(Error("aborted")),X.addEventListener("abort",z,{once:!0})})])}finally{if(Y!==void 0)clearTimeout(Y);if(X&&z)X.removeEventListener("abort",z);J.abort()}}async function m5($,Z=v1,Q){let X=NQ($);if(G8(X))return Y8(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await c1(X,Z,jQ,Q)}catch(Y){return{ok:!1,reason:Q?.aborted?Q.reason instanceof Error&&Q.reason.name==="TimeoutError"?"dns_timeout":"aborted":MQ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(Y8))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:J}}var d1=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function e8($){return $.length<=253&&d1.test($.toLowerCase())}function p1($,Z){let Q=$.trim().toLowerCase();if(!e8(Q))return!1;if(Q.startsWith("*.")){let X=Q.slice(2);return Z===X||Z.endsWith(`.${X}`)}return Q===Z}function u1($){let Z=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec($);if(!Z)return null;let Q=Z.slice(1).map(Number);return Q.some((X)=>X>255)?null:Q}function $$($,Z=[]){let Q=(X)=>{if(X=X.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!X.includes(":"))return X;try{X=new URL(`http://[${X}]/`).hostname.slice(1,-1)}catch{return X}let J=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(X);if(!J)return X;let Y=parseInt(J[1],16),z=parseInt(J[2],16);return`${Y>>8}.${Y&255}.${z>>8}.${z&255}`};return Z.some((X)=>Q(X)===Q($))}function l0($){$=$.toLowerCase().replace(/^\[|\]$/g,"");let Z=u1($);if(Z){let[Y,z,F]=Z;if(Y===127)return"loopback";return Y===0||Y===10||Y>=224||Y===100&&z>=64&&z<=127||Y===169&&z===254||Y===172&&z>=16&&z<=31||Y===192&&(z===168||z===0&&(F===0||F===2)||z===88&&F===99)||Y===198&&(z===18||z===19||z===51&&F===100)||Y===203&&z===0&&F===113?"private":"public"}if(!$.includes(":"))return"hostname";try{$=new URL(`http://[${$}]/`).hostname.slice(1,-1)}catch{return"private"}if($==="::1")return"loopback";let Q=/^::ffff:([\da-f]+):([\da-f]+)$/.exec($);if(Q){let Y=parseInt(Q[1],16),z=parseInt(Q[2],16);return l0(`${Y>>8}.${Y&255}.${z>>8}.${z&255}`)==="public"?"public":"private"}let[X,J=0]=$.split(":").map((Y)=>parseInt(Y||"0",16));return X<8192||X>16383||X===8194||X===8193&&(J<512||J===3512)||X===16383&&J<4096?"private":"public"}function b9($,Z){let Q;try{Q=new URL($)}catch{return{allowed:!1,url:$,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(Q.protocol))return{allowed:!0,url:$,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(Q.protocol))return{allowed:!1,url:$,host:Q.hostname||null,reason:"unsupported_protocol"};let X=Q.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(Z.mode==="off")return{allowed:!0,url:$,host:X,reason:"policy_off"};let J=(F)=>({allowed:!1,url:$,host:X,reason:F});if(Q.username||Q.password)return J("invalid_url");if(Z.mode==="public_web"){let F=l0(X)!=="public"&&l0(X)!=="hostname"||X==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(X)||!X.includes(".")&&!qQ(X)||Boolean(qQ(X)&&Y8(X));return{allowed:!F,url:$,host:X,reason:F?"private_network":"public_web"}}let Y=Number(Q.port||(["https:","wss:"].includes(Q.protocol)?443:80));if(Z.deniedPorts?.includes(Y)||$$(X,Z.deniedHosts))return J("destination_not_allowed");let z=l0(X);if(z==="private"||["local","internal","arpa"].some((F)=>X===F||X.endsWith(`.${F}`)))return J("private_network");if(z==="loopback"||X==="localhost"||X.endsWith(".localhost"))return Z.allowedLoopbackPorts?.includes(Y)?{allowed:!0,url:$,host:X,reason:"loopback"}:J("destination_not_allowed");if(Z.allowedDomains.some((F)=>p1(F,X)))return{allowed:!0,url:$,host:X,reason:"allowed_domain"};return{allowed:!1,url:$,host:X,reason:"destination_not_allowed"}}import TQ from"child_process";import{accessSync as s1,constants as n1,readFileSync as i1,statSync as DQ}from"fs";import{createRequire as _Q}from"module";import{homedir as Z$}from"os";import{dirname as a1,isAbsolute as Q$,join as s0,resolve as o1,win32 as r1}from"path";var z8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:OQ.dependencies["playwright-core"],browser:"chromium"}),AQ=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],X$=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function t1($=process.env){let Z=[$.ProgramFiles??"C:\\Program Files",$["ProgramFiles(x86)"]??"C:\\Program Files (x86)"],Q=$.LOCALAPPDATA?[$.LOCALAPPDATA]:[],X=(J,...Y)=>J.map((z)=>r1.join(z,...Y));return[...X([...Z,...Q],"Google","Chrome","Application","chrome.exe"),...X(Z,"Microsoft","Edge","Application","msedge.exe"),...X([...Z,...Q],"BraveSoftware","Brave-Browser","Application","brave.exe")]}function k9($){try{return s1($,n1.X_OK),Q$($)&&DQ($).isFile()}catch{return!1}}function J$($,Z=process.platform){let Q=Z==="darwin"?AQ:Z==="linux"?X$:Z==="win32"?t1():null;return Q?($??Q).find(k9)??null:null}function e1(){if(!process.versions.bun)return;let $=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,$))return;let Z=[];TQ.spawn=new Proxy(TQ.spawn,{apply(Q,X,J){let Y=Reflect.apply(Q,X,J),z=J[1],F=J[2]?.stdio;if(Array.isArray(z)&&z.includes("--remote-debugging-pipe")&&Array.isArray(F)&&F[3]==="pipe"&&F[4]==="pipe")Z.push(Y);return Y}}),Object.defineProperty(globalThis,$,{value:Z})}async function K8($){if(e1(),$!==void 0){if(!Q$($))throw Error("hands_browser_driver_path_must_be_absolute");let X=s0($,"package.json"),J=JSON.parse(i1(X,"utf8"));if(J.name!==z8.driver)throw Error("hands_browser_wrong_driver");let Y=_Q(X)($),z=Y.default?.chromium??Y.chromium;if(!z)throw Error("hands_browser_missing_chromium");return{version:J.version,chromium:z}}let[Z,Q]=await Promise.all([import("./index-58750fwy.js"),import("./package-9c803cqw.js").then((m)=>l1(m.default,1))]);return{version:Q.default.version,chromium:Z.chromium}}var $7=($,Z=z8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Z}),Z7=($)=>$.loadDriver?.()??K8($.driverModuleDirectory),Q7={"1.60.0":"1223"};function n5(){let $=process.platform,Z=Q7[z8.driverVersion];if(!Z||$!=="linux"&&$!=="darwin"&&$!=="win32")return!1;let Q=(X)=>process.env[X]??process.env[`npm_config_${X.toLowerCase()}`]??process.env[`npm_package_config_${X.toLowerCase()}`];try{let X=Q("PLAYWRIGHT_BROWSERS_PATH"),J=X==="0"?s0(a1(_Q(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?o1(Q("INIT_CWD")||process.cwd(),X):s0($==="darwin"?s0(Z$(),"Library","Caches"):$==="win32"?process.env.LOCALAPPDATA||s0(Z$(),"AppData","Local"):process.env.XDG_CACHE_HOME||s0(Z$(),".cache"),"ms-playwright");return DQ(s0(J,`chromium-${Z}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function F9($={}){return xQ($,z8.driverVersion)}async function Y$($,Z={}){if($.driverVersion!=="1.61.1"||!Q$($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return xQ({...Z,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function xQ($,Z){let Q=(G)=>$7(G,Z),X=$.platform??process.platform;if(X!=="linux"&&X!=="darwin"&&X!=="win32")return Q("unsupported_platform");let J;try{J=await Z7($)}catch{return Q("driver_missing")}if(J.version!==Z)return Q("driver_version_mismatch");let Y=(G,V)=>({status:"resolved",executablePath:G,source:V,driverVersion:J.version});if($.executablePath!==void 0)return k9($.executablePath)?Y($.executablePath,"configured"):Q("executable_missing");let z=J.chromium.executablePath();if(k9(z))return Y(z,"managed");let F=$.allowSystemBrowser===!0?J$($.systemCandidates,X):null;return F?Y(F,"system"):Q("executable_missing")}var L7=["/usr/local/bin/chromium",...X$];function N7($,Z=bQ()){return J$($??(Z==="linux"?L7:void 0),Z)}async function M7(){try{return(await K8()).chromium}catch{return V7(import.meta.url)("playwright-core").chromium}}var j7=1048576,q7=105000,C7=20000,RQ=5000,T7=2000,O7=1000,D7=30000,EQ=81920,_7={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function A7($,Z){let Q=new URL($.url()),X={...await $.allHeaders(),host:Q.host};for(let J of Object.keys(X))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(J))delete X[J];return new Promise((J,Y)=>{let F=(Q.protocol==="https:"?W7:H7)(Q,{method:$.method(),headers:X,agent:!1,lookup:(V,B,H)=>{let K=n0.isIP(Z);if(B.all)H(null,[{address:Z,family:K}]);else H(null,Z,K)}},(V)=>{let B=[],H=0;V.on("data",(K)=>{if(H+=K.length,H>33554432)F.destroy(Error("hands_browser_response_too_large"));else B.push(K)}),V.on("error",Y),V.on("end",()=>{let K={};for(let[L,U]of Object.entries(V.headers))if(U!==void 0&&!["transfer-encoding","connection","content-length"].includes(L))K[L]=Array.isArray(U)?U.join(`
|
|
305
|
+
`.trim();import{Buffer as z9}from"buffer";import{randomUUID as A1}from"crypto";class FQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var VQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),GQ=/^hands_[A-Za-z0-9_-]{8,128}$/,x1=2048,HQ=32,WQ=1e4,I1=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function P1($){let Z=$.split("+"),Q=(Z.pop()??"").replace(/^Key/,"").toLowerCase();if(Q==="f12")return!0;if(Z.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(Q))return!0;if(Z.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&Z.includes("Shift")&&Q==="c")return!0;return Z.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(Q)}var R1=($)=>{let Z=$.closest("a[href],area[href]");return{password:$.tagName==="INPUT"&&$.type==="password",executableLink:Boolean(Z&&!/^(https?:|about:blank)/i.test(Z.href))}},UQ={browser:{close:{returns:"void"},contexts:{returns:"context[]"},isConnected:{returns:"json"},version:{returns:"json"}},context:{addCookies:{returns:"void"},addInitScript:{returns:"void"},browser:{returns:"browser"},clearCookies:{returns:"void"},clearPermissions:{returns:"void"},close:{returns:"void"},cookies:{returns:"json"},grantPermissions:{returns:"void"},newPage:{returns:"page"},pages:{returns:"page[]"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setGeolocation:{returns:"void"},setHTTPCredentials:{returns:"void"},setOffline:{returns:"void"},setViewportSize:{returns:"void"},storageState:{returns:"json"},viewportSize:{returns:"json",special:"contextViewportSize"}},page:{addInitScript:{returns:"void"},addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},bringToFront:{returns:"void"},close:{returns:"void"},content:{returns:"json"},context:{returns:"context"},emulateMedia:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},frame:{returns:"frame"},frameLocator:{returns:"frameLocator"},frames:{returns:"frame[]"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goBack:{returns:"void"},goForward:{returns:"void"},goto:{returns:"void"},isClosed:{returns:"json"},locator:{returns:"locator"},mainFrame:{returns:"frame"},opener:{returns:"page"},pdf:{returns:"bytes"},reload:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setContent:{returns:"void"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setInputFiles:{returns:"void"},setViewportSize:{returns:"void"},title:{returns:"json"},url:{returns:"json"},viewportSize:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},locator:{all:{returns:"locator[]"},allInnerTexts:{returns:"json"},allTextContents:{returns:"json"},and:{returns:"locator"},ariaSnapshot:{returns:"json"},blur:{returns:"void"},boundingBox:{returns:"json"},check:{returns:"void"},clear:{returns:"void"},click:{returns:"void"},contentFrame:{returns:"frameLocator"},count:{returns:"json"},dblclick:{returns:"void"},dragTo:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},evaluateAll:{returns:"json",requiresStringSource:!0},fill:{returns:"void"},filter:{returns:"locator"},first:{returns:"locator",special:"property"},focus:{returns:"void"},getAttribute:{returns:"json"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},hover:{returns:"void"},innerHTML:{returns:"json"},innerText:{returns:"json"},inputValue:{returns:"json"},isChecked:{returns:"json"},isEditable:{returns:"json"},isEnabled:{returns:"json"},isHidden:{returns:"json"},isVisible:{returns:"json"},last:{returns:"locator",special:"property"},locator:{returns:"locator"},nth:{returns:"locator"},or:{returns:"locator"},page:{returns:"page"},press:{returns:"void"},pressSequentially:{returns:"void"},scrollIntoViewIfNeeded:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setInputFiles:{returns:"void"},tap:{returns:"void"},textContent:{returns:"json"},type:{returns:"void"},uncheck:{returns:"void"},waitFor:{returns:"void"}},frame:{addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},childFrames:{returns:"frame[]"},content:{returns:"json"},evaluate:{returns:"json",requiresStringSource:!0},frameLocator:{returns:"frameLocator"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goto:{returns:"void"},isDetached:{returns:"json"},locator:{returns:"locator"},name:{returns:"json"},page:{returns:"page"},parentFrame:{returns:"frame"},setContent:{returns:"void"},title:{returns:"json"},url:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},frameLocator:{getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},locator:{returns:"locator"},owner:{returns:"locator"}}};function P($){throw new FQ($)}function K0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let Z=Object.getPrototypeOf($);return Z===Object.prototype||Z===null}function K9($,Z=0,Q={nodes:0}){if(Z>HQ||++Q.nodes>WQ)P("hands_repl_json_too_complex");if($===null||typeof $==="boolean"||typeof $==="string")return;if(typeof $==="number"){if(!Number.isFinite($))P("hands_repl_invalid_json");return}if(Array.isArray($)){for(let X of $)K9(X,Z+1,Q);return}if(!K0($))P("hands_repl_invalid_json");for(let[X,J]of Object.entries($)){if(VQ.has(X))P("hands_repl_invalid_json");K9(J,Z+1,Q)}}function r8($){return typeof $==="string"&&Object.hasOwn(UQ,$)}function E1($){if(!$.endsWith("[]"))return null;let Z=$.slice(0,-2);return r8(Z)?Z:null}function zQ($){return K0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function S1($){return K0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function KQ($){return K0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function J8(){return Object.freeze({$handsRepl:"undefined"})}function w1($){if(!z9.isBuffer($)&&!($ instanceof Uint8Array))P("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:z9.from($).toString("base64")})}function BQ($){if(!k0($.browser)||!k0($.context)||!k0($.page))P("hands_repl_invalid_roots");if(typeof $.a11y!=="function"||typeof $.view!=="function")P("hands_repl_invalid_callbacks");let Z=$.maxHandles??x1;if(!Number.isInteger(Z)||Z<3||Z>1e5)P("hands_repl_invalid_handle_limit");let Q=new Map,X=new WeakMap,J=$.createOpaqueId??A1,Y=(K,L)=>{if(!k0(L))P("hands_repl_expected_target");let U=X.get(L)?.get(K);if(U)return U;if(Q.size>=Z)P("hands_repl_handle_limit");let W="";for(let C=0;C<16;C+=1){let A=`hands_${J()}`;if(GQ.test(A)&&!Q.has(A)){W=A;break}}if(!W)P("hands_repl_invalid_opaque_id");let j=Object.freeze({$handsRepl:"handle",id:W,kind:K});Q.set(W,{kind:K,target:L});let O=X.get(L);if(!O)O=new Map,X.set(L,O);return O.set(K,j),j},z=Object.freeze({browser:Y("browser",$.browser),context:Y("context",$.context),page:Y("page",$.page)}),F=(K)=>{if(!K0(K)||Object.keys(K).length!==3||K.$handsRepl!=="handle"||typeof K.id!=="string"||!GQ.test(K.id)||!r8(K.kind))P("hands_repl_invalid_handle");let L=Q.get(K.id);if(!L||L.kind!==K.kind)P("hands_repl_unknown_handle");return L},G=(K,L=0,U=new Set)=>{if(L>HQ)P("hands_repl_json_too_complex");if(K===void 0)return J8();if(K===null||typeof K==="boolean"||typeof K==="string")return K;if(typeof K==="number"){if(!Number.isFinite(K))P("hands_repl_non_json_result");return K}if(Array.isArray(K)){if(U.has(K))P("hands_repl_cyclic_result");U.add(K);try{return K.map((W)=>G(W,L+1,U))}finally{U.delete(K)}}if(!K0(K))P("hands_repl_non_json_result");if(U.has(K))P("hands_repl_cyclic_result");U.add(K);try{let W=Object.create(null);for(let j of Object.keys(K)){let O=Object.getOwnPropertyDescriptor(K,j);if(!O||!("value"in O))continue;W[j]=G(O.value,L+1,U)}return W}finally{U.delete(K)}},V=(K,L)=>{if(L==="void")return J8();if(L==="json")return G(K);if(L==="bytes")return w1(K);let U=E1(L);if(U){if(!Array.isArray(K))P("hands_repl_expected_target_list");if(U==="context"&&K.some((W)=>W!==$.context))P("hands_repl_foreign_context");return K.map((W)=>Y(U,W))}if(K===null||K===void 0)return J8();if(!r8(L))P("hands_repl_invalid_return_kind");if(L==="context"&&K!==$.context)P("hands_repl_foreign_context");return Y(L,K)},B=(K)=>{if(K0(K)&&K.$handsRepl==="handle")return F(K).target;if(zQ(K))return z9.from(K.base64,"base64");if(S1(K))return;if(KQ(K))P("hands_repl_route_fulfill_only");if(Array.isArray(K))return K.map(B);if(!K0(K))return K;let L=Object.create(null);for(let[U,W]of Object.entries(K))L[U]=B(W);return L};return Object.freeze({roots:z,dispatch:async(K)=>{if(!K0(K)||typeof K.type!=="string")P("hands_repl_invalid_request");if(K.type==="a11y"){let T=K.target===void 0?Q.get(z.page.id):F(K.target);if(!T||T.kind!=="page"&&T.kind!=="locator")P("hands_repl_invalid_a11y_target");return G(await $.a11y(T.target))}if(K.type==="view"){if(K9(K.source),K.options!==void 0)K9(K.options);let T=zQ(K.source)?z9.from(K.source.base64,"base64"):K.source;if($.privateProfile&&!z9.isBuffer(T))P("hands_repl_profile_requires_image_bytes");return G(await $.view(T,K.options))}if(K.type!=="call")P("hands_repl_invalid_request");if(typeof K.method!=="string"||K.method.length===0||K.method.length>128)P("hands_repl_invalid_method");if(VQ.has(K.method))P("hands_repl_forbidden_method");let L=F(K.target),U=K.args??[];if(!Array.isArray(U))P("hands_repl_invalid_arguments");if(K9(U),L.kind==="page"&&K.method==="captureScreenshot"){if(U.length!==0)P("hands_repl_invalid_arguments");if(!$.screenshotExport)P("hands_repl_screenshot_export_unavailable");return G(await $.screenshotExport(L.target))}if(L.kind==="context"&&["startRecording","stopRecording"].includes(K.method)){if(!$.recording||L.target!==$.context)P("hands_repl_recording_unavailable");if(U.length>(K.method==="startRecording"?1:0))P("hands_repl_invalid_arguments");return G(K.method==="startRecording"?await $.recording.start(U[0]):await $.recording.stop())}if($.privateProfile){let T=K.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(T)||L.kind==="browser"&&T==="close"||L.kind==="context"&&T==="close")P("hands_repl_private_profile_method_denied");if(L.kind==="browser"&&T==="contexts")return V([$.context],"context[]");if((T==="screenshot"||T==="pdf")&&K0(U[0])&&(("path"in U[0])||("style"in U[0])))P("hands_repl_private_profile_path_denied");if(T==="goto"){if(typeof U[0]!=="string")P("hands_repl_private_profile_url_denied");try{let S=new URL(U[0]);if(!["http:","https:"].includes(S.protocol)&&U[0]!=="about:blank")P("hands_repl_private_profile_url_denied")}catch{P("hands_repl_private_profile_url_denied")}}if(T==="getAttribute"&&(typeof U[0]!=="string"||!I1.has(U[0].toLowerCase())))P("hands_repl_private_profile_attribute_denied");if(L.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(T)){let S=[L.target];if(T==="allInnerTexts"){let y=Reflect.get(L.target,"all");if(typeof y!=="function")P("hands_repl_private_profile_probe_unavailable");let E=await Reflect.apply(y,L.target,[]);if(!Array.isArray(E)||E.length>WQ||!E.every(k0))P("hands_repl_private_profile_probe_unavailable");S=E}for(let y of S){let E=Reflect.get(y,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,y,[]))P("hands_repl_private_profile_hidden_value_denied")}}if(T==="press"&&typeof U[0]==="string"&&P1(U[0]))P("hands_repl_private_profile_browser_shortcut_denied");if(L.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(T)){let S=Reflect.get(L.target,"evaluate");if(typeof S!=="function")P("hands_repl_private_profile_probe_unavailable");let y=await Reflect.apply(S,L.target,[R1]);if(!K0(y)||typeof y.password!=="boolean"||typeof y.executableLink!=="boolean")P("hands_repl_private_profile_probe_unavailable");if(T==="inputValue"&&y.password)P("hands_repl_private_profile_password_denied");if(T!=="inputValue"&&y.executableLink)P("hands_repl_private_profile_url_denied");if(T==="inputValue"){let E=Reflect.get(L.target,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,L.target,[]))P("hands_repl_private_profile_hidden_value_denied")}}}let W=UQ[L.kind][K.method];if(!W)P("hands_repl_method_not_allowed");if(W.requiresStringSource&&typeof U[0]!=="string")P("hands_repl_string_source_required");if(L.kind==="browser"&&K.method==="contexts")return[z.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(K.method)&&U.some((T)=>K0(T)&&("path"in T)))P("hands_repl_file_path_not_allowed");if(K.method==="goto"&&typeof U[0]==="string"){let T;try{T=new URL(U[0]).protocol}catch{P("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(T))P("hands_repl_file_path_not_allowed")}if(W.special==="contextViewportSize"){let T=Reflect.get(L.target,"pages");if(typeof T!=="function")P("hands_repl_method_unavailable");let S=await Reflect.apply(T,L.target,[]),y=Array.isArray(S)?S[0]:void 0,E=k0(y)?Reflect.get(y,"viewportSize"):void 0;if(typeof E!=="function")return J8();return V(await Reflect.apply(E,y,[]),W.returns)}if(W.special==="property"){let T=Reflect.get(L.target,K.method);return V(typeof T==="function"?Reflect.apply(T,L.target,[]):T,W.returns)}let j=Reflect.get(L.target,K.method);if(typeof j!=="function")P("hands_repl_method_unavailable");if(W.special==="route"){let T=U[1];if(!KQ(T))P("hands_repl_invalid_route_handler");K9(T.options);let S=B(T.options),y=async(M)=>{if(!k0(M))P("hands_repl_invalid_route");let D=Reflect.get(M,"fulfill");if(typeof D!=="function")P("hands_repl_invalid_route");await Reflect.apply(D,M,[S])},E=[B(U[0]??null),y],N=await Reflect.apply(j,L.target,E);return V(N,W.returns)}let O=U.map(B);if(K.method==="setInputFiles"){let T=L.kind==="locator"?0:1,S=async(E)=>{if(typeof E!=="string"){if(!K0(E)||typeof E.name!=="string"||typeof E.mimeType!=="string"||!z9.isBuffer(E.buffer))P("hands_repl_invalid_file_input");return E}if(!$.readWorkspaceFile)P("hands_repl_workspace_required");return $.readWorkspaceFile(E)},y=O[T];O[T]=Array.isArray(y)?await Promise.all(y.map(S)):await S(y)}if(K.method==="goto")await $.beforeNavigation?.();let C=$.actionRecorder?.(),A=await Reflect.apply(j,L.target,O),I={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[K.method];if(I){let T=Reflect.get(L.target,"page"),S=L.kind==="page"?L.target:typeof T==="function"?Reflect.apply(T,L.target,[]):void 0;C?.(I,k0(S)?S:void 0)}return V(A,W.returns)}})}import{isIP as qQ}from"net";import{Resolver as b1}from"dns/promises";import{isIP as G8}from"net";var k1=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function t8($){if(G8($)!==4)return null;let Z=$.split(".");if(Z.length!==4)return null;let Q=0;for(let X of Z){let J=Number(X);if(!Number.isInteger(J)||J<0||J>255)return null;Q=Q*256+J}return Q>>>0}function f1($,Z,Q){let X=t8(Z);if(X===null)return!1;let J=Q===0?0:4294967295<<32-Q>>>0;return($&J)>>>0===(X&J)>>>0}function LQ($){let Z=t8($);if(Z===null)return!0;return k1.some(([Q,X])=>f1(Z,Q,X))}function m1($){if(G8($)!==6)return null;let Z=$.toLowerCase(),Q=Z.indexOf("%");if(Q>=0)Z=Z.slice(0,Q);let X=[],J=Z.lastIndexOf(":"),Y=J>=0?Z.slice(J+1):"";if(Y.includes(".")){let K=t8(Y);if(K===null)return null;X=[K>>>16&65535,K&65535],Z=Z.slice(0,J+1)+"0:0"}let z=Z.split("::");if(z.length>2)return null;let F=(K)=>{if(K==="")return[];let L=[];for(let U of K.split(":")){if(U===""||U.length>4||!/^[0-9a-f]+$/.test(U))return null;L.push(Number.parseInt(U,16))}return L},G=F(z[0]??"");if(G===null)return null;if(z.length===1){let K=G;if(K.length!==8)return null;return X.length>0?K.slice(0,6).concat(X):K}let V=F(z[1]??"");if(V===null)return null;let B=8-G.length-V.length;if(B<0)return null;let H=G.concat(Array(B).fill(0),V);if(H.length!==8)return null;return X.length>0?H.slice(0,6).concat(X):H}function y1($,Z){return`${$>>8&255}.${$&255}.${Z>>8&255}.${Z&255}`}function g1($){let Z=m1($);if(Z===null)return!0;let[Q,X,J]=Z;if((Q&57344)!==8192)return!0;if(Q===8193&&(X&65024)===0)return!0;if(Q===8193&&X===3512)return!0;if(Q===16383&&(X&61440)===0)return!0;if(Q===8194)return LQ(y1(X,J));return!1}function NQ($){return $.replace(/^\[|\]$/g,"")}function Y8($){let Z=NQ($.trim()),Q=G8(Z);if(Q===4)return LQ(Z);if(Q===6)return g1(Z);return!0}function MQ($){if($ instanceof Error&&$.name==="TimeoutError")return"dns_timeout";switch(typeof $==="object"&&$!==null&&"code"in $?$.code:void 0){case"ENOTFOUND":return"dns_not_found";case"ENODATA":return"dns_empty";case"EAI_AGAIN":case"ESERVFAIL":case"ECONNREFUSED":return"dns_temporary";case"ETIMEOUT":case"ETIMEDOUT":return"dns_timeout";default:return"dns_failed"}}var jQ=5000;function h1($){return async(Z,Q)=>{if(Q?.aborted)throw Error("aborted");let X=new b1({timeout:jQ,tries:1});if($)X.setServers($);let J=()=>X.cancel();Q?.addEventListener("abort",J,{once:!0});try{let[Y,z]=await Promise.allSettled([X.resolve4(Z),X.resolve6(Z)]),F=[...Y.status==="fulfilled"?Y.value:[],...z.status==="fulfilled"?z.value:[]];if(F.length>0)return F;let G=[Y,z].flatMap((B)=>B.status==="rejected"?[B.reason]:[]);throw G.find((B)=>["dns_temporary","dns_timeout"].includes(MQ(B)))??G[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{Q?.removeEventListener("abort",J)}}}var v1=h1();async function c1($,Z,Q,X){if(X?.aborted)throw Error("aborted");let J=new AbortController,Y,z,F=Z($,J.signal);F.catch(()=>{});try{return await Promise.race([F,new Promise((G,V)=>{if(Y=setTimeout(()=>V(new DOMException("DNS lookup timed out","TimeoutError")),Q),X)z=()=>V(Error("aborted")),X.addEventListener("abort",z,{once:!0})})])}finally{if(Y!==void 0)clearTimeout(Y);if(X&&z)X.removeEventListener("abort",z);J.abort()}}async function m5($,Z=v1,Q){let X=NQ($);if(G8(X))return Y8(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await c1(X,Z,jQ,Q)}catch(Y){return{ok:!1,reason:Q?.aborted?Q.reason instanceof Error&&Q.reason.name==="TimeoutError"?"dns_timeout":"aborted":MQ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(Y8))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:J}}var d1=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function e8($){return $.length<=253&&d1.test($.toLowerCase())}function p1($,Z){let Q=$.trim().toLowerCase();if(!e8(Q))return!1;if(Q.startsWith("*.")){let X=Q.slice(2);return Z===X||Z.endsWith(`.${X}`)}return Q===Z}function u1($){let Z=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec($);if(!Z)return null;let Q=Z.slice(1).map(Number);return Q.some((X)=>X>255)?null:Q}function $$($,Z=[]){let Q=(X)=>{if(X=X.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!X.includes(":"))return X;try{X=new URL(`http://[${X}]/`).hostname.slice(1,-1)}catch{return X}let J=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(X);if(!J)return X;let Y=parseInt(J[1],16),z=parseInt(J[2],16);return`${Y>>8}.${Y&255}.${z>>8}.${z&255}`};return Z.some((X)=>Q(X)===Q($))}function l0($){$=$.toLowerCase().replace(/^\[|\]$/g,"");let Z=u1($);if(Z){let[Y,z,F]=Z;if(Y===127)return"loopback";return Y===0||Y===10||Y>=224||Y===100&&z>=64&&z<=127||Y===169&&z===254||Y===172&&z>=16&&z<=31||Y===192&&(z===168||z===0&&(F===0||F===2)||z===88&&F===99)||Y===198&&(z===18||z===19||z===51&&F===100)||Y===203&&z===0&&F===113?"private":"public"}if(!$.includes(":"))return"hostname";try{$=new URL(`http://[${$}]/`).hostname.slice(1,-1)}catch{return"private"}if($==="::1")return"loopback";let Q=/^::ffff:([\da-f]+):([\da-f]+)$/.exec($);if(Q){let Y=parseInt(Q[1],16),z=parseInt(Q[2],16);return l0(`${Y>>8}.${Y&255}.${z>>8}.${z&255}`)==="public"?"public":"private"}let[X,J=0]=$.split(":").map((Y)=>parseInt(Y||"0",16));return X<8192||X>16383||X===8194||X===8193&&(J<512||J===3512)||X===16383&&J<4096?"private":"public"}function b9($,Z){let Q;try{Q=new URL($)}catch{return{allowed:!1,url:$,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(Q.protocol))return{allowed:!0,url:$,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(Q.protocol))return{allowed:!1,url:$,host:Q.hostname||null,reason:"unsupported_protocol"};let X=Q.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(Z.mode==="off")return{allowed:!0,url:$,host:X,reason:"policy_off"};let J=(F)=>({allowed:!1,url:$,host:X,reason:F});if(Q.username||Q.password)return J("invalid_url");if(Z.mode==="public_web"){let F=l0(X)!=="public"&&l0(X)!=="hostname"||X==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(X)||!X.includes(".")&&!qQ(X)||Boolean(qQ(X)&&Y8(X));return{allowed:!F,url:$,host:X,reason:F?"private_network":"public_web"}}let Y=Number(Q.port||(["https:","wss:"].includes(Q.protocol)?443:80));if(Z.deniedPorts?.includes(Y)||$$(X,Z.deniedHosts))return J("destination_not_allowed");let z=l0(X);if(z==="private"||["local","internal","arpa"].some((F)=>X===F||X.endsWith(`.${F}`)))return J("private_network");if(z==="loopback"||X==="localhost"||X.endsWith(".localhost"))return Z.allowedLoopbackPorts?.includes(Y)?{allowed:!0,url:$,host:X,reason:"loopback"}:J("destination_not_allowed");if(Z.allowedDomains.some((F)=>p1(F,X)))return{allowed:!0,url:$,host:X,reason:"allowed_domain"};return{allowed:!1,url:$,host:X,reason:"destination_not_allowed"}}import TQ from"child_process";import{accessSync as s1,constants as n1,readFileSync as i1,statSync as DQ}from"fs";import{createRequire as _Q}from"module";import{homedir as Z$}from"os";import{dirname as a1,isAbsolute as Q$,join as s0,resolve as o1,win32 as r1}from"path";var z8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:OQ.dependencies["playwright-core"],browser:"chromium"}),AQ=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],X$=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function t1($=process.env){let Z=[$.ProgramFiles??"C:\\Program Files",$["ProgramFiles(x86)"]??"C:\\Program Files (x86)"],Q=$.LOCALAPPDATA?[$.LOCALAPPDATA]:[],X=(J,...Y)=>J.map((z)=>r1.join(z,...Y));return[...X([...Z,...Q],"Google","Chrome","Application","chrome.exe"),...X(Z,"Microsoft","Edge","Application","msedge.exe"),...X([...Z,...Q],"BraveSoftware","Brave-Browser","Application","brave.exe")]}function k9($){try{return s1($,n1.X_OK),Q$($)&&DQ($).isFile()}catch{return!1}}function J$($,Z=process.platform){let Q=Z==="darwin"?AQ:Z==="linux"?X$:Z==="win32"?t1():null;return Q?($??Q).find(k9)??null:null}function e1(){if(!process.versions.bun)return;let $=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,$))return;let Z=[];TQ.spawn=new Proxy(TQ.spawn,{apply(Q,X,J){let Y=Reflect.apply(Q,X,J),z=J[1],F=J[2]?.stdio;if(Array.isArray(z)&&z.includes("--remote-debugging-pipe")&&Array.isArray(F)&&F[3]==="pipe"&&F[4]==="pipe")Z.push(Y);return Y}}),Object.defineProperty(globalThis,$,{value:Z})}async function K8($){if(e1(),$!==void 0){if(!Q$($))throw Error("hands_browser_driver_path_must_be_absolute");let X=s0($,"package.json"),J=JSON.parse(i1(X,"utf8"));if(J.name!==z8.driver)throw Error("hands_browser_wrong_driver");let Y=_Q(X)($),z=Y.default?.chromium??Y.chromium;if(!z)throw Error("hands_browser_missing_chromium");return{version:J.version,chromium:z}}let[Z,Q]=await Promise.all([import("./index-vaq4cqv7.js"),import("./package-jr4xjp4y.js").then((m)=>l1(m.default,1))]);return{version:Q.default.version,chromium:Z.chromium}}var $7=($,Z=z8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Z}),Z7=($)=>$.loadDriver?.()??K8($.driverModuleDirectory),Q7={"1.60.0":"1223"};function n5(){let $=process.platform,Z=Q7[z8.driverVersion];if(!Z||$!=="linux"&&$!=="darwin"&&$!=="win32")return!1;let Q=(X)=>process.env[X]??process.env[`npm_config_${X.toLowerCase()}`]??process.env[`npm_package_config_${X.toLowerCase()}`];try{let X=Q("PLAYWRIGHT_BROWSERS_PATH"),J=X==="0"?s0(a1(_Q(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?o1(Q("INIT_CWD")||process.cwd(),X):s0($==="darwin"?s0(Z$(),"Library","Caches"):$==="win32"?process.env.LOCALAPPDATA||s0(Z$(),"AppData","Local"):process.env.XDG_CACHE_HOME||s0(Z$(),".cache"),"ms-playwright");return DQ(s0(J,`chromium-${Z}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function F9($={}){return xQ($,z8.driverVersion)}async function Y$($,Z={}){if($.driverVersion!=="1.61.1"||!Q$($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return xQ({...Z,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function xQ($,Z){let Q=(G)=>$7(G,Z),X=$.platform??process.platform;if(X!=="linux"&&X!=="darwin"&&X!=="win32")return Q("unsupported_platform");let J;try{J=await Z7($)}catch{return Q("driver_missing")}if(J.version!==Z)return Q("driver_version_mismatch");let Y=(G,V)=>({status:"resolved",executablePath:G,source:V,driverVersion:J.version});if($.executablePath!==void 0)return k9($.executablePath)?Y($.executablePath,"configured"):Q("executable_missing");let z=J.chromium.executablePath();if(k9(z))return Y(z,"managed");let F=$.allowSystemBrowser===!0?J$($.systemCandidates,X):null;return F?Y(F,"system"):Q("executable_missing")}var L7=["/usr/local/bin/chromium",...X$];function N7($,Z=bQ()){return J$($??(Z==="linux"?L7:void 0),Z)}async function M7(){try{return(await K8()).chromium}catch{return V7(import.meta.url)("playwright-core").chromium}}var j7=1048576,q7=105000,C7=20000,RQ=5000,T7=2000,O7=1000,D7=30000,EQ=81920,_7={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function A7($,Z){let Q=new URL($.url()),X={...await $.allHeaders(),host:Q.host};for(let J of Object.keys(X))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(J))delete X[J];return new Promise((J,Y)=>{let F=(Q.protocol==="https:"?W7:H7)(Q,{method:$.method(),headers:X,agent:!1,lookup:(V,B,H)=>{let K=n0.isIP(Z);if(B.all)H(null,[{address:Z,family:K}]);else H(null,Z,K)}},(V)=>{let B=[],H=0;V.on("data",(K)=>{if(H+=K.length,H>33554432)F.destroy(Error("hands_browser_response_too_large"));else B.push(K)}),V.on("error",Y),V.on("end",()=>{let K={};for(let[L,U]of Object.entries(V.headers))if(U!==void 0&&!["transfer-encoding","connection","content-length"].includes(L))K[L]=Array.isArray(U)?U.join(`
|
|
306
306
|
`):U;J({status:V.statusCode??502,headers:K,body:Buffer.concat(B)})})}),G=setTimeout(()=>F.destroy(Error("hands_browser_fetch_timeout")),D7);F.once("close",()=>clearTimeout(G)),F.on("error",Y),F.end($.postDataBuffer()??void 0)})}async function x7($,Z,Q=()=>{},X={lookup:(J)=>F7(J,{all:!0}),fetch:A7}){let J=new WeakSet,Y=new WeakMap,z=(F)=>{let G=Y.get(F);if(G)return G;let V=(async()=>{if(!$.newCDPSession)return;let B=await $.newCDPSession(F),H=new Map;B.on("Network.loadingFinished",({requestId:K})=>H.delete(K)),B.on("Network.loadingFailed",({requestId:K})=>H.delete(K)),B.on("Fetch.requestPaused",async(K)=>{let L=K.networkId??K.requestId,U=K.redirectedRequestId?(H.get(L)??0)+1:0;H.set(L,U);let W=b9(K.request.url,Z),j=Z.mode==="enforce"&&Boolean(K.redirectedRequestId)&&W.host!==null&&!n0.isIP(W.host),O=!W.allowed?W:j?{...W,allowed:!1,reason:"destination_not_allowed"}:U>20?{...W,allowed:!1,reason:"redirect_not_supported"}:null;try{if(O)Q(O),await B.send("Fetch.failRequest",{requestId:K.requestId,errorReason:"BlockedByClient"});else await B.send("Fetch.continueRequest",{requestId:K.requestId})}catch{await B.send("Fetch.failRequest",{requestId:K.requestId,errorReason:"Failed"}).catch(()=>{})}}),await B.send("Network.enable"),await B.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),J.add(F)})();return Y.set(F,V),V};return await $.route("**/*",async(F)=>{let G=F.request().url(),V=b9(G,Z);if(V.allowed&&Z.mode==="public_web"){await F.continue();return}let B=F.request();if(V.allowed&&V.host&&n0.isIP(V.host)&&B.isNavigationRequest?.()){let H=B.frame();if(J.has(H.page())&&H===H.page().mainFrame()){await F.continue();return}}if(V.allowed&&(Z.mode==="off"||V.reason==="local_document")){await F.continue();return}if(V.allowed&&V.host)try{let H=V.host,K=l0(H),L,U=await(async()=>{if(K!=="hostname")return[{address:H,family:n0.isIP(H)}];if(V.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([X.lookup(H),new Promise((W,j)=>{L=setTimeout(()=>j(Error("hands_browser_dns_timeout")),5000)})])}finally{if(L)clearTimeout(L)}})();if(!U.length||U.some(({address:W})=>{let j=l0(W);return!n0.isIP(W)||Z.mode==="enforce"&&$$(W,Z.deniedHosts)||(V.reason==="loopback"?j!=="loopback":j!=="public")}))V={...V,allowed:!1,reason:"private_network"};else{let W=await X.fetch(F.request(),U[0].address);if(W.status>=300&&W.status<400){let j=W.headers.location??G;try{j=new URL(j,G).href}catch{}let O=b9(j,Z);V=O.allowed?{...O,allowed:!1,reason:"redirect_not_supported"}:O}else{await F.fulfill(W);return}}}catch{await F.abort("failed");return}Q(V),await F.abort("blockedbyclient")}),await $.routeWebSocket("**/*",async(F)=>{let G=b9(F.url(),Z);if(Z.mode==="enforce"&&G.allowed&&(!G.host||!n0.isIP(G.host)))G={...G,allowed:!1,reason:"destination_not_allowed"};if(G.allowed){F.connectToServer();return}Q(G),await F.close({code:1008,reason:"Reason egress policy denied"})}),Z.mode==="off"?void 0:{preparePage:z}}async function kQ($,Z=bQ(),Q){if(Q){let J=await Y$(Q,{platform:Z,systemCandidates:$});return J.status==="resolved"?J.executablePath:null}if($!==void 0){let J=N7($,Z);if(J)return J}let X=await F9({platform:Z,systemCandidates:$,allowSystemBrowser:!0});return X.status==="resolved"?X.executablePath:null}function SQ($,Z){if(!$)throw Error("hands_repl_workspace_required");let Q=z$($),X=V9($),J=K$(X,V9(X,Z)),z=J!==".."&&!J.startsWith(`..${F$}`)&&!PQ(J)?V9(Q,J):V9(Q,Z);if(b0(V9(X,Z))||b0(z))throw Error("hands_repl_protected_path");let F=(U)=>{let W=K$(Q,U);return W!==""&&W!==".."&&!W.startsWith(`..${F$}`)&&!PQ(W)},G=z$(z);if(b0(G))throw Error("hands_repl_protected_path");if(!F(z)||!F(G))throw Error("hands_repl_file_outside_workspace");let V=K$(Q,z).split(F$),B=[Q,...V.map((U,W)=>V9(Q,...V.slice(0,W+1)))],H=B.map((U)=>IQ(U));if(H.some((U)=>U.isSymbolicLink()))throw Error("hands_repl_file_symlink");let K=H[H.length-1];if(!K.isFile()||K.nlink!==1||K.size>16777216)throw Error("hands_repl_file_not_regular_or_too_large");let L=G7(z,G$.O_RDONLY|G$.O_NOFOLLOW|G$.O_NONBLOCK);try{let U=Y7(L);if(U.dev!==K.dev||U.ino!==K.ino||!U.isFile())throw Error("hands_repl_file_changed");for(let C=0;C<B.length;C++){let A=IQ(B[C]);if(A.dev!==H[C].dev||A.ino!==H[C].ino||A.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!F(z$(z)))throw Error("hands_repl_file_outside_workspace");let W=Buffer.alloc(16777217),j=0;while(j<W.length){let C=z7(L,W,j,W.length-j,null);if(!C)break;j+=C}if(j===W.length)throw Error("hands_repl_file_too_large");let O=W.subarray(0,j);return{name:U7(z),mimeType:_7[B7(z).toLowerCase()]??"application/octet-stream",buffer:O}}finally{J7(L)}}function H9($,Z){$.end(`${JSON.stringify(Z)}
|
|
307
307
|
`)}function F8($){try{K7($)}catch{}}async function fQ($){if($.managedBrowser&&$.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let Z=$.launch||$.targetContext?null:$.managedBrowser?await Y$($.managedBrowser,{executablePath:$.browserExecutablePath}):await F9({executablePath:$.browserExecutablePath,driverModuleDirectory:$.driverModuleDirectory});if(Z?.status==="unavailable")throw Error(`hands_browser_${Z.reason}`);let Q=Z?.status==="resolved"?Z.executablePath:$.browserExecutablePath;if(!Q||!k9(Q))throw Error("hands_browser_unavailable");let X=$.launch??(async(N)=>($.targetContext?await M7():(await K8($.managedBrowser?.driverModuleDirectory??$.driverModuleDirectory)).chromium).launch(N)),J=[],Y={},z=null,F=null,G=null,V=null,B=!1,H=null,K=new Map,L=new WeakMap,U=null,W=()=>{if(B)throw Error("hands_repl_stopped");if(V)throw V},j=(N)=>{let M=L.get(N);if(M)return M;let D=Promise.resolve().then(()=>N.close()).then(()=>{K.delete(N)});return L.set(N,D),D},O=async()=>{let N=[...K.entries()].reverse(),M=U??=performance.now()+O7,D=Promise.allSettled(N.filter(([,_])=>_==="context").map(([_])=>j(_))),w;try{await Promise.race([D,new Promise((_)=>{w=setTimeout(_,Math.max(0,M-performance.now()))})])}finally{if(w)clearTimeout(w)}let k=await Promise.allSettled(N.map(([_])=>j(_))),m=[];for(let[_,g]of k.entries()){if(g.status!=="rejected")continue;let c=g.reason instanceof Error&&["Error","TimeoutError","ProtocolError"].includes(g.reason.name)?g.reason.name:"unknown";m.push(Error(`hands_repl_close_failed: ${N[_][1]}: ${c}`))}if(m.length)throw AggregateError(m,"hands_repl_stop_unconfirmed")},C=(N,M)=>{if(K.set(N,M),B||V)j(N).catch(()=>{return}),W();return N},A=async()=>{let N=await X({executablePath:Q,headless:!0,chromiumSandbox:$.managedBrowser===void 0,args:["--disable-background-networking","--disable-quic","--disable-dev-shm-usage","--disable-gpu","--disable-software-rasterizer","--dns-prefetch-disable","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--no-pings"]}),M=null;try{C(N,"browser"),M=$.targetContext??C(await N.newContext({viewport:{width:1440,height:900},screen:{width:1440,height:900},serviceWorkers:"block",acceptDownloads:!1}),"context");let D=await x7(M,$.networkPolicy??{mode:"off"},$.onEgressDenied);if(W(),D){let b=M.newPage.bind(M);M.newPage=async()=>{let h=await b();return await D.preparePage(h),h}}let k=M.pages()[0]??await M.newPage();await D?.preparePage(k),W();let m=async(b=k)=>{let h=b;if(typeof h.ariaSnapshot==="function")return h.ariaSnapshot({timeout:1e4});return k.locator("body").innerText({timeout:1e4})},_=async(b,h={})=>{let d=h&&typeof h==="object"&&!Array.isArray(h)?h:{},n,z0="image/png";if(Buffer.isBuffer(b)||b instanceof Uint8Array)n=Buffer.from(b);else if(typeof b==="string"&&(b.startsWith("data:")||/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(b)))n=Buffer.from(b.replace(/^data:[^,]*,/,""),"base64");else if(typeof b==="string"){let T0=SQ($.workspaceRoot,b);n=T0.buffer,z0=T0.mimeType}else throw Error("view() needs a Buffer, a base64 string, or a path to an image file");if(n.length===0)throw Error("view(): the image is empty");let M0=String(d.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),W0=Number(d.maxWidth)||1024,U0=Number(d.quality)||72,g0=$.targetContext?await N.newPage():await M.newPage();try{let T0=`data:${z0};base64,${n.toString("base64")}`;for(let t=0;t<5;t+=1){let j0=await g0.evaluate(async(B0)=>{let q0=new Image;q0.src=B0.url,await q0.decode();let h0=Math.min(1,B0.maxWidth/q0.naturalWidth),G0=document.createElement("canvas");G0.width=Math.max(1,Math.round(q0.naturalWidth*h0)),G0.height=Math.max(1,Math.round(q0.naturalHeight*h0));let X0=G0.getContext("2d");if(!X0)throw Error("view(): canvas unavailable");return X0.fillStyle="#ffffff",X0.fillRect(0,0,G0.width,G0.height),X0.drawImage(q0,0,0,G0.width,G0.height),{data:G0.toDataURL("image/jpeg",B0.q/100).split(",")[1]??"",width:G0.width,height:G0.height,sourceWidth:q0.naturalWidth,sourceHeight:q0.naturalHeight}},{url:T0,maxWidth:W0,q:U0}),$9=Buffer.from(j0.data,"base64");if($9.length<=EQ){let B0=M0||"image";return`<<<ARA_VIEW_IMAGE ${j0.data} image/jpeg ${B0}>>>
|
|
308
308
|
Viewing ${B0} (${j0.sourceWidth}x${j0.sourceHeight} source, sent at ${j0.width}x${j0.height}, ${Math.round($9.length/1024)}KB).`}if(W0>640)W0=Math.round(W0*0.75);else U0=Math.max(30,U0-15)}throw Error(`view(): could not reduce the image under ${Math.round(EQ/1024)}KB`)}finally{await g0.close().catch(()=>{return})}},g=BQ({browser:$.targetContext?.browser()??N,context:M,page:k,a11y:m,view:_,readWorkspaceFile:(b)=>SQ($.workspaceRoot,b),privateProfile:$.privateProfile,beforeNavigation:$.beforeNavigation,recording:$.recording,screenshotExport:$.screenshotExport,actionRecorder:()=>{let b=J,h=Y;return(d,n)=>{if(b.length<wQ)b.push(d);if(n)h.page=n}}}),c=async(b)=>{W();let h=C(await N.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await h.route("**/*",(n)=>n.abort()),W(),await h.routeWebSocket("**/*",(n)=>n.close({code:1008,reason:"Reason evaluator network denied"})),W(),await h.exposeBinding("__araHandsRpc",async(n,z0)=>$.onBrowserOperation?$.onBrowserOperation(b,()=>g.dispatch(z0)):g.dispatch(z0)),W();let d=await h.newPage();return W(),await d.goto("data:text/html,<title>Reason Hands evaluator</title>"),W(),await d.evaluate(`(${JQ})(${JSON.stringify(g.roots)})`),{context:h,page:d,runId:b}}catch(d){throw await j(h).catch(()=>{return}),d}},u=await c(),r={browser:N,context:M,page:k,evaluator:u,async captureProgressFrame(b){return _(await b.screenshot({type:"jpeg",quality:65,timeout:2000}),{label:"Screen after browser action"})},async resetEvaluator(b){await j(r.evaluator.context),r.evaluator=await c(b)}};return W(),r}catch(D){throw await O().catch(()=>{return}),D}},R=async()=>{if(W(),z)return z;if(!G){F=A();let N;G=Promise.race([F,new Promise((M,D)=>{N=setTimeout(()=>D(Error("hands_browser_unavailable: startup timed out")),C7)})]).then((M)=>{return W(),z=M,M}).catch(async()=>{V=Error("hands_browser_unavailable: startup failed or timed out");let M;try{await Promise.race([O(),new Promise((D,w)=>{M=setTimeout(()=>w(Error("hands_repl_stop_timeout")),RQ)})])}catch{V=Error("hands_browser_unavailable: startup cleanup unconfirmed")}finally{if(M)clearTimeout(M)}throw V}).finally(()=>{if(N)clearTimeout(N)})}return G},I=async(N,M,D=!1)=>{let w=await R(),k=Y;if($.onBrowserOperation&&w.evaluator.runId!==M)await w.resetEvaluator(M);let _=(async()=>{let u=await w.evaluator.page.evaluate(`(${YQ})(${JSON.stringify({code:N})})`);if(typeof u!=="string")throw Error("hands_repl_invalid_evaluator_output");let r=k.page;if(D&&r&&!u.includes("<<<ARA_VIEW_IMAGE")){let b=()=>w.captureProgressFrame(r);try{let h=await($.onBrowserOperation?$.onBrowserOperation(M,b):b());return k.automaticProgressImage=!0,`${u}
|
|
@@ -455,4 +455,4 @@ lines.on("line", (line) => {
|
|
|
455
455
|
`,(S)=>{if(!S)return;B(T,void 0,S)})});try{if(!G){if(Q.pid===void 0)await m9(X);throw J??Error("hands_node_repl_control_pipe_missing")}let C=await U({action:"probe"});if(C.ok!==!0||C.output!=="ARA_HANDS_REPL_READY")throw Error("hands_node_repl_probe_failed")}catch(C){Y=!0,Q.kill("SIGKILL");try{await m9(X)}finally{await Z.cleanup()}throw C}let W=Promise.resolve(),j=new Set;j$($.socketPath);let O=q6.createServer((C)=>{j.add(C),C.once("close",()=>j.delete(C)),C.setEncoding("utf8");let A="",R=!1,I=!1;C.once("close",()=>{if(I)H()}),C.on("error",()=>C.destroy()),C.on("data",(T)=>{if(R)return;if(A+=T,A.length>Y4){R=!0,M8(C,{ok:!1,error:"REPL request exceeds 1 MiB"});return}let S=A.indexOf(`
|
|
456
456
|
`);if(S===-1)return;R=!0;let y=A.slice(0,S);W=W.then(async()=>{if(C.destroyed)return;try{let E=JSON.parse(y);if(E.action!=="evaluate"||typeof E.code!=="string")throw Error("Invalid REPL request");I=!0;let N=await U({action:"evaluate",code:E.code});if(I=!1,N.ok!==!0||typeof N.output!=="string")throw Error(typeof N.error==="string"?N.error:"hands_node_repl_failed");M8(C,{ok:!0,output:N.output})}catch(E){I=!1,M8(C,{ok:!1,error:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0})}}).catch((E)=>{M8(C,{ok:!1,error:E instanceof Error?E.message:String(E)})})})});try{await new Promise((C,A)=>{O.once("error",A),O.listen($.socketPath,()=>{O.off("error",A);try{U6($.socketPath,384),C()}catch(R){O.close(()=>A(R))}})})}catch(C){Y=!0,Q.kill("SIGKILL");try{await m9(X)}finally{await Z.cleanup(),j$($.socketPath)}throw C}return{socketPath:$.socketPath,async stop(){if(Y)return;Y=!0;let C=new Promise((A)=>O.close(()=>A()));for(let A of j)A.destroy();await C,W.catch(()=>{return}),H();try{await m9(X)}finally{await Z.cleanup(),j$($.socketPath)}}}}var T$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var z4="/workspace",K4="/var/lib/reason/sessions",I6="/var/lib/reason/session-controls";function F4($){let Z=`${K4}/`;if(!$.startsWith(Z))return null;let Q=$.slice(Z.length);if(!T$.test(Q)||Q!==Q.toLowerCase())throw Error("personal_computer_invalid_runtime_root");return`${I6}/${Q}/job.env`}function P6($){if(!T$.test($))throw Error("personal_computer_invalid_identity");return $.toLowerCase()}function q8($){let Z=P6($);return{runtimeRoot:`${K4}/${Z}`,workspaceRoot:`${z4}/sessions/${Z}`,sharedRoot:z4}}var V4="/root/.ara/cloud-browser/repl.sock";function O$($){return $==="compute"}function H4($,Z,Q="linux"){if($)q8($);if(Q!=="linux")throw Error("cloud_browser_os_invalid");if(Z!==void 0&&(!$||!/^[1-9][0-9]{0,18}$/.test(Z)))throw Error("cloud_browser_generation_invalid");let X=$?`/var/lib/reason/browsers/${$.toLowerCase()}`:"/root/.ara/cloud-browser",J=$?`${X}/${Z?`g${Z}`:"current"}`:X,Y=$?`/root/.b/${$.toLowerCase().replaceAll("-","")}`:X;return{temporarySessionDirectory:Y,temporaryDirectory:$?`${Y}/${Z??"current"}`:`${J}/tmp`,directory:J,sessionDirectory:X,config:`${J}/config.json`,status:`${J}/status.json`,socket:`${J}/repl.sock`,bundle:`${J}/driver.mjs`,processName:$?`ara-browser-${$.toLowerCase()}${Z?`-${Z}`:""}`:"ara-cloud-browser"}}var D$="browser_egress",W4=fZ,p6=45000,u6=o9+1500,y0=/^[A-Za-z0-9._:-]{1,160}$/,l6="/run/ara-hands";function s6($,Z,Q=D4()){if($==="darwin")return{temporaryRoot:Q,prepareRoot:!1,sessionMode:448};return{temporaryRoot:Z??l6,prepareRoot:!0,sessionMode:457}}function U4($,Z=process.platform,Q=process.geteuid?.()){return $===!0&&Z==="linux"&&Q===0}function x$($=q4(),Z=process.platform,Q=process.geteuid?.()){return $&&Z==="linux"&&Q===0?{uid:$.uid,gid:$.gid,home:$.home,username:$.username}:null}function n6($=x$(),Z=yQ){return $&&Z()?V$:null}function qG($=x$(),Z=process.platform,Q=process.geteuid?.()){return Z!=="linux"||Q!==0||$!==null}function CG($=process.platform,Z=process.geteuid?.()){return $!=="linux"||Z!==0}function i6($,Z){if(!Z&&($??"linux")==="linux")return V4;return H4(Z,void 0,$??"linux").socket}function a6($){return $[N0]===!0?"sandbox_loopback":"ara_device_wss"}function N9($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function A4($){let Z=$.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z.endsWith(".localhost")||Z==="::1"||Z==="0:0:0:0:0:0:0:1"||Z==="0.0.0.0"||Z.startsWith("127.")}class x4 extends q{expiryDiagnostic;constructor($){super("invalid_hands_expiry","Reason Hands connection expiry is invalid.");this.expiryDiagnostic=$}}function o6($){return N9($)&&Object.keys($).every((Z)=>Z==="source_path"||Z==="branch")&&($.source_path===void 0||i0($.source_path))&&typeof $.branch==="string"&&U$.test($.branch)}function r6($,Z,Q){let X=Z===void 0?Date.now():Z,J=["relay_url","session_id","environment_id","expires_at","policy_mode","policy_version","hands_protocol_version","hands_worker_version","hands_worker_artifact_sha256","hands_worker_entrypoint","target_generation","target_fence_id"],Y=new Set([...J,"workspace_id","legacy_workspace_id",o0,r0,"environment_binding","cloud_browser","sandbox_provider","sandbox_os","personal_workspace","workspace_path","workspace_worktree",p,N0,D$,U9,C0,t0,m0]),z=N9($)?$:null,F=z?.[D$],G=z?.[U9],V=z?.[t0],B=F===void 0||(z?.[p]===f0||V===y9&&z?.[p]===void 0)&&N9(F)&&Object.keys(F).every((C)=>C==="mode"||C==="allowed_domains")&&F.mode==="enforce"&&Array.isArray(F.allowed_domains)&&F.allowed_domains.length<=256&&F.allowed_domains.every((C)=>typeof C==="string"&&e8(C));if(!N9($)||J.some((C)=>!(C in $))||Object.keys($).some((C)=>!Y.has(C))||!B||V!==void 0&&V!==y9||z?.[m0]!==void 0&&z[m0]!==O8||z?.personal_workspace!==void 0&&(z.personal_workspace!==!0||z[p]!==f0)||z?.cloud_browser!==void 0&&(z.cloud_browser!==!0||z[p]!==f0)||z?.sandbox_provider!==void 0&&!O$(z.sandbox_provider)||z?.sandbox_os!==void 0&&z.sandbox_os!=="linux"||G!==void 0&&(z?.[p]!==W9||!H$(G))||p in $&&$[p]!==f0&&$[p]!==W9&&$[p]!==L0||N0 in $&&$[N0]!==!0||$.workspace_path!==void 0&&(!i0($.workspace_path)||$[p]!==L0)||$.workspace_worktree!==void 0&&($.workspace_path===void 0||!o6($.workspace_worktree))||typeof $.relay_url!=="string"||typeof $.session_id!=="string"||!y0.test($.session_id)||$.workspace_id!==void 0&&(typeof $.workspace_id!=="string"||!y0.test($.workspace_id))||$.legacy_workspace_id!==void 0&&(typeof $.legacy_workspace_id!=="string"||!y0.test($.legacy_workspace_id))||$[o0]!==void 0&&($[o0]!==D8||(p in $))||$[r0]!==void 0&&($[r0]!==_8||(p in $))||$[C0]!==void 0&&(typeof $[C0]!=="string"||!y0.test($[C0]))||typeof $.environment_id!=="string"||!y0.test($.environment_id)||typeof $.expires_at!=="string"||$.policy_mode!=="full_access"||$.policy_version!==1||$.hands_protocol_version!==j9||$.hands_worker_version!==q9||$.hands_worker_artifact_sha256!==F0||!eQ($.hands_worker_entrypoint)||!w0($.target_generation)||!O0($.target_fence_id))throw new q("invalid_hands_payload","Reason Hands connection payload is invalid.");let H;try{H=new URL($.relay_url)}catch{throw new q("invalid_hands_relay","Reason Hands relay URL is invalid.")}let K=$[N0]===!0,L=A4(H.hostname);if((K?H.protocol!=="ws:"||!L:L?H.protocol!=="ws:":H.protocol!=="wss:")||H.username||H.password||H.hash||!/^\/device\/[A-Za-z0-9-]+\/[A-Za-z0-9]+$/.test(H.pathname))throw new q("invalid_hands_relay","Reason Hands relay URL is not allowed.");let U=Date.parse($.expires_at),W=Number.isNaN(U)?"parse":new Date(U).toISOString()!==$.expires_at?"noncanonical":U<=X?"expired":U-X>W4?"over_cap":"accepted",j={version:1,outcome:W,clock_source:Z===void 0?"date_now":"injected",validation_now_ms:G9(X),expiry_ms:G9(U),remaining_ms:Number.isSafeInteger(U-X)?U-X:null,maximum_lifetime_ms:W4,cli_artifact:$4()};if(W!=="accepted")throw new x4(j);try{Q?.(j)}catch{}let O=$.environment_binding===void 0?void 0:l8.safeParse($.environment_binding);if(O&&!O.success)throw new q("invalid_hands_request","Reason Hands environment binding is invalid.");return{...$.cloud_browser===!0?{cloud_browser:!0}:{},...O$($.sandbox_provider)?{sandbox_provider:$.sandbox_provider}:{},...$.sandbox_os==="linux"?{sandbox_os:$.sandbox_os}:{},...$.personal_workspace===!0?{personal_workspace:!0}:{},relay_url:H.toString(),...O?.success?{environment_binding:O.data}:{},session_id:$.session_id,...$.workspace_id===void 0?{}:{workspace_id:$.workspace_id},...$.legacy_workspace_id===void 0?{}:{legacy_workspace_id:$.legacy_workspace_id},...$[o0]===D8?{[o0]:D8}:{},...$[r0]===_8?{[r0]:_8}:{},...typeof $[C0]==="string"?{[C0]:$[C0]}:{},...$[t0]===y9?{[t0]:y9}:{},...$[m0]===O8?{[m0]:O8}:{},...typeof $.workspace_path==="string"?{workspace_path:$.workspace_path}:{},...N9($.workspace_worktree)?{workspace_worktree:{...typeof $.workspace_worktree.source_path==="string"?{source_path:$.workspace_worktree.source_path}:{},branch:String($.workspace_worktree.branch)}}:{},environment_id:$.environment_id,expires_at:$.expires_at,policy_mode:"full_access",policy_version:1,hands_protocol_version:j9,hands_worker_version:q9,hands_worker_artifact_sha256:F0,hands_worker_entrypoint:a0,target_generation:$.target_generation,target_fence_id:$.target_fence_id,...p in $?{[p]:$[p]}:{},...K?{[N0]:!0}:{},...G===void 0?{}:{[U9]:G},...F===void 0?{}:{[D$]:{mode:"enforce",allowed_domains:[...new Set(F.allowed_domains)].sort()}}}}function t6(){let $=new Map;return{acquire(Z,Q){if($.has(Z))return null;let X=[...$.values()],J=(z)=>Q.group!==void 0&&z.group===Q.group;if(Q.exclusive?!X.every(J):X.some((z)=>z.exclusive))return null;if(Q.limit!==void 0&&!X.some(J)&&new Set(X.map((z,F)=>z.group??F)).size>=Q.limit)return null;$.set(Z,Q);let Y=!1;return()=>{if(Y)return;Y=!0,$.delete(Z)}},activeOwners:()=>[...$.keys()]}}var e6=t6();function $2($,Z){C9($,{recursive:!0,mode:448});let Q=s($),X=()=>new q("invalid_hands_workspace","Reason Hands managed workspace ancestor must be a real directory, not a link.");for(let z of Z.split("/")){let F=a(Q,z);try{let V=o(F);if(V.isSymbolicLink()||!V.isDirectory())throw X()}catch(V){if(!(V&&typeof V==="object"&&("code"in V)&&V.code==="ENOENT"))throw V;try{C9(F,{mode:448})}catch(B){if(!(B&&typeof B==="object"&&("code"in B)&&B.code==="EEXIST"))throw B}}let G=o(F);if(G.isSymbolicLink()||!G.isDirectory()||s(F)!==F)throw X();Q=F}if(process.platform==="win32"){let z=o(Q);if(z.isSymbolicLink()||!z.isDirectory()||s(Q)!==Q||!A0(s($),Q))throw X();return Q}let J=o(Q),Y=m6(Q,M9.O_RDONLY|M9.O_DIRECTORY|M9.O_NOFOLLOW);try{let z=f6(Y);if(!z.isDirectory()||z.dev!==J.dev||z.ino!==J.ino||s(Q)!==Q)throw X();k6(Y,448)}finally{b6(Y)}return Q}function Z2($,Z=j4(),Q,X,J){if(!y0.test($)||Q!==void 0&&!y0.test(Q))throw new q("invalid_hands_workspace","Reason Hands run identity is invalid.");let Y=Y0(u0({kind:"managed",workspaceId:$,...X?{base:X}:{},...J?{layout:J}:{}})),z=$2(Z,Y0(Y)),F=a(z,c6(Y)),G=!1;try{let K=o(F);if(G=!0,K.isSymbolicLink())throw new q("invalid_hands_workspace","Reason Hands workspace cannot be a symbolic link.");if(!K.isDirectory())throw new q("invalid_hands_workspace","Reason Hands workspace must be a managed directory.")}catch(K){if(K instanceof q||!(K&&typeof K==="object"&&("code"in K)&&K.code==="ENOENT"))throw K}if(J&&!G)try{let K=a(s(Z),Y0(u0({kind:"managed",workspaceId:$,...X?{base:X}:{}}))),L=o(K);if(!L.isSymbolicLink()&&L.isDirectory()&&s(K)===K)C8(K,F),G=!0}catch{}if(Q&&Q!==$){let K=a(z,Q);try{let L=o(K);if(L.isSymbolicLink()||!L.isDirectory())throw new q("invalid_hands_workspace","Reason Hands legacy workspace must be a managed directory.");let U=s(K);if(Y0(U)!==z)throw new q("invalid_hands_workspace","Reason Hands legacy workspace escaped its managed parent.");let W=null;if(G){W=a(z,`.${$}.previous`);try{throw o(W),new q("invalid_hands_workspace","Reason Hands previous workspace backup already exists.")}catch(j){if(j instanceof q||!(j&&typeof j==="object"&&("code"in j)&&j.code==="ENOENT"))throw j}C8(F,W)}try{C8(U,F)}catch(j){if(W)C8(W,F);throw j}G=!0}catch(L){if(L instanceof q||!(L&&typeof L==="object"&&("code"in L)&&L.code==="ENOENT"))throw L}}C9(F,{recursive:!0,mode:448}),g9(F,448);let V=s(F);if(Y0(V)!==z)throw new q("invalid_hands_workspace","Reason Hands workspace escaped its managed parent.");let B=a(V,"repo");try{let K=o(B);if(K.isSymbolicLink()||!K.isDirectory())throw new q("invalid_hands_workspace","Reason Hands repository must be a managed directory.")}catch(K){if(K instanceof q||!(K&&typeof K==="object"&&("code"in K)&&K.code==="ENOENT"))throw K}C9(B,{recursive:!0,mode:448}),g9(B,448);let H=s(B);if(Y0(H)!==V)throw new q("invalid_hands_workspace","Reason Hands repository escaped its managed run workspace.");return{workRoot:V,repoPath:H}}function I4($){let Z=null;try{Z=o($)}catch{}if(!Z||Z.isSymbolicLink()||!Z.isDirectory()||Z.uid!==0||Z.gid!==0||(Z.mode&4095)!==493)throw new q("cloud_workspace_root_invalid","This cloud Session's workspace root is not root's 0755 directory, so Reason Hands cannot use it.")}function Q2($,Z,Q=process.geteuid?.(),X=process.platform){if(X==="win32")return"unknown";let J;try{if(J=e0($),!J.isDirectory())return"unready";w6($,M9.R_OK|M9.W_OK|M9.X_OK)}catch{return"unready"}try{if(o($).isSymbolicLink()||s($)!==$)return"unknown"}catch{return"unknown"}if(Q!==0)return"checked";if(Z===null||J.uid!==Z.uid||(J.mode&448)!==448)return"unknown";for(let Y=Y0($);;Y=Y0(Y)){let z;try{z=e0(Y)}catch{return"unknown"}if(!(z.uid===Z.uid?(z.mode&64)!==0:z.gid===Z.gid?(z.mode&8)!==0:(z.mode&1)!==0))return"unknown";if(Y===Y0(Y))return"checked"}}function X2($,Z){let Q="/";for(let X of["",...$.split("/"),...Z.split("/")].filter((J,Y)=>Y===0||J)){if(X)Q=a(Q,X);let J;try{J=o(Q)}catch{return null}if(J.uid!==0)return J.uid;if((J.mode&2)!==0&&(J.mode&512)===0&&!J.isSymbolicLink())return-1;if(J.isSymbolicLink()||!J.isDirectory())return null}return null}function J2($,Z,Q,X=process.geteuid?.(),J){if(!y0.test(Z))return null;let Y,z;try{Y=s($),z=Y0(u0({kind:"managed",workspaceId:Z,...Q?{base:Q}:{},...J?{layout:J}:{}}))}catch{return null}let F=a(Y,z),G=A$(F)!==null,V=(U)=>new q("cloud_workspace_root_invalid",U),B;if(X===0){let U=X2(Y,z);if(U===null)return null;if(!G)throw new q("invalid_hands_workspace","As root, Reason Hands never prepares a workspace in folders another user owns.");B=U}else{if(!G)return null;let U,W;try{U=o(Y0(F)),W=o(F)}catch{return null}if(U.isSymbolicLink()||!U.isDirectory()||U.uid===0||W.uid!==0)return null;B=U.uid}let H=Y;for(let U of z.split("/")){let W=a(H,U),j=!1;try{let O=o(W);j=!O.isSymbolicLink()&&O.isDirectory()&&s(W)===W}catch{}if(!j)throw V("This cloud Session's workspace root is missing or is not a real directory.");H=W}I4(F);let K;try{K=P4(F)}catch(U){if(U instanceof q)throw U;throw V("This cloud Session's workspace root changed while Reason Hands checked it.")}let L=null;try{L=e0(K.repoPath).uid}catch{}if(L!==B)throw new q("invalid_hands_workspace","Reason Hands repository must belong to the cloud Session's user.");return K}function P4($,Z=!1){let Q=s($),X=a(Q,"repo"),J;try{J=o(X)}catch{throw new q("invalid_hands_workspace","Reason Hands repository is missing from the granted root.")}if(Z){if(!/^\/var\/lib\/reason\/sessions\/[0-9a-f-]{36}$/.test(Q))throw new q("invalid_hands_workspace","Personal runtime identity is invalid.");if(q8(Q.slice(Q.lastIndexOf("/")+1)).runtimeRoot!==Q)throw new q("invalid_hands_workspace","Personal runtime identity is invalid.");let F=s("/workspace"),G=s(X);if(F!=="/workspace"||!e0(G).isDirectory()||!G.startsWith("/workspace/"))throw new q("invalid_hands_workspace","Personal files escaped the personal computer.");return{workRoot:Q,repoPath:G}}let Y=gQ(Q);if(Y&&J.isSymbolicLink()){let F=s(X);if(F!==s(Y)||!e0(F).isDirectory())throw new q("invalid_hands_workspace","Side chat repository must be its parent's checkout.");return{workRoot:Q,repoPath:F}}if(J.isSymbolicLink()||!J.isDirectory())throw new q("invalid_hands_workspace","Reason Hands repository must be a managed directory.");let z=s(X);if(Y0(z)!==Q)throw new q("invalid_hands_workspace","Reason Hands repository escaped its granted root.");return{workRoot:Q,repoPath:z}}function I$($,Z,Q){if(Z!==void 0&&!i0(Z))throw new q("invalid_hands_workspace",`Reason Hands ${Q} is invalid.`);let X=_4($,Z??".");if(!A0($,X))throw new q("invalid_hands_workspace",`Reason Hands ${Q} escapes its granted root.`);return X}function R4($,Z,Q){if(W$(Z)){let X=s(Q);return{anchor:X,target:_4(X,Z),boundary:a(X,B9)}}return{anchor:$,target:I$($,Z,"folder"),boundary:$}}function Y2($,Z){if(!A0($,Z))throw new q("invalid_hands_workspace","Reason Hands folder escapes its granted root.");let Q=$;for(let X of Z.slice($.length).split(d6).filter(Boolean)){Q=a(Q,X);let J=null;try{J=o(Q)}catch(Y){if(Y.code!=="ENOENT")throw Y}if(!J)C9(Q,{mode:448});else if(J.isSymbolicLink()||!J.isDirectory())throw new q("invalid_hands_workspace","Reason Hands folder must be made of real directories.")}}function E4($,Z){let Q=s(I$($,Z.source_path,"repository"));if(!A0($,Q)||!e0(Q).isDirectory())throw new q("invalid_hands_workspace","Reason Hands repository must be a folder in its granted root.");return Q}async function G2($,Z,Q,X=A8()){try{let J=s($);if(_$(R4(J,Z,X).target))return;return await uQ(E4(J,Q))??void 0}catch{return}}function z2($,Z,Q,X,J=K2,Y=A8()){let z=s($),{target:F,boundary:G,anchor:V}=R4(z,Z,Y);if(Q&&!_$(F)){let K=E4(z,Q);Y2(V,Y0(F));let L=["-c","core.hooksPath=/dev/null","-C",K];if(X)J([...L,"update-ref","--create-reflog","-m",X.note,`refs/heads/${Q.branch}`,X.commit,""]);let U=X?J([...L,"worktree","add",F,Q.branch]):J([...L,"worktree","add","-b",Q.branch,F]);if(!X&&U.status!==0&&/already exists/.test(U.stderr)&&!_$(F))U=J([...L,"worktree","add",F,Q.branch]);if(U.status!==0)throw new q(/not a git repository/i.test(U.stderr)?"workspace_not_git_repository":"workspace_worktree_failed","Reason could not create this Session's git worktree.")}let B;try{B=o(F)}catch{throw new q("workspace_folder_missing","This Session's folder no longer exists.")}let H=s(F);if(B.isSymbolicLink()&&!A0(G,H))throw new q("invalid_hands_workspace","Reason Hands folder resolves outside its granted root.");if(!e0(H).isDirectory()||!A0(G,H))throw new q("invalid_hands_workspace","Reason Hands folder must be a directory in its granted root.");if(b0(H))throw new q("protected_path","Credential and secret folders are unavailable to Sessions.");return H}function K2($){let Z=N4();if(!Z)return{status:null,stderr:"git was not found. Install Git for Windows (https://git-scm.com/download/win)."};let Q=S6(Z,$,{encoding:"utf8",timeout:60000,env:{...process.env,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});return{status:Q.status,stderr:Q.stderr??""}}function S4($){return F4($)??A$($)?.jobEnv??a($,"job.env")}function F2($,Z){let Q=S4($),X=o(Q);if(X.isSymbolicLink()||!X.isFile())throw new q("invalid_hands_workspace","Reason Hands job environment must be a managed regular file.");y6(Q,Z),g9(Z,384)}function V2($){if($.workspaceMode===L0&&$.workspacePath!==void 0){let z=$.home??A8(),F=z2($.grantedRoot,$.workspacePath,$.workspaceWorktree,$.workspaceWorktreeStart,void 0,z);if($.workspaceWorktree&&$.deviceId)iQ(z,$.workspacePath,$.deviceId);return{workRoot:F,repoPath:F,workspace:{kind:"root",path:$.workspacePath},jobEnvPath:a($.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!0}}if($.workspaceMode===f0)return{...P4($.grantedRoot,$.personalWorkspace),workspace:{kind:"root"},jobEnvPath:a($.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!1};if($.workspaceMode===W9||$.workspaceMode===L0){let z=o($.grantedRoot);if(z.isSymbolicLink()||!z.isDirectory())throw new q("invalid_hands_workspace","Reason Hands root must be a real directory.");let F=s($.grantedRoot);return{workRoot:F,repoPath:F,workspace:{kind:"root"},jobEnvPath:a($.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!0}}let Z=$.workspaceId??$.runId,Q={kind:"managed",workspaceId:Z,...$.workspaceBase?{base:$.workspaceBase}:{},...$.workspaceLayout?{layout:$.workspaceLayout}:{}},X=t9($.grantedRoot,Q,$.home).anchor,J=J2(X,Z,$.workspaceBase,void 0,$.workspaceLayout);if(J)return{...J,workspace:Q,jobEnvPath:a($.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!1,cloudSessionRoot:!0};let Y=Z2(Z,X,$.legacyWorkspaceId,$.workspaceBase,$.workspaceLayout);return{...Y,workspace:Q,jobEnvPath:a($.temporaryDirectory,"job.env"),workspacePoolPath:Y0(Y.workRoot),managedWorkspace:!0}}function H2($){let{command:Z,prefix:Q}=s8($.executablePath,$.sourceEntrypoint),X=j8({home:v6(),temporaryDirectory:$.temporaryDirectory,path:$.path});if(X.REASON_DEVICE_ROOT=X.ARA_DEVICE_ROOT=$.grantedRoot,X.REASON_HANDS_WORKSPACE=X.ARA_HANDS_WORKSPACE=$.workRoot,X.REASON_HANDS_REPO=X.ARA_HANDS_REPO=$.root,$.workspacePoolPath)X.REASON_HANDS_WORKSPACE_POOL=X.ARA_HANDS_WORKSPACE_POOL=$.workspacePoolPath;return{command:Z,args:[...Q,"__device","__hands-worker","--config",$.configPath],options:{cwd:$.root,env:X,shell:!1,stdio:[W2,"ignore","pipe"]}}}var W2=process.platform==="win32"?"pipe":"ignore";function B4($,Z){if(process.platform!=="win32")return $.kill(Z);if(Z==="SIGTERM")$.stdin?.end();else if($.pid)M4($.pid);return!0}function U2($,Z){let Q="",X=!1,J=Date.now(),Y=0,z=new Set(["connecting","open","dial_pending","socket_error","close","claim_accepted","claim_rejected","stopping","stopped","request_cancelled","permission_denied"].map((H)=>`hands.worker.${H}`)),F=new Set([null,"open_not_received","current_connection","obsolete_connection","request_aborted","request_timeout","client_closed","driver_stopped","driver_handoff","run_cancelled","run_finished","other","frame_too_large","invalid_json","invalid_claim","executor_mismatch","stale_generation","fence_conflict","SIGTERM","SIGINT","SIGHUP","expired","cleanup_complete","cleanup_failed","cancelled","settled","unsupported","unconfirmed",...["sandbox_policy","os_permission_unknown"].flatMap((H)=>["bash","read","write","edit"].map((K)=>`${H}:${K}`))]),G=["timestampMs","connectionAttempt","connectionGeneration","targetGeneration","activeRequestCount","remainingLifetimeMs","suppressedDiagnostics"],V=["peerGeneration","socketState","closeCode"],B=new Set(["event","reason","launchId",...G,...V]);return(H)=>{for(let K of H.toString().split(/(?<=\n)/)){let L=K.endsWith(`
|
|
457
457
|
`);if(!X&&Q.length+K.length<=2048)Q+=K;else X=!0;if(!L)continue;let U=Q;if(Q="",X){X=!1;continue}try{let W=JSON.parse(U);if(!W||typeof W!=="object"||Array.isArray(W)||Object.keys(W).some((j)=>!B.has(j))||!z.has(W.event)||!F.has(W.reason)||W.event==="hands.worker.permission_denied"!==(typeof W.reason==="string"&&W.reason.includes(":"))||W.launchId!==$||G.some((j)=>!Number.isSafeInteger(W[j])||W[j]<0)||V.some((j)=>W[j]!==null&&(!Number.isSafeInteger(W[j])||W[j]<0)))continue;if(Date.now()-J>=60000)J=Date.now(),Y=0;if(Y>=122)continue;Y+=1,Z(W)}catch{}}}}async function B2($){let Z=$.now()+$.timeoutMs;while($.now()<Z){if($.signal.aborted)throw new q("cancelled","Reason Hands start was cancelled.");if($.spawnFailed?.()||$.child.exitCode!==null||$.child.signalCode!==null)throw new q("hands_worker_exited","Reason Hands exited before ready.");let Q=N8($.path,{pid:$.child.pid??-1,launchId:$.launchId,workerVersion:q9,protocolVersion:j9,workerArtifactSha256:F0,workerEntrypoint:a0});if(Q?.targetGeneration===$.targetGeneration&&Q.fenceId===$.fenceId)return Q;await new Promise((X)=>setTimeout(X,10))}throw new q("hands_ready_timeout","Reason Hands did not become ready.")}async function L2($,Z){let Q=()=>$.exitCode===0&&$.signalCode===null;if($.exitCode!==null||$.signalCode!==null)return Q()?"stopped":"already_exited";let X=new Promise((z)=>$.once("exit",()=>z()));try{if(!B4($,"SIGTERM"))return Q()?"stopped":"unobserved"}catch{return Q()?"stopped":"unobserved"}if(await L4(X,Z))return Q()?"stopped":"unobserved";try{B4($,"SIGKILL")}catch{}return await L4(X,Z)?"forced":"unobserved"}async function L4($,Z){let Q;try{return await Promise.race([$.then(()=>!0),new Promise((X)=>{Q=setTimeout(()=>X(!1),Z)})])}finally{clearTimeout(Q)}}function N2($){return new Promise((Z)=>{let Q=!1,X=(F)=>{if(Q)return;Q=!0,clearTimeout(z),$.signal.removeEventListener("abort",J),$.child.off("exit",Y),Z(F)},J=()=>X("cancelled"),Y=()=>X("exited"),z=setTimeout(()=>X("expired"),Math.max(0,$.expiresAt-$.now()));if($.signal.addEventListener("abort",J,{once:!0}),$.child.once("exit",Y),$.signal.aborted)J();else if($.child.exitCode!==null||$.child.signalCode!==null)Y()})}var w4=O4();function M2($,Z){if(!($ instanceof Error)||$ instanceof q)return!1;let Q=["hands_browser_driver_missing","hands_browser_driver_version_mismatch","hands_browser_executable_missing","hands_browser_unsupported_platform","hands_browser_unavailable"].includes($.message),X=["ENOENT","EACCES","EPERM"].includes($.code??"");if(!Q&&!X)return!1;try{return o(Z),!1}catch(J){return N9(J)&&J.code==="ENOENT"}}function j2($){return $.sandbox_provider==="compute"&&!$.cloud_browser&&!$[N0]&&$[p]===f0}function q2($,Z,Q){return $===void 0?{}:{dispatch_stages:{version:1,claim_to_entered_ms:H0($,Z),...Q===void 0?{}:{worker_prespawned:Q}}}}function TG(){w4().catch(()=>{return}),F9().catch(()=>{return})}async function OG($,Z={}){let Q=Z.logDiagnostic??((N)=>console.warn(N)),X=new Map,J=(N)=>{let M=Date.now();X.set(N,M);try{Q(JSON.stringify({event:"sandbox.hands_startup",stage:N,timestampMs:M}))}catch{}};J("entered");let Y=$.claimEnvironment;$.claimEnvironment=void 0;let z=Z.now??Date.now,F,G=r6($.payload,Z.now?.(),(N)=>{F=N});if($.managedPty&&($.managedPty.version!==1||!$.headless||!$.runtimeDirectory||![void 0,!0].includes($.managedPty.startupVerified)||!$.deviceIdentity||!$.claimOwner||$.claimOwner.device_id!==$.deviceIdentity.deviceId||!G.environment_binding||!["darwin","linux","win32"].includes(process.platform)))throw new q("pty_unsupported","Bound PTY requires qualified headless Hands with private jobs and environment.");let V=async(N)=>{let M;try{await Promise.race([N,new Promise((D,w)=>{M=setTimeout(()=>w(new q("hands_event_delivery_unavailable","Hands event delivery did not settle within its deadline.")),Math.max(1,Math.min(Z.eventDeliveryTimeoutMs??5000,5000)))})])}finally{clearTimeout(M)}},B=async(N,M)=>V($.emitEvent(N,M));if($.headless&&(G.cloud_browser===!0||$.managedBrowser!==void 0||G[N0]!==void 0||G[U9]!==void 0||G[p]!==void 0&&G[p]!==L0))throw new q("invalid_hands_request","Managed sandbox extensions are unavailable to a headless worker.");let H=x$(),K=G[m0]===void 0?null:n6(H);if(G[m0]!==void 0&&(K===null||!$.headless||!U4($.hostExecution,Z.hostIdentity?.platform,Z.hostIdentity?.euid)))throw new q("hands_model_jobs_egress_unavailable","This worker cannot hold its jobs to the guest egress guard; the Hands did not start.");if(G[t0]!==void 0&&!($.headless&&U4($.hostExecution,Z.hostIdentity?.platform,Z.hostIdentity?.euid)))throw new q("hands_confinement_unavailable","Confined Hands need a root Linux worker in host mode.");if(G.cloud_browser&&process.platform!=="linux")throw new q("cloud_browser_target_invalid","Cloud browser is available only on a cloud machine.");let L=`${$.operationId}:${$.attemptId}`,U=G[p]===W9,W=$.headless||process.platform==="darwin"&&$.managedBrowser===void 0&&!G.cloud_browser&&!G.browser_egress&&!G[N0]&&(G[p]===void 0||G[p]===L0)||j2(G),j=U?G[U9]??"bash":null,O=j?cQ(j):null;if(O)throw new q(O,"Persistent Node REPL execution is unavailable; this benchmark profile cannot start.");let C=G[p],A=$.headless===!0&&$.ownComputer!==!0?$.handsSlots??1:void 0,R=(Z.slot??e6).acquire(L,{exclusive:A===1||C!==void 0&&C!==L0,...A!==void 0&&A>1?{limit:A}:{},...$.headless===!0&&G[C0]!==void 0?{group:G[C0]}:{}});if(!R)throw new q("hands_slot_busy",A!==void 0&&A>1?`This Reason worker runs at most ${A} sessions at a time.`:"This Reason Device runs one session at a time.");let I=$.headless===!0?C4($.runId):null,T=null,S=null,y,E;try{J("browser_resolution");let N=$.headless&&Z.browserExecutablePath===void 0?await F9():null,M=U||G.cloud_browser?null:Z.browserExecutablePath===void 0?$.headless?N?.status==="resolved"?N.executablePath:null:await kQ(void 0,process.platform,$.managedBrowser):Z.browserExecutablePath;if(!U&&!G.cloud_browser&&!W&&!M)throw new q("hands_browser_unavailable","Reason Hands requires Chrome, Edge, Brave, Chromium, or a Playwright Chromium install.");J("path_resolution");let D;try{D=await(Z.resolvePathEnvironment??w4)()}catch{D={path:T4(),source:"fallback"}}if(J("workspace_setup"),process.platform==="darwin"){let l=G[p]===L0&&G.workspace_path!==void 0?I$($.root,G.workspace_worktree?G.workspace_worktree.source_path:G.workspace_path,"folder"):null;for(let e of new Set([$.root,...l?[l]:[]]))await XQ(e)}let k=G[p]===f0||G[p]===W9?s6(process.platform,Z.sandboxRuntimeRoot):null,m=$.headless&&$.runtimeDirectory?$.runtimeDirectory:k?k.temporaryRoot:D4();if(T="private_runtime",$.headless&&$.runtimeDirectory){L8(m);let l=s($.root);if(!w9(l,m))throw new q("invalid_hands_workspace","Private worker state must not overlap the granted workspace.")}if($.headless&&$.runtimeDirectory&&(!$.deviceIdentity||!G.environment_binding))throw new q("environment_unavailable","Headless Hands requires a server-bound private environment.");if(T="runtime_root",k?.prepareRoot)C9(m,{recursive:!0,mode:457}),g9(m,457);T="temporary_directory";let _=s(g6(a(m,"reason-hands-session-")));S=_,g9(_,k?.sessionMode??448);let g=a(_,"hands-config.json"),c=a(_,"hands-ready.json"),u=R6(),r=G.target_fence_id;if($.workspaceGrant){T="workspace_grant",J("workspace_grant_wait");let l=$.workspaceGrant;await new Promise((e,c0)=>{let Z9=()=>c0(new q("cancelled","Reason Hands was cancelled."));if($.signal.aborted){Z9();return}$.signal.addEventListener("abort",Z9,{once:!0}),l.then(e,c0).finally(()=>$.signal.removeEventListener("abort",Z9))})}T="granted_root";let b=s($.root);T="workspace_layout";let h=G[p]===L0&&G.workspace_path!==void 0&&G.workspace_worktree?await G2(b,G.workspace_path,G.workspace_worktree):void 0,{workRoot:d,repoPath:n,jobEnvPath:z0,workspacePoolPath:M0,managedWorkspace:W0,workspace:U0,cloudSessionRoot:g0}=V2({grantedRoot:b,personalWorkspace:G.personal_workspace===!0,runId:$.runId,workspaceId:G.workspace_id,legacyWorkspaceId:G.legacy_workspace_id,workspaceBase:G[o0],workspaceLayout:G[r0],temporaryDirectory:_,workspaceMode:G[p],applicationSupportPath:Z.applicationSupportPath,...G.workspace_path===void 0?{}:{workspacePath:G.workspace_path},...G.workspace_worktree?{workspaceWorktree:G.workspace_worktree}:{},...h?{workspaceWorktreeStart:h}:{},...$.deviceIdentity?{deviceId:$.deviceIdentity.deviceId}:{}}),T0=a6(G);T="jobs";let t=$.headless&&$.runtimeDirectory?PZ({runtimeDirectory:$.runtimeDirectory,root:b,runId:$.runId}):void 0;y=t?.disposeSocket;let j0=t?RZ(t):null;if(j0)try{Q(JSON.stringify({event:"hands.journal_owner_retired",run_id:$.runId,reason:j0.reason,prior_executor_launch_id:j0.executorLaunchId}))}catch{}if(t&&[d,n].some((l)=>!w9(l,t.journalDirectory)))throw new q("invalid_hands_workspace","A Session can't work in the folder that holds this worker's settings; start it in a project or repository inside it.");let $9=G.personal_workspace?d.slice(d.lastIndexOf("/")+1):void 0;if($9&&$9!==G.workspace_id)throw new q("invalid_hands_workspace","Personal session identity does not match its Device grant.");T="browser_socket";let B0=G.cloud_browser?i6(G.sandbox_os,$9):process.platform==="win32"?`\\\\.\\pipe\\reason-repl-${u}`:a(t?t.launchDirectory:_,"repl.sock");T="relay_url";let q0=A4(new URL(G.relay_url).hostname),h0=T0==="ara_device_wss"&&!q0?(Z.loadProxy??n8)()?.url:void 0,G0;T="environment_owner";let X0=$.headless&&$.deviceIdentity&&G.environment_binding?rQ(_,{runId:$.runId,...$.deviceIdentity,binding:G.environment_binding,expiresAtMs:Date.parse(G.expires_at),identity:()=>G0?.()??null}):void 0;T="job_environment";let T9=!X0&&U0.kind==="managed"&&W0?a(d,"job.env"):null;if(T9)try{T8(T9,"",{mode:384,flag:"wx"})}catch(l){if(!(l instanceof Error&&("code"in l)&&l.code==="EEXIST"))throw l}let x8={url:G.relay_url,transport:T0,...h0===void 0?{}:{proxyUrl:h0},...$.localGithubConfinement?{localGithubConfinement:!0}:{},...G[t0]&&X0?{gitCredentialEnvironment:!0}:{},workerVersion:q9,protocolVersion:j9,workerArtifactSha256:F0,workerEntrypoint:a0,...process.platform==="win32"?{bashExecutable:$8()}:{},targetGeneration:G.target_generation,fenceId:r,workRoot:d,workspaceAliasPath:d,jobEnvPath:z0,...X0?{environmentSnapshotPath:X0.path,...$.hostExecution?{executionEnvironment:nZ()}:{},environmentExpectedBinding:{runId:$.runId,...$.deviceIdentity,binding:G.environment_binding}}:T9?{jobEnvSourcePath:T9,workspacePoolPath:Y0(d)}:W0?{}:{jobEnvSourcePath:S4(d)},repoPath:n,replSocketPath:B0,...G.cloud_browser?{browserRunId:$.runId}:{},readyPath:c,launchId:u,expiresAtMs:Date.parse(G.expires_at),bashTimeoutMs:300000,replTimeoutMs:120000,...t?{managedJobs:{journalDirectory:t.journalDirectory,scopeId:t.scopeId},jobControlSocketPath:t.socketPath}:{},...t&&H?{jobsUser:{...H,...K!==null?{modelGid:K}:{}}}:{},...$.managedPty&&t&&X0?{managedPty:{version:1,...$.managedPty.startupVerified===!0?{persistent:!0}:{},...process.platform==="darwin"?{shell:iZ()}:{}}}:{},...W&&!M?{allowedTools:["bash","read","write","edit"]}:U?{allowedTools:j==="bash"?["bash"]:["bash","repl"]}:{}};if(X0||W0&&!T9)T8(z0,"",{mode:384});else F2(d,z0);T="config_write",T8(g,JSON.stringify(x8),{mode:384}),T=null;let v0={session_id:G.session_id,environment_id:G.environment_id,hands_protocol_version:j9,hands_worker_version:q9,hands_worker_artifact_sha256:F0,hands_worker_entrypoint:a0,target_generation:G.target_generation,target_fence_id:G.target_fence_id,executor_launch_id:u},h9=null,P$=!1,R$=!1,E$,Q0=null,S$,w$,v9="failed",b$=null,I8=Promise.resolve(),k$=null,P8=async(l,e)=>{try{await B(l,e)}catch{}};try{J("event_started");let l,e=(async()=>{await $.emitEvent("hands.started",{...v0,policy_mode:"full_access",policy_version:1,path_source:D.source}),l=Date.now()})();e.catch(()=>{return}),J("worker_setup");let c0=G.browser_egress?{mode:"enforce",allowedDomains:G.browser_egress.allowed_domains}:{mode:"off"};if(j&&j!=="bash")h9=await(Z.startNodeRepl??G4)({socketPath:B0,workRoot:d});else if(!U&&!G.cloud_browser&&M)h9=await(Z.startRepl??fQ)({socketPath:B0,browserExecutablePath:M,workspaceRoot:n,...$.managedBrowser?{managedBrowser:$.managedBrowser}:{},...$.desktopRecording?{recording:$.desktopRecording}:{},networkPolicy:c0,onEgressDenied:(f)=>{let V0=hQ(f.host);Q(JSON.stringify({event:"sandbox.repl_egress_denied",destination_id:V0,reason:f.reason,run_id:$.runId})),I8=I8.then(()=>B("hands.browser_egress_denied",{destination_id:V0,reason:f.reason})).catch((d9)=>{k$??=d9})}}).catch((f)=>{if(!W||$.signal.aborted||z()>=Date.parse(G.expires_at)||!M2(f,B0))throw f;return Object.assign(x8,{allowedTools:["bash","read","write","edit"]}),T8(g,JSON.stringify(x8),{mode:384}),R$=!0,null});let Z9=H2({configPath:g,root:n,grantedRoot:b,workRoot:d,workspacePoolPath:M0,temporaryDirectory:_,path:D.path,executablePath:Z.executablePath,sourceEntrypoint:Z.sourceEntrypoint}),R8=Date.now(),E8,f$,S8=Z.takePrespawnedWorker?.(Z9)??null;if(E$=Z.takePrespawnedWorker?S8!==null:void 0,Q0=S8??(Z.spawnWorker??((f)=>E6(f.command,f.args,f.options)))(Z9),!S8)Z.adoptSpawnedWorker?.(Q0);Q0.stderr?.on("data",U2(u,(f)=>{if(f.event==="hands.worker.connecting")E8??=f.timestampMs;else if(f.event==="hands.worker.open")f$??=f.timestampMs;if(Q(JSON.stringify({...f,run_id:$.runId})),f.event==="hands.worker.permission_denied"&&typeof f.reason==="string"){let[V0,d9]=f.reason.split(":");if(["sandbox_policy","os_permission_unknown"].includes(V0??"")&&["bash","read","write","edit"].includes(d9??""))B("permission.denied",{provenance:V0,operation:d9}).catch(()=>{return})}}));let m$=!1;Q0.on("error",()=>{m$=!0}),Q0.once("exit",(f,V0)=>{try{Q(JSON.stringify({event:"hands.worker.exited",run_id:$.runId,launchId:u,exit_code:f,exit_signal:V0}))}catch{}}),E=Q0,J("worker_ready_wait");let O9=await B2({path:c,launchId:u,fenceId:r,targetGeneration:G.target_generation,child:Q0,spawnFailed:()=>m$,signal:$.signal,timeoutMs:Z.readyTimeoutMs??p6,now:z}),b4=Date.now();if(G0=()=>{if(!Q0||Q0.exitCode!==null||Q0.signalCode!==null)return null;let f=N8(c,O9);return f?{generation:f.targetGeneration,fenceId:f.fenceId}:null},t){let f={root:b,runId:$.runId,operationId:$.operationId,scopeId:t.scopeId,socketPath:t.socketPath,generation:O9.targetGeneration,fenceId:O9.fenceId,executorLaunchId:u,expiresAtMs:Date.parse(G.expires_at),readIdentity:G0,workspace:U0,localGithubConfinement:$.localGithubConfinement===!0};if(X0)f.environment=X0;if($.claimOwner&&$.deviceIdentity&&$.claimOwner.device_id===$.deviceIdentity.deviceId){let V0=[$.deviceIdentity.apiOrigin,G.relay_url];if(h0)V0.push(h0);f.previewAuthority={owner:Object.freeze({...$.claimOwner}),rootId:$.deviceIdentity.rootId,relayOrigin:new URL(G.relay_url).origin,deniedPorts:YZ(V0)}}w$=EZ(f)}if(await new Promise((f)=>{setImmediate(f)}),g0)I4(d);let c9;if(Y&&X0){try{let f=X0.install(Y);c9={snapshot_id:f.snapshot_id,installed_revision:f.installed_revision}}catch{}try{Q(JSON.stringify({event:"hands.environment_at_claim",run_id:$.runId,installed:c9!==void 0}))}catch{}}Y=void 0;let y$=!1;if($.headless){let f=Q2(n,H);try{Q(JSON.stringify({event:"hands.workspace_check",run_id:$.runId,outcome:f}))}catch{}if(f==="unready")throw new q("hands_workspace_unready","This Session's checkout is not a readable, writable directory at its own path, so Reason Hands cannot use it.");y$=f==="checked"}J("event_ready");let g$=V(e);g$.catch(()=>{return});let h$=Date.now();P$=!0,await B("hands.ready",{...v0,expiry_diagnostic:F,startup_stages:{version:1,browser_resolution_ms:H0(X.get("browser_resolution"),X.get("path_resolution")),path_resolution_ms:H0(X.get("path_resolution"),X.get("workspace_setup")),workspace_setup_ms:H0(X.get("workspace_setup"),X.get("event_started")),repl_setup_ms:H0(X.get("worker_setup"),R8),worker_boot_ms:H0(R8,E8),worker_dial_ms:H0(E8,f$),worker_ready_ms:H0(R8,b4),started_event_ms:H0(X.get("event_started"),l),started_join_wait_ms:H0(X.get("event_ready"),h$),total_ms:H0(X.get("entered"),h$)},...q2($.claimedAtMs,X.get("entered"),E$),...$.managedPty?.startupVerified===!0?{managed_pty:{version:1,execution_mode:"host",descendant_cleanup_verified:!0}}:{},policy_mode:"full_access",policy_version:1,path_source:D.source,connection_generation:O9.generation,...c9?{environment_installed:c9}:{},...y$?{workspace_checked:!0}:{},...W&&!h9?{browser_state:"unavailable",browser_reason_code:R$?"setup_failed":"not_resolved"}:{viewport_width:1440,viewport_height:900}}),await g$,J("ready"),S$=X4({path:c,initial:O9,signal:$.signal,isAlive:()=>Q0!==null&&Q0.exitCode===null&&Q0.signalCode===null&&z()<Date.parse(G.expires_at),publish:(f,V0)=>$.emitEvent("hands.reconnected",{...v0,target_generation:f.targetGeneration,target_fence_id:f.fenceId,connection_generation:f.generation},V0),failed:()=>Q(JSON.stringify({event:"hands.worker.generation_proof_failed",run_id:$.runId,executor_launch_id:u}))});let v$=await N2({child:Q0,signal:$.signal,expiresAt:Date.parse(G.expires_at),now:z});if(v$==="cancelled"){let f=$.signal.reason instanceof q?$.signal.reason.code:"cancelled";throw v9=f,new q(f,"Reason Hands was cancelled.")}if(v$==="exited")throw new q("hands_worker_exited","Reason Hands exited unexpectedly.");return v9="expired",{...v0,policy_mode:"full_access",policy_version:1,ended:"expired"}}catch(l){b$=l;let e=l instanceof q?l.code:"hands_failed",c0=e==="cancelled"||["run_finished","run_cancelled","driver_handoff","driver_stopped"].includes(e);if(v9=c0?e:"failed",!c0)await P8("hands.failed",{...v0,reason_code:e});throw l}finally{S$?.stop(),w$?.();let l=Q0?await L2(Q0,Z.stopTimeoutMs??u6):null,e=!1;await $.desktopRecording?.close();try{await h9?.stop()}catch{e=!0}if(await I8,(l==="stopped"||l==="already_exited"&&!P$)&&!e)await P8("hands.stopped",{...v0,reason_code:v9});else if(l!==null||e){if(await P8("hands.failed",{...v0,reason_code:l==="forced"?"hands_stop_forced":"hands_stop_unconfirmed"}),b$===null||e)throw new q("hands_stop_unconfirmed","Reason Hands resource cleanup could not be proven.")}if(k$!==null)throw new q("hands_egress_audit_failed","Reason Hands could not persist a browser egress denial receipt.")}}catch(N){let M=mQ(T,N);if(M)try{Q(JSON.stringify({event:"sandbox.hands_workspace_failed",...M}))}catch{}throw N}finally{try{if(!E||E.exitCode!==null||E.signalCode!==null)y?.();if(S!==null&&(!E||E.exitCode!==null||E.signalCode!==null))h6(S,{recursive:!0,force:!0})}finally{I?.(),R()}}}
|
|
458
|
-
export{v as
|
|
458
|
+
export{v as kb,r$ as lb,t$ as mb,X3 as nb,QZ as ob,l9 as pb,A2 as qb,x2 as rb,I2 as sb,JZ as tb,YZ as ub,XX as vb,PZ as wb,qX as xb,CX as yb,TX as zb,OX as Ab,DX as Bb,_X as Cb,wZ as Db,AX as Eb,IX as Fb,p as Gb,L0 as Hb,MJ as Ib,jJ as Jb,kJ as Kb,fJ as Lb,vZ as Mb,rQ as Nb,mX as Ob,pZ as Pb,nZ as Qb,iZ as Rb,V5 as Sb,H5 as Tb,J0 as Ub,W5 as Vb,U5 as Wb,B5 as Xb,D5 as Yb,C1 as Zb,_5 as _b,w9 as $b,A0 as ac,A5 as bc,n5 as cc,D1 as dc,_1 as ec,NQ as fc,m5 as gc,b9 as hc,N7 as ic,T$ as jc,F4 as kc,U4 as lc,x$ as mc,n6 as nc,qG as oc,CG as pc,x4 as qc,t6 as rc,I4 as sc,P4 as tc,H2 as uc,W2 as vc,B4 as wc,TG as xc,OG as yc};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ya as f}from"./vm-hands-entry-lite-c1rexgd8.js";import{Ai as y,Gi as T,vi as K,zi as U}from"./vm-hands-entry-lite-caxtg4j7.js";import{Li as v}from"./vm-hands-entry-lite-26d4ttdx.js";import{sk as $}from"./vm-hands-entry-lite-ysk49bnz.js";var u=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?u.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as s,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
|
|
3
3
|
`,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)n(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function n(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||process.platform!=="win32"&&J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var o0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function r0(){let x=j(48).toString("base64url"),w=s("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),c=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&c)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function e0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),h=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(h).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),I=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(I)}),U0=$.object({machine:I}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),m=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=m.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function J1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function Q1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function g(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function W1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw g(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw g(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(m,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}async claudeCodeSignIn(x){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:x?AbortSignal.any([x,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(x,w,H={}){let G=x.kind==="setup_token"?{setup_token:x.token}:{access_token:x.credential.access,refresh_token:x.credential.refresh,expires_at:new Date(x.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{...G,...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(h,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
|
|
5
5
|
export{B as A,M as B,r0 as C,P as D,e0 as E,X as F,J0 as G,J1 as H,Q1 as I,W1 as J,A0 as K};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{m as
|
|
2
|
+
import{Vg as p}from"./vm-hands-entry-lite-wtc8ebkr.js";import{ah as h}from"./vm-hands-entry-lite-8v6qhfxc.js";import{ih as s}from"./vm-hands-entry-lite-0dr3sp75.js";import{wj as d}from"./vm-hands-entry-lite-wsnr4fx8.js";import{Jj as i}from"./vm-hands-entry-lite-arw53mkf.js";import{Nk as P}from"./vm-hands-entry-lite-b8bcnenf.js";import{Pk as V}from"./vm-hands-entry-lite-f28ehysx.js";import{existsSync as U,realpathSync as l,statSync as e}from"fs";import{platform as f}from"os";import{isAbsolute as r,sep as zz}from"path";import{existsSync as n}from"fs";import{createRequire as t}from"module";var E=P(h)(()=>t(import.meta.url)("bun:ffi"),n);function m(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&E.available()}function w(z=process.env){return E.defaultShell(z)}function k(z){return E.shellArgs(z)}function v(z){let H=E.spawn({...z,env:z.environment});return H.exited.then(()=>H.close()),{write:(Q)=>H.write(Q),resize:(Q,J)=>H.resize(Q,J),kill:()=>H.close(),exited:H.exited}}var Hz=43200000,y=s,Jz=4,Qz=/^[A-Za-z0-9._:-]{1,160}$/,Vz=1000;function u(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function g(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(Vz,Math.max(1,Math.floor(z)))}function Zz(z,H=Date.now()){let Q=["relay_url","session_id","expires_at"],J=new Set([...Q,"cols","rows","cwd","workspace"]);if(!u(z)||Q.some((C)=>!(C in z))||Object.keys(z).some((C)=>!J.has(C)))throw new V("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:N,session_id:Y,expires_at:R}=z;if(typeof N!=="string")throw new V("invalid_pty_request","Reason terminal relay URL is missing.");let K;try{K=new URL(N)}catch{throw new V("invalid_pty_request","Reason terminal relay URL is invalid.")}if(K.protocol!=="wss:"&&K.protocol!=="ws:"||K.username||K.password)throw new V("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!Qz.test(Y))throw new V("invalid_pty_request","Reason terminal session identity is invalid.");let D=typeof R==="string"?Date.parse(R):Number.NaN;if(!Number.isFinite(D)||D<=H)throw new V("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new V("invalid_pty_request","Reason terminal working directory is invalid.");let j=z.workspace===void 0?void 0:i(z.workspace);if(j===null||j&&z.cwd!==void 0)throw new V("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:N,session_id:Y,expires_at:new Date(Math.min(D,H+Hz)).toISOString(),cols:g(z.cols,80),rows:g(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...j?{workspace:j}:{}}}function $z(z,H){if(f()==="win32")[z,H]=[z.toLowerCase(),H.toLowerCase()];return H===z||H.startsWith(z+zz)}function c(z,H){if(H===void 0)return z;if(!r(H))throw new V("pty_cwd_invalid","Reason terminal working directory must be absolute.");let Q;try{Q=l(H)}catch{throw new V("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!$z(z,Q))throw new V("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!e(Q).isDirectory())throw new V("pty_cwd_invalid","Reason terminal working directory is not a directory.");return Q}function jz(z=process.env){if(f()==="win32")return w(z);let H=z.SHELL;if(H&&r(H)&&U(H))return H;for(let Q of f()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(U(Q))return Q;return"/bin/sh"}function Gz(){let z=globalThis.Bun;if(!z)throw new V("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Sz(){if(f()==="win32")return m();return typeof globalThis.Bun<"u"}var Nz=(z)=>{if(f()==="win32")try{return v({...z,file:z.shell,args:k(z.shell),environment:{...z.environment,TERM:"xterm-256color"}})}catch{throw new V("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let H=Gz()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,N)=>{z.onData(N)}}}),Q=H.terminal;if(!Q){try{H.kill()}catch{}throw new V("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>Q.write(J),resize:(J,N)=>Q.resize(J,N),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Wz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},M=new Set;function Kz(z){if(M.size>=Jz||M.has(z))return null;M.add(z);let H=!1;return()=>{if(H)return;H=!0,M.delete(z)}}async function Tz(z,H={}){let Q=H.now??Date.now,J=Zz(z.payload,Q()),N=Kz(z.operationId);if(!N)throw new V("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=Q(),R,K,D;try{let j=J.workspace?d(z.root,J.workspace):void 0;R=j?c(U(j.boundary)?l(j.boundary):j.boundary,j.path):c(z.root,J.cwd),K=H.environment??process.env,D=H.shellPath??jz(K)}catch(j){throw N(),j}return await new Promise((j,C)=>{let F=null,$=null,I=!1,B=!1,X=!1,_=null,b=0,x=0,O=[],S=0,T=null,G=(Z)=>{if(X)return;if(X=!0,T)clearTimeout(T);z.signal.removeEventListener("abort",A);try{F?.kill()}catch{}try{$?.close(1000,"pty_session_over")}catch{}if(N(),Z.kind==="rejected"){C(Z.error);return}let W={reason:Z.reason,exit_code:_,output_bytes:b,input_bytes:x,duration_ms:Math.max(0,Q()-Y)};z.emitEvent("pty.stopped",{...W}).catch(()=>{return}),j({...W})},A=()=>{let Z=z.signal.reason;G({kind:"rejected",error:Z instanceof V?Z:new V("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){A();return}z.signal.addEventListener("abort",A,{once:!0}),T=setTimeout(()=>G({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-Q()));let a=(Z)=>{if(b+=Z.byteLength,!I||!$){if(O.push(Z),S+=Z.byteLength,S>y)G({kind:"resolved",reason:"output_backpressure"});return}try{$.send(Z)}catch{G({kind:"resolved",reason:"relay_closed"});return}if($.bufferedAmount>y)G({kind:"resolved",reason:"output_backpressure"})};try{F=(H.spawnPty??Nz)({shell:D,args:["-i","-l"],cwd:R,cols:J.cols,rows:J.rows,environment:K,onData:(Z)=>{if(!X)a(Z)}})}catch(Z){G({kind:"rejected",error:Z instanceof V?Z:new V("pty_spawn_failed","Reason could not start the terminal shell.")});return}F.exited.then((Z)=>{if(X)return;if(_=Z,I&&$)try{$.send(JSON.stringify({t:"exit",code:Z}))}catch{}G({kind:"resolved",reason:"shell_exited"})});let o=(H.loadProxy??p)()?.url;try{$=(H.connect??Wz)(J.relay_url,o)}catch{G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$.binaryType="arraybuffer",$.onopen=()=>{if(X||!$)return;I=!0;try{$.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let Z of O.splice(0))$.send(Z);S=0}catch{G({kind:"resolved",reason:"relay_closed"});return}B=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},$.onmessage=(Z)=>{if(X||!F)return;let W=Z.data;if(typeof W==="string"){let L;try{L=JSON.parse(W)}catch{return}if(!u(L))return;if(L.t==="resize"){try{F.resize(g(L.cols,J.cols),g(L.rows,J.rows))}catch{}return}if(L.t==="close")G({kind:"resolved",reason:"client_closed"});return}let q=W instanceof ArrayBuffer?new Uint8Array(W):ArrayBuffer.isView(W)?new Uint8Array(W.buffer,W.byteOffset,W.byteLength):null;if(!q||q.byteLength===0)return;x+=q.byteLength;try{F.write(q)}catch{}},$.onclose=()=>{if(X)return;if(!B){G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}G({kind:"resolved",reason:"relay_closed"})},$.onerror=()=>{if(X||B)return;G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
|
|
3
|
+
export{m as vg,Hz as wg,y as xg,Jz as yg,Zz as zg,c as Ag,jz as Bg,Sz as Cg,Nz as Dg,Wz as Eg,Tz as Fg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{createHash as f,createPublicKey as V,verify as G}from"crypto";var Y="libara_device_keychain.dylib",H="libreason_device_keychain.dylib",k=1,x=2,h=536870912,R=262144;var U=["darwin-arm64","darwin-x64"];class J extends Error{code;constructor(z,F){super(F);this.code=z;this.name="ManagedRuntimeError"}}var C=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,N=/^[a-f0-9]{64}$/;function X(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function $(z,F,Q=[]){let Z=new Set([...F,...Q]);return F.every((W)=>(W in z))&&Object.keys(z).every((W)=>Z.has(W))}function B(z){return typeof z==="string"&&C.test(z)}function O(z){return typeof z==="string"&&!Number.isNaN(Date.parse(z))&&new Date(z).toISOString()===z}function I(z){return U.includes(z)}function c(z,F){if(!B(z)||!I(F))throw new J("invalid_release_asset","Invalid managed runtime release asset.")}function K(z,F){return c(z,F),`reason-runtime-v${z}-${F}`}function g(z,F){return`${K(z,F)}-${H}`}var o="managed-runtime-identity.json",D="reason-macos-background-identity-v1";function q(z){if(z===null)return"null";if(typeof z==="string"||typeof z==="boolean")return JSON.stringify(z);if(typeof z==="number"){if(!Number.isFinite(z))throw new J("invalid_manifest","Manifest numbers must be finite.");return JSON.stringify(z)}if(Array.isArray(z))return`[${z.map((F)=>q(F)).join(",")}]`;if(X(z))return`{${Object.keys(z).sort().map((F)=>`${JSON.stringify(F)}:${q(z[F])}`).join(",")}}`;throw new J("invalid_manifest","Manifest contains an unsupported value.")}function j(z){if(!X(z)||!$(z,["url","sha256","size_bytes"])||typeof z.url!=="string"||typeof z.sha256!=="string"||!N.test(z.sha256)||typeof z.size_bytes!=="number"||!Number.isSafeInteger(z.size_bytes)||z.size_bytes<=0||z.size_bytes>h)throw new J("invalid_manifest","Manifest contains an invalid runtime artifact.");let F;try{F=new URL(z.url)}catch{throw new J("invalid_manifest","Runtime artifact URL is invalid.")}if(F.protocol!=="https:"||F.username||F.password||F.hash)throw new J("invalid_manifest","Runtime artifact URL must be an HTTPS URL without credentials or a fragment.");return{url:F.toString(),sha256:z.sha256,size_bytes:z.size_bytes}}function b(z){if(!X(z)||!$(z,["broker","credential_library"]))throw new J("invalid_manifest","Manifest must bind the broker and credential library as one runtime.");return{broker:j(z.broker),credential_library:j(z.credential_library)}}function _(z){if(!X(z)||!$(z,["schema_version","version","published_at","artifacts"])||z.schema_version!==x||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Managed Reason runtime manifest is invalid.");return{schema_version:x,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":b(z.artifacts["darwin-arm64"]),"darwin-x64":b(z.artifacts["darwin-x64"])}}}function M(z){if(!X(z)||!$(z,["schema_version","version","published_at","artifacts"])||z.schema_version!==k||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Legacy managed runtime manifest is invalid.");return{schema_version:k,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":j(z.artifacts["darwin-arm64"]),"darwin-x64":j(z.artifacts["darwin-x64"])}}}function A(z){if(!X(z)||!$(z,["schema","version","published_at","artifacts"])||z.schema!==D||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Reason background identity manifest is invalid.");return{schema:D,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":j(z.artifacts["darwin-arm64"]),"darwin-x64":j(z.artifacts["darwin-x64"])}}}function S(z){if(typeof z!=="string"||!/^[A-Za-z0-9+/]+={0,2}$/.test(z))throw new J("invalid_signature","Runtime manifest signature is invalid.");let F=Buffer.from(z,"base64");if(F.length!==64||F.toString("base64")!==z)throw new J("invalid_signature","Runtime manifest signature is invalid.");return F}function L(z){let F=z;if(typeof z==="string")try{F=JSON.parse(z)}catch{throw new J("invalid_manifest","Managed Reason runtime manifest is not valid JSON.")}if(!X(F)||!$(F,["key_id","manifest","signature"])||typeof F.key_id!=="string"||!/^[A-Za-z0-9._-]{1,80}$/.test(F.key_id)||typeof F.signature!=="string")throw new J("invalid_manifest","Signed managed Reason runtime manifest is invalid.");return F}function E(z,F){let Q=L(z),Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Runtime manifest was signed by an unknown key.");let W=_(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Runtime manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Runtime manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function d(z,F){let Q=L(z),Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Background identity manifest was signed by an unknown key.");let W=A(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Background identity manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Background identity manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function i(z,F){let Q=z;if(typeof z==="string")try{Q=JSON.parse(z)}catch{throw new J("invalid_manifest","Legacy managed runtime manifest is not valid JSON.")}if(!X(Q)||!$(Q,["key_id","manifest","signature"])||typeof Q.key_id!=="string"||!/^[A-Za-z0-9._-]{1,80}$/.test(Q.key_id)||typeof Q.signature!=="string")throw new J("invalid_manifest","Signed legacy managed runtime manifest is invalid.");let Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Legacy runtime manifest was signed by an unknown key.");let W=M(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Legacy runtime manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Legacy runtime manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function y(z){return f("sha256").update(z).digest("hex")}function n(z,F){if(z.byteLength!==F.size_bytes)throw new J("artifact_size_mismatch","Runtime artifact size did not match its manifest.");if(y(z)!==F.sha256)throw new J("artifact_checksum_mismatch","Runtime artifact checksum did not match its manifest.")}import{existsSync as p}from"fs";import{join as T}from"path";function r(z){let F=T(z,H);return p(F)?F:T(z,Y)}
|
|
3
|
-
export{Y as
|
|
3
|
+
export{Y as ci,H as di,k as ei,x as fi,h as gi,R as hi,U as ii,J as ji,K as ki,g as li,o as mi,q as ni,E as oi,d as pi,i as qi,y as ri,n as si,r as ti};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{cj as I}from"./vm-hands-entry-lite-0mk8rxqv.js";import{Ck as R,Fk as U,Ik as C,Jk as O,Kk as g}from"./vm-hands-entry-lite-rbjky7rd.js";import{spawn as S}from"child_process";import{existsSync as x,mkdirSync as T,readFileSync as w,writeFileSync as E}from"fs";import{homedir as H}from"os";import{basename as L,delimiter as D,join as G,win32 as $}from"path";var N=process.platform==="win32"?U("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",b=N.split(D),_=5000,j=65536,k=new Set(["zsh","bash"]),f=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],P=(z,J)=>new Promise((B,Q)=>{let K;try{K=S(z,[...J],{...C(),stdio:["ignore","pipe","ignore"]}),O(K)}catch(X){Q(X);return}let W=[],V=0,Z=null,q=(X)=>{Z??=Error(X);try{if(K.pid!==void 0)g(K.pid,"SIGKILL")}catch{}},F=setTimeout(()=>q("login_shell_timeout"),_);K.stdout?.on("data",(X)=>{if(V+=X.length,V>j)q("login_shell_output_too_large");else W.push(X)}),K.once("error",(X)=>{clearTimeout(F),Q(X)}),K.once("close",(X)=>{if(clearTimeout(F),Z)Q(Z);else if(X!==0)Q(Error("login_shell_exit_nonzero"));else B(Buffer.concat(W).toString("utf8"))})});function v(z){return typeof z==="string"&&z.startsWith("/")&&!z.includes("\x00")&&k.has(L(z))}function M(z){let J=new Set,B=[];for(let Q of z){if(J.has(Q))continue;J.add(Q),B.push(Q)}return B}function A(z,J=process.platform){let B=J==="win32",Q=z.split(`
|
|
3
3
|
`).at(-1)??"",K=[];for(let W of Q.split(B?";":":")){let V=W.trim();if(B?!$.isAbsolute(V):!V.startsWith("/"))continue;if(V.includes("\x00"))continue;if(I(V))continue;K.push(V)}return M(K)}function y(z){let J=z?.home??H(),B=z?.directoryExists??x,Q=f.map((K)=>G(J,...K)).filter((K)=>{try{return B(K)}catch{return!1}});return M([...Q,...process.platform==="win32"?A(process.env.PATH??process.env.Path??""):[],...b]).join(D)}async function d(z){let J=z?.shell??process.env.SHELL,B=()=>({path:y({home:z?.home,directoryExists:z?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!v(J))return B();let Q;try{Q=await(z?.runLoginShell??P)(J,["-lic",'printf %s "$PATH"'])}catch{return B()}if(Buffer.byteLength(Q,"utf8")>j)return B();let K=A(Q);if(K.length===0)return B();return{path:M([...K,...b]).join(":"),source:"login_shell"}}function n(z){let J=null;return()=>{return J??=d(z),J}}function Y(z){if(z===void 0||z.includes("\x00")||Buffer.byteLength(z,"utf8")>32768)return;return z}function r(z){let J=z.source??process.env,B={HOME:z.home,PATH:z.path??N,TMPDIR:z.temporaryDirectory,SHELL:Y(J.SHELL)??"/bin/zsh",LANG:Y(J.LANG)??"C.UTF-8",LC_ALL:Y(J.LC_ALL)??Y(J.LANG)??"C.UTF-8"},Q=Y(J.LC_CTYPE),K=Y(J.TERM),W=Y(J.COLORTERM);if(Q)B.LC_CTYPE=Q;if(K)B.TERM=K;if(W)B.COLORTERM=W;if(process.platform==="win32"){for(let V of h){let Z=Y(J[V]);if(Z)B[V]=Z}B.TEMP=B.TMP=z.temporaryDirectory,B.SHELL=R()??B.SHELL,B.PATH=m(B.PATH)}return B}function m(z,J=G(H(),".reason","python3")){let B=(W)=>z.split($.delimiter).filter((V)=>V&&!/[\\/]WindowsApps[\\/]?$/i.test(V)).map((V)=>$.join(V,W)).find((V)=>x(V)),Q=B("python.exe");if(B("python3.exe")||!Q)return z;let K=`#!/bin/sh
|
|
4
4
|
exec "${Q.replaceAll("\\","/")}" "$@"
|
|
5
5
|
`;try{let W=G(J,"python3");if(!x(W)||w(W,"utf8")!==K)T(J,{recursive:!0}),E(W,K)}catch{return z}return[J,z].join($.delimiter)}var h=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
|
|
6
|
-
export{N as
|
|
6
|
+
export{N as Jc,A as Kc,y as Lc,n as Mc,r as Nc,m as Oc};
|