@reason-machines/cli-linux-x64 0.2.415 → 0.2.418
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +1 -1
- package/bin/runtime/srt/sandbox-runtime.mjs +38 -38
- package/bin/vm-hands/api-18d75dfn.js +2 -0
- package/bin/vm-hands/api-credentials-3vhge1ap.js +2 -0
- package/bin/vm-hands/connect-cli-pn1h0b08.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-17t4efc4.js +2 -0
- package/bin/vm-hands/desktop-account-6sjrxy69.js +2 -0
- package/bin/vm-hands/device-workspace-s50q53sz.js +2 -0
- package/bin/vm-hands/{fsevents-ekt70rcc.js → fsevents-p3d8kd0p.js} +1 -1
- package/bin/vm-hands/hands-worker-source-kddz4y15.js +2 -0
- package/bin/vm-hands/{index-k8kcz8a3.js → index-wrw65904.js} +35 -35
- package/bin/vm-hands/install-receipt-ysa70fvh.js +2 -0
- package/bin/vm-hands/local-automation-7nc6cgjp.js +2 -0
- package/bin/vm-hands/local-capabilities-5f36fr9x.js +2 -0
- package/bin/vm-hands/local-desktop-users-cppjjr81.js +2 -0
- package/bin/vm-hands/local-display-mac-0qz3b627.js +2 -0
- package/bin/vm-hands/local-display-session-zg4dpnf1.js +2 -0
- package/bin/vm-hands/local-display-video-remg1c30.js +2 -0
- package/bin/vm-hands/local-managed-process-gjc8gvgb.js +2 -0
- package/bin/vm-hands/local-pty-session-rpk05ap5.js +2 -0
- package/bin/vm-hands/managed-runtime-f85h6h7f.js +2 -0
- package/bin/vm-hands/network-contract-trkxqc0w.js +2 -0
- package/bin/vm-hands/package-xqbhdf15.js +2 -0
- package/bin/vm-hands/permissions-bhbnb1bp.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-xn3ddz70.js +2 -0
- package/bin/vm-hands/serve-service-58ea9cwx.js +2 -0
- package/bin/vm-hands/status-z9r8nq3y.js +10 -0
- package/bin/vm-hands/version-p0g28erd.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-bdhjpv7g.js → vm-hands-entry-lite-21qpxvt8.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-2nkj0dpx.js +539 -0
- package/bin/vm-hands/vm-hands-entry-lite-2wzsnnsp.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-8t9xssf9.js → vm-hands-entry-lite-3krzmhkk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-k278g9kj.js → vm-hands-entry-lite-4vks5phw.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-1cwqa4jr.js → vm-hands-entry-lite-50zbqwkv.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-1rrb66r9.js → vm-hands-entry-lite-5dtfehjv.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-6aeea05q.js → vm-hands-entry-lite-60pg3wxj.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9ay6f56v.js → vm-hands-entry-lite-6c67a3jc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-txn44020.js → vm-hands-entry-lite-6wt5ja1k.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-zg36myyf.js → vm-hands-entry-lite-8r31b0ps.js} +4 -4
- package/bin/vm-hands/vm-hands-entry-lite-ah6fwqxp.js +128 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ckv17tn8.js → vm-hands-entry-lite-aj139v8j.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-907pa7f9.js → vm-hands-entry-lite-avc65bd7.js} +6 -6
- package/bin/vm-hands/{vm-hands-entry-lite-9c95p6n9.js → vm-hands-entry-lite-beyyy1gz.js} +37 -37
- package/bin/vm-hands/{vm-hands-entry-lite-ab2m9erf.js → vm-hands-entry-lite-bx5zy5bd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pgb514h0.js → vm-hands-entry-lite-dk79tnax.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-ec9jemny.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-gvwdy3rf.js → vm-hands-entry-lite-fbhqfzbq.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-t7an5zg2.js → vm-hands-entry-lite-fcvf8md1.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-qysyf65v.js → vm-hands-entry-lite-g4zd2d5n.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0xrsph3r.js → vm-hands-entry-lite-hbs3tpdg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-f5e3dbgk.js → vm-hands-entry-lite-hk6trmwa.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-2hvbgp1n.js → vm-hands-entry-lite-hn76pcgk.js} +5 -5
- package/bin/vm-hands/vm-hands-entry-lite-j43nqe8y.js +452 -0
- package/bin/vm-hands/{vm-hands-entry-lite-89z488gz.js → vm-hands-entry-lite-jev771b3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-eqgj4acy.js → vm-hands-entry-lite-jzz73e3f.js} +10 -10
- package/bin/vm-hands/vm-hands-entry-lite-m8nqnd9j.js +126 -0
- package/bin/vm-hands/vm-hands-entry-lite-mmdwr0mf.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-2wgdvb15.js → vm-hands-entry-lite-nefcet81.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hj8n59y9.js → vm-hands-entry-lite-np07qyeq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-1rtkf2xm.js → vm-hands-entry-lite-nzmkyezg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-q0k6kx6d.js → vm-hands-entry-lite-pf5qtbj5.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-qxchbbew.js → vm-hands-entry-lite-ppmvge7n.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-m11j0f9q.js → vm-hands-entry-lite-rfz60hb3.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-s3cg1dsk.js +52 -0
- package/bin/vm-hands/vm-hands-entry-lite-s4bharcb.js +9 -0
- package/bin/vm-hands/{vm-hands-entry-lite-88swf2qr.js → vm-hands-entry-lite-s5qkb1fk.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-cc2tgsqp.js → vm-hands-entry-lite-stmbekq0.js} +16 -16
- package/bin/vm-hands/{vm-hands-entry-lite-kq0qmsw8.js → vm-hands-entry-lite-svvysppj.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-22kfyvnk.js → vm-hands-entry-lite-tdgtpx8e.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b885gwfh.js → vm-hands-entry-lite-vpz54vwj.js} +6 -6
- package/bin/vm-hands/vm-hands-entry-lite-w8w451gj.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-09m2cdkw.js → vm-hands-entry-lite-wx4ax7wg.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-z76nfb19.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-zp6naptr.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/vm-hands-executor-73b49jkg.js +11 -0
- package/bin/vm-hands/vm-hands-op-runner-ef9ts9c6.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-8z6rx1fj.js +4 -0
- package/bin/vm-hands/worker-preview-readiness-w62n91kr.js +2 -0
- package/bin/vm-hands/worker-sandbox-2r5nseff.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-cjv8m2zy.js +0 -2
- package/bin/vm-hands/api-credentials-m5akr9fv.js +0 -2
- package/bin/vm-hands/connect-cli-d60gmgnx.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-dkqb4rqy.js +0 -2
- package/bin/vm-hands/desktop-account-5v7x0ajx.js +0 -2
- package/bin/vm-hands/device-workspace-p9q9dckg.js +0 -2
- package/bin/vm-hands/hands-worker-source-cgrpm21b.js +0 -2
- package/bin/vm-hands/install-receipt-7vt2y2vh.js +0 -2
- package/bin/vm-hands/local-automation-4htjhv65.js +0 -2
- package/bin/vm-hands/local-capabilities-c04tbapa.js +0 -2
- package/bin/vm-hands/local-desktop-users-q886k0mm.js +0 -2
- package/bin/vm-hands/local-display-mac-w85956f1.js +0 -2
- package/bin/vm-hands/local-display-session-pkz7a5q9.js +0 -2
- package/bin/vm-hands/local-pty-session-5f50sqq0.js +0 -2
- package/bin/vm-hands/managed-runtime-ppypxbh9.js +0 -2
- package/bin/vm-hands/network-contract-9x9kc5vv.js +0 -2
- package/bin/vm-hands/package-78fkast4.js +0 -2
- package/bin/vm-hands/permissions-xt02c6dh.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-2tnghj3b.js +0 -2
- package/bin/vm-hands/serve-service-wanptaqv.js +0 -2
- package/bin/vm-hands/status-gt7c4ke0.js +0 -10
- package/bin/vm-hands/version-bq5j7cqg.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-2wvsyggd.js +0 -540
- package/bin/vm-hands/vm-hands-entry-lite-463m6ejk.js +0 -458
- package/bin/vm-hands/vm-hands-entry-lite-8ns59paz.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ewwx4fr3.js +0 -250
- package/bin/vm-hands/vm-hands-entry-lite-grtycq6y.js +0 -52
- package/bin/vm-hands/vm-hands-entry-lite-pmcz7j7t.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-qq9w7wq6.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-rwxbhwky.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-vrqzr15t.js +0 -3
- package/bin/vm-hands/vm-hands-executor-7k9z9988.js +0 -11
- package/bin/vm-hands/vm-hands-op-runner-n8p81rwm.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-bqsz7h0h.js +0 -4
- package/bin/vm-hands/worker-sandbox-smqj3mbe.js +0 -2
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{zt,j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{ue,Ce,Z,Ae,de,rr,Qe,X,O,H,tn}from"./vm-hands-entry-lite-3krzmhkk.js";import{_o,Vn}from"./vm-hands-entry-lite-aj139v8j.js";import{lo,P,Ke,ve,Je,ne,Ze,Bn,Se,Gt,ae,U,N,ce,Ur,Hr,jn}from"./vm-hands-entry-lite-tdgtpx8e.js";import{Pe,oe,pe,Y,Oe,q,Q}from"./vm-hands-entry-lite-4vks5phw.js";import{It,Sr,st,V,D,R,b}from"./vm-hands-entry-lite-beyyy1gz.js";import{xr,kr,bn,io,ze,vn}from"./vm-hands-entry-lite-s5qkb1fk.js";import{K}from"./vm-hands-entry-lite-hk6trmwa.js";import{Ii}from"./vm-hands-entry-lite-fbhqfzbq.js";import{p,He,Dt,at,Yi,_e,we}from"./vm-hands-entry-lite-s4bharcb.js";import{v,h,oo}from"./vm-hands-entry-lite-wx4ax7wg.js";import{E}from"./vm-hands-entry-lite-dk79tnax.js";import{er}from"./vm-hands-entry-lite-6wt5ja1k.js";import{a,ie,Do}from"./vm-hands-entry-lite-jev771b3.js";import{L,Pi,Ti,Bo,y,t,k,xt,o,d,u,i,c,_,ee,s,n}from"./vm-hands-entry-lite-avc65bd7.js";import{Oi}from"./vm-hands-entry-lite-hbs3tpdg.js";import{jo,se,Uo,C,Ne,$e,A}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";var li=()=>{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"},g={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=g[w.expected]??w.expected,I=Bo(w.input),W=g[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Ti(w.values[0])}`;return`Invalid option: expected one of ${Pi(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",I=l(w.origin);if(I)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${I.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",I=l(w.origin);if(I)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${I.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${Pi(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((I)=>`'${I}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function En(){return{localeError:li()}}L(En());class _t extends Error{}function Ro(e){let l;try{l=new URL(e)}catch{throw new _t("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new _t("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new _t("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new _t("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new _t("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as ui}from"crypto";import{isAbsolute as Oo,join as xo,relative as Po,resolve as Yt,sep as Io}from"path";var qt=t().min(1).refine(Oo,"absolute path required"),On=c({version:n(1),apiOrigin:xt(),channel:s(["staging","production"]),stateDirectory:qt,workspaceRoot:qt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:c({version:n(zt),url:t().refine((e)=>{try{return Ro(e)===e}catch{return!1}},"invalid proxy URL"),caFile:qt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(qt).min(1).max(31).optional()}),fi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=_("channel",[On,On.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),On.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!fi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else if(e.channel==="pr"){let g=e.prEnvironment,w=/^https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.up\.railway\.app$/.exec(e.apiOrigin),S=w?.[1]?.match(/(?:^|-)pr-[0-9]+(?=-|$)/g)?.map((I)=>I.replace(/^-/,""));if(!g||/^pr-[1-9][0-9]*$/.exec(g)?.[0]!==g||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==g)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let g=new URL(e.apiOrigin);if(g.origin!==e.apiOrigin||g.username||g.password||g.protocol!=="https:"&&!(g.protocol==="http:"&&Vn(g.origin))||!Vn(g.origin)&&!_o(e.channel,g.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((g)=>!je(g,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return xo(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if($r(l,e))return!1;return!$r(e,l)||E(xo(Io,Po(Yt(e),Yt(l))))}function $r(e,l){let f=Po(Yt(e),Yt(l));return f===""||f!==".."&&!f.startsWith(`..${Io}`)&&!Oo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:g,localLogins:w,folders:S,...I}=e;return ui("sha256").update(JSON.stringify(I)).digest("hex")}var pi=4,_i=[2375,2376,9222,9229];function dr(e){let l=new Set(_i);for(let f of e){let g=new URL(f);l.add(Number(g.port||(["https:","wss:"].includes(g.protocol)?443:80)))}return l}function Vr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var mi=60000;function Ao(e){let l=new AbortController,f=new Map,g=(x)=>JSON.stringify([x.jobId,x.port]);function w(x){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||x.organization_id!==M.organization_id||x.user_id!==M.user_id||x.device_id!==M.device_id)Vr()}function S(x){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===x.generation&&M.binding.target_fence_id===x.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function I(x,M,G){let F=await W(x,M,G);if(F!=="moved")return F;let T=await W(x,M,G);return T==="moved"?null:T}async function W(x,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||x.expiresAtMs<=Date.now()||x.expiresAtMs>e.expiresAtMs)return null;let T=M.opened,re=T!==void 0&&F.generation>T.generation,J=S(F);if(re){if(J){if(J.revision<=T.revision||x.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==T.attachmentRevision||J.binding.root_grant_revision!==T.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>mi)return null}else if(!J||x.expiresAtMs>Date.parse(J.expires_at)||T&&(F.generation!==T.generation||F.fenceId!==T.fenceId))return null;let z=await e.inspect(x.jobId,G),fe=e.identity(),ke=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?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ke?.snapshot_id!==J?.snapshot_id||ke?.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(!T&&F.generation===x.generation&&F.fenceId===x.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:x.port,expiresAtMs:x.expiresAtMs}}}catch{return null}}return{async open(x,M,G){w(M);let{binding:F,deviceRelayUrl:T}=at(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Vr();let re=g(F),J=f.get(re);if(J){if(!He(J.binding,F)||J.relay!==T)Vr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Vr();return{opened:!0,binding:F}}if(f.size>=pi)Vr();let z=new AbortController,fe={},ke=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>I(F,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Re=_e({binding:F,deviceRelayUrl:T,port:ke,signal:z.signal}),Fe={binding:F,relay:T,abort:z,port:ke,opened:Re};f.set(re,Fe);let Ye=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(Ye),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ke.check()))Vr();return{opened:!0,binding:F}}catch{z.abort(),Ye(),Vr()}},async close(x,M){w(M);let{binding:G}=Yi(x),F=f.get(g(G));if(!F||!He(F.binding,G))Vr();return F.abort.abort(),await F.opened.then((T)=>T.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let x of f.values())x.abort.abort();f.clear()}}}import{WebSocket as xn}from"ws";var To=(e)=>("data"in e)?e.data.length:e.bytes,Co=2*Ze;function cr(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var mt=(e)=>!["starting","running"].includes(e.state);function Hi(e,l,f=Date.now()){let g=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==g.length||Object.keys(e).some((M)=>!g.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)<=Se))cr("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))cr("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))cr("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return cr("invalid_pty_request")}if(!["ws:","wss:"].includes(I.protocol)||I.username||I.password||I.hash||I.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(I.hostname))cr("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)cr("invalid_pty_request");return{workspace:H(e.workspace)??cr("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:I.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Ho(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)cr("cancelled");let g=new xn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},I=()=>{w.abort(),S()};e.signal.addEventListener("abort",I,{once:!0});let W=setTimeout(I,Math.max(1,l.leaseExpiresAtMs-Date.now())),x=[],M=0,G=0,F=0,T=!1,re=!1,J=!1,z,fe,ke,be=(le)=>{ke=new r(le,"Bound terminal input was refused."),I()};g.on("error",()=>be("pty_relay_unavailable")),g.on("close",I),g.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 Ge=x.at(-1),Le=he&&Ge!==void 0&&"data"in Ge&&Ge.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Bn){be("pty_input_backpressure");return}if(Le)Ge.data=Buffer.concat([Ge.data,xe]);else if(he)x.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,I();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((Ee)=>Number.isSafeInteger(Ee)&&Ee>=1&&Ee<=Se))throw Error("invalid_control");x.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Re(le){return jn(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)cr(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))cr("pty_binding_changed");if(Re(he),he.process)fe??={...he.process};return he}async function Ye(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)cr("cancelled");let xe=Fe(he);if(xe.inputSequence!==G)cr("job_input_sequence");if(!mt(xe)&&xe.leaseExpiresAtMs<=Date.now())cr("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||g.readyState!==xn.OPEN||g.bufferedAmount+Buffer.byteLength(le)>Co)cr("pty_output_backpressure");g.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)cr("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(g.bufferedAmount+xe.length>Co)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)cr("pty_output_gap");return!0}async function qe(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ge,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function Te(){let le=AbortSignal.timeout(Gt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ge=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,Ge]);if(le.aborted)cr("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let Ee=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(Ee),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),g.once("open",()=>{clearTimeout(Ee),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),T=!0,z=await Ye({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)cr("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await Ye({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())cr("pty_not_ready");await qe("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,Ge=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=We(z);if(mt(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:or}=z.pty;for(let sr of[{cols:Me,rows:or>1?or-1:2},{cols:Me,rows:or}]){if(mt(z))break;let Ir=++G;if(z=await Ye({jobId:l.jobId,action:"resize",input:{sequence:Ir,...sr}}),z.inputSequence!==Ir)cr("job_input_sequence")}continue}let Ee=mt(z)||Ge?void 0:x.shift();if(Ee){M-=To(Ee);let Me=++G;try{z=await Ye("data"in Ee?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:Ee.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:Ee.cols,rows:Ee.rows}})}catch(or){if(!(or instanceof r)||or.code!=="job_input_backpressure")throw or;G-=1,x.unshift(Ee),M+=To(Ee),Ge=!0;continue}if(z.inputSequence!==Me)cr("job_input_sequence")}else if(await new Promise((Me)=>{let or=setTimeout(Me,Ge||!Be?10:50);if(S=()=>{clearTimeout(or),Me()},w.signal.aborted||!Ge&&x.length)S()}),Ge=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await Ye({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ke??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!mt(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!mt(z)||z.pty?.cleanup!=="confirmed")cr("pty_cleanup_unconfirmed");let le=Re(z);if(g.readyState===xn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);g.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await qe("pty.stopped",le)}catch(le){ke??=le}g.terminate()}if(ke)throw ke;if(e.signal.aborted)cr("cancelled");if(!z)cr("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as hi,randomUUID as An}from"crypto";import{spawnSync as Wo}from"child_process";import{closeSync as No,constants as Pn,fstatSync as gi,fsyncSync as bi,lstatSync as Bt,mkdirSync as wi,mkdtempSync as Fo,openSync as Lo,readFileSync as yi,readdirSync as zo,realpathSync as Lt,rmSync as In,unlinkSync as vi}from"fs";import{createConnection as ki}from"net";import{dirname as Si,join as nt,sep as Ei}from"path";import{tmpdir as Ri}from"os";var Pr=new Map,qr=new Map;function Kr(e,l){return hi("sha256").update(JSON.stringify([e,l])).digest("hex")}function ht(e){try{wi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Bt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Lt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function xi(e){let l;try{l=Bt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||zo(e).length>0}function pr(e){let l=Kr(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>xi(nt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;ht(f);let g=nt(f,"jobs");ht(g);let w=nt(g,l.slice(0,16));if(e.maxScopes!==void 0){let I=zo(g);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||I.length>e.maxScopes||!I.includes(l.slice(0,16))&&I.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}ht(w);let S=Fo(nt(Uo(),"reason-j-"));try{return ht(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:nt(S,"control.sock"),disposeSocket:()=>In(S,{recursive:!0,force:!0})}}catch(I){throw In(S,{recursive:!0,force:!0}),I}}var Ai=60000,Di=5000;function Ci(e){if(process.platform==="win32")return Ni(e);let l=Wo("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,g=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||g<0||g%3!==0)return null;let w=new Date(Number(f[6]),g/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Ni(e){let l=Wo(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Ne()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function $o(e,l={}){let f=nt(e.journalDirectory,"owner.lock"),g;try{g=Lo(f,Pn.O_RDONLY|Pn.O_NOFOLLOW)}catch{return null}try{let w=gi(g);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(yi(g,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Ai)return null;I={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:T,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof T!=="number"||!Number.isSafeInteger(T))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(F))I={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Ci)(F);if(z===null||z<=T+Di)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Bt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;vi(f);let x=Lo(e.journalDirectory,Pn.O_RDONLY);try{bi(x)}finally{No(x)}return I}catch{return null}finally{No(g)}}function Ko(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=Kr(l.root,l.runId);if(Pr.has(f)||l.operationId!==void 0&&qr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let g={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)g.previews=Ao({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Pr.get(g.key)===g,identity:()=>{try{return gt(l)}catch{return null}},inspect:(w,S)=>{if(Pr.get(g.key)!==g)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Go(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Pr.set(f,g),l.operationId!==void 0)qr.set(l.operationId,g);return()=>{if(Pr.get(g.key)===g)Pr.delete(g.key);if(l.operationId!==void 0&&qr.get(l.operationId)===g)qr.delete(l.operationId);g.previews?.dispose();for(let w of g.terminals.values())w.abort()}}var Li=5000,Bi=20;async function zi(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=qr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Li;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(qr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=gt(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((I)=>setTimeout(I,Bi))}if(qr.get(e.operationId)!==f||Pr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let g=Kr(e.root,e.runId);if(f.key===g)return;if(Pr.has(g))l("The taking run already has a live Hands job supervisor.");Pr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=g,Pr.set(g,f)}function it(e){let l="operationId"in e?qr.get(e.operationId):Pr.get(Kr(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 qi(e){let l=Pr.get(Kr(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 Wi(e){let l=Pr.get(Kr(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 Vi(e){let l=Kr(e.root,e.runId),f=Pr.get(l),g=f?.binding,w=g?.runId,S=g?.previewAuthority,I=g?.environment,W=e.owner&&{...e.owner},x=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!g||!S||!I||!W||!x||!g.workspace)return M();let G=Object.freeze({...g.workspace}),F=gt(g),T=I.current(),re=()=>{if(Pr.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||O(e.workspace)!==O(G))M();let z=gt(g),fe=I.current();if(z.generation!==F.generation||z.fenceId!==F.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==T.snapshot_id||fe.revision!==T.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||x.device_id!==e.deviceId||x.binding!==fe.binding.kind||x.target_revision!==fe.binding.target_revision||x.root_grant_revision!==fe.binding.root_grant_revision||x.target_generation!==F.generation||x.target_fence_id!==F.fenceId)M()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return M();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Ho({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(T.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:T.revision,snapshotId:T.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:T.binding.kind,targetRevision:T.binding.target_revision,rootGrantRevision:T.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>hr(F,Ur(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 Gi(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Pr.get(Kr(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 Go(l,e.payload,e.signal)}var ji=1e4,Mi=20,Fi=ve/2,Ui=Ke/2,$i=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Go(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:g,...w}=l;if(g!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof g!=="number"||!Number.isSafeInteger(g)||g<1||g>ji))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=gt(e);return hr(G,Ur(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:An()})),f)},I=await S(w);if(g===void 0)return I;let W=Date.now()+g,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Fi&&$i(x.job)<Ui&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Mi,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;x=M}catch{break}}return x}function gt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!U(l.generation)||!N(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function hr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((g,w)=>{let S=ki(e.socketPath),I="",W=!1,x,M=(F,T)=>{if(W)return;if(W=!0,clearTimeout(x),f.removeEventListener("abort",G),S.destroy(),F)w(F);else g(T)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),x=setTimeout(()=>M(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>M(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
3
|
+
`)),S.on("data",(F)=>{if(I+=F,Buffer.byteLength(I)>Je)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=Hr(I.trim());if(F.id!==l.id||F.generation!==e.generation||F.ok&&F.job.jobId!==l.jobId)throw Error("identity");M(void 0,F)}catch{M(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),S.once("close",()=>{if(!W)M(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function Mo(e){let l=Lt(e.root),f=e.authority,g=Date.parse(e.leaseUntil),w=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(g)||g<=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:g,assertCurrent:w};let S=Kr(l,e.runId),I=Pr.get(S),W=I?.binding;if(!W?.environment||!W.workspace||W.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let x=W.environment.current(),M=()=>{w();let F=W.environment.current(),T=gt(W);if(Pr.get(S)!==I||F.github_auth!=="local_gh"||F.run_id!==W.runId||f.runId!==e.runId||F.device_id!==f.deviceId||F.root_id!==f.rootId||String(F.binding.root_grant_revision)!==f.rootRevision||F.binding.target_generation!==f.generation||F.binding.target_fence_id!==f.fenceId||T.generation!==f.generation||T.fenceId!==f.fenceId||F.snapshot_id!==x.snapshot_id||F.revision!==x.revision)throw Error("local_device_gh_authority_changed")};M();let G=ie(l,W.workspace);return{root:G.boundary,signal:e.signal,deadlineMs:g,privateDirectory:Si(W.environment.path),repoPath:G.path,readOnly:f.readOnly,forbiddenSecretValues:Object.values(x.variables),secretNames:(F)=>Object.entries(x.variables).filter(([,T])=>T.trim()===F.trim()).map(([T])=>`variable ${T}`),assertCurrent:M}}async function Ki(e,l){let f=Pe.parse(e.request),g=oe.parse(e.authority);if(g.contributorRefresh&&f.kind==="read"&&g.readOnly)return l(Mo(e));let w=Boolean(g.contributorRefresh);if(w&&(g.merge||f.kind!=="pr_mutation"||f.mutation.action!=="edit"||typeof f.mutation.body!=="string"||f.mutation.title!==void 0||f.mutation.base!==void 0||g.readOnly||g.runId!==e.runId||g.repoFullName!==f.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(f.kind!=="pr_merge"&&!w){if(g.merge)throw Error("local_device_gh_merge_authority_invalid");return l(Mo(e))}if(!w&&(!g.merge||g.readOnly||g.runId!==e.runId||g.repoFullName!==f.repoFullName||g.merge.source==="agent"&&(g.generation===null||g.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let S=Lt(e.root),I=Bt(S),W=Date.parse(e.leaseUntil);if(!Number.isFinite(W)||W<=Date.now())throw Error("local_device_gh_lease_expired");let x=Lt(Ri());if(x===S||x.startsWith(S+Ei))throw Error("local_device_gh_private_scope_unavailable");let M=Fo(nt(x,"reason-gh-merge-"));try{ht(M);let G=()=>{if(e.signal.throwIfAborted(),Date.now()>=W)throw Error("local_device_gh_lease_expired");let F=Bt(e.root);if(F.isSymbolicLink()||F.dev!==I.dev||F.ino!==I.ino||Lt(e.root)!==S)throw Error("local_device_gh_authority_changed");ht(M)};return G(),await l({root:S,readOnly:!1,privateDirectory:M,forbiddenSecretValues:[],signal:e.signal,deadlineMs:W,assertCurrent:G})}finally{In(M,{recursive:!0,force:!0})}}var qo=43200000;function bt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Jo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Vo(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function Ji(e){if(!Jo(e)||!Vo(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 g of["validation_now_ms","expiry_ms"]){let w=e[g];if(w!==null&&(typeof w!=="number"||bt(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(!Jo(f)||!Vo(f,["kind","status","sha256","observed_at_ms"])||f.observed_at_ms!==null&&(typeof f.observed_at_ms!=="number"||bt(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()}),Yo=new RegExp(st.tokenPattern),Qi=c({token_url:xt().max(2048),request_token:t().min(1).max(8192).regex(Yo),aws_credentials_url:xt().max(2048).nullable()});function Xo(e,l){let f=(g,w)=>{try{let S=new URL(g);return S.origin===new URL(l).origin&&S.pathname===w&&!S.username&&!S.password&&!S.search&&!S.hash}catch{return!1}};if(!Yo.test(e.request_token)||!f(e.token_url,st.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,st.awsPath))return null;return{REASON_OIDC_TOKEN_URL:e.token_url,REASON_OIDC_REQUEST_TOKEN:e.request_token,...e.aws_credentials_url!==null?{AWS_CONTAINER_CREDENTIALS_FULL_URI:e.aws_credentials_url,AWS_CONTAINER_AUTHORIZATION_TOKEN:e.request_token}:{}}}function Zo(e){return new TextEncoder().encode(e).byteLength}function ea(e){return Zo(JSON.stringify(e)+`
|
|
4
|
+
`)}var fr=c({version:n(1),snapshot_id:k(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:k(),root_id:k(),binding:Tn.extend({target_generation:o().int().positive(),target_fence_id:k()}),expires_at:y.datetime({offset:!0}),variables:ee(t().max(128).regex(It),t().refine((e)=>!e.includes("\x00")&&Zo(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:n("local_gh").optional(),git:c({base_url:xt().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:Qi.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ea(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ra}from"child_process";import{basename as ta,isAbsolute as Eu}from"path";var na=0,Qo=120000,es=15000,oa=65536;function Dn(e=process.execPath,l=process.argv[1]){let f=ta(e),g=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:g?[l]:[]}}function Zi(e={}){let{command:l,prefix:f}=Dn(e.executablePath,e.sourceEntrypoint),g=e.spawnProcess??ra,w=e.now??Date.now,S=null,I=0,W=!1,x=(G)=>{try{G.kill("SIGKILL")}catch{}},M=()=>{if(W)return;if(S&&w()-I<Qo-es)return;if(S){let F=S;S=null,x(F)}let G;try{G=g(l,[...f,"__device","__hands-worker","--handoff-fd",String(na)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}S=G,I=w(),G.on("error",()=>{if(S===G)S=null}),G.once("exit",(F,T)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:F,exit_signal:T})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:M,take(G){let F=S;if(!F||W)return null;let T=G.args.at(-1),re=G.options.env,J=G.options.cwd,z=[...f,"__device","__hands-worker","--config"];if(G.command!==l||G.args.length!==z.length+1||z.some((Re,Fe)=>G.args[Fe]!==Re)||typeof T!=="string"||!re||typeof J!=="string"||G.options.shell||JSON.stringify(G.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;S=null;let fe=F.stdin,ke={configPath:T,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Re)=>typeof Re[1]==="string"))},be=JSON.stringify(ke);if(F.exitCode!==null||F.signalCode!==null||!fe||fe.destroyed||w()-I>=Qo-es||Buffer.byteLength(be,"utf8")>oa)return x(F),null;return fe.on("error",()=>{return}),fe.end(be),F.once("exit",()=>{M()}),e.log?.("hands.worker_prespawn_taken",{pid:F.pid??null}),F},adopt(G){G.once("exit",()=>{M()})},close(){if(W=!0,S)x(S);S=null}}}import{accessSync as la,constants as ua,statSync as fa}from"fs";import{homedir as pa,tmpdir as _a,userInfo as ma}from"os";import{delimiter as ha,win32 as ga}from"path";var sa=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var ia=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],aa=new Set(["BUN_INSTALL"]);var ca=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function da(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>ca.test(l.replaceAll("_","-")))}function rs(e){return Object.keys(e).filter((l)=>sa.has(l)&&!(l==="NODE_OPTIONS"&&da(e[l]))||ia.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!aa.has(l)).sort()}var ba=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),wa=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,ya=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,va=/^[A-Za-z_][A-Za-z0-9_]*$/;function mr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ga.isAbsolute(w):w.startsWith("/"))||/[\0\r\n]/.test(w)||w.length>32768)throw Error("invalid_host_execution_environment");return w};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let f=new Set(rs(e)),g=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,I]=w;return typeof I==="string"&&I.length<=32768&&!I.includes("\x00")&&S.length<=128&&va.test(S)&&!f.has(S)&&!ba.has(S)&&!wa.test(S)&&!ya.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||pa()),path:((w)=>process.platform==="win32"?vn(w):w)(kr(e.PATH??"").join(ha)||xr),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||_a()),variables:g}}function gr(e=process.env,l=()=>ma().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return la(w,ua.X_OK),fa(w).isFile()}catch{return!1}};if(f(e.SHELL))return e.SHELL;let g;try{g=l()}catch{g=void 0}return f(g)?g:"/bin/zsh"}import{readdir as ka}from"fs/promises";var Sa=15000;function hn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function fn(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then try again.")}async function ts(e,{timeoutMs:l=Sa,open:f=(g)=>ka(g)}={}){let g,w=new Promise((S)=>{g=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(hn(S))throw fn(e);if(S instanceof r)throw S}finally{clearTimeout(g)}}import{chmodSync as rc,closeSync as tc,constants as $n,fstatSync as nc,lstatSync as vs,openSync as oc,readSync as sc,realpathSync as Kn,unlinkSync as ic}from"fs";import{lookup as ac}from"dns/promises";import{createRequire as cc}from"module";import{request as dc}from"http";import{request as lc}from"https";import dt from"net";import{platform as Os}from"os";import{basename as uc,extname as fc,isAbsolute as ks,relative as Gn,resolve as vt,sep as Jn}from"path";var ns=String.raw`
|
|
5
|
+
async (roots) => {
|
|
6
|
+
"use strict";
|
|
7
|
+
const version = 2;
|
|
8
|
+
if (globalThis.__araHandsRepl && globalThis.__araHandsRepl.version === version) return;
|
|
9
|
+
const hostCall = globalThis.__araHandsRpc;
|
|
10
|
+
if (typeof hostCall !== "function") throw new Error("Reason Hands browser bridge is not installed");
|
|
11
|
+
try { delete globalThis.__araHandsRpc; } catch (error) {
|
|
12
|
+
if (!(error instanceof TypeError)) throw error;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const handles = new WeakMap();
|
|
16
|
+
const bytes = new WeakMap();
|
|
17
|
+
const routes = new WeakMap();
|
|
18
|
+
const derived = new Set([
|
|
19
|
+
"browser", "context", "frame", "frameLocator", "getByAltText", "getByLabel",
|
|
20
|
+
"getByPlaceholder", "getByRole", "getByTestId", "getByText", "getByTitle",
|
|
21
|
+
"contentFrame", "locator", "nth", "mainFrame", "newContext", "newPage", "opener", "owner", "page", "parentFrame",
|
|
22
|
+
]);
|
|
23
|
+
const locatorMethods = new Set([
|
|
24
|
+
"all", "allInnerTexts", "allTextContents", "and", "ariaSnapshot", "blur",
|
|
25
|
+
"boundingBox", "check", "clear", "click", "contentFrame", "count", "dblclick",
|
|
26
|
+
"dragTo", "evaluate", "evaluateAll", "fill", "filter", "focus", "getAttribute",
|
|
27
|
+
"hover", "innerHTML", "innerText", "inputValue", "isChecked", "isEditable",
|
|
28
|
+
"isEnabled", "isHidden", "isVisible", "or", "page", "press", "pressSequentially",
|
|
29
|
+
"screenshot", "scrollIntoViewIfNeeded", "selectOption", "setInputFiles", "tap",
|
|
30
|
+
"textContent", "type", "uncheck", "waitFor",
|
|
31
|
+
]);
|
|
32
|
+
const pageMethods = new Set([
|
|
33
|
+
"addInitScript", "addScriptTag", "addStyleTag", "bringToFront", "close", "content",
|
|
34
|
+
"emulateMedia", "evaluate", "frameLocator", "frames", "goBack", "goForward", "goto",
|
|
35
|
+
"isClosed", "pdf", "reload", "route", "screenshot", "captureScreenshot", "selectOption", "setContent",
|
|
36
|
+
"setDefaultNavigationTimeout", "setDefaultTimeout", "setExtraHTTPHeaders", "setInputFiles",
|
|
37
|
+
"setViewportSize", "title", "unroute", "url", "viewportSize", "waitForFunction",
|
|
38
|
+
"waitForLoadState", "waitForNavigation", "waitForTimeout", "waitForURL",
|
|
39
|
+
]);
|
|
40
|
+
const contextMethods = new Set([
|
|
41
|
+
"startRecording", "stopRecording",
|
|
42
|
+
"addCookies", "addInitScript", "clearCookies", "clearPermissions", "close", "cookies",
|
|
43
|
+
"grantPermissions", "pages", "route", "setDefaultNavigationTimeout", "setDefaultTimeout",
|
|
44
|
+
"setExtraHTTPHeaders", "setGeolocation", "setHTTPCredentials", "setOffline",
|
|
45
|
+
"setViewportSize", "storageState", "unroute", "viewportSize",
|
|
46
|
+
]);
|
|
47
|
+
const browserMethods = new Set(["close", "contexts", "isConnected", "version"]);
|
|
48
|
+
const frameMethods = new Set([
|
|
49
|
+
"addScriptTag", "addStyleTag", "childFrames", "content", "evaluate", "frameLocator",
|
|
50
|
+
"goto", "isDetached", "name", "parentFrame", "setContent", "title", "url",
|
|
51
|
+
"waitForFunction", "waitForLoadState", "waitForNavigation", "waitForTimeout", "waitForURL",
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
function record(value) {
|
|
55
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
56
|
+
const proto = Object.getPrototypeOf(value);
|
|
57
|
+
return proto === Object.prototype || proto === null;
|
|
58
|
+
}
|
|
59
|
+
function handle(value) {
|
|
60
|
+
return record(value) && value.$handsRepl === "handle"
|
|
61
|
+
&& typeof value.id === "string" && typeof value.kind === "string";
|
|
62
|
+
}
|
|
63
|
+
function clone(value, stack) {
|
|
64
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return value;
|
|
65
|
+
if (typeof value === "number") {
|
|
66
|
+
if (!Number.isFinite(value)) throw new TypeError("Reason Hands bridge accepts only finite numbers");
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
if (!value || typeof value !== "object") throw new TypeError("Reason Hands bridge accepts only JSON data");
|
|
70
|
+
if (stack.has(value)) throw new TypeError("Reason Hands bridge does not accept cyclic data");
|
|
71
|
+
stack.add(value);
|
|
72
|
+
try {
|
|
73
|
+
if (Array.isArray(value)) return value.map((item) => clone(item, stack));
|
|
74
|
+
if (!record(value)) throw new TypeError("Reason Hands bridge accepts only plain objects");
|
|
75
|
+
const output = Object.create(null);
|
|
76
|
+
for (const key of Object.keys(value)) {
|
|
77
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") {
|
|
78
|
+
throw new TypeError("Reason Hands bridge rejects unsafe object keys");
|
|
79
|
+
}
|
|
80
|
+
output[key] = clone(value[key], stack);
|
|
81
|
+
}
|
|
82
|
+
return output;
|
|
83
|
+
} finally { stack.delete(value); }
|
|
84
|
+
}
|
|
85
|
+
function data(value) { return clone(value, new WeakSet()); }
|
|
86
|
+
function refOf(value) {
|
|
87
|
+
const ref = value && typeof value === "object" ? handles.get(value) : undefined;
|
|
88
|
+
if (!ref) throw new TypeError("Reason Hands operation needs a browser target");
|
|
89
|
+
return ref;
|
|
90
|
+
}
|
|
91
|
+
async function wire(value) {
|
|
92
|
+
const target = value && typeof value === "object" ? handles.get(value) : undefined;
|
|
93
|
+
if (target) return (await target).handle;
|
|
94
|
+
const binary = value && typeof value === "object" ? bytes.get(value) : undefined;
|
|
95
|
+
if (binary) return binary;
|
|
96
|
+
const route = value && typeof value === "object" ? routes.get(value) : undefined;
|
|
97
|
+
if (route) return route;
|
|
98
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return value;
|
|
99
|
+
if (typeof value === "number") {
|
|
100
|
+
if (!Number.isFinite(value)) throw new TypeError("Reason Hands bridge accepts only finite numbers");
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
if (Array.isArray(value)) return await Promise.all(value.map(wire));
|
|
104
|
+
if (!record(value)) throw new TypeError("Reason Hands bridge accepts only JSON data");
|
|
105
|
+
const output = Object.create(null);
|
|
106
|
+
for (const key of Object.keys(value)) output[key] = await wire(value[key]);
|
|
107
|
+
return output;
|
|
108
|
+
}
|
|
109
|
+
function decode(value) {
|
|
110
|
+
if (handle(value)) return makeTarget(value);
|
|
111
|
+
if (record(value) && value.$handsRepl === "bytes" && typeof value.base64 === "string") {
|
|
112
|
+
const output = Object.freeze({ $handsRepl: "bytes", base64: value.base64 });
|
|
113
|
+
bytes.set(output, output);
|
|
114
|
+
return output;
|
|
115
|
+
}
|
|
116
|
+
if (record(value) && value.$handsRepl === "undefined") return undefined;
|
|
117
|
+
if (Array.isArray(value)) return value.map(decode);
|
|
118
|
+
if (!record(value)) return value;
|
|
119
|
+
const output = Object.create(null);
|
|
120
|
+
for (const key of Object.keys(value)) output[key] = decode(value[key]);
|
|
121
|
+
return output;
|
|
122
|
+
}
|
|
123
|
+
async function rpc(request) { return decode(await hostCall(request)); }
|
|
124
|
+
async function invoke(ref, method, args) {
|
|
125
|
+
return await rpc({ type: "call", target: ref.handle, method, args: await Promise.all(args.map(wire)) });
|
|
126
|
+
}
|
|
127
|
+
function targetFrom(value) {
|
|
128
|
+
const ref = value && typeof value === "object" ? handles.get(value) : undefined;
|
|
129
|
+
if (!ref) throw new Error("Reason Hands bridge received an invalid target");
|
|
130
|
+
return ref;
|
|
131
|
+
}
|
|
132
|
+
function lazy(refPromise) {
|
|
133
|
+
const object = Object.create(null);
|
|
134
|
+
const ready = Promise.resolve(refPromise);
|
|
135
|
+
const proxy = new Proxy(object, {
|
|
136
|
+
get(_object, key) {
|
|
137
|
+
if (key === "then") return (resolve, reject) => {
|
|
138
|
+
// Derived targets carry the bridge's internal { handle, kind } ref,
|
|
139
|
+
// not the wire handle accepted by makeTarget. Passing the wrapper
|
|
140
|
+
// used to throw inside this detached fulfillment callback; because
|
|
141
|
+
// that rejection was not forwarded to the thenable consumer, every
|
|
142
|
+
// await context.newPage() / await page.context() hung until an
|
|
143
|
+
// outer tool deadline destroyed the evaluator execution context.
|
|
144
|
+
ready.then((ref) => {
|
|
145
|
+
try { resolve(makeTarget(ref.handle)); } catch (error) { reject(error); }
|
|
146
|
+
}, reject);
|
|
147
|
+
};
|
|
148
|
+
if (typeof key !== "string") return undefined;
|
|
149
|
+
if (key === "first" || key === "last") return lazy(ready.then(async (ref) => targetFrom(await invoke(ref, key, []))));
|
|
150
|
+
if (derived.has(key)) return (...args) => lazy(ready.then(async (ref) => targetFrom(await invoke(ref, key, args))));
|
|
151
|
+
if (key === "evaluate" || key === "evaluateAll") return (source, argument) => ready.then((ref) => evaluateInTarget(ref, source, argument));
|
|
152
|
+
return (...args) => ready.then((ref) => invoke(ref, key, args));
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
handles.set(proxy, ready);
|
|
156
|
+
return proxy;
|
|
157
|
+
}
|
|
158
|
+
function makeTarget(handleValue) {
|
|
159
|
+
if (!handle(handleValue)) throw new Error("Reason Hands bridge received an invalid handle");
|
|
160
|
+
const ref = { handle: Object.freeze({ $handsRepl: "handle", id: handleValue.id, kind: handleValue.kind }), kind: handleValue.kind };
|
|
161
|
+
const object = Object.create(null);
|
|
162
|
+
// Preserve the existing synchronous viewport facade. URL reads use the
|
|
163
|
+
// dispatcher: a human can navigate the real page without an agent goto,
|
|
164
|
+
// and a new evaluator must not invent about:blank for that live page.
|
|
165
|
+
const meta = {
|
|
166
|
+
viewport: ref.kind === "page" && ref.handle.id === roots.page.id
|
|
167
|
+
? { width: 1440, height: 900 }
|
|
168
|
+
: undefined,
|
|
169
|
+
};
|
|
170
|
+
const invokeDerived = (method, args) => lazy(Promise.resolve(invoke(ref, method, args)).then(targetFrom));
|
|
171
|
+
const get = (_object, key) => {
|
|
172
|
+
if (key === "first" || key === "last") return invokeDerived(key, []);
|
|
173
|
+
if (typeof key !== "string") return undefined;
|
|
174
|
+
if (key === "evaluate" || key === "evaluateAll") return (source, argument) => evaluateInTarget(ref, source, argument);
|
|
175
|
+
if (ref.kind === "page" && key === "viewportSize" && meta.viewport) {
|
|
176
|
+
return () => ({ ...meta.viewport });
|
|
177
|
+
}
|
|
178
|
+
if (ref.kind === "page" && key === "setViewportSize") {
|
|
179
|
+
return (next) => invoke(ref, key, [next]).then((value) => {
|
|
180
|
+
if (record(next) && typeof next.width === "number" && typeof next.height === "number") {
|
|
181
|
+
meta.viewport = { width: next.width, height: next.height };
|
|
182
|
+
}
|
|
183
|
+
return value;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if ((ref.kind === "page" || ref.kind === "context") && key === "route") {
|
|
187
|
+
return async (url, handler) => {
|
|
188
|
+
if (typeof handler !== "function") return await invoke(ref, key, [url, handler]);
|
|
189
|
+
let fulfillment;
|
|
190
|
+
const route = Object.freeze({
|
|
191
|
+
fulfill: async (options) => {
|
|
192
|
+
if (fulfillment) throw new TypeError("route() can register one fulfillment action");
|
|
193
|
+
fulfillment = routeFulfill(options);
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
await handler(route);
|
|
197
|
+
if (!fulfillment) {
|
|
198
|
+
throw new TypeError("route() supports a data-only route.fulfill({ ... }) callback");
|
|
199
|
+
}
|
|
200
|
+
return await invoke(ref, key, [url, fulfillment]);
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
if (derived.has(key)) return (...args) => invokeDerived(key, args);
|
|
204
|
+
const methods = ref.kind === "browser" ? browserMethods
|
|
205
|
+
: ref.kind === "context" ? contextMethods
|
|
206
|
+
: ref.kind === "page" ? pageMethods
|
|
207
|
+
: ref.kind === "frame" ? frameMethods
|
|
208
|
+
: locatorMethods;
|
|
209
|
+
if (!methods.has(key)) return undefined;
|
|
210
|
+
return (...args) => invoke(ref, key, args);
|
|
211
|
+
};
|
|
212
|
+
const proxy = new Proxy(object, { get });
|
|
213
|
+
handles.set(proxy, Promise.resolve(ref));
|
|
214
|
+
return proxy;
|
|
215
|
+
}
|
|
216
|
+
async function evaluateInTarget(ref, source, argument) {
|
|
217
|
+
const text = typeof source === "function" ? Function.prototype.toString.call(source) : source;
|
|
218
|
+
if (typeof text !== "string" || !text.trim()) throw new TypeError("evaluate() needs a function or expression string");
|
|
219
|
+
const value = argument === undefined ? undefined : JSON.stringify(await wire(argument));
|
|
220
|
+
let renderer;
|
|
221
|
+
if (ref.kind === "locator") {
|
|
222
|
+
renderer = typeof source === "function"
|
|
223
|
+
? "(element) => (" + text + ")(element" + (value === undefined ? "" : ", " + value) + ")"
|
|
224
|
+
: text;
|
|
225
|
+
} else {
|
|
226
|
+
renderer = typeof source === "function"
|
|
227
|
+
? "(" + text + ")(" + (value === undefined ? "" : value) + ")"
|
|
228
|
+
: value === undefined ? text : "(" + text + ")(" + value + ")";
|
|
229
|
+
}
|
|
230
|
+
return await invoke(ref, "evaluate", [renderer]);
|
|
231
|
+
}
|
|
232
|
+
function routeFulfill(options) {
|
|
233
|
+
const token = Object.freeze(Object.create(null));
|
|
234
|
+
routes.set(token, { $handsRepl: "routeFulfill", options: data(options) });
|
|
235
|
+
return token;
|
|
236
|
+
}
|
|
237
|
+
const replConsole = Object.freeze({
|
|
238
|
+
log: (...values) => { logs.push(values.map(render).join(" ")); },
|
|
239
|
+
info: (...values) => { logs.push(values.map(render).join(" ")); },
|
|
240
|
+
warn: (...values) => { logs.push("[warn] " + values.map(render).join(" ")); },
|
|
241
|
+
error: (...values) => { logs.push("[error] " + values.map(render).join(" ")); },
|
|
242
|
+
});
|
|
243
|
+
function render(value) {
|
|
244
|
+
if (value === undefined) return "undefined";
|
|
245
|
+
if (typeof value === "string") return value;
|
|
246
|
+
try { const text = JSON.stringify(value); return text === undefined ? String(value) : text; } catch { return "[unrenderable]"; }
|
|
247
|
+
}
|
|
248
|
+
const logs = [];
|
|
249
|
+
const browser = makeTarget(roots && roots.browser);
|
|
250
|
+
const context = makeTarget(roots && roots.context);
|
|
251
|
+
const page = makeTarget(roots && roots.page);
|
|
252
|
+
const state = Object.create(null);
|
|
253
|
+
async function a11y(target) {
|
|
254
|
+
const ref = target === undefined ? await refOf(page) : await refOf(target);
|
|
255
|
+
return await rpc({ type: "a11y", target: ref.handle });
|
|
256
|
+
}
|
|
257
|
+
async function view(source, options) {
|
|
258
|
+
return await rpc({ type: "view", source: await wire(source), options: options === undefined ? Object.create(null) : await wire(options) });
|
|
259
|
+
}
|
|
260
|
+
async function evaluate(code) {
|
|
261
|
+
if (typeof code !== "string") throw new TypeError("Reason Hands REPL code must be a string");
|
|
262
|
+
logs.length = 0;
|
|
263
|
+
let program;
|
|
264
|
+
let statementList = false;
|
|
265
|
+
try { program = new Function('"use strict"; return (async () => await (' + code + "\n))();"); }
|
|
266
|
+
catch {
|
|
267
|
+
statementList = true;
|
|
268
|
+
const strictCode = '"use strict";\n' + code;
|
|
269
|
+
program = new Function(
|
|
270
|
+
'"use strict"; return (async () => (0, eval)(' + JSON.stringify(strictCode) + '))();',
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
let value;
|
|
274
|
+
try {
|
|
275
|
+
value = await program();
|
|
276
|
+
} catch (error) {
|
|
277
|
+
// Indirect eval preserves a statement-list completion value but cannot
|
|
278
|
+
// parse top-level await or return. Those programs retain the prior async
|
|
279
|
+
// block behavior; a syntax failure occurs before any user code executes.
|
|
280
|
+
if (!statementList || !(error instanceof SyntaxError)) throw error;
|
|
281
|
+
program = new Function('"use strict"; return (async () => {' + code + "\n})();");
|
|
282
|
+
value = await program();
|
|
283
|
+
}
|
|
284
|
+
const output = render(value);
|
|
285
|
+
return logs.length === 0 ? output : value === undefined ? logs.join("\n") : logs.join("\n") + "\n" + output;
|
|
286
|
+
}
|
|
287
|
+
function install(name, value) { Object.defineProperty(globalThis, name, { value, configurable: false, enumerable: false, writable: false }); }
|
|
288
|
+
install("browser", browser); install("context", context); install("page", page);
|
|
289
|
+
install("state", state); install("browserState", state);
|
|
290
|
+
install("a11y", a11y); install("view", view); install("routeFulfill", routeFulfill); install("console", replConsole);
|
|
291
|
+
install("__araHandsRepl", Object.freeze({ version, evaluate }));
|
|
292
|
+
}
|
|
293
|
+
`.trim(),os=String.raw`
|
|
294
|
+
async (input) => {
|
|
295
|
+
const bridge = globalThis.__araHandsRepl;
|
|
296
|
+
if (!bridge || typeof bridge.evaluate !== "function") throw new Error("Reason Hands browser bridge is not installed");
|
|
297
|
+
return await bridge.evaluate(typeof input === "string" ? input : input && input.code);
|
|
298
|
+
}
|
|
299
|
+
`.trim();import{Buffer as wt}from"buffer";import{randomUUID as Ea}from"crypto";class cs 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 ds=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),ss=/^hands_[A-Za-z0-9_-]{8,128}$/,Ra=2048,ls=32,us=1e4,Oa=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function xa(e){let l=e.split("+"),f=(l.pop()??"").replace(/^Key/,"").toLowerCase();if(f==="f12")return!0;if(l.some((g)=>["Control","ControlOrMeta","Meta"].includes(g))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(f))return!0;if(l.some((g)=>["Control","ControlOrMeta","Meta"].includes(g))&&l.includes("Shift")&&f==="c")return!0;return l.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(f)}var Pa=(e)=>{let l=e.closest("a[href],area[href]");return{password:e.tagName==="INPUT"&&e.type==="password",executableLink:Boolean(l&&!/^(https?:|about:blank)/i.test(l.href))}},fs={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 cs(e)}function Nr(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let l=Object.getPrototypeOf(e);return l===Object.prototype||l===null}function yt(e,l=0,f={nodes:0}){if(l>ls||++f.nodes>us)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 g of e)yt(g,l+1,f);return}if(!Nr(e))Ie("hands_repl_invalid_json");for(let[g,w]of Object.entries(e)){if(ds.has(g))Ie("hands_repl_invalid_json");yt(w,l+1,f)}}function Cn(e){return typeof e==="string"&&Object.hasOwn(fs,e)}function Ia(e){if(!e.endsWith("[]"))return null;let l=e.slice(0,-2);return Cn(l)?l:null}function is(e){return Nr(e)&&Object.keys(e).length===2&&e.$handsRepl==="bytes"&&typeof e.base64==="string"}function Aa(e){return Nr(e)&&Object.keys(e).length===1&&e.$handsRepl==="undefined"}function as(e){return Nr(e)&&Object.keys(e).length===2&&e.$handsRepl==="routeFulfill"&&"options"in e}function Yr(e){return!!e&&typeof e==="object"}function Xt(){return Object.freeze({$handsRepl:"undefined"})}function Ta(e){if(!wt.isBuffer(e)&&!(e instanceof Uint8Array))Ie("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:wt.from(e).toString("base64")})}function ps(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??Ra;if(!Number.isInteger(l)||l<3||l>1e5)Ie("hands_repl_invalid_handle_limit");let f=new Map,g=new WeakMap,w=e.createOpaqueId??Ea,S=(T,re)=>{if(!Yr(re))Ie("hands_repl_expected_target");let J=g.get(re)?.get(T);if(J)return J;if(f.size>=l)Ie("hands_repl_handle_limit");let z="";for(let be=0;be<16;be+=1){let Re=`hands_${w()}`;if(ss.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:T});f.set(z,{kind:T,target:re});let ke=g.get(re);if(!ke)ke=new Map,g.set(re,ke);return ke.set(T,fe),fe},I=Object.freeze({browser:S("browser",e.browser),context:S("context",e.context),page:S("page",e.page)}),W=(T)=>{if(!Nr(T)||Object.keys(T).length!==3||T.$handsRepl!=="handle"||typeof T.id!=="string"||!ss.test(T.id)||!Cn(T.kind))Ie("hands_repl_invalid_handle");let re=f.get(T.id);if(!re||re.kind!==T.kind)Ie("hands_repl_unknown_handle");return re},x=(T,re=0,J=new Set)=>{if(re>ls)Ie("hands_repl_json_too_complex");if(T===void 0)return Xt();if(T===null||typeof T==="boolean"||typeof T==="string")return T;if(typeof T==="number"){if(!Number.isFinite(T))Ie("hands_repl_non_json_result");return T}if(Array.isArray(T)){if(J.has(T))Ie("hands_repl_cyclic_result");J.add(T);try{return T.map((z)=>x(z,re+1,J))}finally{J.delete(T)}}if(!Nr(T))Ie("hands_repl_non_json_result");if(J.has(T))Ie("hands_repl_cyclic_result");J.add(T);try{let z=Object.create(null);for(let fe of Object.keys(T)){let ke=Object.getOwnPropertyDescriptor(T,fe);if(!ke||!("value"in ke))continue;z[fe]=x(ke.value,re+1,J)}return z}finally{J.delete(T)}},M=(T,re)=>{if(re==="void")return Xt();if(re==="json")return x(T);if(re==="bytes")return Ta(T);let J=Ia(re);if(J){if(!Array.isArray(T))Ie("hands_repl_expected_target_list");if(J==="context"&&T.some((z)=>z!==e.context))Ie("hands_repl_foreign_context");return T.map((z)=>S(J,z))}if(T===null||T===void 0)return Xt();if(!Cn(re))Ie("hands_repl_invalid_return_kind");if(re==="context"&&T!==e.context)Ie("hands_repl_foreign_context");return S(re,T)},G=(T)=>{if(Nr(T)&&T.$handsRepl==="handle")return W(T).target;if(is(T))return wt.from(T.base64,"base64");if(Aa(T))return;if(as(T))Ie("hands_repl_route_fulfill_only");if(Array.isArray(T))return T.map(G);if(!Nr(T))return T;let re=Object.create(null);for(let[J,z]of Object.entries(T))re[J]=G(z);return re};return Object.freeze({roots:I,dispatch:async(T)=>{if(!Nr(T)||typeof T.type!=="string")Ie("hands_repl_invalid_request");if(T.type==="a11y"){let ye=T.target===void 0?f.get(I.page.id):W(T.target);if(!ye||ye.kind!=="page"&&ye.kind!=="locator")Ie("hands_repl_invalid_a11y_target");return x(await e.a11y(ye.target))}if(T.type==="view"){if(yt(T.source),T.options!==void 0)yt(T.options);let ye=is(T.source)?wt.from(T.source.base64,"base64"):T.source;if(e.privateProfile&&!wt.isBuffer(ye))Ie("hands_repl_profile_requires_image_bytes");return x(await e.view(ye,T.options))}if(T.type!=="call")Ie("hands_repl_invalid_request");if(typeof T.method!=="string"||T.method.length===0||T.method.length>128)Ie("hands_repl_invalid_method");if(ds.has(T.method))Ie("hands_repl_forbidden_method");let re=W(T.target),J=T.args??[];if(!Array.isArray(J))Ie("hands_repl_invalid_arguments");if(yt(J),re.kind==="page"&&T.method==="captureScreenshot"){if(J.length!==0)Ie("hands_repl_invalid_arguments");if(!e.screenshotExport)Ie("hands_repl_screenshot_export_unavailable");return x(await e.screenshotExport(re.target))}if(re.kind==="context"&&["startRecording","stopRecording"].includes(T.method)){if(!e.recording||re.target!==e.context)Ie("hands_repl_recording_unavailable");if(J.length>(T.method==="startRecording"?1:0))Ie("hands_repl_invalid_arguments");return x(T.method==="startRecording"?await e.recording.start(J[0]):await e.recording.stop())}if(e.privateProfile){let ye=T.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(ye)||re.kind==="browser"&&ye==="close"||re.kind==="context"&&ye==="close")Ie("hands_repl_private_profile_method_denied");if(re.kind==="browser"&&ye==="contexts")return M([e.context],"context[]");if((ye==="screenshot"||ye==="pdf")&&Nr(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"||!Oa.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 qe=Reflect.get(re.target,"all");if(typeof qe!=="function")Ie("hands_repl_private_profile_probe_unavailable");let Te=await Reflect.apply(qe,re.target,[]);if(!Array.isArray(Te)||Te.length>us||!Te.every(Yr))Ie("hands_repl_private_profile_probe_unavailable");We=Te}for(let qe of We){let Te=Reflect.get(qe,"isVisible");if(typeof Te!=="function"||!await Reflect.apply(Te,qe,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}if(ye==="press"&&typeof J[0]==="string"&&xa(J[0]))Ie("hands_repl_private_profile_browser_shortcut_denied");if(re.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(ye)){let We=Reflect.get(re.target,"evaluate");if(typeof We!=="function")Ie("hands_repl_private_profile_probe_unavailable");let qe=await Reflect.apply(We,re.target,[Pa]);if(!Nr(qe)||typeof qe.password!=="boolean"||typeof qe.executableLink!=="boolean")Ie("hands_repl_private_profile_probe_unavailable");if(ye==="inputValue"&&qe.password)Ie("hands_repl_private_profile_password_denied");if(ye!=="inputValue"&&qe.executableLink)Ie("hands_repl_private_profile_url_denied");if(ye==="inputValue"){let Te=Reflect.get(re.target,"isVisible");if(typeof Te!=="function"||!await Reflect.apply(Te,re.target,[]))Ie("hands_repl_private_profile_hidden_value_denied")}}}let z=fs[re.kind][T.method];if(!z)Ie("hands_repl_method_not_allowed");if(z.requiresStringSource&&typeof J[0]!=="string")Ie("hands_repl_string_source_required");if(re.kind==="browser"&&T.method==="contexts")return[I.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(T.method)&&J.some((ye)=>Nr(ye)&&("path"in ye)))Ie("hands_repl_file_path_not_allowed");if(T.method==="goto"&&typeof J[0]==="string"){let ye;try{ye=new URL(J[0]).protocol}catch{Ie("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(ye))Ie("hands_repl_file_path_not_allowed")}if(z.special==="contextViewportSize"){let ye=Reflect.get(re.target,"pages");if(typeof ye!=="function")Ie("hands_repl_method_unavailable");let We=await Reflect.apply(ye,re.target,[]),qe=Array.isArray(We)?We[0]:void 0,Te=Yr(qe)?Reflect.get(qe,"viewportSize"):void 0;if(typeof Te!=="function")return Xt();return M(await Reflect.apply(Te,qe,[]),z.returns)}if(z.special==="property"){let ye=Reflect.get(re.target,T.method);return M(typeof ye==="function"?Reflect.apply(ye,re.target,[]):ye,z.returns)}let fe=Reflect.get(re.target,T.method);if(typeof fe!=="function")Ie("hands_repl_method_unavailable");if(z.special==="route"){let ye=J[1];if(!as(ye))Ie("hands_repl_invalid_route_handler");yt(ye.options);let We=G(ye.options),qe=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])},Te=[G(J[0]??null),qe],le=await Reflect.apply(fe,re.target,Te);return M(le,z.returns)}let ke=J.map(G);if(T.method==="setInputFiles"){let ye=re.kind==="locator"?0:1,We=async(Te)=>{if(typeof Te!=="string"){if(!Nr(Te)||typeof Te.name!=="string"||typeof Te.mimeType!=="string"||!wt.isBuffer(Te.buffer))Ie("hands_repl_invalid_file_input");return Te}if(!e.readWorkspaceFile)Ie("hands_repl_workspace_required");return e.readWorkspaceFile(Te)},qe=ke[ye];ke[ye]=Array.isArray(qe)?await Promise.all(qe.map(We)):await We(qe)}if(T.method==="goto")await e.beforeNavigation?.();let be=e.actionRecorder?.(),Re=await Reflect.apply(fe,re.target,ke),Ye={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[T.method];if(Ye){let ye=Reflect.get(re.target,"page"),We=re.kind==="page"?re.target:typeof ye==="function"?Reflect.apply(ye,re.target,[]):void 0;be?.(Ye,Yr(We)?We:void 0)}return M(Re,z.returns)}})}import{isIP as gs}from"net";import{Resolver as Da}from"dns/promises";import{isIP as Qt}from"net";var Ca=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function Hn(e){if(Qt(e)!==4)return null;let l=e.split(".");if(l.length!==4)return null;let f=0;for(let g of l){let w=Number(g);if(!Number.isInteger(w)||w<0||w>255)return null;f=f*256+w}return f>>>0}function Ha(e,l,f){let g=Hn(l);if(g===null)return!1;let w=f===0?0:4294967295<<32-f>>>0;return(e&w)>>>0===(g&w)>>>0}function _s(e){let l=Hn(e);if(l===null)return!0;return Ca.some(([f,g])=>Ha(l,f,g))}function Na(e){if(Qt(e)!==6)return null;let l=e.toLowerCase(),f=l.indexOf("%");if(f>=0)l=l.slice(0,f);let g=[],w=l.lastIndexOf(":"),S=w>=0?l.slice(w+1):"";if(S.includes(".")){let T=Hn(S);if(T===null)return null;g=[T>>>16&65535,T&65535],l=l.slice(0,w+1)+"0:0"}let I=l.split("::");if(I.length>2)return null;let W=(T)=>{if(T==="")return[];let re=[];for(let J of T.split(":")){if(J===""||J.length>4||!/^[0-9a-f]+$/.test(J))return null;re.push(Number.parseInt(J,16))}return re},x=W(I[0]??"");if(x===null)return null;if(I.length===1){let T=x;if(T.length!==8)return null;return g.length>0?T.slice(0,6).concat(g):T}let M=W(I[1]??"");if(M===null)return null;let G=8-x.length-M.length;if(G<0)return null;let F=x.concat(Array(G).fill(0),M);if(F.length!==8)return null;return g.length>0?F.slice(0,6).concat(g):F}function La(e,l){return`${e>>8&255}.${e&255}.${l>>8&255}.${l&255}`}function Ba(e){let l=Na(e);if(l===null)return!0;let[f,g,w]=l;if((f&57344)!==8192)return!0;if(f===8193&&(g&65024)===0)return!0;if(f===8193&&g===3512)return!0;if(f===16383&&(g&61440)===0)return!0;if(f===8194)return _s(La(g,w));return!1}function _r(e){return e.replace(/^\[|\]$/g,"")}function Zt(e){let l=_r(e.trim()),f=Qt(l);if(f===4)return _s(l);if(f===6)return Ba(l);return!0}function ms(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 hs=5000;function ja(e){return async(l,f)=>{if(f?.aborted)throw Error("aborted");let g=new Da({timeout:hs,tries:1});if(e)g.setServers(e);let w=()=>g.cancel();f?.addEventListener("abort",w,{once:!0});try{let[S,I]=await Promise.allSettled([g.resolve4(l),g.resolve6(l)]),W=[...S.status==="fulfilled"?S.value:[],...I.status==="fulfilled"?I.value:[]];if(W.length>0)return W;let x=[S,I].flatMap((G)=>G.status==="rejected"?[G.reason]:[]);throw x.find((G)=>["dns_temporary","dns_timeout"].includes(ms(G)))??x[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{f?.removeEventListener("abort",w)}}}var Ma=ja();async function Wa(e,l,f,g){if(g?.aborted)throw Error("aborted");let w=new AbortController,S,I,W=l(e,w.signal);W.catch(()=>{});try{return await Promise.race([W,new Promise((x,M)=>{if(S=setTimeout(()=>M(new DOMException("DNS lookup timed out","TimeoutError")),f),g)I=()=>M(Error("aborted")),g.addEventListener("abort",I,{once:!0})})])}finally{if(S!==void 0)clearTimeout(S);if(g&&I)g.removeEventListener("abort",I);w.abort()}}async function Xi(e,l=Ma,f){let g=_r(e);if(Qt(g))return Zt(g)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[g]};let w;try{w=await Wa(g,l,hs,f)}catch(S){return{ok:!1,reason:f?.aborted?f.reason instanceof Error&&f.reason.name==="TimeoutError"?"dns_timeout":"aborted":ms(S)}}if(w.length===0)return{ok:!1,reason:"dns_empty"};if(w.some(Zt))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:w}}var Fa=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function Nn(e){return e.length<=253&&Fa.test(e.toLowerCase())}function Ua(e,l){let f=e.trim().toLowerCase();if(!Nn(f))return!1;if(f.startsWith("*.")){let g=f.slice(2);return l===g||l.endsWith(`.${g}`)}return f===l}function za(e){let l=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!l)return null;let f=l.slice(1).map(Number);return f.some((g)=>g>255)?null:f}function Ln(e,l=[]){let f=(g)=>{if(g=g.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!g.includes(":"))return g;try{g=new URL(`http://[${g}]/`).hostname.slice(1,-1)}catch{return g}let w=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(g);if(!w)return g;let S=parseInt(w[1],16),I=parseInt(w[2],16);return`${S>>8}.${S&255}.${I>>8}.${I&255}`};return l.some((g)=>f(g)===f(e))}function ct(e){e=e.toLowerCase().replace(/^\[|\]$/g,"");let l=za(e);if(l){let[S,I,W]=l;if(S===127)return"loopback";return S===0||S===10||S>=224||S===100&&I>=64&&I<=127||S===169&&I===254||S===172&&I>=16&&I<=31||S===192&&(I===168||I===0&&(W===0||W===2)||I===88&&W===99)||S===198&&(I===18||I===19||I===51&&W===100)||S===203&&I===0&&W===113?"private":"public"}if(!e.includes(":"))return"hostname";try{e=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return"private"}if(e==="::1")return"loopback";let f=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(e);if(f){let S=parseInt(f[1],16),I=parseInt(f[2],16);return ct(`${S>>8}.${S&255}.${I>>8}.${I&255}`)==="public"?"public":"private"}let[g,w=0]=e.split(":").map((S)=>parseInt(S||"0",16));return g<8192||g>16383||g===8194||g===8193&&(w<512||w===3512)||g===16383&&w<4096?"private":"public"}function Ue(e,l){let f;try{f=new URL(e)}catch{return{allowed:!1,url:e,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(f.protocol))return{allowed:!0,url:e,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(f.protocol))return{allowed:!1,url:e,host:f.hostname||null,reason:"unsupported_protocol"};let g=f.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(l.mode==="off")return{allowed:!0,url:e,host:g,reason:"policy_off"};let w=(W)=>({allowed:!1,url:e,host:g,reason:W});if(f.username||f.password)return w("invalid_url");if(l.mode==="public_web"){let W=ct(g)!=="public"&&ct(g)!=="hostname"||g==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(g)||!g.includes(".")&&!gs(g)||Boolean(gs(g)&&Zt(g));return{allowed:!W,url:e,host:g,reason:W?"private_network":"public_web"}}let S=Number(f.port||(["https:","wss:"].includes(f.protocol)?443:80));if(l.deniedPorts?.includes(S)||Ln(g,l.deniedHosts))return w("destination_not_allowed");let I=ct(g);if(I==="private"||["local","internal","arpa"].some((W)=>g===W||g.endsWith(`.${W}`)))return w("private_network");if(I==="loopback"||g==="localhost"||g.endsWith(".localhost"))return l.allowedLoopbackPorts?.includes(S)?{allowed:!0,url:e,host:g,reason:"loopback"}:w("destination_not_allowed");if(l.allowedDomains.some((W)=>Ua(W,g)))return{allowed:!0,url:e,host:g,reason:"allowed_domain"};return{allowed:!1,url:e,host:g,reason:"destination_not_allowed"}}import bs from"child_process";import{accessSync as $a,constants as Ka,readFileSync as Ga,statSync as Ja}from"fs";import{createRequire as Va}from"module";import{dirname as ff,isAbsolute as Mn,join as qa,resolve as pf,win32 as Ya}from"path";var Wn=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:er.dependencies["playwright-core"],browser:"chromium"}),ws=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],Fn=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function Xa(e=process.env){let l=[e.ProgramFiles??"C:\\Program Files",e["ProgramFiles(x86)"]??"C:\\Program Files (x86)"],f=e.LOCALAPPDATA?[e.LOCALAPPDATA]:[],g=(w,...S)=>w.map((I)=>Ya.join(I,...S));return[...g([...l,...f],"Google","Chrome","Application","chrome.exe"),...g(l,"Microsoft","Edge","Application","msedge.exe"),...g([...l,...f],"BraveSoftware","Brave-Browser","Application","brave.exe")]}function jt(e){try{return $a(e,Ka.X_OK),Mn(e)&&Ja(e).isFile()}catch{return!1}}function Un(e,l=process.platform){let f=l==="darwin"?ws:l==="linux"?Fn:l==="win32"?Xa():null;return f?(e??f).find(jt)??null:null}function Za(){if(!process.versions.bun)return;let e=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,e))return;let l=[];bs.spawn=new Proxy(bs.spawn,{apply(f,g,w){let S=Reflect.apply(f,g,w),I=w[1],W=w[2]?.stdio;if(Array.isArray(I)&&I.includes("--remote-debugging-pipe")&&Array.isArray(W)&&W[3]==="pipe"&&W[4]==="pipe")l.push(S);return S}}),Object.defineProperty(globalThis,e,{value:l})}async function en(e){if(Za(),e!==void 0){if(!Mn(e))throw Error("hands_browser_driver_path_must_be_absolute");let g=qa(e,"package.json"),w=JSON.parse(Ga(g,"utf8"));if(w.name!==Wn.driver)throw Error("hands_browser_wrong_driver");let S=Va(g)(e),I=S.default?.chromium??S.chromium;if(!I)throw Error("hands_browser_missing_chromium");return{version:w.version,chromium:I}}let[l,f]=await Promise.all([import("./index-wrw65904.js"),import("./package-xqbhdf15.js").then((m)=>Oi(m.default,1))]);return{version:f.default.version,chromium:l.chromium}}var Qa=(e,l=Wn.driverVersion)=>({status:"unavailable",reason:e,expectedDriverVersion:l}),ec=(e)=>e.loadDriver?.()??en(e.driverModuleDirectory);async function Mt(e={}){return ys(e,Wn.driverVersion)}async function zn(e,l={}){if(e.driverVersion!=="1.61.1"||!Mn(e.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return ys({...l,driverModuleDirectory:e.driverModuleDirectory,allowSystemBrowser:!0},e.driverVersion)}async function ys(e,l){let f=(x)=>Qa(x,l),g=e.platform??process.platform;if(g!=="linux"&&g!=="darwin"&&g!=="win32")return f("unsupported_platform");let w;try{w=await ec(e)}catch{return f("driver_missing")}if(w.version!==l)return f("driver_version_mismatch");let S=(x,M)=>({status:"resolved",executablePath:x,source:M,driverVersion:w.version});if(e.executablePath!==void 0)return jt(e.executablePath)?S(e.executablePath,"configured"):f("executable_missing");let I=w.chromium.executablePath();if(jt(I))return S(I,"managed");let W=e.allowSystemBrowser===!0?Un(e.systemCandidates,g):null;return W?S(W,"system"):f("executable_missing")}var pc=["/usr/local/bin/chromium",...Fn];function mn(e,l=Os()){return Un(e??(l==="linux"?pc:void 0),l)}async function _c(){try{return(await en()).chromium}catch{return cc(import.meta.url)("playwright-core").chromium}}var mc=1048576,hc=105000,gc=20000,Ss=5000,bc=2000,wc=1000,yc=30000,Es=81920,vc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function kc(e,l){let f=new URL(e.url()),g={...await e.allHeaders(),host:f.host};for(let w of Object.keys(g))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(w))delete g[w];return new Promise((w,S)=>{let W=(f.protocol==="https:"?lc:dc)(f,{method:e.method(),headers:g,agent:!1,lookup:(M,G,F)=>{let T=dt.isIP(l);if(G.all)F(null,[{address:l,family:T}]);else F(null,l,T)}},(M)=>{let G=[],F=0;M.on("data",(T)=>{if(F+=T.length,F>33554432)W.destroy(Error("hands_browser_response_too_large"));else G.push(T)}),M.on("error",S),M.on("end",()=>{let T={};for(let[re,J]of Object.entries(M.headers))if(J!==void 0&&!["transfer-encoding","connection","content-length"].includes(re))T[re]=Array.isArray(J)?J.join(`
|
|
300
|
+
`):J;w({status:M.statusCode??502,headers:T,body:Buffer.concat(G)})})}),x=setTimeout(()=>W.destroy(Error("hands_browser_fetch_timeout")),yc);W.once("close",()=>clearTimeout(x)),W.on("error",S),W.end(e.postDataBuffer()??void 0)})}async function Sc(e,l,f=()=>{},g={lookup:(w)=>ac(w,{all:!0}),fetch:kc}){let w=new WeakSet,S=new WeakMap,I=(W)=>{let x=S.get(W);if(x)return x;let M=(async()=>{if(!e.newCDPSession)return;let G=await e.newCDPSession(W),F=new Map;G.on("Network.loadingFinished",({requestId:T})=>F.delete(T)),G.on("Network.loadingFailed",({requestId:T})=>F.delete(T)),G.on("Fetch.requestPaused",async(T)=>{let re=T.networkId??T.requestId,J=T.redirectedRequestId?(F.get(re)??0)+1:0;F.set(re,J);let z=Ue(T.request.url,l),fe=l.mode==="enforce"&&Boolean(T.redirectedRequestId)&&z.host!==null&&!dt.isIP(z.host),ke=!z.allowed?z:fe?{...z,allowed:!1,reason:"destination_not_allowed"}:J>20?{...z,allowed:!1,reason:"redirect_not_supported"}:null;try{if(ke)f(ke),await G.send("Fetch.failRequest",{requestId:T.requestId,errorReason:"BlockedByClient"});else await G.send("Fetch.continueRequest",{requestId:T.requestId})}catch{await G.send("Fetch.failRequest",{requestId:T.requestId,errorReason:"Failed"}).catch(()=>{})}}),await G.send("Network.enable"),await G.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),w.add(W)})();return S.set(W,M),M};return await e.route("**/*",async(W)=>{let x=W.request().url(),M=Ue(x,l);if(M.allowed&&l.mode==="public_web"){await W.continue();return}let G=W.request();if(M.allowed&&M.host&&dt.isIP(M.host)&&G.isNavigationRequest?.()){let F=G.frame();if(w.has(F.page())&&F===F.page().mainFrame()){await W.continue();return}}if(M.allowed&&(l.mode==="off"||M.reason==="local_document")){await W.continue();return}if(M.allowed&&M.host)try{let F=M.host,T=ct(F),re,J=await(async()=>{if(T!=="hostname")return[{address:F,family:dt.isIP(F)}];if(M.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([g.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=ct(z);return!dt.isIP(z)||l.mode==="enforce"&&Ln(z,l.deniedHosts)||(M.reason==="loopback"?fe!=="loopback":fe!=="public")}))M={...M,allowed:!1,reason:"private_network"};else{let z=await g.fetch(W.request(),J[0].address);if(z.status>=300&&z.status<400){let fe=z.headers.location??x;try{fe=new URL(fe,x).href}catch{}let ke=Ue(fe,l);M=ke.allowed?{...ke,allowed:!1,reason:"redirect_not_supported"}:ke}else{await W.fulfill(z);return}}}catch{await W.abort("failed");return}f(M),await W.abort("blockedbyclient")}),await e.routeWebSocket("**/*",async(W)=>{let x=Ue(W.url(),l);if(l.mode==="enforce"&&x.allowed&&(!x.host||!dt.isIP(x.host)))x={...x,allowed:!1,reason:"destination_not_allowed"};if(x.allowed){W.connectToServer();return}f(x),await W.close({code:1008,reason:"Reason egress policy denied"})}),l.mode==="off"?void 0:{preparePage:I}}async function xs(e,l=Os(),f){if(f){let w=await zn(f,{platform:l,systemCandidates:e});return w.status==="resolved"?w.executablePath:null}if(e!==void 0){let w=mn(e,l);if(w)return w}let g=await Mt({platform:l,systemCandidates:e,allowSystemBrowser:!0});return g.status==="resolved"?g.executablePath:null}function Rs(e,l){if(!e)throw Error("hands_repl_workspace_required");let f=Kn(e),g=vt(e),w=Gn(g,vt(g,l)),I=w!==".."&&!w.startsWith(`..${Jn}`)&&!ks(w)?vt(f,w):vt(f,l);if(E(vt(g,l))||E(I))throw Error("hands_repl_protected_path");let W=(J)=>{let z=Gn(f,J);return z!==""&&z!==".."&&!z.startsWith(`..${Jn}`)&&!ks(z)},x=Kn(I);if(E(x))throw Error("hands_repl_protected_path");if(!W(I)||!W(x))throw Error("hands_repl_file_outside_workspace");let M=Gn(f,I).split(Jn),G=[f,...M.map((J,z)=>vt(f,...M.slice(0,z+1)))],F=G.map((J)=>vs(J));if(F.some((J)=>J.isSymbolicLink()))throw Error("hands_repl_file_symlink");let T=F[F.length-1];if(!T.isFile()||T.nlink!==1||T.size>16777216)throw Error("hands_repl_file_not_regular_or_too_large");let re=oc(I,$n.O_RDONLY|$n.O_NOFOLLOW|$n.O_NONBLOCK);try{let J=nc(re);if(J.dev!==T.dev||J.ino!==T.ino||!J.isFile())throw Error("hands_repl_file_changed");for(let be=0;be<G.length;be++){let Re=vs(G[be]);if(Re.dev!==F[be].dev||Re.ino!==F[be].ino||Re.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!W(Kn(I)))throw Error("hands_repl_file_outside_workspace");let z=Buffer.alloc(16777217),fe=0;while(fe<z.length){let be=sc(re,z,fe,z.length-fe,null);if(!be)break;fe+=be}if(fe===z.length)throw Error("hands_repl_file_too_large");let ke=z.subarray(0,fe);return{name:uc(I),mimeType:vc[fc(I).toLowerCase()]??"application/octet-stream",buffer:ke}}finally{tc(re)}}function kt(e,l){e.end(`${JSON.stringify(l)}
|
|
301
|
+
`)}function rn(e){try{ic(e)}catch{}}async function Ps(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 zn(e.managedBrowser,{executablePath:e.browserExecutablePath}):await Mt({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||!jt(f))throw Error("hands_browser_unavailable");let g=e.launch??(async(le)=>(e.targetContext?await _c():(await en(e.managedBrowser?.driverModuleDirectory??e.driverModuleDirectory)).chromium).launch(le)),w=[],S={},I=null,W=null,x=null,M=null,G=!1,F=null,T=new Map,re=new WeakMap,J=null,z=()=>{if(G)throw Error("hands_repl_stopped");if(M)throw M},fe=(le)=>{let he=re.get(le);if(he)return he;let xe=Promise.resolve().then(()=>le.close()).then(()=>{T.delete(le)});return re.set(le,xe),xe},ke=async()=>{let le=[...T.entries()].reverse(),he=J??=performance.now()+wc,xe=Promise.allSettled(le.filter(([,Ee])=>Ee==="context").map(([Ee])=>fe(Ee))),Ge;try{await Promise.race([xe,new Promise((Ee)=>{Ge=setTimeout(Ee,Math.max(0,he-performance.now()))})])}finally{if(Ge)clearTimeout(Ge)}let Le=await Promise.allSettled(le.map(([Ee])=>fe(Ee))),Be=[];for(let[Ee,Me]of Le.entries()){if(Me.status!=="rejected")continue;let or=Me.reason instanceof Error&&["Error","TimeoutError","ProtocolError"].includes(Me.reason.name)?Me.reason.name:"unknown";Be.push(Error(`hands_repl_close_failed: ${le[Ee][1]}: ${or}`))}if(Be.length)throw AggregateError(Be,"hands_repl_stop_unconfirmed")},be=(le,he)=>{if(T.set(le,he),G||M)fe(le).catch(()=>{return}),z();return le},Re=async()=>{let le=await g({executablePath:f,headless:!0,chromiumSandbox:e.managedBrowser===void 0,args:["--disable-background-networking","--disable-quic","--disable-dev-shm-usage","--disable-gpu","--disable-software-rasterizer","--dns-prefetch-disable","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--no-pings"]}),he=null;try{be(le,"browser"),he=e.targetContext??be(await le.newContext({viewport:{width:1440,height:900},screen:{width:1440,height:900},serviceWorkers:"block",acceptDownloads:!1}),"context");let xe=await Sc(he,e.networkPolicy??{mode:"off"},e.onEgressDenied);if(z(),xe){let Ve=he.newPage.bind(he);he.newPage=async()=>{let ir=await Ve();return await xe.preparePage(ir),ir}}let Le=he.pages()[0]??await he.newPage();await xe?.preparePage(Le),z();let Be=async(Ve=Le)=>{let ir=Ve;if(typeof ir.ariaSnapshot==="function")return ir.ariaSnapshot({timeout:1e4});return Le.locator("body").innerText({timeout:1e4})},Ee=async(Ve,ir={})=>{let ar=ir&&typeof ir==="object"&&!Array.isArray(ir)?ir:{},Er,zr="image/png";if(Buffer.isBuffer(Ve)||Ve instanceof Uint8Array)Er=Buffer.from(Ve);else if(typeof Ve==="string"&&(Ve.startsWith("data:")||/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Ve)))Er=Buffer.from(Ve.replace(/^data:[^,]*,/,""),"base64");else if(typeof Ve==="string"){let Qr=Rs(e.workspaceRoot,Ve);Er=Qr.buffer,zr=Qr.mimeType}else throw Error("view() needs a Buffer, a base64 string, or a path to an image file");if(Er.length===0)throw Error("view(): the image is empty");let ln=String(ar.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),Jr=Number(ar.maxWidth)||1024,ut=Number(ar.quality)||72,Ut=e.targetContext?await le.newPage():await he.newPage();try{let Qr=`data:${zr};base64,${Er.toString("base64")}`;for(let Rr=0;Rr<5;Rr+=1){let Wr=await Ut.evaluate(async(jr)=>{let Fr=new Image;Fr.src=jr.url,await Fr.decode();let et=Math.min(1,jr.maxWidth/Fr.naturalWidth),Cr=document.createElement("canvas");Cr.width=Math.max(1,Math.round(Fr.naturalWidth*et)),Cr.height=Math.max(1,Math.round(Fr.naturalHeight*et));let Tr=Cr.getContext("2d");if(!Tr)throw Error("view(): canvas unavailable");return Tr.fillStyle="#ffffff",Tr.fillRect(0,0,Cr.width,Cr.height),Tr.drawImage(Fr,0,0,Cr.width,Cr.height),{data:Cr.toDataURL("image/jpeg",jr.q/100).split(",")[1]??"",width:Cr.width,height:Cr.height,sourceWidth:Fr.naturalWidth,sourceHeight:Fr.naturalHeight}},{url:Qr,maxWidth:Jr,q:ut}),ft=Buffer.from(Wr.data,"base64");if(ft.length<=Es){let jr=ln||"image";return`<<<ARA_VIEW_IMAGE ${Wr.data} image/jpeg ${jr}>>>
|
|
302
|
+
Viewing ${jr} (${Wr.sourceWidth}x${Wr.sourceHeight} source, sent at ${Wr.width}x${Wr.height}, ${Math.round(ft.length/1024)}KB).`}if(Jr>640)Jr=Math.round(Jr*0.75);else ut=Math.max(30,ut-15)}throw Error(`view(): could not reduce the image under ${Math.round(Es/1024)}KB`)}finally{await Ut.close().catch(()=>{return})}},Me=ps({browser:e.targetContext?.browser()??le,context:he,page:Le,a11y:Be,view:Ee,readWorkspaceFile:(Ve)=>Rs(e.workspaceRoot,Ve),privateProfile:e.privateProfile,beforeNavigation:e.beforeNavigation,recording:e.recording,screenshotExport:e.screenshotExport,actionRecorder:()=>{let Ve=w,ir=S;return(ar,Er)=>{if(Ve.length<lo)Ve.push(ar);if(Er)ir.page=Er}}}),or=async(Ve)=>{z();let ir=be(await le.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await ir.route("**/*",(Er)=>Er.abort()),z(),await ir.routeWebSocket("**/*",(Er)=>Er.close({code:1008,reason:"Reason evaluator network denied"})),z(),await ir.exposeBinding("__araHandsRpc",async(Er,zr)=>e.onBrowserOperation?e.onBrowserOperation(Ve,()=>Me.dispatch(zr)):Me.dispatch(zr)),z();let ar=await ir.newPage();return z(),await ar.goto("data:text/html,<title>Reason Hands evaluator</title>"),z(),await ar.evaluate(`(${ns})(${JSON.stringify(Me.roots)})`),{context:ir,page:ar,runId:Ve}}catch(ar){throw await fe(ir).catch(()=>{return}),ar}},sr=await or(),Ir={browser:le,context:he,page:Le,evaluator:sr,async captureProgressFrame(Ve){return Ee(await Ve.screenshot({type:"jpeg",quality:65,timeout:2000}),{label:"Screen after browser action"})},async resetEvaluator(Ve){await fe(Ir.evaluator.context),Ir.evaluator=await or(Ve)}};return z(),Ir}catch(xe){throw await ke().catch(()=>{return}),xe}},Fe=async()=>{if(z(),I)return I;if(!x){W=Re();let le;x=Promise.race([W,new Promise((he,xe)=>{le=setTimeout(()=>xe(Error("hands_browser_unavailable: startup timed out")),gc)})]).then((he)=>(z(),I=he,he)).catch(async()=>{M=Error("hands_browser_unavailable: startup failed or timed out");let he;try{await Promise.race([ke(),new Promise((xe,Ge)=>{he=setTimeout(()=>Ge(Error("hands_repl_stop_timeout")),Ss)})])}catch{M=Error("hands_browser_unavailable: startup cleanup unconfirmed")}finally{if(he)clearTimeout(he)}throw M}).finally(()=>{if(le)clearTimeout(le)})}return x},Ye=async(le,he,xe=!1)=>{let Ge=await Fe(),Le=S;if(e.onBrowserOperation&&Ge.evaluator.runId!==he)await Ge.resetEvaluator(he);let Ee=(async()=>{let sr=await Ge.evaluator.page.evaluate(`(${os})(${JSON.stringify({code:le})})`);if(typeof sr!=="string")throw Error("hands_repl_invalid_evaluator_output");let Ir=Le.page;if(xe&&Ir&&!sr.includes("<<<ARA_VIEW_IMAGE")){let Ve=()=>Ge.captureProgressFrame(Ir);try{let ir=await(e.onBrowserOperation?e.onBrowserOperation(he,Ve):Ve());return Le.automaticProgressImage=!0,`${sr}
|
|
303
|
+
${ir}`}catch{return`${sr}
|
|
304
|
+
Screen capture unavailable.`}}return sr})(),Me,or=new Promise((sr,Ir)=>{Me=setTimeout(()=>Ir(Error("REPL evaluation timed out after 105 seconds")),hc)});try{return await Promise.race([Ee,or])}catch(sr){if(sr instanceof Error&&sr.message.includes("timed out"))Ee.catch(()=>{return}),await Ge.resetEvaluator(he).catch(()=>{return});throw sr}finally{if(Me)clearTimeout(Me)}},ye=Promise.resolve(),We=new Set,qe=new Set;rn(e.socketPath);let Te=dt.createServer((le)=>{We.add(le),le.once("close",()=>{We.delete(le),qe.delete(le)}),le.setEncoding("utf8");let he="",xe=!1;le.on("data",(Ge)=>{if(xe)return;if(he+=Ge,he.length>mc){xe=!0,kt(le,{ok:!1,error:"REPL request exceeds 1 MiB"});return}let Le=he.indexOf(`
|
|
305
|
+
`);if(Le===-1)return;xe=!0;let Be=he.slice(0,Le);if(e.onControl)try{let Ee=JSON.parse(Be);if(typeof Ee.action==="string"&&Ee.action!=="evaluate")qe.add(le)}catch{}ye=ye.then(async()=>{if(le.destroyed)return;w=[],S={};try{let Ee=JSON.parse(Be);if(Ee.action==="probe"){let Ve=await Fe();await Ye("undefined",Ve.evaluator.runId),kt(le,{ok:!0,output:"ARA_HANDS_REPL_READY"});return}if(typeof Ee.action==="string"&&Ee.action!=="evaluate"&&e.onControl){kt(le,{ok:!0,output:await e.onControl(Ee.action,Ee)});return}if(Ee.action!=="evaluate"||typeof Ee.code!=="string")throw Error("Invalid REPL request");let Me=Ee.code,or=typeof Ee.runId==="string"?Ee.runId:void 0,sr=()=>Ye(Me,or,Ee.includeProgressCapture===!0),Ir=await(e.onEvaluate?e.onEvaluate(Ee,sr):sr());kt(le,{ok:!0,output:Ir,browserActions:w,...S.automaticProgressImage?{automaticProgressImage:!0}:{}})}catch(Ee){kt(le,{ok:!1,error:Ee instanceof Error?Ee.message:String(Ee),stack:Ee instanceof Error?Ee.stack:void 0,browserActions:w})}}).catch((Ee)=>{kt(le,{ok:!1,error:Ee instanceof Error?Ee.message:String(Ee)})})})});try{await new Promise((le,he)=>{Te.once("error",he),Te.listen(e.socketPath,()=>{Te.off("error",he);try{if(process.platform!=="win32")rc(e.socketPath,384);le()}catch(xe){Te.close(()=>he(xe))}})})}catch(le){throw rn(e.socketPath),le}return{socketPath:e.socketPath,browserExecutablePath:f,stop(){if(F)return F;G=!0;let le=qe.size?setTimeout(()=>{for(let Le of qe)Le.destroy()},bc):void 0,he=new Promise((Le)=>Te.close(()=>{if(le)clearTimeout(le);Le()}));for(let Le of We)if(!qe.has(Le))Le.destroy();ye.catch(()=>{return});let xe=async()=>{await he,rn(e.socketPath);let Le=[ke()];if(W)Le.push(W.then(()=>{return},()=>{return}));let Be=await Promise.allSettled(Le),Ee=await Promise.allSettled([ke()]),Me=[...Be,...Ee].filter((or)=>or.status==="rejected");if(Me.length)throw AggregateError(Me.map((or)=>or.reason),"hands_repl_stop_unconfirmed")},Ge;return F=Promise.race([xe(),new Promise((Le,Be)=>{Ge=setTimeout(()=>Be(Error("hands_repl_stop_timeout")),Ss)})]).finally(()=>{if(Ge)clearTimeout(Ge);rn(e.socketPath)}),F}}}var Ec=["private_runtime","runtime_root","temporary_directory","granted_root","workspace_layout","jobs","browser_socket","relay_url","environment_owner","job_environment","config_write"],Rc=["ENOENT","EACCES","EPERM","EINVAL","ENOTDIR","EISDIR","ELOOP","EROFS","ENOSPC","EMFILE","ENFILE","EEXIST"];function Is(e,l){if(!e||!Ec.includes(e))return null;let f=typeof l==="object"&&l!==null&&"code"in l?l.code:null;return{workspace_stage:e,workspace_errno:typeof f==="string"&&Rc.includes(f)?f:"unknown"}}import{lstatSync as Oc,readFileSync as xc}from"fs";var Pc="/run/sc/egress-guard",Ic=10002,qn=10003;function As(e=process.platform,l=Pc){if(e!=="linux")return!1;try{let f=Oc(l);if(!f.isFile()||f.uid!==0||(f.mode&18)!==0)return!1;return xc(l,"utf8")===`v1 ${Ic} ${qn}
|
|
306
|
+
`}catch{return!1}}var Ac=/^(\/.+)-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;function Ts(e){let l=Ac.exec(e.replace(/\/+$/,""));return l?`${l[1]}/repo`:null}import{randomUUID as yd}from"crypto";import{spawn as vd,spawnSync as kd}from"child_process";import{accessSync as Sd,chmodSync as Ft,closeSync as Ed,constants as Tt,fchmodSync as Rd,fstatSync as Od,openSync as xd,copyFileSync as Pd,existsSync as ao,lstatSync as ur,statSync as lt,mkdtempSync as Id,mkdirSync as Ct,realpathSync as nr,renameSync as cn,rmSync as Ad,writeFileSync as dn}from"fs";import{homedir as Td,tmpdir as ti}from"os";import{basename as Dd,dirname as Dr,join as lr,resolve as ni,sep as Cd}from"path";var Tc={"navigation.ara-egress.invalid":"canary_navigation","fetch.ara-egress.invalid":"canary_fetch","subresource.ara-egress.invalid":"canary_subresource","codeload.github.com":"canary_redirect","websocket.ara-egress.invalid":"canary_websocket"};function Ds(e){return e===null?"other":Tc[e]??"other"}function Br(e,l){if(e===void 0||l===void 0)return null;let f=Math.round(l-e);return Number.isSafeInteger(f)&&f>=0&&f<=600000?f:null}var Xe="workspace_mode",Xr="granted_root",Mr="project_root",St="terminal_root",Et="terminal_benchmark_tool_profile",Dc=["bash","bash-node-repl","bash-node-repl-files"],Cs="hands_node_repl_persistent_execution_unsupported";function Hs(e){return e==="bash"?null:"hands_node_repl_persistent_execution_unsupported"}function Ns(e){return Dc.includes(e)}var Uf=i({device_id:t().uuid(),root_id:t().uuid()}),Yn=/^reason\/[0-9a-f]{8}$/,Cc=c({source_path:t().refine(X).optional(),branch:t().regex(Yn)}),zf=i({checkout_mode:s(["worktree","direct"]).optional(),project_workspace_source:i({kind:n("local_device"),device_id:t().uuid(),root_id:t().uuid(),path:t().refine(X).optional(),worktree:Cc.optional()})});import{execFile as Hc}from"child_process";var Nc=20000,Lc=1e4,Ls=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/,Bc=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","gc.auto=0","-c","maintenance.auto=false"];async function Bs(e,l=jc){let f=(fe,ke=Lc)=>l([...Bc,"-C",e,...fe],ke),g=async(fe)=>{let ke=await f(fe);return ke.status===0?ke.stdout.trim():null},w=await g(["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(!w||!Ls.test(w))return null;let S=w.slice(0,12),I=(fe)=>({commit:w,from:"head",note:`reason: started from ${fe}`}),W=await g(["symbolic-ref","--quiet","HEAD"]);if(!W?.startsWith("refs/heads/"))return I(`the checkout's detached HEAD ${S}`);let x=W.slice(11),M=await f(["--no-optional-locks","status","--porcelain=v1","--untracked-files=no"]);if(M.status!==0||M.stdout.trim())return I(`${x} at ${S}: the checkout has uncommitted changes, which stay there`);let G=await g(["config","--get",`branch.${x}.remote`]),F=await g(["config","--get",`branch.${x}.merge`]);if(!G||!F?.startsWith("refs/")||G.startsWith("-"))return I(`${x} at ${S}: it has no upstream to catch up with`);let T=G==="."||(await f(["fetch","--quiet","--no-tags","--no-write-fetch-head","--no-recurse-submodules",G,F],Nc)).status===0,re=await g(["rev-parse","--abbrev-ref","--symbolic-full-name","@{upstream}"]),J=re?await g(["rev-parse","--verify","--quiet","@{upstream}^{commit}"]):null;if(!re||!J||!Ls.test(J))return I(`${x} at ${S}: ${T?"it has no upstream to catch up with":`fetching ${G} failed`}`);if(!T)return I(`${x} at ${S}: fetching ${re} failed, so it may be behind`);if(J===w)return I(`${x} at ${S}, the same commit as ${re} after fetching it`);if((await f(["merge-base","--is-ancestor",w,J])).status!==0)return I(`${x} at ${S}: it has commits that ${re} does not`);let z=await g(["rev-list","--count",`${w}..${J}`]);return{commit:J,from:"upstream",note:`reason: started from ${re} at ${J.slice(0,12)}, fetched just now: ${x} had no commits of its own and was ${z??"some"} commits behind it`}}function jc(e,l){return new Promise((f)=>{Hc("git",e,{encoding:"utf8",timeout:l,maxBuffer:1048576,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}},(g,w)=>{let S=g?typeof g.code==="number"?g.code:null:0;f({status:S,stdout:String(w??"")})})})}import{lstatSync as Mc,readdirSync as Vf,readFileSync as qf,realpathSync as js,rmdirSync as Yf,unlinkSync as Xf,writeFileSync as Wc}from"fs";import{join as Xn,resolve as Qf}from"path";var Fc=".reason-device";function Ms(e,l,f){let g=l.split("/"),w=de.split("/");if(g.length!==w.length+2||w.some((S,I)=>g[I]!==S)||!rr.test(g[w.length]))return;try{let S=Uc(e,g[w.length]);Wc(Xn(S,Fc),f,{flag:"wx",mode:384})}catch{}}function Uc(e,l){let f=()=>new r("session_worktree_outside_workspace","Reason removes only Session folders in ~/.reason/workspace/sessions.");if(!rr.test(l))throw f();let g=Xn(js(e),de),w=Xn(g,l);if(!Mc(w).isDirectory()||js(w)!==w)throw f();return w}import{createHash as zc}from"crypto";import{join as $c}from"path";function Kc(e){return Sr(e)}function Gr(){throw new r("environment_unavailable","The private Session environment is unavailable or stale.")}function nn(e){return zc("sha256").update(JSON.stringify({...e,variables:Object.fromEntries(Object.entries(e.variables).sort(([l],[f])=>l.localeCompare(f)))})).digest("hex")}function Ws(e,l){v(e);let f=$c(e,"environment.json"),g,w=new Set,S=(W,x)=>`${x}:${W}`,I=(W)=>{let x=fr.safeParse(W);if(!x.success)return Gr();let M=x.data,G=l.identity(),F=Date.parse(M.expires_at);if(!G||M.run_id!==l.runId||M.device_id!==l.deviceId||M.root_id!==l.rootId||M.binding.kind!==l.binding.kind||M.binding.target_revision!==l.binding.target_revision||M.binding.root_grant_revision!==l.binding.root_grant_revision||M.binding.target_generation!==G.generation||M.binding.target_fence_id!==G.fenceId||F<=Date.now()||F>l.expiresAtMs||l.expiresAtMs<=Date.now()||Object.keys(M.variables).some((T)=>!Kc(T)))return Gr();if(M.git){let T=new URL(l.apiOrigin),re=new URL(M.git.base_url),J=Date.parse(M.git.expires_at);if(re.origin!==T.origin)throw new r("environment_git_origin_mismatch","The delivered Git broker is not on this worker's API origin.");if(!["/git","/git/"].includes(re.pathname)||re.username||re.password||re.search||re.hash||J<=Date.now()||J>F)return Gr()}if(M.cloud_access&&!Xo(M.cloud_access,l.apiOrigin))throw new r("environment_cloud_access_origin_mismatch","The delivered cloud access is not on this worker's API origin.");return M};return{path:f,install(W){let x=I(W),M=nn(x);if(g&&(x.revision<g.revision||x.revision===g.revision&&(M!==g.hash||x.snapshot_id!==g.snapshotId)))return Gr();if(!g||x.revision>g.revision){if(oo(f,x,V.snapshotBytes),nn(I(JSON.parse(h(f,V.snapshotBytes))))!==M)return Gr();let G=g;if(g={revision:x.revision,hash:M,snapshotId:x.snapshot_id,generation:x.binding.target_generation},G&&G.generation<g.generation)w.add(S(G.snapshotId,G.revision))}else if(nn(I(JSON.parse(h(f,V.snapshotBytes))))!==g.hash)return Gr();return{installed:!0,snapshot_id:x.snapshot_id,installed_revision:x.revision}},current(){if(!g)return Gr();try{let W=I(JSON.parse(h(f,V.snapshotBytes)));if(nn(W)!==g.hash)return Gr();return W}catch{return Gr()}},carried:(W,x)=>w.has(S(W,x))}}var Pt=Object.freeze([Object.freeze({version:"0.2.61",artifact_sha256:"02ffcd514bf7cc0a9e73d4ce31ecea32709429cd0adf79e7062c1b70ff9ab8b8",legacy_linux_x64_sha256:"cdc0828abde3157e39afc6a64e033deee52ff7cfb09b55a42e60394df24980b9"}),Object.freeze({version:"0.2.62",artifact_sha256:"20a77fff617e18315c60777d46a2de2c433e42eba4e1c5e0b5535d967847303d",legacy_linux_x64_sha256:"cce594365d518b680abfb2378d234c8ef4e3daf257df83adef650a4523fb2d92"}),Object.freeze({version:"0.2.63",artifact_sha256:"20a77fff617e18315c60777d46a2de2c433e42eba4e1c5e0b5535d967847303d"}),Object.freeze({version:"0.2.64",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.65",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.66",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.67",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.68",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.69",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.70",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.71",artifact_sha256:"830afe8cffb1f4ebb2663b5f86e5d2a7c9965fa03706178b251eea5d415917d2"}),Object.freeze({version:"0.2.72",artifact_sha256:"6071ba92082b8378f5484e8dce446d3f0c3bde61d5b5ca48efa6f72389d3ab64"}),Object.freeze({version:"0.2.73",artifact_sha256:"6071ba92082b8378f5484e8dce446d3f0c3bde61d5b5ca48efa6f72389d3ab64"}),Object.freeze({version:"0.2.74",artifact_sha256:"6071ba92082b8378f5484e8dce446d3f0c3bde61d5b5ca48efa6f72389d3ab64"}),Object.freeze({version:"0.2.75",artifact_sha256:"a6e0648894f1f4876affd77c0ff42642c1f9cbe9bb752de19d7a97a5fb3b820e"}),Object.freeze({version:"0.2.76",artifact_sha256:"857446b7e0b25fe1cc21e58860c7d984ee9a1c28efb4a4c49bc573a2d70bb3c0"}),Object.freeze({version:"0.2.77",artifact_sha256:"857446b7e0b25fe1cc21e58860c7d984ee9a1c28efb4a4c49bc573a2d70bb3c0"}),Object.freeze({version:"0.2.78",artifact_sha256:"0a7a7ece14850a28b8f972d66e4eef570eb2bb75d58f8a82f4e9afe91424e27f",pi_tools_v1:!0}),Object.freeze({version:"0.2.79",artifact_sha256:"96f52656b454fc5b9ffe520f5c5d55720b5173eb084cd326d2710e434623897b",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.80",artifact_sha256:"6ee0ed70889e2771bd9b239ee039b549361b56ce870e08956ec7cce7fa199cd7",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.81",artifact_sha256:"c8909b36f4ee9316c0c3e298cb9adb5fc821a6ec5ca365cab60043eb942c258a",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.82",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.83",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.84",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.85",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.86",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.87",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.88",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.89",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.90",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.91",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.92",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.93",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.94",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.95",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.96",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.97",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.98",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.99",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.100",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.101",artifact_sha256:"38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.102",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.103",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.104",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.105",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.106",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.107",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.108",artifact_sha256:"53da53b31916c077bd63814db6cef8646785352d628b06a9ded927a94b08ecdd",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.109",artifact_sha256:"7a82b33611b9f47478fb181d0da6f49a04f7e4bc401a7752530fecffb2dc5864",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.110",artifact_sha256:"00b7dcc9078a7d7ea4814414fbf92dcf9ba3b0fd51186aac1b967e9ae306a377",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.111",artifact_sha256:"7688e992667a48defe6fefb3b8624012b918e8776498faf9e5b20b69c13d7520",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.112",artifact_sha256:"7688e992667a48defe6fefb3b8624012b918e8776498faf9e5b20b69c13d7520",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.113",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.114",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.115",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.116",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.117",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.118",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.119",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.120",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.121",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.122",artifact_sha256:"cc134e4d22b3f4032099d9f3c18a95815177598e0e6658840702e0dafaf5c7ad",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.123",artifact_sha256:"ae68959cc57c3d3e360ba16883479d0706a0c2e742fe61a66b78e12fbbf5463e",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.124",artifact_sha256:"ae68959cc57c3d3e360ba16883479d0706a0c2e742fe61a66b78e12fbbf5463e",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.125",artifact_sha256:"503ec2935bd73740bca494782cea6e6740667ce416d1a526c8cdf152ab3d0090",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.126",artifact_sha256:"503ec2935bd73740bca494782cea6e6740667ce416d1a526c8cdf152ab3d0090",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.127",artifact_sha256:"503ec2935bd73740bca494782cea6e6740667ce416d1a526c8cdf152ab3d0090",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.128",artifact_sha256:"852f8b11cee963d2f077f010b5c836fab0ee84e0026c4762bc4c7ef28e4deb2b",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.129",artifact_sha256:"852f8b11cee963d2f077f010b5c836fab0ee84e0026c4762bc4c7ef28e4deb2b",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.130",artifact_sha256:"852f8b11cee963d2f077f010b5c836fab0ee84e0026c4762bc4c7ef28e4deb2b",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.131",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.132",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.133",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.134",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.135",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.136",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.137",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.138",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.139",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.140",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.141",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.142",artifact_sha256:"39e5173130068852fd81ffbe0f75cf52d7afcfcd92d640fedda85e1993960527",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.143",artifact_sha256:"ddd5382224321a671a5e338ccc8f9aae09ad876b534e6a8bfec07dc04c5b57d3",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.144",artifact_sha256:"ddd5382224321a671a5e338ccc8f9aae09ad876b534e6a8bfec07dc04c5b57d3",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.145",artifact_sha256:"ddd5382224321a671a5e338ccc8f9aae09ad876b534e6a8bfec07dc04c5b57d3",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0}),Object.freeze({version:"0.2.146",artifact_sha256:"8b2959fed27dff6769a0124ecbbddceaa671dc2dd502f5f77d54dbe69c99e4b5",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.147",artifact_sha256:"8b2959fed27dff6769a0124ecbbddceaa671dc2dd502f5f77d54dbe69c99e4b5",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.148",artifact_sha256:"8b2959fed27dff6769a0124ecbbddceaa671dc2dd502f5f77d54dbe69c99e4b5",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.149",artifact_sha256:"8b2959fed27dff6769a0124ecbbddceaa671dc2dd502f5f77d54dbe69c99e4b5",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.150",artifact_sha256:"8b2959fed27dff6769a0124ecbbddceaa671dc2dd502f5f77d54dbe69c99e4b5",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.151",artifact_sha256:"8b2959fed27dff6769a0124ecbbddceaa671dc2dd502f5f77d54dbe69c99e4b5",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.152",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.153",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.154",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.155",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.156",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.157",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.158",artifact_sha256:"065b5bfc86ec87cf2907d83864ffef9912a8cb18b2b36db435c74cfd3891b8f8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0}),Object.freeze({version:"0.2.159",artifact_sha256:"cc806ca6df14c39d45a944d1e1db9827dae35b3e66e0265ededb3eea3d883dcb",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.160",artifact_sha256:"0b8f6c4598a19acbeff93929efc237dbc4e356ccb26abf6957e297bfc1b551e8",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.161",artifact_sha256:"d570f5035bfc5916c31f4954ce5bcc00013eec83edb020edbbfbd3260b9c17d0",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.162",artifact_sha256:"6e52c44af7a3ea3633a4dc28aa63696143cd80044bca7f67a57c4c156985566f",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.163",artifact_sha256:"8c14891abb51ab566864387137ea4af511db7ef9c565afb63e4f2b49c91260b6",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.164",artifact_sha256:"8c14891abb51ab566864387137ea4af511db7ef9c565afb63e4f2b49c91260b6",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.165",artifact_sha256:"8c14891abb51ab566864387137ea4af511db7ef9c565afb63e4f2b49c91260b6",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.166",artifact_sha256:"8c14891abb51ab566864387137ea4af511db7ef9c565afb63e4f2b49c91260b6",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.167",artifact_sha256:"62658de309f9b9c8fd70041c83898d8625d85fed303ac6e60c3a17afc85477e2",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.168",artifact_sha256:"24d7efe74218b862a90f48cf71dc59dce1d0dba29b167168aca06649bbfab364",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.169",artifact_sha256:"83879d03741c3f37c1502535d128685421cd7a498bc22543516a23ef2b21e496",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.170",artifact_sha256:"386b975277972e253599e5168b654e35c50b5eed9cbe711d7359e2efedd78f31",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.171",artifact_sha256:"386b975277972e253599e5168b654e35c50b5eed9cbe711d7359e2efedd78f31",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.172",artifact_sha256:"7a01a820961bd03b31007e46ba4f09df0a621ea5bfc9ee84548d6acdfd750169",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.173",artifact_sha256:"82c9ece017e109cf8b4b54734ac7a81b1ecb2ff35a426998369b6c3e690fd1ae",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.174",artifact_sha256:"07fa1db4f84afe909ad4de4bcdbda9bc785cf2598b51769b1f5620bb86b3743b",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.175",artifact_sha256:"07fa1db4f84afe909ad4de4bcdbda9bc785cf2598b51769b1f5620bb86b3743b",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0}),Object.freeze({version:"0.2.176",artifact_sha256:"ba3e211489877d0622aeca87be98e235d245f39d2b57f275cd924168d05f98ce",pi_tools_v1:!0,background_bash_v1:!0,machine_sdk_v1:!0,pi_tools_confinement_v1:!0,home_folder_v1:!0})]),Gc="16befed856b4414dee65733e82549e1db74fe0ff3841d2571cfd8605d3ee970b",Jc=Object.freeze(["ea63410f321f70848139a63ddcaa9f3f0a48daa3641898cc1db9f0e15ddfbb13","6cd101ddb09f87ed6996aa92a93911b1759b5ae33e9579c3dff8225ecfcbe1b6",Gc]),Fs=Object.freeze(["0f57db3036c275f78064796a72827d0f47fe702475e5feebb31e1569bcb5a0cf","38e82c8fefcc4ef98468eb3b4f0df450e4e196a8bd1063bb4de14ffef951a0c2"]),gp=Object.freeze(["pi_tools_v1","background_bash_v1","machine_sdk_v1","pi_tools_confinement_v1","home_folder_v1","workspace_before_v1"]),bp=new Set([b,...Pt.map((e)=>e.artifact_sha256),...Jc,...Fs]);var wp=new Set([b,...Pt.filter((e)=>e.pi_tools_v1).map((e)=>e.artifact_sha256),...Fs]);var yp=new Set([b,...Pt.filter((e)=>e.pi_tools_confinement_v1).map((e)=>e.artifact_sha256)]);var vp=new Set([b,...Pt.filter((e)=>e.home_folder_v1).map((e)=>e.artifact_sha256)]);var kp=new Set([b,...Pt.filter((e)=>e.background_bash_v1).map((e)=>e.artifact_sha256)]);var Sp=new Set([b,...Pt.filter((e)=>e.machine_sdk_v1).map((e)=>e.artifact_sha256)]);var Vc=[R,"reason-hands-worker.cjs"];function Us(e){return typeof e==="string"&&Vc.includes(e)}var qc;function zs(){return qc??{kind:"unavailable",status:"unsupported_entrypoint",sha256:null,observed_at_ms:null}}import{closeSync as Yc,constants as Zn,fstatSync as $s,lstatSync as Xc,openSync as Zc,readSync as Qc,realpathSync as ed,watch as rd}from"fs";import{dirname as Ks}from"path";function on(e,l){let f;try{let g=Ks(e),w=Xc(g);if(!w.isDirectory()||w.isSymbolicLink()||!A(w,18)||ed(g)!==g)return null;f=Zc(e,Zn.O_RDONLY|Zn.O_NOFOLLOW|Zn.O_NONBLOCK);let S=$s(f);if(!S.isFile()||S.nlink!==1||!A(S)||S.size<1||S.size>8192)return null;let I=Buffer.alloc(8193),W=Qc(f,I,0,I.length,0),x=$s(f);if(W!==S.size||x.size!==S.size||x.nlink!==1||x.mtimeMs!==S.mtimeMs||x.ctimeMs!==S.ctimeMs)return null;let M=JSON.parse(I.subarray(0,W).toString("utf8"));if(!M||M.pid!==l.pid||!Number.isSafeInteger(M.pid)||M.pid<1||M.launchId!==l.launchId||M.workerVersion!==l.workerVersion||M.protocolVersion!==l.protocolVersion||M.workerArtifactSha256!==l.workerArtifactSha256||M.workerEntrypoint!==l.workerEntrypoint||M.workspaceAliasReady!==!0||!U(M.targetGeneration)||!U(M.generation)||!N(M.fenceId))return null;return{...l,generation:M.generation,targetGeneration:M.targetGeneration,fenceId:M.fenceId,workspaceAliasReady:!0}}catch{return null}finally{if(f!==void 0)Yc(f)}}var td=(e,l,f)=>{let g=rd(e,{persistent:!1},l);return g.on("error",f),g};function Gs(e){let l=new AbortController,f=e.initial,g=f.targetGeneration,w=!1,S=!1,I,W,x=()=>{if(S)return;S=!0,I?.close(),I=void 0,clearInterval(W),e.signal.removeEventListener("abort",x),l.abort()},M=()=>{if(S)return;if(!e.isAlive()){x();return}let G=on(e.path,e.initial);if(!G||G.generation<f.generation||G.targetGeneration<f.targetGeneration||G.targetGeneration===f.targetGeneration&&G.fenceId!==f.fenceId)return;if(f=G,w||G.targetGeneration<=g)return;g=G.targetGeneration,w=!0,Promise.resolve().then(()=>(l.signal.throwIfAborted(),e.publish(G,l.signal))).catch(()=>{if(!S)x(),e.failed?.()}).finally(()=>{w=!1,M()})};if(e.signal.aborted)return x(),{stop:x};e.signal.addEventListener("abort",x,{once:!0});try{I=(e.watch??td)(Ks(e.path),M,()=>{I?.close(),I=void 0})}catch{}return W=setInterval(M,1000),W.unref?.(),M(),{stop:x}}import{spawn as nd}from"child_process";import{chmodSync as od,mkdtempSync as sd,realpathSync as id,rmSync as ad,unlinkSync as cd,writeFileSync as dd}from"fs";import ld from"net";import{platform as ud,tmpdir as fd}from"os";import{join as Js}from"path";var Vs=1048576,ro=105000,pd=2000,_d=String.raw`
|
|
307
|
+
const { writeSync } = require("node:fs");
|
|
308
|
+
const { createRequire } = require("node:module");
|
|
309
|
+
const { join } = require("node:path");
|
|
310
|
+
const { createInterface } = require("node:readline");
|
|
311
|
+
const { formatWithOptions, inspect } = require("node:util");
|
|
312
|
+
const vm = require("node:vm");
|
|
313
|
+
|
|
314
|
+
const timeoutMs = ${ro};
|
|
315
|
+
const maxLogChars = 524288;
|
|
316
|
+
let activeOutput = [];
|
|
317
|
+
let activeOutputChars = 0;
|
|
318
|
+
function appendOutput(value) {
|
|
319
|
+
if (activeOutputChars >= maxLogChars) return;
|
|
320
|
+
const kept = String(value).slice(0, maxLogChars - activeOutputChars);
|
|
321
|
+
activeOutput.push(kept);
|
|
322
|
+
activeOutputChars += kept.length;
|
|
323
|
+
}
|
|
324
|
+
const replConsole = Object.fromEntries(
|
|
325
|
+
["log", "info", "warn", "error", "debug"].map((method) => [
|
|
326
|
+
method,
|
|
327
|
+
(...args) => {
|
|
328
|
+
const formatted = formatWithOptions({ colors: false }, ...args);
|
|
329
|
+
appendOutput(formatted + "\n");
|
|
330
|
+
},
|
|
331
|
+
]),
|
|
332
|
+
);
|
|
333
|
+
const originalProcessKill = process.kill.bind(process);
|
|
334
|
+
function selfOnlyProcessKill(pid, signal) {
|
|
335
|
+
if (pid !== process.pid) {
|
|
336
|
+
const error = new Error("kill EPERM");
|
|
337
|
+
error.code = "EPERM";
|
|
338
|
+
error.errno = -1;
|
|
339
|
+
error.syscall = "kill";
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
return originalProcessKill(pid, signal);
|
|
343
|
+
}
|
|
344
|
+
Object.defineProperty(process, "kill", {
|
|
345
|
+
value: selfOnlyProcessKill,
|
|
346
|
+
configurable: false,
|
|
347
|
+
enumerable: true,
|
|
348
|
+
writable: false,
|
|
349
|
+
});
|
|
350
|
+
Object.defineProperty(process, "_kill", {
|
|
351
|
+
value: selfOnlyProcessKill,
|
|
352
|
+
configurable: false,
|
|
353
|
+
enumerable: false,
|
|
354
|
+
writable: false,
|
|
355
|
+
});
|
|
356
|
+
const localRequire = createRequire(join(process.cwd(), "__ara_hands_node_repl__.js"));
|
|
357
|
+
const context = vm.createContext({
|
|
358
|
+
AbortController,
|
|
359
|
+
AbortSignal,
|
|
360
|
+
Buffer,
|
|
361
|
+
URL,
|
|
362
|
+
URLSearchParams,
|
|
363
|
+
clearImmediate,
|
|
364
|
+
clearInterval,
|
|
365
|
+
clearTimeout,
|
|
366
|
+
console: replConsole,
|
|
367
|
+
fetch,
|
|
368
|
+
process,
|
|
369
|
+
queueMicrotask,
|
|
370
|
+
require: localRequire,
|
|
371
|
+
setImmediate,
|
|
372
|
+
setInterval,
|
|
373
|
+
setTimeout,
|
|
374
|
+
structuredClone,
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
async function evaluate(code) {
|
|
378
|
+
activeOutput = [];
|
|
379
|
+
activeOutputChars = 0;
|
|
380
|
+
const originalStdoutWrite = process.stdout.write;
|
|
381
|
+
process.stdout.write = function(chunk, encoding, callback) {
|
|
382
|
+
const normalizedEncoding = typeof encoding === "string" ? encoding : undefined;
|
|
383
|
+
appendOutput(Buffer.isBuffer(chunk) ? chunk.toString(normalizedEncoding) : chunk);
|
|
384
|
+
const completed = typeof encoding === "function" ? encoding : callback;
|
|
385
|
+
if (typeof completed === "function") queueMicrotask(completed);
|
|
386
|
+
return true;
|
|
387
|
+
};
|
|
388
|
+
const script = new vm.Script(code, { filename: "reason-hands-node-repl.js" });
|
|
389
|
+
let timer;
|
|
390
|
+
try {
|
|
391
|
+
const value = script.runInContext(context, { timeout: timeoutMs });
|
|
392
|
+
const resolved = await Promise.race([
|
|
393
|
+
Promise.resolve(value),
|
|
394
|
+
new Promise((_, reject) => {
|
|
395
|
+
timer = setTimeout(
|
|
396
|
+
() => reject(new Error("REPL evaluation timed out after 105 seconds")),
|
|
397
|
+
timeoutMs,
|
|
398
|
+
);
|
|
399
|
+
}),
|
|
400
|
+
]);
|
|
401
|
+
const inspected = inspect(resolved, {
|
|
402
|
+
depth: 8,
|
|
403
|
+
colors: false,
|
|
404
|
+
maxArrayLength: 200,
|
|
405
|
+
maxStringLength: 16_000,
|
|
406
|
+
breakLength: 120,
|
|
407
|
+
});
|
|
408
|
+
const emitted = activeOutput.join("");
|
|
409
|
+
return emitted.length === 0
|
|
410
|
+
? inspected
|
|
411
|
+
: emitted + (emitted.endsWith("\n") ? "" : "\n") + inspected;
|
|
412
|
+
} finally {
|
|
413
|
+
if (timer) clearTimeout(timer);
|
|
414
|
+
process.stdout.write = originalStdoutWrite;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Ordinary stdout is just an untrusted result stream, not a control authority.
|
|
419
|
+
// The parent must terminate and reap this process before accepting any result.
|
|
420
|
+
function respond(payload) { writeSync(1, JSON.stringify(payload) + "\n"); }
|
|
421
|
+
|
|
422
|
+
let queue = Promise.resolve();
|
|
423
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
424
|
+
lines.on("line", (line) => {
|
|
425
|
+
queue = queue.then(async () => {
|
|
426
|
+
try {
|
|
427
|
+
const request = JSON.parse(line);
|
|
428
|
+
if (request.action === "probe") {
|
|
429
|
+
respond({ ok: true, output: "ARA_HANDS_REPL_READY" });
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (request.action !== "evaluate" || typeof request.code !== "string") {
|
|
433
|
+
throw new Error("Invalid REPL request");
|
|
434
|
+
}
|
|
435
|
+
respond({ ok: true, output: await evaluate(request.code) });
|
|
436
|
+
} catch (error) {
|
|
437
|
+
respond({
|
|
438
|
+
ok: false,
|
|
439
|
+
error: error instanceof Error ? error.message : String(error),
|
|
440
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
}).catch((error) => respond({ ok: false, error: String(error) }));
|
|
444
|
+
});
|
|
445
|
+
`;function md(e=process.execPath,l=process.versions.bun){return l?"node":e}function Qn(e){try{cd(e)}catch{}}function sn(e,l){e.end(`${JSON.stringify(l)}
|
|
446
|
+
`)}function eo(e){return JSON.stringify(e)}function hd(e){let l=sd(Js(fd(),"reason-node-repl-")),f=Js(l,"node-repl.sb"),w=["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)","(deny network*)",`(allow file-read* ${["/System","/usr","/bin","/opt/homebrew","/usr/local"].map((I)=>`(subpath ${eo(I)})`).join(" ")})`,`(allow file-read* file-write* (subpath ${eo(e.workRoot)}) (subpath ${eo(l)}))`].join(`
|
|
447
|
+
`);dd(f,w,{mode:384});let S=!1;return{command:"/usr/bin/sandbox-exec",args:["-f",f,e.nodeExecutable,...e.nodeArgs],cwd:e.workRoot,env:{...e.environment,TMPDIR:l},async cleanup(){if(S)return;S=!0,ad(l,{recursive:!0,force:!0})}}}async function gd(e){let l=id(e.workRoot),f=e.nodeExecutable??md(),g=["--max-old-space-size=512","--permission",`--allow-fs-read=${l}`,`--allow-fs-write=${l}`,"-e",_d],w=ze({home:l,temporaryDirectory:l}),S=e.platformName??ud();if(S==="linux")return{command:f,args:g,cwd:l,env:w,async cleanup(){}};if(S==="darwin")return hd({nodeExecutable:f,nodeArgs:g,workRoot:l,environment:w});throw Error("hands_node_repl_platform_unsupported")}async function Wt(e){let l;try{await Promise.race([e,new Promise((f,g)=>{l=setTimeout(()=>g(Error("hands_node_repl_child_cleanup_timeout")),pd)})])}finally{clearTimeout(l)}}async function qs(e){if(e.executionMode!=="single-evaluation")throw Error(Cs);let l=await gd(e),f;try{f=nd(l.command,l.args,{cwd:l.cwd,env:l.env,stdio:["pipe","pipe","pipe"]})}catch(be){throw await l.cleanup(),be}let g=new Promise((be)=>f.once("close",()=>be())),w;f.once("error",(be)=>{w=be});let S=!1,I=!1,W="";f.stderr.setEncoding("utf8"),f.stderr.on("data",(be)=>{W=`${W}${be}`.slice(-16384)});let x=f.stdout,M,G=(be,Re,Fe)=>{if(Fe)be.failure??=Fe;if(be.finishing)return;be.finishing=!0,I=!0,f.kill("SIGKILL"),Wt(g).then(()=>{if(be.failure)be.reject(be.failure);else be.resolve(Re??{})},(Ye)=>be.reject(Ye))},F=()=>{if(I=!0,M)G(M,void 0,Error("hands_node_repl_state_lost"));else f.kill("SIGKILL")},T="";x?.setEncoding("utf8"),x?.on("data",(be)=>{if(M?.finishing||I)return;if(T+=be,T.length>Vs){F();return}while(!0){let Re=T.indexOf(`
|
|
448
|
+
`);if(Re===-1)return;let Fe=T.slice(0,Re);T=T.slice(Re+1);let Ye=M;if(!Ye){F();return}try{let ye=JSON.parse(Fe);if(Ye.action==="probe")Ye.resolve(ye);else{G(Ye,ye);return}}catch{G(Ye,void 0,Error("invalid_hands_node_repl_child_response"));return}}});let re=(be)=>{let Re=W.trim(),Fe=be??Error(Re?`hands_node_repl_child_exited:${Re}`:"hands_node_repl_child_exited");if(I=!0,M&&!M.finishing)G(M,void 0,Fe)};f.once("error",re),f.once("close",()=>re()),f.stdin.on("error",re);let J=(be)=>new Promise((Re,Fe)=>{if(S||I||f.exitCode!==null||f.signalCode!==null){Fe(Error(I?"hands_node_repl_state_lost":"hands_node_repl_stopped"));return}let Ye=setTimeout(F,be.action==="probe"?1e4:Math.max(1,Math.min(e.evaluationTimeoutMs??ro-1000,ro-1000))),ye={action:be.action,finishing:!1,resolve(We){if(M===ye)M=void 0;clearTimeout(Ye),Re(We)},reject(We){if(M===ye)M=void 0;clearTimeout(Ye),Fe(We)}};M=ye,f.stdin.write(`${JSON.stringify(be)}
|
|
449
|
+
`,(We)=>{if(!We)return;G(ye,void 0,We)})});try{if(!x){if(f.pid===void 0)await Wt(g);throw w??Error("hands_node_repl_control_pipe_missing")}let be=await J({action:"probe"});if(be.ok!==!0||be.output!=="ARA_HANDS_REPL_READY")throw Error("hands_node_repl_probe_failed")}catch(be){S=!0,f.kill("SIGKILL");try{await Wt(g)}finally{await l.cleanup()}throw be}let z=Promise.resolve(),fe=new Set;Qn(e.socketPath);let ke=ld.createServer((be)=>{fe.add(be),be.once("close",()=>fe.delete(be)),be.setEncoding("utf8");let Re="",Fe=!1,Ye=!1;be.once("close",()=>{if(Ye)F()}),be.on("error",()=>be.destroy()),be.on("data",(ye)=>{if(Fe)return;if(Re+=ye,Re.length>Vs){Fe=!0,sn(be,{ok:!1,error:"REPL request exceeds 1 MiB"});return}let We=Re.indexOf(`
|
|
450
|
+
`);if(We===-1)return;Fe=!0;let qe=Re.slice(0,We);z=z.then(async()=>{if(be.destroyed)return;try{let Te=JSON.parse(qe);if(Te.action!=="evaluate"||typeof Te.code!=="string")throw Error("Invalid REPL request");Ye=!0;let le=await J({action:"evaluate",code:Te.code});if(Ye=!1,le.ok!==!0||typeof le.output!=="string")throw Error(typeof le.error==="string"?le.error:"hands_node_repl_failed");sn(be,{ok:!0,output:le.output})}catch(Te){Ye=!1,sn(be,{ok:!1,error:Te instanceof Error?Te.message:String(Te),stack:Te instanceof Error?Te.stack:void 0})}}).catch((Te)=>{sn(be,{ok:!1,error:Te instanceof Error?Te.message:String(Te)})})})});try{await new Promise((be,Re)=>{ke.once("error",Re),ke.listen(e.socketPath,()=>{ke.off("error",Re);try{od(e.socketPath,384),be()}catch(Fe){ke.close(()=>Re(Fe))}})})}catch(be){S=!0,f.kill("SIGKILL");try{await Wt(g)}finally{await l.cleanup(),Qn(e.socketPath)}throw be}return{socketPath:e.socketPath,async stop(){if(S)return;S=!0;let be=new Promise((Re)=>ke.close(()=>Re()));for(let Re of fe)Re.destroy();await be,z.catch(()=>{return}),F();try{await Wt(g)}finally{await l.cleanup(),Qn(e.socketPath)}}}}var to=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var Ys="/workspace",Xs="/var/lib/reason/sessions",bd="/var/lib/reason/session-controls";function yr(e){let l=`${Xs}/`;if(!e.startsWith(l))return null;let f=e.slice(l.length);if(!to.test(f)||f!==f.toLowerCase())throw Error("personal_computer_invalid_runtime_root");return`${bd}/${f}/job.env`}function wd(e){if(!to.test(e))throw Error("personal_computer_invalid_identity");return e.toLowerCase()}function an(e){let l=wd(e);return{runtimeRoot:`${Xs}/${l}`,workspaceRoot:`${Ys}/sessions/${l}`,sharedRoot:Ys}}var Zs="/root/.ara/cloud-browser/repl.sock";function no(e){return e==="compute"}function Qs(e,l,f="linux"){if(e)an(e);if(f!=="linux")throw Error("cloud_browser_os_invalid");if(l!==void 0&&(!e||!/^[1-9][0-9]{0,18}$/.test(l)))throw Error("cloud_browser_generation_invalid");let g=e?`/var/lib/reason/browsers/${e.toLowerCase()}`:"/root/.ara/cloud-browser",w=e?`${g}/${l?`g${l}`:"current"}`:g,S=e?`/root/.b/${e.toLowerCase().replaceAll("-","")}`:g;return{temporarySessionDirectory:S,temporaryDirectory:e?`${S}/${l??"current"}`:`${w}/tmp`,directory:w,sessionDirectory:g,config:`${w}/config.json`,status:`${w}/status.json`,socket:`${w}/repl.sock`,bundle:`${w}/driver.mjs`,processName:e?`ara-browser-${e.toLowerCase()}${l?`-${l}`:""}`:"ara-cloud-browser"}}var so="browser_egress",ei=qo,Hd=45000,Nd=Gt+1500,Zr=/^[A-Za-z0-9._:-]{1,160}$/,Ld="/run/ara-hands";function Bd(e,l,f=ti()){if(e==="darwin")return{temporaryRoot:f,prepareRoot:!1,sessionMode:448};return{temporaryRoot:l??Ld,prepareRoot:!0,sessionMode:457}}function me(e,l=process.platform,f=process.geteuid?.()){return e===!0&&l==="linux"&&f===0}function ge(e=K(),l=process.platform,f=process.geteuid?.()){return e&&l==="linux"&&f===0?{uid:e.uid,gid:e.gid,home:e.home,username:e.username}:null}function Rt(e=ge(),l=As){return e&&l()?qn:null}function jd(e,l){if(!l&&(e??"linux")==="linux")return Zs;return Qs(l,void 0,e??"linux").socket}function At(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function oi(e){let l=e.toLowerCase().replace(/^\[|\]$/g,"");return l==="localhost"||l.endsWith(".localhost")||l==="::1"||l==="0:0:0:0:0:0:0:1"||l==="0.0.0.0"||l.startsWith("127.")}class wr extends r{expiryDiagnostic;constructor(e){super("invalid_hands_expiry","Reason Hands connection expiry is invalid.");this.expiryDiagnostic=e}}function Md(e){return At(e)&&Object.keys(e).every((l)=>l==="source_path"||l==="branch")&&(e.source_path===void 0||X(e.source_path))&&typeof e.branch==="string"&&Yn.test(e.branch)}function Wd(e,l,f){let g=l===void 0?Date.now():l,w=["relay_url","session_id","environment_id","expires_at","policy_mode","policy_version","hands_protocol_version","hands_worker_version","hands_worker_artifact_sha256","hands_worker_entrypoint","target_generation","target_fence_id"],S=new Set([...w,"workspace_id","legacy_workspace_id",Ce,Ae,"environment_binding","cloud_browser","sandbox_provider","sandbox_os","personal_workspace","workspace_path","workspace_worktree",Xe,so,Et,Q,Y,q]),I=At(e)?e:null,W=I?.[so],x=I?.[Et],M=I?.[Y],G=W===void 0||(I?.[Xe]===Xr||M===pe&&I?.[Xe]===void 0)&&At(W)&&Object.keys(W).every((ke)=>ke==="mode"||ke==="allowed_domains")&&W.mode==="enforce"&&Array.isArray(W.allowed_domains)&&W.allowed_domains.length<=256&&W.allowed_domains.every((ke)=>typeof ke==="string"&&Nn(ke));if(!At(e)||w.some((ke)=>!(ke in e))||Object.keys(e).some((ke)=>!S.has(ke))||!G||M!==void 0&&M!==pe||I?.[q]!==void 0&&I[q]!==Oe||I?.personal_workspace!==void 0&&(I.personal_workspace!==!0||I[Xe]!==Xr)||I?.cloud_browser!==void 0&&(I.cloud_browser!==!0||I[Xe]!==Xr)||I?.sandbox_provider!==void 0&&!no(I.sandbox_provider)||I?.sandbox_os!==void 0&&I.sandbox_os!=="linux"||x!==void 0&&(I?.[Xe]!==St||!Ns(x))||Xe in e&&e[Xe]!==Xr&&e[Xe]!==St&&e[Xe]!==Mr||e.workspace_path!==void 0&&(!X(e.workspace_path)||e[Xe]!==Mr)||e.workspace_worktree!==void 0&&(e.workspace_path===void 0||!Md(e.workspace_worktree))||typeof e.relay_url!=="string"||typeof e.session_id!=="string"||!Zr.test(e.session_id)||e.workspace_id!==void 0&&(typeof e.workspace_id!=="string"||!Zr.test(e.workspace_id))||e.legacy_workspace_id!==void 0&&(typeof e.legacy_workspace_id!=="string"||!Zr.test(e.legacy_workspace_id))||e[Ce]!==void 0&&(e[Ce]!==ue||(Xe in e))||e[Ae]!==void 0&&(e[Ae]!==Z||(Xe in e))||e[Q]!==void 0&&(typeof e[Q]!=="string"||!Zr.test(e[Q]))||typeof e.environment_id!=="string"||!Zr.test(e.environment_id)||typeof e.expires_at!=="string"||e.policy_mode!=="full_access"||e.policy_version!==1||e.hands_protocol_version!==P||e.hands_worker_version!==D||e.hands_worker_artifact_sha256!==b||!Us(e.hands_worker_entrypoint)||!U(e.target_generation)||!N(e.target_fence_id))throw new r("invalid_hands_payload","Reason Hands connection payload is invalid.");let F;try{F=new URL(e.relay_url)}catch{throw new r("invalid_hands_relay","Reason Hands relay URL is invalid.")}if((oi(F.hostname)?F.protocol!=="ws:":F.protocol!=="wss:")||F.username||F.password||F.hash||!/^\/device\/[A-Za-z0-9-]+\/[A-Za-z0-9]+$/.test(F.pathname))throw new r("invalid_hands_relay","Reason Hands relay URL is not allowed.");let re=Date.parse(e.expires_at),J=Number.isNaN(re)?"parse":new Date(re).toISOString()!==e.expires_at?"noncanonical":re<=g?"expired":re-g>ei?"over_cap":"accepted",z={version:1,outcome:J,clock_source:l===void 0?"date_now":"injected",validation_now_ms:bt(g),expiry_ms:bt(re),remaining_ms:Number.isSafeInteger(re-g)?re-g:null,maximum_lifetime_ms:ei,cli_artifact:zs()};if(J!=="accepted")throw new wr(z);try{f?.(z)}catch{}let fe=e.environment_binding===void 0?void 0:Tn.safeParse(e.environment_binding);if(fe&&!fe.success)throw new r("invalid_hands_request","Reason Hands environment binding is invalid.");return{...e.cloud_browser===!0?{cloud_browser:!0}:{},...no(e.sandbox_provider)?{sandbox_provider:e.sandbox_provider}:{},...e.sandbox_os==="linux"?{sandbox_os:e.sandbox_os}:{},...e.personal_workspace===!0?{personal_workspace:!0}:{},relay_url:F.toString(),...fe?.success?{environment_binding:fe.data}:{},session_id:e.session_id,...e.workspace_id===void 0?{}:{workspace_id:e.workspace_id},...e.legacy_workspace_id===void 0?{}:{legacy_workspace_id:e.legacy_workspace_id},...e[Ce]===ue?{[Ce]:ue}:{},...e[Ae]===Z?{[Ae]:Z}:{},...typeof e[Q]==="string"?{[Q]:e[Q]}:{},...e[Y]===pe?{[Y]:pe}:{},...e[q]===Oe?{[q]:Oe}:{},...typeof e.workspace_path==="string"?{workspace_path:e.workspace_path}:{},...At(e.workspace_worktree)?{workspace_worktree:{...typeof e.workspace_worktree.source_path==="string"?{source_path:e.workspace_worktree.source_path}:{},branch:String(e.workspace_worktree.branch)}}:{},environment_id:e.environment_id,expires_at:e.expires_at,policy_mode:"full_access",policy_version:1,hands_protocol_version:P,hands_worker_version:D,hands_worker_artifact_sha256:b,hands_worker_entrypoint:R,target_generation:e.target_generation,target_fence_id:e.target_fence_id,...Xe in e?{[Xe]:e[Xe]}:{},...x===void 0?{}:{[Et]:x},...W===void 0?{}:{[so]:{mode:"enforce",allowed_domains:[...new Set(W.allowed_domains)].sort()}}}}function Fd(){let e=new Map;return{acquire(l,f){if(e.has(l))return null;let g=[...e.values()],w=(I)=>f.group!==void 0&&I.group===f.group;if(f.exclusive?!g.every(w):g.some((I)=>I.exclusive))return null;if(f.limit!==void 0&&!g.some(w)&&new Set(g.map((I,W)=>I.group??W)).size>=f.limit)return null;e.set(l,f);let S=!1;return()=>{if(S)return;S=!0,e.delete(l)}},activeOwners:()=>[...e.keys()]}}var Ud=Fd();function zd(e,l){Ct(e,{recursive:!0,mode:448});let f=nr(e),g=()=>new r("invalid_hands_workspace","Reason Hands managed workspace ancestor must be a real directory, not a link.");for(let I of l.split("/")){let W=lr(f,I);try{let M=ur(W);if(M.isSymbolicLink()||!M.isDirectory())throw g()}catch(M){if(!(M&&typeof M==="object"&&("code"in M)&&M.code==="ENOENT"))throw M;try{Ct(W,{mode:448})}catch(G){if(!(G&&typeof G==="object"&&("code"in G)&&G.code==="EEXIST"))throw G}}let x=ur(W);if(x.isSymbolicLink()||!x.isDirectory()||nr(W)!==W)throw g();f=W}if(process.platform==="win32"){let I=ur(f);if(I.isSymbolicLink()||!I.isDirectory()||nr(f)!==f||!$r(nr(e),f))throw g();return f}let w=ur(f),S=xd(f,Tt.O_RDONLY|Tt.O_DIRECTORY|Tt.O_NOFOLLOW);try{let I=Od(S);if(!I.isDirectory()||I.dev!==w.dev||I.ino!==w.ino||nr(f)!==f)throw g();Rd(S,448)}finally{Ed(S)}return f}function $d(e,l=Do(),f,g,w){if(!Zr.test(e)||f!==void 0&&!Zr.test(f))throw new r("invalid_hands_workspace","Reason Hands run identity is invalid.");let S=Dr(O({kind:"managed",workspaceId:e,...g?{base:g}:{},...w?{layout:w}:{}})),I=zd(l,Dr(S)),W=lr(I,Dd(S)),x=!1;try{let T=ur(W);if(x=!0,T.isSymbolicLink())throw new r("invalid_hands_workspace","Reason Hands workspace cannot be a symbolic link.");if(!T.isDirectory())throw new r("invalid_hands_workspace","Reason Hands workspace must be a managed directory.")}catch(T){if(T instanceof r||!(T&&typeof T==="object"&&("code"in T)&&T.code==="ENOENT"))throw T}if(w&&!x)try{let T=lr(nr(l),Dr(O({kind:"managed",workspaceId:e,...g?{base:g}:{}}))),re=ur(T);if(!re.isSymbolicLink()&&re.isDirectory()&&nr(T)===T)cn(T,W),x=!0}catch{}if(f&&f!==e){let T=lr(I,f);try{let re=ur(T);if(re.isSymbolicLink()||!re.isDirectory())throw new r("invalid_hands_workspace","Reason Hands legacy workspace must be a managed directory.");let J=nr(T);if(Dr(J)!==I)throw new r("invalid_hands_workspace","Reason Hands legacy workspace escaped its managed parent.");let z=null;if(x){z=lr(I,`.${e}.previous`);try{throw ur(z),new r("invalid_hands_workspace","Reason Hands previous workspace backup already exists.")}catch(fe){if(fe instanceof r||!(fe&&typeof fe==="object"&&("code"in fe)&&fe.code==="ENOENT"))throw fe}cn(W,z)}try{cn(J,W)}catch(fe){if(z)cn(z,W);throw fe}x=!0}catch(re){if(re instanceof r||!(re&&typeof re==="object"&&("code"in re)&&re.code==="ENOENT"))throw re}}Ct(W,{recursive:!0,mode:448}),Ft(W,448);let M=nr(W);if(Dr(M)!==I)throw new r("invalid_hands_workspace","Reason Hands workspace escaped its managed parent.");let G=lr(M,"repo");try{let T=ur(G);if(T.isSymbolicLink()||!T.isDirectory())throw new r("invalid_hands_workspace","Reason Hands repository must be a managed directory.")}catch(T){if(T instanceof r||!(T&&typeof T==="object"&&("code"in T)&&T.code==="ENOENT"))throw T}Ct(G,{recursive:!0,mode:448}),Ft(G,448);let F=nr(G);if(Dr(F)!==M)throw new r("invalid_hands_workspace","Reason Hands repository escaped its managed run workspace.");return{workRoot:M,repoPath:F}}function br(e){let l=null;try{l=ur(e)}catch{}if(!l||l.isSymbolicLink()||!l.isDirectory()||l.uid!==0||l.gid!==0||(l.mode&4095)!==493)throw new r("cloud_workspace_root_invalid","This cloud Session's workspace root is not root's 0755 directory, so Reason Hands cannot use it.")}function Kd(e,l,f=process.geteuid?.(),g=process.platform){if(g==="win32")return"unknown";let w;try{if(w=lt(e),!w.isDirectory())return"unready";Sd(e,Tt.R_OK|Tt.W_OK|Tt.X_OK)}catch{return"unready"}try{if(ur(e).isSymbolicLink()||nr(e)!==e)return"unknown"}catch{return"unknown"}if(f!==0)return"checked";if(l===null||w.uid!==l.uid||(w.mode&448)!==448)return"unknown";for(let S=Dr(e);;S=Dr(S)){let I;try{I=lt(S)}catch{return"unknown"}if(!(I.uid===l.uid?(I.mode&64)!==0:I.gid===l.gid?(I.mode&8)!==0:(I.mode&1)!==0))return"unknown";if(S===Dr(S))return"checked"}}function Gd(e,l){let f="/";for(let g of["",...e.split("/"),...l.split("/")].filter((w,S)=>S===0||w)){if(g)f=lr(f,g);let w;try{w=ur(f)}catch{return null}if(w.uid!==0)return w.uid;if((w.mode&2)!==0&&(w.mode&512)===0&&!w.isSymbolicLink())return-1;if(w.isSymbolicLink()||!w.isDirectory())return null}return null}function Jd(e,l,f,g=process.geteuid?.(),w){if(!Zr.test(l))return null;let S,I;try{S=nr(e),I=Dr(O({kind:"managed",workspaceId:l,...f?{base:f}:{},...w?{layout:w}:{}}))}catch{return null}let W=lr(S,I),x=tn(W)!==null,M=(J)=>new r("cloud_workspace_root_invalid",J),G;if(g===0){let J=Gd(S,I);if(J===null)return null;if(!x)throw new r("invalid_hands_workspace","As root, Reason Hands never prepares a workspace in folders another user owns.");G=J}else{if(!x)return null;let J,z;try{J=ur(Dr(W)),z=ur(W)}catch{return null}if(J.isSymbolicLink()||!J.isDirectory()||J.uid===0||z.uid!==0)return null;G=J.uid}let F=S;for(let J of I.split("/")){let z=lr(F,J),fe=!1;try{let ke=ur(z);fe=!ke.isSymbolicLink()&&ke.isDirectory()&&nr(z)===z}catch{}if(!fe)throw M("This cloud Session's workspace root is missing or is not a real directory.");F=z}br(W);let T;try{T=vr(W)}catch(J){if(J instanceof r)throw J;throw M("This cloud Session's workspace root changed while Reason Hands checked it.")}let re=null;try{re=lt(T.repoPath).uid}catch{}if(re!==G)throw new r("invalid_hands_workspace","Reason Hands repository must belong to the cloud Session's user.");return T}function vr(e,l=!1){let f=nr(e),g=lr(f,"repo"),w;try{w=ur(g)}catch{throw new r("invalid_hands_workspace","Reason Hands repository is missing from the granted root.")}if(l){if(!/^\/var\/lib\/reason\/sessions\/[0-9a-f-]{36}$/.test(f))throw new r("invalid_hands_workspace","Personal runtime identity is invalid.");if(an(f.slice(f.lastIndexOf("/")+1)).runtimeRoot!==f)throw new r("invalid_hands_workspace","Personal runtime identity is invalid.");let W=nr("/workspace"),x=nr(g);if(W!=="/workspace"||!lt(x).isDirectory()||!x.startsWith("/workspace/"))throw new r("invalid_hands_workspace","Personal files escaped the personal computer.");return{workRoot:f,repoPath:x}}let S=Ts(f);if(S&&w.isSymbolicLink()){let W=nr(g);if(W!==nr(S)||!lt(W).isDirectory())throw new r("invalid_hands_workspace","Side chat repository must be its parent's checkout.");return{workRoot:f,repoPath:W}}if(w.isSymbolicLink()||!w.isDirectory())throw new r("invalid_hands_workspace","Reason Hands repository must be a managed directory.");let I=nr(g);if(Dr(I)!==f)throw new r("invalid_hands_workspace","Reason Hands repository escaped its granted root.");return{workRoot:f,repoPath:I}}function co(e,l,f){if(l!==void 0&&!X(l))throw new r("invalid_hands_workspace",`Reason Hands ${f} is invalid.`);let g=ni(e,l??".");if(!$r(e,g))throw new r("invalid_hands_workspace",`Reason Hands ${f} escapes its granted root.`);return g}function si(e,l,f){if(Qe(l)){let g=nr(f);return{anchor:g,target:ni(g,l),boundary:lr(g,de)}}return{anchor:e,target:co(e,l,"folder"),boundary:e}}function Vd(e,l){if(!$r(e,l))throw new r("invalid_hands_workspace","Reason Hands folder escapes its granted root.");let f=e;for(let g of l.slice(e.length).split(Cd).filter(Boolean)){f=lr(f,g);let w=null;try{w=ur(f)}catch(S){if(S.code!=="ENOENT")throw S}if(!w)Ct(f,{mode:448});else if(w.isSymbolicLink()||!w.isDirectory())throw new r("invalid_hands_workspace","Reason Hands folder must be made of real directories.")}}function ii(e,l){let f=nr(co(e,l.source_path,"repository"));if(!$r(e,f)||!lt(f).isDirectory())throw new r("invalid_hands_workspace","Reason Hands repository must be a folder in its granted root.");return f}async function qd(e,l,f,g=a()){try{let w=nr(e);if(ao(si(w,l,g).target))return;return await Bs(ii(w,f))??void 0}catch{return}}function Yd(e,l,f,g,w=Xd,S=a()){let I=nr(e),{target:W,boundary:x,anchor:M}=si(I,l,S);if(f&&!ao(W)){let T=ii(I,f);Vd(M,Dr(W));let re=["-c","core.hooksPath=/dev/null","-C",T];if(g)w([...re,"update-ref","--create-reflog","-m",g.note,`refs/heads/${f.branch}`,g.commit,""]);let J=g?w([...re,"worktree","add",W,f.branch]):w([...re,"worktree","add","-b",f.branch,W]);if(!g&&J.status!==0&&/already exists/.test(J.stderr)&&!ao(W))J=w([...re,"worktree","add",W,f.branch]);if(J.status!==0)throw new r(/not a git repository/i.test(J.stderr)?"workspace_not_git_repository":"workspace_worktree_failed","Reason could not create this Session's git worktree.")}let G;try{G=ur(W)}catch{throw new r("workspace_folder_missing","This Session's folder no longer exists.")}let F=nr(W);if(G.isSymbolicLink()&&!$r(x,F))throw new r("invalid_hands_workspace","Reason Hands folder resolves outside its granted root.");if(!lt(F).isDirectory()||!$r(x,F))throw new r("invalid_hands_workspace","Reason Hands folder must be a directory in its granted root.");if(E(F))throw new r("protected_path","Credential and secret folders are unavailable to Sessions.");return F}function Xd(e){let l=jo();if(!l)return{status:null,stderr:"git was not found. Install Git for Windows (https://git-scm.com/download/win)."};let f=kd(l,e,{encoding:"utf8",timeout:60000,env:{...process.env,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});return{status:f.status,stderr:f.stderr??""}}function ai(e){return yr(e)??tn(e)?.jobEnv??lr(e,"job.env")}function Zd(e,l){let f=ai(e),g=ur(f);if(g.isSymbolicLink()||!g.isFile())throw new r("invalid_hands_workspace","Reason Hands job environment must be a managed regular file.");Pd(f,l),Ft(l,384)}function Qd(e){if(e.workspaceMode===Mr&&e.workspacePath!==void 0){let I=e.home??a(),W=Yd(e.grantedRoot,e.workspacePath,e.workspaceWorktree,e.workspaceWorktreeStart,void 0,I);if(e.workspaceWorktree&&e.deviceId)Ms(I,e.workspacePath,e.deviceId);return{workRoot:W,repoPath:W,workspace:{kind:"root",path:e.workspacePath},jobEnvPath:lr(e.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!0}}if(e.workspaceMode===Xr)return{...vr(e.grantedRoot,e.personalWorkspace),workspace:{kind:"root"},jobEnvPath:lr(e.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!1};if(e.workspaceMode===St||e.workspaceMode===Mr){let I=ur(e.grantedRoot);if(I.isSymbolicLink()||!I.isDirectory())throw new r("invalid_hands_workspace","Reason Hands root must be a real directory.");let W=nr(e.grantedRoot);return{workRoot:W,repoPath:W,workspace:{kind:"root"},jobEnvPath:lr(e.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!0}}let l=e.workspaceId??e.runId,f={kind:"managed",workspaceId:l,...e.workspaceBase?{base:e.workspaceBase}:{},...e.workspaceLayout?{layout:e.workspaceLayout}:{}},g=ie(e.grantedRoot,f,e.home).anchor,w=Jd(g,l,e.workspaceBase,void 0,e.workspaceLayout);if(w)return{...w,workspace:f,jobEnvPath:lr(e.temporaryDirectory,"job.env"),workspacePoolPath:null,managedWorkspace:!1,cloudSessionRoot:!0};let S=$d(l,g,e.legacyWorkspaceId,e.workspaceBase,e.workspaceLayout);return{...S,workspace:f,jobEnvPath:lr(e.temporaryDirectory,"job.env"),workspacePoolPath:Dr(S.workRoot),managedWorkspace:!0}}function gn(e){let{command:l,prefix:f}=Dn(e.executablePath,e.sourceEntrypoint),g=ze({home:Td(),temporaryDirectory:e.temporaryDirectory,path:e.path});if(g.REASON_DEVICE_ROOT=g.ARA_DEVICE_ROOT=e.grantedRoot,g.REASON_HANDS_WORKSPACE=g.ARA_HANDS_WORKSPACE=e.workRoot,g.REASON_HANDS_REPO=g.ARA_HANDS_REPO=e.root,e.workspacePoolPath)g.REASON_HANDS_WORKSPACE_POOL=g.ARA_HANDS_WORKSPACE_POOL=e.workspacePoolPath;return{command:l,args:[...f,"__device","__hands-worker","--config",e.configPath],options:{cwd:e.root,env:g,shell:!1,stdio:[_n,"ignore","pipe"]}}}var _n=process.platform==="win32"?"pipe":"ignore";function ot(e,l){if(process.platform!=="win32")return e.kill(l);if(l==="SIGTERM")e.stdin?.end();else if(e.pid)$e(e.pid);return!0}function el(e,l){let f="",g=!1,w=Date.now(),S=0,I=new Set(["connecting","open","dial_pending","socket_error","close","claim_accepted","claim_rejected","stopping","stopped","request_cancelled","permission_denied"].map((F)=>`hands.worker.${F}`)),W=new Set([null,"open_not_received","current_connection","obsolete_connection","request_aborted","request_timeout","client_closed","driver_stopped","driver_handoff","run_cancelled","run_finished","other","frame_too_large","invalid_json","invalid_claim","executor_mismatch","stale_generation","fence_conflict","SIGTERM","SIGINT","SIGHUP","expired","cleanup_complete","cleanup_failed","cancelled","settled","unsupported","unconfirmed",...["sandbox_policy","os_permission_unknown"].flatMap((F)=>["bash","read","write","edit"].map((T)=>`${F}:${T}`))]),x=["timestampMs","connectionAttempt","connectionGeneration","targetGeneration","activeRequestCount","remainingLifetimeMs","suppressedDiagnostics"],M=["peerGeneration","socketState","closeCode"],G=new Set(["event","reason","launchId",...x,...M]);return(F)=>{for(let T of F.toString().split(/(?<=\n)/)){let re=T.endsWith(`
|
|
451
|
+
`);if(!g&&f.length+T.length<=2048)f+=T;else g=!0;if(!re)continue;let J=f;if(f="",g){g=!1;continue}try{let z=JSON.parse(J);if(!z||typeof z!=="object"||Array.isArray(z)||Object.keys(z).some((fe)=>!G.has(fe))||!I.has(z.event)||!W.has(z.reason)||z.event==="hands.worker.permission_denied"!==(typeof z.reason==="string"&&z.reason.includes(":"))||z.launchId!==e||x.some((fe)=>!Number.isSafeInteger(z[fe])||z[fe]<0)||M.some((fe)=>z[fe]!==null&&(!Number.isSafeInteger(z[fe])||z[fe]<0)))continue;if(Date.now()-w>=60000)w=Date.now(),S=0;if(S>=122)continue;S+=1,l(z)}catch{}}}}async function rl(e){let l=e.now()+e.timeoutMs;while(e.now()<l){if(e.signal.aborted)throw new r("cancelled","Reason Hands start was cancelled.");if(e.spawnFailed?.()||e.child.exitCode!==null||e.child.signalCode!==null)throw new r("hands_worker_exited","Reason Hands exited before ready.");let f=on(e.path,{pid:e.child.pid??-1,launchId:e.launchId,workerVersion:D,protocolVersion:P,workerArtifactSha256:b,workerEntrypoint:R});if(f?.targetGeneration===e.targetGeneration&&f.fenceId===e.fenceId)return f;await new Promise((g)=>setTimeout(g,10))}throw new r("hands_ready_timeout","Reason Hands did not become ready.")}async function tl(e,l){let f=()=>e.exitCode===0&&e.signalCode===null;if(e.exitCode!==null||e.signalCode!==null)return f()?"stopped":"already_exited";let g=new Promise((I)=>e.once("exit",()=>I()));try{if(!ot(e,"SIGTERM"))return f()?"stopped":"unobserved"}catch{return f()?"stopped":"unobserved"}if(await ri(g,l))return f()?"stopped":"unobserved";try{ot(e,"SIGKILL")}catch{}return await ri(g,l)?"forced":"unobserved"}async function ri(e,l){let f;try{return await Promise.race([e.then(()=>!0),new Promise((g)=>{f=setTimeout(()=>g(!1),l)})])}finally{clearTimeout(f)}}function nl(e){return new Promise((l)=>{let f=!1,g=(W)=>{if(f)return;f=!0,clearTimeout(I),e.signal.removeEventListener("abort",w),e.child.off("exit",S),l(W)},w=()=>g("cancelled"),S=()=>g("exited"),I=setTimeout(()=>g("expired"),Math.max(0,e.expiresAt-e.now()));if(e.signal.addEventListener("abort",w,{once:!0}),e.child.once("exit",S),e.signal.aborted)w();else if(e.child.exitCode!==null||e.child.signalCode!==null)S()})}var ol=io();function sl(e,l){if(!(e instanceof Error)||e instanceof r)return!1;let f=["hands_browser_driver_missing","hands_browser_driver_version_mismatch","hands_browser_executable_missing","hands_browser_unsupported_platform","hands_browser_unavailable"].includes(e.message),g=["ENOENT","EACCES","EPERM"].includes(e.code??"");if(!f&&!g)return!1;try{return ur(l),!1}catch(w){return At(w)&&w.code==="ENOENT"}}function il(e){return e.sandbox_provider==="compute"&&!e.cloud_browser&&e[Xe]===Xr}function al(e,l,f){return e===void 0?{}:{dispatch_stages:{version:1,claim_to_entered_ms:Br(e,l),...f===void 0?{}:{worker_prespawned:f}}}}async function Ot(e,l={}){let f=l.logDiagnostic??((le)=>console.warn(le)),g=new Map,w=(le)=>{let he=Date.now();g.set(le,he);try{f(JSON.stringify({event:"sandbox.hands_startup",stage:le,timestampMs:he}))}catch{}};w("entered");let S=e.claimEnvironment;e.claimEnvironment=void 0;let I=l.now??Date.now,W,x=Wd(e.payload,l.now?.(),(le)=>{W=le});if(e.managedPty&&(e.managedPty.version!==1||!e.headless||!e.runtimeDirectory||![void 0,!0].includes(e.managedPty.startupVerified)||!e.deviceIdentity||!e.claimOwner||e.claimOwner.device_id!==e.deviceIdentity.deviceId||!x.environment_binding||!["darwin","linux","win32"].includes(process.platform)))throw new r("pty_unsupported","Bound PTY requires qualified headless Hands with private jobs and environment.");let M=async(le)=>{let he;try{await Promise.race([le,new Promise((xe,Ge)=>{he=setTimeout(()=>Ge(new r("hands_event_delivery_unavailable","Hands event delivery did not settle within its deadline.")),Math.max(1,Math.min(l.eventDeliveryTimeoutMs??5000,5000)))})])}finally{clearTimeout(he)}},G=async(le,he)=>M(e.emitEvent(le,he));if(e.headless&&(x.cloud_browser===!0||e.managedBrowser!==void 0||x[Et]!==void 0||x[Xe]!==void 0&&x[Xe]!==Mr))throw new r("invalid_hands_request","Managed sandbox extensions are unavailable to a headless worker.");let F=ge(),T=x[q]===void 0?null:Rt(F);if(x[q]!==void 0&&(T===null||!e.headless||!me(e.hostExecution,l.hostIdentity?.platform,l.hostIdentity?.euid)))throw new r("hands_model_jobs_egress_unavailable","This worker cannot hold its jobs to the guest egress guard; the Hands did not start.");if(x[Y]!==void 0&&!(e.headless&&me(e.hostExecution,l.hostIdentity?.platform,l.hostIdentity?.euid)))throw new r("hands_confinement_unavailable","Confined Hands need a root Linux worker in host mode.");if(x.cloud_browser&&process.platform!=="linux")throw new r("cloud_browser_target_invalid","Cloud browser is available only on a cloud machine.");let re=`${e.operationId}:${e.attemptId}`,J=x[Xe]===St,z=e.headless||process.platform==="darwin"&&e.managedBrowser===void 0&&!x.cloud_browser&&!x.browser_egress&&(x[Xe]===void 0||x[Xe]===Mr)||il(x),fe=J?x[Et]??"bash":null,ke=fe?Hs(fe):null;if(ke)throw new r(ke,"Persistent Node REPL execution is unavailable; this benchmark profile cannot start.");let be=x[Xe],Re=e.headless===!0&&e.ownComputer!==!0?e.handsSlots??1:void 0,Fe=(l.slot??Ud).acquire(re,{exclusive:Re===1||be!==void 0&&be!==Mr,...Re!==void 0&&Re>1?{limit:Re}:{},...e.headless===!0&&x[Q]!==void 0?{group:x[Q]}:{}});if(!Fe)throw new r("hands_slot_busy",Re!==void 0&&Re>1?`This Reason worker runs at most ${Re} sessions at a time.`:"This Reason Device runs one session at a time.");let Ye=e.headless===!0?Ii(e.runId):null,ye=null,We=null,qe,Te;try{w("browser_resolution");let le=e.headless&&l.browserExecutablePath===void 0?await Mt():null,he=J||x.cloud_browser?null:l.browserExecutablePath===void 0?e.headless?le?.status==="resolved"?le.executablePath:null:await xs(void 0,process.platform,e.managedBrowser):l.browserExecutablePath;if(!J&&!x.cloud_browser&&!z&&!he)throw new r("hands_browser_unavailable","Reason Hands requires Chrome, Edge, Brave, Chromium, or a Playwright Chromium install.");w("path_resolution");let xe;try{xe=await(l.resolvePathEnvironment??ol)()}catch{xe={path:bn(),source:"fallback"}}if(w("workspace_setup"),process.platform==="darwin"){let tr=x[Xe]===Mr&&x.workspace_path!==void 0?co(e.root,x.workspace_worktree?x.workspace_worktree.source_path:x.workspace_path,"folder"):null;for(let Or of new Set([e.root,...tr?[tr]:[]]))await ts(Or)}let Le=x[Xe]===Xr||x[Xe]===St?Bd(process.platform,l.sandboxRuntimeRoot):null,Be=e.headless&&e.runtimeDirectory?e.runtimeDirectory:Le?Le.temporaryRoot:ti();if(ye="private_runtime",e.headless&&e.runtimeDirectory){v(Be);let tr=nr(e.root);if(!je(tr,Be))throw new r("invalid_hands_workspace","Private worker state must not overlap the granted workspace.")}if(e.headless&&e.runtimeDirectory&&(!e.deviceIdentity||!x.environment_binding))throw new r("environment_unavailable","Headless Hands requires a server-bound private environment.");if(ye="runtime_root",Le?.prepareRoot)Ct(Be,{recursive:!0,mode:457}),Ft(Be,457);ye="temporary_directory";let Ee=nr(Id(lr(Be,"reason-hands-session-")));We=Ee,Ft(Ee,Le?.sessionMode??448);let Me=lr(Ee,"hands-config.json"),or=lr(Ee,"hands-ready.json"),sr=yd(),Ir=x.target_fence_id;if(e.workspaceGrant){ye="workspace_grant",w("workspace_grant_wait");let tr=e.workspaceGrant;await new Promise((Or,tt)=>{let pt=()=>tt(new r("cancelled","Reason Hands was cancelled."));if(e.signal.aborted){pt();return}e.signal.addEventListener("abort",pt,{once:!0}),tr.then(Or,tt).finally(()=>e.signal.removeEventListener("abort",pt))})}ye="granted_root";let Ve=nr(e.root);ye="workspace_layout";let ir=x[Xe]===Mr&&x.workspace_path!==void 0&&x.workspace_worktree?await qd(Ve,x.workspace_path,x.workspace_worktree):void 0,{workRoot:ar,repoPath:Er,jobEnvPath:zr,workspacePoolPath:ln,managedWorkspace:Jr,workspace:ut,cloudSessionRoot:Ut}=Qd({grantedRoot:Ve,personalWorkspace:x.personal_workspace===!0,runId:e.runId,workspaceId:x.workspace_id,legacyWorkspaceId:x.legacy_workspace_id,workspaceBase:x[Ce],workspaceLayout:x[Ae],temporaryDirectory:Ee,workspaceMode:x[Xe],applicationSupportPath:l.applicationSupportPath,...x.workspace_path===void 0?{}:{workspacePath:x.workspace_path},...x.workspace_worktree?{workspaceWorktree:x.workspace_worktree}:{},...ir?{workspaceWorktreeStart:ir}:{},...e.deviceIdentity?{deviceId:e.deviceIdentity.deviceId}:{}}),Qr="ara_device_wss";ye="jobs";let Rr=e.headless&&e.runtimeDirectory?pr({runtimeDirectory:e.runtimeDirectory,root:Ve,runId:e.runId}):void 0;qe=Rr?.disposeSocket;let Wr=Rr?$o(Rr):null;if(Wr)try{f(JSON.stringify({event:"hands.journal_owner_retired",run_id:e.runId,reason:Wr.reason,prior_executor_launch_id:Wr.executorLaunchId}))}catch{}if(Rr&&[ar,Er].some((tr)=>!je(tr,Rr.journalDirectory)))throw new r("invalid_hands_workspace","A Session can't work in the folder that holds this worker's settings; start it in a project or repository inside it.");let ft=x.personal_workspace?ar.slice(ar.lastIndexOf("/")+1):void 0;if(ft&&ft!==x.workspace_id)throw new r("invalid_hands_workspace","Personal session identity does not match its Device grant.");ye="browser_socket";let jr=x.cloud_browser?jd(x.sandbox_os,ft):process.platform==="win32"?`\\\\.\\pipe\\reason-repl-${sr}`:lr(Rr?Rr.launchDirectory:Ee,"repl.sock");ye="relay_url";let Fr=oi(new URL(x.relay_url).hostname),et=Qr==="ara_device_wss"&&!Fr?(l.loadProxy??j)()?.url:void 0,Cr;ye="environment_owner";let Tr=e.headless&&e.deviceIdentity&&x.environment_binding?Ws(Ee,{runId:e.runId,...e.deviceIdentity,binding:x.environment_binding,expiresAtMs:Date.parse(x.expires_at),identity:()=>Cr?.()??null}):void 0;ye="job_environment";let Ht=!Tr&&ut.kind==="managed"&&Jr?lr(ar,"job.env"):null;if(Ht)try{dn(Ht,"",{mode:384,flag:"wx"})}catch(tr){if(!(tr instanceof Error&&("code"in tr)&&tr.code==="EEXIST"))throw tr}let un={url:x.relay_url,transport:Qr,...et===void 0?{}:{proxyUrl:et},...e.localGithubConfinement?{localGithubConfinement:!0}:{},...x[Y]&&Tr?{gitCredentialEnvironment:!0}:{},workerVersion:D,protocolVersion:P,workerArtifactSha256:b,workerEntrypoint:R,...process.platform==="win32"?{bashExecutable:se()}:{},targetGeneration:x.target_generation,fenceId:Ir,workRoot:ar,workspaceAliasPath:ar,jobEnvPath:zr,...Tr?{environmentSnapshotPath:Tr.path,...e.hostExecution?{executionEnvironment:mr()}:{},environmentExpectedBinding:{runId:e.runId,...e.deviceIdentity,binding:x.environment_binding}}:Ht?{jobEnvSourcePath:Ht,workspacePoolPath:Dr(ar)}:Jr?{}:{jobEnvSourcePath:ai(ar)},repoPath:Er,replSocketPath:jr,...x.cloud_browser?{browserRunId:e.runId}:{},readyPath:or,launchId:sr,expiresAtMs:Date.parse(x.expires_at),bashTimeoutMs:300000,replTimeoutMs:120000,...Rr?{managedJobs:{journalDirectory:Rr.journalDirectory,scopeId:Rr.scopeId},jobControlSocketPath:Rr.socketPath}:{},...Rr&&F?{jobsUser:{...F,...T!==null?{modelGid:T}:{}}}:{},...e.managedPty&&Rr&&Tr?{managedPty:{version:1,...e.managedPty.startupVerified===!0?{persistent:!0}:{},...process.platform==="darwin"?{shell:gr()}:{}}}:{},...z&&!he?{allowedTools:["bash","read","write","edit"]}:J?{allowedTools:fe==="bash"?["bash"]:["bash","repl"]}:{}};if(Tr||Jr&&!Ht)dn(zr,"",{mode:384});else Zd(ar,zr);ye="config_write",dn(Me,JSON.stringify(un),{mode:384}),ye=null;let rt={session_id:x.session_id,environment_id:x.environment_id,hands_protocol_version:P,hands_worker_version:D,hands_worker_artifact_sha256:b,hands_worker_entrypoint:R,target_generation:x.target_generation,target_fence_id:x.target_fence_id,executor_launch_id:sr},$t=null,uo=!1,fo=!1,po,Ar=null,mo,ho,Kt="failed",go=null,pn=Promise.resolve(),bo=null,wn=async(tr,Or)=>{try{await G(tr,Or)}catch{}};try{w("event_started");let tr,Or=(async()=>{await e.emitEvent("hands.started",{...rt,policy_mode:"full_access",policy_version:1,path_source:xe.source}),tr=Date.now()})();Or.catch(()=>{return}),w("worker_setup");let tt=x.browser_egress?{mode:"enforce",allowedDomains:x.browser_egress.allowed_domains}:{mode:"off"};if(fe&&fe!=="bash")$t=await(l.startNodeRepl??qs)({socketPath:jr,workRoot:ar});else if(!J&&!x.cloud_browser&&he)$t=await(l.startRepl??Ps)({socketPath:jr,browserExecutablePath:he,workspaceRoot:Er,...e.managedBrowser?{managedBrowser:e.managedBrowser}:{},...e.desktopRecording?{recording:e.desktopRecording}:{},networkPolicy:tt,onEgressDenied:(De)=>{let Lr=Ds(De.host);f(JSON.stringify({event:"sandbox.repl_egress_denied",destination_id:Lr,reason:De.reason,run_id:e.runId})),pn=pn.then(()=>G("hands.browser_egress_denied",{destination_id:Lr,reason:De.reason})).catch((Vt)=>{bo??=Vt})}}).catch((De)=>{if(!z||e.signal.aborted||I()>=Date.parse(x.expires_at)||!sl(De,jr))throw De;return Object.assign(un,{allowedTools:["bash","read","write","edit"]}),dn(Me,JSON.stringify(un),{mode:384}),fo=!0,null});let pt=gn({configPath:Me,root:Er,grantedRoot:Ve,workRoot:ar,workspacePoolPath:ln,temporaryDirectory:Ee,path:xe.path,executablePath:l.executablePath,sourceEntrypoint:l.sourceEntrypoint}),yn=Date.now(),kn,wo,Sn=l.takePrespawnedWorker?.(pt)??null;if(po=l.takePrespawnedWorker?Sn!==null:void 0,Ar=Sn??(l.spawnWorker??((De)=>vd(De.command,De.args,De.options)))(pt),!Sn)l.adoptSpawnedWorker?.(Ar);Ar.stderr?.on("data",el(sr,(De)=>{if(De.event==="hands.worker.connecting")kn??=De.timestampMs;else if(De.event==="hands.worker.open")wo??=De.timestampMs;if(f(JSON.stringify({...De,run_id:e.runId})),De.event==="hands.worker.permission_denied"&&typeof De.reason==="string"){let[Lr,Vt]=De.reason.split(":");if(["sandbox_policy","os_permission_unknown"].includes(Lr??"")&&["bash","read","write","edit"].includes(Vt??""))G("permission.denied",{provenance:Lr,operation:Vt}).catch(()=>{return})}}));let yo=!1;Ar.on("error",()=>{yo=!0}),Ar.once("exit",(De,Lr)=>{try{f(JSON.stringify({event:"hands.worker.exited",run_id:e.runId,launchId:sr,exit_code:De,exit_signal:Lr}))}catch{}}),Te=Ar,w("worker_ready_wait");let Nt=await rl({path:or,launchId:sr,fenceId:Ir,targetGeneration:x.target_generation,child:Ar,spawnFailed:()=>yo,signal:e.signal,timeoutMs:l.readyTimeoutMs??Hd,now:I}),ci=Date.now();if(Cr=()=>{if(!Ar||Ar.exitCode!==null||Ar.signalCode!==null)return null;let De=on(or,Nt);return De?{generation:De.targetGeneration,fenceId:De.fenceId}:null},Rr){let De={root:Ve,runId:e.runId,operationId:e.operationId,scopeId:Rr.scopeId,socketPath:Rr.socketPath,generation:Nt.targetGeneration,fenceId:Nt.fenceId,executorLaunchId:sr,expiresAtMs:Date.parse(x.expires_at),readIdentity:Cr,workspace:ut,localGithubConfinement:e.localGithubConfinement===!0};if(Tr)De.environment=Tr;if(e.claimOwner&&e.deviceIdentity&&e.claimOwner.device_id===e.deviceIdentity.deviceId){let Lr=[e.deviceIdentity.apiOrigin,x.relay_url];if(et)Lr.push(et);De.previewAuthority={owner:Object.freeze({...e.claimOwner}),rootId:e.deviceIdentity.rootId,relayOrigin:new URL(x.relay_url).origin,deniedPorts:dr(Lr)}}ho=Ko(De)}if(await new Promise((De)=>{setImmediate(De)}),Ut)br(ar);let Jt;if(S&&Tr){try{let De=Tr.install(S);Jt={snapshot_id:De.snapshot_id,installed_revision:De.installed_revision}}catch{}try{f(JSON.stringify({event:"hands.environment_at_claim",run_id:e.runId,installed:Jt!==void 0}))}catch{}}S=void 0;let vo=!1;if(e.headless){let De=Kd(Er,F);try{f(JSON.stringify({event:"hands.workspace_check",run_id:e.runId,outcome:De}))}catch{}if(De==="unready")throw new r("hands_workspace_unready","This Session's checkout is not a readable, writable directory at its own path, so Reason Hands cannot use it.");vo=De==="checked"}w("event_ready");let ko=M(Or);ko.catch(()=>{return});let So=Date.now();uo=!0,await G("hands.ready",{...rt,expiry_diagnostic:W,startup_stages:{version:1,browser_resolution_ms:Br(g.get("browser_resolution"),g.get("path_resolution")),path_resolution_ms:Br(g.get("path_resolution"),g.get("workspace_setup")),workspace_setup_ms:Br(g.get("workspace_setup"),g.get("event_started")),repl_setup_ms:Br(g.get("worker_setup"),yn),worker_boot_ms:Br(yn,kn),worker_dial_ms:Br(kn,wo),worker_ready_ms:Br(yn,ci),started_event_ms:Br(g.get("event_started"),tr),started_join_wait_ms:Br(g.get("event_ready"),So),total_ms:Br(g.get("entered"),So)},...al(e.claimedAtMs,g.get("entered"),po),...e.managedPty?.startupVerified===!0?{managed_pty:{version:1,execution_mode:"host",descendant_cleanup_verified:!0}}:{},policy_mode:"full_access",policy_version:1,path_source:xe.source,connection_generation:Nt.generation,...Jt?{environment_installed:Jt}:{},...vo?{workspace_checked:!0}:{},...z&&!$t?{browser_state:"unavailable",browser_reason_code:fo?"setup_failed":"not_resolved"}:{viewport_width:1440,viewport_height:900}}),await ko,w("ready"),mo=Gs({path:or,initial:Nt,signal:e.signal,isAlive:()=>Ar!==null&&Ar.exitCode===null&&Ar.signalCode===null&&I()<Date.parse(x.expires_at),publish:(De,Lr)=>e.emitEvent("hands.reconnected",{...rt,target_generation:De.targetGeneration,target_fence_id:De.fenceId,connection_generation:De.generation},Lr),failed:()=>f(JSON.stringify({event:"hands.worker.generation_proof_failed",run_id:e.runId,executor_launch_id:sr}))});let Eo=await nl({child:Ar,signal:e.signal,expiresAt:Date.parse(x.expires_at),now:I});if(Eo==="cancelled"){let De=e.signal.reason instanceof r?e.signal.reason.code:"cancelled";throw Kt=De,new r(De,"Reason Hands was cancelled.")}if(Eo==="exited")throw new r("hands_worker_exited","Reason Hands exited unexpectedly.");return Kt="expired",{...rt,policy_mode:"full_access",policy_version:1,ended:"expired"}}catch(tr){go=tr;let Or=tr instanceof r?tr.code:"hands_failed",tt=Or==="cancelled"||["run_finished","run_cancelled","driver_handoff","driver_stopped"].includes(Or);if(Kt=tt?Or:"failed",!tt)await wn("hands.failed",{...rt,reason_code:Or});throw tr}finally{mo?.stop(),ho?.();let tr=Ar?await tl(Ar,l.stopTimeoutMs??Nd):null,Or=!1;await e.desktopRecording?.close();try{await $t?.stop()}catch{Or=!0}if(await pn,(tr==="stopped"||tr==="already_exited"&&!uo)&&!Or)await wn("hands.stopped",{...rt,reason_code:Kt});else if(tr!==null||Or){if(await wn("hands.failed",{...rt,reason_code:tr==="forced"?"hands_stop_forced":"hands_stop_unconfirmed"}),go===null||Or)throw new r("hands_stop_unconfirmed","Reason Hands resource cleanup could not be proven.")}if(bo!==null)throw new r("hands_egress_audit_failed","Reason Hands could not persist a browser egress denial receipt.")}}catch(le){let he=Is(ye,le);if(he)try{f(JSON.stringify({event:"sandbox.hands_workspace_failed",...he}))}catch{}throw le}finally{try{if(!Te||Te.exitCode!==null||Te.signalCode!==null)qe?.();if(We!==null&&(!Te||Te.exitCode!==null||Te.signalCode!==null))Ad(We,{recursive:!0,force:!0})}finally{Ye?.(),Fe()}}}
|
|
452
|
+
export{B,m,je,te,dr,Hi,pr,zi,it,qi,Wi,Vi,Gi,hr,Ki,Ji,fr,Zi,mr,gr,hn,fn,_r,Xi,Ue,mn,yr,me,ge,Rt,wr,br,vr,gn,_n,ot,Ot};
|