@reason-machines/cli-linux-x64 0.2.502 → 0.2.504
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/vm-hands/api-credentials-gnefpvc1.js +2 -0
- package/bin/vm-hands/api-mjzanhf1.js +2 -0
- package/bin/vm-hands/connect-cli-dy7mdehx.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-389h3q6n.js → custom-endpoint-device-j1x988g0.js} +1 -1
- package/bin/vm-hands/{desktop-account-tjf36aya.js → desktop-account-4525j7h3.js} +1 -1
- package/bin/vm-hands/{fsevents-s0cwdhcq.js → fsevents-8zxmv89w.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-wrj180b5.js → hands-worker-source-atg5dc7b.js} +1 -1
- package/bin/vm-hands/{index-w9sxzata.js → index-ttmxy9nd.js} +2 -2
- package/bin/vm-hands/install-receipt-6v65enmf.js +2 -0
- package/bin/vm-hands/local-automation-wfa3dpbs.js +2 -0
- package/bin/vm-hands/local-capabilities-3v7x217d.js +2 -0
- package/bin/vm-hands/local-desktop-users-ar6xpadb.js +2 -0
- package/bin/vm-hands/local-display-mac-fnp3317m.js +2 -0
- package/bin/vm-hands/local-display-session-2064d8k8.js +2 -0
- package/bin/vm-hands/local-display-video-1hxqy3xj.js +2 -0
- package/bin/vm-hands/local-managed-process-trmeeyh2.js +2 -0
- package/bin/vm-hands/local-pty-session-5yh2a63r.js +2 -0
- package/bin/vm-hands/managed-runtime-hhk63f61.js +2 -0
- package/bin/vm-hands/network-contract-rzw769gw.js +2 -0
- package/bin/vm-hands/package-r7sgmw4t.js +2 -0
- package/bin/vm-hands/permissions-xwyhbnjc.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-vw2dbdse.js → reason-hands-protocol-8fgk2s53.js} +1 -1
- package/bin/vm-hands/serve-service-aye42qtb.js +2 -0
- package/bin/vm-hands/{status-0ddc2j79.js → status-qtm9gb55.js} +1 -1
- package/bin/vm-hands/version-gnb213c3.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-4zvbfed0.js → vm-hands-entry-lite-0y9n06b6.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-krm8w7wp.js → vm-hands-entry-lite-3sjkzhf6.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-545m8hm0.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-wg6e62nd.js → vm-hands-entry-lite-57v7y0km.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-dw558ggz.js → vm-hands-entry-lite-5gevvgec.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-9wa2y4x0.js → vm-hands-entry-lite-5tbntcyq.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-vahmtkh4.js → vm-hands-entry-lite-61y11rrd.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3gztfxwt.js → vm-hands-entry-lite-77j164ps.js} +8 -8
- package/bin/vm-hands/{vm-hands-entry-lite-1dmq2pve.js → vm-hands-entry-lite-8e5djf5y.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-64z2tjpg.js → vm-hands-entry-lite-8wcyveeh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1bp1vz26.js → vm-hands-entry-lite-c11fg8gx.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-1c9b38y1.js → vm-hands-entry-lite-e1z3y9rs.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-w0pegc58.js → vm-hands-entry-lite-eabever7.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-2jadtgms.js → vm-hands-entry-lite-ewr54tpc.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-ex69qn9q.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-a1xa7s06.js → vm-hands-entry-lite-gvjffc5t.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-hmaazqdr.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-a7q8mkmm.js → vm-hands-entry-lite-kq7hrjch.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-2dx4pnz7.js → vm-hands-entry-lite-mk5ayds8.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-4c4xqd7k.js → vm-hands-entry-lite-mqzr55mw.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-8qhz89mt.js → vm-hands-entry-lite-ncbzy69k.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-q602ehtq.js → vm-hands-entry-lite-pydgnx8a.js} +10 -10
- package/bin/vm-hands/{vm-hands-entry-lite-13rapgf5.js → vm-hands-entry-lite-qpdpzg8g.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-1zcc5b3q.js → vm-hands-entry-lite-qt71vz32.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-qxsqx6hz.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-tddvxqej.js → vm-hands-entry-lite-rmabryke.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-gc7550c0.js → vm-hands-entry-lite-rzr2ncf5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cwp0jmm6.js → vm-hands-entry-lite-sss0m3yn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-22785718.js → vm-hands-entry-lite-wg0cykk2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-n4xgpgkw.js → vm-hands-entry-lite-x39tmj7j.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-1g1v87ky.js → vm-hands-entry-lite-xdjrdkh2.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-hag0ysby.js → vm-hands-executor-8c542krk.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-2tpvq0f7.js → vm-hands-op-runner-88e10ptt.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-grs1wftp.js → vm-hands-runtime-njh3th64.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-7xtgxsar.js +2 -0
- package/bin/vm-hands/{worker-sandbox-k4cfh0ya.js → worker-sandbox-s9pyac8p.js} +1 -1
- package/package.json +1 -1
- package/bin/vm-hands/api-c919je1j.js +0 -2
- package/bin/vm-hands/api-credentials-4g0m4mqb.js +0 -2
- package/bin/vm-hands/connect-cli-negc7na6.js +0 -2
- package/bin/vm-hands/install-receipt-9bv4vth9.js +0 -2
- package/bin/vm-hands/local-automation-0456011e.js +0 -2
- package/bin/vm-hands/local-capabilities-pbwd792c.js +0 -2
- package/bin/vm-hands/local-desktop-users-tqagws7p.js +0 -2
- package/bin/vm-hands/local-display-mac-w792g9g3.js +0 -2
- package/bin/vm-hands/local-display-session-jsmwws20.js +0 -2
- package/bin/vm-hands/local-display-video-w3xg2fwn.js +0 -2
- package/bin/vm-hands/local-managed-process-mqg0z162.js +0 -2
- package/bin/vm-hands/local-pty-session-rdv5wv5g.js +0 -2
- package/bin/vm-hands/managed-runtime-8twvvmch.js +0 -2
- package/bin/vm-hands/network-contract-h6s7ptm5.js +0 -2
- package/bin/vm-hands/package-yy8qcwwn.js +0 -2
- package/bin/vm-hands/permissions-28a0zxca.js +0 -2
- package/bin/vm-hands/serve-service-dqkb0ea6.js +0 -2
- package/bin/vm-hands/version-r5t5fdn6.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-091s68f7.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-7qs80dq9.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-9nchsk6j.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-e4c6z5t3.js +0 -2
- package/bin/vm-hands/worker-preview-readiness-m2dn9mmn.js +0 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Gt,j}from"./vm-hands-entry-lite-gc7550c0.js";import{ue,Ce,Z,Ae,de,rr,et,X,O,H,tn}from"./vm-hands-entry-lite-38g65s5x.js";import{Lo,ri}from"./vm-hands-entry-lite-nqdstx24.js";import{xo,P,Je,Se,Ze,ne,Xe,Wn,Ee,Xt,ae,U,N,ce,Hr,zr,Gn}from"./vm-hands-entry-lite-dw558ggz.js";import{Pe,oe,pe,Y,Re,q,Q}from"./vm-hands-entry-lite-9wa2y4x0.js";import{It,kr,at,V,D,R,b,En}from"./vm-hands-entry-lite-3gztfxwt.js";import{Er,xr,vn,oo,He,Sn}from"./vm-hands-entry-lite-tebh7dcm.js";import{K}from"./vm-hands-entry-lite-8qhz89mt.js";import{Mi}from"./vm-hands-entry-lite-1g1v87ky.js";import{p,ze,Dt,ct,so,_e,we}from"./vm-hands-entry-lite-psywfz8m.js";import{v,h,lo}from"./vm-hands-entry-lite-f69t48dj.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{Qt}from"./vm-hands-entry-lite-cwp0jmm6.js";import{a,ie,$o}from"./vm-hands-entry-lite-swrymqj9.js";import{L,Ii,Di,Ho,y,t,k,Et,o,d,u,i,c,g,ee,s,n}from"./vm-hands-entry-lite-a1xa7s06.js";import{Li}from"./vm-hands-entry-lite-2dx4pnz7.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{qo,se,Wo,C,De,Me,A}from"./vm-hands-entry-lite-87vmbt38.js";var gi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function l(w){return e[w]??null}let f={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},_={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=_[w.expected]??w.expected,I=Ho(w.input),W=_[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Di(w.values[0])}`;return`Invalid option: expected one of ${Ii(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",I=l(w.origin);if(I)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${I.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",I=l(w.origin);if(I)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${I.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${Ii(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((I)=>`'${I}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function Rn(){return{localeError:gi()}}L(Rn());class pt extends Error{}function Ao(e){let l;try{l=new URL(e)}catch{throw new pt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new pt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new pt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new pt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new pt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as bi}from"crypto";import{isAbsolute as To,join as Do,relative as Co,resolve as Vt,sep as No}from"path";var Jt=t().min(1).refine(To,"absolute path required"),xn=c({version:n(1),apiOrigin:Et(),channel:s(["staging","production"]),stateDirectory:Jt,workspaceRoot:Jt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:c({version:n(Gt),url:t().refine((e)=>{try{return Ao(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Jt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(Jt).min(1).max(31).optional()}),wi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[xn,xn.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),xn.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!wi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else if(e.channel==="pr"){let _=e.prEnvironment,w=/^https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.up\.railway\.app$/.exec(e.apiOrigin),S=w?.[1]?.match(/(?:^|-)pr-[0-9]+(?=-|$)/g)?.map((I)=>I.replace(/^-/,""));if(!_||/^pr-[1-9][0-9]*$/.exec(_)?.[0]!==_||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==_)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Lo(e.channel,_.origin))l.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!je(e.workspaceRoot,e.stateDirectory))l.addIssue({code:"custom",message:"state and workspace must be disjoint"});let f=e.folders??[];if(new Set([e.workspaceRoot,...f]).size!==f.length+1||f.some((_)=>!je(_,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return Do(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if(Fr(l,e))return!1;return!Fr(e,l)||E(Do(No,Co(Vt(e),Vt(l))))}function Fr(e,l){let f=Co(Vt(e),Vt(l));return f===""||f!==".."&&!f.startsWith(`..${No}`)&&!To(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...I}=e;return bi("sha256").update(JSON.stringify(I)).digest("hex")}var yi=4,vi=[2375,2376,9222,9229];function pr(e){let l=new Set(vi);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var ki=60000;function Bo(e){let l=new AbortController,f=new Map,_=(x)=>JSON.stringify([x.jobId,x.port]);function w(x){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||x.organization_id!==M.organization_id||x.user_id!==M.user_id||x.device_id!==M.device_id)Gr()}function S(x){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===x.generation&&M.binding.target_fence_id===x.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function I(x,M,G){let F=await W(x,M,G);if(F!=="moved")return F;let T=await W(x,M,G);return T==="moved"?null:T}async function W(x,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||x.expiresAtMs<=Date.now()||x.expiresAtMs>e.expiresAtMs)return null;let T=M.opened,re=T!==void 0&&F.generation>T.generation,J=S(F);if(re){if(J){if(J.revision<=T.revision||x.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==T.attachmentRevision||J.binding.root_grant_revision!==T.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>ki)return null}else if(!J||x.expiresAtMs>Date.parse(J.expires_at)||T&&(F.generation!==T.generation||F.fenceId!==T.fenceId))return null;let z=await e.inspect(x.jobId,G),fe=e.identity(),ve=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:F.generation,fenceId:F.fenceId,snapshotId:J.snapshot_id,revision:J.revision,attachmentRevision:J.binding.target_revision,grantRevision:J.binding.root_grant_revision},Oe=re?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ve?.snapshot_id!==J?.snapshot_id||ve?.revision!==J?.revision)return"moved";let $e=z.ok&&z.job.environmentSnapshotId!==void 0&&z.job.environmentRevision!==void 0?{snapshotId:z.job.environmentSnapshotId,revision:z.job.environmentRevision}:null;if(!z.ok||z.generation!==F.generation||!Oe||!$e)return null;if(($e.snapshotId!==Oe.snapshotId||$e.revision!==Oe.revision)&&(re||!e.environment.carried($e.snapshotId,$e.revision)))return null;if(!T&&F.generation===x.generation&&F.fenceId===x.fenceId)M.opened={...Oe,...$e};return{executorLaunchId:e.executorLaunchId,job:z.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:Oe.attachmentRevision,grantRevision:Oe.grantRevision,generation:Oe.generation,fenceId:Oe.fenceId,jobId:z.job.jobId,port:x.port,expiresAtMs:x.expiresAtMs}}}catch{return null}}return{async open(x,M,G){w(M);let{binding:F,deviceRelayUrl:T}=ct(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Gr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==T)Gr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:F}}if(f.size>=yi)Gr();let z=new AbortController,fe={},ve=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>I(F,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Oe=_e({binding:F,deviceRelayUrl:T,port:ve,signal:z.signal}),$e={binding:F,relay:T,abort:z,port:ve,opened:Oe};f.set(re,$e);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===$e)f.delete(re)};try{if((await Oe).closed.then(qe),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ve.check()))Gr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Gr()}},async close(x,M){w(M);let{binding:G}=so(x),F=f.get(_(G));if(!F||!ze(F.binding,G))Gr();return F.abort.abort(),await F.opened.then((T)=>T.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let x of f.values())x.abort.abort();f.clear()}}}import{WebSocket as Pn}from"ws";var jo=(e)=>("data"in e)?e.data.length:e.bytes,Mo=2*Xe;function ir(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var _t=(e)=>!["starting","running"].includes(e.state);function Ji(e,l,f=Date.now()){let _=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==_.length||Object.keys(e).some((M)=>!_.includes(M))||!ae(l)||!ae(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((M)=>Number.isSafeInteger(M)&&Number(M)>=1&&Number(M)<=Ee))ir("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ir("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ir("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return ir("invalid_pty_request")}if(!["ws:","wss:"].includes(I.protocol)||I.username||I.password||I.hash||I.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(I.hostname))ir("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ir("invalid_pty_request");return{workspace:H(e.workspace)??ir("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:I.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Fo(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ir("cancelled");let _=new Pn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},I=()=>{w.abort(),S()};e.signal.addEventListener("abort",I,{once:!0});let W=setTimeout(I,Math.max(1,l.leaseExpiresAtMs-Date.now())),x=[],M=0,G=0,F=0,T=!1,re=!1,J=!1,z,fe,ve,be=(le)=>{ve=new r(le,"Bound terminal input was refused."),I()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",I),_.on("message",(le,he)=>{if(w.signal.aborted)return;if(!re){be("pty_not_ready");return}let xe=Array.isArray(le)?Buffer.concat(le):le instanceof ArrayBuffer?Buffer.from(le):le;if(xe.length===0)return;let Ke=x.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Wn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.data,xe]);else if(he)x.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,I();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((ke)=>Number.isSafeInteger(ke)&&ke>=1&&ke<=Ee))throw Error("invalid_control");x.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Oe(le){return Gn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function $e(le){if(!le.ok)ir(le.error);let he=le.job;if(le.generation!==f.scope.generation||he.jobId!==l.jobId||!he.pty||he.leaseExpiresAtMs>l.leaseExpiresAtMs||he.process&&he.process.executorLaunchId!==f.scope.executorLaunchId||he.process&&fe&&(he.process.pid!==fe.pid||he.process.processGroupId!==fe.processGroupId)||he.state!=="starting"&&(he.environmentRevision!==f.environment.revision||he.environmentSnapshotId!==f.environment.snapshotId))ir("pty_binding_changed");if(Oe(he),he.process)fe??={...he.process};return he}async function qe(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)ir("cancelled");let xe=$e(he);if(xe.inputSequence!==G)ir("job_input_sequence");if(!_t(xe)&&xe.leaseExpiresAtMs<=Date.now())ir("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Pn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Mo)ir("pty_output_backpressure");_.send(le)}function Fe(le){if(le.firstCursor>F+1)F=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=F)continue;if(he.cursor!==F+1)ir("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Mo)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)ir("pty_output_gap");return!0}async function Ve(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ke,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function Te(){let le=AbortSignal.timeout(Xt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ke=new Promise((Le,Be)=>{if(xe=()=>Be(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),le.addEventListener("abort",xe,{once:!0}),le.aborted)xe()});try{let Le=await Promise.race([he,Ke]);if(le.aborted)ir("pty_cleanup_unconfirmed");return $e(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),We=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",We,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",We),Le()}),w.signal.aborted)We()}),f.assertCurrent(),T=!0,z=await qe({jobId:l.jobId,action:"start",input:{mode:"pty",cols:l.cols,rows:l.rows,leaseExpiresAtMs:l.leaseExpiresAtMs}});let le=Date.now()+5000;while(z.state==="starting"){if(Date.now()>=le)ir("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ir("pty_not_ready");await Ve("pty.ready",Oe(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Oe(z)}));let he=!1,xe=0,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=Fe(z);if(_t(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:We,rows:tr}=z.pty;for(let nr of[{cols:We,rows:tr>1?tr-1:2},{cols:We,rows:tr}]){if(_t(z))break;let Pr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Pr,...nr}}),z.inputSequence!==Pr)ir("job_input_sequence")}continue}let ke=_t(z)||Ke?void 0:x.shift();if(ke){M-=jo(ke);let We=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:We,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:We,cols:ke.cols,rows:ke.rows}})}catch(tr){if(!(tr instanceof r)||tr.code!=="job_input_backpressure")throw tr;G-=1,x.unshift(ke),M+=jo(ke),Ke=!0;continue}if(z.inputSequence!==We)ir("job_input_sequence")}else if(await new Promise((We)=>{let tr=setTimeout(We,Ke||!Be?10:50);if(S=()=>{clearTimeout(tr),We()},w.signal.aborted||!Ke&&x.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(We){if(!J||!(We instanceof r)||We.code!=="cancelled")throw We}}}catch(le){ve??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!_t(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!_t(z)||z.pty?.cleanup!=="confirmed")ir("pty_cleanup_unconfirmed");let le=Oe(z);if(_.readyState===Pn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);_.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await Ve("pty.stopped",le)}catch(le){ve??=le}_.terminate()}if(ve)throw ve;if(e.signal.aborted)ir("cancelled");if(!z)ir("pty_cleanup_unconfirmed");return{receipt:Oe(z)}}import{createHash as Si,randomUUID as Tn}from"crypto";import{spawnSync as Go}from"child_process";import{closeSync as Uo,constants as In,fstatSync as Ei,fsyncSync as Ri,lstatSync as Lt,mkdirSync as Oi,mkdtempSync as Jo,openSync as zo,readFileSync as xi,readdirSync as Vo,realpathSync as Nt,rmSync as An,unlinkSync as Pi}from"fs";import{createConnection as Ai}from"net";import{dirname as Ti,join as tt,sep as Ci}from"path";import{tmpdir as Hi}from"os";var Or=new Map,Jr=new Map;function Ur(e,l){return Si("sha256").update(JSON.stringify([e,l])).digest("hex")}function mt(e){try{Oi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Lt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Nt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function Ni(e){let l;try{l=Lt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||Vo(e).length>0}function hr(e){let l=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>Ni(tt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;mt(f);let _=tt(f,"jobs");mt(_);let w=tt(_,l.slice(0,16));if(e.maxScopes!==void 0){let I=Vo(_);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||I.length>e.maxScopes||!I.includes(l.slice(0,16))&&I.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}mt(w);let S=Jo(tt(Wo(),"reason-j-"));try{return mt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Tn()}`:tt(S,"control.sock"),disposeSocket:()=>An(S,{recursive:!0,force:!0})}}catch(I){throw An(S,{recursive:!0,force:!0}),I}}var Bi=60000,ji=5000;function Wi(e){if(process.platform==="win32")return Fi(e);let l=Go("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),f=l.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(l.stdout.trim()):null,_=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||_<0||_%3!==0)return null;let w=new Date(Number(f[6]),_/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Fi(e){let l=Go(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:De()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function Yo(e,l={}){let f=tt(e.journalDirectory,"owner.lock"),_;try{_=zo(f,In.O_RDONLY|In.O_NOFOLLOW)}catch{return null}try{let w=Ei(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(xi(_,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Bi)return null;I={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:T,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof T!=="number"||!Number.isSafeInteger(T))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(F))I={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Wi)(F);if(z===null||z<=T+ji)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Lt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Pi(f);let x=zo(e.journalDirectory,In.O_RDONLY);try{Ri(x)}finally{Uo(x)}return I}catch{return null}finally{Uo(_)}}function Xo(e){let l={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},f=Ur(l.root,l.runId);if(Or.has(f)||l.operationId!==void 0&&Jr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Bo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Or.get(_.key)===_,identity:()=>{try{return ht(l)}catch{return null}},inspect:(w,S)=>{if(Or.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Zo(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Or.set(f,_),l.operationId!==void 0)Jr.set(l.operationId,_);return()=>{if(Or.get(_.key)===_)Or.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Ui=5000,zi=20;async function Zi(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Ui;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=ht(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((I)=>setTimeout(I,zi))}if(Jr.get(e.operationId)!==f||Or.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(e.root,e.runId);if(f.key===_)return;if(Or.has(_))l("The taking run already has a live Hands job supervisor.");Or.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,Or.set(_,f)}function ot(e){let l="operationId"in e?Jr.get(e.operationId):Or.get(Ur(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function Xi(e){let l=Or.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function Yi(e){let l=Or.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function Qi(e){let l=Ur(e.root,e.runId),f=Or.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,I=_?.environment,W=e.owner&&{...e.owner},x=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!_||!S||!I||!W||!x||!_.workspace)return M();let G=Object.freeze({..._.workspace}),F=ht(_),T=I.current(),re=()=>{if(Or.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||O(e.workspace)!==O(G))M();let z=ht(_),fe=I.current();if(z.generation!==F.generation||z.fenceId!==F.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==T.snapshot_id||fe.revision!==T.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||x.device_id!==e.deviceId||x.binding!==fe.binding.kind||x.target_revision!==fe.binding.target_revision||x.root_grant_revision!==fe.binding.root_grant_revision||x.target_generation!==F.generation||x.target_fence_id!==F.fenceId)M()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return M();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Fo({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(T.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:T.revision,snapshotId:T.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:T.binding.kind,targetRevision:T.binding.target_revision,rootGrantRevision:T.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>fr(F,Hr(JSON.stringify({...z,type:"job",version:2,generation:F.generation,id:Tn()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function eo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Or.get(Ur(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Zo(l,e.payload,e.signal)}var $i=1e4,Ki=20,Gi=Se/2,Vi=Je/2,qi=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Zo(e,l,f){if(Object.keys(l).some((M)=>!["jobId","action","input","waitForExitMs"].includes(M)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:_,...w}=l;if(_!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof _!=="number"||!Number.isSafeInteger(_)||_<1||_>$i))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=ht(e);return fr(G,Hr(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:Tn()})),f)},I=await S(w);if(_===void 0)return I;let W=Date.now()+_,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Gi&&qi(x.job)<Vi&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Ki,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;x=M}catch{break}}return x}function ht(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!U(l.generation)||!N(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function fr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Ai(e.socketPath),I="",W=!1,x,M=(F,T)=>{if(W)return;if(W=!0,clearTimeout(x),f.removeEventListener("abort",G),S.destroy(),F)w(F);else _(T)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),x=setTimeout(()=>M(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>M(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
2
|
+
import{Gt,j}from"./vm-hands-entry-lite-rzr2ncf5.js";import{ue,Ce,Z,Ae,de,rr,et,X,O,H,tn}from"./vm-hands-entry-lite-38g65s5x.js";import{Lo,ri}from"./vm-hands-entry-lite-nqdstx24.js";import{xo,P,Je,Se,Ze,ne,Xe,Vn,Ee,Xt,ae,U,N,ce,Hr,zr,Kn}from"./vm-hands-entry-lite-5gevvgec.js";import{Pe,oe,pe,Y,Re,q,Q}from"./vm-hands-entry-lite-5tbntcyq.js";import{It,kr,at,V,D,R,b,En}from"./vm-hands-entry-lite-77j164ps.js";import{Er,xr,vn,oo,He,Sn}from"./vm-hands-entry-lite-tebh7dcm.js";import{K}from"./vm-hands-entry-lite-ncbzy69k.js";import{Mi}from"./vm-hands-entry-lite-xdjrdkh2.js";import{p,ze,Dt,ct,so,_e,we}from"./vm-hands-entry-lite-psywfz8m.js";import{v,h,lo}from"./vm-hands-entry-lite-f69t48dj.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{Qt}from"./vm-hands-entry-lite-sss0m3yn.js";import{a,ie,$o}from"./vm-hands-entry-lite-swrymqj9.js";import{L,Ii,Di,Ho,y,t,k,Et,o,d,u,i,c,g,ee,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";import{Li}from"./vm-hands-entry-lite-mk5ayds8.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{qo,se,Wo,C,De,Me,A}from"./vm-hands-entry-lite-87vmbt38.js";var gi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function l(w){return e[w]??null}let f={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},_={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=_[w.expected]??w.expected,I=Ho(w.input),W=_[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Di(w.values[0])}`;return`Invalid option: expected one of ${Ii(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",I=l(w.origin);if(I)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${I.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",I=l(w.origin);if(I)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${I.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${Ii(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((I)=>`'${I}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function Rn(){return{localeError:gi()}}L(Rn());class pt extends Error{}function Ao(e){let l;try{l=new URL(e)}catch{throw new pt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new pt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new pt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new pt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new pt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as bi}from"crypto";import{isAbsolute as To,join as Do,relative as Co,resolve as Vt,sep as No}from"path";var Jt=t().min(1).refine(To,"absolute path required"),xn=c({version:n(1),apiOrigin:Et(),channel:s(["staging","production"]),stateDirectory:Jt,workspaceRoot:Jt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:c({version:n(Gt),url:t().refine((e)=>{try{return Ao(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Jt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(Jt).min(1).max(31).optional()}),wi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[xn,xn.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),xn.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!wi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else if(e.channel==="pr"){let _=e.prEnvironment,w=/^https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.up\.railway\.app$/.exec(e.apiOrigin),S=w?.[1]?.match(/(?:^|-)pr-[0-9]+(?=-|$)/g)?.map((I)=>I.replace(/^-/,""));if(!_||/^pr-[1-9][0-9]*$/.exec(_)?.[0]!==_||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==_)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Lo(e.channel,_.origin))l.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!je(e.workspaceRoot,e.stateDirectory))l.addIssue({code:"custom",message:"state and workspace must be disjoint"});let f=e.folders??[];if(new Set([e.workspaceRoot,...f]).size!==f.length+1||f.some((_)=>!je(_,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return Do(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if(Fr(l,e))return!1;return!Fr(e,l)||E(Do(No,Co(Vt(e),Vt(l))))}function Fr(e,l){let f=Co(Vt(e),Vt(l));return f===""||f!==".."&&!f.startsWith(`..${No}`)&&!To(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...I}=e;return bi("sha256").update(JSON.stringify(I)).digest("hex")}var yi=4,vi=[2375,2376,9222,9229];function pr(e){let l=new Set(vi);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var ki=60000;function Bo(e){let l=new AbortController,f=new Map,_=(x)=>JSON.stringify([x.jobId,x.port]);function w(x){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||x.organization_id!==M.organization_id||x.user_id!==M.user_id||x.device_id!==M.device_id)Gr()}function S(x){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===x.generation&&M.binding.target_fence_id===x.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function I(x,M,G){let F=await W(x,M,G);if(F!=="moved")return F;let T=await W(x,M,G);return T==="moved"?null:T}async function W(x,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||x.expiresAtMs<=Date.now()||x.expiresAtMs>e.expiresAtMs)return null;let T=M.opened,re=T!==void 0&&F.generation>T.generation,J=S(F);if(re){if(J){if(J.revision<=T.revision||x.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==T.attachmentRevision||J.binding.root_grant_revision!==T.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>ki)return null}else if(!J||x.expiresAtMs>Date.parse(J.expires_at)||T&&(F.generation!==T.generation||F.fenceId!==T.fenceId))return null;let z=await e.inspect(x.jobId,G),fe=e.identity(),ve=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:F.generation,fenceId:F.fenceId,snapshotId:J.snapshot_id,revision:J.revision,attachmentRevision:J.binding.target_revision,grantRevision:J.binding.root_grant_revision},Oe=re?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ve?.snapshot_id!==J?.snapshot_id||ve?.revision!==J?.revision)return"moved";let $e=z.ok&&z.job.environmentSnapshotId!==void 0&&z.job.environmentRevision!==void 0?{snapshotId:z.job.environmentSnapshotId,revision:z.job.environmentRevision}:null;if(!z.ok||z.generation!==F.generation||!Oe||!$e)return null;if(($e.snapshotId!==Oe.snapshotId||$e.revision!==Oe.revision)&&(re||!e.environment.carried($e.snapshotId,$e.revision)))return null;if(!T&&F.generation===x.generation&&F.fenceId===x.fenceId)M.opened={...Oe,...$e};return{executorLaunchId:e.executorLaunchId,job:z.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:Oe.attachmentRevision,grantRevision:Oe.grantRevision,generation:Oe.generation,fenceId:Oe.fenceId,jobId:z.job.jobId,port:x.port,expiresAtMs:x.expiresAtMs}}}catch{return null}}return{async open(x,M,G){w(M);let{binding:F,deviceRelayUrl:T}=ct(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Gr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==T)Gr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:F}}if(f.size>=yi)Gr();let z=new AbortController,fe={},ve=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>I(F,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Oe=_e({binding:F,deviceRelayUrl:T,port:ve,signal:z.signal}),$e={binding:F,relay:T,abort:z,port:ve,opened:Oe};f.set(re,$e);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===$e)f.delete(re)};try{if((await Oe).closed.then(qe),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ve.check()))Gr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Gr()}},async close(x,M){w(M);let{binding:G}=so(x),F=f.get(_(G));if(!F||!ze(F.binding,G))Gr();return F.abort.abort(),await F.opened.then((T)=>T.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let x of f.values())x.abort.abort();f.clear()}}}import{WebSocket as Pn}from"ws";var jo=(e)=>("data"in e)?e.data.length:e.bytes,Mo=2*Xe;function ir(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var _t=(e)=>!["starting","running"].includes(e.state);function Ji(e,l,f=Date.now()){let _=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==_.length||Object.keys(e).some((M)=>!_.includes(M))||!ae(l)||!ae(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((M)=>Number.isSafeInteger(M)&&Number(M)>=1&&Number(M)<=Ee))ir("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ir("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ir("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return ir("invalid_pty_request")}if(!["ws:","wss:"].includes(I.protocol)||I.username||I.password||I.hash||I.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(I.hostname))ir("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ir("invalid_pty_request");return{workspace:H(e.workspace)??ir("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:I.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Fo(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ir("cancelled");let _=new Pn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},I=()=>{w.abort(),S()};e.signal.addEventListener("abort",I,{once:!0});let W=setTimeout(I,Math.max(1,l.leaseExpiresAtMs-Date.now())),x=[],M=0,G=0,F=0,T=!1,re=!1,J=!1,z,fe,ve,be=(le)=>{ve=new r(le,"Bound terminal input was refused."),I()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",I),_.on("message",(le,he)=>{if(w.signal.aborted)return;if(!re){be("pty_not_ready");return}let xe=Array.isArray(le)?Buffer.concat(le):le instanceof ArrayBuffer?Buffer.from(le):le;if(xe.length===0)return;let Ke=x.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.data,xe]);else if(he)x.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,I();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((ke)=>Number.isSafeInteger(ke)&&ke>=1&&ke<=Ee))throw Error("invalid_control");x.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Oe(le){return Kn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function $e(le){if(!le.ok)ir(le.error);let he=le.job;if(le.generation!==f.scope.generation||he.jobId!==l.jobId||!he.pty||he.leaseExpiresAtMs>l.leaseExpiresAtMs||he.process&&he.process.executorLaunchId!==f.scope.executorLaunchId||he.process&&fe&&(he.process.pid!==fe.pid||he.process.processGroupId!==fe.processGroupId)||he.state!=="starting"&&(he.environmentRevision!==f.environment.revision||he.environmentSnapshotId!==f.environment.snapshotId))ir("pty_binding_changed");if(Oe(he),he.process)fe??={...he.process};return he}async function qe(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)ir("cancelled");let xe=$e(he);if(xe.inputSequence!==G)ir("job_input_sequence");if(!_t(xe)&&xe.leaseExpiresAtMs<=Date.now())ir("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Pn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Mo)ir("pty_output_backpressure");_.send(le)}function Fe(le){if(le.firstCursor>F+1)F=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=F)continue;if(he.cursor!==F+1)ir("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Mo)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)ir("pty_output_gap");return!0}async function Ve(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ke,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function Te(){let le=AbortSignal.timeout(Xt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ke=new Promise((Le,Be)=>{if(xe=()=>Be(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),le.addEventListener("abort",xe,{once:!0}),le.aborted)xe()});try{let Le=await Promise.race([he,Ke]);if(le.aborted)ir("pty_cleanup_unconfirmed");return $e(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),We=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",We,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",We),Le()}),w.signal.aborted)We()}),f.assertCurrent(),T=!0,z=await qe({jobId:l.jobId,action:"start",input:{mode:"pty",cols:l.cols,rows:l.rows,leaseExpiresAtMs:l.leaseExpiresAtMs}});let le=Date.now()+5000;while(z.state==="starting"){if(Date.now()>=le)ir("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ir("pty_not_ready");await Ve("pty.ready",Oe(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Oe(z)}));let he=!1,xe=0,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=Fe(z);if(_t(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:We,rows:tr}=z.pty;for(let nr of[{cols:We,rows:tr>1?tr-1:2},{cols:We,rows:tr}]){if(_t(z))break;let Pr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Pr,...nr}}),z.inputSequence!==Pr)ir("job_input_sequence")}continue}let ke=_t(z)||Ke?void 0:x.shift();if(ke){M-=jo(ke);let We=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:We,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:We,cols:ke.cols,rows:ke.rows}})}catch(tr){if(!(tr instanceof r)||tr.code!=="job_input_backpressure")throw tr;G-=1,x.unshift(ke),M+=jo(ke),Ke=!0;continue}if(z.inputSequence!==We)ir("job_input_sequence")}else if(await new Promise((We)=>{let tr=setTimeout(We,Ke||!Be?10:50);if(S=()=>{clearTimeout(tr),We()},w.signal.aborted||!Ke&&x.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(We){if(!J||!(We instanceof r)||We.code!=="cancelled")throw We}}}catch(le){ve??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!_t(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!_t(z)||z.pty?.cleanup!=="confirmed")ir("pty_cleanup_unconfirmed");let le=Oe(z);if(_.readyState===Pn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);_.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await Ve("pty.stopped",le)}catch(le){ve??=le}_.terminate()}if(ve)throw ve;if(e.signal.aborted)ir("cancelled");if(!z)ir("pty_cleanup_unconfirmed");return{receipt:Oe(z)}}import{createHash as Si,randomUUID as Tn}from"crypto";import{spawnSync as Go}from"child_process";import{closeSync as Uo,constants as In,fstatSync as Ei,fsyncSync as Ri,lstatSync as Lt,mkdirSync as Oi,mkdtempSync as Jo,openSync as zo,readFileSync as xi,readdirSync as Vo,realpathSync as Nt,rmSync as An,unlinkSync as Pi}from"fs";import{createConnection as Ai}from"net";import{dirname as Ti,join as tt,sep as Ci}from"path";import{tmpdir as Hi}from"os";var Or=new Map,Jr=new Map;function Ur(e,l){return Si("sha256").update(JSON.stringify([e,l])).digest("hex")}function mt(e){try{Oi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Lt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Nt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function Ni(e){let l;try{l=Lt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||Vo(e).length>0}function hr(e){let l=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>Ni(tt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;mt(f);let _=tt(f,"jobs");mt(_);let w=tt(_,l.slice(0,16));if(e.maxScopes!==void 0){let I=Vo(_);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||I.length>e.maxScopes||!I.includes(l.slice(0,16))&&I.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}mt(w);let S=Jo(tt(Wo(),"reason-j-"));try{return mt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Tn()}`:tt(S,"control.sock"),disposeSocket:()=>An(S,{recursive:!0,force:!0})}}catch(I){throw An(S,{recursive:!0,force:!0}),I}}var Bi=60000,ji=5000;function Wi(e){if(process.platform==="win32")return Fi(e);let l=Go("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),f=l.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(l.stdout.trim()):null,_=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||_<0||_%3!==0)return null;let w=new Date(Number(f[6]),_/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Fi(e){let l=Go(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:De()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function Yo(e,l={}){let f=tt(e.journalDirectory,"owner.lock"),_;try{_=zo(f,In.O_RDONLY|In.O_NOFOLLOW)}catch{return null}try{let w=Ei(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(xi(_,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Bi)return null;I={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:T,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof T!=="number"||!Number.isSafeInteger(T))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(F))I={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Wi)(F);if(z===null||z<=T+ji)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Lt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Pi(f);let x=zo(e.journalDirectory,In.O_RDONLY);try{Ri(x)}finally{Uo(x)}return I}catch{return null}finally{Uo(_)}}function Xo(e){let l={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},f=Ur(l.root,l.runId);if(Or.has(f)||l.operationId!==void 0&&Jr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Bo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Or.get(_.key)===_,identity:()=>{try{return ht(l)}catch{return null}},inspect:(w,S)=>{if(Or.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Zo(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Or.set(f,_),l.operationId!==void 0)Jr.set(l.operationId,_);return()=>{if(Or.get(_.key)===_)Or.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Ui=5000,zi=20;async function Zi(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Ui;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=ht(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((I)=>setTimeout(I,zi))}if(Jr.get(e.operationId)!==f||Or.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(e.root,e.runId);if(f.key===_)return;if(Or.has(_))l("The taking run already has a live Hands job supervisor.");Or.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,Or.set(_,f)}function ot(e){let l="operationId"in e?Jr.get(e.operationId):Or.get(Ur(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function Xi(e){let l=Or.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function Yi(e){let l=Or.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function Qi(e){let l=Ur(e.root,e.runId),f=Or.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,I=_?.environment,W=e.owner&&{...e.owner},x=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!_||!S||!I||!W||!x||!_.workspace)return M();let G=Object.freeze({..._.workspace}),F=ht(_),T=I.current(),re=()=>{if(Or.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||O(e.workspace)!==O(G))M();let z=ht(_),fe=I.current();if(z.generation!==F.generation||z.fenceId!==F.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==T.snapshot_id||fe.revision!==T.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||x.device_id!==e.deviceId||x.binding!==fe.binding.kind||x.target_revision!==fe.binding.target_revision||x.root_grant_revision!==fe.binding.root_grant_revision||x.target_generation!==F.generation||x.target_fence_id!==F.fenceId)M()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return M();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Fo({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(T.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:T.revision,snapshotId:T.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:T.binding.kind,targetRevision:T.binding.target_revision,rootGrantRevision:T.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>fr(F,Hr(JSON.stringify({...z,type:"job",version:2,generation:F.generation,id:Tn()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function eo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Or.get(Ur(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Zo(l,e.payload,e.signal)}var $i=1e4,Ki=20,Gi=Se/2,Vi=Je/2,qi=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Zo(e,l,f){if(Object.keys(l).some((M)=>!["jobId","action","input","waitForExitMs"].includes(M)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:_,...w}=l;if(_!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof _!=="number"||!Number.isSafeInteger(_)||_<1||_>$i))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=ht(e);return fr(G,Hr(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:Tn()})),f)},I=await S(w);if(_===void 0)return I;let W=Date.now()+_,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Gi&&qi(x.job)<Vi&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Ki,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;x=M}catch{break}}return x}function ht(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!U(l.generation)||!N(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function fr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Ai(e.socketPath),I="",W=!1,x,M=(F,T)=>{if(W)return;if(W=!0,clearTimeout(x),f.removeEventListener("abort",G),S.destroy(),F)w(F);else _(T)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),x=setTimeout(()=>M(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>M(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
3
3
|
`)),S.on("data",(F)=>{if(I+=F,Buffer.byteLength(I)>Ze)M(new r("hands_job_result_unknown","Hands job result exceeded its bound."))}),S.once("end",()=>{if(Date.now()>=e.expiresAtMs){M(new r("hands_job_result_unknown","Hands authority expired before the result was acknowledged."));return}try{let F=zr(I.trim());if(F.id!==l.id||F.generation!==e.generation||F.ok&&F.job.jobId!==l.jobId)throw Error("identity");M(void 0,F)}catch{M(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),S.once("close",()=>{if(!W)M(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function Ko(e){let l=Nt(e.root),f=e.authority,_=Date.parse(e.leaseUntil),w=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(_)||_<=Date.now())throw Error("local_device_gh_lease_expired")};if(w(),f.readOnly&&f.generation===null)return{root:l,readOnly:!0,signal:e.signal,deadlineMs:_,assertCurrent:w};let S=Ur(l,e.runId),I=Or.get(S),W=I?.binding;if(!W?.environment||!W.workspace||W.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let x=W.environment.current(),M=()=>{w();let F=W.environment.current(),T=ht(W);if(Or.get(S)!==I||F.github_auth!=="local_gh"||F.run_id!==W.runId||f.runId!==e.runId||F.device_id!==f.deviceId||F.root_id!==f.rootId||String(F.binding.root_grant_revision)!==f.rootRevision||F.binding.target_generation!==f.generation||F.binding.target_fence_id!==f.fenceId||T.generation!==f.generation||T.fenceId!==f.fenceId||F.snapshot_id!==x.snapshot_id||F.revision!==x.revision)throw Error("local_device_gh_authority_changed")};M();let G=ie(l,W.workspace);return{root:G.boundary,signal:e.signal,deadlineMs:_,privateDirectory:Ti(W.environment.path),repoPath:G.path,readOnly:f.readOnly,forbiddenSecretValues:Object.values(x.variables),secretNames:(F)=>Object.entries(x.variables).filter(([,T])=>T.trim()===F.trim()).map(([T])=>`variable ${T}`),assertCurrent:M}}async function to(e,l){let f=Pe.parse(e.request),_=oe.parse(e.authority);if(_.contributorRefresh&&f.kind==="read"&&_.readOnly)return l(Ko(e));let w=Boolean(_.contributorRefresh);if(w&&(_.merge||f.kind!=="pr_mutation"||f.mutation.action!=="edit"||typeof f.mutation.body!=="string"||f.mutation.title!==void 0||f.mutation.base!==void 0||_.readOnly||_.runId!==e.runId||_.repoFullName!==f.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(f.kind!=="pr_merge"&&!w){if(_.merge)throw Error("local_device_gh_merge_authority_invalid");return l(Ko(e))}if(!w&&(!_.merge||_.readOnly||_.runId!==e.runId||_.repoFullName!==f.repoFullName||_.merge.source==="agent"&&(_.generation===null||_.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let S=Nt(e.root),I=Lt(S),W=Date.parse(e.leaseUntil);if(!Number.isFinite(W)||W<=Date.now())throw Error("local_device_gh_lease_expired");let x=Nt(Hi());if(x===S||x.startsWith(S+Ci))throw Error("local_device_gh_private_scope_unavailable");let M=Jo(tt(x,"reason-gh-merge-"));try{mt(M);let G=()=>{if(e.signal.throwIfAborted(),Date.now()>=W)throw Error("local_device_gh_lease_expired");let F=Lt(e.root);if(F.isSymbolicLink()||F.dev!==I.dev||F.ino!==I.ino||Nt(e.root)!==S)throw Error("local_device_gh_authority_changed");mt(M)};return G(),await l({root:S,readOnly:!1,privateDirectory:M,forbiddenSecretValues:[],signal:e.signal,deadlineMs:W,assertCurrent:G})}finally{An(M,{recursive:!0,force:!0})}}var rs=43200000;function gt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Qo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function es(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function ro(e){if(!Qo(e)||!es(e,["version","outcome","clock_source","validation_now_ms","expiry_ms","remaining_ms","maximum_lifetime_ms","cli_artifact"])||e.version!==1||e.maximum_lifetime_ms!==43200000||typeof e.outcome!=="string"||!["accepted","parse","noncanonical","expired","over_cap"].includes(e.outcome)||typeof e.clock_source!=="string"||!["date_now","injected"].includes(e.clock_source))return null;for(let _ of["validation_now_ms","expiry_ms"]){let w=e[_];if(w!==null&&(typeof w!=="number"||gt(w)===null))return null}if(e.remaining_ms!==null&&(typeof e.remaining_ms!=="number"||!Number.isSafeInteger(e.remaining_ms)))return null;let l=typeof e.expiry_ms==="number"&&typeof e.validation_now_ms==="number"?e.expiry_ms-e.validation_now_ms:null;if(e.remaining_ms!==(l!==null&&Number.isSafeInteger(l)?l:null))return null;if(e.outcome==="parse"&&e.expiry_ms!==null)return null;if(e.outcome!=="parse"&&e.expiry_ms===null)return null;if(e.outcome==="expired"&&!(typeof l==="number"&&l<=0))return null;if(e.outcome==="over_cap"&&!(typeof l==="number"&&l>43200000))return null;if(e.outcome==="accepted"&&!(typeof l==="number"&&l>0&&l<=43200000))return null;let f=e.cli_artifact;if(!Qo(f)||!es(f,["kind","status","sha256","observed_at_ms"])||f.observed_at_ms!==null&&(typeof f.observed_at_ms!=="number"||gt(f.observed_at_ms)===null))return null;if(f.kind==="entrypoint_file"){if(f.status!=="observed"||typeof f.sha256!=="string"||!/^[a-f0-9]{64}$/.test(f.sha256)||f.observed_at_ms===null)return null}else if(f.kind!=="unavailable"||f.sha256!==null||typeof f.status!=="string"||!["unsupported_entrypoint","read_failed","file_changed","size_limit","time_limit"].includes(f.status))return null;return e}var Dn=c({kind:s(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),ts=new RegExp(at.tokenPattern),ea=c({token_url:Et().max(2048),request_token:t().min(1).max(8192).regex(ts),aws_credentials_url:Et().max(2048).nullable()});function ns(e,l){let f=(_,w)=>{try{let S=new URL(_);return S.origin===new URL(l).origin&&S.pathname===w&&!S.username&&!S.password&&!S.search&&!S.hash}catch{return!1}};if(!ts.test(e.request_token)||!f(e.token_url,at.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,at.awsPath))return null;return{REASON_OIDC_TOKEN_URL:e.token_url,REASON_OIDC_REQUEST_TOKEN:e.request_token,...e.aws_credentials_url!==null?{AWS_CONTAINER_CREDENTIALS_FULL_URI:e.aws_credentials_url,AWS_CONTAINER_AUTHORIZATION_TOKEN:e.request_token}:{}}}function os(e){return new TextEncoder().encode(e).byteLength}function ra(e){return os(JSON.stringify(e)+`
|
|
4
|
-
`)}var mr=c({version:n(1),snapshot_id:k(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:k(),root_id:k(),binding:Dn.extend({target_generation:o().int().positive(),target_fence_id:k()}),expires_at:y.datetime({offset:!0}),variables:ee(t().max(128).regex(It),t().refine((e)=>!e.includes("\x00")&&os(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:n("local_gh").optional(),git:c({base_url:Et().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:ea.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ra(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ta}from"child_process";import{basename as na,isAbsolute as Ou}from"path";var oa=0,ss=120000,is=15000,sa=65536;function Cn(e=process.execPath,l=process.argv[1]){let f=na(e),_=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:_?[l]:[]}}function no(e={}){let{command:l,prefix:f}=Cn(e.executablePath,e.sourceEntrypoint),_=e.spawnProcess??ta,w=e.now??Date.now,S=null,I=0,W=!1,x=(G)=>{try{G.kill("SIGKILL")}catch{}},M=()=>{if(W)return;if(S&&w()-I<ss-is)return;if(S){let F=S;S=null,x(F)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(oa)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}S=G,I=w(),G.on("error",()=>{if(S===G)S=null}),G.once("exit",(F,T)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:F,exit_signal:T})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:M,take(G){let F=S;if(!F||W)return null;let T=G.args.at(-1),re=G.options.env,J=G.options.cwd,z=[...f,"__device","__hands-worker","--config"];if(G.command!==l||G.args.length!==z.length+1||z.some((Oe,$e)=>G.args[$e]!==Oe)||typeof T!=="string"||!re||typeof J!=="string"||G.options.shell||JSON.stringify(G.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;S=null;let fe=F.stdin,ve={configPath:T,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Oe)=>typeof Oe[1]==="string"))},be=JSON.stringify(ve);if(F.exitCode!==null||F.signalCode!==null||!fe||fe.destroyed||w()-I>=ss-is||Buffer.byteLength(be,"utf8")>sa)return x(F),null;return fe.on("error",()=>{return}),fe.end(be),F.once("exit",()=>{M()}),e.log?.("hands.worker_prespawn_taken",{pid:F.pid??null}),F},adopt(G){G.once("exit",()=>{M()})},close(){if(W=!0,S)x(S);S=null}}}import{accessSync as ua,constants as fa,statSync as pa}from"fs";import{homedir as _a,tmpdir as ma,userInfo as ha}from"os";import{delimiter as ga,win32 as ba}from"path";var ia=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var aa=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],ca=new Set(["BUN_INSTALL"]);var da=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function la(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>da.test(l.replaceAll("_","-")))}function as(e){return Object.keys(e).filter((l)=>ia.has(l)&&!(l==="NODE_OPTIONS"&&la(e[l]))||aa.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!ca.has(l)).sort()}var wa=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),ya=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,va=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,ka=/^[A-Za-z_][A-Za-z0-9_]*$/;function gr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ba.isAbsolute(w):w.startsWith("/"))||/[\0\r\n]/.test(w)||w.length>32768)throw Error("invalid_host_execution_environment");return w};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let f=new Set(as(e)),_=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,I]=w;return typeof I==="string"&&I.length<=32768&&!I.includes("\x00")&&S.length<=128&&ka.test(S)&&!f.has(S)&&!wa.has(S)&&!ya.test(S)&&!va.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||_a()),path:((w)=>process.platform==="win32"?Sn(w):w)(xr(e.PATH??"").join(ga)||Er),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||ma()),variables:_}}function _r(e=process.env,l=()=>ha().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return ua(w,fa.X_OK),pa(w).isFile()}catch{return!1}};if(f(e.SHELL))return e.SHELL;let _;try{_=l()}catch{_=void 0}return f(_)?_:"/bin/zsh"}import{readdir as Sa}from"fs/promises";var Ea=15000;function gn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function _n(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then try again.")}async function cs(e,{timeoutMs:l=Ea,open:f=(_)=>Sa(_)}={}){let _,w=new Promise((S)=>{_=setTimeout(()=>S("pending"),l)});try{if(await Promise.race([f(e).then(()=>"open"),w])==="pending")throw new r("folder_access_pending",`macOS is asking whether Reason may open ${e}. Answer the prompt on this Mac, then try again.`)}catch(S){if(gn(S))throw _n(e);if(S instanceof r)throw S}finally{clearTimeout(_)}}import{chmodSync as tc,closeSync as nc,constants as
|
|
4
|
+
`)}var mr=c({version:n(1),snapshot_id:k(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:k(),root_id:k(),binding:Dn.extend({target_generation:o().int().positive(),target_fence_id:k()}),expires_at:y.datetime({offset:!0}),variables:ee(t().max(128).regex(It),t().refine((e)=>!e.includes("\x00")&&os(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:n("local_gh").optional(),git:c({base_url:Et().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:ea.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ra(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ta}from"child_process";import{basename as na,isAbsolute as Ou}from"path";var oa=0,ss=120000,is=15000,sa=65536;function Cn(e=process.execPath,l=process.argv[1]){let f=na(e),_=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:_?[l]:[]}}function no(e={}){let{command:l,prefix:f}=Cn(e.executablePath,e.sourceEntrypoint),_=e.spawnProcess??ta,w=e.now??Date.now,S=null,I=0,W=!1,x=(G)=>{try{G.kill("SIGKILL")}catch{}},M=()=>{if(W)return;if(S&&w()-I<ss-is)return;if(S){let F=S;S=null,x(F)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(oa)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}S=G,I=w(),G.on("error",()=>{if(S===G)S=null}),G.once("exit",(F,T)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:F,exit_signal:T})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:M,take(G){let F=S;if(!F||W)return null;let T=G.args.at(-1),re=G.options.env,J=G.options.cwd,z=[...f,"__device","__hands-worker","--config"];if(G.command!==l||G.args.length!==z.length+1||z.some((Oe,$e)=>G.args[$e]!==Oe)||typeof T!=="string"||!re||typeof J!=="string"||G.options.shell||JSON.stringify(G.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;S=null;let fe=F.stdin,ve={configPath:T,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Oe)=>typeof Oe[1]==="string"))},be=JSON.stringify(ve);if(F.exitCode!==null||F.signalCode!==null||!fe||fe.destroyed||w()-I>=ss-is||Buffer.byteLength(be,"utf8")>sa)return x(F),null;return fe.on("error",()=>{return}),fe.end(be),F.once("exit",()=>{M()}),e.log?.("hands.worker_prespawn_taken",{pid:F.pid??null}),F},adopt(G){G.once("exit",()=>{M()})},close(){if(W=!0,S)x(S);S=null}}}import{accessSync as ua,constants as fa,statSync as pa}from"fs";import{homedir as _a,tmpdir as ma,userInfo as ha}from"os";import{delimiter as ga,win32 as ba}from"path";var ia=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var aa=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],ca=new Set(["BUN_INSTALL"]);var da=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function la(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>da.test(l.replaceAll("_","-")))}function as(e){return Object.keys(e).filter((l)=>ia.has(l)&&!(l==="NODE_OPTIONS"&&la(e[l]))||aa.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!ca.has(l)).sort()}var wa=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),ya=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,va=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,ka=/^[A-Za-z_][A-Za-z0-9_]*$/;function gr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ba.isAbsolute(w):w.startsWith("/"))||/[\0\r\n]/.test(w)||w.length>32768)throw Error("invalid_host_execution_environment");return w};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let f=new Set(as(e)),_=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,I]=w;return typeof I==="string"&&I.length<=32768&&!I.includes("\x00")&&S.length<=128&&ka.test(S)&&!f.has(S)&&!wa.has(S)&&!ya.test(S)&&!va.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||_a()),path:((w)=>process.platform==="win32"?Sn(w):w)(xr(e.PATH??"").join(ga)||Er),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||ma()),variables:_}}function _r(e=process.env,l=()=>ha().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return ua(w,fa.X_OK),pa(w).isFile()}catch{return!1}};if(f(e.SHELL))return e.SHELL;let _;try{_=l()}catch{_=void 0}return f(_)?_:"/bin/zsh"}import{readdir as Sa}from"fs/promises";var Ea=15000;function gn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function _n(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then try again.")}async function cs(e,{timeoutMs:l=Ea,open:f=(_)=>Sa(_)}={}){let _,w=new Promise((S)=>{_=setTimeout(()=>S("pending"),l)});try{if(await Promise.race([f(e).then(()=>"open"),w])==="pending")throw new r("folder_access_pending",`macOS is asking whether Reason may open ${e}. Answer the prompt on this Mac, then try again.`)}catch(S){if(gn(S))throw _n(e);if(S instanceof r)throw S}finally{clearTimeout(_)}}import{chmodSync as tc,closeSync as nc,constants as zn,fstatSync as oc,lstatSync as xs,openSync as sc,readSync as ic,realpathSync as $n,unlinkSync as ac}from"fs";import{lookup as cc}from"dns/promises";import{createRequire as dc}from"module";import{request as lc}from"http";import{request as uc}from"https";import it from"net";import{platform as Ds}from"os";import{basename as fc,extname as pc,isAbsolute as Ps,relative as Gn,resolve as yt,sep as Jn}from"path";var ds=String.raw`
|
|
5
5
|
async (roots) => {
|
|
6
6
|
"use strict";
|
|
7
7
|
const version = 2;
|
|
@@ -296,9 +296,9 @@ async (input) => {
|
|
|
296
296
|
if (!bridge || typeof bridge.evaluate !== "function") throw new Error("Reason Hands browser bridge is not installed");
|
|
297
297
|
return await bridge.evaluate(typeof input === "string" ? input : input && input.code);
|
|
298
298
|
}
|
|
299
|
-
`.trim();import{Buffer as bt}from"buffer";import{randomUUID as Ra}from"crypto";class _s extends Error{code;constructor(e){super(e==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":e);this.code=e;this.name="HandsReplBrowserDispatcherError"}}var ms=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),us=/^hands_[A-Za-z0-9_-]{8,128}$/,Oa=2048,hs=32,gs=1e4,xa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function Pa(e){let l=e.split("+"),f=(l.pop()??"").replace(/^Key/,"").toLowerCase();if(f==="f12")return!0;if(l.some((_)=>["Control","ControlOrMeta","Meta"].includes(_))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(f))return!0;if(l.some((_)=>["Control","ControlOrMeta","Meta"].includes(_))&&l.includes("Shift")&&f==="c")return!0;return l.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(f)}var Ia=(e)=>{let l=e.closest("a[href],area[href]");return{password:e.tagName==="INPUT"&&e.type==="password",executableLink:Boolean(l&&!/^(https?:|about:blank)/i.test(l.href))}},bs={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 Ie(e){throw new _s(e)}function Dr(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let l=Object.getPrototypeOf(e);return l===Object.prototype||l===null}function wt(e,l=0,f={nodes:0}){if(l>hs||++f.nodes>gs)Ie("hands_repl_json_too_complex");if(e===null||typeof e==="boolean"||typeof e==="string")return;if(typeof e==="number"){if(!Number.isFinite(e))Ie("hands_repl_invalid_json");return}if(Array.isArray(e)){for(let _ of e)wt(_,l+1,f);return}if(!Dr(e))Ie("hands_repl_invalid_json");for(let[_,w]of Object.entries(e)){if(ms.has(_))Ie("hands_repl_invalid_json");wt(w,l+1,f)}}function Hn(e){return typeof e==="string"&&Object.hasOwn(bs,e)}function Aa(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Hn(l)?l:null}function fs(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Ta(e){return Dr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function ps(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function Vr(e){return!!e&&typeof e==="object"}function qt(){return Object.freeze({$handsRepl:"undefined"})}function Da(e){if(!bt.isBuffer(e)&&!(e instanceof Uint8Array))Ie("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:bt.from(e).toString("base64")})}function ws(e){if(!Vr(e.browser)||!Vr(e.context)||!Vr(e.page))Ie("hands_repl_invalid_roots");if(typeof e.a11y!=="function"||typeof e.view!=="function")Ie("hands_repl_invalid_callbacks");let l=e.maxHandles??Oa;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,_=new WeakMap,w=e.createOpaqueId??Ra,S=(T,re)=>{if(!Vr(re))Ie("hands_repl_expected_target");let J=_.get(re)?.get(T);if(J)return J;if(f.size>=l)Ie("hands_repl_handle_limit");let z="";for(let be=0;be<16;be+=1){let Oe=`hands_${w()}`;if(us.test(Oe)&&!f.has(Oe)){z=Oe;break}}if(!z)Ie("hands_repl_invalid_opaque_id");let fe=Object.freeze({$handsRepl:"handle",id:z,kind:T});f.set(z,{kind:T,target:re});let ve=_.get(re);if(!ve)ve=new Map,_.set(re,ve);return ve.set(T,fe),fe},I=Object.freeze({browser:S("browser",e.browser),context:S("context",e.context),page:S("page",e.page)}),W=(T)=>{if(!Dr(T)||Object.keys(T).length!==3||T.$handsRepl!=="handle"||typeof T.id!=="string"||!us.test(T.id)||!Hn(T.kind))Ie("hands_repl_invalid_handle");let re=f.get(T.id);if(!re||re.kind!==T.kind)Ie("hands_repl_unknown_handle");return re},x=(T,re=0,J=new Set)=>{if(re>hs)Ie("hands_repl_json_too_complex");if(T===void 0)return qt();if(T===null||typeof T==="boolean"||typeof T==="string")return T;if(typeof T==="number"){if(!Number.isFinite(T))Ie("hands_repl_non_json_result");return T}if(Array.isArray(T)){if(J.has(T))Ie("hands_repl_cyclic_result");J.add(T);try{return T.map((z)=>x(z,re+1,J))}finally{J.delete(T)}}if(!Dr(T))Ie("hands_repl_non_json_result");if(J.has(T))Ie("hands_repl_cyclic_result");J.add(T);try{let z=Object.create(null);for(let fe of Object.keys(T)){let ve=Object.getOwnPropertyDescriptor(T,fe);if(!ve||!("value"in ve))continue;z[fe]=x(ve.value,re+1,J)}return z}finally{J.delete(T)}},M=(T,re)=>{if(re==="void")return qt();if(re==="json")return x(T);if(re==="bytes")return Da(T);let J=Aa(re);if(J){if(!Array.isArray(T))Ie("hands_repl_expected_target_list");if(J==="context"&&T.some((z)=>z!==e.context))Ie("hands_repl_foreign_context");return T.map((z)=>S(J,z))}if(T===null||T===void 0)return qt();if(!Hn(re))Ie("hands_repl_invalid_return_kind");if(re==="context"&&T!==e.context)Ie("hands_repl_foreign_context");return S(re,T)},G=(T)=>{if(Dr(T)&&T.$handsRepl==="handle")return W(T).target;if(fs(T))return bt.from(T.base64,"base64");if(Ta(T))return;if(ps(T))Ie("hands_repl_route_fulfill_only");if(Array.isArray(T))return T.map(G);if(!Dr(T))return T;let re=Object.create(null);for(let[J,z]of Object.entries(T))re[J]=G(z);return re};return Object.freeze({roots:I,dispatch:async(T)=>{if(!Dr(T)||typeof T.type!=="string")Ie("hands_repl_invalid_request");if(T.type==="a11y"){let ye=T.target===void 0?f.get(I.page.id):W(T.target);if(!ye||ye.kind!=="page"&&ye.kind!=="locator")Ie("hands_repl_invalid_a11y_target");return x(await e.a11y(ye.target))}if(T.type==="view"){if(wt(T.source),T.options!==void 0)wt(T.options);let ye=fs(T.source)?bt.from(T.source.base64,"base64"):T.source;if(e.privateProfile&&!bt.isBuffer(ye))Ie("hands_repl_profile_requires_image_bytes");return x(await e.view(ye,T.options))}if(T.type!=="call")Ie("hands_repl_invalid_request");if(typeof T.method!=="string"||T.method.length===0||T.method.length>128)Ie("hands_repl_invalid_method");if(ms.has(T.method))Ie("hands_repl_forbidden_method");let re=W(T.target),J=T.args??[];if(!Array.isArray(J))Ie("hands_repl_invalid_arguments");if(wt(J),re.kind==="page"&&T.method==="captureScreenshot"){if(J.length!==0)Ie("hands_repl_invalid_arguments");if(!e.screenshotExport)Ie("hands_repl_screenshot_export_unavailable");return x(await e.screenshotExport(re.target))}if(re.kind==="context"&&["startRecording","stopRecording"].includes(T.method)){if(!e.recording||re.target!==e.context)Ie("hands_repl_recording_unavailable");if(J.length>(T.method==="startRecording"?1:0))Ie("hands_repl_invalid_arguments");return x(T.method==="startRecording"?await e.recording.start(J[0]):await e.recording.stop())}if(e.privateProfile){let ye=T.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(ye)||re.kind==="browser"&&ye==="close"||re.kind==="context"&&ye==="close")Ie("hands_repl_private_profile_method_denied");if(re.kind==="browser"&&ye==="contexts")return M([e.context],"context[]");if((ye==="screenshot"||ye==="pdf")&&Dr(J[0])&&(("path"in J[0])||("style"in J[0])))Ie("hands_repl_private_profile_path_denied");if(ye==="goto"){if(typeof J[0]!=="string")Ie("hands_repl_private_profile_url_denied");try{let Fe=new URL(J[0]);if(!["http:","https:"].includes(Fe.protocol)&&J[0]!=="about:blank")Ie("hands_repl_private_profile_url_denied")}catch{Ie("hands_repl_private_profile_url_denied")}}if(ye==="getAttribute"&&(typeof J[0]!=="string"||!xa.has(J[0].toLowerCase())))Ie("hands_repl_private_profile_attribute_denied");if(re.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(ye)){let Fe=[re.target];if(ye==="allInnerTexts"){let Ve=Reflect.get(re.target,"all");if(typeof Ve!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Te=await Reflect.apply(Ve,re.target,[]);if(!Array.isArray(Te)||Te.length>gs||!Te.every(Vr))Ie("hands_repl_private_profile_probe_unavailable");Fe=Te}for(let Ve of Fe){let Te=Reflect.get(Ve,"isVisible");if(typeof Te!=="function"||!await Reflect.apply(Te,Ve,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}if(ye==="press"&&typeof J[0]==="string"&&Pa(J[0]))Ie("hands_repl_private_profile_browser_shortcut_denied");if(re.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(ye)){let Fe=Reflect.get(re.target,"evaluate");if(typeof Fe!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Ve=await Reflect.apply(Fe,re.target,[Ia]);if(!Dr(Ve)||typeof Ve.password!=="boolean"||typeof Ve.executableLink!=="boolean")Ie("hands_repl_private_profile_probe_unavailable");if(ye==="inputValue"&&Ve.password)Ie("hands_repl_private_profile_password_denied");if(ye!=="inputValue"&&Ve.executableLink)Ie("hands_repl_private_profile_url_denied");if(ye==="inputValue"){let Te=Reflect.get(re.target,"isVisible");if(typeof Te!=="function"||!await Reflect.apply(Te,re.target,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}}let z=bs[re.kind][T.method];if(!z)Ie("hands_repl_method_not_allowed");if(z.requiresStringSource&&typeof J[0]!=="string")Ie("hands_repl_string_source_required");if(re.kind==="browser"&&T.method==="contexts")return[I.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(T.method)&&J.some((ye)=>Dr(ye)&&("path"in ye)))Ie("hands_repl_file_path_not_allowed");if(T.method==="goto"&&typeof J[0]==="string"){let ye;try{ye=new URL(J[0]).protocol}catch{Ie("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(ye))Ie("hands_repl_file_path_not_allowed")}if(z.special==="contextViewportSize"){let ye=Reflect.get(re.target,"pages");if(typeof ye!=="function")Ie("hands_repl_method_unavailable");let Fe=await Reflect.apply(ye,re.target,[]),Ve=Array.isArray(Fe)?Fe[0]:void 0,Te=Vr(Ve)?Reflect.get(Ve,"viewportSize"):void 0;if(typeof Te!=="function")return qt();return M(await Reflect.apply(Te,Ve,[]),z.returns)}if(z.special==="property"){let ye=Reflect.get(re.target,T.method);return M(typeof ye==="function"?Reflect.apply(ye,re.target,[]):ye,z.returns)}let fe=Reflect.get(re.target,T.method);if(typeof fe!=="function")Ie("hands_repl_method_unavailable");if(z.special==="route"){let ye=J[1];if(!ps(ye))Ie("hands_repl_invalid_route_handler");wt(ye.options);let Fe=G(ye.options),Ve=async(he)=>{if(!Vr(he))Ie("hands_repl_invalid_route");let xe=Reflect.get(he,"fulfill");if(typeof xe!=="function")Ie("hands_repl_invalid_route");await Reflect.apply(xe,he,[Fe])},Te=[G(J[0]??null),Ve],le=await Reflect.apply(fe,re.target,Te);return M(le,z.returns)}let ve=J.map(G);if(T.method==="setInputFiles"){let ye=re.kind==="locator"?0:1,Fe=async(Te)=>{if(typeof Te!=="string"){if(!Dr(Te)||typeof Te.name!=="string"||typeof Te.mimeType!=="string"||!bt.isBuffer(Te.buffer))Ie("hands_repl_invalid_file_input");return Te}if(!e.readWorkspaceFile)Ie("hands_repl_workspace_required");return e.readWorkspaceFile(Te)},Ve=ve[ye];ve[ye]=Array.isArray(Ve)?await Promise.all(Ve.map(Fe)):await Fe(Ve)}if(T.method==="goto")await e.beforeNavigation?.();let be=e.actionRecorder?.(),Oe=await Reflect.apply(fe,re.target,ve),qe={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"}[T.method];if(qe){let ye=Reflect.get(re.target,"page"),Fe=re.kind==="page"?re.target:typeof ye==="function"?Reflect.apply(ye,re.target,[]):void 0;be?.(qe,Vr(Fe)?Fe:void 0)}return M(Oe,z.returns)}})}import{isIP as Ss}from"net";import{Resolver as Ca}from"dns/promises";import{isIP as Zt}from"net";var Ha=[["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 Nn(e){if(Zt(e)!==4)return null;let l=e.split(".");if(l.length!==4)return null;let f=0;for(let _ of l){let w=Number(_);if(!Number.isInteger(w)||w<0||w>255)return null;f=f*256+w}return f>>>0}function Na(e,l,f){let _=Nn(l);if(_===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(_&w)>>>0}function ys(e){let l=Nn(e);if(l===null)return!0;return Ha.some(([f,_])=>Na(l,f,_))}function La(e){if(Zt(e)!==6)return null;let l=e.toLowerCase(),f=l.indexOf("%");if(f>=0)l=l.slice(0,f);let _=[],w=l.lastIndexOf(":"),S=w>=0?l.slice(w+1):"";if(S.includes(".")){let T=Nn(S);if(T===null)return null;_=[T>>>16&65535,T&65535],l=l.slice(0,w+1)+"0:0"}let I=l.split("::");if(I.length>2)return null;let W=(T)=>{if(T==="")return[];let re=[];for(let J of T.split(":")){if(J===""||J.length>4||!/^[0-9a-f]+$/.test(J))return null;re.push(Number.parseInt(J,16))}return re},x=W(I[0]??"");if(x===null)return null;if(I.length===1){let T=x;if(T.length!==8)return null;return _.length>0?T.slice(0,6).concat(_):T}let M=W(I[1]??"");if(M===null)return null;let G=8-x.length-M.length;if(G<0)return null;let F=x.concat(Array(G).fill(0),M);if(F.length!==8)return null;return _.length>0?F.slice(0,6).concat(_):F}function Ba(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function ja(e){let l=La(e);if(l===null)return!0;let[f,_,w]=l;if((f&57344)!==8192)return!0;if(f===8193&&(_&65024)===0)return!0;if(f===8193&&_===3512)return!0;if(f===16383&&(_&61440)===0)return!0;if(f===8194)return ys(Ba(_,w));return!1}function yr(e){return e.replace(/^\[|\]$/g,"")}function Yt(e){let l=yr(e.trim()),f=Zt(l);if(f===4)return ys(l);if(f===6)return ja(l);return!0}function vs(e){if(e instanceof Error&&e.name==="TimeoutError")return"dns_timeout";switch(typeof e==="object"&&e!==null&&"code"in e?e.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 ks=5000;function Ma(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let _=new Ca({timeout:ks,tries:1});if(e)_.setServers(e);let w=()=>_.cancel();f?.addEventListener("abort",w,{once:!0});try{let[S,I]=await Promise.allSettled([_.resolve4(l),_.resolve6(l)]),W=[...S.status==="fulfilled"?S.value:[],...I.status==="fulfilled"?I.value:[]];if(W.length>0)return W;let x=[S,I].flatMap((G)=>G.status==="rejected"?[G.reason]:[]);throw x.find((G)=>["dns_temporary","dns_timeout"].includes(vs(G)))??x[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var Wa=Ma();async function Fa(e,l,f,_){if(_?.aborted)throw Error("aborted");let w=new AbortController,S,I,W=l(e,w.signal);W.catch(()=>{});try{return await Promise.race([W,new Promise((x,M)=>{if(S=setTimeout(()=>M(new DOMException("DNS lookup timed out","TimeoutError")),f),_)I=()=>M(Error("aborted")),_.addEventListener("abort",I,{once:!0})})])}finally{if(S!==void 0)clearTimeout(S);if(_&&I)_.removeEventListener("abort",I);w.abort()}}async function io(e,l=Wa,f){let _=yr(e);if(Zt(_))return Yt(_)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[_]};let w;try{w=await Fa(_,l,ks,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":vs(S)}}if(w.length===0)return{ok:!1,reason:"dns_empty"};if(w.some(Yt))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:w}}var Ua=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Ln(e){return e.length<=253&&Ua.test(e.toLowerCase())}function za(e,l){let f=e.trim().toLowerCase();if(!Ln(f))return!1;if(f.startsWith("*.")){let _=f.slice(2);return l===_||l.endsWith(`.${_}`)}return f===l}function $a(e){let l=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!l)return null;let f=l.slice(1).map(Number);return f.some((_)=>_>255)?null:f}function Bn(e,l=[]){let f=(_)=>{if(_=_.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!_.includes(":"))return _;try{_=new URL(`http://[${_}]/`).hostname.slice(1,-1)}catch{return _}let w=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(_);if(!w)return _;let S=parseInt(w[1],16),I=parseInt(w[2],16);return`${S>>8}.${S&255}.${I>>8}.${I&255}`};return l.some((_)=>f(_)===f(e))}function nt(e){e=e.toLowerCase().replace(/^\[|\]$/g,"");let l=$a(e);if(l){let[S,I,W]=l;if(S===127)return"loopback";return S===0||S===10||S>=224||S===100&&I>=64&&I<=127||S===169&&I===254||S===172&&I>=16&&I<=31||S===192&&(I===168||I===0&&(W===0||W===2)||I===88&&W===99)||S===198&&(I===18||I===19||I===51&&W===100)||S===203&&I===0&&W===113?"private":"public"}if(!e.includes(":"))return"hostname";try{e=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return"private"}if(e==="::1")return"loopback";let f=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(e);if(f){let S=parseInt(f[1],16),I=parseInt(f[2],16);return nt(`${S>>8}.${S&255}.${I>>8}.${I&255}`)==="public"?"public":"private"}let[_,w=0]=e.split(":").map((S)=>parseInt(S||"0",16));return _<8192||_>16383||_===8194||_===8193&&(w<512||w===3512)||_===16383&&w<4096?"private":"public"}function Ue(e,l){let f;try{f=new URL(e)}catch{return{allowed:!1,url:e,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(f.protocol))return{allowed:!0,url:e,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(f.protocol))return{allowed:!1,url:e,host:f.hostname||null,reason:"unsupported_protocol"};let _=f.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(l.mode==="off")return{allowed:!0,url:e,host:_,reason:"policy_off"};let w=(W)=>({allowed:!1,url:e,host:_,reason:W});if(f.username||f.password)return w("invalid_url");if(l.mode==="public_web"){let W=nt(_)!=="public"&&nt(_)!=="hostname"||_==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(_)||!_.includes(".")&&!Ss(_)||Boolean(Ss(_)&&Yt(_));return{allowed:!W,url:e,host:_,reason:W?"private_network":"public_web"}}let S=Number(f.port||(["https:","wss:"].includes(f.protocol)?443:80));if(l.deniedPorts?.includes(S)||Bn(_,l.deniedHosts))return w("destination_not_allowed");let I=nt(_);if(I==="private"||["local","internal","arpa"].some((W)=>_===W||_.endsWith(`.${W}`)))return w("private_network");if(I==="loopback"||_==="localhost"||_.endsWith(".localhost"))return l.allowedLoopbackPorts?.includes(S)?{allowed:!0,url:e,host:_,reason:"loopback"}:w("destination_not_allowed");if(l.allowedDomains.some((W)=>za(W,_)))return{allowed:!0,url:e,host:_,reason:"allowed_domain"};return{allowed:!1,url:e,host:_,reason:"destination_not_allowed"}}import Es from"child_process";import{accessSync as Ka,constants as Ga,readFileSync as Ja,statSync as Va}from"fs";import{createRequire as qa}from"module";import{dirname as _f,isAbsolute as jn,join as Ya,resolve as mf,win32 as Xa}from"path";var Mn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:Qt.dependencies["playwright-core"],browser:"chromium"}),Rs=["/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"],Fn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function Za(e=process.env){let l=[e.ProgramFiles??"C:\\Program Files",e["ProgramFiles(x86)"]??"C:\\Program Files (x86)"],f=e.LOCALAPPDATA?[e.LOCALAPPDATA]:[],_=(w,...S)=>w.map((I)=>Xa.join(I,...S));return[..._([...l,...f],"Google","Chrome","Application","chrome.exe"),..._(l,"Microsoft","Edge","Application","msedge.exe"),..._([...l,...f],"BraveSoftware","Brave-Browser","Application","brave.exe")]}function Bt(e){try{return Ka(e,Ga.X_OK),jn(e)&&Va(e).isFile()}catch{return!1}}function Un(e,l=process.platform){let f=l==="darwin"?Rs:l==="linux"?Fn:l==="win32"?Za():null;return f?(e??f).find(Bt)??null:null}function Qa(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];Es.spawn=new Proxy(Es.spawn,{apply(f,_,w){let S=Reflect.apply(f,_,w),I=w[1],W=w[2]?.stdio;if(Array.isArray(I)&&I.includes("--remote-debugging-pipe")&&Array.isArray(W)&&W[3]==="pipe"&&W[4]==="pipe")l.push(S);return S}}),Object.defineProperty(globalThis,e,{value:l})}async function en(e){if(Qa(),e!==void 0){if(!jn(e))throw Error("hands_browser_driver_path_must_be_absolute");let _=Ya(e,"package.json"),w=JSON.parse(Ja(_,"utf8"));if(w.name!==Mn.driver)throw Error("hands_browser_wrong_driver");let S=qa(_)(e),I=S.default?.chromium??S.chromium;if(!I)throw Error("hands_browser_missing_chromium");return{version:w.version,chromium:I}}let[l,f]=await Promise.all([import("./index-w9sxzata.js"),import("./package-yy8qcwwn.js").then((m)=>Li(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var ec=(e,l=Mn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),rc=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function jt(e={}){return Os(e,Mn.driverVersion)}async function zn(e,l={}){if(e.driverVersion!=="1.61.1"||!jn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return Os({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function Os(e,l){let f=(x)=>ec(x,l),_=e.platform??process.platform;if(_!=="linux"&&_!=="darwin"&&_!=="win32")return f("unsupported_platform");let w;try{w=await rc(e)}catch{return f("driver_missing")}if(w.version!==l)return f("driver_version_mismatch");let S=(x,M)=>({status:"resolved",executablePath:x,source:M,driverVersion:w.version});if(e.executablePath!==void 0)return Bt(e.executablePath)?S(e.executablePath,"configured"):f("executable_missing");let I=w.chromium.executablePath();if(Bt(I))return S(I,"managed");let W=e.allowSystemBrowser===!0?Un(e.systemCandidates,_):null;return W?S(W,"system"):f("executable_missing")}var _c=["/usr/local/bin/chromium",...Fn];function yn(e,l=Ds()){return Un(e??(l==="linux"?_c:void 0),l)}async function mc(){try{return(await en()).chromium}catch{return dc(import.meta.url)("playwright-core").chromium}}var hc=1048576,gc=105000,bc=20000,Is=5000,wc=2000,yc=1000,vc=30000,As=81920,kc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Sc(e,l){let f=new URL(e.url()),_={...await e.allHeaders(),host:f.host};for(let w of Object.keys(_))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(w))delete _[w];return new Promise((w,S)=>{let W=(f.protocol==="https:"?uc:lc)(f,{method:e.method(),headers:_,agent:!1,lookup:(M,G,F)=>{let T=it.isIP(l);if(G.all)F(null,[{address:l,family:T}]);else F(null,l,T)}},(M)=>{let G=[],F=0;M.on("data",(T)=>{if(F+=T.length,F>33554432)W.destroy(Error("hands_browser_response_too_large"));else G.push(T)}),M.on("error",S),M.on("end",()=>{let T={};for(let[re,J]of Object.entries(M.headers))if(J!==void 0&&!["transfer-encoding","connection","content-length"].includes(re))T[re]=Array.isArray(J)?J.join(`
|
|
300
|
-
`):J;w({status:M.statusCode??502,headers:T,body:Buffer.concat(G)})})}),x=setTimeout(()=>W.destroy(Error("hands_browser_fetch_timeout")),vc);W.once("close",()=>clearTimeout(x)),W.on("error",S),W.end(e.postDataBuffer()??void 0)})}async function Ec(e,l,f=()=>{},_={lookup:(w)=>cc(w,{all:!0}),fetch:Sc}){let w=new WeakSet,S=new WeakMap,I=(W)=>{let x=S.get(W);if(x)return x;let M=(async()=>{if(!e.newCDPSession)return;let G=await e.newCDPSession(W),F=new Map;G.on("Network.loadingFinished",({requestId:T})=>F.delete(T)),G.on("Network.loadingFailed",({requestId:T})=>F.delete(T)),G.on("Fetch.requestPaused",async(T)=>{let re=T.networkId??T.requestId,J=T.redirectedRequestId?(F.get(re)??0)+1:0;F.set(re,J);let z=Ue(T.request.url,l),fe=l.mode==="enforce"&&Boolean(T.redirectedRequestId)&&z.host!==null&&!it.isIP(z.host),ve=!z.allowed?z:fe?{...z,allowed:!1,reason:"destination_not_allowed"}:J>20?{...z,allowed:!1,reason:"redirect_not_supported"}:null;try{if(ve)f(ve),await G.send("Fetch.failRequest",{requestId:T.requestId,errorReason:"BlockedByClient"});else await G.send("Fetch.continueRequest",{requestId:T.requestId})}catch{await G.send("Fetch.failRequest",{requestId:T.requestId,errorReason:"Failed"}).catch(()=>{})}}),await G.send("Network.enable"),await G.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),w.add(W)})();return S.set(W,M),M};return await e.route("**/*",async(W)=>{let x=W.request().url(),M=Ue(x,l);if(M.allowed&&l.mode==="public_web"){await W.continue();return}let G=W.request();if(M.allowed&&M.host&&it.isIP(M.host)&&G.isNavigationRequest?.()){let F=G.frame();if(w.has(F.page())&&F===F.page().mainFrame()){await W.continue();return}}if(M.allowed&&(l.mode==="off"||M.reason==="local_document")){await W.continue();return}if(M.allowed&&M.host)try{let F=M.host,T=nt(F),re,J=await(async()=>{if(T!=="hostname")return[{address:F,family:it.isIP(F)}];if(M.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([_.lookup(F),new Promise((z,fe)=>{re=setTimeout(()=>fe(Error("hands_browser_dns_timeout")),5000)})])}finally{if(re)clearTimeout(re)}})();if(!J.length||J.some(({address:z})=>{let fe=nt(z);return!it.isIP(z)||l.mode==="enforce"&&Bn(z,l.deniedHosts)||(M.reason==="loopback"?fe!=="loopback":fe!=="public")}))M={...M,allowed:!1,reason:"private_network"};else{let z=await _.fetch(W.request(),J[0].address);if(z.status>=300&&z.status<400){let fe=z.headers.location??x;try{fe=new URL(fe,x).href}catch{}let ve=Ue(fe,l);M=ve.allowed?{...ve,allowed:!1,reason:"redirect_not_supported"}:ve}else{await W.fulfill(z);return}}}catch{await W.abort("failed");return}f(M),await W.abort("blockedbyclient")}),await e.routeWebSocket("**/*",async(W)=>{let x=Ue(W.url(),l);if(l.mode==="enforce"&&x.allowed&&(!x.host||!it.isIP(x.host)))x={...x,allowed:!1,reason:"destination_not_allowed"};if(x.allowed){W.connectToServer();return}f(x),await W.close({code:1008,reason:"Reason egress policy denied"})}),l.mode==="off"?void 0:{preparePage:I}}async function Cs(e,l=Ds(),f){if(f){let w=await
|
|
301
|
-
`)}function rn(e){try{ac(e)}catch{}}async function Hs(e){if(e.managedBrowser&&e.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let l=e.launch||e.targetContext?null:e.managedBrowser?await
|
|
299
|
+
`.trim();import{Buffer as bt}from"buffer";import{randomUUID as Ra}from"crypto";class _s extends Error{code;constructor(e){super(e==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":e);this.code=e;this.name="HandsReplBrowserDispatcherError"}}var ms=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),us=/^hands_[A-Za-z0-9_-]{8,128}$/,Oa=2048,hs=32,gs=1e4,xa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function Pa(e){let l=e.split("+"),f=(l.pop()??"").replace(/^Key/,"").toLowerCase();if(f==="f12")return!0;if(l.some((_)=>["Control","ControlOrMeta","Meta"].includes(_))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(f))return!0;if(l.some((_)=>["Control","ControlOrMeta","Meta"].includes(_))&&l.includes("Shift")&&f==="c")return!0;return l.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(f)}var Ia=(e)=>{let l=e.closest("a[href],area[href]");return{password:e.tagName==="INPUT"&&e.type==="password",executableLink:Boolean(l&&!/^(https?:|about:blank)/i.test(l.href))}},bs={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 Ie(e){throw new _s(e)}function Dr(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let l=Object.getPrototypeOf(e);return l===Object.prototype||l===null}function wt(e,l=0,f={nodes:0}){if(l>hs||++f.nodes>gs)Ie("hands_repl_json_too_complex");if(e===null||typeof e==="boolean"||typeof e==="string")return;if(typeof e==="number"){if(!Number.isFinite(e))Ie("hands_repl_invalid_json");return}if(Array.isArray(e)){for(let _ of e)wt(_,l+1,f);return}if(!Dr(e))Ie("hands_repl_invalid_json");for(let[_,w]of Object.entries(e)){if(ms.has(_))Ie("hands_repl_invalid_json");wt(w,l+1,f)}}function Hn(e){return typeof e==="string"&&Object.hasOwn(bs,e)}function Aa(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Hn(l)?l:null}function fs(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Ta(e){return Dr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function ps(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function Vr(e){return!!e&&typeof e==="object"}function qt(){return Object.freeze({$handsRepl:"undefined"})}function Da(e){if(!bt.isBuffer(e)&&!(e instanceof Uint8Array))Ie("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:bt.from(e).toString("base64")})}function ws(e){if(!Vr(e.browser)||!Vr(e.context)||!Vr(e.page))Ie("hands_repl_invalid_roots");if(typeof e.a11y!=="function"||typeof e.view!=="function")Ie("hands_repl_invalid_callbacks");let l=e.maxHandles??Oa;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,_=new WeakMap,w=e.createOpaqueId??Ra,S=(T,re)=>{if(!Vr(re))Ie("hands_repl_expected_target");let J=_.get(re)?.get(T);if(J)return J;if(f.size>=l)Ie("hands_repl_handle_limit");let z="";for(let be=0;be<16;be+=1){let Oe=`hands_${w()}`;if(us.test(Oe)&&!f.has(Oe)){z=Oe;break}}if(!z)Ie("hands_repl_invalid_opaque_id");let fe=Object.freeze({$handsRepl:"handle",id:z,kind:T});f.set(z,{kind:T,target:re});let ve=_.get(re);if(!ve)ve=new Map,_.set(re,ve);return ve.set(T,fe),fe},I=Object.freeze({browser:S("browser",e.browser),context:S("context",e.context),page:S("page",e.page)}),W=(T)=>{if(!Dr(T)||Object.keys(T).length!==3||T.$handsRepl!=="handle"||typeof T.id!=="string"||!us.test(T.id)||!Hn(T.kind))Ie("hands_repl_invalid_handle");let re=f.get(T.id);if(!re||re.kind!==T.kind)Ie("hands_repl_unknown_handle");return re},x=(T,re=0,J=new Set)=>{if(re>hs)Ie("hands_repl_json_too_complex");if(T===void 0)return qt();if(T===null||typeof T==="boolean"||typeof T==="string")return T;if(typeof T==="number"){if(!Number.isFinite(T))Ie("hands_repl_non_json_result");return T}if(Array.isArray(T)){if(J.has(T))Ie("hands_repl_cyclic_result");J.add(T);try{return T.map((z)=>x(z,re+1,J))}finally{J.delete(T)}}if(!Dr(T))Ie("hands_repl_non_json_result");if(J.has(T))Ie("hands_repl_cyclic_result");J.add(T);try{let z=Object.create(null);for(let fe of Object.keys(T)){let ve=Object.getOwnPropertyDescriptor(T,fe);if(!ve||!("value"in ve))continue;z[fe]=x(ve.value,re+1,J)}return z}finally{J.delete(T)}},M=(T,re)=>{if(re==="void")return qt();if(re==="json")return x(T);if(re==="bytes")return Da(T);let J=Aa(re);if(J){if(!Array.isArray(T))Ie("hands_repl_expected_target_list");if(J==="context"&&T.some((z)=>z!==e.context))Ie("hands_repl_foreign_context");return T.map((z)=>S(J,z))}if(T===null||T===void 0)return qt();if(!Hn(re))Ie("hands_repl_invalid_return_kind");if(re==="context"&&T!==e.context)Ie("hands_repl_foreign_context");return S(re,T)},G=(T)=>{if(Dr(T)&&T.$handsRepl==="handle")return W(T).target;if(fs(T))return bt.from(T.base64,"base64");if(Ta(T))return;if(ps(T))Ie("hands_repl_route_fulfill_only");if(Array.isArray(T))return T.map(G);if(!Dr(T))return T;let re=Object.create(null);for(let[J,z]of Object.entries(T))re[J]=G(z);return re};return Object.freeze({roots:I,dispatch:async(T)=>{if(!Dr(T)||typeof T.type!=="string")Ie("hands_repl_invalid_request");if(T.type==="a11y"){let ye=T.target===void 0?f.get(I.page.id):W(T.target);if(!ye||ye.kind!=="page"&&ye.kind!=="locator")Ie("hands_repl_invalid_a11y_target");return x(await e.a11y(ye.target))}if(T.type==="view"){if(wt(T.source),T.options!==void 0)wt(T.options);let ye=fs(T.source)?bt.from(T.source.base64,"base64"):T.source;if(e.privateProfile&&!bt.isBuffer(ye))Ie("hands_repl_profile_requires_image_bytes");return x(await e.view(ye,T.options))}if(T.type!=="call")Ie("hands_repl_invalid_request");if(typeof T.method!=="string"||T.method.length===0||T.method.length>128)Ie("hands_repl_invalid_method");if(ms.has(T.method))Ie("hands_repl_forbidden_method");let re=W(T.target),J=T.args??[];if(!Array.isArray(J))Ie("hands_repl_invalid_arguments");if(wt(J),re.kind==="page"&&T.method==="captureScreenshot"){if(J.length!==0)Ie("hands_repl_invalid_arguments");if(!e.screenshotExport)Ie("hands_repl_screenshot_export_unavailable");return x(await e.screenshotExport(re.target))}if(re.kind==="context"&&["startRecording","stopRecording"].includes(T.method)){if(!e.recording||re.target!==e.context)Ie("hands_repl_recording_unavailable");if(J.length>(T.method==="startRecording"?1:0))Ie("hands_repl_invalid_arguments");return x(T.method==="startRecording"?await e.recording.start(J[0]):await e.recording.stop())}if(e.privateProfile){let ye=T.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(ye)||re.kind==="browser"&&ye==="close"||re.kind==="context"&&ye==="close")Ie("hands_repl_private_profile_method_denied");if(re.kind==="browser"&&ye==="contexts")return M([e.context],"context[]");if((ye==="screenshot"||ye==="pdf")&&Dr(J[0])&&(("path"in J[0])||("style"in J[0])))Ie("hands_repl_private_profile_path_denied");if(ye==="goto"){if(typeof J[0]!=="string")Ie("hands_repl_private_profile_url_denied");try{let Fe=new URL(J[0]);if(!["http:","https:"].includes(Fe.protocol)&&J[0]!=="about:blank")Ie("hands_repl_private_profile_url_denied")}catch{Ie("hands_repl_private_profile_url_denied")}}if(ye==="getAttribute"&&(typeof J[0]!=="string"||!xa.has(J[0].toLowerCase())))Ie("hands_repl_private_profile_attribute_denied");if(re.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(ye)){let Fe=[re.target];if(ye==="allInnerTexts"){let Ve=Reflect.get(re.target,"all");if(typeof Ve!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Te=await Reflect.apply(Ve,re.target,[]);if(!Array.isArray(Te)||Te.length>gs||!Te.every(Vr))Ie("hands_repl_private_profile_probe_unavailable");Fe=Te}for(let Ve of Fe){let Te=Reflect.get(Ve,"isVisible");if(typeof Te!=="function"||!await Reflect.apply(Te,Ve,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}if(ye==="press"&&typeof J[0]==="string"&&Pa(J[0]))Ie("hands_repl_private_profile_browser_shortcut_denied");if(re.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(ye)){let Fe=Reflect.get(re.target,"evaluate");if(typeof Fe!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Ve=await Reflect.apply(Fe,re.target,[Ia]);if(!Dr(Ve)||typeof Ve.password!=="boolean"||typeof Ve.executableLink!=="boolean")Ie("hands_repl_private_profile_probe_unavailable");if(ye==="inputValue"&&Ve.password)Ie("hands_repl_private_profile_password_denied");if(ye!=="inputValue"&&Ve.executableLink)Ie("hands_repl_private_profile_url_denied");if(ye==="inputValue"){let Te=Reflect.get(re.target,"isVisible");if(typeof Te!=="function"||!await Reflect.apply(Te,re.target,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}}let z=bs[re.kind][T.method];if(!z)Ie("hands_repl_method_not_allowed");if(z.requiresStringSource&&typeof J[0]!=="string")Ie("hands_repl_string_source_required");if(re.kind==="browser"&&T.method==="contexts")return[I.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(T.method)&&J.some((ye)=>Dr(ye)&&("path"in ye)))Ie("hands_repl_file_path_not_allowed");if(T.method==="goto"&&typeof J[0]==="string"){let ye;try{ye=new URL(J[0]).protocol}catch{Ie("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(ye))Ie("hands_repl_file_path_not_allowed")}if(z.special==="contextViewportSize"){let ye=Reflect.get(re.target,"pages");if(typeof ye!=="function")Ie("hands_repl_method_unavailable");let Fe=await Reflect.apply(ye,re.target,[]),Ve=Array.isArray(Fe)?Fe[0]:void 0,Te=Vr(Ve)?Reflect.get(Ve,"viewportSize"):void 0;if(typeof Te!=="function")return qt();return M(await Reflect.apply(Te,Ve,[]),z.returns)}if(z.special==="property"){let ye=Reflect.get(re.target,T.method);return M(typeof ye==="function"?Reflect.apply(ye,re.target,[]):ye,z.returns)}let fe=Reflect.get(re.target,T.method);if(typeof fe!=="function")Ie("hands_repl_method_unavailable");if(z.special==="route"){let ye=J[1];if(!ps(ye))Ie("hands_repl_invalid_route_handler");wt(ye.options);let Fe=G(ye.options),Ve=async(he)=>{if(!Vr(he))Ie("hands_repl_invalid_route");let xe=Reflect.get(he,"fulfill");if(typeof xe!=="function")Ie("hands_repl_invalid_route");await Reflect.apply(xe,he,[Fe])},Te=[G(J[0]??null),Ve],le=await Reflect.apply(fe,re.target,Te);return M(le,z.returns)}let ve=J.map(G);if(T.method==="setInputFiles"){let ye=re.kind==="locator"?0:1,Fe=async(Te)=>{if(typeof Te!=="string"){if(!Dr(Te)||typeof Te.name!=="string"||typeof Te.mimeType!=="string"||!bt.isBuffer(Te.buffer))Ie("hands_repl_invalid_file_input");return Te}if(!e.readWorkspaceFile)Ie("hands_repl_workspace_required");return e.readWorkspaceFile(Te)},Ve=ve[ye];ve[ye]=Array.isArray(Ve)?await Promise.all(Ve.map(Fe)):await Fe(Ve)}if(T.method==="goto")await e.beforeNavigation?.();let be=e.actionRecorder?.(),Oe=await Reflect.apply(fe,re.target,ve),qe={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"}[T.method];if(qe){let ye=Reflect.get(re.target,"page"),Fe=re.kind==="page"?re.target:typeof ye==="function"?Reflect.apply(ye,re.target,[]):void 0;be?.(qe,Vr(Fe)?Fe:void 0)}return M(Oe,z.returns)}})}import{isIP as Ss}from"net";import{Resolver as Ca}from"dns/promises";import{isIP as Zt}from"net";var Ha=[["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 Nn(e){if(Zt(e)!==4)return null;let l=e.split(".");if(l.length!==4)return null;let f=0;for(let _ of l){let w=Number(_);if(!Number.isInteger(w)||w<0||w>255)return null;f=f*256+w}return f>>>0}function Na(e,l,f){let _=Nn(l);if(_===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(_&w)>>>0}function ys(e){let l=Nn(e);if(l===null)return!0;return Ha.some(([f,_])=>Na(l,f,_))}function La(e){if(Zt(e)!==6)return null;let l=e.toLowerCase(),f=l.indexOf("%");if(f>=0)l=l.slice(0,f);let _=[],w=l.lastIndexOf(":"),S=w>=0?l.slice(w+1):"";if(S.includes(".")){let T=Nn(S);if(T===null)return null;_=[T>>>16&65535,T&65535],l=l.slice(0,w+1)+"0:0"}let I=l.split("::");if(I.length>2)return null;let W=(T)=>{if(T==="")return[];let re=[];for(let J of T.split(":")){if(J===""||J.length>4||!/^[0-9a-f]+$/.test(J))return null;re.push(Number.parseInt(J,16))}return re},x=W(I[0]??"");if(x===null)return null;if(I.length===1){let T=x;if(T.length!==8)return null;return _.length>0?T.slice(0,6).concat(_):T}let M=W(I[1]??"");if(M===null)return null;let G=8-x.length-M.length;if(G<0)return null;let F=x.concat(Array(G).fill(0),M);if(F.length!==8)return null;return _.length>0?F.slice(0,6).concat(_):F}function Ba(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function ja(e){let l=La(e);if(l===null)return!0;let[f,_,w]=l;if((f&57344)!==8192)return!0;if(f===8193&&(_&65024)===0)return!0;if(f===8193&&_===3512)return!0;if(f===16383&&(_&61440)===0)return!0;if(f===8194)return ys(Ba(_,w));return!1}function yr(e){return e.replace(/^\[|\]$/g,"")}function Yt(e){let l=yr(e.trim()),f=Zt(l);if(f===4)return ys(l);if(f===6)return ja(l);return!0}function vs(e){if(e instanceof Error&&e.name==="TimeoutError")return"dns_timeout";switch(typeof e==="object"&&e!==null&&"code"in e?e.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 ks=5000;function Ma(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let _=new Ca({timeout:ks,tries:1});if(e)_.setServers(e);let w=()=>_.cancel();f?.addEventListener("abort",w,{once:!0});try{let[S,I]=await Promise.allSettled([_.resolve4(l),_.resolve6(l)]),W=[...S.status==="fulfilled"?S.value:[],...I.status==="fulfilled"?I.value:[]];if(W.length>0)return W;let x=[S,I].flatMap((G)=>G.status==="rejected"?[G.reason]:[]);throw x.find((G)=>["dns_temporary","dns_timeout"].includes(vs(G)))??x[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var Wa=Ma();async function Fa(e,l,f,_){if(_?.aborted)throw Error("aborted");let w=new AbortController,S,I,W=l(e,w.signal);W.catch(()=>{});try{return await Promise.race([W,new Promise((x,M)=>{if(S=setTimeout(()=>M(new DOMException("DNS lookup timed out","TimeoutError")),f),_)I=()=>M(Error("aborted")),_.addEventListener("abort",I,{once:!0})})])}finally{if(S!==void 0)clearTimeout(S);if(_&&I)_.removeEventListener("abort",I);w.abort()}}async function io(e,l=Wa,f){let _=yr(e);if(Zt(_))return Yt(_)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[_]};let w;try{w=await Fa(_,l,ks,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":vs(S)}}if(w.length===0)return{ok:!1,reason:"dns_empty"};if(w.some(Yt))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:w}}var Ua=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Ln(e){return e.length<=253&&Ua.test(e.toLowerCase())}function za(e,l){let f=e.trim().toLowerCase();if(!Ln(f))return!1;if(f.startsWith("*.")){let _=f.slice(2);return l===_||l.endsWith(`.${_}`)}return f===l}function $a(e){let l=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!l)return null;let f=l.slice(1).map(Number);return f.some((_)=>_>255)?null:f}function Bn(e,l=[]){let f=(_)=>{if(_=_.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!_.includes(":"))return _;try{_=new URL(`http://[${_}]/`).hostname.slice(1,-1)}catch{return _}let w=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(_);if(!w)return _;let S=parseInt(w[1],16),I=parseInt(w[2],16);return`${S>>8}.${S&255}.${I>>8}.${I&255}`};return l.some((_)=>f(_)===f(e))}function nt(e){e=e.toLowerCase().replace(/^\[|\]$/g,"");let l=$a(e);if(l){let[S,I,W]=l;if(S===127)return"loopback";return S===0||S===10||S>=224||S===100&&I>=64&&I<=127||S===169&&I===254||S===172&&I>=16&&I<=31||S===192&&(I===168||I===0&&(W===0||W===2)||I===88&&W===99)||S===198&&(I===18||I===19||I===51&&W===100)||S===203&&I===0&&W===113?"private":"public"}if(!e.includes(":"))return"hostname";try{e=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return"private"}if(e==="::1")return"loopback";let f=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(e);if(f){let S=parseInt(f[1],16),I=parseInt(f[2],16);return nt(`${S>>8}.${S&255}.${I>>8}.${I&255}`)==="public"?"public":"private"}let[_,w=0]=e.split(":").map((S)=>parseInt(S||"0",16));return _<8192||_>16383||_===8194||_===8193&&(w<512||w===3512)||_===16383&&w<4096?"private":"public"}function Ue(e,l){let f;try{f=new URL(e)}catch{return{allowed:!1,url:e,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(f.protocol))return{allowed:!0,url:e,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(f.protocol))return{allowed:!1,url:e,host:f.hostname||null,reason:"unsupported_protocol"};let _=f.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(l.mode==="off")return{allowed:!0,url:e,host:_,reason:"policy_off"};let w=(W)=>({allowed:!1,url:e,host:_,reason:W});if(f.username||f.password)return w("invalid_url");if(l.mode==="public_web"){let W=nt(_)!=="public"&&nt(_)!=="hostname"||_==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(_)||!_.includes(".")&&!Ss(_)||Boolean(Ss(_)&&Yt(_));return{allowed:!W,url:e,host:_,reason:W?"private_network":"public_web"}}let S=Number(f.port||(["https:","wss:"].includes(f.protocol)?443:80));if(l.deniedPorts?.includes(S)||Bn(_,l.deniedHosts))return w("destination_not_allowed");let I=nt(_);if(I==="private"||["local","internal","arpa"].some((W)=>_===W||_.endsWith(`.${W}`)))return w("private_network");if(I==="loopback"||_==="localhost"||_.endsWith(".localhost"))return l.allowedLoopbackPorts?.includes(S)?{allowed:!0,url:e,host:_,reason:"loopback"}:w("destination_not_allowed");if(l.allowedDomains.some((W)=>za(W,_)))return{allowed:!0,url:e,host:_,reason:"allowed_domain"};return{allowed:!1,url:e,host:_,reason:"destination_not_allowed"}}import Es from"child_process";import{accessSync as Ka,constants as Ga,readFileSync as Ja,statSync as Va}from"fs";import{createRequire as qa}from"module";import{dirname as _f,isAbsolute as jn,join as Ya,resolve as mf,win32 as Xa}from"path";var Mn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:Qt.dependencies["playwright-core"],browser:"chromium"}),Rs=["/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"],Wn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function Za(e=process.env){let l=[e.ProgramFiles??"C:\\Program Files",e["ProgramFiles(x86)"]??"C:\\Program Files (x86)"],f=e.LOCALAPPDATA?[e.LOCALAPPDATA]:[],_=(w,...S)=>w.map((I)=>Xa.join(I,...S));return[..._([...l,...f],"Google","Chrome","Application","chrome.exe"),..._(l,"Microsoft","Edge","Application","msedge.exe"),..._([...l,...f],"BraveSoftware","Brave-Browser","Application","brave.exe")]}function Bt(e){try{return Ka(e,Ga.X_OK),jn(e)&&Va(e).isFile()}catch{return!1}}function Fn(e,l=process.platform){let f=l==="darwin"?Rs:l==="linux"?Wn:l==="win32"?Za():null;return f?(e??f).find(Bt)??null:null}function Qa(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];Es.spawn=new Proxy(Es.spawn,{apply(f,_,w){let S=Reflect.apply(f,_,w),I=w[1],W=w[2]?.stdio;if(Array.isArray(I)&&I.includes("--remote-debugging-pipe")&&Array.isArray(W)&&W[3]==="pipe"&&W[4]==="pipe")l.push(S);return S}}),Object.defineProperty(globalThis,e,{value:l})}async function en(e){if(Qa(),e!==void 0){if(!jn(e))throw Error("hands_browser_driver_path_must_be_absolute");let _=Ya(e,"package.json"),w=JSON.parse(Ja(_,"utf8"));if(w.name!==Mn.driver)throw Error("hands_browser_wrong_driver");let S=qa(_)(e),I=S.default?.chromium??S.chromium;if(!I)throw Error("hands_browser_missing_chromium");return{version:w.version,chromium:I}}let[l,f]=await Promise.all([import("./index-ttmxy9nd.js"),import("./package-r7sgmw4t.js").then((m)=>Li(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var ec=(e,l=Mn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),rc=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function jt(e={}){return Os(e,Mn.driverVersion)}async function Un(e,l={}){if(e.driverVersion!=="1.61.1"||!jn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return Os({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function Os(e,l){let f=(x)=>ec(x,l),_=e.platform??process.platform;if(_!=="linux"&&_!=="darwin"&&_!=="win32")return f("unsupported_platform");let w;try{w=await rc(e)}catch{return f("driver_missing")}if(w.version!==l)return f("driver_version_mismatch");let S=(x,M)=>({status:"resolved",executablePath:x,source:M,driverVersion:w.version});if(e.executablePath!==void 0)return Bt(e.executablePath)?S(e.executablePath,"configured"):f("executable_missing");let I=w.chromium.executablePath();if(Bt(I))return S(I,"managed");let W=e.allowSystemBrowser===!0?Fn(e.systemCandidates,_):null;return W?S(W,"system"):f("executable_missing")}var _c=["/usr/local/bin/chromium",...Wn];function yn(e,l=Ds()){return Fn(e??(l==="linux"?_c:void 0),l)}async function mc(){try{return(await en()).chromium}catch{return dc(import.meta.url)("playwright-core").chromium}}var hc=1048576,gc=105000,bc=20000,Is=5000,wc=2000,yc=1000,vc=30000,As=81920,kc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Sc(e,l){let f=new URL(e.url()),_={...await e.allHeaders(),host:f.host};for(let w of Object.keys(_))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(w))delete _[w];return new Promise((w,S)=>{let W=(f.protocol==="https:"?uc:lc)(f,{method:e.method(),headers:_,agent:!1,lookup:(M,G,F)=>{let T=it.isIP(l);if(G.all)F(null,[{address:l,family:T}]);else F(null,l,T)}},(M)=>{let G=[],F=0;M.on("data",(T)=>{if(F+=T.length,F>33554432)W.destroy(Error("hands_browser_response_too_large"));else G.push(T)}),M.on("error",S),M.on("end",()=>{let T={};for(let[re,J]of Object.entries(M.headers))if(J!==void 0&&!["transfer-encoding","connection","content-length"].includes(re))T[re]=Array.isArray(J)?J.join(`
|
|
300
|
+
`):J;w({status:M.statusCode??502,headers:T,body:Buffer.concat(G)})})}),x=setTimeout(()=>W.destroy(Error("hands_browser_fetch_timeout")),vc);W.once("close",()=>clearTimeout(x)),W.on("error",S),W.end(e.postDataBuffer()??void 0)})}async function Ec(e,l,f=()=>{},_={lookup:(w)=>cc(w,{all:!0}),fetch:Sc}){let w=new WeakSet,S=new WeakMap,I=(W)=>{let x=S.get(W);if(x)return x;let M=(async()=>{if(!e.newCDPSession)return;let G=await e.newCDPSession(W),F=new Map;G.on("Network.loadingFinished",({requestId:T})=>F.delete(T)),G.on("Network.loadingFailed",({requestId:T})=>F.delete(T)),G.on("Fetch.requestPaused",async(T)=>{let re=T.networkId??T.requestId,J=T.redirectedRequestId?(F.get(re)??0)+1:0;F.set(re,J);let z=Ue(T.request.url,l),fe=l.mode==="enforce"&&Boolean(T.redirectedRequestId)&&z.host!==null&&!it.isIP(z.host),ve=!z.allowed?z:fe?{...z,allowed:!1,reason:"destination_not_allowed"}:J>20?{...z,allowed:!1,reason:"redirect_not_supported"}:null;try{if(ve)f(ve),await G.send("Fetch.failRequest",{requestId:T.requestId,errorReason:"BlockedByClient"});else await G.send("Fetch.continueRequest",{requestId:T.requestId})}catch{await G.send("Fetch.failRequest",{requestId:T.requestId,errorReason:"Failed"}).catch(()=>{})}}),await G.send("Network.enable"),await G.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),w.add(W)})();return S.set(W,M),M};return await e.route("**/*",async(W)=>{let x=W.request().url(),M=Ue(x,l);if(M.allowed&&l.mode==="public_web"){await W.continue();return}let G=W.request();if(M.allowed&&M.host&&it.isIP(M.host)&&G.isNavigationRequest?.()){let F=G.frame();if(w.has(F.page())&&F===F.page().mainFrame()){await W.continue();return}}if(M.allowed&&(l.mode==="off"||M.reason==="local_document")){await W.continue();return}if(M.allowed&&M.host)try{let F=M.host,T=nt(F),re,J=await(async()=>{if(T!=="hostname")return[{address:F,family:it.isIP(F)}];if(M.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([_.lookup(F),new Promise((z,fe)=>{re=setTimeout(()=>fe(Error("hands_browser_dns_timeout")),5000)})])}finally{if(re)clearTimeout(re)}})();if(!J.length||J.some(({address:z})=>{let fe=nt(z);return!it.isIP(z)||l.mode==="enforce"&&Bn(z,l.deniedHosts)||(M.reason==="loopback"?fe!=="loopback":fe!=="public")}))M={...M,allowed:!1,reason:"private_network"};else{let z=await _.fetch(W.request(),J[0].address);if(z.status>=300&&z.status<400){let fe=z.headers.location??x;try{fe=new URL(fe,x).href}catch{}let ve=Ue(fe,l);M=ve.allowed?{...ve,allowed:!1,reason:"redirect_not_supported"}:ve}else{await W.fulfill(z);return}}}catch{await W.abort("failed");return}f(M),await W.abort("blockedbyclient")}),await e.routeWebSocket("**/*",async(W)=>{let x=Ue(W.url(),l);if(l.mode==="enforce"&&x.allowed&&(!x.host||!it.isIP(x.host)))x={...x,allowed:!1,reason:"destination_not_allowed"};if(x.allowed){W.connectToServer();return}f(x),await W.close({code:1008,reason:"Reason egress policy denied"})}),l.mode==="off"?void 0:{preparePage:I}}async function Cs(e,l=Ds(),f){if(f){let w=await Un(f,{platform:l,systemCandidates:e});return w.status==="resolved"?w.executablePath:null}if(e!==void 0){let w=yn(e,l);if(w)return w}let _=await jt({platform:l,systemCandidates:e,allowSystemBrowser:!0});return _.status==="resolved"?_.executablePath:null}function Ts(e,l){if(!e)throw Error("hands_repl_workspace_required");let f=$n(e),_=yt(e),w=Gn(_,yt(_,l)),I=w!==".."&&!w.startsWith(`..${Jn}`)&&!Ps(w)?yt(f,w):yt(f,l);if(E(yt(_,l))||E(I))throw Error("hands_repl_protected_path");let W=(J)=>{let z=Gn(f,J);return z!==""&&z!==".."&&!z.startsWith(`..${Jn}`)&&!Ps(z)},x=$n(I);if(E(x))throw Error("hands_repl_protected_path");if(!W(I)||!W(x))throw Error("hands_repl_file_outside_workspace");let M=Gn(f,I).split(Jn),G=[f,...M.map((J,z)=>yt(f,...M.slice(0,z+1)))],F=G.map((J)=>xs(J));if(F.some((J)=>J.isSymbolicLink()))throw Error("hands_repl_file_symlink");let T=F[F.length-1];if(!T.isFile()||T.nlink!==1||T.size>16777216)throw Error("hands_repl_file_not_regular_or_too_large");let re=sc(I,zn.O_RDONLY|zn.O_NOFOLLOW|zn.O_NONBLOCK);try{let J=oc(re);if(J.dev!==T.dev||J.ino!==T.ino||!J.isFile())throw Error("hands_repl_file_changed");for(let be=0;be<G.length;be++){let Oe=xs(G[be]);if(Oe.dev!==F[be].dev||Oe.ino!==F[be].ino||Oe.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!W($n(I)))throw Error("hands_repl_file_outside_workspace");let z=Buffer.alloc(16777217),fe=0;while(fe<z.length){let be=ic(re,z,fe,z.length-fe,null);if(!be)break;fe+=be}if(fe===z.length)throw Error("hands_repl_file_too_large");let ve=z.subarray(0,fe);return{name:fc(I),mimeType:kc[pc(I).toLowerCase()]??"application/octet-stream",buffer:ve}}finally{nc(re)}}function vt(e,l){e.end(`${JSON.stringify(l)}
|
|
301
|
+
`)}function rn(e){try{ac(e)}catch{}}async function Hs(e){if(e.managedBrowser&&e.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let l=e.launch||e.targetContext?null:e.managedBrowser?await Un(e.managedBrowser,{executablePath:e.browserExecutablePath}):await jt({executablePath:e.browserExecutablePath,driverModuleDirectory:e.driverModuleDirectory});if(l?.status==="unavailable")throw Error(`hands_browser_${l.reason}`);let f=l?.status==="resolved"?l.executablePath:e.browserExecutablePath;if(!f||!Bt(f))throw Error("hands_browser_unavailable");let _=e.launch??(async(le)=>(e.targetContext?await mc():(await en(e.managedBrowser?.driverModuleDirectory??e.driverModuleDirectory)).chromium).launch(le)),w=[],S={},I=null,W=null,x=null,M=null,G=!1,F=null,T=new Map,re=new WeakMap,J=null,z=()=>{if(G)throw Error("hands_repl_stopped");if(M)throw M},fe=(le)=>{let he=re.get(le);if(he)return he;let xe=Promise.resolve().then(()=>le.close()).then(()=>{T.delete(le)});return re.set(le,xe),xe},ve=async()=>{let le=[...T.entries()].reverse(),he=J??=performance.now()+yc,xe=Promise.allSettled(le.filter(([,ke])=>ke==="context").map(([ke])=>fe(ke))),Ke;try{await Promise.race([xe,new Promise((ke)=>{Ke=setTimeout(ke,Math.max(0,he-performance.now()))})])}finally{if(Ke)clearTimeout(Ke)}let Le=await Promise.allSettled(le.map(([ke])=>fe(ke))),Be=[];for(let[ke,We]of Le.entries()){if(We.status!=="rejected")continue;let tr=We.reason instanceof Error&&["Error","TimeoutError","ProtocolError"].includes(We.reason.name)?We.reason.name:"unknown";Be.push(Error(`hands_repl_close_failed: ${le[ke][1]}: ${tr}`))}if(Be.length)throw AggregateError(Be,"hands_repl_stop_unconfirmed")},be=(le,he)=>{if(T.set(le,he),G||M)fe(le).catch(()=>{return}),z();return le},Oe=async()=>{let le=await _({executablePath:f,headless:!0,chromiumSandbox:e.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"]}),he=null;try{be(le,"browser"),he=e.targetContext??be(await le.newContext({viewport:{width:1440,height:900},screen:{width:1440,height:900},serviceWorkers:"block",acceptDownloads:!1}),"context");let xe=await Ec(he,e.networkPolicy??{mode:"off"},e.onEgressDenied);if(z(),xe){let Ge=he.newPage.bind(he);he.newPage=async()=>{let or=await Ge();return await xe.preparePage(or),or}}let Le=he.pages()[0]??await he.newPage();await xe?.preparePage(Le),z();let Be=async(Ge=Le)=>{let or=Ge;if(typeof or.ariaSnapshot==="function")return or.ariaSnapshot({timeout:1e4});return Le.locator("body").innerText({timeout:1e4})},ke=async(Ge,or={})=>{let sr=or&&typeof or==="object"&&!Array.isArray(or)?or:{},dr,Wr="image/png";if(Buffer.isBuffer(Ge)||Ge instanceof Uint8Array)dr=Buffer.from(Ge);else if(typeof Ge==="string"&&(Ge.startsWith("data:")||/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Ge)))dr=Buffer.from(Ge.replace(/^data:[^,]*,/,""),"base64");else if(typeof Ge==="string"){let Xr=Ts(e.workspaceRoot,Ge);dr=Xr.buffer,Wr=Xr.mimeType}else throw Error("view() needs a Buffer, a base64 string, or a path to an image file");if(dr.length===0)throw Error("view(): the image is empty");let ln=String(sr.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),Kr=Number(sr.maxWidth)||1024,lt=Number(sr.quality)||72,Ft=e.targetContext?await le.newPage():await he.newPage();try{let Xr=`data:${Wr};base64,${dr.toString("base64")}`;for(let lr=0;lr<5;lr+=1){let jr=await Ft.evaluate(async(Lr)=>{let Mr=new Image;Mr.src=Lr.url,await Mr.decode();let Zr=Math.min(1,Lr.maxWidth/Mr.naturalWidth),Tr=document.createElement("canvas");Tr.width=Math.max(1,Math.round(Mr.naturalWidth*Zr)),Tr.height=Math.max(1,Math.round(Mr.naturalHeight*Zr));let Ir=Tr.getContext("2d");if(!Ir)throw Error("view(): canvas unavailable");return Ir.fillStyle="#ffffff",Ir.fillRect(0,0,Tr.width,Tr.height),Ir.drawImage(Mr,0,0,Tr.width,Tr.height),{data:Tr.toDataURL("image/jpeg",Lr.q/100).split(",")[1]??"",width:Tr.width,height:Tr.height,sourceWidth:Mr.naturalWidth,sourceHeight:Mr.naturalHeight}},{url:Xr,maxWidth:Kr,q:lt}),ut=Buffer.from(jr.data,"base64");if(ut.length<=As){let Lr=ln||"image";return`<<<ARA_VIEW_IMAGE ${jr.data} image/jpeg ${Lr}>>>
|
|
302
302
|
Viewing ${Lr} (${jr.sourceWidth}x${jr.sourceHeight} source, sent at ${jr.width}x${jr.height}, ${Math.round(ut.length/1024)}KB).`}if(Kr>640)Kr=Math.round(Kr*0.75);else lt=Math.max(30,lt-15)}throw Error(`view(): could not reduce the image under ${Math.round(As/1024)}KB`)}finally{await Ft.close().catch(()=>{return})}},We=ws({browser:e.targetContext?.browser()??le,context:he,page:Le,a11y:Be,view:ke,readWorkspaceFile:(Ge)=>Ts(e.workspaceRoot,Ge),privateProfile:e.privateProfile,beforeNavigation:e.beforeNavigation,recording:e.recording,screenshotExport:e.screenshotExport,actionRecorder:()=>{let Ge=w,or=S;return(sr,dr)=>{if(Ge.length<xo)Ge.push(sr);if(dr)or.page=dr}}}),tr=async(Ge)=>{z();let or=be(await le.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await or.route("**/*",(dr)=>dr.abort()),z(),await or.routeWebSocket("**/*",(dr)=>dr.close({code:1008,reason:"Reason evaluator network denied"})),z(),await or.exposeBinding("__araHandsRpc",async(dr,Wr)=>e.onBrowserOperation?e.onBrowserOperation(Ge,()=>We.dispatch(Wr)):We.dispatch(Wr)),z();let sr=await or.newPage();return z(),await sr.goto("data:text/html,<title>Reason Hands evaluator</title>"),z(),await sr.evaluate(`(${ds})(${JSON.stringify(We.roots)})`),{context:or,page:sr,runId:Ge}}catch(sr){throw await fe(or).catch(()=>{return}),sr}},nr=await tr(),Pr={browser:le,context:he,page:Le,evaluator:nr,async captureProgressFrame(Ge){return ke(await Ge.screenshot({type:"jpeg",quality:65,timeout:2000}),{label:"Screen after browser action"})},async resetEvaluator(Ge){await fe(Pr.evaluator.context),Pr.evaluator=await tr(Ge)}};return z(),Pr}catch(xe){throw await ve().catch(()=>{return}),xe}},$e=async()=>{if(z(),I)return I;if(!x){W=Oe();let le;x=Promise.race([W,new Promise((he,xe)=>{le=setTimeout(()=>xe(Error("hands_browser_unavailable: startup timed out")),bc)})]).then((he)=>(z(),I=he,he)).catch(async()=>{M=Error("hands_browser_unavailable: startup failed or timed out");let he;try{await Promise.race([ve(),new Promise((xe,Ke)=>{he=setTimeout(()=>Ke(Error("hands_repl_stop_timeout")),Is)})])}catch{M=Error("hands_browser_unavailable: startup cleanup unconfirmed")}finally{if(he)clearTimeout(he)}throw M}).finally(()=>{if(le)clearTimeout(le)})}return x},qe=async(le,he,xe=!1)=>{let Ke=await $e(),Le=S;if(e.onBrowserOperation&&Ke.evaluator.runId!==he)await Ke.resetEvaluator(he);let ke=(async()=>{let nr=await Ke.evaluator.page.evaluate(`(${ls})(${JSON.stringify({code:le})})`);if(typeof nr!=="string")throw Error("hands_repl_invalid_evaluator_output");let Pr=Le.page;if(xe&&Pr&&!nr.includes("<<<ARA_VIEW_IMAGE")){let Ge=()=>Ke.captureProgressFrame(Pr);try{let or=await(e.onBrowserOperation?e.onBrowserOperation(he,Ge):Ge());return Le.automaticProgressImage=!0,`${nr}
|
|
303
303
|
${or}`}catch{return`${nr}
|
|
304
304
|
Screen capture unavailable.`}}return nr})(),We,tr=new Promise((nr,Pr)=>{We=setTimeout(()=>Pr(Error("REPL evaluation timed out after 105 seconds")),gc)});try{return await Promise.race([ke,tr])}catch(nr){if(nr instanceof Error&&nr.message.includes("timed out"))ke.catch(()=>{return}),await Ke.resetEvaluator(he).catch(()=>{return});throw nr}finally{if(We)clearTimeout(We)}},ye=Promise.resolve(),Fe=new Set,Ve=new Set;rn(e.socketPath);let Te=it.createServer((le)=>{Fe.add(le),le.once("close",()=>{Fe.delete(le),Ve.delete(le)}),le.setEncoding("utf8");let he="",xe=!1;le.on("data",(Ke)=>{if(xe)return;if(he+=Ke,he.length>hc){xe=!0,vt(le,{ok:!1,error:"REPL request exceeds 1 MiB"});return}let Le=he.indexOf(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_,Xr,_t,ke}from"./vm-hands-entry-lite-nqdstx24.js";import{Po}from"./vm-hands-entry-lite-7777m86y.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{t,i,s,n}from"./vm-hands-entry-lite-a1xa7s06.js";import{createHmac as bt,createPublicKey as be,randomBytes as mt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as De,statSync as It,unlinkSync as Le,writeFileSync as we}from"fs";import{basename as Dt,dirname as w,isAbsolute as Ae,join as m,resolve as Lt}from"path";var $e=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as g,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as f}from"path";var O=1,ue=16384,y=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Wt(r=process.execPath){let e=r;try{e=te(r)}catch{}return Po(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!g(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function v(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ke{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Wt(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!v(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(y),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!v(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||f(le(),".config");_t(r);let e=f(r,"ara");return Xr(e)?e:f(r,"reason")}class Nr{directory;constructor(r=_e()){this.directory=r}keyPath(){return f(this.directory,"local-device.key")}bindingPath(){return f(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!g(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!g(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!g(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(g(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!g(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(g(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!g(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ke:new Nr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Pe=1,Ee=`ARA-DEVICE-BINDING-V1
|
|
2
|
+
import{_,Xr,_t,ke}from"./vm-hands-entry-lite-nqdstx24.js";import{Po}from"./vm-hands-entry-lite-7777m86y.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{t,i,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";import{createHmac as bt,createPublicKey as be,randomBytes as mt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as De,statSync as It,unlinkSync as Le,writeFileSync as we}from"fs";import{basename as Dt,dirname as w,isAbsolute as Ae,join as m,resolve as Lt}from"path";var $e=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as g,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as f}from"path";var O=1,ue=16384,y=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Wt(r=process.execPath){let e=r;try{e=te(r)}catch{}return Po(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!g(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function v(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ke{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Wt(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!v(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(y),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!v(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||f(le(),".config");_t(r);let e=f(r,"ara");return Xr(e)?e:f(r,"reason")}class Nr{directory;constructor(r=_e()){this.directory=r}keyPath(){return f(this.directory,"local-device.key")}bindingPath(){return f(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!g(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!g(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!g(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(g(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!g(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(g(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!g(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ke:new Nr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Pe=1,Ee=`ARA-DEVICE-BINDING-V1
|
|
3
3
|
`;function Re(r){return r===void 0||typeof r==="number"&&Number.isInteger(r)&&r>=1&&r<=4}function G(r,e=Date.now()){let o=B.safeParse(r);if(!o.success)return!1;let c=o.data,d=typeof c.occurredAt==="string"?Date.parse(c.occurredAt):NaN,p=typeof c.expiresAt==="string"?Date.parse(c.expiresAt):NaN;return c.kind==="permission_denied"&&["bash","read","write","edit"].includes(c.operation)&&["sandbox_policy","os_permission_unknown"].includes(c.provenance)&&Number.isFinite(d)&&d<=e&&p>e&&p>d&&p-d<=600000}function Vt(r,e,o=Date.now()){if(!r||!e||r.state!=="connected"||r.deviceId!==e.deviceId)return null;let c=Date.parse(r.lastHeartbeatAt??""),d=r.permissionRecovery;if(!(o-c>=0&&o-c<30000)||!G(d,o)||d.deviceId!==e.deviceId||d.organizationId!==e.orgId)return null;try{process.kill(r.pid,0)}catch{return null}return d}function H(r={},e=a()){let o=_({env:{...process.env,...r}}),c=r.XDG_CONFIG_HOME?.trim()||m(e,".config");return ke(c,...o==="staging"?["staging"]:[])}function Lr(r={},e=a()){return m(H(r,e),"local-device.json")}function xe(r={},e=a()){return m(H(r,e),"local-daemon.json")}function Ne(r,e){Se(w(r),{recursive:!0,mode:448}),L(w(r),448);let o=`${r}.${process.pid}.${me()}.tmp`;try{we(o,`${JSON.stringify(e,null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),L(o,384),De(o,r),L(r,384)}finally{if(z(o))Le(o)}return r}function E(r){if(!z(r))return null;try{return JSON.parse(Ie(r,"utf8"))}catch{return null}}function Oe(r){if(!Array.isArray(r))return null;let e=[];for(let o of r){if(!o||typeof o!=="object")return null;let c=o;if(typeof c.id!=="string"||typeof c.label!=="string"||typeof c.path!=="string"||typeof c.pathFingerprint!=="string"||!c.permissions||typeof c.permissions.read!=="boolean"||typeof c.permissions.write!=="boolean"||typeof c.permissions.execute!=="boolean"||typeof c.permissions.discover_environment!=="boolean"||typeof c.permissions.expose_mcp!=="boolean")return null;e.push({id:c.id,label:c.label,path:c.path,pathFingerprint:c.pathFingerprint,permissions:c.permissions})}return e}function J(r,e,o=[]){let c=Object.keys(r);return e.every((d)=>Object.hasOwn(r,d))&&c.every((d)=>e.includes(d)||o.includes(d))}function Ce(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost")return null;return e.origin}catch{return null}}function Y(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r,o=Oe(e.roots),c=Ce(e.apiOrigin);if(!c||typeof e.orgId!=="string"||typeof e.deviceId!=="string"||typeof e.displayName!=="string"||typeof e.registeredAt!=="string"||!Re(e.handsSlots)||e.worker!==void 0&&(!e.worker||!/^[a-f0-9]{64}$/.test(e.worker.configDigest)||!["persistent","ephemeral"].includes(e.worker.lifetime)||!Number.isFinite(Date.parse(e.worker.expiresAt)))||!o)return null;return{apiOrigin:c,orgId:e.orgId,deviceId:e.deviceId,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:o}}function Te(r){return{version:A,apiOrigin:r.apiOrigin,orgId:r.orgId,deviceId:r.deviceId,devicePublicKey:r.devicePublicKey,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:r.roots.map((e)=>({id:e.id,label:e.label,path:e.path,pathFingerprint:e.pathFingerprint,permissions:{read:e.permissions.read,write:e.permissions.write,execute:e.permissions.execute,discover_environment:e.permissions.discover_environment,expose_mcp:e.permissions.expose_mcp}})),credentialStorage:P}}function X(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r;if(!J(e,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Y(e);if(!o||e.version!==A||e.credentialStorage!==P||!v(e.devicePublicKey))return null;return{version:A,...o,devicePublicKey:e.devicePublicKey,credentialStorage:P}}function Ue(r){return new TextEncoder().encode(`${Ee}${JSON.stringify(Te(r))}`)}function Fe(r){let e=Buffer.from(r,"base64url");return be({format:"jwk",key:{kty:"EC",crv:"P-256",x:e.subarray(1,33).toString("base64url"),y:e.subarray(33,65).toString("base64url")}})}function Me(r){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new l("invalid_binding")}if(!e||typeof e!=="object"||Array.isArray(e))throw new l("invalid_binding");let o=e;if(!J(o,["version","state","signature"])||o.version!==Pe||typeof o.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test(o.signature))throw new l("invalid_binding");let c=X(o.state);if(!c)throw new l("invalid_binding");let d=!1;try{d=he("sha256",Ue(c),Fe(c.devicePublicKey),Buffer.from(o.signature,"base64url"))}catch{d=!1}if(!d)throw new l("invalid_binding");return c}function je(r){let{credentialStorage:e,...o}=r;return o}function Mr(r=Lr(),e={}){let o=E(r),c=e.proofStore??e.credentialStore??V(),d=c.loadBinding();if(!d){if(o&&typeof o==="object"&&!Array.isArray(o)&&Ve(o))return null;if(o!==null)throw new l("invalid_binding");return null}let p=Me(d),W=c.loadPublicKey();if(c.privateKeyIsNonExtractable(),W!==p.devicePublicKey)throw new l("invalid_public_key");let R=X(o);if(e.repair!==!1&&(!R||JSON.stringify(R)!==JSON.stringify(p)))Ne(r,p);return je(p)}function Ve(r){let e=r,o=Y(r);if(!o)return null;if(e.version===2){if(typeof e.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(e.deviceCredential)||e.deviceCredential.length>4096)return null;return{state:o,credentialSource:"plaintext-v2"}}if(e.version!==3||e.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in e)return null;return{state:o,credentialSource:"keychain-v3"}}function pt(r=xe()){let e=E(r);if(!e||typeof e!=="object")return null;let o=e;if(o.version!==1||typeof o.pid!=="number"||!Number.isInteger(o.pid)||!["starting","connected","stopped","error"].includes(o.state??"")||typeof o.startedAt!=="string"||o.lastHeartbeatAt!==void 0&&typeof o.lastHeartbeatAt!=="string"||o.lastUsedAt!==void 0&&typeof o.lastUsedAt!=="string"||o.organizationId!==void 0&&typeof o.organizationId!=="string"||o.organizationName!==void 0&&typeof o.organizationName!=="string"||o.organizationSlug!==void 0&&typeof o.organizationSlug!=="string"||o.error!==void 0&&typeof o.error!=="string"||o.reconnectingSince!==void 0&&typeof o.reconnectingSince!=="string"||o.workspace!==void 0&&typeof o.workspace!=="string")return null;if(o.permissionRecovery!==void 0&&!G(o.permissionRecovery))delete o.permissionRecovery;return o}var Gt=1;function Be(r=Lr()){return m(w(r),"local-device.proxy.json")}function j(r=Be()){let e=E(r);if(!e||typeof e!=="object"||Array.isArray(e))return null;let o=e;if(o.version!==Gt||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!Ae(o.caFile)))return null;return{version:Gt,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}
|
|
5
5
|
export{l,Wt,Ke,Nr,Vt,Lr,Mr,pt,Gt,j};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Qt={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var Qt={name:"github-native-engineer-device-worker-production",version:"0.2.504",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
3
|
export{Qt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Qe}from"./vm-hands-entry-lite-ex69qn9q.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Xn="so.ara.cli",k=[Xn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Vr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",To="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Vr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Vr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Gr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Gr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
|
|
3
3
|
`)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
|
|
4
4
|
`).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
|
|
5
5
|
`)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Yn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
|