@reason-machines/cli-linux-x64 0.2.545 → 0.2.547

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 (40) hide show
  1. package/THIRD_PARTY_NOTICES.txt +2 -2
  2. package/bin/reason +1 -1
  3. package/bin/vm-hands/{api-credentials-ka0tgvfr.js → api-credentials-a67s65s1.js} +1 -1
  4. package/bin/vm-hands/{api-vct1jx91.js → api-qhsfyayr.js} +1 -1
  5. package/bin/vm-hands/{connect-cli-6pa06bp4.js → connect-cli-2jv8444d.js} +1 -1
  6. package/bin/vm-hands/{index-gmsadq51.js → index-j6wffzfd.js} +1 -1
  7. package/bin/vm-hands/{local-automation-nfmdd0bj.js → local-automation-gygsvq1s.js} +1 -1
  8. package/bin/vm-hands/{local-capabilities-9qs476nx.js → local-capabilities-npdrmmdc.js} +1 -1
  9. package/bin/vm-hands/{local-display-session-v6se296d.js → local-display-session-wtx6hhye.js} +1 -1
  10. package/bin/vm-hands/local-display-video-z0k1wtes.js +2 -0
  11. package/bin/vm-hands/{local-managed-process-j6dxwzsg.js → local-managed-process-fp93w0p7.js} +1 -1
  12. package/bin/vm-hands/{managed-runtime-g5ypgdzd.js → managed-runtime-2t9hvdz0.js} +1 -1
  13. package/bin/vm-hands/{permissions-nes7hvyb.js → permissions-ex4dv8fx.js} +1 -1
  14. package/bin/vm-hands/{serve-service-kr5ggkqy.js → serve-service-y73w7z0m.js} +1 -1
  15. package/bin/vm-hands/{status-gkdk2phq.js → status-yscg3sd0.js} +1 -1
  16. package/bin/vm-hands/version-0f9960eq.js +2 -0
  17. package/bin/vm-hands/{vm-hands-entry-lite-kng982rg.js → vm-hands-entry-lite-5tdbk4pq.js} +1 -1
  18. package/bin/vm-hands/{vm-hands-entry-lite-tpjqd8qx.js → vm-hands-entry-lite-63r581qe.js} +1 -1
  19. package/bin/vm-hands/{vm-hands-entry-lite-pfqj73fy.js → vm-hands-entry-lite-6bf97ret.js} +1 -1
  20. package/bin/vm-hands/{vm-hands-entry-lite-gz65ybc2.js → vm-hands-entry-lite-d2kj2jj0.js} +2 -2
  21. package/bin/vm-hands/vm-hands-entry-lite-d3rz0tgb.js +2 -0
  22. package/bin/vm-hands/{vm-hands-entry-lite-wb4fppse.js → vm-hands-entry-lite-d4n0wg5b.js} +1 -1
  23. package/bin/vm-hands/{vm-hands-entry-lite-ax1rvy38.js → vm-hands-entry-lite-dbae6y48.js} +1 -1
  24. package/bin/vm-hands/{vm-hands-entry-lite-sxs29kff.js → vm-hands-entry-lite-e71jtjxa.js} +1 -1
  25. package/bin/vm-hands/{vm-hands-entry-lite-eragp1xm.js → vm-hands-entry-lite-fw4y4xxg.js} +1 -1
  26. package/bin/vm-hands/{vm-hands-entry-lite-mbv4mqha.js → vm-hands-entry-lite-g89cjfan.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-x7w4n87s.js → vm-hands-entry-lite-j7e86nvy.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-1b3x8f9z.js → vm-hands-entry-lite-vn6zr7gp.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-8x8940ky.js → vm-hands-entry-lite-x3tgdvcf.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-8jcb5jqm.js → vm-hands-entry-lite-x7ks944h.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-p4z0dgch.js → vm-hands-entry-lite-zbwsn5rk.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-9r9tfka9.js → vm-hands-entry-lite-zjgrdarj.js} +1 -1
  33. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  34. package/bin/vm-hands/{vm-hands-executor-x1dympcw.js → vm-hands-executor-af6mwegq.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-op-runner-az83nsye.js → vm-hands-op-runner-wj99gtgs.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-runtime-wfp8q87s.js → vm-hands-runtime-a81sts1s.js} +3 -3
  37. package/package.json +1 -1
  38. package/bin/vm-hands/local-display-video-s2447446.js +0 -2
  39. package/bin/vm-hands/version-qtakrr9g.js +0 -2
  40. package/bin/vm-hands/vm-hands-entry-lite-r34f55z4.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Jt,j}from"./vm-hands-entry-lite-vj0gm694.js";import{ue,Ce,X,Ae,de,ir,et,Y,I,U,rn}from"./vm-hands-entry-lite-a0g6c3wr.js";import{Uo,ri}from"./vm-hands-entry-lite-4anjdcth.js";import{Io,P,Je,Se,Xe,ne,Ye,Vn,Ee,Qt,ae,H,N,ce,zr,qr,Kn}from"./vm-hands-entry-lite-hv3dxd5k.js";import{Pe,oe,pe,Z,Te,q,Q}from"./vm-hands-entry-lite-nxd394w3.js";import{Lt,Pr,lt,V,O,T,b,Cn}from"./vm-hands-entry-lite-4r1yn35v.js";import{Cr,Ar,xn,uo,Ue,kn}from"./vm-hands-entry-lite-5tnma5qb.js";import{K}from"./vm-hands-entry-lite-ct4mtq1m.js";import{ji}from"./vm-hands-entry-lite-xe0benev.js";import{p,ze,$t,ut,po,_e,we}from"./vm-hands-entry-lite-2hfrcr50.js";import{v,h,mo}from"./vm-hands-entry-lite-hfx1q0b0.js";import{E}from"./vm-hands-entry-lite-72nj66ab.js";import{tr}from"./vm-hands-entry-lite-9r9tfka9.js";import{a,zo,qo,ie,Vo}from"./vm-hands-entry-lite-jvszqt0z.js";import{L,$i,Mi,Yo,y,t,k,At,o,d,u,n,c,g,ee,s,i}from"./vm-hands-entry-lite-dszmx6yf.js";import{Fi}from"./vm-hands-entry-lite-pzj5s203.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Qo,se,Ui,C,Oe,$e,A}from"./vm-hands-entry-lite-b6gsggvp.js";var Ri=()=>{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,x=Yo(w.input),W=_[x]??x;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Mi(w.values[0])}`;return`Invalid option: expected one of ${$i(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",x=l(w.origin);if(x)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${x.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",x=l(w.origin);if(x)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${x.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":""}: ${$i(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((x)=>`'${x}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function gn(){return{localeError:Ri()}}L(gn());class mt extends Error{}function No(e){let l;try{l=new URL(e)}catch{throw new mt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new mt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new mt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new mt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new mt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as Oi}from"crypto";import{isAbsolute as Bo,join as jo,relative as Mo,resolve as qt,sep as Wo}from"path";var Vt=t().min(1).refine(Bo,"absolute path required"),Lo=c({version:i(1),apiOrigin:At(),channel:s(["staging","production"]),stateDirectory:Vt,workspaceRoot:Vt,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:i(Jt),url:t().refine((e)=>{try{return No(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Vt.optional()}).optional(),userChrome:d().optional(),cloudSessions:i(!0).optional(),localLogins:d().optional(),folders:u(Vt).min(1).max(31).optional()}),xi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[Lo,Lo.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!xi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Uo(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 jo(e.stateDirectory,`headless-${e.channel}`)}function je(e,l){if(Fr(l,e))return!1;return!Fr(e,l)||E(jo(Wo,Mo(qt(e),qt(l))))}function Fr(e,l){let f=Mo(qt(e),qt(l));return f===""||f!==".."&&!f.startsWith(`..${Wo}`)&&!Bo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...x}=e;return Oi("sha256").update(JSON.stringify(x)).digest("hex")}var Pi=4,Ii=[2375,2376,9222,9229];function mr(e){let l=new Set(Ii);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Ai=60000;function Fo(e){let l=new AbortController,f=new Map,_=(R)=>JSON.stringify([R.jobId,R.port]);function w(R){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||R.organization_id!==M.organization_id||R.user_id!==M.user_id||R.device_id!==M.device_id)Gr()}function S(R){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===R.generation&&M.binding.target_fence_id===R.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function x(R,M,G){let F=await W(R,M,G);if(F!=="moved")return F;let D=await W(R,M,G);return D==="moved"?null:D}async function W(R,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||R.expiresAtMs<=Date.now()||R.expiresAtMs>e.expiresAtMs)return null;let D=M.opened,re=D!==void 0&&F.generation>D.generation,J=S(F);if(re){if(J){if(J.revision<=D.revision||R.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==D.attachmentRevision||J.binding.root_grant_revision!==D.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>Ai)return null}else if(!J||R.expiresAtMs>Date.parse(J.expires_at)||D&&(F.generation!==D.generation||F.fenceId!==D.fenceId))return null;let z=await e.inspect(R.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},Re=re?D: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 Fe=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||!Re||!Fe)return null;if((Fe.snapshotId!==Re.snapshotId||Fe.revision!==Re.revision)&&(re||!e.environment.carried(Fe.snapshotId,Fe.revision)))return null;if(!D&&F.generation===R.generation&&F.fenceId===R.fenceId)M.opened={...Re,...Fe};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:Re.attachmentRevision,grantRevision:Re.grantRevision,generation:Re.generation,fenceId:Re.fenceId,jobId:z.job.jobId,port:R.port,expiresAtMs:R.expiresAtMs}}}catch{return null}}return{async open(R,M,G){w(M);let{binding:F,deviceRelayUrl:D}=ut(R);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(D).origin!==e.authority.relayOrigin)Gr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==D)Gr();if(await J.opened,!await $t(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:F}}if(f.size>=Pi)Gr();let z=new AbortController,fe={},ve=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>x(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 Re=_e({binding:F,deviceRelayUrl:D,port:ve,signal:z.signal}),Fe={binding:F,relay:D,abort:z,port:ve,opened:Re};f.set(re,Fe);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(qe),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await $t(()=>ve.check()))Gr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Gr()}},async close(R,M){w(M);let{binding:G}=po(R),F=f.get(_(G));if(!F||!ze(F.binding,G))Gr();return F.abort.abort(),await F.opened.then((D)=>D.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let R of f.values())R.abort.abort();f.clear()}}}import{WebSocket as Rn}from"ws";var $o=(e)=>("data"in e)?e.data.length:e.bytes,Ko=2*Ye;function ar(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var ht=(e)=>!["starting","running"].includes(e.state);function eo(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 x;try{x=new URL(e.relay_url)}catch{return ar("invalid_pty_request")}if(!["ws:","wss:"].includes(x.protocol)||x.username||x.password||x.hash||x.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(x.hostname))ar("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ar("invalid_pty_request");return{workspace:U(e.workspace)??ar("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:x.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Go(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ar("cancelled");let _=new Rn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},x=()=>{w.abort(),S()};e.signal.addEventListener("abort",x,{once:!0});let W=setTimeout(x,Math.max(1,l.leaseExpiresAtMs-Date.now())),R=[],M=0,G=0,F=0,D=!1,re=!1,J=!1,z,fe,ve,be=(le)=>{ve=new r(le,"Bound terminal input was refused."),x()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",x),_.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=R.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.data,xe]);else if(he)R.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,x();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");R.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Re(le){return Kn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function Fe(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(Re(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=Fe(he);if(xe.inputSequence!==G)ar("job_input_sequence");if(!ht(xe)&&xe.leaseExpiresAtMs<=Date.now())ar("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Rn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Ko)ar("pty_output_backpressure");_.send(le)}function We(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>Ko)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 De(){let le=AbortSignal.timeout(Qt),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 Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{x(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),D=!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",Re(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Re(z)}));let he=!1,xe=0,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=We(z);if(ht(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:Me,rows:rr}=z.pty;for(let or of[{cols:Me,rows:rr>1?rr-1:2},{cols:Me,rows:rr}]){if(ht(z))break;let Rr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Rr,...or}}),z.inputSequence!==Rr)ar("job_input_sequence")}continue}let ke=ht(z)||Ke?void 0:R.shift();if(ke){M-=$o(ke);let Me=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:ke.cols,rows:ke.rows}})}catch(rr){if(!(rr instanceof r)||rr.code!=="job_input_backpressure")throw rr;G-=1,R.unshift(ke),M+=$o(ke),Ke=!0;continue}if(z.inputSequence!==Me)ar("job_input_sequence")}else if(await new Promise((Me)=>{let rr=setTimeout(Me,Ke||!Be?10:50);if(S=()=>{clearTimeout(rr),Me()},w.signal.aborted||!Ke&&R.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ve??=le}finally{if(re=!1,R.length=0,clearTimeout(W),e.signal.removeEventListener("abort",x),x(),D&&(!z||!ht(z)))try{z=await De()}catch{z=void 0}try{if(!z||!ht(z)||z.pty?.cleanup!=="confirmed")ar("pty_cleanup_unconfirmed");let le=Re(z);if(_.readyState===Rn.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:Re(z)}}import{createHash as Ti,randomUUID as An}from"crypto";import{spawnSync as es}from"child_process";import{closeSync as Jo,constants as On,fstatSync as Di,fsyncSync as Ci,lstatSync as Ht,mkdirSync as Hi,mkdtempSync as rs,openSync as Xo,readFileSync as Ni,readdirSync as ts,realpathSync as Vr,rmSync as Pn,unlinkSync as Li}from"fs";import{createConnection as Bi}from"net";import{dirname as Wi,join as ot,sep as In}from"path";import{tmpdir as ns}from"os";var hr=new Map,Jr=new Map;function Ur(e,l){return Ti("sha256").update(JSON.stringify([e,l])).digest("hex")}function gt(e){try{Hi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Ht(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Vr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function zi(e){let l;try{l=Ht(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||ts(e).length>0}function Ki(e){if(process.platform==="win32")return Ui();let l=e.map((f)=>{try{return Vr(f)}catch{return f}});for(let f of[()=>Ui(),()=>Vr("/dev/shm"),()=>Vr(ns())]){let _;try{_=f()}catch{continue}if(!l.some((w)=>_===w||_.startsWith(w.endsWith(In)?w:w+In)))return _}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function gr(e){let l=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((x)=>zi(ot(x,"jobs",l.slice(0,16))))??e.runtimeDirectory;gt(f);let _=ot(f,"jobs");gt(_);let w=ot(_,l.slice(0,16));if(e.maxScopes!==void 0){let x=ts(_);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||x.length>e.maxScopes||!x.includes(l.slice(0,16))&&x.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.")}gt(w);let S=rs(ot(Ki(e.folders??[]),"reason-j-"));try{return gt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:ot(S,"control.sock"),disposeSocket:()=>Pn(S,{recursive:!0,force:!0})}}catch(x){throw Pn(S,{recursive:!0,force:!0}),x}}var Gi=60000,Ji=5000;function Vi(e){if(process.platform==="win32")return qi(e);let l=es("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 qi(e){let l=es(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Oe()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function os(e,l={}){let f=ot(e.journalDirectory,"owner.lock"),_;try{_=Xo(f,On.O_RDONLY|On.O_NOFOLLOW)}catch{return null}try{let w=Di(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Ni(_,"utf8"))}catch{}let x;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Gi)return null;x={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:D,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof D!=="number"||!Number.isSafeInteger(D))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))x={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Vi)(F);if(z===null||z<=D+Ji)return null;x={reason:"pid_reused",executorLaunchId:re}}}let W=Ht(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Li(f);let R=Xo(e.journalDirectory,On.O_RDONLY);try{Ci(R)}finally{Jo(R)}return x}catch{return null}finally{Jo(_)}}function ss(e){let l={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},f=Ur(l.root,l.runId);if(hr.has(f)||l.operationId!==void 0&&Jr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Fo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>hr.get(_.key)===_,identity:()=>{try{return bt(l)}catch{return null}},inspect:(w,S)=>{if(hr.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return is(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(hr.set(f,_),l.operationId!==void 0)Jr.set(l.operationId,_);return()=>{if(hr.get(_.key)===_)hr.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Yi=5000,Xi=20;async function to(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!H(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Yi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=bt(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((x)=>setTimeout(x,Xi))}if(Jr.get(e.operationId)!==f||hr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(e.root,e.runId);if(f.key===_)return;if(hr.has(_))l("The taking run already has a live Hands job supervisor.");hr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,hr.set(_,f)}function at(e){let l="operationId"in e?Jr.get(e.operationId):hr.get(Ur(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function ro(e){let l=hr.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function no(e){let l=hr.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function io(e){let l=Ur(e.root,e.runId),f=hr.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,x=_?.environment,W=e.owner&&{...e.owner},R=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!_||!S||!x||!W||!R||!_.workspace)return M();let G=Object.freeze({..._.workspace}),F=bt(_),D=x.current(),re=()=>{if(hr.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||I(e.workspace)!==I(G))M();let z=bt(_),fe=x.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!==D.snapshot_id||fe.revision!==D.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||R.device_id!==e.deviceId||R.binding!==fe.binding.kind||R.target_revision!==fe.binding.target_revision||R.root_grant_revision!==fe.binding.root_grant_revision||R.target_generation!==F.generation||R.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 Go({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(D.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:D.revision,snapshotId:D.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:D.binding.kind,targetRevision:D.binding.target_revision,rootGrantRevision:D.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>_r(F,zr(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 oo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=hr.get(Ur(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return is(l,e.payload,e.signal)}var Zi=1e4,Qi=20,ea=Se/2,ra=Je/2,ta=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function is(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||_>Zi))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=bt(e);return _r(G,zr(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:An()})),f)},x=await S(w);if(_===void 0)return x;let W=Date.now()+_,R=x;while(R.ok&&["starting","running"].includes(R.job.state)&&R.job.output.length<ea&&ta(R.job)<ra&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Qi,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;R=M}catch{break}}return R}function bt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!H(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 _r(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Bi(e.socketPath),x="",W=!1,R,M=(F,D)=>{if(W)return;if(W=!0,clearTimeout(R),f.removeEventListener("abort",G),S.destroy(),F)w(F);else _(D)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),R=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{Jt,j}from"./vm-hands-entry-lite-vj0gm694.js";import{ue,Ce,X,Ae,de,ir,et,Y,I,U,rn}from"./vm-hands-entry-lite-a0g6c3wr.js";import{Uo,ri}from"./vm-hands-entry-lite-4anjdcth.js";import{Io,P,Je,Se,Xe,ne,Ye,Vn,Ee,Qt,ae,H,N,ce,zr,qr,Kn}from"./vm-hands-entry-lite-hv3dxd5k.js";import{Pe,oe,pe,Z,Te,q,Q}from"./vm-hands-entry-lite-nxd394w3.js";import{Lt,Pr,lt,V,O,T,b,Cn}from"./vm-hands-entry-lite-4r1yn35v.js";import{Cr,Ar,xn,uo,Ue,kn}from"./vm-hands-entry-lite-5tnma5qb.js";import{K}from"./vm-hands-entry-lite-ct4mtq1m.js";import{ji}from"./vm-hands-entry-lite-xe0benev.js";import{p,ze,$t,ut,po,_e,we}from"./vm-hands-entry-lite-2hfrcr50.js";import{v,h,mo}from"./vm-hands-entry-lite-hfx1q0b0.js";import{E}from"./vm-hands-entry-lite-72nj66ab.js";import{tr}from"./vm-hands-entry-lite-zjgrdarj.js";import{a,zo,qo,ie,Vo}from"./vm-hands-entry-lite-jvszqt0z.js";import{L,$i,Mi,Yo,y,t,k,At,o,d,u,n,c,g,ee,s,i}from"./vm-hands-entry-lite-dszmx6yf.js";import{Fi}from"./vm-hands-entry-lite-pzj5s203.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Qo,se,Ui,C,Oe,$e,A}from"./vm-hands-entry-lite-b6gsggvp.js";var Ri=()=>{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,x=Yo(w.input),W=_[x]??x;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Mi(w.values[0])}`;return`Invalid option: expected one of ${$i(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",x=l(w.origin);if(x)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${x.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",x=l(w.origin);if(x)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${x.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":""}: ${$i(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((x)=>`'${x}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function gn(){return{localeError:Ri()}}L(gn());class mt extends Error{}function No(e){let l;try{l=new URL(e)}catch{throw new mt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new mt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new mt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new mt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new mt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as Oi}from"crypto";import{isAbsolute as Bo,join as jo,relative as Mo,resolve as qt,sep as Wo}from"path";var Vt=t().min(1).refine(Bo,"absolute path required"),Lo=c({version:i(1),apiOrigin:At(),channel:s(["staging","production"]),stateDirectory:Vt,workspaceRoot:Vt,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:i(Jt),url:t().refine((e)=>{try{return No(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Vt.optional()}).optional(),userChrome:d().optional(),cloudSessions:i(!0).optional(),localLogins:d().optional(),folders:u(Vt).min(1).max(31).optional()}),xi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[Lo,Lo.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!xi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Uo(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 jo(e.stateDirectory,`headless-${e.channel}`)}function je(e,l){if(Fr(l,e))return!1;return!Fr(e,l)||E(jo(Wo,Mo(qt(e),qt(l))))}function Fr(e,l){let f=Mo(qt(e),qt(l));return f===""||f!==".."&&!f.startsWith(`..${Wo}`)&&!Bo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...x}=e;return Oi("sha256").update(JSON.stringify(x)).digest("hex")}var Pi=4,Ii=[2375,2376,9222,9229];function mr(e){let l=new Set(Ii);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Ai=60000;function Fo(e){let l=new AbortController,f=new Map,_=(R)=>JSON.stringify([R.jobId,R.port]);function w(R){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||R.organization_id!==M.organization_id||R.user_id!==M.user_id||R.device_id!==M.device_id)Gr()}function S(R){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===R.generation&&M.binding.target_fence_id===R.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function x(R,M,G){let F=await W(R,M,G);if(F!=="moved")return F;let D=await W(R,M,G);return D==="moved"?null:D}async function W(R,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||R.expiresAtMs<=Date.now()||R.expiresAtMs>e.expiresAtMs)return null;let D=M.opened,re=D!==void 0&&F.generation>D.generation,J=S(F);if(re){if(J){if(J.revision<=D.revision||R.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==D.attachmentRevision||J.binding.root_grant_revision!==D.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>Ai)return null}else if(!J||R.expiresAtMs>Date.parse(J.expires_at)||D&&(F.generation!==D.generation||F.fenceId!==D.fenceId))return null;let z=await e.inspect(R.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},Re=re?D: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 Fe=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||!Re||!Fe)return null;if((Fe.snapshotId!==Re.snapshotId||Fe.revision!==Re.revision)&&(re||!e.environment.carried(Fe.snapshotId,Fe.revision)))return null;if(!D&&F.generation===R.generation&&F.fenceId===R.fenceId)M.opened={...Re,...Fe};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:Re.attachmentRevision,grantRevision:Re.grantRevision,generation:Re.generation,fenceId:Re.fenceId,jobId:z.job.jobId,port:R.port,expiresAtMs:R.expiresAtMs}}}catch{return null}}return{async open(R,M,G){w(M);let{binding:F,deviceRelayUrl:D}=ut(R);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(D).origin!==e.authority.relayOrigin)Gr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==D)Gr();if(await J.opened,!await $t(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:F}}if(f.size>=Pi)Gr();let z=new AbortController,fe={},ve=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>x(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 Re=_e({binding:F,deviceRelayUrl:D,port:ve,signal:z.signal}),Fe={binding:F,relay:D,abort:z,port:ve,opened:Re};f.set(re,Fe);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(qe),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await $t(()=>ve.check()))Gr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Gr()}},async close(R,M){w(M);let{binding:G}=po(R),F=f.get(_(G));if(!F||!ze(F.binding,G))Gr();return F.abort.abort(),await F.opened.then((D)=>D.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let R of f.values())R.abort.abort();f.clear()}}}import{WebSocket as Rn}from"ws";var $o=(e)=>("data"in e)?e.data.length:e.bytes,Ko=2*Ye;function ar(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var ht=(e)=>!["starting","running"].includes(e.state);function eo(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 x;try{x=new URL(e.relay_url)}catch{return ar("invalid_pty_request")}if(!["ws:","wss:"].includes(x.protocol)||x.username||x.password||x.hash||x.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(x.hostname))ar("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ar("invalid_pty_request");return{workspace:U(e.workspace)??ar("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:x.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Go(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ar("cancelled");let _=new Rn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},x=()=>{w.abort(),S()};e.signal.addEventListener("abort",x,{once:!0});let W=setTimeout(x,Math.max(1,l.leaseExpiresAtMs-Date.now())),R=[],M=0,G=0,F=0,D=!1,re=!1,J=!1,z,fe,ve,be=(le)=>{ve=new r(le,"Bound terminal input was refused."),x()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",x),_.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=R.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.data,xe]);else if(he)R.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,x();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");R.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Re(le){return Kn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function Fe(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(Re(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=Fe(he);if(xe.inputSequence!==G)ar("job_input_sequence");if(!ht(xe)&&xe.leaseExpiresAtMs<=Date.now())ar("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Rn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Ko)ar("pty_output_backpressure");_.send(le)}function We(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>Ko)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 De(){let le=AbortSignal.timeout(Qt),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 Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{x(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),D=!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",Re(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Re(z)}));let he=!1,xe=0,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=We(z);if(ht(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:Me,rows:rr}=z.pty;for(let or of[{cols:Me,rows:rr>1?rr-1:2},{cols:Me,rows:rr}]){if(ht(z))break;let Rr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Rr,...or}}),z.inputSequence!==Rr)ar("job_input_sequence")}continue}let ke=ht(z)||Ke?void 0:R.shift();if(ke){M-=$o(ke);let Me=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:ke.cols,rows:ke.rows}})}catch(rr){if(!(rr instanceof r)||rr.code!=="job_input_backpressure")throw rr;G-=1,R.unshift(ke),M+=$o(ke),Ke=!0;continue}if(z.inputSequence!==Me)ar("job_input_sequence")}else if(await new Promise((Me)=>{let rr=setTimeout(Me,Ke||!Be?10:50);if(S=()=>{clearTimeout(rr),Me()},w.signal.aborted||!Ke&&R.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ve??=le}finally{if(re=!1,R.length=0,clearTimeout(W),e.signal.removeEventListener("abort",x),x(),D&&(!z||!ht(z)))try{z=await De()}catch{z=void 0}try{if(!z||!ht(z)||z.pty?.cleanup!=="confirmed")ar("pty_cleanup_unconfirmed");let le=Re(z);if(_.readyState===Rn.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:Re(z)}}import{createHash as Ti,randomUUID as An}from"crypto";import{spawnSync as es}from"child_process";import{closeSync as Jo,constants as On,fstatSync as Di,fsyncSync as Ci,lstatSync as Ht,mkdirSync as Hi,mkdtempSync as rs,openSync as Xo,readFileSync as Ni,readdirSync as ts,realpathSync as Vr,rmSync as Pn,unlinkSync as Li}from"fs";import{createConnection as Bi}from"net";import{dirname as Wi,join as ot,sep as In}from"path";import{tmpdir as ns}from"os";var hr=new Map,Jr=new Map;function Ur(e,l){return Ti("sha256").update(JSON.stringify([e,l])).digest("hex")}function gt(e){try{Hi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Ht(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Vr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function zi(e){let l;try{l=Ht(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||ts(e).length>0}function Ki(e){if(process.platform==="win32")return Ui();let l=e.map((f)=>{try{return Vr(f)}catch{return f}});for(let f of[()=>Ui(),()=>Vr("/dev/shm"),()=>Vr(ns())]){let _;try{_=f()}catch{continue}if(!l.some((w)=>_===w||_.startsWith(w.endsWith(In)?w:w+In)))return _}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function gr(e){let l=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((x)=>zi(ot(x,"jobs",l.slice(0,16))))??e.runtimeDirectory;gt(f);let _=ot(f,"jobs");gt(_);let w=ot(_,l.slice(0,16));if(e.maxScopes!==void 0){let x=ts(_);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||x.length>e.maxScopes||!x.includes(l.slice(0,16))&&x.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.")}gt(w);let S=rs(ot(Ki(e.folders??[]),"reason-j-"));try{return gt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:ot(S,"control.sock"),disposeSocket:()=>Pn(S,{recursive:!0,force:!0})}}catch(x){throw Pn(S,{recursive:!0,force:!0}),x}}var Gi=60000,Ji=5000;function Vi(e){if(process.platform==="win32")return qi(e);let l=es("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 qi(e){let l=es(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Oe()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function os(e,l={}){let f=ot(e.journalDirectory,"owner.lock"),_;try{_=Xo(f,On.O_RDONLY|On.O_NOFOLLOW)}catch{return null}try{let w=Di(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Ni(_,"utf8"))}catch{}let x;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Gi)return null;x={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:D,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof D!=="number"||!Number.isSafeInteger(D))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))x={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Vi)(F);if(z===null||z<=D+Ji)return null;x={reason:"pid_reused",executorLaunchId:re}}}let W=Ht(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Li(f);let R=Xo(e.journalDirectory,On.O_RDONLY);try{Ci(R)}finally{Jo(R)}return x}catch{return null}finally{Jo(_)}}function ss(e){let l={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},f=Ur(l.root,l.runId);if(hr.has(f)||l.operationId!==void 0&&Jr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Fo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>hr.get(_.key)===_,identity:()=>{try{return bt(l)}catch{return null}},inspect:(w,S)=>{if(hr.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return is(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(hr.set(f,_),l.operationId!==void 0)Jr.set(l.operationId,_);return()=>{if(hr.get(_.key)===_)hr.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Yi=5000,Xi=20;async function to(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!H(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Yi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=bt(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((x)=>setTimeout(x,Xi))}if(Jr.get(e.operationId)!==f||hr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(e.root,e.runId);if(f.key===_)return;if(hr.has(_))l("The taking run already has a live Hands job supervisor.");hr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,hr.set(_,f)}function at(e){let l="operationId"in e?Jr.get(e.operationId):hr.get(Ur(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function ro(e){let l=hr.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function no(e){let l=hr.get(Ur(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function io(e){let l=Ur(e.root,e.runId),f=hr.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,x=_?.environment,W=e.owner&&{...e.owner},R=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!_||!S||!x||!W||!R||!_.workspace)return M();let G=Object.freeze({..._.workspace}),F=bt(_),D=x.current(),re=()=>{if(hr.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||I(e.workspace)!==I(G))M();let z=bt(_),fe=x.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!==D.snapshot_id||fe.revision!==D.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||R.device_id!==e.deviceId||R.binding!==fe.binding.kind||R.target_revision!==fe.binding.target_revision||R.root_grant_revision!==fe.binding.root_grant_revision||R.target_generation!==F.generation||R.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 Go({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(D.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:D.revision,snapshotId:D.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:D.binding.kind,targetRevision:D.binding.target_revision,rootGrantRevision:D.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>_r(F,zr(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 oo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=hr.get(Ur(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return is(l,e.payload,e.signal)}var Zi=1e4,Qi=20,ea=Se/2,ra=Je/2,ta=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function is(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||_>Zi))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=bt(e);return _r(G,zr(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:An()})),f)},x=await S(w);if(_===void 0)return x;let W=Date.now()+_,R=x;while(R.ok&&["starting","running"].includes(R.job.state)&&R.job.output.length<ea&&ta(R.job)<ra&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Qi,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;R=M}catch{break}}return R}function bt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!H(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 _r(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Bi(e.socketPath),x="",W=!1,R,M=(F,D)=>{if(W)return;if(W=!0,clearTimeout(R),f.removeEventListener("abort",G),S.destroy(),F)w(F);else _(D)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),R=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(x+=F,Buffer.byteLength(x)>Xe)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=qr(x.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 Zo(e){let l=Vr(e.root),f=e.authority,_=Date.parse(e.leaseUntil),w=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(_)||_<=Date.now())throw Error("local_device_gh_lease_expired")};if(w(),f.readOnly&&f.generation===null)return{root:l,readOnly:!0,signal:e.signal,deadlineMs:_,assertCurrent:w};let S=Ur(l,e.runId),x=hr.get(S),W=x?.binding;if(!W?.environment||!W.workspace||W.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let R=W.environment.current(),M=()=>{w();let F=W.environment.current(),D=bt(W);if(hr.get(S)!==x||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||D.generation!==f.generation||D.fenceId!==f.fenceId||F.snapshot_id!==R.snapshot_id||F.revision!==R.revision)throw Error("local_device_gh_authority_changed")};M();let G=ie(l,W.workspace);return{root:G.boundary,signal:e.signal,deadlineMs:_,privateDirectory:Wi(W.environment.path),repoPath:G.path,readOnly:f.readOnly,forbiddenSecretValues:Object.values(R.variables),secretNames:(F)=>Object.entries(R.variables).filter(([,D])=>D.trim()===F.trim()).map(([D])=>`variable ${D}`),assertCurrent:M}}async function so(e,l){let f=Pe.parse(e.request),_=oe.parse(e.authority);if(_.contributorRefresh&&f.kind==="read"&&_.readOnly)return l(Zo(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(Zo(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=Vr(e.root),x=Ht(S),W=Date.parse(e.leaseUntil);if(!Number.isFinite(W)||W<=Date.now())throw Error("local_device_gh_lease_expired");let R=Vr(ns());if(R===S||R.startsWith(S+In))throw Error("local_device_gh_private_scope_unavailable");let M=rs(ot(R,"reason-gh-merge-"));try{gt(M);let G=()=>{if(e.signal.throwIfAborted(),Date.now()>=W)throw Error("local_device_gh_lease_expired");let F=Ht(e.root);if(F.isSymbolicLink()||F.dev!==x.dev||F.ino!==x.ino||Vr(e.root)!==S)throw Error("local_device_gh_authority_changed");gt(M)};return G(),await l({root:S,readOnly:!1,privateDirectory:M,forbiddenSecretValues:[],signal:e.signal,deadlineMs:W,assertCurrent:G})}finally{Pn(M,{recursive:!0,force:!0})}}var ds=43200000;function wt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function as(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function cs(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function ao(e){if(!as(e)||!cs(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"||wt(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(!as(f)||!cs(f,["kind","status","sha256","observed_at_ms"])||f.observed_at_ms!==null&&(typeof f.observed_at_ms!=="number"||wt(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()}),ls=new RegExp(lt.tokenPattern),na=c({token_url:At().max(2048),request_token:t().min(1).max(8192).regex(ls),aws_credentials_url:At().max(2048).nullable()});function us(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(!ls.test(e.request_token)||!f(e.token_url,lt.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,lt.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 fs(e){return new TextEncoder().encode(e).byteLength}function oa(e){return fs(JSON.stringify(e)+`
4
4
  `)}var yr=c({version:i(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(Lt),t().refine((e)=>!e.includes("\x00")&&fs(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:i("local_gh").optional(),git:c({base_url:At().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:na.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>oa(e)<=V.snapshotBytes,"snapshot too large");import{spawn as sa}from"child_process";import{basename as ia,isAbsolute as Iu}from"path";var aa=0,ps=120000,_s=15000,ca=65536;function Dn(e=process.execPath,l=process.argv[1]){let f=ia(e),_=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:_?[l]:[]}}function co(e={}){let{command:l,prefix:f}=Dn(e.executablePath,e.sourceEntrypoint),_=e.spawnProcess??sa,w=e.now??Date.now,S=null,x=0,W=!1,R=(G)=>{try{G.kill("SIGKILL")}catch{}},M=()=>{if(W)return;if(S&&w()-x<ps-_s)return;if(S){let F=S;S=null,R(F)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(aa)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}S=G,x=w(),G.on("error",()=>{if(S===G)S=null}),G.once("exit",(F,D)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:F,exit_signal:D})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:M,take(G){let F=S;if(!F||W)return null;let D=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((Re,Fe)=>G.args[Fe]!==Re)||typeof D!=="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:D,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Re)=>typeof Re[1]==="string"))},be=JSON.stringify(ve);if(F.exitCode!==null||F.signalCode!==null||!fe||fe.destroyed||w()-x>=ps-_s||Buffer.byteLength(be,"utf8")>ca)return R(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)R(S);S=null}}}import{accessSync as _a,constants as ma,statSync as ha}from"fs";import{homedir as ga,tmpdir as ba,userInfo as wa}from"os";import{delimiter as ya,win32 as va}from"path";var da=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 la=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],ua=new Set(["BUN_INSTALL"]);var fa=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function pa(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>fa.test(l.replaceAll("_","-")))}function ms(e){return Object.keys(e).filter((l)=>da.has(l)&&!(l==="NODE_OPTIONS"&&pa(e[l]))||la.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!ua.has(l)).sort()}var ka=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),Sa=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,Ea=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,Ra=/^[A-Za-z_][A-Za-z0-9_]*$/;function wr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?va.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(ms(e)),_=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,x]=w;return typeof x==="string"&&x.length<=32768&&!x.includes("\x00")&&S.length<=128&&Ra.test(S)&&!f.has(S)&&!ka.has(S)&&!Sa.test(S)&&!Ea.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||ga()),path:((w)=>process.platform==="win32"?kn(w):w)(Ar(e.PATH??"").join(ya)||Cr),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||ba()),variables:_}}function br(e=process.env,l=()=>wa().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return _a(w,ma.X_OK),ha(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 Oa}from"fs/promises";var xa=15000;function wn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function bn(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 restart the Reason app or worker on this Mac and try again: until it restarts it keeps the earlier refusal.")}async function hs(e,{timeoutMs:l=xa,open:f=(_)=>Oa(_)}={}){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(wn(S))throw bn(e);if(S instanceof r)throw S}finally{clearTimeout(_)}}import{chmodSync as sc,closeSync as ic,constants as zn,fstatSync as ac,lstatSync as Ns,openSync as cc,readSync as dc,realpathSync as $n,unlinkSync as lc}from"fs";import{lookup as uc}from"dns/promises";import{createRequire as fc}from"module";import{request as pc}from"http";import{request as _c}from"https";import it from"net";import{platform as Ws}from"os";import{basename as mc,extname as hc,isAbsolute as Ls,relative as Gn,resolve as kt,sep as Jn}from"path";var gs=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 yt}from"buffer";import{randomUUID as Pa}from"crypto";class ks 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 Ss=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),ws=/^hands_[A-Za-z0-9_-]{8,128}$/,Ia=2048,Es=32,Rs=1e4,Aa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function Ta(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 Da=(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))}},Os={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 ks(e)}function Dr(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let l=Object.getPrototypeOf(e);return l===Object.prototype||l===null}function vt(e,l=0,f={nodes:0}){if(l>Es||++f.nodes>Rs)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)vt(_,l+1,f);return}if(!Dr(e))Ie("hands_repl_invalid_json");for(let[_,w]of Object.entries(e)){if(Ss.has(_))Ie("hands_repl_invalid_json");vt(w,l+1,f)}}function Hn(e){return typeof e==="string"&&Object.hasOwn(Os,e)}function Ca(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Hn(l)?l:null}function ys(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Ha(e){return Dr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function vs(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function Yr(e){return!!e&&typeof e==="object"}function Yt(){return Object.freeze({$handsRepl:"undefined"})}function Na(e){if(!yt.isBuffer(e)&&!(e instanceof Uint8Array))Ie("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:yt.from(e).toString("base64")})}function xs(e){if(!Yr(e.browser)||!Yr(e.context)||!Yr(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??Ia;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,_=new WeakMap,w=e.createOpaqueId??Pa,S=(D,re)=>{if(!Yr(re))Ie("hands_repl_expected_target");let J=_.get(re)?.get(D);if(J)return J;if(f.size>=l)Ie("hands_repl_handle_limit");let z="";for(let be=0;be<16;be+=1){let Re=`hands_${w()}`;if(ws.test(Re)&&!f.has(Re)){z=Re;break}}if(!z)Ie("hands_repl_invalid_opaque_id");let fe=Object.freeze({$handsRepl:"handle",id:z,kind:D});f.set(z,{kind:D,target:re});let ve=_.get(re);if(!ve)ve=new Map,_.set(re,ve);return ve.set(D,fe),fe},x=Object.freeze({browser:S("browser",e.browser),context:S("context",e.context),page:S("page",e.page)}),W=(D)=>{if(!Dr(D)||Object.keys(D).length!==3||D.$handsRepl!=="handle"||typeof D.id!=="string"||!ws.test(D.id)||!Hn(D.kind))Ie("hands_repl_invalid_handle");let re=f.get(D.id);if(!re||re.kind!==D.kind)Ie("hands_repl_unknown_handle");return re},R=(D,re=0,J=new Set)=>{if(re>Es)Ie("hands_repl_json_too_complex");if(D===void 0)return Yt();if(D===null||typeof D==="boolean"||typeof D==="string")return D;if(typeof D==="number"){if(!Number.isFinite(D))Ie("hands_repl_non_json_result");return D}if(Array.isArray(D)){if(J.has(D))Ie("hands_repl_cyclic_result");J.add(D);try{return D.map((z)=>R(z,re+1,J))}finally{J.delete(D)}}if(!Dr(D))Ie("hands_repl_non_json_result");if(J.has(D))Ie("hands_repl_cyclic_result");J.add(D);try{let z=Object.create(null);for(let fe of Object.keys(D)){let ve=Object.getOwnPropertyDescriptor(D,fe);if(!ve||!("value"in ve))continue;z[fe]=R(ve.value,re+1,J)}return z}finally{J.delete(D)}},M=(D,re)=>{if(re==="void")return Yt();if(re==="json")return R(D);if(re==="bytes")return Na(D);let J=Ca(re);if(J){if(!Array.isArray(D))Ie("hands_repl_expected_target_list");if(J==="context"&&D.some((z)=>z!==e.context))Ie("hands_repl_foreign_context");return D.map((z)=>S(J,z))}if(D===null||D===void 0)return Yt();if(!Hn(re))Ie("hands_repl_invalid_return_kind");if(re==="context"&&D!==e.context)Ie("hands_repl_foreign_context");return S(re,D)},G=(D)=>{if(Dr(D)&&D.$handsRepl==="handle")return W(D).target;if(ys(D))return yt.from(D.base64,"base64");if(Ha(D))return;if(vs(D))Ie("hands_repl_route_fulfill_only");if(Array.isArray(D))return D.map(G);if(!Dr(D))return D;let re=Object.create(null);for(let[J,z]of Object.entries(D))re[J]=G(z);return re};return Object.freeze({roots:x,dispatch:async(D)=>{if(!Dr(D)||typeof D.type!=="string")Ie("hands_repl_invalid_request");if(D.type==="a11y"){let ye=D.target===void 0?f.get(x.page.id):W(D.target);if(!ye||ye.kind!=="page"&&ye.kind!=="locator")Ie("hands_repl_invalid_a11y_target");return R(await e.a11y(ye.target))}if(D.type==="view"){if(vt(D.source),D.options!==void 0)vt(D.options);let ye=ys(D.source)?yt.from(D.source.base64,"base64"):D.source;if(e.privateProfile&&!yt.isBuffer(ye))Ie("hands_repl_profile_requires_image_bytes");return R(await e.view(ye,D.options))}if(D.type!=="call")Ie("hands_repl_invalid_request");if(typeof D.method!=="string"||D.method.length===0||D.method.length>128)Ie("hands_repl_invalid_method");if(Ss.has(D.method))Ie("hands_repl_forbidden_method");let re=W(D.target),J=D.args??[];if(!Array.isArray(J))Ie("hands_repl_invalid_arguments");if(vt(J),re.kind==="page"&&D.method==="captureScreenshot"){if(J.length!==0)Ie("hands_repl_invalid_arguments");if(!e.screenshotExport)Ie("hands_repl_screenshot_export_unavailable");return R(await e.screenshotExport(re.target))}if(re.kind==="context"&&["startRecording","stopRecording"].includes(D.method)){if(!e.recording||re.target!==e.context)Ie("hands_repl_recording_unavailable");if(J.length>(D.method==="startRecording"?1:0))Ie("hands_repl_invalid_arguments");return R(D.method==="startRecording"?await e.recording.start(J[0]):await e.recording.stop())}if(e.privateProfile){let ye=D.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(ye)||re.kind==="browser"&&ye==="close"||re.kind==="context"&&ye==="close")Ie("hands_repl_private_profile_method_denied");if(re.kind==="browser"&&ye==="contexts")return M([e.context],"context[]");if((ye==="screenshot"||ye==="pdf")&&Dr(J[0])&&(("path"in J[0])||("style"in J[0])))Ie("hands_repl_private_profile_path_denied");if(ye==="goto"){if(typeof J[0]!=="string")Ie("hands_repl_private_profile_url_denied");try{let We=new URL(J[0]);if(!["http:","https:"].includes(We.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"||!Aa.has(J[0].toLowerCase())))Ie("hands_repl_private_profile_attribute_denied");if(re.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(ye)){let We=[re.target];if(ye==="allInnerTexts"){let Ve=Reflect.get(re.target,"all");if(typeof Ve!=="function")Ie("hands_repl_private_profile_probe_unavailable");let De=await Reflect.apply(Ve,re.target,[]);if(!Array.isArray(De)||De.length>Rs||!De.every(Yr))Ie("hands_repl_private_profile_probe_unavailable");We=De}for(let Ve of We){let De=Reflect.get(Ve,"isVisible");if(typeof De!=="function"||!await Reflect.apply(De,Ve,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}if(ye==="press"&&typeof J[0]==="string"&&Ta(J[0]))Ie("hands_repl_private_profile_browser_shortcut_denied");if(re.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(ye)){let We=Reflect.get(re.target,"evaluate");if(typeof We!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Ve=await Reflect.apply(We,re.target,[Da]);if(!Dr(Ve)||typeof Ve.password!=="boolean"||typeof Ve.executableLink!=="boolean")Ie("hands_repl_private_profile_probe_unavailable");if(ye==="inputValue"&&Ve.password)Ie("hands_repl_private_profile_password_denied");if(ye!=="inputValue"&&Ve.executableLink)Ie("hands_repl_private_profile_url_denied");if(ye==="inputValue"){let De=Reflect.get(re.target,"isVisible");if(typeof De!=="function"||!await Reflect.apply(De,re.target,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}}let z=Os[re.kind][D.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"&&D.method==="contexts")return[x.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(D.method)&&J.some((ye)=>Dr(ye)&&("path"in ye)))Ie("hands_repl_file_path_not_allowed");if(D.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 We=await Reflect.apply(ye,re.target,[]),Ve=Array.isArray(We)?We[0]:void 0,De=Yr(Ve)?Reflect.get(Ve,"viewportSize"):void 0;if(typeof De!=="function")return Yt();return M(await Reflect.apply(De,Ve,[]),z.returns)}if(z.special==="property"){let ye=Reflect.get(re.target,D.method);return M(typeof ye==="function"?Reflect.apply(ye,re.target,[]):ye,z.returns)}let fe=Reflect.get(re.target,D.method);if(typeof fe!=="function")Ie("hands_repl_method_unavailable");if(z.special==="route"){let ye=J[1];if(!vs(ye))Ie("hands_repl_invalid_route_handler");vt(ye.options);let We=G(ye.options),Ve=async(he)=>{if(!Yr(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,[We])},De=[G(J[0]??null),Ve],le=await Reflect.apply(fe,re.target,De);return M(le,z.returns)}let ve=J.map(G);if(D.method==="setInputFiles"){let ye=re.kind==="locator"?0:1,We=async(De)=>{if(typeof De!=="string"){if(!Dr(De)||typeof De.name!=="string"||typeof De.mimeType!=="string"||!yt.isBuffer(De.buffer))Ie("hands_repl_invalid_file_input");return De}if(!e.readWorkspaceFile)Ie("hands_repl_workspace_required");return e.readWorkspaceFile(De)},Ve=ve[ye];ve[ye]=Array.isArray(Ve)?await Promise.all(Ve.map(We)):await We(Ve)}if(D.method==="goto")await e.beforeNavigation?.();let be=e.actionRecorder?.(),Re=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"}[D.method];if(qe){let ye=Reflect.get(re.target,"page"),We=re.kind==="page"?re.target:typeof ye==="function"?Reflect.apply(ye,re.target,[]):void 0;be?.(qe,Yr(We)?We:void 0)}return M(Re,z.returns)}})}import{isIP as Ts}from"net";import{Resolver as La}from"dns/promises";import{isIP as Zt}from"net";var Ba=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function Nn(e){if(Zt(e)!==4)return null;let l=e.split(".");if(l.length!==4)return null;let f=0;for(let _ of l){let w=Number(_);if(!Number.isInteger(w)||w<0||w>255)return null;f=f*256+w}return f>>>0}function ja(e,l,f){let _=Nn(l);if(_===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(_&w)>>>0}function Ps(e){let l=Nn(e);if(l===null)return!0;return Ba.some(([f,_])=>ja(l,f,_))}function Ma(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 D=Nn(S);if(D===null)return null;_=[D>>>16&65535,D&65535],l=l.slice(0,w+1)+"0:0"}let x=l.split("::");if(x.length>2)return null;let W=(D)=>{if(D==="")return[];let re=[];for(let J of D.split(":")){if(J===""||J.length>4||!/^[0-9a-f]+$/.test(J))return null;re.push(Number.parseInt(J,16))}return re},R=W(x[0]??"");if(R===null)return null;if(x.length===1){let D=R;if(D.length!==8)return null;return _.length>0?D.slice(0,6).concat(_):D}let M=W(x[1]??"");if(M===null)return null;let G=8-R.length-M.length;if(G<0)return null;let F=R.concat(Array(G).fill(0),M);if(F.length!==8)return null;return _.length>0?F.slice(0,6).concat(_):F}function Wa(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function Fa(e){let l=Ma(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 Ps(Wa(_,w));return!1}function vr(e){return e.replace(/^\[|\]$/g,"")}function Xt(e){let l=vr(e.trim()),f=Zt(l);if(f===4)return Ps(l);if(f===6)return Fa(l);return!0}function Is(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 As=5000;function Ua(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let _=new La({timeout:As,tries:1});if(e)_.setServers(e);let w=()=>_.cancel();f?.addEventListener("abort",w,{once:!0});try{let[S,x]=await Promise.allSettled([_.resolve4(l),_.resolve6(l)]),W=[...S.status==="fulfilled"?S.value:[],...x.status==="fulfilled"?x.value:[]];if(W.length>0)return W;let R=[S,x].flatMap((G)=>G.status==="rejected"?[G.reason]:[]);throw R.find((G)=>["dns_temporary","dns_timeout"].includes(Is(G)))??R[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var za=Ua();async function $a(e,l,f,_){if(_?.aborted)throw Error("aborted");let w=new AbortController,S,x,W=l(e,w.signal);W.catch(()=>{});try{return await Promise.race([W,new Promise((R,M)=>{if(S=setTimeout(()=>M(new DOMException("DNS lookup timed out","TimeoutError")),f),_)x=()=>M(Error("aborted")),_.addEventListener("abort",x,{once:!0})})])}finally{if(S!==void 0)clearTimeout(S);if(_&&x)_.removeEventListener("abort",x);w.abort()}}async function lo(e,l=za,f){let _=vr(e);if(Zt(_))return Xt(_)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[_]};let w;try{w=await $a(_,l,As,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":Is(S)}}if(w.length===0)return{ok:!1,reason:"dns_empty"};if(w.some(Xt))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:w}}var Ka=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Ln(e){return e.length<=253&&Ka.test(e.toLowerCase())}function Ga(e,l){let f=e.trim().toLowerCase();if(!Ln(f))return!1;if(f.startsWith("*.")){let _=f.slice(2);return l===_||l.endsWith(`.${_}`)}return f===l}function Ja(e){let l=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!l)return null;let f=l.slice(1).map(Number);return f.some((_)=>_>255)?null:f}function Bn(e,l=[]){let f=(_)=>{if(_=_.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!_.includes(":"))return _;try{_=new URL(`http://[${_}]/`).hostname.slice(1,-1)}catch{return _}let w=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(_);if(!w)return _;let S=parseInt(w[1],16),x=parseInt(w[2],16);return`${S>>8}.${S&255}.${x>>8}.${x&255}`};return l.some((_)=>f(_)===f(e))}function st(e){e=e.toLowerCase().replace(/^\[|\]$/g,"");let l=Ja(e);if(l){let[S,x,W]=l;if(S===127)return"loopback";return S===0||S===10||S>=224||S===100&&x>=64&&x<=127||S===169&&x===254||S===172&&x>=16&&x<=31||S===192&&(x===168||x===0&&(W===0||W===2)||x===88&&W===99)||S===198&&(x===18||x===19||x===51&&W===100)||S===203&&x===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),x=parseInt(f[2],16);return st(`${S>>8}.${S&255}.${x>>8}.${x&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 He(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=st(_)!=="public"&&st(_)!=="hostname"||_==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(_)||!_.includes(".")&&!Ts(_)||Boolean(Ts(_)&&Xt(_));return{allowed:!W,url:e,host:_,reason:W?"private_network":"public_web"}}let S=Number(f.port||(["https:","wss:"].includes(f.protocol)?443:80));if(l.deniedPorts?.includes(S)||Bn(_,l.deniedHosts))return w("destination_not_allowed");let x=st(_);if(x==="private"||["local","internal","arpa"].some((W)=>_===W||_.endsWith(`.${W}`)))return w("private_network");if(x==="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)=>Ga(W,_)))return{allowed:!0,url:e,host:_,reason:"allowed_domain"};return{allowed:!1,url:e,host:_,reason:"destination_not_allowed"}}import Ds from"child_process";import{accessSync as Va,constants as qa,readFileSync as Ya,statSync as Xa}from"fs";import{createRequire as Za}from"module";import{dirname as gf,isAbsolute as jn,join as Qa,resolve as bf,win32 as ec}from"path";var Mn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:tr.dependencies["playwright-core"],browser:"chromium"}),Cs=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],Wn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function rc(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((x)=>ec.join(x,...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 Va(e,qa.X_OK),jn(e)&&Xa(e).isFile()}catch{return!1}}function Fn(e,l=process.platform){let f=l==="darwin"?Cs:l==="linux"?Wn:l==="win32"?rc():null;return f?(e??f).find(Bt)??null:null}function tc(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];Ds.spawn=new Proxy(Ds.spawn,{apply(f,_,w){let S=Reflect.apply(f,_,w),x=w[1],W=w[2]?.stdio;if(Array.isArray(x)&&x.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(tc(),e!==void 0){if(!jn(e))throw Error("hands_browser_driver_path_must_be_absolute");let _=Qa(e,"package.json"),w=JSON.parse(Ya(_,"utf8"));if(w.name!==Mn.driver)throw Error("hands_browser_wrong_driver");let S=Za(_)(e),x=S.default?.chromium??S.chromium;if(!x)throw Error("hands_browser_missing_chromium");return{version:w.version,chromium:x}}let[l,f]=await Promise.all([import("./index-gmsadq51.js"),import("./package-way7qesn.js").then((m)=>Fi(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var nc=(e,l=Mn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),oc=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function jt(e={}){return Hs(e,Mn.driverVersion)}async function Un(e,l={}){if(e.driverVersion!=="1.61.1"||!jn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return Hs({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function Hs(e,l){let f=(R)=>nc(R,l),_=e.platform??process.platform;if(_!=="linux"&&_!=="darwin"&&_!=="win32")return f("unsupported_platform");let w;try{w=await oc(e)}catch{return f("driver_missing")}if(w.version!==l)return f("driver_version_mismatch");let S=(R,M)=>({status:"resolved",executablePath:R,source:M,driverVersion:w.version});if(e.executablePath!==void 0)return Bt(e.executablePath)?S(e.executablePath,"configured"):f("executable_missing");let x=w.chromium.executablePath();if(Bt(x))return S(x,"managed");let W=e.allowSystemBrowser===!0?Fn(e.systemCandidates,_):null;return W?S(W,"system"):f("executable_missing")}var gc=["/usr/local/bin/chromium",...Wn];function vn(e,l=Ws()){return Fn(e??(l==="linux"?gc:void 0),l)}async function bc(){try{return(await en()).chromium}catch{return fc(import.meta.url)("playwright-core").chromium}}var wc=1048576,yc=105000,vc=20000,Bs=5000,kc=2000,Sc=1000,Ec=30000,js=81920,Rc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Oc(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:"?_c:pc)(f,{method:e.method(),headers:_,agent:!1,lookup:(M,G,F)=>{let D=it.isIP(l);if(G.all)F(null,[{address:l,family:D}]);else F(null,l,D)}},(M)=>{let G=[],F=0;M.on("data",(D)=>{if(F+=D.length,F>33554432)W.destroy(Error("hands_browser_response_too_large"));else G.push(D)}),M.on("error",S),M.on("end",()=>{let D={};for(let[re,J]of Object.entries(M.headers))if(J!==void 0&&!["transfer-encoding","connection","content-length"].includes(re))D[re]=Array.isArray(J)?J.join(`
299
+ `.trim();import{Buffer as yt}from"buffer";import{randomUUID as Pa}from"crypto";class ks 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 Ss=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),ws=/^hands_[A-Za-z0-9_-]{8,128}$/,Ia=2048,Es=32,Rs=1e4,Aa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function Ta(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 Da=(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))}},Os={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 ks(e)}function Dr(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let l=Object.getPrototypeOf(e);return l===Object.prototype||l===null}function vt(e,l=0,f={nodes:0}){if(l>Es||++f.nodes>Rs)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)vt(_,l+1,f);return}if(!Dr(e))Ie("hands_repl_invalid_json");for(let[_,w]of Object.entries(e)){if(Ss.has(_))Ie("hands_repl_invalid_json");vt(w,l+1,f)}}function Hn(e){return typeof e==="string"&&Object.hasOwn(Os,e)}function Ca(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Hn(l)?l:null}function ys(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Ha(e){return Dr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function vs(e){return Dr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function Yr(e){return!!e&&typeof e==="object"}function Yt(){return Object.freeze({$handsRepl:"undefined"})}function Na(e){if(!yt.isBuffer(e)&&!(e instanceof Uint8Array))Ie("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:yt.from(e).toString("base64")})}function xs(e){if(!Yr(e.browser)||!Yr(e.context)||!Yr(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??Ia;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,_=new WeakMap,w=e.createOpaqueId??Pa,S=(D,re)=>{if(!Yr(re))Ie("hands_repl_expected_target");let J=_.get(re)?.get(D);if(J)return J;if(f.size>=l)Ie("hands_repl_handle_limit");let z="";for(let be=0;be<16;be+=1){let Re=`hands_${w()}`;if(ws.test(Re)&&!f.has(Re)){z=Re;break}}if(!z)Ie("hands_repl_invalid_opaque_id");let fe=Object.freeze({$handsRepl:"handle",id:z,kind:D});f.set(z,{kind:D,target:re});let ve=_.get(re);if(!ve)ve=new Map,_.set(re,ve);return ve.set(D,fe),fe},x=Object.freeze({browser:S("browser",e.browser),context:S("context",e.context),page:S("page",e.page)}),W=(D)=>{if(!Dr(D)||Object.keys(D).length!==3||D.$handsRepl!=="handle"||typeof D.id!=="string"||!ws.test(D.id)||!Hn(D.kind))Ie("hands_repl_invalid_handle");let re=f.get(D.id);if(!re||re.kind!==D.kind)Ie("hands_repl_unknown_handle");return re},R=(D,re=0,J=new Set)=>{if(re>Es)Ie("hands_repl_json_too_complex");if(D===void 0)return Yt();if(D===null||typeof D==="boolean"||typeof D==="string")return D;if(typeof D==="number"){if(!Number.isFinite(D))Ie("hands_repl_non_json_result");return D}if(Array.isArray(D)){if(J.has(D))Ie("hands_repl_cyclic_result");J.add(D);try{return D.map((z)=>R(z,re+1,J))}finally{J.delete(D)}}if(!Dr(D))Ie("hands_repl_non_json_result");if(J.has(D))Ie("hands_repl_cyclic_result");J.add(D);try{let z=Object.create(null);for(let fe of Object.keys(D)){let ve=Object.getOwnPropertyDescriptor(D,fe);if(!ve||!("value"in ve))continue;z[fe]=R(ve.value,re+1,J)}return z}finally{J.delete(D)}},M=(D,re)=>{if(re==="void")return Yt();if(re==="json")return R(D);if(re==="bytes")return Na(D);let J=Ca(re);if(J){if(!Array.isArray(D))Ie("hands_repl_expected_target_list");if(J==="context"&&D.some((z)=>z!==e.context))Ie("hands_repl_foreign_context");return D.map((z)=>S(J,z))}if(D===null||D===void 0)return Yt();if(!Hn(re))Ie("hands_repl_invalid_return_kind");if(re==="context"&&D!==e.context)Ie("hands_repl_foreign_context");return S(re,D)},G=(D)=>{if(Dr(D)&&D.$handsRepl==="handle")return W(D).target;if(ys(D))return yt.from(D.base64,"base64");if(Ha(D))return;if(vs(D))Ie("hands_repl_route_fulfill_only");if(Array.isArray(D))return D.map(G);if(!Dr(D))return D;let re=Object.create(null);for(let[J,z]of Object.entries(D))re[J]=G(z);return re};return Object.freeze({roots:x,dispatch:async(D)=>{if(!Dr(D)||typeof D.type!=="string")Ie("hands_repl_invalid_request");if(D.type==="a11y"){let ye=D.target===void 0?f.get(x.page.id):W(D.target);if(!ye||ye.kind!=="page"&&ye.kind!=="locator")Ie("hands_repl_invalid_a11y_target");return R(await e.a11y(ye.target))}if(D.type==="view"){if(vt(D.source),D.options!==void 0)vt(D.options);let ye=ys(D.source)?yt.from(D.source.base64,"base64"):D.source;if(e.privateProfile&&!yt.isBuffer(ye))Ie("hands_repl_profile_requires_image_bytes");return R(await e.view(ye,D.options))}if(D.type!=="call")Ie("hands_repl_invalid_request");if(typeof D.method!=="string"||D.method.length===0||D.method.length>128)Ie("hands_repl_invalid_method");if(Ss.has(D.method))Ie("hands_repl_forbidden_method");let re=W(D.target),J=D.args??[];if(!Array.isArray(J))Ie("hands_repl_invalid_arguments");if(vt(J),re.kind==="page"&&D.method==="captureScreenshot"){if(J.length!==0)Ie("hands_repl_invalid_arguments");if(!e.screenshotExport)Ie("hands_repl_screenshot_export_unavailable");return R(await e.screenshotExport(re.target))}if(re.kind==="context"&&["startRecording","stopRecording"].includes(D.method)){if(!e.recording||re.target!==e.context)Ie("hands_repl_recording_unavailable");if(J.length>(D.method==="startRecording"?1:0))Ie("hands_repl_invalid_arguments");return R(D.method==="startRecording"?await e.recording.start(J[0]):await e.recording.stop())}if(e.privateProfile){let ye=D.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(ye)||re.kind==="browser"&&ye==="close"||re.kind==="context"&&ye==="close")Ie("hands_repl_private_profile_method_denied");if(re.kind==="browser"&&ye==="contexts")return M([e.context],"context[]");if((ye==="screenshot"||ye==="pdf")&&Dr(J[0])&&(("path"in J[0])||("style"in J[0])))Ie("hands_repl_private_profile_path_denied");if(ye==="goto"){if(typeof J[0]!=="string")Ie("hands_repl_private_profile_url_denied");try{let We=new URL(J[0]);if(!["http:","https:"].includes(We.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"||!Aa.has(J[0].toLowerCase())))Ie("hands_repl_private_profile_attribute_denied");if(re.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(ye)){let We=[re.target];if(ye==="allInnerTexts"){let Ve=Reflect.get(re.target,"all");if(typeof Ve!=="function")Ie("hands_repl_private_profile_probe_unavailable");let De=await Reflect.apply(Ve,re.target,[]);if(!Array.isArray(De)||De.length>Rs||!De.every(Yr))Ie("hands_repl_private_profile_probe_unavailable");We=De}for(let Ve of We){let De=Reflect.get(Ve,"isVisible");if(typeof De!=="function"||!await Reflect.apply(De,Ve,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}if(ye==="press"&&typeof J[0]==="string"&&Ta(J[0]))Ie("hands_repl_private_profile_browser_shortcut_denied");if(re.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(ye)){let We=Reflect.get(re.target,"evaluate");if(typeof We!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Ve=await Reflect.apply(We,re.target,[Da]);if(!Dr(Ve)||typeof Ve.password!=="boolean"||typeof Ve.executableLink!=="boolean")Ie("hands_repl_private_profile_probe_unavailable");if(ye==="inputValue"&&Ve.password)Ie("hands_repl_private_profile_password_denied");if(ye!=="inputValue"&&Ve.executableLink)Ie("hands_repl_private_profile_url_denied");if(ye==="inputValue"){let De=Reflect.get(re.target,"isVisible");if(typeof De!=="function"||!await Reflect.apply(De,re.target,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}}let z=Os[re.kind][D.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"&&D.method==="contexts")return[x.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(D.method)&&J.some((ye)=>Dr(ye)&&("path"in ye)))Ie("hands_repl_file_path_not_allowed");if(D.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 We=await Reflect.apply(ye,re.target,[]),Ve=Array.isArray(We)?We[0]:void 0,De=Yr(Ve)?Reflect.get(Ve,"viewportSize"):void 0;if(typeof De!=="function")return Yt();return M(await Reflect.apply(De,Ve,[]),z.returns)}if(z.special==="property"){let ye=Reflect.get(re.target,D.method);return M(typeof ye==="function"?Reflect.apply(ye,re.target,[]):ye,z.returns)}let fe=Reflect.get(re.target,D.method);if(typeof fe!=="function")Ie("hands_repl_method_unavailable");if(z.special==="route"){let ye=J[1];if(!vs(ye))Ie("hands_repl_invalid_route_handler");vt(ye.options);let We=G(ye.options),Ve=async(he)=>{if(!Yr(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,[We])},De=[G(J[0]??null),Ve],le=await Reflect.apply(fe,re.target,De);return M(le,z.returns)}let ve=J.map(G);if(D.method==="setInputFiles"){let ye=re.kind==="locator"?0:1,We=async(De)=>{if(typeof De!=="string"){if(!Dr(De)||typeof De.name!=="string"||typeof De.mimeType!=="string"||!yt.isBuffer(De.buffer))Ie("hands_repl_invalid_file_input");return De}if(!e.readWorkspaceFile)Ie("hands_repl_workspace_required");return e.readWorkspaceFile(De)},Ve=ve[ye];ve[ye]=Array.isArray(Ve)?await Promise.all(Ve.map(We)):await We(Ve)}if(D.method==="goto")await e.beforeNavigation?.();let be=e.actionRecorder?.(),Re=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"}[D.method];if(qe){let ye=Reflect.get(re.target,"page"),We=re.kind==="page"?re.target:typeof ye==="function"?Reflect.apply(ye,re.target,[]):void 0;be?.(qe,Yr(We)?We:void 0)}return M(Re,z.returns)}})}import{isIP as Ts}from"net";import{Resolver as La}from"dns/promises";import{isIP as Zt}from"net";var Ba=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function Nn(e){if(Zt(e)!==4)return null;let l=e.split(".");if(l.length!==4)return null;let f=0;for(let _ of l){let w=Number(_);if(!Number.isInteger(w)||w<0||w>255)return null;f=f*256+w}return f>>>0}function ja(e,l,f){let _=Nn(l);if(_===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(_&w)>>>0}function Ps(e){let l=Nn(e);if(l===null)return!0;return Ba.some(([f,_])=>ja(l,f,_))}function Ma(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 D=Nn(S);if(D===null)return null;_=[D>>>16&65535,D&65535],l=l.slice(0,w+1)+"0:0"}let x=l.split("::");if(x.length>2)return null;let W=(D)=>{if(D==="")return[];let re=[];for(let J of D.split(":")){if(J===""||J.length>4||!/^[0-9a-f]+$/.test(J))return null;re.push(Number.parseInt(J,16))}return re},R=W(x[0]??"");if(R===null)return null;if(x.length===1){let D=R;if(D.length!==8)return null;return _.length>0?D.slice(0,6).concat(_):D}let M=W(x[1]??"");if(M===null)return null;let G=8-R.length-M.length;if(G<0)return null;let F=R.concat(Array(G).fill(0),M);if(F.length!==8)return null;return _.length>0?F.slice(0,6).concat(_):F}function Wa(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function Fa(e){let l=Ma(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 Ps(Wa(_,w));return!1}function vr(e){return e.replace(/^\[|\]$/g,"")}function Xt(e){let l=vr(e.trim()),f=Zt(l);if(f===4)return Ps(l);if(f===6)return Fa(l);return!0}function Is(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 As=5000;function Ua(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let _=new La({timeout:As,tries:1});if(e)_.setServers(e);let w=()=>_.cancel();f?.addEventListener("abort",w,{once:!0});try{let[S,x]=await Promise.allSettled([_.resolve4(l),_.resolve6(l)]),W=[...S.status==="fulfilled"?S.value:[],...x.status==="fulfilled"?x.value:[]];if(W.length>0)return W;let R=[S,x].flatMap((G)=>G.status==="rejected"?[G.reason]:[]);throw R.find((G)=>["dns_temporary","dns_timeout"].includes(Is(G)))??R[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var za=Ua();async function $a(e,l,f,_){if(_?.aborted)throw Error("aborted");let w=new AbortController,S,x,W=l(e,w.signal);W.catch(()=>{});try{return await Promise.race([W,new Promise((R,M)=>{if(S=setTimeout(()=>M(new DOMException("DNS lookup timed out","TimeoutError")),f),_)x=()=>M(Error("aborted")),_.addEventListener("abort",x,{once:!0})})])}finally{if(S!==void 0)clearTimeout(S);if(_&&x)_.removeEventListener("abort",x);w.abort()}}async function lo(e,l=za,f){let _=vr(e);if(Zt(_))return Xt(_)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[_]};let w;try{w=await $a(_,l,As,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":Is(S)}}if(w.length===0)return{ok:!1,reason:"dns_empty"};if(w.some(Xt))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:w}}var Ka=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Ln(e){return e.length<=253&&Ka.test(e.toLowerCase())}function Ga(e,l){let f=e.trim().toLowerCase();if(!Ln(f))return!1;if(f.startsWith("*.")){let _=f.slice(2);return l===_||l.endsWith(`.${_}`)}return f===l}function Ja(e){let l=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!l)return null;let f=l.slice(1).map(Number);return f.some((_)=>_>255)?null:f}function Bn(e,l=[]){let f=(_)=>{if(_=_.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!_.includes(":"))return _;try{_=new URL(`http://[${_}]/`).hostname.slice(1,-1)}catch{return _}let w=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(_);if(!w)return _;let S=parseInt(w[1],16),x=parseInt(w[2],16);return`${S>>8}.${S&255}.${x>>8}.${x&255}`};return l.some((_)=>f(_)===f(e))}function st(e){e=e.toLowerCase().replace(/^\[|\]$/g,"");let l=Ja(e);if(l){let[S,x,W]=l;if(S===127)return"loopback";return S===0||S===10||S>=224||S===100&&x>=64&&x<=127||S===169&&x===254||S===172&&x>=16&&x<=31||S===192&&(x===168||x===0&&(W===0||W===2)||x===88&&W===99)||S===198&&(x===18||x===19||x===51&&W===100)||S===203&&x===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),x=parseInt(f[2],16);return st(`${S>>8}.${S&255}.${x>>8}.${x&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 He(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=st(_)!=="public"&&st(_)!=="hostname"||_==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(_)||!_.includes(".")&&!Ts(_)||Boolean(Ts(_)&&Xt(_));return{allowed:!W,url:e,host:_,reason:W?"private_network":"public_web"}}let S=Number(f.port||(["https:","wss:"].includes(f.protocol)?443:80));if(l.deniedPorts?.includes(S)||Bn(_,l.deniedHosts))return w("destination_not_allowed");let x=st(_);if(x==="private"||["local","internal","arpa"].some((W)=>_===W||_.endsWith(`.${W}`)))return w("private_network");if(x==="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)=>Ga(W,_)))return{allowed:!0,url:e,host:_,reason:"allowed_domain"};return{allowed:!1,url:e,host:_,reason:"destination_not_allowed"}}import Ds from"child_process";import{accessSync as Va,constants as qa,readFileSync as Ya,statSync as Xa}from"fs";import{createRequire as Za}from"module";import{dirname as gf,isAbsolute as jn,join as Qa,resolve as bf,win32 as ec}from"path";var Mn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:tr.dependencies["playwright-core"],browser:"chromium"}),Cs=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],Wn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function rc(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((x)=>ec.join(x,...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 Va(e,qa.X_OK),jn(e)&&Xa(e).isFile()}catch{return!1}}function Fn(e,l=process.platform){let f=l==="darwin"?Cs:l==="linux"?Wn:l==="win32"?rc():null;return f?(e??f).find(Bt)??null:null}function tc(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];Ds.spawn=new Proxy(Ds.spawn,{apply(f,_,w){let S=Reflect.apply(f,_,w),x=w[1],W=w[2]?.stdio;if(Array.isArray(x)&&x.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(tc(),e!==void 0){if(!jn(e))throw Error("hands_browser_driver_path_must_be_absolute");let _=Qa(e,"package.json"),w=JSON.parse(Ya(_,"utf8"));if(w.name!==Mn.driver)throw Error("hands_browser_wrong_driver");let S=Za(_)(e),x=S.default?.chromium??S.chromium;if(!x)throw Error("hands_browser_missing_chromium");return{version:w.version,chromium:x}}let[l,f]=await Promise.all([import("./index-j6wffzfd.js"),import("./package-way7qesn.js").then((m)=>Fi(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var nc=(e,l=Mn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),oc=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function jt(e={}){return Hs(e,Mn.driverVersion)}async function Un(e,l={}){if(e.driverVersion!=="1.61.1"||!jn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return Hs({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function Hs(e,l){let f=(R)=>nc(R,l),_=e.platform??process.platform;if(_!=="linux"&&_!=="darwin"&&_!=="win32")return f("unsupported_platform");let w;try{w=await oc(e)}catch{return f("driver_missing")}if(w.version!==l)return f("driver_version_mismatch");let S=(R,M)=>({status:"resolved",executablePath:R,source:M,driverVersion:w.version});if(e.executablePath!==void 0)return Bt(e.executablePath)?S(e.executablePath,"configured"):f("executable_missing");let x=w.chromium.executablePath();if(Bt(x))return S(x,"managed");let W=e.allowSystemBrowser===!0?Fn(e.systemCandidates,_):null;return W?S(W,"system"):f("executable_missing")}var gc=["/usr/local/bin/chromium",...Wn];function vn(e,l=Ws()){return Fn(e??(l==="linux"?gc:void 0),l)}async function bc(){try{return(await en()).chromium}catch{return fc(import.meta.url)("playwright-core").chromium}}var wc=1048576,yc=105000,vc=20000,Bs=5000,kc=2000,Sc=1000,Ec=30000,js=81920,Rc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Oc(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:"?_c:pc)(f,{method:e.method(),headers:_,agent:!1,lookup:(M,G,F)=>{let D=it.isIP(l);if(G.all)F(null,[{address:l,family:D}]);else F(null,l,D)}},(M)=>{let G=[],F=0;M.on("data",(D)=>{if(F+=D.length,F>33554432)W.destroy(Error("hands_browser_response_too_large"));else G.push(D)}),M.on("error",S),M.on("end",()=>{let D={};for(let[re,J]of Object.entries(M.headers))if(J!==void 0&&!["transfer-encoding","connection","content-length"].includes(re))D[re]=Array.isArray(J)?J.join(`
300
300
  `):J;w({status:M.statusCode??502,headers:D,body:Buffer.concat(G)})})}),R=setTimeout(()=>W.destroy(Error("hands_browser_fetch_timeout")),Ec);W.once("close",()=>clearTimeout(R)),W.on("error",S),W.end(e.postDataBuffer()??void 0)})}async function xc(e,l,f=()=>{},_={lookup:(w)=>uc(w,{all:!0}),fetch:Oc}){let w=new WeakSet,S=new WeakMap,x=(W)=>{let R=S.get(W);if(R)return R;let M=(async()=>{if(!e.newCDPSession)return;let G=await e.newCDPSession(W),F=new Map;G.on("Network.loadingFinished",({requestId:D})=>F.delete(D)),G.on("Network.loadingFailed",({requestId:D})=>F.delete(D)),G.on("Fetch.requestPaused",async(D)=>{let re=D.networkId??D.requestId,J=D.redirectedRequestId?(F.get(re)??0)+1:0;F.set(re,J);let z=He(D.request.url,l),fe=l.mode==="enforce"&&Boolean(D.redirectedRequestId)&&z.host!==null&&!it.isIP(z.host),ve=!z.allowed?z:fe?{...z,allowed:!1,reason:"destination_not_allowed"}:J>20?{...z,allowed:!1,reason:"redirect_not_supported"}:null;try{if(ve)f(ve),await G.send("Fetch.failRequest",{requestId:D.requestId,errorReason:"BlockedByClient"});else await G.send("Fetch.continueRequest",{requestId:D.requestId})}catch{await G.send("Fetch.failRequest",{requestId:D.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 R=W.request().url(),M=He(R,l);if(M.allowed&&l.mode==="public_web"){await W.continue();return}let G=W.request();if(M.allowed&&M.host&&it.isIP(M.host)&&G.isNavigationRequest?.()){let F=G.frame();if(w.has(F.page())&&F===F.page().mainFrame()){await W.continue();return}}if(M.allowed&&(l.mode==="off"||M.reason==="local_document")){await W.continue();return}if(M.allowed&&M.host)try{let F=M.host,D=st(F),re,J=await(async()=>{if(D!=="hostname")return[{address:F,family:it.isIP(F)}];if(M.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([_.lookup(F),new Promise((z,fe)=>{re=setTimeout(()=>fe(Error("hands_browser_dns_timeout")),5000)})])}finally{if(re)clearTimeout(re)}})();if(!J.length||J.some(({address:z})=>{let fe=st(z);return!it.isIP(z)||l.mode==="enforce"&&Bn(z,l.deniedHosts)||(M.reason==="loopback"?fe!=="loopback":fe!=="public")}))M={...M,allowed:!1,reason:"private_network"};else{let z=await _.fetch(W.request(),J[0].address);if(z.status>=300&&z.status<400){let fe=z.headers.location??R;try{fe=new URL(fe,R).href}catch{}let ve=He(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 R=He(W.url(),l);if(l.mode==="enforce"&&R.allowed&&(!R.host||!it.isIP(R.host)))R={...R,allowed:!1,reason:"destination_not_allowed"};if(R.allowed){W.connectToServer();return}f(R),await W.close({code:1008,reason:"Reason egress policy denied"})}),l.mode==="off"?void 0:{preparePage:x}}async function Fs(e,l=Ws(),f){if(f){let w=await Un(f,{platform:l,systemCandidates:e});return w.status==="resolved"?w.executablePath:null}if(e!==void 0){let w=vn(e,l);if(w)return w}let _=await jt({platform:l,systemCandidates:e,allowSystemBrowser:!0});return _.status==="resolved"?_.executablePath:null}function Ms(e,l){if(!e)throw Error("hands_repl_workspace_required");let f=$n(e),_=kt(e),w=Gn(_,kt(_,l)),x=w!==".."&&!w.startsWith(`..${Jn}`)&&!Ls(w)?kt(f,w):kt(f,l);if(E(kt(_,l))||E(x))throw Error("hands_repl_protected_path");let W=(J)=>{let z=Gn(f,J);return z!==""&&z!==".."&&!z.startsWith(`..${Jn}`)&&!Ls(z)},R=$n(x);if(E(R))throw Error("hands_repl_protected_path");if(!W(x)||!W(R))throw Error("hands_repl_file_outside_workspace");let M=Gn(f,x).split(Jn),G=[f,...M.map((J,z)=>kt(f,...M.slice(0,z+1)))],F=G.map((J)=>Ns(J));if(F.some((J)=>J.isSymbolicLink()))throw Error("hands_repl_file_symlink");let D=F[F.length-1];if(!D.isFile()||D.nlink!==1||D.size>16777216)throw Error("hands_repl_file_not_regular_or_too_large");let re=cc(x,zn.O_RDONLY|zn.O_NOFOLLOW|zn.O_NONBLOCK);try{let J=ac(re);if(J.dev!==D.dev||J.ino!==D.ino||!J.isFile())throw Error("hands_repl_file_changed");for(let be=0;be<G.length;be++){let Re=Ns(G[be]);if(Re.dev!==F[be].dev||Re.ino!==F[be].ino||Re.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!W($n(x)))throw Error("hands_repl_file_outside_workspace");let z=Buffer.alloc(16777217),fe=0;while(fe<z.length){let be=dc(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:mc(x),mimeType:Rc[hc(x).toLowerCase()]??"application/octet-stream",buffer:ve}}finally{ic(re)}}function St(e,l){e.end(`${JSON.stringify(l)}
301
301
  `)}function tn(e){try{lc(e)}catch{}}async function Us(e){if(e.managedBrowser&&e.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let l=e.launch||e.targetContext?null:e.managedBrowser?await Un(e.managedBrowser,{executablePath:e.browserExecutablePath}):await jt({executablePath:e.browserExecutablePath,driverModuleDirectory:e.driverModuleDirectory});if(l?.status==="unavailable")throw Error(`hands_browser_${l.reason}`);let f=l?.status==="resolved"?l.executablePath:e.browserExecutablePath;if(!f||!Bt(f))throw Error("hands_browser_unavailable");let _=e.launch??(async(le)=>(e.targetContext?await bc():(await en(e.managedBrowser?.driverModuleDirectory??e.driverModuleDirectory)).chromium).launch(le)),w=[],S={},x=null,W=null,R=null,M=null,G=!1,F=null,D=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(()=>{D.delete(le)});return re.set(le,xe),xe},ve=async()=>{let le=[...D.entries()].reverse(),he=J??=performance.now()+Sc,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,Me]of Le.entries()){if(Me.status!=="rejected")continue;let rr=Me.reason instanceof Error&&["Error","TimeoutError","ProtocolError"].includes(Me.reason.name)?Me.reason.name:"unknown";Be.push(Error(`hands_repl_close_failed: ${le[ke][1]}: ${rr}`))}if(Be.length)throw AggregateError(Be,"hands_repl_stop_unconfirmed")},be=(le,he)=>{if(D.set(le,he),G||M)fe(le).catch(()=>{return}),z();return le},Re=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 xc(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 nr=sr&&typeof sr==="object"&&!Array.isArray(sr)?sr:{},lr,Wr="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 Qr=Ms(e.workspaceRoot,Ge);lr=Qr.buffer,Wr=Qr.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(nr.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),Kr=Number(nr.maxWidth)||1024,ft=Number(nr.quality)||72,Ft=e.targetContext?await le.newPage():await he.newPage();try{let Qr=`data:${Wr};base64,${lr.toString("base64")}`;for(let ur=0;ur<5;ur+=1){let jr=await Ft.evaluate(async(Lr)=>{let Mr=new Image;Mr.src=Lr.url,await Mr.decode();let rt=Math.min(1,Lr.maxWidth/Mr.naturalWidth),Tr=document.createElement("canvas");Tr.width=Math.max(1,Math.round(Mr.naturalWidth*rt)),Tr.height=Math.max(1,Math.round(Mr.naturalHeight*rt));let Or=Tr.getContext("2d");if(!Or)throw Error("view(): canvas unavailable");return Or.fillStyle="#ffffff",Or.fillRect(0,0,Tr.width,Tr.height),Or.drawImage(Mr,0,0,Tr.width,Tr.height),{data:Tr.toDataURL("image/jpeg",Lr.q/100).split(",")[1]??"",width:Tr.width,height:Tr.height,sourceWidth:Mr.naturalWidth,sourceHeight:Mr.naturalHeight}},{url:Qr,maxWidth:Kr,q:ft}),pt=Buffer.from(jr.data,"base64");if(pt.length<=js){let Lr=ln||"image";return`<<<ARA_VIEW_IMAGE ${jr.data} image/jpeg ${Lr}>>>
302
302
  Viewing ${Lr} (${jr.sourceWidth}x${jr.sourceHeight} source, sent at ${jr.width}x${jr.height}, ${Math.round(pt.length/1024)}KB).`}if(Kr>640)Kr=Math.round(Kr*0.75);else ft=Math.max(30,ft-15)}throw Error(`view(): could not reduce the image under ${Math.round(js/1024)}KB`)}finally{await Ft.close().catch(()=>{return})}},Me=xs({browser:e.targetContext?.browser()??le,context:he,page:Le,a11y:Be,view:ke,readWorkspaceFile:(Ge)=>Ms(e.workspaceRoot,Ge),privateProfile:e.privateProfile,beforeNavigation:e.beforeNavigation,recording:e.recording,screenshotExport:e.screenshotExport,actionRecorder:()=>{let Ge=w,sr=S;return(nr,lr)=>{if(Ge.length<Io)Ge.push(nr);if(lr)sr.page=lr}}}),rr=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,Wr)=>e.onBrowserOperation?e.onBrowserOperation(Ge,()=>Me.dispatch(Wr)):Me.dispatch(Wr)),z();let nr=await sr.newPage();return z(),await nr.goto("data:text/html,<title>Reason Hands evaluator</title>"),z(),await nr.evaluate(`(${gs})(${JSON.stringify(Me.roots)})`),{context:sr,page:nr,runId:Ge}}catch(nr){throw await fe(sr).catch(()=>{return}),nr}},or=await rr(),Rr={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(Rr.evaluator.context),Rr.evaluator=await rr(Ge)}};return z(),Rr}catch(xe){throw await ve().catch(()=>{return}),xe}},Fe=async()=>{if(z(),x)return x;if(!R){W=Re();let le;R=Promise.race([W,new Promise((he,xe)=>{le=setTimeout(()=>xe(Error("hands_browser_unavailable: startup timed out")),vc)})]).then((he)=>(z(),x=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")),Bs)})])}catch{M=Error("hands_browser_unavailable: startup cleanup unconfirmed")}finally{if(he)clearTimeout(he)}throw M}).finally(()=>{if(le)clearTimeout(le)})}return R},qe=async(le,he,xe=!1)=>{let Ke=await Fe(),Le=S;if(e.onBrowserOperation&&Ke.evaluator.runId!==he)await Ke.resetEvaluator(he);let ke=(async()=>{let or=await Ke.evaluator.page.evaluate(`(${bs})(${JSON.stringify({code:le})})`);if(typeof or!=="string")throw Error("hands_repl_invalid_evaluator_output");let Rr=Le.page;if(xe&&Rr&&!or.includes("<<<ARA_VIEW_IMAGE")){let Ge=()=>Ke.captureProgressFrame(Rr);try{let sr=await(e.onBrowserOperation?e.onBrowserOperation(he,Ge):Ge());return Le.automaticProgressImage=!0,`${or}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{nt,Et,cr,on,xt,kt,Di,sn,Oi,Ni,Li}from"./vm-hands-entry-lite-xv7tgef8.js";import{Pe,sr,ni,wt,Go,oe,Ko,Jo,tt,Re,nn,oi,vt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Z,Te,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ri,St,Ti}from"./vm-hands-entry-lite-nxd394w3.js";import{ue,X,I}from"./vm-hands-entry-lite-a0g6c3wr.js";import{P,Yt}from"./vm-hands-entry-lite-hv3dxd5k.js";import{mr,eo,to,at,ro,no,io,oo,so,ao,yr,wr,br,wn,bn,vr,lo,vn,Sr,me,ge,Ot,Er,kr,Nt}from"./vm-hands-entry-lite-8jcb5jqm.js";import{O,T,b}from"./vm-hands-entry-lite-4r1yn35v.js";import{Xi,Yi,_n,Zi,yn,Qi,st,fr}from"./vm-hands-entry-lite-8x8940ky.js";import{K}from"./vm-hands-entry-lite-ct4mtq1m.js";import{Ue}from"./vm-hands-entry-lite-5tnma5qb.js";import{j}from"./vm-hands-entry-lite-vj0gm694.js";import{hr,gn,Ji}from"./vm-hands-entry-lite-9azmqs47.js";import{vo,So,dt,Eo,xo,ko,Co,Ao,Po,Ro}from"./vm-hands-entry-lite-k9vk84wa.js";import{Dr,Vt,Or,Hn,Un}from"./vm-hands-entry-lite-hhk4h552.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-mbv4mqha.js";import{Nn,x,yo}from"./vm-hands-entry-lite-gz65ybc2.js";import{wo,bo}from"./vm-hands-entry-lite-1b3x8f9z.js";import{Bt,Pn,Rn}from"./vm-hands-entry-lite-x7w4n87s.js";import{ye,ho,fo}from"./vm-hands-entry-lite-2hfrcr50.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{Mt}from"./vm-hands-entry-lite-yptpy066.js";import{ve,Ut,zt,qt,E}from"./vm-hands-entry-lite-72nj66ab.js";import{a,ie}from"./vm-hands-entry-lite-jvszqt0z.js";import{t,k,o,d,u,n,W,g,ee,s,i,Zo}from"./vm-hands-entry-lite-dszmx6yf.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,$e,ln}from"./vm-hands-entry-lite-b6gsggvp.js";import{Me}from"./vm-hands-entry-lite-3gbf905c.js";import{request as $l}from"http";import{request as Bl}from"https";import{lookup as Fl}from"dns/promises";import{isIP as Ul}from"net";async function Hl(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Bl:$l)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:Di},(f)=>c({response:f,close:()=>{f.destroy(),m.destroy(),f.socket?.destroy()}}));m.once("error",p),m.once("timeout",()=>m.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),m.end(e.body)})}var Ki=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),jl=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function es(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(Ki.has(c))return"custom_endpoint_host_not_found";if(jl.has(c))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(c))return"custom_endpoint_tls_failed"}for(let p of[...e instanceof AggregateError?e.errors:[],e.cause]){let m=es(p,l+1);if(m)return m}return null}async function ql(e,l){let c=es(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||Ul(p)!==0)return c;let m;return await Promise.race([Fl(p).then(()=>!0,(h)=>!Ki.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function Wl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function Vl(e,l){let c=Buffer.from(e),p=Buffer.from(l),m=new Uint32Array(c.length);for(let h=1,y=0;h<c.length;h++){while(y&&c[h]!==c[y])y=m[y-1];if(c[h]===c[y])y++;m[h]=y}let f=0;return(h,y=!1)=>{let S=Buffer.allocUnsafe(h.length*p.length+f),w=0;for(let _ of h){while(f&&c[f]!==_){let v=m[f-1];w+=c.copy(S,w,0,f-v),f=v}if(c[f]===_){if(f++,f===c.length)w+=p.copy(S,w),f=0}else S[w++]=_}if(y)w+=c.copy(S,w,0,f),f=0;return S.subarray(0,w)}}async function ts(e){e.signal.throwIfAborted();let l=Oi.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=Ni.parse(await e.credential(e.signal));if(!sn(c,{baseUrl:c.baseUrl,api:p.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let m,f,h=0,y=0,S=0,w=Wl(p.apiKey),_=Vl(p.apiKey,w),v=async(C,A)=>{e.signal.throwIfAborted(),await new Promise((M,N)=>{let L=()=>{e.signal.removeEventListener("abort",L),N(e.signal.reason)};if(e.signal.addEventListener("abort",L,{once:!0}),e.signal.aborted){L();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(C,A))).then(()=>{e.signal.removeEventListener("abort",L),M()},(B)=>{e.signal.removeEventListener("abort",L),N(B)})})},R=async(C)=>{if(h+=C.length,h>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<C.length;A+=Et){if(S>=on)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await v(`custom_endpoint.chunk.${S++}`,{eof:!1,data:C.subarray(A,A+Et).toString("base64")})}};try{let C=await Hl({url:c.url,body:c.body,signal:e.signal,headers:{...c.headers,...p.api==="anthropic-messages"?{"x-api-key":p.apiKey}:{authorization:`Bearer ${p.apiKey}`}}});m=C.response,f=C.close;let A=m.statusCode??500;if(A>=300&&A<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(m.headers["content-encoding"]&&m.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let N of["content-type","retry-after","x-request-id","request-id"]){let L=m.headers[N];if(typeof L==="string")M[N]=L.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:A,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:M});for await(let N of m){e.signal.throwIfAborted();let L=Buffer.isBuffer(N)?N:Buffer.from(N);if(y+=L.length,y>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await R(_(L))}return await R(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(C){if(e.signal.throwIfAborted(),C instanceof r)throw C;throw new r((m?null:await ql(C,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as rs}from"path";function zl(e,l){return e===rs(l,".ara","workspace")||e===rs(l,".reason","workspace")}function ls(e,l){let c=e.filter((p)=>zl(p.path,l));return c.length===1?c[0].path:null}var Gl=/^[a-f0-9]{64}$/;var an=32,Yl=/^\/[^\x00-\x1f\x7f\\]*$/;function Cr(e){if(typeof e!=="string"||e.length>4096||!Yl.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((l)=>l!==""&&l!=="."&&l!=="..")}function Pr(e,l){let c=l==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!c)return e;let p=c[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${c[1].toUpperCase()}:${p?`/${p}`:""}`}function cn(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let l=e;if(!Cr(l.home)||!Array.isArray(l.roots)||l.roots.length>an)return;let c=[];for(let p of l.roots){if(!p||typeof p!=="object"||Array.isArray(p))return;let{path_fingerprint:m,path:f}=p;if(typeof m!=="string"||!Gl.test(m)||!Cr(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Kl(e){let l=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&l?l:void 0}function Xl(e){return Kl(e)??e.email.toLowerCase()}function un(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?Xl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var Gt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Jl=[...ve.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...Ut.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...[...zt].map((e)=>`/(${Gt(e)})$`),`/${Gt(".env.")}[^/]*$`,...qt.map((e)=>`/[^/]*${Gt(e)}$`)],cs=`function localGithubSandboxProfile(root, temporary) {
2
+ import{nt,Et,cr,on,xt,kt,Di,sn,Oi,Ni,Li}from"./vm-hands-entry-lite-xv7tgef8.js";import{Pe,sr,ni,wt,Go,oe,Ko,Jo,tt,Re,nn,oi,vt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Z,Te,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ri,St,Ti}from"./vm-hands-entry-lite-nxd394w3.js";import{ue,X,I}from"./vm-hands-entry-lite-a0g6c3wr.js";import{P,Yt}from"./vm-hands-entry-lite-hv3dxd5k.js";import{mr,eo,to,at,ro,no,io,oo,so,ao,yr,wr,br,wn,bn,vr,lo,vn,Sr,me,ge,Ot,Er,kr,Nt}from"./vm-hands-entry-lite-x7ks944h.js";import{O,T,b}from"./vm-hands-entry-lite-4r1yn35v.js";import{Xi,Yi,_n,Zi,yn,Qi,st,fr}from"./vm-hands-entry-lite-x3tgdvcf.js";import{K}from"./vm-hands-entry-lite-ct4mtq1m.js";import{Ue}from"./vm-hands-entry-lite-5tnma5qb.js";import{j}from"./vm-hands-entry-lite-vj0gm694.js";import{hr,gn,Ji}from"./vm-hands-entry-lite-9azmqs47.js";import{vo,So,dt,Eo,xo,ko,Co,Ao,Po,Ro}from"./vm-hands-entry-lite-k9vk84wa.js";import{Dr,Vt,Or,Hn,Un}from"./vm-hands-entry-lite-hhk4h552.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-g89cjfan.js";import{Nn,x,yo}from"./vm-hands-entry-lite-d2kj2jj0.js";import{wo,bo}from"./vm-hands-entry-lite-vn6zr7gp.js";import{Bt,Pn,Rn}from"./vm-hands-entry-lite-j7e86nvy.js";import{ye,ho,fo}from"./vm-hands-entry-lite-2hfrcr50.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{Mt}from"./vm-hands-entry-lite-yptpy066.js";import{ve,Ut,zt,qt,E}from"./vm-hands-entry-lite-72nj66ab.js";import{a,ie}from"./vm-hands-entry-lite-jvszqt0z.js";import{t,k,o,d,u,n,W,g,ee,s,i,Zo}from"./vm-hands-entry-lite-dszmx6yf.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,$e,ln}from"./vm-hands-entry-lite-b6gsggvp.js";import{Me}from"./vm-hands-entry-lite-3gbf905c.js";import{request as $l}from"http";import{request as Bl}from"https";import{lookup as Fl}from"dns/promises";import{isIP as Ul}from"net";async function Hl(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Bl:$l)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:Di},(f)=>c({response:f,close:()=>{f.destroy(),m.destroy(),f.socket?.destroy()}}));m.once("error",p),m.once("timeout",()=>m.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),m.end(e.body)})}var Ki=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),jl=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function es(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(Ki.has(c))return"custom_endpoint_host_not_found";if(jl.has(c))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(c))return"custom_endpoint_tls_failed"}for(let p of[...e instanceof AggregateError?e.errors:[],e.cause]){let m=es(p,l+1);if(m)return m}return null}async function ql(e,l){let c=es(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||Ul(p)!==0)return c;let m;return await Promise.race([Fl(p).then(()=>!0,(h)=>!Ki.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function Wl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function Vl(e,l){let c=Buffer.from(e),p=Buffer.from(l),m=new Uint32Array(c.length);for(let h=1,y=0;h<c.length;h++){while(y&&c[h]!==c[y])y=m[y-1];if(c[h]===c[y])y++;m[h]=y}let f=0;return(h,y=!1)=>{let S=Buffer.allocUnsafe(h.length*p.length+f),w=0;for(let _ of h){while(f&&c[f]!==_){let v=m[f-1];w+=c.copy(S,w,0,f-v),f=v}if(c[f]===_){if(f++,f===c.length)w+=p.copy(S,w),f=0}else S[w++]=_}if(y)w+=c.copy(S,w,0,f),f=0;return S.subarray(0,w)}}async function ts(e){e.signal.throwIfAborted();let l=Oi.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=Ni.parse(await e.credential(e.signal));if(!sn(c,{baseUrl:c.baseUrl,api:p.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let m,f,h=0,y=0,S=0,w=Wl(p.apiKey),_=Vl(p.apiKey,w),v=async(C,A)=>{e.signal.throwIfAborted(),await new Promise((M,N)=>{let L=()=>{e.signal.removeEventListener("abort",L),N(e.signal.reason)};if(e.signal.addEventListener("abort",L,{once:!0}),e.signal.aborted){L();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(C,A))).then(()=>{e.signal.removeEventListener("abort",L),M()},(B)=>{e.signal.removeEventListener("abort",L),N(B)})})},R=async(C)=>{if(h+=C.length,h>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<C.length;A+=Et){if(S>=on)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await v(`custom_endpoint.chunk.${S++}`,{eof:!1,data:C.subarray(A,A+Et).toString("base64")})}};try{let C=await Hl({url:c.url,body:c.body,signal:e.signal,headers:{...c.headers,...p.api==="anthropic-messages"?{"x-api-key":p.apiKey}:{authorization:`Bearer ${p.apiKey}`}}});m=C.response,f=C.close;let A=m.statusCode??500;if(A>=300&&A<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(m.headers["content-encoding"]&&m.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let N of["content-type","retry-after","x-request-id","request-id"]){let L=m.headers[N];if(typeof L==="string")M[N]=L.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:A,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:M});for await(let N of m){e.signal.throwIfAborted();let L=Buffer.isBuffer(N)?N:Buffer.from(N);if(y+=L.length,y>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await R(_(L))}return await R(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(C){if(e.signal.throwIfAborted(),C instanceof r)throw C;throw new r((m?null:await ql(C,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as rs}from"path";function zl(e,l){return e===rs(l,".ara","workspace")||e===rs(l,".reason","workspace")}function ls(e,l){let c=e.filter((p)=>zl(p.path,l));return c.length===1?c[0].path:null}var Gl=/^[a-f0-9]{64}$/;var an=32,Yl=/^\/[^\x00-\x1f\x7f\\]*$/;function Cr(e){if(typeof e!=="string"||e.length>4096||!Yl.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((l)=>l!==""&&l!=="."&&l!=="..")}function Pr(e,l){let c=l==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!c)return e;let p=c[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${c[1].toUpperCase()}:${p?`/${p}`:""}`}function cn(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let l=e;if(!Cr(l.home)||!Array.isArray(l.roots)||l.roots.length>an)return;let c=[];for(let p of l.roots){if(!p||typeof p!=="object"||Array.isArray(p))return;let{path_fingerprint:m,path:f}=p;if(typeof m!=="string"||!Gl.test(m)||!Cr(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Kl(e){let l=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&l?l:void 0}function Xl(e){return Kl(e)??e.email.toLowerCase()}function un(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?Xl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var Gt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Jl=[...ve.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...Ut.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...[...zt].map((e)=>`/(${Gt(e)})$`),`/${Gt(".env.")}[^/]*$`,...qt.map((e)=>`/[^/]*${Gt(e)}$`)],cs=`function localGithubSandboxProfile(root, temporary) {
3
3
  return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
4
4
  '(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
5
5
  '(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var tr={name:"github-native-engineer-device-worker-production",version:"0.2.545",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
2
+ var tr={name:"github-native-engineer-device-worker-production",version:"0.2.547",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"5.0.1",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^5.0.1",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
3
3
  export{tr};