@reason-machines/cli-linux-x64 0.2.471 → 0.2.473

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/bin/reason +2 -2
  2. package/bin/vm-hands/api-credentials-s9h7p7mh.js +2 -0
  3. package/bin/vm-hands/{api-7xy672j8.js → api-y0tty1bt.js} +1 -1
  4. package/bin/vm-hands/connect-cli-hzad1rps.js +2 -0
  5. package/bin/vm-hands/{custom-endpoint-device-r2nn1xj9.js → custom-endpoint-device-6c5s0j3t.js} +1 -1
  6. package/bin/vm-hands/desktop-account-wgkkapa4.js +2 -0
  7. package/bin/vm-hands/{fsevents-sxsgn7s9.js → fsevents-xj75dzay.js} +1 -1
  8. package/bin/vm-hands/{hands-worker-source-k8v5kmmw.js → hands-worker-source-rjsr93rq.js} +1 -1
  9. package/bin/vm-hands/{index-d5n50g8b.js → index-kn7eerh9.js} +2 -2
  10. package/bin/vm-hands/local-automation-pq08yjbc.js +2 -0
  11. package/bin/vm-hands/local-capabilities-35z8nr0y.js +2 -0
  12. package/bin/vm-hands/local-desktop-users-3641y146.js +2 -0
  13. package/bin/vm-hands/local-display-session-ecntdwxe.js +2 -0
  14. package/bin/vm-hands/local-display-video-v7g7n7tf.js +2 -0
  15. package/bin/vm-hands/local-managed-process-0q0khgdg.js +2 -0
  16. package/bin/vm-hands/{local-pty-session-k6kab3tc.js → local-pty-session-k3c8bwtj.js} +1 -1
  17. package/bin/vm-hands/managed-runtime-0f805trk.js +2 -0
  18. package/bin/vm-hands/network-contract-z0sk9jzq.js +2 -0
  19. package/bin/vm-hands/package-t67yw2kp.js +2 -0
  20. package/bin/vm-hands/permissions-7ay3j94c.js +2 -0
  21. package/bin/vm-hands/serve-service-vgt7qedg.js +2 -0
  22. package/bin/vm-hands/{status-3mgfgra8.js → status-69b64z1g.js} +1 -1
  23. package/bin/vm-hands/version-t0xnbt7t.js +2 -0
  24. package/bin/vm-hands/{vm-hands-entry-lite-mmrdd8gk.js → vm-hands-entry-lite-4t4sh0q6.js} +1 -1
  25. package/bin/vm-hands/{vm-hands-entry-lite-nxyk22qr.js → vm-hands-entry-lite-6431pknh.js} +3 -3
  26. package/bin/vm-hands/{vm-hands-entry-lite-5zvph0py.js → vm-hands-entry-lite-7e2x9bfe.js} +3 -3
  27. package/bin/vm-hands/{vm-hands-entry-lite-spajqeyc.js → vm-hands-entry-lite-7fyrsw85.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-eqbbemee.js → vm-hands-entry-lite-7mf3t1v6.js} +1 -1
  29. package/bin/vm-hands/vm-hands-entry-lite-9ar02hg7.js +3 -0
  30. package/bin/vm-hands/vm-hands-entry-lite-ahtvnd86.js +2 -0
  31. package/bin/vm-hands/{vm-hands-entry-lite-egax7vw4.js → vm-hands-entry-lite-amwx1104.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-gez48xt4.js → vm-hands-entry-lite-cvgeeyjj.js} +4 -4
  33. package/bin/vm-hands/{vm-hands-entry-lite-98rmcvag.js → vm-hands-entry-lite-dg9eh49f.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-vfxx44f3.js → vm-hands-entry-lite-dykbkjpt.js} +3 -3
  35. package/bin/vm-hands/vm-hands-entry-lite-e508r607.js +2 -0
  36. package/bin/vm-hands/{vm-hands-entry-lite-tn8v3yfj.js → vm-hands-entry-lite-ey2hbfs8.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-r3yp6cr9.js → vm-hands-entry-lite-fykfnzjg.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-03d1fhxv.js → vm-hands-entry-lite-hk6grdfm.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-awp08wyd.js → vm-hands-entry-lite-hyk852md.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-7ja63pfz.js → vm-hands-entry-lite-jwgheerx.js} +3 -3
  41. package/bin/vm-hands/{vm-hands-entry-lite-d2fveq6h.js → vm-hands-entry-lite-k3ksgb4t.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-7c7swrjq.js → vm-hands-entry-lite-kqdysn28.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-b8yapqfn.js → vm-hands-entry-lite-mb6atrr0.js} +5 -5
  44. package/bin/vm-hands/{vm-hands-entry-lite-vm6et8tm.js → vm-hands-entry-lite-pz1gnec4.js} +10 -10
  45. package/bin/vm-hands/{vm-hands-entry-lite-hdc0sb80.js → vm-hands-entry-lite-r43h85w5.js} +4 -4
  46. package/bin/vm-hands/{vm-hands-entry-lite-8eksd9j1.js → vm-hands-entry-lite-s8san9e5.js} +3 -3
  47. package/bin/vm-hands/{vm-hands-entry-lite-8qvsnkvv.js → vm-hands-entry-lite-tmart4k9.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-5agyspqp.js → vm-hands-entry-lite-vmnxnr7y.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-kz48x6p0.js → vm-hands-entry-lite-wwp36b4m.js} +3 -3
  50. package/bin/vm-hands/{vm-hands-entry-lite-44qha2rt.js → vm-hands-entry-lite-wxz5n6tc.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-gdzw92jk.js → vm-hands-entry-lite-ye0pkbqd.js} +1 -1
  52. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  53. package/bin/vm-hands/{vm-hands-executor-zn1wyrng.js → vm-hands-executor-3cxjy1sr.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-op-runner-h6s4p65y.js → vm-hands-op-runner-pmpa2r8z.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-runtime-ecfwv3a4.js → vm-hands-runtime-2emg32yv.js} +3 -3
  56. package/bin/vm-hands/worker-preview-readiness-jrmtzbwm.js +2 -0
  57. package/bin/vm-hands/{worker-sandbox-1g7jheqm.js → worker-sandbox-26a3hggc.js} +1 -1
  58. package/package.json +1 -1
  59. package/bin/vm-hands/api-credentials-bbmmmkwx.js +0 -2
  60. package/bin/vm-hands/connect-cli-c5bmsf0p.js +0 -2
  61. package/bin/vm-hands/desktop-account-3cc0bhw8.js +0 -2
  62. package/bin/vm-hands/local-automation-xqbgsg13.js +0 -2
  63. package/bin/vm-hands/local-capabilities-rnsn2yye.js +0 -2
  64. package/bin/vm-hands/local-desktop-users-qskbh51j.js +0 -2
  65. package/bin/vm-hands/local-display-session-avdg9bkp.js +0 -2
  66. package/bin/vm-hands/local-display-video-7t4c9cwg.js +0 -2
  67. package/bin/vm-hands/local-managed-process-zvm6srg5.js +0 -2
  68. package/bin/vm-hands/managed-runtime-10rq8hz6.js +0 -2
  69. package/bin/vm-hands/network-contract-y2eybfhn.js +0 -2
  70. package/bin/vm-hands/package-8v6gpwas.js +0 -2
  71. package/bin/vm-hands/permissions-0yb0vzqr.js +0 -2
  72. package/bin/vm-hands/serve-service-q02jz4d9.js +0 -2
  73. package/bin/vm-hands/version-5ffeerbd.js +0 -2
  74. package/bin/vm-hands/vm-hands-entry-lite-3pxmmb7z.js +0 -3
  75. package/bin/vm-hands/vm-hands-entry-lite-n1k1njzh.js +0 -3
  76. package/bin/vm-hands/vm-hands-entry-lite-zz8yhajj.js +0 -2
  77. package/bin/vm-hands/worker-preview-readiness-6hzzjnk7.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Gt,j}from"./vm-hands-entry-lite-8qvsnkvv.js";import{ue,Ce,Z,Ae,de,rr,Qe,X,O,H,tn}from"./vm-hands-entry-lite-3krzmhkk.js";import{Do,ei}from"./vm-hands-entry-lite-k83rkcys.js";import{So,P,Je,Se,Ze,ne,Xe,qn,Ee,Xt,ae,U,N,ce,Hr,zr,Vn}from"./vm-hands-entry-lite-5zdybh8s.js";import{Pe,oe,pe,Y,Re,q,Q}from"./vm-hands-entry-lite-b8yapqfn.js";import{It,kr,st,V,D,R,b}from"./vm-hands-entry-lite-kz48x6p0.js";import{Er,xr,vn,no,He,Sn}from"./vm-hands-entry-lite-hzh8fdxx.js";import{K}from"./vm-hands-entry-lite-r3yp6cr9.js";import{Ni}from"./vm-hands-entry-lite-7ja63pfz.js";import{p,ze,Dt,at,io,_e,we}from"./vm-hands-entry-lite-h6rhk6h1.js";import{v,h,ao}from"./vm-hands-entry-lite-52x189kf.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{Qt}from"./vm-hands-entry-lite-eqbbemee.js";import{a,ie,Lo}from"./vm-hands-entry-lite-cf1x5cbr.js";import{L,Ri,Oi,jo,y,t,k,Et,o,d,u,i,c,g,ee,s,n}from"./vm-hands-entry-lite-5agyspqp.js";import{Di}from"./vm-hands-entry-lite-d2fveq6h.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ho,se,zo,C,De,Me,A}from"./vm-hands-entry-lite-vdhgwmmp.js";var _i=()=>{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=jo(w.input),W=_[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Oi(w.values[0])}`;return`Invalid option: expected one of ${Ri(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":""}: ${Ri(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 En(){return{localeError:_i()}}L(En());class pt extends Error{}function xo(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 mi}from"crypto";import{isAbsolute as Po,join as Io,relative as Ao,resolve as Vt,sep as To}from"path";var Jt=t().min(1).refine(Po,"absolute path required"),On=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 xo(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()}),hi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[On,On.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),On.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!hi.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:"&&ei(_.origin))||!ei(_.origin)&&!Do(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 Io(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if(Ur(l,e))return!1;return!Ur(e,l)||E(Io(To,Ao(Vt(e),Vt(l))))}function Ur(e,l){let f=Ao(Vt(e),Vt(l));return f===""||f!==".."&&!f.startsWith(`..${To}`)&&!Po(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...I}=e;return mi("sha256").update(JSON.stringify(I)).digest("hex")}var gi=4,bi=[2375,2376,9222,9229];function pr(e){let l=new Set(bi);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Jr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var wi=60000;function Co(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)Jr()}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())>wi)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}=at(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Jr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==T)Jr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Jr();return{opened:!0,binding:F}}if(f.size>=gi)Jr();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()))Jr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Jr()}},async close(x,M){w(M);let{binding:G}=io(x),F=f.get(_(G));if(!F||!ze(F.binding,G))Jr();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 xn}from"ws";var No=(e)=>("data"in e)?e.data.length:e.bytes,Bo=2*Xe;function ar(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 Gi(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))ar("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ar("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ar("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return ar("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))ar("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ar("invalid_pty_request");return{workspace:H(e.workspace)??ar("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 Mo(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ar("cancelled");let _=new xn(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>qn){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 Vn(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)ar(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))ar("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)ar("cancelled");let xe=$e(he);if(xe.inputSequence!==G)ar("job_input_sequence");if(!_t(xe)&&xe.leaseExpiresAtMs<=Date.now())ar("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==xn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Bo)ar("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)ar("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Bo)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)ar("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)ar("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)ar("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())ar("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:nr}=z.pty;for(let or of[{cols:We,rows:nr>1?nr-1:2},{cols:We,rows:nr}]){if(_t(z))break;let Pr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Pr,...or}}),z.inputSequence!==Pr)ar("job_input_sequence")}continue}let ke=_t(z)||Ke?void 0:x.shift();if(ke){M-=No(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(nr){if(!(nr instanceof r)||nr.code!=="job_input_backpressure")throw nr;G-=1,x.unshift(ke),M+=No(ke),Ke=!0;continue}if(z.inputSequence!==We)ar("job_input_sequence")}else if(await new Promise((We)=>{let nr=setTimeout(We,Ke||!Be?10:50);if(S=()=>{clearTimeout(nr),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")ar("pty_cleanup_unconfirmed");let le=Oe(z);if(_.readyState===xn.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)ar("cancelled");if(!z)ar("pty_cleanup_unconfirmed");return{receipt:Oe(z)}}import{createHash as yi,randomUUID as An}from"crypto";import{spawnSync as $o}from"child_process";import{closeSync as Wo,constants as Pn,fstatSync as vi,fsyncSync as ki,lstatSync as Lt,mkdirSync as Si,mkdtempSync as Ko,openSync as Fo,readFileSync as Ei,readdirSync as Go,realpathSync as Nt,rmSync as In,unlinkSync as xi}from"fs";import{createConnection as Pi}from"net";import{dirname as Ii,join as tt,sep as Ai}from"path";import{tmpdir as Ti}from"os";var Or=new Map,Vr=new Map;function $r(e,l){return yi("sha256").update(JSON.stringify([e,l])).digest("hex")}function mt(e){try{Si(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 Ci(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()||Go(e).length>0}function hr(e){let l=$r(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>Ci(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=Go(_);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=Ko(tt(zo(),"reason-j-"));try{return mt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:tt(S,"control.sock"),disposeSocket:()=>In(S,{recursive:!0,force:!0})}}catch(I){throw In(S,{recursive:!0,force:!0}),I}}var Hi=60000,Li=5000;function Bi(e){if(process.platform==="win32")return ji(e);let l=$o("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 ji(e){let l=$o(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 Jo(e,l={}){let f=tt(e.journalDirectory,"owner.lock"),_;try{_=Fo(f,Pn.O_RDONLY|Pn.O_NOFOLLOW)}catch{return null}try{let w=vi(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Ei(_,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Hi)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??Bi)(F);if(z===null||z<=T+Li)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Lt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;xi(f);let x=Fo(e.journalDirectory,Pn.O_RDONLY);try{ki(x)}finally{Wo(x)}return I}catch{return null}finally{Wo(_)}}function Vo(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=$r(l.root,l.runId);if(Or.has(f)||l.operationId!==void 0&&Vr.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=Co({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 qo(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Or.set(f,_),l.operationId!==void 0)Vr.set(l.operationId,_);return()=>{if(Or.get(_.key)===_)Or.delete(_.key);if(l.operationId!==void 0&&Vr.get(l.operationId)===_)Vr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Mi=5000,Wi=20;async function Ki(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=Vr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Mi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Vr.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,Wi))}if(Vr.get(e.operationId)!==f||Or.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=$r(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 it(e){let l="operationId"in e?Vr.get(e.operationId):Or.get($r(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 Ji(e){let l=Or.get($r(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 Zi(e){let l=Or.get($r(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 Xi(e){let l=$r(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 Mo({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:An()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function Yi(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Or.get($r(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 qo(l,e.payload,e.signal)}var Fi=1e4,Ui=20,zi=Se/2,$i=Je/2,Vi=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function qo(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||_>Fi))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:An()})),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<zi&&Vi(x.job)<$i&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Ui,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=Pi(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-tmart4k9.js";import{ue,Ce,Z,Ae,de,rr,Qe,X,O,H,tn}from"./vm-hands-entry-lite-3krzmhkk.js";import{Do,ei}from"./vm-hands-entry-lite-k83rkcys.js";import{So,P,Je,Se,Ze,ne,Xe,qn,Ee,Xt,ae,U,N,ce,Hr,zr,Vn}from"./vm-hands-entry-lite-5zdybh8s.js";import{Pe,oe,pe,Y,Re,q,Q}from"./vm-hands-entry-lite-mb6atrr0.js";import{It,kr,st,V,D,R,b}from"./vm-hands-entry-lite-wwp36b4m.js";import{Er,xr,vn,no,He,Sn}from"./vm-hands-entry-lite-hzh8fdxx.js";import{K}from"./vm-hands-entry-lite-fykfnzjg.js";import{Ni}from"./vm-hands-entry-lite-jwgheerx.js";import{p,ze,Dt,at,io,_e,we}from"./vm-hands-entry-lite-h6rhk6h1.js";import{v,h,ao}from"./vm-hands-entry-lite-52x189kf.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{Qt}from"./vm-hands-entry-lite-7mf3t1v6.js";import{a,ie,Lo}from"./vm-hands-entry-lite-cf1x5cbr.js";import{L,Ri,Oi,jo,y,t,k,Et,o,d,u,i,c,g,ee,s,n}from"./vm-hands-entry-lite-vmnxnr7y.js";import{Di}from"./vm-hands-entry-lite-k3ksgb4t.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ho,se,zo,C,De,Me,A}from"./vm-hands-entry-lite-vdhgwmmp.js";var _i=()=>{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=jo(w.input),W=_[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Oi(w.values[0])}`;return`Invalid option: expected one of ${Ri(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":""}: ${Ri(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 En(){return{localeError:_i()}}L(En());class pt extends Error{}function xo(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 mi}from"crypto";import{isAbsolute as Po,join as Io,relative as Ao,resolve as Vt,sep as To}from"path";var Jt=t().min(1).refine(Po,"absolute path required"),On=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 xo(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()}),hi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[On,On.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),On.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!hi.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:"&&ei(_.origin))||!ei(_.origin)&&!Do(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 Io(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if(Ur(l,e))return!1;return!Ur(e,l)||E(Io(To,Ao(Vt(e),Vt(l))))}function Ur(e,l){let f=Ao(Vt(e),Vt(l));return f===""||f!==".."&&!f.startsWith(`..${To}`)&&!Po(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...I}=e;return mi("sha256").update(JSON.stringify(I)).digest("hex")}var gi=4,bi=[2375,2376,9222,9229];function pr(e){let l=new Set(bi);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Jr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var wi=60000;function Co(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)Jr()}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())>wi)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}=at(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Jr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==T)Jr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Jr();return{opened:!0,binding:F}}if(f.size>=gi)Jr();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()))Jr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Jr()}},async close(x,M){w(M);let{binding:G}=io(x),F=f.get(_(G));if(!F||!ze(F.binding,G))Jr();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 xn}from"ws";var No=(e)=>("data"in e)?e.data.length:e.bytes,Bo=2*Xe;function ar(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 Gi(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))ar("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ar("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ar("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return ar("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))ar("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ar("invalid_pty_request");return{workspace:H(e.workspace)??ar("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 Mo(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ar("cancelled");let _=new xn(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>qn){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 Vn(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)ar(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))ar("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)ar("cancelled");let xe=$e(he);if(xe.inputSequence!==G)ar("job_input_sequence");if(!_t(xe)&&xe.leaseExpiresAtMs<=Date.now())ar("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==xn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Bo)ar("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)ar("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Bo)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)ar("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)ar("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)ar("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())ar("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:nr}=z.pty;for(let or of[{cols:We,rows:nr>1?nr-1:2},{cols:We,rows:nr}]){if(_t(z))break;let Pr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Pr,...or}}),z.inputSequence!==Pr)ar("job_input_sequence")}continue}let ke=_t(z)||Ke?void 0:x.shift();if(ke){M-=No(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(nr){if(!(nr instanceof r)||nr.code!=="job_input_backpressure")throw nr;G-=1,x.unshift(ke),M+=No(ke),Ke=!0;continue}if(z.inputSequence!==We)ar("job_input_sequence")}else if(await new Promise((We)=>{let nr=setTimeout(We,Ke||!Be?10:50);if(S=()=>{clearTimeout(nr),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")ar("pty_cleanup_unconfirmed");let le=Oe(z);if(_.readyState===xn.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)ar("cancelled");if(!z)ar("pty_cleanup_unconfirmed");return{receipt:Oe(z)}}import{createHash as yi,randomUUID as An}from"crypto";import{spawnSync as $o}from"child_process";import{closeSync as Wo,constants as Pn,fstatSync as vi,fsyncSync as ki,lstatSync as Lt,mkdirSync as Si,mkdtempSync as Ko,openSync as Fo,readFileSync as Ei,readdirSync as Go,realpathSync as Nt,rmSync as In,unlinkSync as xi}from"fs";import{createConnection as Pi}from"net";import{dirname as Ii,join as tt,sep as Ai}from"path";import{tmpdir as Ti}from"os";var Or=new Map,Vr=new Map;function $r(e,l){return yi("sha256").update(JSON.stringify([e,l])).digest("hex")}function mt(e){try{Si(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 Ci(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()||Go(e).length>0}function hr(e){let l=$r(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>Ci(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=Go(_);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=Ko(tt(zo(),"reason-j-"));try{return mt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:tt(S,"control.sock"),disposeSocket:()=>In(S,{recursive:!0,force:!0})}}catch(I){throw In(S,{recursive:!0,force:!0}),I}}var Hi=60000,Li=5000;function Bi(e){if(process.platform==="win32")return ji(e);let l=$o("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 ji(e){let l=$o(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 Jo(e,l={}){let f=tt(e.journalDirectory,"owner.lock"),_;try{_=Fo(f,Pn.O_RDONLY|Pn.O_NOFOLLOW)}catch{return null}try{let w=vi(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Ei(_,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Hi)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??Bi)(F);if(z===null||z<=T+Li)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Lt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;xi(f);let x=Fo(e.journalDirectory,Pn.O_RDONLY);try{ki(x)}finally{Wo(x)}return I}catch{return null}finally{Wo(_)}}function Vo(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=$r(l.root,l.runId);if(Or.has(f)||l.operationId!==void 0&&Vr.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=Co({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 qo(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Or.set(f,_),l.operationId!==void 0)Vr.set(l.operationId,_);return()=>{if(Or.get(_.key)===_)Or.delete(_.key);if(l.operationId!==void 0&&Vr.get(l.operationId)===_)Vr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Mi=5000,Wi=20;async function Ki(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=Vr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Mi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Vr.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,Wi))}if(Vr.get(e.operationId)!==f||Or.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=$r(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 it(e){let l="operationId"in e?Vr.get(e.operationId):Or.get($r(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 Ji(e){let l=Or.get($r(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 Zi(e){let l=Or.get($r(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 Xi(e){let l=$r(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 Mo({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:An()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function Yi(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Or.get($r(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 qo(l,e.payload,e.signal)}var Fi=1e4,Ui=20,zi=Se/2,$i=Je/2,Vi=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function qo(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||_>Fi))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:An()})),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<zi&&Vi(x.job)<$i&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Ui,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=Pi(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 Uo(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=$r(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:Ii(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 Qi(e,l){let f=Pe.parse(e.request),_=oe.parse(e.authority);if(_.contributorRefresh&&f.kind==="read"&&_.readOnly)return l(Uo(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(Uo(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(Ti());if(x===S||x.startsWith(S+Ai))throw Error("local_device_gh_private_scope_unavailable");let M=Ko(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{In(M,{recursive:!0,force:!0})}}var Zo=43200000;function gt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Yo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Xo(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function eo(e){if(!Yo(e)||!Xo(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(!Yo(f)||!Xo(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 Tn=c({kind:s(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),Qo=new RegExp(st.tokenPattern),qi=c({token_url:Et().max(2048),request_token:t().min(1).max(8192).regex(Qo),aws_credentials_url:Et().max(2048).nullable()});function es(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(!Qo.test(e.request_token)||!f(e.token_url,st.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,st.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 rs(e){return new TextEncoder().encode(e).byteLength}function ea(e){return rs(JSON.stringify(e)+`
4
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:Tn.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")&&rs(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:qi.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ea(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ra}from"child_process";import{basename as ta,isAbsolute as Eu}from"path";var na=0,ts=120000,ns=15000,oa=65536;function Dn(e=process.execPath,l=process.argv[1]){let f=ta(e),_=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:_?[l]:[]}}function to(e={}){let{command:l,prefix:f}=Dn(e.executablePath,e.sourceEntrypoint),_=e.spawnProcess??ra,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<ts-ns)return;if(S){let F=S;S=null,x(F)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(na)],{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>=ts-ns||Buffer.byteLength(be,"utf8")>oa)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 la,constants as ua,statSync as fa}from"fs";import{homedir as pa,tmpdir as _a,userInfo as ma}from"os";import{delimiter as ha,win32 as ga}from"path";var sa=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 ia=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],aa=new Set(["BUN_INSTALL"]);var ca=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function da(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>ca.test(l.replaceAll("_","-")))}function os(e){return Object.keys(e).filter((l)=>sa.has(l)&&!(l==="NODE_OPTIONS"&&da(e[l]))||ia.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!aa.has(l)).sort()}var ba=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),wa=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,ya=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,va=/^[A-Za-z_][A-Za-z0-9_]*$/;function gr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ga.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(os(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&&va.test(S)&&!f.has(S)&&!ba.has(S)&&!wa.test(S)&&!ya.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||pa()),path:((w)=>process.platform==="win32"?Sn(w):w)(xr(e.PATH??"").join(ha)||Er),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||_a()),variables:_}}function _r(e=process.env,l=()=>ma().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return la(w,ua.X_OK),fa(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 ka}from"fs/promises";var Sa=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 ss(e,{timeoutMs:l=Sa,open:f=(_)=>ka(_)}={}){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 rc,closeSync as tc,constants as Un,fstatSync as nc,lstatSync as Es,openSync as oc,readSync as sc,realpathSync as zn,unlinkSync as ic}from"fs";import{lookup as ac}from"dns/promises";import{createRequire as cc}from"module";import{request as dc}from"http";import{request as lc}from"https";import ct from"net";import{platform as Is}from"os";import{basename as uc,extname as fc,isAbsolute as Rs,relative as $n,resolve as yt,sep as Kn}from"path";var is=String.raw`
5
5
  async (roots) => {
@@ -296,7 +296,7 @@ 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 Ea}from"crypto";class us 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 fs=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),cs=/^hands_[A-Za-z0-9_-]{8,128}$/,Ra=2048,ps=32,_s=1e4,Oa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function xa(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 Pa=(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))}},ms={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 us(e)}function Cr(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>ps||++f.nodes>_s)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(!Cr(e))Ie("hands_repl_invalid_json");for(let[_,w]of Object.entries(e)){if(fs.has(_))Ie("hands_repl_invalid_json");wt(w,l+1,f)}}function Cn(e){return typeof e==="string"&&Object.hasOwn(ms,e)}function Ia(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Cn(l)?l:null}function ds(e){return Cr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Aa(e){return Cr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function ls(e){return Cr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function qr(e){return!!e&&typeof e==="object"}function qt(){return Object.freeze({$handsRepl:"undefined"})}function Ta(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 hs(e){if(!qr(e.browser)||!qr(e.context)||!qr(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??Ra;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,_=new WeakMap,w=e.createOpaqueId??Ea,S=(T,re)=>{if(!qr(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(cs.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(!Cr(T)||Object.keys(T).length!==3||T.$handsRepl!=="handle"||typeof T.id!=="string"||!cs.test(T.id)||!Cn(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>ps)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(!Cr(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 Ta(T);let J=Ia(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(!Cn(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(Cr(T)&&T.$handsRepl==="handle")return W(T).target;if(ds(T))return bt.from(T.base64,"base64");if(Aa(T))return;if(ls(T))Ie("hands_repl_route_fulfill_only");if(Array.isArray(T))return T.map(G);if(!Cr(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(!Cr(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=ds(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(fs.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")&&Cr(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"||!Oa.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>_s||!Te.every(qr))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"&&xa(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,[Pa]);if(!Cr(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=ms[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)=>Cr(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=qr(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(!ls(ye))Ie("hands_repl_invalid_route_handler");wt(ye.options);let Fe=G(ye.options),Ve=async(he)=>{if(!qr(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(!Cr(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,qr(Fe)?Fe:void 0)}return M(Oe,z.returns)}})}import{isIP as ys}from"net";import{Resolver as Da}from"dns/promises";import{isIP as Zt}from"net";var Ca=[["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 Hn(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 Ha(e,l,f){let _=Hn(l);if(_===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(_&w)>>>0}function gs(e){let l=Hn(e);if(l===null)return!0;return Ca.some(([f,_])=>Ha(l,f,_))}function Na(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=Hn(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 La(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function Ba(e){let l=Na(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 gs(La(_,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 gs(l);if(f===6)return Ba(l);return!0}function bs(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 ws=5000;function ja(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let _=new Da({timeout:ws,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(bs(G)))??x[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var Ma=ja();async function Wa(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 ro(e,l=Ma,f){let _=yr(e);if(Zt(_))return Yt(_)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[_]};let w;try{w=await Wa(_,l,ws,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":bs(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 Fa=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Nn(e){return e.length<=253&&Fa.test(e.toLowerCase())}function Ua(e,l){let f=e.trim().toLowerCase();if(!Nn(f))return!1;if(f.startsWith("*.")){let _=f.slice(2);return l===_||l.endsWith(`.${_}`)}return f===l}function za(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 Ln(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=za(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(".")&&!ys(_)||Boolean(ys(_)&&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)||Ln(_,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)=>Ua(W,_)))return{allowed:!0,url:e,host:_,reason:"allowed_domain"};return{allowed:!1,url:e,host:_,reason:"destination_not_allowed"}}import vs from"child_process";import{accessSync as $a,constants as Ka,readFileSync as Ga,statSync as Ja}from"fs";import{createRequire as Va}from"module";import{dirname as ff,isAbsolute as Bn,join as qa,resolve as pf,win32 as Ya}from"path";var jn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:Qt.dependencies["playwright-core"],browser:"chromium"}),ks=["/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"],Mn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function Xa(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)=>Ya.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 $a(e,Ka.X_OK),Bn(e)&&Ja(e).isFile()}catch{return!1}}function Wn(e,l=process.platform){let f=l==="darwin"?ks:l==="linux"?Mn:l==="win32"?Xa():null;return f?(e??f).find(Bt)??null:null}function Za(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];vs.spawn=new Proxy(vs.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(Za(),e!==void 0){if(!Bn(e))throw Error("hands_browser_driver_path_must_be_absolute");let _=qa(e,"package.json"),w=JSON.parse(Ga(_,"utf8"));if(w.name!==jn.driver)throw Error("hands_browser_wrong_driver");let S=Va(_)(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-d5n50g8b.js"),import("./package-8v6gpwas.js").then((m)=>Di(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var Qa=(e,l=jn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),ec=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function jt(e={}){return Ss(e,jn.driverVersion)}async function Fn(e,l={}){if(e.driverVersion!=="1.61.1"||!Bn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return Ss({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function Ss(e,l){let f=(x)=>Qa(x,l),_=e.platform??process.platform;if(_!=="linux"&&_!=="darwin"&&_!=="win32")return f("unsupported_platform");let w;try{w=await ec(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?Wn(e.systemCandidates,_):null;return W?S(W,"system"):f("executable_missing")}var pc=["/usr/local/bin/chromium",...Mn];function yn(e,l=Is()){return Wn(e??(l==="linux"?pc:void 0),l)}async function _c(){try{return(await en()).chromium}catch{return cc(import.meta.url)("playwright-core").chromium}}var mc=1048576,hc=105000,gc=20000,Os=5000,bc=2000,wc=1000,yc=30000,xs=81920,vc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function kc(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:"?lc:dc)(f,{method:e.method(),headers:_,agent:!1,lookup:(M,G,F)=>{let T=ct.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(`
299
+ `.trim();import{Buffer as bt}from"buffer";import{randomUUID as Ea}from"crypto";class us 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 fs=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),cs=/^hands_[A-Za-z0-9_-]{8,128}$/,Ra=2048,ps=32,_s=1e4,Oa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function xa(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 Pa=(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))}},ms={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 us(e)}function Cr(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>ps||++f.nodes>_s)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(!Cr(e))Ie("hands_repl_invalid_json");for(let[_,w]of Object.entries(e)){if(fs.has(_))Ie("hands_repl_invalid_json");wt(w,l+1,f)}}function Cn(e){return typeof e==="string"&&Object.hasOwn(ms,e)}function Ia(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Cn(l)?l:null}function ds(e){return Cr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Aa(e){return Cr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function ls(e){return Cr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function qr(e){return!!e&&typeof e==="object"}function qt(){return Object.freeze({$handsRepl:"undefined"})}function Ta(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 hs(e){if(!qr(e.browser)||!qr(e.context)||!qr(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??Ra;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,_=new WeakMap,w=e.createOpaqueId??Ea,S=(T,re)=>{if(!qr(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(cs.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(!Cr(T)||Object.keys(T).length!==3||T.$handsRepl!=="handle"||typeof T.id!=="string"||!cs.test(T.id)||!Cn(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>ps)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(!Cr(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 Ta(T);let J=Ia(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(!Cn(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(Cr(T)&&T.$handsRepl==="handle")return W(T).target;if(ds(T))return bt.from(T.base64,"base64");if(Aa(T))return;if(ls(T))Ie("hands_repl_route_fulfill_only");if(Array.isArray(T))return T.map(G);if(!Cr(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(!Cr(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=ds(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(fs.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")&&Cr(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"||!Oa.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>_s||!Te.every(qr))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"&&xa(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,[Pa]);if(!Cr(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=ms[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)=>Cr(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=qr(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(!ls(ye))Ie("hands_repl_invalid_route_handler");wt(ye.options);let Fe=G(ye.options),Ve=async(he)=>{if(!qr(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(!Cr(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,qr(Fe)?Fe:void 0)}return M(Oe,z.returns)}})}import{isIP as ys}from"net";import{Resolver as Da}from"dns/promises";import{isIP as Zt}from"net";var Ca=[["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 Hn(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 Ha(e,l,f){let _=Hn(l);if(_===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(_&w)>>>0}function gs(e){let l=Hn(e);if(l===null)return!0;return Ca.some(([f,_])=>Ha(l,f,_))}function Na(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=Hn(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 La(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function Ba(e){let l=Na(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 gs(La(_,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 gs(l);if(f===6)return Ba(l);return!0}function bs(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 ws=5000;function ja(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let _=new Da({timeout:ws,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(bs(G)))??x[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var Ma=ja();async function Wa(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 ro(e,l=Ma,f){let _=yr(e);if(Zt(_))return Yt(_)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[_]};let w;try{w=await Wa(_,l,ws,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":bs(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 Fa=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Nn(e){return e.length<=253&&Fa.test(e.toLowerCase())}function Ua(e,l){let f=e.trim().toLowerCase();if(!Nn(f))return!1;if(f.startsWith("*.")){let _=f.slice(2);return l===_||l.endsWith(`.${_}`)}return f===l}function za(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 Ln(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=za(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(".")&&!ys(_)||Boolean(ys(_)&&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)||Ln(_,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)=>Ua(W,_)))return{allowed:!0,url:e,host:_,reason:"allowed_domain"};return{allowed:!1,url:e,host:_,reason:"destination_not_allowed"}}import vs from"child_process";import{accessSync as $a,constants as Ka,readFileSync as Ga,statSync as Ja}from"fs";import{createRequire as Va}from"module";import{dirname as ff,isAbsolute as Bn,join as qa,resolve as pf,win32 as Ya}from"path";var jn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:Qt.dependencies["playwright-core"],browser:"chromium"}),ks=["/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"],Mn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function Xa(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)=>Ya.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 $a(e,Ka.X_OK),Bn(e)&&Ja(e).isFile()}catch{return!1}}function Wn(e,l=process.platform){let f=l==="darwin"?ks:l==="linux"?Mn:l==="win32"?Xa():null;return f?(e??f).find(Bt)??null:null}function Za(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];vs.spawn=new Proxy(vs.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(Za(),e!==void 0){if(!Bn(e))throw Error("hands_browser_driver_path_must_be_absolute");let _=qa(e,"package.json"),w=JSON.parse(Ga(_,"utf8"));if(w.name!==jn.driver)throw Error("hands_browser_wrong_driver");let S=Va(_)(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-kn7eerh9.js"),import("./package-t67yw2kp.js").then((m)=>Di(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var Qa=(e,l=jn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),ec=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function jt(e={}){return Ss(e,jn.driverVersion)}async function Fn(e,l={}){if(e.driverVersion!=="1.61.1"||!Bn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return Ss({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function Ss(e,l){let f=(x)=>Qa(x,l),_=e.platform??process.platform;if(_!=="linux"&&_!=="darwin"&&_!=="win32")return f("unsupported_platform");let w;try{w=await ec(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?Wn(e.systemCandidates,_):null;return W?S(W,"system"):f("executable_missing")}var pc=["/usr/local/bin/chromium",...Mn];function yn(e,l=Is()){return Wn(e??(l==="linux"?pc:void 0),l)}async function _c(){try{return(await en()).chromium}catch{return cc(import.meta.url)("playwright-core").chromium}}var mc=1048576,hc=105000,gc=20000,Os=5000,bc=2000,wc=1000,yc=30000,xs=81920,vc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function kc(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:"?lc:dc)(f,{method:e.method(),headers:_,agent:!1,lookup:(M,G,F)=>{let T=ct.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
300
  `):J;w({status:M.statusCode??502,headers:T,body:Buffer.concat(G)})})}),x=setTimeout(()=>W.destroy(Error("hands_browser_fetch_timeout")),yc);W.once("close",()=>clearTimeout(x)),W.on("error",S),W.end(e.postDataBuffer()??void 0)})}async function Sc(e,l,f=()=>{},_={lookup:(w)=>ac(w,{all:!0}),fetch:kc}){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&&!ct.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&&ct.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:ct.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!ct.isIP(z)||l.mode==="enforce"&&Ln(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||!ct.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 As(e,l=Is(),f){if(f){let w=await Fn(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 Ps(e,l){if(!e)throw Error("hands_repl_workspace_required");let f=zn(e),_=yt(e),w=$n(_,yt(_,l)),I=w!==".."&&!w.startsWith(`..${Kn}`)&&!Rs(w)?yt(f,w):yt(f,l);if(E(yt(_,l))||E(I))throw Error("hands_repl_protected_path");let W=(J)=>{let z=$n(f,J);return z!==""&&z!==".."&&!z.startsWith(`..${Kn}`)&&!Rs(z)},x=zn(I);if(E(x))throw Error("hands_repl_protected_path");if(!W(I)||!W(x))throw Error("hands_repl_file_outside_workspace");let M=$n(f,I).split(Kn),G=[f,...M.map((J,z)=>yt(f,...M.slice(0,z+1)))],F=G.map((J)=>Es(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=oc(I,Un.O_RDONLY|Un.O_NOFOLLOW|Un.O_NONBLOCK);try{let J=nc(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=Es(G[be]);if(Oe.dev!==F[be].dev||Oe.ino!==F[be].ino||Oe.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!W(zn(I)))throw Error("hands_repl_file_outside_workspace");let z=Buffer.alloc(16777217),fe=0;while(fe<z.length){let be=sc(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:uc(I),mimeType:vc[fc(I).toLowerCase()]??"application/octet-stream",buffer:ve}}finally{tc(re)}}function vt(e,l){e.end(`${JSON.stringify(l)}
301
301
  `)}function rn(e){try{ic(e)}catch{}}async function Ts(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 Fn(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 _c():(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()+wc,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 nr=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]}: ${nr}`))}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 Sc(he,e.networkPolicy??{mode:"off"},e.onEgressDenied);if(z(),xe){let Ge=he.newPage.bind(he);he.newPage=async()=>{let sr=await Ge();return await xe.preparePage(sr),sr}}let Le=he.pages()[0]??await he.newPage();await xe?.preparePage(Le),z();let Be=async(Ge=Le)=>{let sr=Ge;if(typeof sr.ariaSnapshot==="function")return sr.ariaSnapshot({timeout:1e4});return Le.locator("body").innerText({timeout:1e4})},ke=async(Ge,sr={})=>{let ir=sr&&typeof sr==="object"&&!Array.isArray(sr)?sr:{},lr,Fr="image/png";if(Buffer.isBuffer(Ge)||Ge instanceof Uint8Array)lr=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)))lr=Buffer.from(Ge.replace(/^data:[^,]*,/,""),"base64");else if(typeof Ge==="string"){let Zr=Ps(e.workspaceRoot,Ge);lr=Zr.buffer,Fr=Zr.mimeType}else throw Error("view() needs a Buffer, a base64 string, or a path to an image file");if(lr.length===0)throw Error("view(): the image is empty");let ln=String(ir.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),Gr=Number(ir.maxWidth)||1024,lt=Number(ir.quality)||72,Ft=e.targetContext?await le.newPage():await he.newPage();try{let Zr=`data:${Fr};base64,${lr.toString("base64")}`;for(let ur=0;ur<5;ur+=1){let Mr=await Ft.evaluate(async(Br)=>{let Wr=new Image;Wr.src=Br.url,await Wr.decode();let Qr=Math.min(1,Br.maxWidth/Wr.naturalWidth),Dr=document.createElement("canvas");Dr.width=Math.max(1,Math.round(Wr.naturalWidth*Qr)),Dr.height=Math.max(1,Math.round(Wr.naturalHeight*Qr));let Ar=Dr.getContext("2d");if(!Ar)throw Error("view(): canvas unavailable");return Ar.fillStyle="#ffffff",Ar.fillRect(0,0,Dr.width,Dr.height),Ar.drawImage(Wr,0,0,Dr.width,Dr.height),{data:Dr.toDataURL("image/jpeg",Br.q/100).split(",")[1]??"",width:Dr.width,height:Dr.height,sourceWidth:Wr.naturalWidth,sourceHeight:Wr.naturalHeight}},{url:Zr,maxWidth:Gr,q:lt}),ut=Buffer.from(Mr.data,"base64");if(ut.length<=xs){let Br=ln||"image";return`<<<ARA_VIEW_IMAGE ${Mr.data} image/jpeg ${Br}>>>
302
302
  Viewing ${Br} (${Mr.sourceWidth}x${Mr.sourceHeight} source, sent at ${Mr.width}x${Mr.height}, ${Math.round(ut.length/1024)}KB).`}if(Gr>640)Gr=Math.round(Gr*0.75);else lt=Math.max(30,lt-15)}throw Error(`view(): could not reduce the image under ${Math.round(xs/1024)}KB`)}finally{await Ft.close().catch(()=>{return})}},We=hs({browser:e.targetContext?.browser()??le,context:he,page:Le,a11y:Be,view:ke,readWorkspaceFile:(Ge)=>Ps(e.workspaceRoot,Ge),privateProfile:e.privateProfile,beforeNavigation:e.beforeNavigation,recording:e.recording,screenshotExport:e.screenshotExport,actionRecorder:()=>{let Ge=w,sr=S;return(ir,lr)=>{if(Ge.length<So)Ge.push(ir);if(lr)sr.page=lr}}}),nr=async(Ge)=>{z();let sr=be(await le.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await sr.route("**/*",(lr)=>lr.abort()),z(),await sr.routeWebSocket("**/*",(lr)=>lr.close({code:1008,reason:"Reason evaluator network denied"})),z(),await sr.exposeBinding("__araHandsRpc",async(lr,Fr)=>e.onBrowserOperation?e.onBrowserOperation(Ge,()=>We.dispatch(Fr)):We.dispatch(Fr)),z();let ir=await sr.newPage();return z(),await ir.goto("data:text/html,<title>Reason Hands evaluator</title>"),z(),await ir.evaluate(`(${is})(${JSON.stringify(We.roots)})`),{context:sr,page:ir,runId:Ge}}catch(ir){throw await fe(sr).catch(()=>{return}),ir}},or=await nr(),Pr={browser:le,context:he,page:Le,evaluator:or,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 nr(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")),gc)})]).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")),Os)})])}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 or=await Ke.evaluator.page.evaluate(`(${as})(${JSON.stringify({code:le})})`);if(typeof or!=="string")throw Error("hands_repl_invalid_evaluator_output");let Pr=Le.page;if(xe&&Pr&&!or.includes("<<<ARA_VIEW_IMAGE")){let Ge=()=>Ke.captureProgressFrame(Pr);try{let sr=await(e.onBrowserOperation?e.onBrowserOperation(he,Ge):Ge());return Le.automaticProgressImage=!0,`${or}
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-vdhgwmmp.js";import{execFileSync as b}from"child_process";import{mkdirSync as y,readdirSync as h,readFileSync as D,rmSync as f,statSync as k,writeFileSync as w}from"fs";import{join as p,sep as S}from"path";import{setTimeout as x}from"timers/promises";var L=3000,u=null;function g(e){return p(e,"users")}function xt(e){if(u?.root===e.root)return;let t=g(e.root);y(t,{recursive:!0,mode:448}),w(p(t,String(process.pid)),"",{mode:384}),u=e}function da(){if(!u)return;f(p(g(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}}function _(){let e=process.getuid?.();if(process.platform==="linux")return h("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(k(`/proc/${n}`).uid!==e)return[];let s=D(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return b(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let c=/^(\d+) (.+)$/.exec(s.trim());return c?[{pid:Number(c[1]),command:c[2]}]:[]});return b("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
3
- `).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function pa(){let e=u;if(!e)return{released:"unused",stopped:0};let t=g(e.root);f(p(t,String(process.pid)),{force:!0}),u=null;let n=!1;for(let o of h(t)){let i=Number(o);if(Number.isSafeInteger(i)&&i>0&&m(i))n=!0;else f(p(t,o),{force:!0})}if(n)return{released:"shared",stopped:0};let s=_().filter((o)=>o.pid!==process.pid&&(o.command.includes(`${e.root}${S}`)||o.command.includes(`${e.automation}${S}`)||o.command.includes(e.extensionDir))),c=(o,i)=>{try{process.kill(o,i)}catch{}};for(let o of s)c(o.pid,"SIGTERM");for(let o=Date.now()+L;Date.now()<o&&s.some((i)=>m(i.pid));)await new Promise((i)=>setTimeout(i,100));for(let o of s)if(m(o.pid))c(o.pid,"SIGKILL");return{released:"stopped",stopped:s.length}}var P=20000,E=30000,M=100,a=new Map,l=null,d=[];function Ni(e){a.set(e,(a.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(a.get(e)??1)-1;if(n>0){a.set(e,n);return}if(a.delete(e),l?.run===e)l.idleUntil=0}}function N(){return new r("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function O(e,t){return l!==null&&l.run!==e&&(l.calls>0||t<l.idleUntil)}async function Li(e,t,n=Date.now){let s=Symbol(e);d.push(s);try{let i=n()+E;for(;;){if(!O(e,n())&&(l?.run===e||d[0]===s))break;if(n()>=i)throw N();await x(M,void 0,{signal:t}).catch(()=>t.throwIfAborted())}}finally{d.splice(d.indexOf(s),1)}if(l?.run!==e)l={run:e,calls:0,idleUntil:0};let c=l;c.calls+=1;let o=!1;return()=>{if(o)return;o=!0,c.calls-=1,c.idleUntil=n()+P}}
4
- export{xt,da,pa,Ni,Li};
2
+ import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-vdhgwmmp.js";import{execFileSync as b}from"child_process";import{mkdirSync as y,readdirSync as h,readFileSync as D,rmSync as f,statSync as k,writeFileSync as w}from"fs";import{join as p,sep as S}from"path";import{setTimeout as x}from"timers/promises";var L=3000,u=null;function g(e){return p(e,"users")}function xt(e){if(u?.root===e.root)return;let t=g(e.root);y(t,{recursive:!0,mode:448}),w(p(t,String(process.pid)),"",{mode:384}),u=e}function ua(){if(!u)return;f(p(g(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}}function _(){let e=process.getuid?.();if(process.platform==="linux")return h("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(k(`/proc/${n}`).uid!==e)return[];let s=D(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return b(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let c=/^(\d+) (.+)$/.exec(s.trim());return c?[{pid:Number(c[1]),command:c[2]}]:[]});return b("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
3
+ `).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function da(){let e=u;if(!e)return{released:"unused",stopped:0};let t=g(e.root);f(p(t,String(process.pid)),{force:!0}),u=null;let n=!1;for(let o of h(t)){let i=Number(o);if(Number.isSafeInteger(i)&&i>0&&m(i))n=!0;else f(p(t,o),{force:!0})}if(n)return{released:"shared",stopped:0};let s=_().filter((o)=>o.pid!==process.pid&&(o.command.includes(`${e.root}${S}`)||o.command.includes(`${e.automation}${S}`)||o.command.includes(e.extensionDir))),c=(o,i)=>{try{process.kill(o,i)}catch{}};for(let o of s)c(o.pid,"SIGTERM");for(let o=Date.now()+L;Date.now()<o&&s.some((i)=>m(i.pid));)await new Promise((i)=>setTimeout(i,100));for(let o of s)if(m(o.pid))c(o.pid,"SIGKILL");return{released:"stopped",stopped:s.length}}var P=20000,E=30000,M=100,a=new Map,l=null,d=[];function Ni(e){a.set(e,(a.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(a.get(e)??1)-1;if(n>0){a.set(e,n);return}if(a.delete(e),l?.run===e)l.idleUntil=0}}function N(){return new r("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function O(e,t){return l!==null&&l.run!==e&&(l.calls>0||t<l.idleUntil)}async function Li(e,t,n=Date.now){let s=Symbol(e);d.push(s);try{let i=n()+E;for(;;){if(!O(e,n())&&(l?.run===e||d[0]===s))break;if(n()>=i)throw N();await x(M,void 0,{signal:t}).catch(()=>t.throwIfAborted())}}finally{d.splice(d.indexOf(s),1)}if(l?.run!==e)l={run:e,calls:0,idleUntil:0};let c=l;c.calls+=1;let o=!1;return()=>{if(o)return;o=!0,c.calls-=1,c.idleUntil=n()+P}}
4
+ export{xt,ua,da,Ni,Li};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,Di=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var he=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var as=(a,b)=>{for(var c in b)h(a,c,{get:b[c],enumerable:!0,configurable:!0,set:s.bind(b,c)})};var cs=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var e=import.meta.require;
3
- export{Di,he,as,cs,e};
2
+ var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,Di=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var he=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var ss=(a,b)=>{for(var c in b)h(a,c,{get:b[c],enumerable:!0,configurable:!0,set:s.bind(b,c)})};var as=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var e=import.meta.require;
3
+ export{Di,he,ss,as,e};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ge,ut}from"./vm-hands-entry-lite-jyvmw8b7.js";import{mt}from"./vm-hands-entry-lite-zz8yhajj.js";import{Ao,le,Gr,ft,Po}from"./vm-hands-entry-lite-gdzw92jk.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{a,tr}from"./vm-hands-entry-lite-cf1x5cbr.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var Rr=(e,t)=>{if(l)S(l);let s=O(e,Ao);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(tr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function po(e,t){return E(e)&&!U(e,t)}function ho(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Gr(t)??"unknown"}; this CLI is ${mt}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function Qo(e=a()){let t=ft(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=Po(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>Qo(),grants:(e)=>Ge(e),request:(e,t)=>ut(e,t),worker:async()=>(await import("./status-3mgfgra8.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Rr,restartConnection:async()=>(await import("./connect-cli-c5bmsf0p.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function es(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function Ms(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function $s(e,t){let s=t.host??V(),{io:n}=t,r=await es(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
2
+ import{Ge,ut}from"./vm-hands-entry-lite-jyvmw8b7.js";import{mt}from"./vm-hands-entry-lite-e508r607.js";import{Ao,le,Gr,ft,Po}from"./vm-hands-entry-lite-ye0pkbqd.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{a,tr}from"./vm-hands-entry-lite-cf1x5cbr.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var Rr=(e,t)=>{if(l)S(l);let s=O(e,Ao);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(tr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function po(e,t){return E(e)&&!U(e,t)}function ho(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Gr(t)??"unknown"}; this CLI is ${mt}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function Yo(e=a()){let t=ft(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=Po(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>Yo(),grants:(e)=>Ge(e),request:(e,t)=>ut(e,t),worker:async()=>(await import("./status-69b64z1g.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Rr,restartConnection:async()=>(await import("./connect-cli-hzad1rps.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function Qo(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function Ls(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function Ms(e,t){let s=t.host??V(),{io:n}=t,r=await Qo(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
3
3
  `),0;let c=!1,u=!1,d=s.identity();for(let o of i){let{label:p,pane:h}=k[o.id];if(o.id!=="disk"){if(d.state!=="ready"){if(!c)n.stderr.write(`Reason permissions: ${d.detail}
4
4
  `);c=!0;continue}let g=o.id;await s.request(d.prefix,g),s.open([h]);let I=s.tile(d.path,g);if(n.stdout.write(`Allow Reason in System Settings > Privacy & Security > ${p}.
5
5
  `),!t.wait)continue;if(n.stdout.write(`Waiting for it (Ctrl-C to stop)\u2026
@@ -11,4 +11,4 @@ import{Ge,ut}from"./vm-hands-entry-lite-jyvmw8b7.js";import{mt}from"./vm-hands-e
11
11
  `),await x(async()=>(await s.worker())?.full_disk_access==="granted",s))n.stdout.write(`Full Disk Access: granted.
12
12
  `);else n.stderr.write("Full Disk Access is not reported yet. If you allowed it, `reason connect` restarts the worker with it.\n"),c=!0}if(u)try{if(await s.restartConnection())n.stdout.write(`This computer's Reason connection restarted to use them.
13
13
  `)}catch(o){n.stderr.write(`This computer's Reason connection uses them after it restarts (\`reason connect\`): ${o instanceof Error?o.message:String(o)}
14
- `)}return c?1:0}export{Rr,po,ho,Qo,es,Ms,$s};
14
+ `)}return c?1:0}export{Rr,po,ho,Yo,Qo,Ls,Ms};