@reason-machines/cli-linux-arm64-musl 0.2.313 → 0.2.314

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/{connect-cli-dqghjqd4.js → connect-cli-edkrs4p6.js} +1 -1
  3. package/bin/vm-hands/{local-automation-eb60mapm.js → local-automation-3tg97fb8.js} +1 -1
  4. package/bin/vm-hands/{local-capabilities-6rr3bahs.js → local-capabilities-rb17efqw.js} +1 -1
  5. package/bin/vm-hands/{local-display-session-vbyhrk1t.js → local-display-session-4jnfvpv1.js} +1 -1
  6. package/bin/vm-hands/{permissions-8e309cm8.js → permissions-5kqh2dqz.js} +1 -1
  7. package/bin/vm-hands/{status-nac4r75q.js → status-gp9kxbq1.js} +2 -2
  8. package/bin/vm-hands/{version-c4jz97dy.js → version-jp149s8j.js} +1 -1
  9. package/bin/vm-hands/{vm-hands-entry-lite-pct56639.js → vm-hands-entry-lite-3tp9yvsn.js} +1 -1
  10. package/bin/vm-hands/{vm-hands-entry-lite-nqgg6v5n.js → vm-hands-entry-lite-abfcsza2.js} +39 -39
  11. package/bin/vm-hands/{vm-hands-entry-lite-erxpqz9e.js → vm-hands-entry-lite-fws38v57.js} +1 -1
  12. package/bin/vm-hands/{vm-hands-entry-lite-bsfm2m38.js → vm-hands-entry-lite-hmff1sqa.js} +1 -1
  13. package/bin/vm-hands/{vm-hands-entry-lite-sg20hwxb.js → vm-hands-entry-lite-hzkc742v.js} +1 -1
  14. package/bin/vm-hands/{vm-hands-entry-lite-ncty87q3.js → vm-hands-entry-lite-ksd4969g.js} +1 -1
  15. package/bin/vm-hands/{vm-hands-entry-lite-qdcp5vf4.js → vm-hands-entry-lite-njt12v46.js} +1 -1
  16. package/bin/vm-hands/{vm-hands-entry-lite-8gr872ee.js → vm-hands-entry-lite-qssnr12b.js} +2 -2
  17. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  18. package/bin/vm-hands/{vm-hands-executor-fwq7gd0d.js → vm-hands-executor-rzz9q5jj.js} +1 -1
  19. package/bin/vm-hands/{vm-hands-op-runner-q0z9bqyk.js → vm-hands-op-runner-mwmgvdh0.js} +1 -1
  20. package/bin/vm-hands/{vm-hands-runtime-0h74s3jy.js → vm-hands-runtime-rkpxmsd0.js} +2 -2
  21. package/package.json +1 -1
@@ -1,31 +1,31 @@
1
1
  // @bun
2
- import{$a as n6,Ea as u6,Ga as w4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as L4,wa as v6,xa as p6}from"./vm-hands-entry-lite-sg20hwxb.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-rrk5g62b.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-ya1a2eep.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-0ergg2ky.js";import{Bc as r1,Ec as H7,Nc as D7}from"./vm-hands-entry-lite-ncty87q3.js";import{$c as d,$d as g8,Ad as w6,Cd as O6,Dd as j6,Ed as I6,Fd as A6,Gd as T6,Ld as D8,Md as M8,Nd as L8,Oc as L1,Od as w8,Pc as Q2,Pd as O8,Qc as e5,Qd as j8,Rc as I3,Sc as r3,Sd as I8,Tc as a3,Td as A8,Uc as M0,Ud as T8,Vd as _8,Wd as R8,Xd as P8,Yc as N0,Yd as z8,Zd as q8,_d as E8,ad as E1,dd as H8,fd as g1,hd as $6,id as J6,jd as Z6,kd as Q6,ld as K6,md as B6,nd as V6,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as L6}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as V}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ae as l1,be as W7,ce as Y7,de as F7,ee as N7,fe as C7,le as p5,pe as Q5,qe as T5,we as M7,ze as K5}from"./vm-hands-entry-lite-bsfm2m38.js";import{Ze as j4,ef as c6}from"./vm-hands-entry-lite-pf1ft65e.js";import{jf as M3,wf as g6}from"./vm-hands-entry-lite-q2pb31vh.js";import{Bg as Z7,Cg as Q7,Dg as K7,Eg as B7,Gg as V7,Hg as G7,Jg as U7,Kg as X7}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Yg as n1}from"./vm-hands-entry-lite-7k65s010.js";import{$g as k6,_g as j1,ah as H4,bh as D4}from"./vm-hands-entry-lite-em388nee.js";import{dh as D3,fh as $1,lh as K8,mh as J4}from"./vm-hands-entry-lite-yp315y25.js";import{Kh as H}from"./vm-hands-entry-lite-xsq25kmd.js";import{Oh as a4}from"./vm-hands-entry-lite-hf0mk7vd.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=K.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as s from"path";import{homedir as a7}from"os";function $2($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function J2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=r7($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,s,$,J),home:a7};function A($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");A(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function o3($,J,Z=o7){let Q=L1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)n3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=$2(z,s,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+s.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:s.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},F=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{r3(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>Q2)A("local_device_gh_response_too_large");let y={};for(let r of k[2].split(/\r?\n/)){let a=r.indexOf(":"),D0=r.slice(0,a).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=r.slice(a+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await F(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await F(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+s.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+i3+")")(),I=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+s.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let r=s.join(N,".ara-local-gh-tmp");if(z.mkdirSync(r,{recursive:!0,mode:448}),z.lstatSync(r).isSymbolicLink()||z.realpathSync(r)!==r)A("local_device_gh_workspace_unavailable");J.assertCurrent();let a=await Z.command(...I(M(N,r),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:N,TMPDIR:r,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),a.error||a.status!==0)A("local_device_gh_collection_failed");return a.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),E=async(L,T)=>{let P=s.join(L,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...I(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(S,["cat-file","--batch"],[...new Set(L)].join(`
2
+ import{$a as a6,Ea as l6,Ga as O4,Ha as j4,Ma as c6,Na as n6,Xa as A4,ab as i6,bb as k4,cb as f4,eb as o6,ga as X4,gb as V8,hb as y0,ia as Y2,ib as m0,ja as W4,jb as n1,ka as Y4,la as F4,ma as f6,mb as t6,na as x6,oa as L4,pa as y6,pb as G8,qa as T3,qb as T4,ra as h6,sa as m6,sb as e6,ta as v6,ua as p6,va as w4,wa as u6,xa as d6}from"./vm-hands-entry-lite-hzkc742v.js";import{Ab as n0,Bb as r0,Ib as P0,tb as o3,ub as g6,vb as S6}from"./vm-hands-entry-lite-rrk5g62b.js";import{Jb as $7,Mb as J7,Ob as Z7,Pb as Q7}from"./vm-hands-entry-lite-ya1a2eep.js";import{Ub as s6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as P6,Wb as z6,Xb as q6,Yb as E6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as t1,ac as e1,bc as k3,dc as f3,fc as b3,gc as x3,kc as y3}from"./vm-hands-entry-lite-0ergg2ky.js";import{Bc as a1,Ec as M7,Nc as L7}from"./vm-hands-entry-lite-ksd4969g.js";import{$c as d,$d as k8,Ad as j6,Cd as I6,Dd as A6,Ed as T6,Fd as _6,Gd as R6,Ld as L8,Md as w8,Nd as O8,Oc as L1,Od as j8,Pc as K2,Pd as I8,Qc as J6,Qd as A8,Rc as A3,Sc as a3,Sd as T8,Tc as i3,Td as _8,Uc as M0,Ud as R8,Vd as P8,Wd as z8,Xd as q8,Yc as N0,Yd as E8,Zd as g8,_d as S8,ad as E1,dd as M8,fd as g1,hd as Z6,id as Q6,jd as K6,kd as B6,ld as V6,md as G6,nd as U6,od as X6,pd as W6,qd as Y6,rd as F6,sd as N6,td as C6,ud as H6,vd as D6,wd as M6,xd as L6,yd as w6,zd as O6}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as V}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ae as s1,be as F7,ce as N7,de as C7,ee as H7,fe as D7,le as d5,pe as B5,qe as R5,we as w7,ze as V5}from"./vm-hands-entry-lite-hmff1sqa.js";import{Ze as I4,ef as r6}from"./vm-hands-entry-lite-pf1ft65e.js";import{jf as L3,wf as k6}from"./vm-hands-entry-lite-q2pb31vh.js";import{Bg as K7,Cg as B7,Dg as V7,Eg as G7,Gg as U7,Hg as X7,Jg as W7,Kg as Y7}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Yg as r1}from"./vm-hands-entry-lite-7k65s010.js";import{$g as b6,_g as j1,ah as D4,bh as M4}from"./vm-hands-entry-lite-em388nee.js";import{dh as M3,fh as $1,lh as B8,mh as Z4}from"./vm-hands-entry-lite-yp315y25.js";import{Kh as H}from"./vm-hands-entry-lite-xsq25kmd.js";import{Oh as i4}from"./vm-hands-entry-lite-hf0mk7vd.js";import{request as p7}from"http";import{request as u7}from"https";async function d7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?u7:p7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:f3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function l7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function s7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let N=K[B-1];Y+=Z.copy(W,Y,0,B-N),B=N}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function h3($){$.signal.throwIfAborted();let J=x3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=y3.parse(await $.credential($.signal));if(!b3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=l7(Q.apiKey),X=s7(Q.apiKey,Y),N=async(F,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let j=()=>{$.signal.removeEventListener("abort",j),M($.signal.reason)};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted){j();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(F,D)}).then(()=>{$.signal.removeEventListener("abort",j),w()},(O)=>{$.signal.removeEventListener("abort",j),M(O)})})},C=async(F)=>{if(G+=F.length,G>e1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<F.length;D+=t1){if(W>=k3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await N(`custom_endpoint.chunk.${W++}`,{eof:!1,data:F.subarray(D,D+t1).toString("base64")})}};try{let F=await d7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=F.response,B=F.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let j=K.headers[M];if(typeof j==="string")w[M]=j.replaceAll(Q.apiKey,Y).slice(0,4096)}await N("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let j=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=j.length,U>e1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(j))}return await C(X(Buffer.alloc(0),!0)),await N(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(F){if($.signal.throwIfAborted(),F instanceof H)throw F;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as m3}from"path";function c7($,J){return $===m3(J,".ara","workspace")||$===m3(J,".reason","workspace")}function v3($,J){let Z=$.filter((Q)=>c7(Q.path,J));return Z.length===1?Z[0].path:null}var n7=/^[a-f0-9]{64}$/;var $2=32,r7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!r7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>$2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!n7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as i7}from"child_process";import*as z from"fs";import*as s from"path";import{homedir as o7}from"os";function J2($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function p3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var u3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function Z2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function d3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function l3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=d3(J).filter((G)=>!K.has(G));for(let G of $){let U=Z2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,N)=>X.offset-N.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((N)=>Z.secretNames?.(N.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:p3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of u3){let N=l3(X,W).find((C)=>!K.has(C[0]));if(N){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:p3(W,N.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function s3($,J=[]){let Z=d3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of u3)for(let G of l3(B,K))Q.add(G[0])}return[...Q]}function a7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function c3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+a7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,n3=536870912,Q2=/^[a-f0-9]{40}$/,t7=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=i7($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(F)=>{if(U??=Error(F),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),N=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(F)=>{if(W)return;W=!0,clearTimeout(N),Z.signal?.removeEventListener("abort",X),Q({status:F,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,F])}),K.stderr.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,F])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(F)=>C(F)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),e7={command:t7,gh:($,J)=>J2(z,s,$,J),home:o7};function A($){throw Error($)}var $9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),J9=($)=>JSON.stringify($,(J,Z)=>$9.has(J)?void 0:Z);function r3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");A(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function t3($,J,Z=e7){let Q=L1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=M1([{path:"github-operation",content:J9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)r3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=J2(z,s,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+s.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:s.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},N=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{a3(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>K2)A("local_device_gh_response_too_large");let y={};for(let r of k[2].split(/\r?\n/)){let a=r.indexOf(":"),D0=r.slice(0,a).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=r.slice(a+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await N(["api","graphql","--hostname","github.com","-f",`query=${i3}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>K2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await N(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await N(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await N(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let F=z.realpathSync(J.repoPath);if(F!==K&&!F.startsWith(K+s.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+o3+")")(),j=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+s.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let r=s.join(F,".ara-local-gh-tmp");if(z.mkdirSync(r,{recursive:!0,mode:448}),z.lstatSync(r).isSymbolicLink()||z.realpathSync(r)!==r)A("local_device_gh_workspace_unavailable");J.assertCurrent();let a=await Z.command(...j(M(F,r),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:F,TMPDIR:r,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),a.error||a.status!==0)A("local_device_gh_collection_failed");return a.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),E=async(L,T)=>{let P=s.join(L,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...j(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(S,["cat-file","--batch"],[...new Set(L)].join(`
3
3
  `)+`
4
- `,T0*8);for(let k=0;k<P.length;){let x=P.indexOf(10,k),[y,r,a]=P.subarray(k,x).toString("utf8").split(" ");if(x<0||!y||r!=="blob"||!/^[0-9]+$/.test(a??""))A("local_device_gh_object_invalid");T.set(y,P.subarray(x+1,x+1+Number(a)).toString("utf8")),k=x+1+Number(a)+1}return T},j=async(L,T,P)=>{let k=s.join(N,".ara-local-gh-tmp"),x=M(N,k)+`
5
- (allow file-read* file-write* (subpath ${JSON.stringify(N)}))
4
+ `,T0*8);for(let k=0;k<P.length;){let x=P.indexOf(10,k),[y,r,a]=P.subarray(k,x).toString("utf8").split(" ");if(x<0||!y||r!=="blob"||!/^[0-9]+$/.test(a??""))A("local_device_gh_object_invalid");T.set(y,P.subarray(x+1,x+1+Number(a)).toString("utf8")),k=x+1+Number(a)+1}return T},I=async(L,T,P)=>{let k=s.join(F,".ara-local-gh-tmp"),x=M(F,k)+`
5
+ (allow file-read* file-write* (subpath ${JSON.stringify(F)}))
6
6
  (allow file-read* (subpath ${JSON.stringify(L)}))
7
- (allow file-read-metadata (path-ancestors ${JSON.stringify(L)}))`,y=async(a,D0)=>{J.assertCurrent();let d0=await Z.command(...I(x,a,D0),{cwd:N,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:N,TMPDIR:k,GIT_INDEX_FILE:s.join(N,".git","index"),OPENSSL_CONF:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),d0.error||d0.status!==0)A("local_device_gh_materialization_failed")},r=["--git-dir="+L,"--work-tree="+N,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await y(U,[...r,"read-tree",T]),await y(U,[...r,"checkout-index","--all","--index"]),await O(N,["update-ref","refs/heads/"+P,T]),await O(N,["symbolic-ref","HEAD","refs/heads/"+P])},q=await C(`/repos/${Q.repoFullName}`);if(q.status!==200)A("local_device_gh_repository_unavailable");let _=JSON.parse(q.body);if(_.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||_.default_branch!==Q.defaultBranch||Q.kind==="publish"&&_.permissions?.push!==!0)A("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)A("local_device_gh_default_branch");let S=z.mkdtempSync(s.join(W,"github-publication-"));z.chmodSync(S,448);try{if(await O(S,["init","--bare","--template="]),Q.kind==="prepare"){if(await O(S,["fetch","--depth=1","--no-tags","--no-recurse-submodules",D,Q.baseSha]),await R(S,["rev-parse","FETCH_HEAD"])!==Q.baseSha)A("local_device_gh_base_changed");let p=s.join(N,".git"),K0=!1;if(z.existsSync(p)){if(!z.lstatSync(p).isDirectory()||z.lstatSync(p).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((i)=>z.existsSync(s.join(p,i))))A("local_device_gh_repository_layout_invalid");let e=await O(N,["rev-parse","--verify","-q","HEAD"]).then((i)=>i.toString("utf8").trim(),()=>null),B0=await O(N,["config","--local","--get","remote.origin.url"]).then((i)=>i.toString("utf8").trim(),()=>"");if(e!==null||B0){if(e!==Q.baseSha||await R(N,["branch","--show-current"])!==Q.branch)A("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}K0=!0}let $0=z.readdirSync(N).filter((e)=>!(K0&&e===".git")),U0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if($0.some((e)=>!U0.includes(e))||$0.some((e)=>{let B0=s.join(N,e);return!z.lstatSync(B0).isDirectory()||z.lstatSync(B0).isSymbolicLink()||z.readdirSync(B0).length>0}))A("local_device_gh_checkout_not_empty");if(!K0)await O(N,["init","--template="]);let F0=await O(S,["pack-objects","--stdout","--revs"],Q.baseSha+`
8
- `,c3);return await E(N,Q.baseSha),await O(N,["index-pack","--strict","--stdin"],F0,65536),await O(N,["remote","add","origin",D]),await j(S,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let L=s.join(N,".git");if(!z.lstatSync(L).isDirectory()||z.lstatSync(L).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((p)=>z.existsSync(s.join(L,p))))A("local_device_gh_repository_layout_invalid");if(await R(N,["branch","--show-current"])!==Q.branch)A("local_device_gh_branch_changed");let T=await R(N,["rev-parse","--verify","HEAD"]);if(!Z2.test(T))A("local_device_gh_head_invalid");let P=await C(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(P.status!==200||JSON.parse(P.body).sha!==Q.baseSha)A("local_device_gh_base_unverified");let k=await C(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?k.status!==404:k.status!==200||JSON.parse(k.body).object?.sha!==Q.remoteHeadSha)A("local_device_gh_remote_changed");let x=[...(await R(N,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha])).split(`
9
- `),...(await R(N,["rev-list","--objects","--no-object-names","--no-walk",Q.baseSha])).split(`
10
- `)].filter(Boolean);if(x.some((p)=>!Z2.test(p)))A("local_device_gh_object_invalid");let y=await O(N,["pack-objects","--stdout"],[...new Set(x)].join(`
7
+ (allow file-read-metadata (path-ancestors ${JSON.stringify(L)}))`,y=async(a,D0)=>{J.assertCurrent();let d0=await Z.command(...j(x,a,D0),{cwd:F,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:F,TMPDIR:k,GIT_INDEX_FILE:s.join(F,".git","index"),OPENSSL_CONF:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),d0.error||d0.status!==0)A("local_device_gh_materialization_failed")},r=["--git-dir="+L,"--work-tree="+F,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await y(U,[...r,"read-tree",T]),await y(U,[...r,"checkout-index","--all","--index"]),await O(F,["update-ref","refs/heads/"+P,T]),await O(F,["symbolic-ref","HEAD","refs/heads/"+P])},q=await C(`/repos/${Q.repoFullName}`);if(q.status!==200)A("local_device_gh_repository_unavailable");let _=JSON.parse(q.body);if(_.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||_.default_branch!==Q.defaultBranch||Q.kind==="publish"&&_.permissions?.push!==!0)A("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)A("local_device_gh_default_branch");let S=z.mkdtempSync(s.join(W,"github-publication-"));z.chmodSync(S,448);try{if(await O(S,["init","--bare","--template="]),Q.kind==="prepare"){if(await O(S,["fetch","--depth=1","--no-tags","--no-recurse-submodules",D,Q.baseSha]),await R(S,["rev-parse","FETCH_HEAD"])!==Q.baseSha)A("local_device_gh_base_changed");let p=s.join(F,".git"),K0=!1;if(z.existsSync(p)){if(!z.lstatSync(p).isDirectory()||z.lstatSync(p).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((i)=>z.existsSync(s.join(p,i))))A("local_device_gh_repository_layout_invalid");let e=await O(F,["rev-parse","--verify","-q","HEAD"]).then((i)=>i.toString("utf8").trim(),()=>null),B0=await O(F,["config","--local","--get","remote.origin.url"]).then((i)=>i.toString("utf8").trim(),()=>"");if(e!==null||B0){if(e!==Q.baseSha||await R(F,["branch","--show-current"])!==Q.branch)A("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}K0=!0}let $0=z.readdirSync(F).filter((e)=>!(K0&&e===".git")),U0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if($0.some((e)=>!U0.includes(e))||$0.some((e)=>{let B0=s.join(F,e);return!z.lstatSync(B0).isDirectory()||z.lstatSync(B0).isSymbolicLink()||z.readdirSync(B0).length>0}))A("local_device_gh_checkout_not_empty");if(!K0)await O(F,["init","--template="]);let F0=await O(S,["pack-objects","--stdout","--revs"],Q.baseSha+`
8
+ `,n3);return await E(F,Q.baseSha),await O(F,["index-pack","--strict","--stdin"],F0,65536),await O(F,["remote","add","origin",D]),await I(S,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let L=s.join(F,".git");if(!z.lstatSync(L).isDirectory()||z.lstatSync(L).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((p)=>z.existsSync(s.join(L,p))))A("local_device_gh_repository_layout_invalid");if(await R(F,["branch","--show-current"])!==Q.branch)A("local_device_gh_branch_changed");let T=await R(F,["rev-parse","--verify","HEAD"]);if(!Q2.test(T))A("local_device_gh_head_invalid");let P=await C(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(P.status!==200||JSON.parse(P.body).sha!==Q.baseSha)A("local_device_gh_base_unverified");let k=await C(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?k.status!==404:k.status!==200||JSON.parse(k.body).object?.sha!==Q.remoteHeadSha)A("local_device_gh_remote_changed");let x=[...(await R(F,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha])).split(`
9
+ `),...(await R(F,["rev-list","--objects","--no-object-names","--no-walk",Q.baseSha])).split(`
10
+ `)].filter(Boolean);if(x.some((p)=>!Q2.test(p)))A("local_device_gh_object_invalid");let y=await O(F,["pack-objects","--stdout"],[...new Set(x)].join(`
11
11
  `)+`
12
- `,c3);if(z.writeFileSync(s.join(S,"shallow"),Q.baseSha+`
12
+ `,n3);if(z.writeFileSync(s.join(S,"shallow"),Q.baseSha+`
13
13
  `,{flag:"wx",mode:384}),await O(S,["index-pack","--strict","--stdin"],y,65536),await O(S,["merge-base","--is-ancestor",Q.baseSha,T]),Q.remoteHeadSha)await O(S,["merge-base","--is-ancestor",Q.remoteHeadSha,T]);let r=(await R(S,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
14
- `).filter(Boolean);if(r.length>5000)A("local_device_gh_collection_too_large");let a=[],D0=0;for(let p of r){if(!Z2.test(p))A("local_device_gh_object_invalid");let K0=await R(S,["cat-file","-t",p]);if(!["blob","commit","tree"].includes(K0))A("local_device_gh_object_invalid");let $0=await O(S,["cat-file",K0,p]);if(D0+=$0.length,D0>T0)A("local_device_gh_collection_too_large");if(K0==="tree"){let U0=0;while(U0<$0.length){let F0=$0.indexOf(32,U0),e=$0.indexOf(0,F0+1);if(F0<U0||e<=F0||e+21>$0.length)A("local_device_gh_object_invalid");let B0=$0.subarray(F0+1,e).toString("utf8");if(B0.includes("/")||!J2(B0).valid)A("local_device_gh_object_invalid");U0=e+21}}a.push({path:`object-${p}`,content:$0.toString("utf8")})}let d0=J.secretNames?{secretNames:J.secretNames}:{},l0=M1(a,J.forbiddenSecretValues,d0),E3=new Map;if(!l0.clean)try{let p=(await O(S,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,T])).toString("utf8").split("\x00"),K0=[],$0=[];for(let i=0;i+1<p.length;i+=2){let[,y7,h7,i1,C1]=p[i].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!i1||!C1)continue;if(y7!=="160000"&&!/^0+$/.test(i1))K0.push(i1);if(h7!=="160000"&&!/^0+$/.test(C1))$0.push(C1),E3.set(`object-${C1}`,p[i+1])}let U0=await v([...K0,...$0]),F0=new Set(l0.violations.map((i)=>i.path)),e=l3(a.filter((i)=>F0.has(i.path)),J.forbiddenSecretValues),B0=s3(e,$0.map((i)=>U0.get(i)??""),K0.map((i)=>U0.get(i)??""));if(B0.size>0)l0=M1(a,J.forbiddenSecretValues,{...d0,published:B0})}catch{}if(!l0.clean)n3(l0.violations,(p)=>E3.get(p)??`an object in the pushed history (${p})`,"Remove it from the files and commit again; a commit or message in the pushed history that holds it must be amended before this branch can be pushed.");await O(S,["push","--no-recurse-submodules",D,`${T}:refs/heads/${Q.branch}`]);let g3=await C(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(g3.status!==200||JSON.parse(g3.body).object?.sha!==T)A("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:T,scannedObjectCount:a.length}}finally{z.rmSync(S,{recursive:!0,force:!0})}}var _0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),K2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},$9=V.object({...K2,version:V.literal(2),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!1),source_bound:V.literal(!1),profiles:V.array(_0.shape.profile).min(1).max(16),extension_instance_ids:V.array(_0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),J9=V.object({...K2,version:V.literal(3),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!0),source_bound:V.literal(!1),max_seconds:V.literal(15),profiles:V.array(_0.shape.profile).min(1).max(16),extension_instance_ids:V.array(_0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),B2=V.union([$9,J9]),lQ=V.union([V.object({...K2,version:V.literal(1),development_only:V.literal(!0),profile:_0.shape.profile,extension_instance_id:_0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),B2]);import{randomUUID as F2}from"crypto";import{spawn as H9}from"child_process";import{existsSync as N2,lstatSync as T4,mkdirSync as D9,readFileSync as M9,realpathSync as w1,rmSync as L9,writeFileSync as w9}from"fs";import{dirname as _4,join as X0,relative as O9,sep as j9}from"path";var Z9=["process.run.v1","process.full.v1"],Q9=600000,K9=1800000,B9=20000,t3="process.cancel.v1",e3=V.object({action:V.literal("start"),request_id:V.string().uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),cwd:V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")&&!$.startsWith("/")&&!$.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:V.enum(["host","confined"]).default("host"),timeout_ms:V.number().int().min(1000).max(K9).default(Q9).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),V2={device_id:V.string().uuid(),root_id:V.string().uuid()},V9=V.discriminatedUnion("action",[e3.extend(V2),V.object({...V2,action:V.literal("inspect"),process_id:V.string().uuid(),after:V.number().int().min(0).default(0),wait_ms:V.number().int().min(0).max(B9).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),V.object({...V2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),nQ=V.toJSONSchema(V9,{io:"input"}),rQ=e3.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),s0=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:V.number().int().nullable(),first_cursor:V.number().int().min(0),next_cursor:V.number().int().min(0),truncated:V.boolean(),observed_at:V.iso.datetime(),output:V.array(V.object({cursor:V.number().int().min(1),stream:V.enum(["stdout","stderr"]),text:V.string().max(32768)}).strict()).max(128)}).strict().refine(($)=>{if(Buffer.byteLength(JSON.stringify($))>1e5||$.next_cursor<$.first_cursor-1)return!1;if(($.state==="starting"||$.state==="running"||$.state==="uncertain")&&$.exit_code!==null)return!1;if($.state==="exited"&&($.exit_code===null||$.exit_code<0||$.exit_code>255))return!1;if($.state==="cancelled"&&$.exit_code!==130||$.state==="expired"&&$.exit_code!==124)return!1;let Z=$.first_cursor-1;for(let Q of $.output){if(Q.cursor<=Z||Q.cursor>$.next_cursor)return!1;Z=Q.cursor}return!0});function $4($){return Z9.includes($)}var aQ=V.object({operation_constraints:V.record(V.string(),V.unknown())}),iQ=V.object({ready:V.literal(!0),version:V.literal(1),execution_mode:V.enum(["host","confined"]),max_timeout_ms:V.number().int().min(1000).optional()});var G9=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["queued","cancelled_before_start","not_started"]),exit_code:V.null(),output:V.array(V.never()).length(0),first_cursor:V.literal(0),next_cursor:V.literal(0),truncated:V.literal(!1),cancellation_requested:V.literal(!1),reason_code:V.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),U9=V.object({...s0.shape,state:V.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:V.iso.datetime().optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:V.boolean(),reason_code:V.string().nullable().optional(),execution_authority:V.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:V.object({cause:V.literal("brain_generation_changed"),terminal_confirmed:V.boolean(),next_step:V.enum(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:s0.shape.state.or(V.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),oQ=V.toJSONSchema(U9),tQ=V.union([s0,G9.refine(($)=>$.state==="cancelled_before_start")]),G2=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["exited","cancelled","expired"]),exit_code:V.number().int().min(0).max(255),observed_at:V.iso.datetime()}).strict().refine(($)=>($.state!=="cancelled"||$.exit_code===130)&&($.state!=="expired"||$.exit_code===124)),X9=V.object({process_terminal_observation:G2}).strict();function eQ($,J){let Z=X9.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var Z4="preview.serve.v1",Q4=43200000;var QK=3,K4="preview.open.v1",B4=1,U2="gid_proxy_v1",V4="egress",X2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,W9=V.object({version:V.literal(U2),allowed_domains:V.array(V.string().max(260).regex(X2)).max(1024)}).strict(),Y9=V.custom(($)=>J4($)!==null,"invalid workspace"),F9=V.object({version:V.literal(1),request_id:V.uuid(),session_id:V.uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),port:V.number().int().min(1024).max(65535),workspace:Y9,egress:W9.optional()}).strict(),G4=F9.extend({expires_at:V.iso.datetime()}).strict();var N9=4,C9=5000;function Y2($,J,Z){let Q=null;try{Q=W2($)}catch{}X4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function F4($){let J=new Map;return{open(Z){let Q=(X)=>Y2(Z,$.claim.operation_id,X),K;try{K=W2(Z)}catch{return Q("binding_invalid")}let{binding:B,deviceRelayUrl:G}=K,U=$.claim.owner;if(!U||B.organizationId!==U.organization_id||B.userId!==U.user_id||B.deviceId!==U.device_id||B.rootId!==$.claim.root_id||B.jobId!==$.claim.operation_id||B.fenceId!==$.claim.operation_id||B.generation!==B4||B.expiresAtMs>Math.min(Date.now()+U4.lifetimeMs+C9,$.expiresAtMs))return Q("binding_mismatch");if(B.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(B.port)?.abort(),J.delete(B.port),J.size>=N9)return Q("preview_capacity");let W=new AbortController;J.set(B.port,W);let Y=Y4({binding:B,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(W.signal.aborted)return null;let X=await $.inspect();return X?{binding:B,executorLaunchId:$.executorLaunchId,job:X}:null}});W4({binding:B,deviceRelayUrl:G,port:Y,signal:W.signal}).then((X)=>X.closed,(X)=>{let F=X instanceof Error?X.message:"preview_failed";if(F!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:B.jobId,port:B.port,reason_code:F})}
15
- `)}).finally(()=>{if(J.get(B.port)===W)J.delete(B.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class c0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var R4=256,O1=new Map,P4="preview.serve.v1",R0=new Map;function z4($){let J=R0.get($.operation_id);if(J){if(J.claim!==$)throw V0("process_authority_lost");return J}if(R0.size>=R4)throw V0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return R0.set($.operation_id,Z),Z}function N4($){return{version:1,process_id:$,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var C4=($)=>new Promise((J)=>setTimeout(J,$)),V0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function I9($=j1(),J=A9()){let Z=_4(j4({},$)),Q=O9(H4($),Z),[K,...B]=Q.split(j9);return{directory:X0(J,Q,"processes"),previous:[X0(Z,"processes"),...K==="reason"?[X0(J,"ara",...B,"processes")]:[]]}}function A9(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=D4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function I1($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw V0("process_authority_lost");let J=z4($.claim);if(J.executing)throw V0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",N4($.claim.operation_id);J.phase="starting";let Z=$.journals??I9();D9(Z.directory,{recursive:!0,mode:448});let Q=M4({runtimeDirectory:w1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((j)=>N2(j)).map((j)=>w1(j)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:R4});try{for(let j of[$.root,$.cwd])if(!I4(w1(j),Q.journalDirectory))throw new H("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(j){throw Q.disposeSocket(),j}let K=T4(Q.journalDirectory),B=$.claim.capability===P4,G=()=>O1.set($.claim.operation_id,{path:Q.journalDirectory,ino:K.ino,dev:K.dev,anyCompletion:B}),U=_4(Q.socketPath),W=X0(U,"config.json"),Y={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:n0,protocolVersion:2,workerArtifactSha256:P0,workerEntrypoint:r0,targetGeneration:1,fenceId:F2(),workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:X0(U,"unused.env"),replSocketPath:X0(U,"unused.sock"),readyPath:X0(U,"ready.json"),directTerminalReceiptPath:X0(U,"terminal.json"),launchId:F2(),expiresAtMs:$.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Q.journalDirectory,scopeId:Q.scopeId},jobControlSocketPath:Q.socketPath,...$.prefix?{bashCommandPrefix:$.prefix}:{},...$.jobsUser?{jobsUser:$.jobsUser}:{}},X;try{w9(W,JSON.stringify(Y),{mode:384});let j=A4({configPath:W,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(W,Y)??H9(j.command,j.args,{...j.options,env:$.environment,stdio:["ignore","ignore","ignore"]})}catch(j){throw Q.disposeSocket(),j}let F=!1,C=new Promise((j,q)=>{X.once("exit",(_)=>{F=!0,j(_)}),X.once("error",(_)=>{F=!0,q(_)})});C.catch(()=>{});let N={root:$.root,runId:$.claim.run_id,scopeId:Q.scopeId,socketPath:Q.socketPath,generation:1,fenceId:Y.fenceId,executorLaunchId:Y.launchId,expiresAtMs:Y.expiresAtMs},D=async(j)=>{let q=await L4(N,{type:"job",version:2,generation:1,id:F2(),jobId:$.claim.operation_id,...j==="start"?{action:j,input:{script:$.command,leaseExpiresAtMs:$.expiresAtMs}}:j==="inspect"?{action:j,input:{after:0}}:j==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:j,input:{}}},new AbortController().signal);if(!q.ok)throw V0(q.error);return q.job},w=!1,M=!1,I,O=()=>{w=!0,X.kill("SIGTERM")};$.signal.addEventListener("abort",O,{once:!0});let R,E=0,v=async(j)=>{let q=[...j.output],_={version:1,process_id:$.claim.operation_id,state:j.state,exit_code:j.exitCode,first_cursor:j.firstCursor,next_cursor:j.nextCursor,truncated:j.truncated,output:q,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(_))>90000&&q.length)q.shift(),_.truncated=!0,_.first_cursor=q[0]?.cursor??_.next_cursor+1;R=s0.parse(_),await $.emit(R),E=Date.now()};try{let j=Math.min(Date.now()+1e4,$.expiresAtMs);while(!N2(Y.readyPath)){if(F)throw new H("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if($.signal.aborted||Date.now()>=j)throw V0("process_start_unconfirmed");await C4(25)}let q=JSON.parse(M9(Y.readyPath,"utf8"));if(q.launchId!==Y.launchId||q.fenceId!==Y.fenceId||q.workerArtifactSha256!==P0)throw V0();if($.signal.throwIfAborted(),J.cancelRequested)return N4($.claim.operation_id);let _;try{M=!0,_=await D("start")}catch(S){if(!(S instanceof H)||S.code!=="hands_job_result_unknown")throw S;_=await D("inspect")}if(J.phase="running",J.cancel=async()=>{await D("cancel")},B&&$.preview)J.tunnels=F4({claim:$.claim,executorLaunchId:Y.launchId,expiresAtMs:$.expiresAtMs,deniedPorts:$.preview.deniedPorts,inspect:async()=>J.phase==="running"&&!F?await D("probe"):null});if(J.cancelRequested)await J.cancel(),_=await D("inspect");for(;;){if(!["starting","running"].includes(_.state))J.phase="settling",J.cancel=void 0;if(!R||R.state!==_.state||R.next_cursor!==_.nextCursor&&Date.now()-E>=5000)await v(_);if(!["starting","running"].includes(_.state))break;if($.signal.aborted||F)throw V0();await C4(1000);try{_=await D("inspect"),I=void 0}catch(S){if(!(S instanceof H)||S.code!=="hands_job_result_unknown"||$.signal.aborted||F||Date.now()-(I??=Date.now())>120000)throw S}}if(!R||R.state==="uncertain")throw V0();return R}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",O),!F&&!w)X.kill("SIGTERM");let j,q=await Promise.race([C.then((_)=>({code:_})),new Promise((_)=>{j=setTimeout(()=>_(null),6000)})]).finally(()=>{clearTimeout(j)});if(!q){X.kill("SIGKILL");try{await C}finally{if(F)Q.disposeSocket()}throw V0("process_cleanup_unconfirmed")}try{if((w||$.signal.aborted)&&q.code===0&&M){w4(U);let _=JSON.parse(O4(Y.directTerminalReceiptPath)),S=G2.safeParse(_.observation);if(Object.keys(_).length===4&&_.launch_id===Y.launchId&&_.fence_id===Y.fenceId&&_.scope_id===Q.scopeId&&S.success&&S.data.process_id===$.claim.operation_id){if(B)G();throw new c0(S.data)}}}catch(_){if(_ instanceof c0)throw _}finally{if(F)Q.disposeSocket()}if(q.code!==0&&!w&&M)throw V0("process_cleanup_unconfirmed");if(!w&&q.code===0&&(R&&["exited","cancelled","expired"].includes(R.state)||!M&&J.cancelRequested)||B&&q.code===0&&!M)G()}}async function _K($,J){if(J.kind===K4&&$.capability===P4){let K=R0.get($.operation_id);if(K?.claim===$&&K.tunnels)K.tunnels.open(J.payload);else Y2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==t3||!$4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=R0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=z4($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function RK($,J){R0.delete($);let Z=O1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return O1.delete($),!1;try{let Q=T4(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||Q.uid!==process.getuid?.()||(Q.mode&63)!==0||w1(Z.path)!==Z.path||N2(X0(Z.path,"owner.lock")))return!1;return L9(Z.path,{recursive:!0}),O1.delete($),!0}catch{return!1}}import{createServer as T9,request as _9}from"http";import{connect as R9,isIP as P9}from"net";var f4=120000,z9=15000;function q9($,J,Z){let Q=S4(J).toLowerCase().replace(/\.$/,"");if(!Q||P9(Q))return!1;return $.some((K)=>{if(!X2.test(K))return!1;let B=K.lastIndexOf(":"),G=B>0?K.slice(0,B):K;if(B>0&&Number(K.slice(B+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function E9($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,K=Z?Number(Z[2]):J;return Q&&K>=1&&K<=65535?{host:Q,port:K}:null}async function C2($,J,Z){if(!q9(Z,$,J))return null;let Q=await k4($);return Q.ok?Q.addresses[0]:null}function a0($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
14
+ `).filter(Boolean);if(r.length>5000)A("local_device_gh_collection_too_large");let a=[],D0=0;for(let p of r){if(!Q2.test(p))A("local_device_gh_object_invalid");let K0=await R(S,["cat-file","-t",p]);if(!["blob","commit","tree"].includes(K0))A("local_device_gh_object_invalid");let $0=await O(S,["cat-file",K0,p]);if(D0+=$0.length,D0>T0)A("local_device_gh_collection_too_large");if(K0==="tree"){let U0=0;while(U0<$0.length){let F0=$0.indexOf(32,U0),e=$0.indexOf(0,F0+1);if(F0<U0||e<=F0||e+21>$0.length)A("local_device_gh_object_invalid");let B0=$0.subarray(F0+1,e).toString("utf8");if(B0.includes("/")||!Z2(B0).valid)A("local_device_gh_object_invalid");U0=e+21}}a.push({path:`object-${p}`,content:$0.toString("utf8")})}let d0=J.secretNames?{secretNames:J.secretNames}:{},l0=M1(a,J.forbiddenSecretValues,d0),g3=new Map;if(!l0.clean)try{let p=(await O(S,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,T])).toString("utf8").split("\x00"),K0=[],$0=[];for(let i=0;i+1<p.length;i+=2){let[,m7,v7,o1,C1]=p[i].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!o1||!C1)continue;if(m7!=="160000"&&!/^0+$/.test(o1))K0.push(o1);if(v7!=="160000"&&!/^0+$/.test(C1))$0.push(C1),g3.set(`object-${C1}`,p[i+1])}let U0=await v([...K0,...$0]),F0=new Set(l0.violations.map((i)=>i.path)),e=s3(a.filter((i)=>F0.has(i.path)),J.forbiddenSecretValues),B0=c3(e,$0.map((i)=>U0.get(i)??""),K0.map((i)=>U0.get(i)??""));if(B0.size>0)l0=M1(a,J.forbiddenSecretValues,{...d0,published:B0})}catch{}if(!l0.clean)r3(l0.violations,(p)=>g3.get(p)??`an object in the pushed history (${p})`,"Remove it from the files and commit again; a commit or message in the pushed history that holds it must be amended before this branch can be pushed.");await O(S,["push","--no-recurse-submodules",D,`${T}:refs/heads/${Q.branch}`]);let S3=await C(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(S3.status!==200||JSON.parse(S3.body).object?.sha!==T)A("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:T,scannedObjectCount:a.length}}finally{z.rmSync(S,{recursive:!0,force:!0})}}var _0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),B2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},Z9=V.object({...B2,version:V.literal(2),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!1),source_bound:V.literal(!1),profiles:V.array(_0.shape.profile).min(1).max(16),extension_instance_ids:V.array(_0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),Q9=V.object({...B2,version:V.literal(3),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!0),source_bound:V.literal(!1),max_seconds:V.literal(15),profiles:V.array(_0.shape.profile).min(1).max(16),extension_instance_ids:V.array(_0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),V2=V.union([Z9,Q9]),rQ=V.union([V.object({...B2,version:V.literal(1),development_only:V.literal(!0),profile:_0.shape.profile,extension_instance_id:_0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),V2]);import{randomUUID as N2}from"crypto";import{spawn as M9}from"child_process";import{existsSync as C2,lstatSync as _4,mkdirSync as L9,readFileSync as w9,realpathSync as w1,rmSync as O9,writeFileSync as j9}from"fs";import{dirname as R4,join as X0,relative as I9,sep as A9}from"path";var K9=["process.run.v1","process.full.v1"],B9=600000,V9=1800000,G9=20000,e3="process.cancel.v1",$4=V.object({action:V.literal("start"),request_id:V.string().uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),cwd:V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")&&!$.startsWith("/")&&!$.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:V.enum(["host","confined"]).default("host"),timeout_ms:V.number().int().min(1000).max(V9).default(B9).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),G2={device_id:V.string().uuid(),root_id:V.string().uuid()},U9=V.discriminatedUnion("action",[$4.extend(G2),V.object({...G2,action:V.literal("inspect"),process_id:V.string().uuid(),after:V.number().int().min(0).default(0),wait_ms:V.number().int().min(0).max(G9).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),V.object({...G2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),oQ=V.toJSONSchema(U9,{io:"input"}),tQ=$4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),s0=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:V.number().int().nullable(),first_cursor:V.number().int().min(0),next_cursor:V.number().int().min(0),truncated:V.boolean(),observed_at:V.iso.datetime(),output:V.array(V.object({cursor:V.number().int().min(1),stream:V.enum(["stdout","stderr"]),text:V.string().max(32768)}).strict()).max(128)}).strict().refine(($)=>{if(Buffer.byteLength(JSON.stringify($))>1e5||$.next_cursor<$.first_cursor-1)return!1;if(($.state==="starting"||$.state==="running"||$.state==="uncertain")&&$.exit_code!==null)return!1;if($.state==="exited"&&($.exit_code===null||$.exit_code<0||$.exit_code>255))return!1;if($.state==="cancelled"&&$.exit_code!==130||$.state==="expired"&&$.exit_code!==124)return!1;let Z=$.first_cursor-1;for(let Q of $.output){if(Q.cursor<=Z||Q.cursor>$.next_cursor)return!1;Z=Q.cursor}return!0});function J4($){return K9.includes($)}var eQ=V.object({operation_constraints:V.record(V.string(),V.unknown())}),$K=V.object({ready:V.literal(!0),version:V.literal(1),execution_mode:V.enum(["host","confined"]),max_timeout_ms:V.number().int().min(1000).optional()});var X9=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["queued","cancelled_before_start","not_started"]),exit_code:V.null(),output:V.array(V.never()).length(0),first_cursor:V.literal(0),next_cursor:V.literal(0),truncated:V.literal(!1),cancellation_requested:V.literal(!1),reason_code:V.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),W9=V.object({...s0.shape,state:V.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:V.iso.datetime().optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:V.boolean(),reason_code:V.string().nullable().optional(),execution_authority:V.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:V.object({cause:V.literal("brain_generation_changed"),terminal_confirmed:V.boolean(),next_step:V.enum(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:s0.shape.state.or(V.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),JK=V.toJSONSchema(W9),ZK=V.union([s0,X9.refine(($)=>$.state==="cancelled_before_start")]),U2=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["exited","cancelled","expired"]),exit_code:V.number().int().min(0).max(255),observed_at:V.iso.datetime()}).strict().refine(($)=>($.state!=="cancelled"||$.exit_code===130)&&($.state!=="expired"||$.exit_code===124)),Y9=V.object({process_terminal_observation:U2}).strict();function QK($,J){let Z=Y9.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var Q4="preview.serve.v1",K4=43200000;var GK=3,B4="preview.open.v1",V4=1,X2="gid_proxy_v1",G4="egress",W2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,F9=V.object({version:V.literal(X2),allowed_domains:V.array(V.string().max(260).regex(W2)).max(1024)}).strict(),N9=V.custom(($)=>Z4($)!==null,"invalid workspace"),C9=V.object({version:V.literal(1),request_id:V.uuid(),session_id:V.uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),port:V.number().int().min(1024).max(65535),workspace:N9,egress:F9.optional()}).strict(),U4=C9.extend({expires_at:V.iso.datetime()}).strict();var H9=4,D9=5000;function F2($,J,Z){let Q=null;try{Q=Y2($)}catch{}W4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function N4($){let J=new Map;return{open(Z){let Q=(X)=>F2(Z,$.claim.operation_id,X),K;try{K=Y2(Z)}catch{return Q("binding_invalid")}let{binding:B,deviceRelayUrl:G}=K,U=$.claim.owner;if(!U||B.organizationId!==U.organization_id||B.userId!==U.user_id||B.deviceId!==U.device_id||B.rootId!==$.claim.root_id||B.jobId!==$.claim.operation_id||B.fenceId!==$.claim.operation_id||B.generation!==V4||B.expiresAtMs>Math.min(Date.now()+X4.lifetimeMs+D9,$.expiresAtMs))return Q("binding_mismatch");if(B.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(B.port)?.abort(),J.delete(B.port),J.size>=H9)return Q("preview_capacity");let W=new AbortController;J.set(B.port,W);let Y=F4({binding:B,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(W.signal.aborted)return null;let X=await $.inspect();return X?{binding:B,executorLaunchId:$.executorLaunchId,job:X}:null}});Y4({binding:B,deviceRelayUrl:G,port:Y,signal:W.signal}).then((X)=>X.closed,(X)=>{let N=X instanceof Error?X.message:"preview_failed";if(N!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:B.jobId,port:B.port,reason_code:N})}
15
+ `)}).finally(()=>{if(J.get(B.port)===W)J.delete(B.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class c0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var P4=256,O1=new Map,z4="preview.serve.v1",R0=new Map;function q4($){let J=R0.get($.operation_id);if(J){if(J.claim!==$)throw V0("process_authority_lost");return J}if(R0.size>=P4)throw V0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return R0.set($.operation_id,Z),Z}function C4($){return{version:1,process_id:$,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var H4=($)=>new Promise((J)=>setTimeout(J,$)),V0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function T9($=j1(),J=_9()){let Z=R4(I4({},$)),Q=I9(D4($),Z),[K,...B]=Q.split(A9);return{directory:X0(J,Q,"processes"),previous:[X0(Z,"processes"),...K==="reason"?[X0(J,"ara",...B,"processes")]:[]]}}function _9(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=M4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function I1($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw V0("process_authority_lost");let J=q4($.claim);if(J.executing)throw V0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",C4($.claim.operation_id);J.phase="starting";let Z=$.journals??T9();L9(Z.directory,{recursive:!0,mode:448});let Q=L4({runtimeDirectory:w1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((I)=>C2(I)).map((I)=>w1(I)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:P4});try{for(let I of[$.root,$.cwd])if(!A4(w1(I),Q.journalDirectory))throw new H("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(I){throw Q.disposeSocket(),I}let K=_4(Q.journalDirectory),B=$.claim.capability===z4,G=()=>O1.set($.claim.operation_id,{path:Q.journalDirectory,ino:K.ino,dev:K.dev,anyCompletion:B}),U=R4(Q.socketPath),W=X0(U,"config.json"),Y={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:n0,protocolVersion:2,workerArtifactSha256:P0,workerEntrypoint:r0,targetGeneration:1,fenceId:N2(),workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:X0(U,"unused.env"),replSocketPath:X0(U,"unused.sock"),readyPath:X0(U,"ready.json"),directTerminalReceiptPath:X0(U,"terminal.json"),launchId:N2(),expiresAtMs:$.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Q.journalDirectory,scopeId:Q.scopeId},jobControlSocketPath:Q.socketPath,...$.prefix?{bashCommandPrefix:$.prefix}:{},...$.jobsUser?{jobsUser:$.jobsUser}:{}},X;try{j9(W,JSON.stringify(Y),{mode:384});let I=T4({configPath:W,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(W,Y)??M9(I.command,I.args,{...I.options,env:$.environment,stdio:["ignore","ignore","ignore"]})}catch(I){throw Q.disposeSocket(),I}let N=!1,C=new Promise((I,q)=>{X.once("exit",(_)=>{N=!0,I(_)}),X.once("error",(_)=>{N=!0,q(_)})});C.catch(()=>{});let F={root:$.root,runId:$.claim.run_id,scopeId:Q.scopeId,socketPath:Q.socketPath,generation:1,fenceId:Y.fenceId,executorLaunchId:Y.launchId,expiresAtMs:Y.expiresAtMs},D=async(I)=>{let q=await w4(F,{type:"job",version:2,generation:1,id:N2(),jobId:$.claim.operation_id,...I==="start"?{action:I,input:{script:$.command,leaseExpiresAtMs:$.expiresAtMs}}:I==="inspect"?{action:I,input:{after:0}}:I==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:I,input:{}}},new AbortController().signal);if(!q.ok)throw V0(q.error);return q.job},w=!1,M=!1,j,O=()=>{w=!0,X.kill("SIGTERM")};$.signal.addEventListener("abort",O,{once:!0});let R,E=0,v=async(I)=>{let q=[...I.output],_={version:1,process_id:$.claim.operation_id,state:I.state,exit_code:I.exitCode,first_cursor:I.firstCursor,next_cursor:I.nextCursor,truncated:I.truncated,output:q,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(_))>90000&&q.length)q.shift(),_.truncated=!0,_.first_cursor=q[0]?.cursor??_.next_cursor+1;R=s0.parse(_),await $.emit(R),E=Date.now()};try{let I=Math.min(Date.now()+1e4,$.expiresAtMs);while(!C2(Y.readyPath)){if(N)throw new H("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if($.signal.aborted||Date.now()>=I)throw V0("process_start_unconfirmed");await H4(25)}let q=JSON.parse(w9(Y.readyPath,"utf8"));if(q.launchId!==Y.launchId||q.fenceId!==Y.fenceId||q.workerArtifactSha256!==P0)throw V0();if($.signal.throwIfAborted(),J.cancelRequested)return C4($.claim.operation_id);let _;try{M=!0,_=await D("start")}catch(S){if(!(S instanceof H)||S.code!=="hands_job_result_unknown")throw S;_=await D("inspect")}if(J.phase="running",J.cancel=async()=>{await D("cancel")},B&&$.preview)J.tunnels=N4({claim:$.claim,executorLaunchId:Y.launchId,expiresAtMs:$.expiresAtMs,deniedPorts:$.preview.deniedPorts,inspect:async()=>J.phase==="running"&&!N?await D("probe"):null});if(J.cancelRequested)await J.cancel(),_=await D("inspect");for(;;){if(!["starting","running"].includes(_.state))J.phase="settling",J.cancel=void 0;if(!R||R.state!==_.state||R.next_cursor!==_.nextCursor&&Date.now()-E>=5000)await v(_);if(!["starting","running"].includes(_.state))break;if($.signal.aborted||N)throw V0();await H4(1000);try{_=await D("inspect"),j=void 0}catch(S){if(!(S instanceof H)||S.code!=="hands_job_result_unknown"||$.signal.aborted||N||Date.now()-(j??=Date.now())>120000)throw S}}if(!R||R.state==="uncertain")throw V0();return R}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",O),!N&&!w)X.kill("SIGTERM");let I,q=await Promise.race([C.then((_)=>({code:_})),new Promise((_)=>{I=setTimeout(()=>_(null),6000)})]).finally(()=>{clearTimeout(I)});if(!q){X.kill("SIGKILL");try{await C}finally{if(N)Q.disposeSocket()}throw V0("process_cleanup_unconfirmed")}try{if((w||$.signal.aborted)&&q.code===0&&M){O4(U);let _=JSON.parse(j4(Y.directTerminalReceiptPath)),S=U2.safeParse(_.observation);if(Object.keys(_).length===4&&_.launch_id===Y.launchId&&_.fence_id===Y.fenceId&&_.scope_id===Q.scopeId&&S.success&&S.data.process_id===$.claim.operation_id){if(B)G();throw new c0(S.data)}}}catch(_){if(_ instanceof c0)throw _}finally{if(N)Q.disposeSocket()}if(q.code!==0&&!w&&M)throw V0("process_cleanup_unconfirmed");if(!w&&q.code===0&&(R&&["exited","cancelled","expired"].includes(R.state)||!M&&J.cancelRequested)||B&&q.code===0&&!M)G()}}async function qK($,J){if(J.kind===B4&&$.capability===z4){let K=R0.get($.operation_id);if(K?.claim===$&&K.tunnels)K.tunnels.open(J.payload);else F2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==e3||!J4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=R0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=q4($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function EK($,J){R0.delete($);let Z=O1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return O1.delete($),!1;try{let Q=_4(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||Q.uid!==process.getuid?.()||(Q.mode&63)!==0||w1(Z.path)!==Z.path||C2(X0(Z.path,"owner.lock")))return!1;return O9(Z.path,{recursive:!0}),O1.delete($),!0}catch{return!1}}import{createServer as R9,request as P9}from"http";import{connect as z9,isIP as q9}from"net";var b4=120000,E9=15000;function g9($,J,Z){let Q=k4(J).toLowerCase().replace(/\.$/,"");if(!Q||q9(Q))return!1;return $.some((K)=>{if(!W2.test(K))return!1;let B=K.lastIndexOf(":"),G=B>0?K.slice(0,B):K;if(B>0&&Number(K.slice(B+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function S9($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,K=Z?Number(Z[2]):J;return Q&&K>=1&&K<=65535?{host:Q,port:K}:null}async function H2($,J,Z){if(!g9(Z,$,J))return null;let Q=await f4($);return Q.ok?Q.addresses[0]:null}function a0($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
16
16
  Connection: close\r
17
17
  Content-Length: 0\r
18
18
  \r
19
- `)}function q4($,J){return new Promise((Z,Q)=>{let K=R9({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),z9);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(G)=>{clearTimeout(B),Q(G)})})}function E4($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(f4,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function g4($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function b4($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=T9((U,W)=>{(async()=>{let Y;try{Y=new URL(U.url??"")}catch{Y=new URL("invalid:")}let X=Number(Y.port||80),F=Y.protocol==="http:"?await C2(Y.hostname,X,Z):null;if(!F){J(),W.writeHead(403,{connection:"close"}).end();return}let C=_9({host:F,port:X,method:U.method,path:`${Y.pathname}${Y.search}`,headers:g4(U.headers,Y.host),agent:!1,timeout:f4},(N)=>{W.writeHead(N.statusCode??502,N.headers),N.pipe(W)});C.on("timeout",()=>C.destroy()),C.on("error",()=>{if(!W.headersSent)W.writeHead(502);W.end()}),W.on("close",()=>C.destroy()),U.pipe(C)})().catch(()=>{if(!W.headersSent)W.writeHead(502);W.end()})});B.on("connection",K),B.on("connect",(U,W,Y)=>{K(W),W.on("error",()=>W.destroy()),(async()=>{let X=E9(U.url??"",443),F=X?await C2(X.host,X.port,Z):null;if(!X||!F){J(),a0(W,403);return}let C=await q4(F,X.port).catch(()=>null);if(!C){a0(W,502);return}if(W.destroyed){C.destroy();return}K(C),W.write(`HTTP/1.1 200 Connection Established\r
19
+ `)}function E4($,J){return new Promise((Z,Q)=>{let K=z9({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),E9);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(G)=>{clearTimeout(B),Q(G)})})}function g4($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(b4,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function S4($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function x4($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=R9((U,W)=>{(async()=>{let Y;try{Y=new URL(U.url??"")}catch{Y=new URL("invalid:")}let X=Number(Y.port||80),N=Y.protocol==="http:"?await H2(Y.hostname,X,Z):null;if(!N){J(),W.writeHead(403,{connection:"close"}).end();return}let C=P9({host:N,port:X,method:U.method,path:`${Y.pathname}${Y.search}`,headers:S4(U.headers,Y.host),agent:!1,timeout:b4},(F)=>{W.writeHead(F.statusCode??502,F.headers),F.pipe(W)});C.on("timeout",()=>C.destroy()),C.on("error",()=>{if(!W.headersSent)W.writeHead(502);W.end()}),W.on("close",()=>C.destroy()),U.pipe(C)})().catch(()=>{if(!W.headersSent)W.writeHead(502);W.end()})});B.on("connection",K),B.on("connect",(U,W,Y)=>{K(W),W.on("error",()=>W.destroy()),(async()=>{let X=S9(U.url??"",443),N=X?await H2(X.host,X.port,Z):null;if(!X||!N){J(),a0(W,403);return}let C=await E4(N,X.port).catch(()=>null);if(!C){a0(W,502);return}if(W.destroyed){C.destroy();return}K(C),W.write(`HTTP/1.1 200 Connection Established\r
20
20
  \r
21
- `),E4(W,C,Y)})().catch(()=>W.destroy())}),B.on("upgrade",(U,W,Y)=>{K(W),W.on("error",()=>W.destroy()),(async()=>{let X;try{X=new URL(U.url??"")}catch{a0(W,403);return}let F=Number(X.port||80),C=["http:","ws:"].includes(X.protocol)?await C2(X.hostname,F,Z):null;if(!C){J(),a0(W,403);return}let N=await q4(C,F).catch(()=>null);if(!N){a0(W,502);return}K(N);let D=g4(U.headers,X.host),w=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[M,I]of Object.entries(D))for(let O of Array.isArray(I)?I:I===void 0?[]:[I])w.push(`${M}: ${O}`);N.write(`${w.join(`\r
21
+ `),g4(W,C,Y)})().catch(()=>W.destroy())}),B.on("upgrade",(U,W,Y)=>{K(W),W.on("error",()=>W.destroy()),(async()=>{let X;try{X=new URL(U.url??"")}catch{a0(W,403);return}let N=Number(X.port||80),C=["http:","ws:"].includes(X.protocol)?await H2(X.hostname,N,Z):null;if(!C){J(),a0(W,403);return}let F=await E4(C,N).catch(()=>null);if(!F){a0(W,502);return}K(F);let D=S4(U.headers,X.host),w=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[M,j]of Object.entries(D))for(let O of Array.isArray(j)?j:j===void 0?[]:[j])w.push(`${M}: ${O}`);F.write(`${w.join(`\r
22
22
  `)}\r
23
23
  \r
24
- `),E4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{B.once("error",W),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as O2,randomUUID as f9}from"crypto";import{closeSync as t0,constants as c,fchownSync as b9,fstatSync as z0,fsyncSync as x9,linkSync as y9,mkdirSync as h9,openSync as i4,readSync as o4,unlinkSync as m9,writeSync as v9}from"fs";import{platform as n4}from"os";import{getSystemErrorName as p9}from"util";var x4={type:"string",format:"uuid"},v4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,A1={type:"string",minLength:1,maxLength:4096,pattern:v4},H2=V.string().min(1).max(4096).regex(new RegExp(v4)),T1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},_1={device_id:x4,root_id:x4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},fK={read:{schema:V.object({...T1,path:H2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{..._1,path:A1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...T1,path:H2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{..._1,path:A1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...T1,command:V.string().min(1).max(16000),cwd:H2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{..._1,command:{type:"string",minLength:1,maxLength:16000},cwd:A1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},W0=1073741824,i0=600000,y4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,p4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${y4}(?:/${y4})*(?![\s\S])`,u4=new RegExp(p4);function d4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&u4.test($)}var D2=V.string().min(1).max(4096).regex(u4),M2={...A1,pattern:p4},l4=V.string().regex(/^[a-f0-9]{64}$/),s4=V.object({kind:V.literal("workspace"),path:D2}).strict(),g9=V.discriminatedUnion("kind",[s4,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:l4}).strict()]),R1=1,o0="cloud_workspace_id",L2="cloud_workspace",w2=1,S9=V.discriminatedUnion("kind",[s4,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(W0),sha256:l4}).strict()]),c4=V.object({source_version:V.literal(R1),source:S9,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[o0]:V.string().min(1).max(160).optional()}).strict(),bK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(R1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var h4=V.object({...T1,timeout_ms:V.number().int().min(1000).max(i0).optional(),source_path:D2,destination_path:D2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),m4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{..._1,timeout_ms:{type:"integer",minimum:1000,maximum:i0},source_path:M2,destination_path:M2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},k9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:M2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},xK=V.union([h4,h4.omit({source_path:!0}).extend({source:g9}).strict()]),yK={...m4,required:["device_id","root_id","destination_path"],properties:{...m4.properties,source:k9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var j2=65536;function u($){throw new H($,$)}function z1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function P1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function u9($,J,Z){let Q;switch(z1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return P1($,J,Q)}function d9($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function l9(){if(n4()==="linux")return{open:(U,W,Y,X=384)=>i4(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>h9(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>y9(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>m9(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(n4()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),K=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),B=K.symbols.__error();if(B===null)return K.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=p9(-Q.i32(B));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(K.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(K.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(K.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(K.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>K.close()}}function t4($,J){let Z=z0($),Q=z0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)b9(J,Z.uid,Z.gid)}function s9($,J,Z,Q){if(!d4(Z))return u("transfer_path_invalid");let K=Z.split("/"),B=i4(J,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW);try{for(let G of K.slice(0,-1)){let U;try{U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW)}catch(W){if(!Q||z1(W)!=="ENOENT")throw W;try{$.mkdir(B,G)}catch(Y){if(z1(Y)!=="EEXIST")throw Y}U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW),t4(B,U)}t0(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw t0(B),G}}function r4($,J){let Z=z0($,{bigint:!0});if(!Z.isFile()||Z.size>W0)return u("transfer_file_invalid");let Q=O2("sha256"),K=Buffer.alloc(j2),B=0;while(!0){J.throwIfAborted();let U=o4($,K,0,K.length,B);if(!U)break;if(B+=U,B>W0)return u("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=z0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=d9($.payload.url),Z=await l9(),Q,K,B;try{if(Q=s9(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK);let C=z0(K,{bigint:!0});if(!C.isFile()||C.size>W0)return u("transfer_file_invalid");let N=O2("sha256"),D=0,w=K,M,I=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let j=Buffer.alloc(j2),q=o4(w,j,0,j.length,D);if(!q){v.close();return}if(D+=q,D>C.size)return u("transfer_source_changed");N.update(j.subarray(0,q)),v.enqueue(j.subarray(0,q))}catch(j){throw M=j,j}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:I,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(C.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return P1(v,$.signal,"transfer_upload_failed")}let O=z0(K,{bigint:!0});if(BigInt(D)!==C.size||O.size!==C.size||O.mtimeNs!==C.mtimeNs||O.ctimeNs!==C.ctimeNs)return u("transfer_source_changed");let R=N.digest("hex"),E=r4(K,$.signal);if(E.size_bytes!==D||E.sha256!==R)return u("transfer_source_changed");return{size_bytes:D,sha256:R,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>W0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK)}catch(C){if(z1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=r4(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{t0(W)}return u("transfer_destination_exists")}B=`.reason-copy-${f9()}`,K=Z.open(Q.fd,B,c.O_CREAT|c.O_EXCL|c.O_WRONLY|c.O_NOFOLLOW,384),t4(Q.fd,K);let Y;try{let C=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!C.ok||!C.body)return u("transfer_download_failed");Y=C.body.getReader()}catch(C){return P1(C,$.signal,"transfer_download_failed")}let X=O2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((N)=>P1(N,$.signal,"transfer_download_failed"));if(C.done)break;if(F+=C.value.length,F>G)return u("transfer_size_mismatch");X.update(C.value);for(let N=0;N<C.value.length;)$.signal.throwIfAborted(),N+=v9(K,C.value,N,Math.min(j2,C.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return x9(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)t0(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}t0(Q.fd)}}finally{Z.close()}}}}catch(J){return u9(J,$.signal,$.direction)}}import{spawn as n9}from"child_process";import{mkdtempSync as r9,rmSync as a9,writeFileSync as i9}from"fs";import{constants as o9,platform as t9,tmpdir as e9}from"os";import{join as Z8}from"path";import{gunzipSync as c9,gzipSync as nK}from"zlib";var $8=900000,aK=$8+60000,e0=49152,e4=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),J8=V.object({version:V.literal(1),script_gzip:e4(163840),stdin_gzip:e4(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max($8)}).strict(),I2=V.string().max(e0+256),iK=V.object({exit_code:V.number().int().min(0).max(255),stdout:I2,stderr:I2,combined:I2.optional()}).strict();function A2($){return c9(Buffer.from($,"base64")).toString("utf8")}var $$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",J$=["RUSTUP_HOME","TZ","LC_ALL"],Z$=2000,Q$=100;function _2(){return t9()==="linux"&&process.geteuid?.()===0}function T2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
24
+ `),g4(W,F,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{B.once("error",W),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as j2,randomUUID as x9}from"crypto";import{closeSync as t0,constants as c,fchownSync as y9,fstatSync as z0,fsyncSync as h9,linkSync as m9,mkdirSync as v9,openSync as o4,readSync as t4,unlinkSync as p9,writeSync as u9}from"fs";import{platform as r4}from"os";import{getSystemErrorName as d9}from"util";var y4={type:"string",format:"uuid"},p4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,A1={type:"string",minLength:1,maxLength:4096,pattern:p4},D2=V.string().min(1).max(4096).regex(new RegExp(p4)),T1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},_1={device_id:y4,root_id:y4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},hK={read:{schema:V.object({...T1,path:D2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{..._1,path:A1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...T1,path:D2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{..._1,path:A1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...T1,command:V.string().min(1).max(16000),cwd:D2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{..._1,command:{type:"string",minLength:1,maxLength:16000},cwd:A1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},W0=1073741824,i0=600000,h4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,u4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${h4}(?:/${h4})*(?![\s\S])`,d4=new RegExp(u4);function l4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&d4.test($)}var M2=V.string().min(1).max(4096).regex(d4),L2={...A1,pattern:u4},s4=V.string().regex(/^[a-f0-9]{64}$/),c4=V.object({kind:V.literal("workspace"),path:M2}).strict(),k9=V.discriminatedUnion("kind",[c4,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:s4}).strict()]),R1=1,o0="cloud_workspace_id",w2="cloud_workspace",O2=1,f9=V.discriminatedUnion("kind",[c4,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(W0),sha256:s4}).strict()]),n4=V.object({source_version:V.literal(R1),source:f9,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[o0]:V.string().min(1).max(160).optional()}).strict(),mK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(R1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var m4=V.object({...T1,timeout_ms:V.number().int().min(1000).max(i0).optional(),source_path:M2,destination_path:M2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),v4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{..._1,timeout_ms:{type:"integer",minimum:1000,maximum:i0},source_path:L2,destination_path:L2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},b9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:L2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},vK=V.union([m4,m4.omit({source_path:!0}).extend({source:k9}).strict()]),pK={...v4,required:["device_id","root_id","destination_path"],properties:{...v4.properties,source:b9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var I2=65536;function u($){throw new H($,$)}function z1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function P1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function l9($,J,Z){let Q;switch(z1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return P1($,J,Q)}function s9($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function c9(){if(r4()==="linux")return{open:(U,W,Y,X=384)=>o4(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>v9(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>m9(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>p9(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(r4()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),K=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),B=K.symbols.__error();if(B===null)return K.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=d9(-Q.i32(B));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(K.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(K.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(K.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(K.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>K.close()}}function e4($,J){let Z=z0($),Q=z0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)y9(J,Z.uid,Z.gid)}function n9($,J,Z,Q){if(!l4(Z))return u("transfer_path_invalid");let K=Z.split("/"),B=o4(J,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW);try{for(let G of K.slice(0,-1)){let U;try{U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW)}catch(W){if(!Q||z1(W)!=="ENOENT")throw W;try{$.mkdir(B,G)}catch(Y){if(z1(Y)!=="EEXIST")throw Y}U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW),e4(B,U)}t0(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw t0(B),G}}function a4($,J){let Z=z0($,{bigint:!0});if(!Z.isFile()||Z.size>W0)return u("transfer_file_invalid");let Q=j2("sha256"),K=Buffer.alloc(I2),B=0;while(!0){J.throwIfAborted();let U=t4($,K,0,K.length,B);if(!U)break;if(B+=U,B>W0)return u("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=z0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=s9($.payload.url),Z=await c9(),Q,K,B;try{if(Q=n9(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK);let C=z0(K,{bigint:!0});if(!C.isFile()||C.size>W0)return u("transfer_file_invalid");let F=j2("sha256"),D=0,w=K,M,j=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let I=Buffer.alloc(I2),q=t4(w,I,0,I.length,D);if(!q){v.close();return}if(D+=q,D>C.size)return u("transfer_source_changed");F.update(I.subarray(0,q)),v.enqueue(I.subarray(0,q))}catch(I){throw M=I,I}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:j,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(C.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return P1(v,$.signal,"transfer_upload_failed")}let O=z0(K,{bigint:!0});if(BigInt(D)!==C.size||O.size!==C.size||O.mtimeNs!==C.mtimeNs||O.ctimeNs!==C.ctimeNs)return u("transfer_source_changed");let R=F.digest("hex"),E=a4(K,$.signal);if(E.size_bytes!==D||E.sha256!==R)return u("transfer_source_changed");return{size_bytes:D,sha256:R,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>W0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK)}catch(C){if(z1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=a4(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{t0(W)}return u("transfer_destination_exists")}B=`.reason-copy-${x9()}`,K=Z.open(Q.fd,B,c.O_CREAT|c.O_EXCL|c.O_WRONLY|c.O_NOFOLLOW,384),e4(Q.fd,K);let Y;try{let C=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!C.ok||!C.body)return u("transfer_download_failed");Y=C.body.getReader()}catch(C){return P1(C,$.signal,"transfer_download_failed")}let X=j2("sha256"),N=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((F)=>P1(F,$.signal,"transfer_download_failed"));if(C.done)break;if(N+=C.value.length,N>G)return u("transfer_size_mismatch");X.update(C.value);for(let F=0;F<C.value.length;)$.signal.throwIfAborted(),F+=u9(K,C.value,F,Math.min(I2,C.value.length-F))}}finally{await Y.cancel().catch(()=>{})}if(N!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return h9(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)t0(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}t0(Q.fd)}}finally{Z.close()}}}}catch(J){return l9(J,$.signal,$.direction)}}import{spawn as a9}from"child_process";import{mkdtempSync as i9,rmSync as o9,writeFileSync as t9}from"fs";import{constants as e9,platform as $$,tmpdir as J$}from"os";import{join as Q8}from"path";import{gunzipSync as r9,gzipSync as oK}from"zlib";var J8=900000,eK=J8+60000,e0=49152,$8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),Z8=V.object({version:V.literal(1),script_gzip:$8(163840),stdin_gzip:$8(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max(J8)}).strict(),A2=V.string().max(e0+256),$B=V.object({exit_code:V.number().int().min(0).max(255),stdout:A2,stderr:A2,combined:A2.optional()}).strict();function T2($){return r9(Buffer.from($,"base64")).toString("utf8")}var Z$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",Q$=["RUSTUP_HOME","TZ","LC_ALL"],K$=2000,B$=100;function R2(){return $$()==="linux"&&process.geteuid?.()===0}function _2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
25
25
  [reason: ${G} bytes of output omitted]
26
- `:"")+K.toString("utf8")}}}async function Q8($,J){if(!_2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=J8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=A2(Q.script_gzip),B=A2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r9(Z8(e9(),"reason-workspace-setup-"));try{let U=Z8(G,"setup.sh");i9(U,K,{mode:384});let W={PATH:$$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let E of J$)if(process.env[E])W[E]=process.env[E];Object.assign(W,Q.env);let Y=n9("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=T2(e0),F=T2(e0),C=T2(e0);Y.stdout.on("data",(E)=>{X.push(E),C.push(E)}),Y.stderr.on("data",(E)=>{F.push(E),C.push(E)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let N=(E)=>{try{if(Y.pid)process.kill(-Y.pid,E)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),Z$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((E,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(j,q)=>E({code:j,signal:q}))}).finally(()=>{clearTimeout(I),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((E)=>{let v=setTimeout(E,Q$);Y.once("close",()=>{clearTimeout(v),E()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let R=D?124:O.signal?128+(o9.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,R),stdout:X.text(),stderr:F.text(),...R!==0?{combined:C.text()}:{}}}finally{a9(G,{recursive:!0,force:!0})}}import{chmodSync as K$,mkdtempSync as B$,realpathSync as G8,rmSync as V$}from"fs";import{tmpdir as G$}from"os";import{dirname as U$,join as R2,sep as X$}from"path";function P2($){return V8($,B8($)!==null).repoPath}function U8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[$1,void 0].map((K)=>U$(K8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=G8(R2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${X$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function X8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=P2($.runtimeRoot);if(L0(Q)||L0(R2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=B$(R2(G$(),`reason-cloud-copy-${process.pid}-`));try{K$(Z,448);let Q=G8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{V$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as L7,existsSync as G0,fstatSync as w7,lstatSync as O7,mkdirSync as mZ,mkdtempSync as j7,openSync as I7,readSync as vZ,realpathSync as J0,rmSync as A7,statSync as N1,writeSync as pZ}from"fs";import{homedir as W1,platform as l,tmpdir as T7}from"os";import{dirname as Y1,isAbsolute as uZ,join as T3,relative as L3,resolve as dZ,sep as lZ}from"path";import{spawn as sZ}from"child_process";import{createHash as C$,randomBytes as H$}from"crypto";var z2=30000,W$=1800000,Y$=5000,q1=30000,F$=g1+15000,W8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,N$=[/^\/app\/local-runtime\/operations\/claim$/,W8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(N$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},F$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(Y$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(W$,z2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(E1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+z2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!W8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(z2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var g2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function IB($,J={}){let Z=D$($),Q=J.rootPathsSupported===!0?D1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function D$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}function M$($){return $===408||$===429||$===500||$===502||$===503||$===504}function L$($){if($ instanceof Y0)return!1;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function w$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function O$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function AB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function Y8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function F8($){return C$("sha256").update($??"").digest("hex")}function j$($){return D8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function N8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var I$=20000,A$=1e4,C8=[2000,4000];class E2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class T${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=M8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J){let Z=this.proofOptions.challengeAttemptTimeoutsMs??C8;for(let Q of Z)try{return await this.challengeAttempt($,J,Q)}catch(K){if(J?.aborted||!(K instanceof E2))throw K}return await this.challengeAttempt($,J,null)}async challengeAttempt($,J,Z){let Q=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,B=K&&Z!==null?setTimeout(()=>K.abort(new E2(Z)),Z):null;try{let G=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:Q,signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return L8(await this.parseResponse(G))}catch(G){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw G}finally{if(B)clearTimeout(B)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=I$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,C8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B){let G=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=A$?B:null,U=!G&&K?await this.takeSpareChallenge(Z.deviceId):null,W=G??U??await this.challenge(Z.deviceId,Q);if(K)this.refillSpareChallenge(Z.deviceId);let Y=F8(J),X=this.signProof("POST",$,W.challenge,Y);return{"x-device-id":Z.deviceId,"x-device-timestamp":X.timestamp,"x-device-nonce":X.nonce,"x-device-challenge":W.challenge,"x-device-body-sha256":Y,"x-device-signature":X.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>H$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(j$({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!H8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",E1,Q,F8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&Y8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??O$,W=this.sessionFor($,J.device),Y;for(let X=0;X<G;X+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let C=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,J.signal,J.useSpareChallenge===!0&&X===0,X===0?J.issuedChallenge:void 0),N=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...C,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,signal:J.signal});return await this.parseResponse(N)}catch(F){if(Y=F,J.signal?.aborted)throw F;let C=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),N=F instanceof Y0&&M$(F.status),D=L$(F),w=J.transientRetryOwner!=="caller"&&(N||D);if((C||w)&&X+1<G){let M=C?0:w$(X,F,this.proofOptions.retryBaseDelayMs??500);if(M>0)await U(M,J.signal);continue}if(C&&X+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw Y??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return w8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return O8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return j8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return I8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return A8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return T8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});R8(Q)}async localSubscription($,J,Z){return _8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!N8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(d.operationClaim,{device:$,body:Q(30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,g1))},signal:J.signal});if(B===null)return null;return P8(B,g2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return z8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!N8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return q8(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(Y8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return g8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-p2bvtf6p.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return E8(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var _$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),J1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function S1($,J){if(_$.has($))return!1;if(J1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||J1.has($)))return!1;return!0}import{accessSync as R$,constants as P$,existsSync as z$,statSync as q$}from"fs";import{basename as E$,isAbsolute as g$}from"path";var Z1=["-lic"],S$="/bin/zsh",k$=new Set(["zsh","bash"]),S8=20000,S2=60000,f$=65536,b$=64,x$=8192,y$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),h$=["DYLD_","LD_"];function m$($){let J=$.toUpperCase();return y$.has(J)||h$.some((Z)=>J.startsWith(Z))}function k8($=process.env){return!0}function v$($){if(!g$($)||$.includes("\x00"))return!1;if(!k$.has(E$($)))return!1;try{if(!q$($).isFile())return!1;return R$($,P$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&v$(J))return J;return S$}function k2($=process.env){return k8($)&&z$(E0($))}function f2($=process.env){if(!k8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function b2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>f$)throw new H("invalid_payload","command is missing or too large.");return $}function x2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>b$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>x$)throw new H("invalid_payload","env entry is invalid or too large.");if(m$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function f8($){let J=$.processEnv??process.env;if(f2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=b2($.command),Q=E0(J),{forwarded:K,ignored:B}=x2($.requestEnv),G=await $.spawn(Q,[...Z1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...Z1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function b8($=process.env){return{transport:"shell",shell:`${E0($)} ${Z1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:S2}}import{readFile as p$,readdir as u$,readlink as d$,realpath as l$}from"fs/promises";import{basename as s$,relative as c$,sep as n$}from"path";var w0="/proc",r$=250,x8=500,a$=50,i$=250,o$=1024,y8=4096,t$=1,e$=3,h8=9,$J="0A",JJ=/^socket:\[(\d+)\]$/,y2={readDirectory:($)=>u$($),readLink:($)=>d$($),readTextFile:($)=>p$($,"utf8"),realPath:($)=>l$($)};function v8($,J){return J===$||J.startsWith(`${$}${n$}`)}function ZJ($,J){return c$($,J)||"."}async function p8($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function u8($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,y8).split(`
27
- `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${w0}/${$}/cmdline`)).slice(0,y8).split("\x00",1)[0]?.trim();return Q?s$(Q):null}catch{return null}}async function d8($,J=y2){let Z;try{Z=await J.readLink(`${w0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function l8($,J=y2){let Z=[];for(let Q of await p8(J)){if(Z.length>=r$)break;let K=await d8(Q,J);if(!K||!v8($,K))continue;Z.push({pid:Q,command:await u8(Q,J),cwd:ZJ($,K)})}return{processes:Z}}function m8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function QJ($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(K<0)K=W;continue}if(K>=0){let Y=W-K;if(Y>Q)Z=K,Q=Y;K=-1}}let B=J.map((W)=>W.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function KJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=m8($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...m8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${QJ(Z)}]:${J}`}return null}function BJ($,J){let Z=[];for(let Q of $.split(`
28
- `).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=h8)continue;if(K[e$]?.toUpperCase()!==$J)continue;let B=K[t$]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=KJ(B.slice(0,G),U),Y=K[h8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function VJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=x8)break;let Q;try{Q=await $.readTextFile(`${w0}/net/${Z}`)}catch{continue}J.push(...BJ(Q,x8-J.length))}return J}async function GJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await p8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${w0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,o$)){let G;try{G=await J.readLink(`${w0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(JJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function s8($,J=y2){let Z=await VJ(J),Q=await GJ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;K.push({pid:F,port:X.port,address:X.address})}K.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,a$),G=await Promise.all(B.map(async(X)=>[X,await d8(X,J)])),U=new Map(G),W=K.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&v8($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await u8(X,J)])));return{ports:W.slice(0,i$).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as m2}from"path";var k1=200,UJ=250,XJ=250;async function f1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function h2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var c8="/System/Volumes/Data",WJ=["/tmp","/var","/etc"];function v2($){let J=m2.normalize($);if(J.startsWith(`${c8}/`))J=J.slice(c8.length);return WJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function n8($){return $&&m2.isAbsolute($)?v2($):null}async function r8($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=k1){let K=J.slice(Q,Q+k1).join(",");for(let B of await f1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:n8(B.names[0])})}return Z}async function a8($,J){let Z=v2($),Q=(await f1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=n8(B.names[0]);return G!==null&&h2(Z,G)}).map((B)=>B.pid).slice(0,UJ),K=await r8(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&h2(Z,G.cwd)?[{pid:B,command:G.command,cwd:m2.relative(Z,G.cwd)||"."}]:[]})}}async function i8($,J){let Z=v2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await f1(J,Q),B=await r8(J,K.map((Y)=>Y.pid)),G=K.map((Y)=>Y.pid).filter((Y)=>{let X=B.get(Y)?.cwd;return Boolean(X&&h2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=k1){let X=G.slice(Y,Y+k1).join(",");for(let F of await f1(J,["-a","-p",X,...Q]))for(let C of F.names)if(U.has(`${F.pid} ${C}`))W.push({pid:F.pid,command:F.command,address:C})}return{ports:W.slice(0,XJ)}}import{join as AJ}from"path";import{spawn as MJ}from"child_process";import{randomUUID as LJ}from"crypto";import{chmodSync as e8,lstatSync as $5,mkdirSync as wJ,readdirSync as OJ,statSync as jJ,unlinkSync as IJ}from"fs";import{join as u2}from"path";function Q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var p2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var b1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var O0=()=>{throw Error("proof_visual_contract_invalid")};class o8 extends Error{constructor(){super("proof_visual_contract_invalid")}}function FJ($){if(!Q1($)||$.version!==1)return O0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new o8;if(!Q1($.viewport)||!b1($.viewport.width,1,4096)||!b1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>p2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return O0();let J=$.targets.map((Q)=>{if(!Q1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return O0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return O0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return O0();Z=$.additionalViewports.map((K)=>{if(!Q1(K)||!b1(K.width,1,4096)||!Number.isInteger(K.width)||!b1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return O0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return O0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var CJ=["organizationId","userId","sessionId","runId"],HJ=[...CJ,"prUrl","headSha","skillDigest","evidenceKind"],dB=[...HJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DJ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function t8($){return DJ[$].directory}var J5=10485760;function Z5($={}){let J=$.directory??t8("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");wJ(J,{recursive:!0,mode:457});let B=$5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");e8(J,457);let G=OJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:jJ(u2(J,M)).mtimeMs})).sort((M,I)=>I.time-M.time);for(let M of G.slice(9))IJ(u2(J,M.name));let U=u2(J,`${LJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??MJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(J5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,C=!1,N=new Promise((M,I)=>{X=M,F=I});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,I)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),I(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(O)=>{try{if(O!==0&&O!==255)throw Error();let R=$5(U);if(!C||!R.isFile()||R.isSymbolicLink()||R.uid!==process.getuid?.()||R.size<128||R.size>J5+65536)throw Error();e8(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),I(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(K)+5)*1000);D.finally(()=>clearTimeout(w)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await N}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function B5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??Q5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AJ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??K5)();return B??=Z5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:j1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as G3}from"child_process";import{createHash as mJ,randomUUID as vJ}from"crypto";import{existsSync as Q0,mkdirSync as Z3,mkdtempSync as U3,readdirSync as d1,readFileSync as X3,renameSync as pJ,rmSync as V1,statSync as m1,writeFileSync as uJ}from"fs";import{homedir as W3,tmpdir as _5}from"os";import{basename as R5,dirname as Q3,join as g,relative as P5,resolve as K3,sep as z5}from"path";var o=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),x1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),V5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),l2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),s2=["home","lock","side_button","siri","apple_pay"],TJ=V.enum(["tree","screenshot","both","none"]),_J=V.object({...l2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:TJ.optional(),wait_for:_J.optional(),timeout:V.number().min(0).max(20).optional()},d2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...l2.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(s2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),c2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:o}).strict(),V.object({action:V.literal("shutdown"),device:o}).strict(),V.object({action:V.literal("build"),path:x1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:o.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:x1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:o.optional(),steps:V.array(V.lazy(()=>d2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:o.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:o.optional(),app_path:x1.optional(),bundle_id:V5.optional(),steps:V.array(V.lazy(()=>d2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:o.optional(),bundle_id:V5}).strict(),V.object({action:V.literal("logs"),device:o.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:o.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:x1.optional()}).strict(),V.object({action:V.literal("chrome"),device:o.optional()}).strict(),V.object({action:V.literal("inspect"),device:o.optional()}).strict(),V.object({action:V.literal("tap"),device:o.optional(),x:Z0.optional(),y:Z0.optional(),...l2.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:o.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:o.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:o.optional(),name:V.enum(s2),...C0}).strict(),V.object({action:V.literal("open_url"),device:o.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:o.optional(),steps:V.array(d2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:o.optional(),mode:V.enum(["light","dark"])}).strict()]),G5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),UV=V.object({text:V.string(),error:V.string().optional(),device:G5.optional(),devices:V.array(G5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var XV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),WV={type:"object",properties:{action:{type:"string",enum:c2.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...s2]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as i2}from"child_process";import{createHash as PJ}from"crypto";import{existsSync as r2,mkdirSync as y1,mkdtempSync as zJ,readdirSync as U5,readFileSync as X5,renameSync as qJ,rmSync as W5,symlinkSync as a2,writeFileSync as K1}from"fs";import{homedir as EJ}from"os";import{dirname as C5,join as b}from"path";import{createInterface as gJ}from"readline";var n2=`// Reason's simulator host: one warm process per booted iOS Simulator.
26
+ `:"")+K.toString("utf8")}}}async function K8($,J){if(!R2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=Z8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=T2(Q.script_gzip),B=T2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=i9(Q8(J$(),"reason-workspace-setup-"));try{let U=Q8(G,"setup.sh");t9(U,K,{mode:384});let W={PATH:Z$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let E of Q$)if(process.env[E])W[E]=process.env[E];Object.assign(W,Q.env);let Y=a9("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=_2(e0),N=_2(e0),C=_2(e0);Y.stdout.on("data",(E)=>{X.push(E),C.push(E)}),Y.stderr.on("data",(E)=>{N.push(E),C.push(E)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let F=(E)=>{try{if(Y.pid)process.kill(-Y.pid,E)}catch{}},D=!1,w,M=()=>{F("SIGTERM"),w??=setTimeout(()=>F("SIGKILL"),K$)},j=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((E,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(I,q)=>E({code:I,signal:q}))}).finally(()=>{clearTimeout(j),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((E)=>{let v=setTimeout(E,B$);Y.once("close",()=>{clearTimeout(v),E()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let R=D?124:O.signal?128+(e9.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,R),stdout:X.text(),stderr:N.text(),...R!==0?{combined:C.text()}:{}}}finally{o9(G,{recursive:!0,force:!0})}}import{chmodSync as V$,mkdtempSync as G$,realpathSync as U8,rmSync as U$}from"fs";import{tmpdir as X$}from"os";import{dirname as W$,join as P2,sep as Y$}from"path";function z2($){return G8($,V8($)!==null).repoPath}function X8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[$1,void 0].map((K)=>W$(B8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=U8(P2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${Y$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function W8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=z2($.runtimeRoot);if(L0(Q)||L0(P2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=G$(P2(X$(),`reason-cloud-copy-${process.pid}-`));try{V$(Z,448);let Q=U8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{U$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as O7,existsSync as G0,fstatSync as j7,lstatSync as I7,mkdirSync as dZ,mkdtempSync as A7,openSync as T7,readSync as lZ,realpathSync as J0,rmSync as _7,statSync as N1,writeSync as sZ}from"fs";import{homedir as W1,platform as l,tmpdir as R7}from"os";import{dirname as Y1,isAbsolute as cZ,join as _3,relative as w3,resolve as nZ,sep as rZ}from"path";import{spawn as aZ}from"child_process";import{createHash as D$,randomBytes as M$}from"crypto";var q2=30000,F$=1800000,N$=5000,q1=30000,C$=g1+15000,Y8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,H$=[/^\/app\/local-runtime\/operations\/claim$/,Y8];class E2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(H$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},C$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(N$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(F$,q2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(E1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+q2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!Y8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(q2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var S2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function RB($,J={}){let Z=L$($),Q=J.rootPathsSupported===!0?D1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function L$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class S1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function w$($){return $===408||$===429||$===500||$===502||$===503||$===504}function O$($){if($ instanceof Y0)return!1;if($ instanceof S1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function j$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function I$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function PB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function F8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function N8($){return D$("sha256").update($??"").digest("hex")}function A$($){return L8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function C8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var T$=20000,_$=1e4,H8=[2000,4000],R$=30000,P$=15000;function D8($){return $?{keepalive:!1}:{}}class g2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class z${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=w8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??H8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof g2))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new g2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...D8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return O8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=T$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,H8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=_$?B:null,W=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=N8(J),N=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":N.timestamp,"x-device-nonce":N.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":N.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>M$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(A$({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!M8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new E2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",E1,Q,N8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&F8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??I$,W=this.sessionFor($,J.device),Y=Math.max(R$,(J.holdMs??0)+P$),X={fresh:!1},N;for(let C=0;C<G;C+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new S1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let j=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,M,J.useSpareChallenge===!0&&C===0,C===0?J.issuedChallenge:void 0,X),O=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...j,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...D8(X.fresh),signal:M});return await this.parseResponse(O)}catch(j){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw j}finally{clearTimeout(w)}}catch(F){if(N=F,F instanceof S1)X.fresh=!0;if(J.signal?.aborted)throw F;let D=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),w=F instanceof Y0&&w$(F.status),M=O$(F),j=J.transientRetryOwner!=="caller"&&(w||M);if((D||j)&&C+1<G){let O=D?0:j$(C,F,this.proofOptions.retryBaseDelayMs??500);if(O>0)await U(O,J.signal);continue}if(D&&C+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw N??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return j8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return I8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return A8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return T8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return _8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return R8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});z8(Q)}async localSubscription($,J,Z){return P8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!C8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,g1))},signal:J.signal});if(B===null)return null;return q8(B,S2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return E8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!C8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return g8(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(F8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return k8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-p2bvtf6p.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return S8(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var q$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),J1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function k1($,J){if(q$.has($))return!1;if(J1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||J1.has($)))return!1;return!0}import{accessSync as E$,constants as g$,existsSync as S$,statSync as k$}from"fs";import{basename as f$,isAbsolute as b$}from"path";var Z1=["-lic"],x$="/bin/zsh",y$=new Set(["zsh","bash"]),f8=20000,k2=60000,h$=65536,m$=64,v$=8192,p$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),u$=["DYLD_","LD_"];function d$($){let J=$.toUpperCase();return p$.has(J)||u$.some((Z)=>J.startsWith(Z))}function b8($=process.env){return!0}function l$($){if(!b$($)||$.includes("\x00"))return!1;if(!y$.has(f$($)))return!1;try{if(!k$($).isFile())return!1;return E$($,g$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&l$(J))return J;return x$}function f2($=process.env){return b8($)&&S$(E0($))}function b2($=process.env){if(!b8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function x2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>h$)throw new H("invalid_payload","command is missing or too large.");return $}function y2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>m$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>v$)throw new H("invalid_payload","env entry is invalid or too large.");if(d$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function x8($){let J=$.processEnv??process.env;if(b2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=x2($.command),Q=E0(J),{forwarded:K,ignored:B}=y2($.requestEnv),G=await $.spawn(Q,[...Z1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...Z1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function y8($=process.env){return{transport:"shell",shell:`${E0($)} ${Z1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:k2}}import{readFile as s$,readdir as c$,readlink as n$,realpath as r$}from"fs/promises";import{basename as a$,relative as i$,sep as o$}from"path";var w0="/proc",t$=250,h8=500,e$=50,$J=250,JJ=1024,m8=4096,ZJ=1,QJ=3,v8=9,KJ="0A",BJ=/^socket:\[(\d+)\]$/,h2={readDirectory:($)=>c$($),readLink:($)=>n$($),readTextFile:($)=>s$($,"utf8"),realPath:($)=>r$($)};function u8($,J){return J===$||J.startsWith(`${$}${o$}`)}function VJ($,J){return i$($,J)||"."}async function d8($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function l8($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,m8).split(`
27
+ `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${w0}/${$}/cmdline`)).slice(0,m8).split("\x00",1)[0]?.trim();return Q?a$(Q):null}catch{return null}}async function s8($,J=h2){let Z;try{Z=await J.readLink(`${w0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function c8($,J=h2){let Z=[];for(let Q of await d8(J)){if(Z.length>=t$)break;let K=await s8(Q,J);if(!K||!u8($,K))continue;Z.push({pid:Q,command:await l8(Q,J),cwd:VJ($,K)})}return{processes:Z}}function p8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function GJ($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(K<0)K=W;continue}if(K>=0){let Y=W-K;if(Y>Q)Z=K,Q=Y;K=-1}}let B=J.map((W)=>W.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function UJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=p8($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...p8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${GJ(Z)}]:${J}`}return null}function XJ($,J){let Z=[];for(let Q of $.split(`
28
+ `).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=v8)continue;if(K[QJ]?.toUpperCase()!==KJ)continue;let B=K[ZJ]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=UJ(B.slice(0,G),U),Y=K[v8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function WJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=h8)break;let Q;try{Q=await $.readTextFile(`${w0}/net/${Z}`)}catch{continue}J.push(...XJ(Q,h8-J.length))}return J}async function YJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await d8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${w0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,JJ)){let G;try{G=await J.readLink(`${w0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(BJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function n8($,J=h2){let Z=await WJ(J),Q=await YJ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let N=Q.get(X.inode);if(N===void 0)continue;K.push({pid:N,port:X.port,address:X.address})}K.sort((X,N)=>X.pid-N.pid||X.port-N.port||(X.address<N.address?-1:X.address>N.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,e$),G=await Promise.all(B.map(async(X)=>[X,await s8(X,J)])),U=new Map(G),W=K.filter((X)=>{let N=U.get(X.pid);return Boolean(N&&u8($,N))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await l8(X,J)])));return{ports:W.slice(0,$J).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as v2}from"path";var f1=200,FJ=250,NJ=250;async function b1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function m2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var r8="/System/Volumes/Data",CJ=["/tmp","/var","/etc"];function p2($){let J=v2.normalize($);if(J.startsWith(`${r8}/`))J=J.slice(r8.length);return CJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function a8($){return $&&v2.isAbsolute($)?p2($):null}async function i8($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=f1){let K=J.slice(Q,Q+f1).join(",");for(let B of await b1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:a8(B.names[0])})}return Z}async function o8($,J){let Z=p2($),Q=(await b1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=a8(B.names[0]);return G!==null&&m2(Z,G)}).map((B)=>B.pid).slice(0,FJ),K=await i8(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&m2(Z,G.cwd)?[{pid:B,command:G.command,cwd:v2.relative(Z,G.cwd)||"."}]:[]})}}async function t8($,J){let Z=p2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await b1(J,Q),B=await i8(J,K.map((Y)=>Y.pid)),G=K.map((Y)=>Y.pid).filter((Y)=>{let X=B.get(Y)?.cwd;return Boolean(X&&m2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=f1){let X=G.slice(Y,Y+f1).join(",");for(let N of await b1(J,["-a","-p",X,...Q]))for(let C of N.names)if(U.has(`${N.pid} ${C}`))W.push({pid:N.pid,command:N.command,address:C})}return{ports:W.slice(0,NJ)}}import{join as PJ}from"path";import{spawn as jJ}from"child_process";import{randomUUID as IJ}from"crypto";import{chmodSync as J5,lstatSync as Z5,mkdirSync as AJ,readdirSync as TJ,statSync as _J,unlinkSync as RJ}from"fs";import{join as d2}from"path";function Q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var u2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var x1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var O0=()=>{throw Error("proof_visual_contract_invalid")};class e8 extends Error{constructor(){super("proof_visual_contract_invalid")}}function DJ($){if(!Q1($)||$.version!==1)return O0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new e8;if(!Q1($.viewport)||!x1($.viewport.width,1,4096)||!x1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>u2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return O0();let J=$.targets.map((Q)=>{if(!Q1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return O0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return O0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return O0();Z=$.additionalViewports.map((K)=>{if(!Q1(K)||!x1(K.width,1,4096)||!Number.isInteger(K.width)||!x1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return O0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return O0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var LJ=["organizationId","userId","sessionId","runId"],wJ=[...LJ,"prUrl","headSha","skillDigest","evidenceKind"],nB=[...wJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var OJ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function $5($){return OJ[$].directory}var Q5=10485760;function K5($={}){let J=$.directory??$5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");AJ(J,{recursive:!0,mode:457});let B=Z5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");J5(J,457);let G=TJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:_J(d2(J,M)).mtimeMs})).sort((M,j)=>j.time-M.time);for(let M of G.slice(9))RJ(d2(J,M.name));let U=d2(J,`${IJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??jJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(Q5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,N,C=!1,F=new Promise((M,j)=>{X=M,N=j});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,j)=>{Y.once("error",()=>{N(Error("cloud_browser_recording_unavailable")),j(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(O)=>{try{if(O!==0&&O!==255)throw Error();let R=Z5(U);if(!C||!R.isFile()||R.isSymbolicLink()||R.uid!==process.getuid?.()||R.size<128||R.size>Q5+65536)throw Error();J5(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{N(Error("cloud_browser_recording_failed")),j(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(K)+5)*1000);D.finally(()=>clearTimeout(w)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await F}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function G5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??B5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=PJ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??V5)();return B??=K5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:j1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as U3}from"child_process";import{createHash as dJ,randomUUID as lJ}from"crypto";import{existsSync as Q0,mkdirSync as Q3,mkdtempSync as X3,readdirSync as l1,readFileSync as W3,renameSync as sJ,rmSync as V1,statSync as v1,writeFileSync as cJ}from"fs";import{homedir as Y3,tmpdir as P5}from"os";import{basename as z5,dirname as K3,join as g,relative as q5,resolve as B3,sep as E5}from"path";var o=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),y1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),U5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),s2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),c2=["home","lock","side_button","siri","apple_pay"],zJ=V.enum(["tree","screenshot","both","none"]),qJ=V.object({...s2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:zJ.optional(),wait_for:qJ.optional(),timeout:V.number().min(0).max(20).optional()},l2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...s2.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(c2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),n2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:o}).strict(),V.object({action:V.literal("shutdown"),device:o}).strict(),V.object({action:V.literal("build"),path:y1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:o.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:y1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:o.optional(),steps:V.array(V.lazy(()=>l2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:o.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:o.optional(),app_path:y1.optional(),bundle_id:U5.optional(),steps:V.array(V.lazy(()=>l2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:o.optional(),bundle_id:U5}).strict(),V.object({action:V.literal("logs"),device:o.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:o.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:y1.optional()}).strict(),V.object({action:V.literal("chrome"),device:o.optional()}).strict(),V.object({action:V.literal("inspect"),device:o.optional()}).strict(),V.object({action:V.literal("tap"),device:o.optional(),x:Z0.optional(),y:Z0.optional(),...s2.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:o.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:o.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:o.optional(),name:V.enum(c2),...C0}).strict(),V.object({action:V.literal("open_url"),device:o.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:o.optional(),steps:V.array(l2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:o.optional(),mode:V.enum(["light","dark"])}).strict()]),X5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),FV=V.object({text:V.string(),error:V.string().optional(),device:X5.optional(),devices:V.array(X5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var NV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),CV={type:"object",properties:{action:{type:"string",enum:n2.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...c2]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as o2}from"child_process";import{createHash as gJ}from"crypto";import{existsSync as a2,mkdirSync as h1,mkdtempSync as SJ,readdirSync as W5,readFileSync as Y5,renameSync as kJ,rmSync as F5,symlinkSync as i2,writeFileSync as K1}from"fs";import{homedir as fJ}from"os";import{dirname as D5,join as b}from"path";import{createInterface as bJ}from"readline";var r2=`// Reason's simulator host: one warm process per booted iOS Simulator.
29
29
  //
30
30
  // Built on the Mac on first use (cli/simulator-host.ts) against the MIT
31
31
  // FBSimulatorControl frameworks that the pinned AXe ships, so loading
@@ -484,33 +484,33 @@ case "stream":
484
484
  default:
485
485
  fail("usage: simulator-host serve|stream <udid> ...")
486
486
  }
487
- `;var Y5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",SJ=180000,kJ=15000,fJ=30000,bJ=600000,xJ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
487
+ `;var N5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",xJ=180000,yJ=15000,hJ=30000,mJ=600000,vJ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
488
488
  @end
489
- `).join("");function F5($,J,Z){return new Promise((Q)=>{let K=i2($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),B="";K.stdout.on("data",(G)=>{B+=G}),K.stderr.on("data",(G)=>{B+=G}),K.once("error",(G)=>Q({code:-1,output:String(G)})),K.once("close",(G)=>Q({code:G??-1,output:B}))})}var N5=new Map;function o2($){let J=b(C5($),"Frameworks"),Z=N5.get(J);if(!Z)N5.set(J,Z=yJ(J));return Z}async function yJ($){if(process.platform!=="darwin"||!r2(b($,"FBSimulatorControl.framework")))return null;let J=await F5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=PJ("sha256").update(n2).update(J.output).update($).digest("hex").slice(0,16),Q=b(EJ(),".local","share","reason","simulator","host"),K=b(Q,Z,"simulator-host");if(r2(K))return K;y1(Q,{recursive:!0,mode:448});let B=zJ(b(Q,".staging-"));try{let G=b(B,"Frameworks"),U=b(G,"FBSimulatorControl.framework"),W=b(U,"Modules","FBSimulatorControl.swiftmodule");y1(W,{recursive:!0});for(let w of U5($))if(w!=="FBSimulatorControl.framework")a2(b($,w),b(G,w));let Y=b($,"FBSimulatorControl.framework");a2(b(Y,"FBSimulatorControl"),b(U,"FBSimulatorControl")),a2(b(Y,"Headers"),b(U,"Headers")),K1(b(U,"Modules","module.modulemap"),X5(b(Y,"Modules","module.modulemap")));let X=X5(b(Y,"Modules","FBSimulatorControl.swiftmodule",`${Y5}.swiftinterface`),"utf8");K1(b(W,`${Y5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let F=b(B,"include","CoreSimulator");y1(F,{recursive:!0}),K1(b(F,"module.modulemap"),`module CoreSimulator {
489
+ `).join("");function C5($,J,Z){return new Promise((Q)=>{let K=o2($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),B="";K.stdout.on("data",(G)=>{B+=G}),K.stderr.on("data",(G)=>{B+=G}),K.once("error",(G)=>Q({code:-1,output:String(G)})),K.once("close",(G)=>Q({code:G??-1,output:B}))})}var H5=new Map;function t2($){let J=b(D5($),"Frameworks"),Z=H5.get(J);if(!Z)H5.set(J,Z=pJ(J));return Z}async function pJ($){if(process.platform!=="darwin"||!a2(b($,"FBSimulatorControl.framework")))return null;let J=await C5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=gJ("sha256").update(r2).update(J.output).update($).digest("hex").slice(0,16),Q=b(fJ(),".local","share","reason","simulator","host"),K=b(Q,Z,"simulator-host");if(a2(K))return K;h1(Q,{recursive:!0,mode:448});let B=SJ(b(Q,".staging-"));try{let G=b(B,"Frameworks"),U=b(G,"FBSimulatorControl.framework"),W=b(U,"Modules","FBSimulatorControl.swiftmodule");h1(W,{recursive:!0});for(let w of W5($))if(w!=="FBSimulatorControl.framework")i2(b($,w),b(G,w));let Y=b($,"FBSimulatorControl.framework");i2(b(Y,"FBSimulatorControl"),b(U,"FBSimulatorControl")),i2(b(Y,"Headers"),b(U,"Headers")),K1(b(U,"Modules","module.modulemap"),Y5(b(Y,"Modules","module.modulemap")));let X=Y5(b(Y,"Modules","FBSimulatorControl.swiftmodule",`${N5}.swiftinterface`),"utf8");K1(b(W,`${N5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let N=b(B,"include","CoreSimulator");h1(N,{recursive:!0}),K1(b(N,"module.modulemap"),`module CoreSimulator {
490
490
  header "CoreSimulator.h"
491
491
  export *
492
492
  }
493
- `),K1(b(F,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
494
- ${xJ}`);let C=b(B,"main.swift");K1(C,n2);let N=b(B,"simulator-host"),D=await F5("xcrun",["swiftc","-O","-F",G,"-I",b(B,"include"),"-module-cache-path",b(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,C,"-o",N],SJ);if(D.code!==0||!r2(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
493
+ `),K1(b(N,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
494
+ ${vJ}`);let C=b(B,"main.swift");K1(C,r2);let F=b(B,"simulator-host"),D=await C5("xcrun",["swiftc","-O","-F",G,"-I",b(B,"include"),"-module-cache-path",b(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,C,"-o",F],xJ);if(D.code!==0||!a2(F))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
495
495
  ${D.output.slice(-2000)}
496
- `),null;y1(C5(K),{recursive:!0}),qJ(N,K);for(let w of U5(Q))if(w!==Z&&!w.startsWith(".staging-"))W5(b(Q,w),{recursive:!0,force:!0});return K}catch{return null}finally{W5(B,{recursive:!0,force:!0})}}class B1 extends Error{}class S0 extends Error{}class H5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;gJ({input:$.stdout}).on("line",(Q)=>{let K;try{K=JSON.parse(Q)}catch{return}let B=this.pending.get(Number(K.id));if(!B)return;if(this.pending.delete(Number(K.id)),clearTimeout(B.timer),K.ok===!0)B.resolve(K);else B.reject(new B1(String(K.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new S0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let K=setTimeout(()=>{this.pending.delete(J),Q(new S0("The simulator host did not answer.")),this.close()},fJ);this.pending.set(J,{resolve:Z,reject:Q,timer:K}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
497
- `)})}close(){if(this.child.exitCode===null&&this.child.signalCode===null)this.child.kill("SIGTERM");this.end()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>this.close(),bJ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new S0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var g0=new Map;async function h1($,J,Z=!1){let Q=g0.get(J);if(!Q){let K={started:hJ($,J)};g0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&g0.get(J)===K)g0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function hJ($,J){let Z=await o2($);if(!Z)return null;let Q=i2(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),kJ);Q.stdout.once("data",(W)=>{clearTimeout(U),G(String(W).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(U),G(!1)}),Q.once("error",()=>{clearTimeout(U),G(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let B=new H5(Q,()=>{let G=g0.get(J);if(G&&(G.host===B||G.host===void 0))g0.delete(J)});return B}function D5($,J,Z,Q,K){return i2($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var k0={version:"1.8.0",url:"https://github.com/cameroncooke/AXe/releases/download/v1.8.0/AXe-macOS-v1.8.0-universal.tar.gz",sha256:"7b76340b72e90d0f211bc7c4636f15009076eff07acef2f2b632b175debd8834"},dJ=50000,lJ=112640,sJ=174080,t2=2,cJ=60000,nJ=2000,rJ=300,aJ=40,iJ=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function x0($,J,Z={}){return new Promise((Q,K)=>{let B=G3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],U=[];B.stdout.on("data",(Y)=>G.push(Y)),B.stderr.on("data",(Y)=>U.push(Y));let W=setTimeout(()=>B.kill("SIGKILL"),Z.timeoutMs??dJ);B.on("error",(Y)=>{clearTimeout(W),K(Y)}),B.on("close",(Y)=>{clearTimeout(W),Q({code:Y??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function f($,J){throw new H($,J)}async function n($,J,Z,Q={}){let K=await x0($,J,Q);if(K.code!==0)f("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function G1(){return process.platform==="darwin"&&Q0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Q0("/usr/bin/xcrun")}var e2=null;function j0(){return g(W3(),".local","share","reason","simulator","axe")}function Y3(){let $=g(j0(),k0.version,"axe");if(Q0($))return Promise.resolve($);return e2??=(async()=>{Z3(j0(),{recursive:!0,mode:448});let J=U3(g(j0(),".staging-"));try{let Z=g(J,"axe.tgz");await T5(k0.url,k0.sha256,Z);let Q=g(J,"tree");if(Z3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!Q0(g(Q,"axe"))||!Q0(g(Q,"Frameworks")))f("simulator_axe_missing","The AXe archive has an unexpected layout.");V1(g(j0(),k0.version),{recursive:!0,force:!0}),pJ(Q,g(j0(),k0.version));for(let K of d1(j0()))if(K!==k0.version&&!K.startsWith(".staging-"))V1(g(j0(),K),{recursive:!0,force:!0});return $}finally{V1(J,{recursive:!0,force:!0}),e2=null}})(),e2}var q5=Y3;async function E5($){let J=await Y3().catch(()=>null);return J?h1(J,$.udid).catch(()=>null):null}async function v1($,J,Z){let Q=await Y3().catch(()=>f("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await x0(Q,[...$,"--udid",J]);if(K.code===0)return K.stdout;let B=(K.stderr||K.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(B))f("simulator_element_not_found",B.slice(-500));return f("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function oJ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function tJ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function F3(){let J=JSON.parse(await n("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,K]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let B of K){if(B.isAvailable===!1)continue;let G=B.name.toLowerCase();if(B.deviceTypeIdentifier)B3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:oJ(Q),state:tJ(B.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,K)=>Number(K.state==="booted")-Number(Q.state==="booted")||K.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(K.name))}var B3=new Map,V3=null;async function t($,J){let Z=await F3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)f("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let K=Z.filter((B)=>B.state==="booted");if(Q=K.find((B)=>B.udid===V3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)f("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")f("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return V3=Q.udid,Q}function h($){return`${$.name} (${$.runtime})`}async function eJ($){if($.state!=="booted"){let J=await x0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))f("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await n("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return V3=$.udid,{...$,state:"booted"}}function N3($,J){let Z=K3($,J),Q=P5($,Z);if(Q.startsWith("..")||Q.startsWith(z5)||K3($,Q)!==Z)f("simulator_path_outside_root",`${J} is outside this machine's granted folder (${$}). Pass a path inside it, or one relative to it.`);return Z}var M5=4,$Z=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function JZ($){let J=[],Z=(Q,K)=>{let B;try{B=d1(Q)}catch{return}if(B.includes("project.yml")||B.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=M5)return;for(let G of B.sort()){if(G.startsWith(".")||$Z.has(G))continue;let U=g(Q,G);try{if(m1(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)f("simulator_project_not_found",`No Xcode project or project.yml within ${M5} folders of ${$}; pass path.`);return f("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>P5($,Q)||".").join(", ")}.`)}var b0=new Map;async function ZZ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:Q3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:Q3($)};if(!m1($).isDirectory())f("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>d1($).filter((B)=>B.endsWith(K)).sort();if(Q0(g($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>Q0("/opt/homebrew/bin/xcodegen")?n("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(K));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:g($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:g($,Q),dir:$};return f("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function g5($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function QZ($){let J=(await g5($))[0];if(!J)f("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function KZ($){let J=[],Z=new Set;return $.forEach((Q,K)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let B=$.slice(K+1,K+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...B].join(`
498
- `).slice(0,800))}),J}async function BZ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await g5(Z).catch(()=>[]);if(B.length)$.log.push(`error: this project's schemes are: ${B.join(", ")}`)}$.status="failed";return}let Q=g($.productsDir,`${$.configuration}-iphonesimulator`),K=Q0(Q)?d1(Q).filter((B)=>B.endsWith(".app")).map((B)=>g(Q,B)).sort((B,G)=>m1(G).mtimeMs-m1(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await f5($.appPath).catch(()=>{return});if($.status=$.appPath?"succeeded":"failed",!$.appPath)$.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function L5($,J){let Z=$.path?N3(J,$.path):JZ(J),Q=await ZZ(Z),K=$.scheme??await QZ(Q),B=$.configuration??"Debug",G=await t($.device,{booted:!1}).catch(()=>null),U=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",W=mJ("sha256").update(Q.path).digest("hex").slice(0,16),Y=g(W3(),"Library","Caches","reason","simulator-builds",W),X={id:`build-${vJ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:g(Y,"Build","Products"),configuration:B};b0.set(X.id,X);for(let[D,w]of b0)if(b0.size>20&&w.status!=="running")b0.delete(D);let F=G3("xcodebuild",[Q.flag,Q.path,"-scheme",K,"-configuration",B,"-destination",U,"-derivedDataPath",Y,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),C="",N=(D)=>{let w=(C+D.toString("utf8")).split(`
499
- `);if(C=w.pop()??"",X.log.push(...w),X.log.length>5000)X.log.splice(0,X.log.length-5000)};return F.stdout.on("data",N),F.stderr.on("data",N),F.on("error",(D)=>{X.log.push(`error: ${D.message}`),X.status="failed",X.ended=Date.now()}),F.on("close",(D)=>{if(C)X.log.push(C);BZ(X,D??-1,Q)}),{text:`Build ${X.id} started: ${K} (${B}) for ${G?h(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:S5(X)}}function S5($){return{id:$.id,status:$.status,errors:KZ($.log),log_tail:$.log.slice(-aJ).join(`
500
- `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var VZ=45000,GZ=30000;async function $3($,J=VZ){let Z=Date.now()+J;while(b0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=k5($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function k5($){let J=b0.get($);if(!J)f("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=S5(J);return{text:J.status==="running"?`Build ${$} is running (${Math.round(Z.elapsed_ms/1000)} s).`:J.status==="succeeded"?`Build ${$} succeeded: ${J.appPath}. Launch it with app_path.`:`Build ${$} failed with ${Z.errors.length} error(s).`,build:Z}}async function f5($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",g($,"Info.plist")],"Reading the bundle id")).trim()}var H0=new Map;function UZ($,J){H0.get($.udid)?.stop();let Z=G3("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",$.udid,J],{stdio:["ignore","pipe","pipe"]}),Q={udid:$.udid,bundleId:J,lines:[],first:0,stop:()=>Z.kill("SIGTERM")};H0.set($.udid,Q);let K="",B=(G)=>{let U=(K+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
501
- `);K=U.pop()??"",Q.lines.push(...U);let W=Q.lines.length-nJ;if(W>0)Q.lines.splice(0,W),Q.first+=W};return Z.stdout.on("data",B),Z.stderr.on("data",B),new Promise((G)=>{let U=setTimeout(()=>G(null),15000),W=()=>{let Y=Q.lines.concat(K).join(`
502
- `).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(Y)clearTimeout(U),G(Number(Y))};Z.stdout.on("data",W),Z.on("close",()=>{clearTimeout(U),G(null)})})}async function XZ($,J){let Z=await t($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=WZ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,B],`Installing ${R5(B)}`),Q=await f5(B)}if($.bundle_id){if((await x0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)f("simulator_app_not_installed",`${$.bundle_id} is not installed on ${h(Z)}.`)}let K=await UZ(Z,Q);if(K===null){let B=H0.get(Z.udid)?.lines.slice(-20).join(`
496
+ `),null;h1(D5(K),{recursive:!0}),kJ(F,K);for(let w of W5(Q))if(w!==Z&&!w.startsWith(".staging-"))F5(b(Q,w),{recursive:!0,force:!0});return K}catch{return null}finally{F5(B,{recursive:!0,force:!0})}}class B1 extends Error{}class S0 extends Error{}class M5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;bJ({input:$.stdout}).on("line",(Q)=>{let K;try{K=JSON.parse(Q)}catch{return}let B=this.pending.get(Number(K.id));if(!B)return;if(this.pending.delete(Number(K.id)),clearTimeout(B.timer),K.ok===!0)B.resolve(K);else B.reject(new B1(String(K.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new S0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let K=setTimeout(()=>{this.pending.delete(J),Q(new S0("The simulator host did not answer.")),this.close()},hJ);this.pending.set(J,{resolve:Z,reject:Q,timer:K}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
497
+ `)})}close(){if(this.child.exitCode===null&&this.child.signalCode===null)this.child.kill("SIGTERM");this.end()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>this.close(),mJ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new S0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var g0=new Map;async function m1($,J,Z=!1){let Q=g0.get(J);if(!Q){let K={started:uJ($,J)};g0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&g0.get(J)===K)g0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function uJ($,J){let Z=await t2($);if(!Z)return null;let Q=o2(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),yJ);Q.stdout.once("data",(W)=>{clearTimeout(U),G(String(W).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(U),G(!1)}),Q.once("error",()=>{clearTimeout(U),G(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let B=new M5(Q,()=>{let G=g0.get(J);if(G&&(G.host===B||G.host===void 0))g0.delete(J)});return B}function L5($,J,Z,Q,K){return o2($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var k0={version:"1.8.0",url:"https://github.com/cameroncooke/AXe/releases/download/v1.8.0/AXe-macOS-v1.8.0-universal.tar.gz",sha256:"7b76340b72e90d0f211bc7c4636f15009076eff07acef2f2b632b175debd8834"},nJ=50000,rJ=112640,aJ=174080,e2=2,iJ=60000,oJ=2000,tJ=300,eJ=40,$Z=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function x0($,J,Z={}){return new Promise((Q,K)=>{let B=U3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],U=[];B.stdout.on("data",(Y)=>G.push(Y)),B.stderr.on("data",(Y)=>U.push(Y));let W=setTimeout(()=>B.kill("SIGKILL"),Z.timeoutMs??nJ);B.on("error",(Y)=>{clearTimeout(W),K(Y)}),B.on("close",(Y)=>{clearTimeout(W),Q({code:Y??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function f($,J){throw new H($,J)}async function n($,J,Z,Q={}){let K=await x0($,J,Q);if(K.code!==0)f("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function G1(){return process.platform==="darwin"&&Q0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Q0("/usr/bin/xcrun")}var $3=null;function j0(){return g(Y3(),".local","share","reason","simulator","axe")}function F3(){let $=g(j0(),k0.version,"axe");if(Q0($))return Promise.resolve($);return $3??=(async()=>{Q3(j0(),{recursive:!0,mode:448});let J=X3(g(j0(),".staging-"));try{let Z=g(J,"axe.tgz");await R5(k0.url,k0.sha256,Z);let Q=g(J,"tree");if(Q3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!Q0(g(Q,"axe"))||!Q0(g(Q,"Frameworks")))f("simulator_axe_missing","The AXe archive has an unexpected layout.");V1(g(j0(),k0.version),{recursive:!0,force:!0}),sJ(Q,g(j0(),k0.version));for(let K of l1(j0()))if(K!==k0.version&&!K.startsWith(".staging-"))V1(g(j0(),K),{recursive:!0,force:!0});return $}finally{V1(J,{recursive:!0,force:!0}),$3=null}})(),$3}var g5=F3;async function S5($){let J=await F3().catch(()=>null);return J?m1(J,$.udid).catch(()=>null):null}async function p1($,J,Z){let Q=await F3().catch(()=>f("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await x0(Q,[...$,"--udid",J]);if(K.code===0)return K.stdout;let B=(K.stderr||K.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(B))f("simulator_element_not_found",B.slice(-500));return f("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function JZ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function ZZ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function N3(){let J=JSON.parse(await n("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,K]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let B of K){if(B.isAvailable===!1)continue;let G=B.name.toLowerCase();if(B.deviceTypeIdentifier)V3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:JZ(Q),state:ZZ(B.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,K)=>Number(K.state==="booted")-Number(Q.state==="booted")||K.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(K.name))}var V3=new Map,G3=null;async function t($,J){let Z=await N3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)f("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let K=Z.filter((B)=>B.state==="booted");if(Q=K.find((B)=>B.udid===G3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)f("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")f("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return G3=Q.udid,Q}function h($){return`${$.name} (${$.runtime})`}async function QZ($){if($.state!=="booted"){let J=await x0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))f("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await n("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return G3=$.udid,{...$,state:"booted"}}function C3($,J){let Z=B3($,J),Q=q5($,Z);if(Q.startsWith("..")||Q.startsWith(E5)||B3($,Q)!==Z)f("simulator_path_outside_root",`${J} is outside this machine's granted folder (${$}). Pass a path inside it, or one relative to it.`);return Z}var w5=4,KZ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function BZ($){let J=[],Z=(Q,K)=>{let B;try{B=l1(Q)}catch{return}if(B.includes("project.yml")||B.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=w5)return;for(let G of B.sort()){if(G.startsWith(".")||KZ.has(G))continue;let U=g(Q,G);try{if(v1(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)f("simulator_project_not_found",`No Xcode project or project.yml within ${w5} folders of ${$}; pass path.`);return f("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>q5($,Q)||".").join(", ")}.`)}var b0=new Map;async function VZ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:K3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:K3($)};if(!v1($).isDirectory())f("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>l1($).filter((B)=>B.endsWith(K)).sort();if(Q0(g($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>Q0("/opt/homebrew/bin/xcodegen")?n("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(K));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:g($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:g($,Q),dir:$};return f("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function k5($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function GZ($){let J=(await k5($))[0];if(!J)f("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function UZ($){let J=[],Z=new Set;return $.forEach((Q,K)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let B=$.slice(K+1,K+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...B].join(`
498
+ `).slice(0,800))}),J}async function XZ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await k5(Z).catch(()=>[]);if(B.length)$.log.push(`error: this project's schemes are: ${B.join(", ")}`)}$.status="failed";return}let Q=g($.productsDir,`${$.configuration}-iphonesimulator`),K=Q0(Q)?l1(Q).filter((B)=>B.endsWith(".app")).map((B)=>g(Q,B)).sort((B,G)=>v1(G).mtimeMs-v1(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await x5($.appPath).catch(()=>{return});if($.status=$.appPath?"succeeded":"failed",!$.appPath)$.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function O5($,J){let Z=$.path?C3(J,$.path):BZ(J),Q=await VZ(Z),K=$.scheme??await GZ(Q),B=$.configuration??"Debug",G=await t($.device,{booted:!1}).catch(()=>null),U=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",W=dJ("sha256").update(Q.path).digest("hex").slice(0,16),Y=g(Y3(),"Library","Caches","reason","simulator-builds",W),X={id:`build-${lJ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:g(Y,"Build","Products"),configuration:B};b0.set(X.id,X);for(let[D,w]of b0)if(b0.size>20&&w.status!=="running")b0.delete(D);let N=U3("xcodebuild",[Q.flag,Q.path,"-scheme",K,"-configuration",B,"-destination",U,"-derivedDataPath",Y,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),C="",F=(D)=>{let w=(C+D.toString("utf8")).split(`
499
+ `);if(C=w.pop()??"",X.log.push(...w),X.log.length>5000)X.log.splice(0,X.log.length-5000)};return N.stdout.on("data",F),N.stderr.on("data",F),N.on("error",(D)=>{X.log.push(`error: ${D.message}`),X.status="failed",X.ended=Date.now()}),N.on("close",(D)=>{if(C)X.log.push(C);XZ(X,D??-1,Q)}),{text:`Build ${X.id} started: ${K} (${B}) for ${G?h(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:f5(X)}}function f5($){return{id:$.id,status:$.status,errors:UZ($.log),log_tail:$.log.slice(-eJ).join(`
500
+ `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var WZ=45000,YZ=30000;async function J3($,J=WZ){let Z=Date.now()+J;while(b0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=b5($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function b5($){let J=b0.get($);if(!J)f("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=f5(J);return{text:J.status==="running"?`Build ${$} is running (${Math.round(Z.elapsed_ms/1000)} s).`:J.status==="succeeded"?`Build ${$} succeeded: ${J.appPath}. Launch it with app_path.`:`Build ${$} failed with ${Z.errors.length} error(s).`,build:Z}}async function x5($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",g($,"Info.plist")],"Reading the bundle id")).trim()}var H0=new Map;function FZ($,J){H0.get($.udid)?.stop();let Z=U3("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",$.udid,J],{stdio:["ignore","pipe","pipe"]}),Q={udid:$.udid,bundleId:J,lines:[],first:0,stop:()=>Z.kill("SIGTERM")};H0.set($.udid,Q);let K="",B=(G)=>{let U=(K+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
501
+ `);K=U.pop()??"",Q.lines.push(...U);let W=Q.lines.length-oJ;if(W>0)Q.lines.splice(0,W),Q.first+=W};return Z.stdout.on("data",B),Z.stderr.on("data",B),new Promise((G)=>{let U=setTimeout(()=>G(null),15000),W=()=>{let Y=Q.lines.concat(K).join(`
502
+ `).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(Y)clearTimeout(U),G(Number(Y))};Z.stdout.on("data",W),Z.on("close",()=>{clearTimeout(U),G(null)})})}async function NZ($,J){let Z=await t($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=CZ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,B],`Installing ${z5(B)}`),Q=await x5(B)}if($.bundle_id){if((await x0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)f("simulator_app_not_installed",`${$.bundle_id} is not installed on ${h(Z)}.`)}let K=await FZ(Z,Q);if(K===null){let B=H0.get(Z.udid)?.lines.slice(-20).join(`
503
503
  `)??"";f("simulator_launch_failed",`${Q} did not start on ${h(Z)}.${B?`
504
- ${B}`:""}`)}return{text:`Launched ${Q} on ${h(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function WZ($,J){let Z=K3(J),Q=g(W3(),"Library","Caches","reason","simulator-builds")+z5;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:N3($,Z)}function YZ($,J){let Z=H0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${h($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-rJ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${h($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var p1=new Map;function w5($,...J){let Z=p1.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)f("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function O5($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function C3($,J=1,Z){let Q=U3(g(_5(),"reason-sim-"));try{let K=g(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){Z3(Q3(Z),{recursive:!0});let N=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),D=Number(N.match(/pixelWidth: (\d+)/)?.[1]),w=Number(N.match(/pixelHeight: (\d+)/)?.[1]),M=2/O5($,D);await n("sips",["-z",String(Math.round(w*M)),String(Math.round(D*M)),K,"--out",Z],"Saving the screenshot")}let B=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),G=Number(B.match(/pixelWidth: (\d+)/)?.[1]),U=Number(B.match(/pixelHeight: (\d+)/)?.[1]),W=O5($,G),Y=Math.round(G/W),X=Math.round(U/W);p1.set($.udid,{width:Y,height:X});let F=Buffer.alloc(0),C=J===2?sJ:lJ;for(let N of[70,50,35]){let D=g(Q,`screen-${N}.jpg`);if(await n("sips",["-z",String(X*J),String(Y*J),"-s","format","jpeg","-s","formatOptions",String(N),K,"--out",D],"Encoding the screenshot"),F=X3(D),F.byteLength<=C)break}return{text:`Screenshot of ${h($)} at ${Y}x${X} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:F.toString("base64"),width:Y,height:X}}}finally{V1(Q,{recursive:!0,force:!0})}}async function FZ($){let J=await E5($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return v1(["describe-ui"],$.udid,"Reading the accessibility tree")}async function u1($){let J=JSON.parse(await FZ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(K,B,G="")=>{let U=(K.role??K.type??"?").replace(/^AX/,""),W=K.AXLabel||K.title||"",Y=K.AXValue?` value="${String(K.AXValue).slice(0,120)}"`:"",X=K.AXUniqueId?` id=${K.AXUniqueId}`:"";if(K.AXUniqueId)Z.ids.add(K.AXUniqueId);if(W)Z.labels.add(W);let F=K.frame;if(U==="Application"&&F&&!Z.bounds)Z.bounds={width:F.width,height:F.height};if(F&&F.width>0&&F.height>0&&(K.AXUniqueId||K.AXLabel))Z.targets.push({...K.AXUniqueId?{id:K.AXUniqueId.trim()}:{},...K.AXLabel?{label:K.AXLabel.trim()}:{},role:U,frame:F});let C=Boolean(W||X||Y||!["Group","Other"].includes(U));if(C){let N=`${" ".repeat(Math.min(B,12))}${U} "${W.slice(0,160)}"${X}${Y}`+(F?` (${Math.round(F.x)},${Math.round(F.y)} ${Math.round(F.width)}x${Math.round(F.height)})`:"")+(K.enabled===!1?" disabled":"");Z.lines.push(N);let D=U==="Image"&&!X,w=(U==="StaticText"||U==="Image")&&!X&&W!==""&&G.includes(W);if(!D&&!w)Z.compact.push(N)}for(let N of K.children??[])Q(N,C?B+1:B,W||G)};for(let K of J)Q(K,0);return Z}function b5($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
504
+ ${B}`:""}`)}return{text:`Launched ${Q} on ${h(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function CZ($,J){let Z=B3(J),Q=g(Y3(),"Library","Caches","reason","simulator-builds")+E5;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:C3($,Z)}function HZ($,J){let Z=H0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${h($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-tJ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${h($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var u1=new Map;function j5($,...J){let Z=u1.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)f("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function I5($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function H3($,J=1,Z){let Q=X3(g(P5(),"reason-sim-"));try{let K=g(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){Q3(K3(Z),{recursive:!0});let F=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),D=Number(F.match(/pixelWidth: (\d+)/)?.[1]),w=Number(F.match(/pixelHeight: (\d+)/)?.[1]),M=2/I5($,D);await n("sips",["-z",String(Math.round(w*M)),String(Math.round(D*M)),K,"--out",Z],"Saving the screenshot")}let B=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),G=Number(B.match(/pixelWidth: (\d+)/)?.[1]),U=Number(B.match(/pixelHeight: (\d+)/)?.[1]),W=I5($,G),Y=Math.round(G/W),X=Math.round(U/W);u1.set($.udid,{width:Y,height:X});let N=Buffer.alloc(0),C=J===2?aJ:rJ;for(let F of[70,50,35]){let D=g(Q,`screen-${F}.jpg`);if(await n("sips",["-z",String(X*J),String(Y*J),"-s","format","jpeg","-s","formatOptions",String(F),K,"--out",D],"Encoding the screenshot"),N=W3(D),N.byteLength<=C)break}return{text:`Screenshot of ${h($)} at ${Y}x${X} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:N.toString("base64"),width:Y,height:X}}}finally{V1(Q,{recursive:!0,force:!0})}}async function DZ($){let J=await S5($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return p1(["describe-ui"],$.udid,"Reading the accessibility tree")}async function d1($){let J=JSON.parse(await DZ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(K,B,G="")=>{let U=(K.role??K.type??"?").replace(/^AX/,""),W=K.AXLabel||K.title||"",Y=K.AXValue?` value="${String(K.AXValue).slice(0,120)}"`:"",X=K.AXUniqueId?` id=${K.AXUniqueId}`:"";if(K.AXUniqueId)Z.ids.add(K.AXUniqueId);if(W)Z.labels.add(W);let N=K.frame;if(U==="Application"&&N&&!Z.bounds)Z.bounds={width:N.width,height:N.height};if(N&&N.width>0&&N.height>0&&(K.AXUniqueId||K.AXLabel))Z.targets.push({...K.AXUniqueId?{id:K.AXUniqueId.trim()}:{},...K.AXLabel?{label:K.AXLabel.trim()}:{},role:U,frame:N});let C=Boolean(W||X||Y||!["Group","Other"].includes(U));if(C){let F=`${" ".repeat(Math.min(B,12))}${U} "${W.slice(0,160)}"${X}${Y}`+(N?` (${Math.round(N.x)},${Math.round(N.y)} ${Math.round(N.width)}x${Math.round(N.height)})`:"")+(K.enabled===!1?" disabled":"");Z.lines.push(F);let D=U==="Image"&&!X,w=(U==="StaticText"||U==="Image")&&!X&&W!==""&&G.includes(W);if(!D&&!w)Z.compact.push(F)}for(let F of K.children??[])Q(F,C?B+1:B,W||G)};for(let K of J)Q(K,0);return Z}function y5($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
505
505
  `);return Q.length>J?`${Q.slice(0,J)}
506
- \u2026 (truncated)`:Q}async function NZ($){let J=await u1($);return{text:`Accessibility tree of ${h($)} (frames in points; tap by id or label):
507
- ${b5(J,cJ)}`,device:$}}var CZ=450,HZ=1e4;function DZ($,J){let Z=J.id?$.ids.has(J.id):[...$.labels].some((Q)=>Q===J.label||Q.includes(J.label));return J.gone?!Z:Z}async function I0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let K=null,B="";if(J.wait_for){let U=Date.now()+(J.timeout??5)*1000,W=J.wait_for,Y=W.id?`id ${W.id}`:`"${W.label}"`;for(;;){if(K=await u1($),DZ(K,W)){B=` ${Y} is ${W.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){B=W.gone?` Waited ${J.timeout??5} s: ${Y} is still on screen.`:` Waited ${J.timeout??5} s: ${Y} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(CZ);let G={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await u1($),G.screen=b5(K,HZ,!0),G.text+=`
506
+ \u2026 (truncated)`:Q}async function MZ($){let J=await d1($);return{text:`Accessibility tree of ${h($)} (frames in points; tap by id or label):
507
+ ${y5(J,iJ)}`,device:$}}var LZ=450,wZ=1e4;function OZ($,J){let Z=J.id?$.ids.has(J.id):[...$.labels].some((Q)=>Q===J.label||Q.includes(J.label));return J.gone?!Z:Z}async function I0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let K=null,B="";if(J.wait_for){let U=Date.now()+(J.timeout??5)*1000,W=J.wait_for,Y=W.id?`id ${W.id}`:`"${W.label}"`;for(;;){if(K=await d1($),OZ(K,W)){B=` ${Y} is ${W.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){B=W.gone?` Waited ${J.timeout??5} s: ${Y} is still on screen.`:` Waited ${J.timeout??5} s: ${Y} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(LZ);let G={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await d1($),G.screen=y5(K,wZ,!0),G.text+=`
508
508
  Screen now:
509
- ${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await C3($);G.image=U.image}return G}function j5($){return`'${$.replace(/'/g,"'\\''")}'`}function MZ($){switch($.action){case"tap":if($.x!==void 0&&$.y!==void 0)return $.duration?`touch -x ${$.x} -y ${$.y} --down --up --delay ${$.duration}`:`tap -x ${$.x} -y ${$.y}`;return $.id?`tap --id ${j5($.id)}`:`tap --label ${j5($.label)}`;case"swipe":return`swipe --start-x ${$.x} --start-y ${$.y} --end-x ${$.x2} --end-y ${$.y2} --duration ${$.duration??0.3}`;case"button":return`button ${$.name.replace("_","-")}`;case"sleep":return`sleep ${$.seconds}`}}var x5=0.35,LZ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function wZ($,J){let Z=$.targets.filter((Y)=>J.id!==void 0?Y.id===J.id.trim():Y.label===J.label?.trim()),Q=(Y)=>({x:Y.frame.x+Y.frame.width/2,y:Y.frame.y+Y.frame.height/2}),K=$.bounds,B=K?Z.filter((Y)=>{let{x:X,y:F}=Q(Y);return X>=0&&F>=0&&X<=K.width&&F<=K.height}):Z,G=B.length?B:Z,U=G.filter((Y)=>LZ.has(Y.role)),W=(U.length?U:G)[0];return W?Q(W):null}async function OZ($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let G=wZ(await u1($),J);if(G)return G;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return f("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
509
+ ${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await H3($);G.image=U.image}return G}function A5($){return`'${$.replace(/'/g,"'\\''")}'`}function jZ($){switch($.action){case"tap":if($.x!==void 0&&$.y!==void 0)return $.duration?`touch -x ${$.x} -y ${$.y} --down --up --delay ${$.duration}`:`tap -x ${$.x} -y ${$.y}`;return $.id?`tap --id ${A5($.id)}`:`tap --label ${A5($.label)}`;case"swipe":return`swipe --start-x ${$.x} --start-y ${$.y} --end-x ${$.x2} --end-y ${$.y2} --duration ${$.duration??0.3}`;case"button":return`button ${$.name.replace("_","-")}`;case"sleep":return`sleep ${$.seconds}`}}var h5=0.35,IZ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function AZ($,J){let Z=$.targets.filter((Y)=>J.id!==void 0?Y.id===J.id.trim():Y.label===J.label?.trim()),Q=(Y)=>({x:Y.frame.x+Y.frame.width/2,y:Y.frame.y+Y.frame.height/2}),K=$.bounds,B=K?Z.filter((Y)=>{let{x:X,y:N}=Q(Y);return X>=0&&N>=0&&X<=K.width&&N<=K.height}):Z,G=B.length?B:Z,U=G.filter((Y)=>IZ.has(Y.role)),W=(U.length?U:G)[0];return W?Q(W):null}async function TZ($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let G=AZ(await d1($),J);if(G)return G;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return f("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
510
510
  No accessibility element matched ${U}. Make sure the app is on the expected screen, then inspect it and prefer an id when there is one.
511
- (${Q-1} of ${K} steps had completed.)`)}await Bun.sleep(250)}}async function f0($,J,Z){let Q=await E5($);if(!Q)return I5($,J,Z);for(let[K,B]of J.entries()){try{switch(B.action){case"tap":{let U=B.x!==void 0&&B.y!==void 0?{x:B.x,y:B.y}:await OZ($,B,Z,K+1,J.length);await Q.call(B.duration?{op:"tap",...U,duration:B.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:B.x,y:B.y,x2:B.x2,y2:B.y2,duration:B.duration??0.3});break;case"button":await Q.call({op:"button",name:B.name});break;case"type":await Q.call({op:"text",text:B.text}).catch((U)=>U instanceof B1?v1(["type",B.text],$.udid,`Step ${K+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(B.seconds*1000);break}}catch(U){if(U instanceof S0)return await I5($,J.slice(K),Z),`Ran ${J.length} step(s) on ${h($)}.`;if(U instanceof B1)f("simulator_command_failed",`Step ${K+1} failed: ${U.message}
512
- (${K} of ${J.length} steps had completed.)`);throw U}let G=J[K+1];if(B.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(x5*1000)}return`Ran ${J.length} step(s) on ${h($)}.`}async function I5($,J,Z){let Q=[],K=[],B=0,G=0,U=async()=>{if(Q.length===0)return;let W=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let Y of Q)W.push("--step",Y);try{await v1(W,$.udid,`Steps ${G+1}-${G+B}`)}catch(Y){if(Y instanceof H){let X=Y.message.replace(/Step (\d+) failed/,(F,C)=>{let N=K[Number(C)-1];return N?`Step ${N} failed`:F});f(Y.code,`${X}
513
- (${G} of ${J.length} steps had completed before this batch.)`)}throw Y}G+=B,Q=[],K=[],B=0};for(let[W,Y]of J.entries()){if(Y.action==="type"){await U(),await v1(["type",Y.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(MZ(Y)),B+=1,K.push(W+1);let X=J[W+1];if(Y.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${x5}`),K.push(W+1)}return await U(),`Ran ${J.length} step(s) on ${h($)}.`}var jZ=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],A5=new Map,IZ=`ObjC.import("AppKit");
511
+ (${Q-1} of ${K} steps had completed.)`)}await Bun.sleep(250)}}async function f0($,J,Z){let Q=await S5($);if(!Q)return T5($,J,Z);for(let[K,B]of J.entries()){try{switch(B.action){case"tap":{let U=B.x!==void 0&&B.y!==void 0?{x:B.x,y:B.y}:await TZ($,B,Z,K+1,J.length);await Q.call(B.duration?{op:"tap",...U,duration:B.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:B.x,y:B.y,x2:B.x2,y2:B.y2,duration:B.duration??0.3});break;case"button":await Q.call({op:"button",name:B.name});break;case"type":await Q.call({op:"text",text:B.text}).catch((U)=>U instanceof B1?p1(["type",B.text],$.udid,`Step ${K+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(B.seconds*1000);break}}catch(U){if(U instanceof S0)return await T5($,J.slice(K),Z),`Ran ${J.length} step(s) on ${h($)}.`;if(U instanceof B1)f("simulator_command_failed",`Step ${K+1} failed: ${U.message}
512
+ (${K} of ${J.length} steps had completed.)`);throw U}let G=J[K+1];if(B.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(h5*1000)}return`Ran ${J.length} step(s) on ${h($)}.`}async function T5($,J,Z){let Q=[],K=[],B=0,G=0,U=async()=>{if(Q.length===0)return;let W=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let Y of Q)W.push("--step",Y);try{await p1(W,$.udid,`Steps ${G+1}-${G+B}`)}catch(Y){if(Y instanceof H){let X=Y.message.replace(/Step (\d+) failed/,(N,C)=>{let F=K[Number(C)-1];return F?`Step ${F} failed`:N});f(Y.code,`${X}
513
+ (${G} of ${J.length} steps had completed before this batch.)`)}throw Y}G+=B,Q=[],K=[],B=0};for(let[W,Y]of J.entries()){if(Y.action==="type"){await U(),await p1(["type",Y.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(jZ(Y)),B+=1,K.push(W+1);let X=J[W+1];if(Y.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${h5}`),K.push(W+1)}return await U(),`Ran ${J.length} step(s) on ${h($)}.`}var _Z=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],_5=new Map,RZ=`ObjC.import("AppKit");
514
514
  function run(argv) {
515
515
  const [input, output, width, height] = argv;
516
516
  const w = Number(width), h = Number(height);
@@ -522,8 +522,8 @@ function run(argv) {
522
522
  image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, $.NSCompositingOperationCopy, 1);
523
523
  $.NSGraphicsContext.restoreGraphicsState;
524
524
  rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(output, true);
525
- }`;async function J3($,J,Z){let Q=await n("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),K=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),B=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)K=K*Z/B,B=Z;let G=U3(g(_5(),"reason-chrome-"));try{let U=g(G,"render.js"),W=g(G,"out.png");if(uJ(U,IZ),await n("osascript",["-l","JavaScript",U,$,W,String(Math.max(1,Math.round(K*J))),String(Math.max(1,Math.round(B*J)))],"Rendering the frame"),!Q0(W))f("simulator_command_failed",`Rendering ${R5($)} produced no image.`);return{image:X3(W).toString("base64"),width:K,height:B}}finally{V1(G,{recursive:!0,force:!0})}}async function AZ($){if(!B3.has($.udid))await F3();let J=B3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)f("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function TZ($){let J=await AZ($),Z=p1.get($.udid)??($.state==="booted"?(await C3($),p1.get($.udid)):void 0);if(!Z)f("simulator_not_booted",`${$.name} is not booted.`);let Q=A5.get(J);if(Q)return{text:`Frame of ${h($)}.`,device:$,chrome:Q};let K=g(J,"Contents","Resources"),B=JSON.parse(await n("plutil",["-convert","json","-o","-",g(K,"profile.plist")],"Reading the device profile")),G=B.framebufferMask?g(K,`${B.framebufferMask}.pdf`):null,U=G&&Q0(G)?await J3(G,t2,Z.height):null,W=B.chromeIdentifier?.split(".").pop(),Y=W?g("/Library/Developer/DeviceKit/Chrome",`${W}.devicechrome`,"Contents","Resources"):"";if(!W||!Q0(g(Y,"chrome.json")))f("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(X3(g(Y,"chrome.json"),"utf8")),F={};for(let O of jZ){let R=X.images[O];if(!R)f("simulator_command_failed",`${$.name}'s frame has no ${O} piece.`);F[O]=await J3(g(Y,`${R}.pdf`),t2)}let{sizing:C}=X.images,N={top:C.topHeight,left:C.leftWidth,bottom:C.bottomHeight,right:C.rightWidth},D=Z.width+N.left+N.right,w=Z.height+N.top+N.bottom,M=[];for(let O of X.inputs??[]){let R=g(Y,`${O.image}.pdf`);if(!Q0(R))continue;let E=await J3(R,t2),{x:v,y:j}=O.offsets.normal,q=(S,L,T)=>S<0?L+S-T:S,_=O.anchor==="left"?{x:v-E.width,y:q(j,w,E.height)}:O.anchor==="right"?{x:D+v,y:q(j,w,E.height)}:O.anchor==="top"?{x:q(v,D,E.width),y:j-E.height}:{x:q(v,D,E.width),y:w+j};M.push({name:O.name,image:E.image,..._,width:E.width,height:E.height})}let I={identifier:X.identifier,screen:{width:Z.width,height:Z.height},inset:N,padding:X.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:F,buttons:M,...U?{screen_mask:U.image}:{}};return A5.set(J,I),{text:`Frame of ${h($)}.`,device:$,chrome:I}}var _Z=new Set(["simulator_command_failed","simulator_launch_failed","simulator_point_off_screen","simulator_build_no_scheme","simulator_element_not_found","simulator_path_outside_root","simulator_project_not_found"]);async function U1($){try{return await y5($)}catch(J){if(J instanceof H&&_Z.has(J.code))return{text:J.message,error:J.code};throw J}}async function y5($){if(!G1())f("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=c2.safeParse($.payload);if(!J.success)f("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await F3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(h).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await eJ(await t(Z.device,{booted:!1}));return{text:`${h(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await t(Z.device,{booted:!1});H0.get(Q.udid)?.stop(),H0.delete(Q.udid);let K=await x0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))f("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${h(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await L5(Z,$.root);return Z.wait&&Q.build?$3(Q.build.id):Q}case"build_status":return Z.wait?$3(Z.build_id):k5(Z.build_id);case"run":{let Q=await L5({...Z,action:"build"},$.root),K=await $3(Q.build.id,GZ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await y5({root:$.root,payload:{action:"launch",app_path:K.build.app_path,...Z.device?{device:Z.device}:{},...Z.steps?{steps:Z.steps}:{},...Z.observe?{observe:Z.observe}:{},...Z.wait_for?{wait_for:Z.wait_for}:{},...Z.timeout!==void 0?{timeout:Z.timeout}:{}}});return{...B,text:`Built in ${Math.round(K.build.elapsed_ms/1000)} s. ${B.text}`,build:K.build}}case"launch":{let Q=await XZ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await f0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return I0(Q.device,Z,Q)}case"steps":{let Q=await t(Z.device,{booted:!0});return I0(Q,Z,{text:await f0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await t(Z.device,{booted:!0});if(H0.get(Q.udid)?.bundleId===Z.bundle_id)H0.get(Q.udid)?.stop();return await x0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${h(Q)}.`,device:Q}}case"logs":return YZ(await t(Z.device,{booted:!1}),Z.after);case"screenshot":return C3(await t(Z.device,{booted:!0}),Z.scale,Z.save_path?N3($.root,Z.save_path):void 0);case"chrome":return TZ(await t(Z.device,{booted:!1}));case"inspect":return NZ(await t(Z.device,{booted:!0}));case"tap":{let Q=await t(Z.device,{booted:!0}),K=Z.x!==void 0&&Z.y!==void 0;if(K)w5(Q,[Z.x,Z.y]);await f0(Q,[K?{action:"tap",x:Z.x,y:Z.y,...Z.duration&&Z.duration>0?{duration:Z.duration}:{}}:Z.id?{action:"tap",id:Z.id}:{action:"tap",label:Z.label}],3);let B=K?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return I0(Q,Z,{text:`Tapped ${B} on ${h(Q)}.`,device:Q})}case"swipe":{let Q=await t(Z.device,{booted:!0});return w5(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await f0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),I0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${h(Q)}.`,device:Q})}case"type":{let Q=await t(Z.device,{booted:!0});return await f0(Q,[{action:"type",text:Z.text}],3),I0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${h(Q)}.`,device:Q})}case"button":{let Q=await t(Z.device,{booted:!0});return await f0(Q,[{action:"button",name:Z.name}],3),I0(Q,Z,{text:`Pressed ${Z.name} on ${h(Q)}.`,device:Q})}case"open_url":{let Q=await t(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{f("simulator_invalid_request","open_url needs an absolute URL.")}if(iJ.has(K.protocol))f("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),I0(Q,Z,{text:`Opened ${K.href} on ${h(Q)}.`,device:Q})}case"appearance":{let Q=await t(Z.device,{booted:!0});return await n("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${h(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as RZ,readFileSync as PZ,rmSync as zZ}from"fs";import{tmpdir as qZ}from"os";import{join as h5}from"path";import{spawn as u5}from"child_process";var EZ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,X1=1,gZ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],m5=60,SZ=8,d5=G1;var v5={65293:40,65421:40,65307:41,65288:42,65289:43,65535:76,65360:74,65367:77,65365:75,65366:78,65361:80,65362:82,65363:79,65364:81,65505:225,65506:229,65507:224,65508:228,65513:226,65514:230,65515:227,65516:231,65511:227,65512:231,65509:57},kZ=(()=>{let $={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((Z,Q)=>{$[Z]=4+Q,$[Z.toUpperCase()]=4+Q}),"1234567890".split("").forEach((Z,Q)=>{$[Z]=30+Q}),"!@#$%^&*()".split("").forEach((Z,Q)=>{$[Z]=30+Q});let J=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[Z,Q,K]of J)$[Z]=K,$[Q]=K;return $})();function fZ($){if(v5[$]!==void 0)return v5[$];return $>=32&&$<=126?kZ[String.fromCharCode($)]??null:null}function l5($,J){let Z=u5("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function bZ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,G,U){let W=(U&X1)!==0;if(W&&!(Z&X1))K({op:"touch",phase:"down",x:B,y:G});else if(W&&(B!==Q.x||G!==Q.y))K({op:"touch",phase:"move",x:B,y:G});else if(!W&&Z&X1)K({op:"touch",phase:"up",x:B,y:G});for(let Y of gZ)if(U&Y.bit&&!(Z&Y.bit))K({op:"swipe",x:B,y:G,x2:B+Y.dx*m5,y2:G+Y.dy*m5,duration:0.08});Z=U,Q={x:B,y:G}},key(B,G){let U=fZ(G);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){l5($,B)},close(){if(Z&X1)K({op:"touch",phase:"up",...Q});Z=0}}}function xZ($,J){let Z=null,Q="",K,B=(G)=>{U1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,W){let Y=(W&X1)!==0;if(Y&&!Z)Z={x:G,y:U,at:Date.now()};if(!Y&&Z){let X=(Date.now()-Z.at)/1000;if(Math.hypot(G-Z.x,U-Z.y)>SZ)B({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:U,duration:Math.min(Math.max(X,0.05),1)});else B({action:"tap",x:Z.x,y:Z.y,...X>0.5?{duration:Math.min(X,10)}:{}});Z=null}},key(G,U){if(!G)return;let W=U===65293?`
526
- `:U>=32&&U<=126?String.fromCharCode(U):null;if(W===null)return;Q+=W,clearTimeout(K),K=setTimeout(()=>{let Y=Q;Q="",B({action:"type",text:Y})},250)},clipboard(G){l5($,G)},close(){clearTimeout(K),Z=null}}}function yZ($,J,Z){return new Promise((Q,K)=>{let B=u5($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function hZ($,J){let Z=RZ(h5(qZ(),"reason-simulator-stream-"));try{let Q=h5(Z,"screen.png");if(await yZ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=PZ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{zZ(Z,{recursive:!0,force:!0})}}async function s5($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!EZ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await q5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await U1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:B.image.width,height:B.image.height},U=await o2(K),W=U?await h1(K,Z,!0):null,Y=U?null:await p5();if(!U&&!Y)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let X={kind:"simulator",udid:Z,axe:K,points:G,sound:null,size:U?G:await hZ(Z,$.signal),stream:U?(F,C,N)=>D5(U,Z,Math.min(F,60),N,C):null,input:W?bZ(Z,W):xZ(Z,$.root)};return await l1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...Y?{ffmpeg:()=>Y}:{}}})}var _7=131072,cZ=131072,nZ=128,R7=8192,_3=30000,R3=15000,rZ=/^[a-z][a-z0-9_]{0,63}$/,aZ=new Set(["jobs.control","fs.read","fs.write"]),c5=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function s1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function n5($){return $.map(s1).join("/")}function H3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var iZ=[...H3(_6,4).map(($)=>`/(${$.map(n5).join("|")})(/|$)`),...H3(R6,4).map(($)=>`/(${$.map(n5).join("|")})$`),...H3([...P6],6).map(($)=>`/(${$.map(s1).join("|")})$`),`/${s1(".env")}\\.[^/]+$`,`/[^/]+(${z6.map(s1).join("|")})$`],w3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),P7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function z7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function oZ($){return t6($)}function O3(){if(l()==="darwin")return G0("/usr/bin/sandbox-exec");if(l()==="linux")return e6();return!1}function r5(){if(l()==="linux")return G0("/proc");if(!O3())return!1;if(l()==="darwin")return G0("/usr/sbin/lsof");return!1}function q7(){return l()==="darwin"?"/bin/zsh":$7()}function j3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function tZ($){if(!j3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>N0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function u0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function a1($,J,Z=R7){let Q=u0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function eZ($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function F1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function v0($,J){return J===$||J.startsWith(`${$}${lZ}`)}function h0($){if(L0($))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.")}function m($){let J;try{J=J0($.path)}catch(Z){if(process.platform==="darwin"&&n6(Z))throw r6($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!N1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return h0(J),J}function P3($,J="."){if(!J||J.includes("\x00")||uZ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");let Z=dZ($,J);if(!v0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function p0($,J=".",Z=!1){let Q=P3($,J),K;try{K=J0(Q)}catch(B){if(k7(B))throw f7();throw new H("path_not_found","Path does not exist.")}if(!v0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)h0(K);return K}function $Q($,J){let Z=P3($,J);if(h0(Z),G0(Z)){let B=J0(Z);if(!v0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(O7(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return h0(B),B}let Q=Y1(Z);while(!G0(Q)){let B=Y1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=J0(Q);if(!v0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return h0(K),Z}function E7($,J){return L3($,J)||"."}function JQ($,J=_7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function g7($,J){return{...d6({home:$,temporaryDirectory:J}),ZDOTDIR:J,BASH_ENV:"/dev/null",ENV:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}function ZQ($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...iZ.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),"(deny network*)"].join(`
527
- `)}async function z3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,W=!1,Y=!1,X;try{X=sZ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],detached:!0})}catch(w){K(w);return}let F=(w,M)=>{if(Y)return;Y=!0,clearTimeout(D),Z.signal.removeEventListener("abort",N),Q({exitCode:w,signal:M,stdout:B,stderr:G,timedOut:W,truncated:U})},C=(w,M)=>{let I=`${w}${String(M)}`,O=JQ(I);return U||=O.truncated,O.value};X.stdout.on("data",(w)=>{B=C(B,w)}),X.stderr.on("data",(w)=>{G=C(G,w)}),X.once("error",K),X.once("exit",F);let N=()=>{try{X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",N,{once:!0});let D=setTimeout(()=>{W=!0,N()},Z.timeoutMs)})}var a5=null;function QQ(){return a5??=J7({scrubEnvironment:g7,spawnCaptured:z3,isProtectedPath:L0}),a5}var KQ=async($,J,Z)=>{if(l()==="linux")return QQ()($,J,Z);if(l()!=="darwin"||!G0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=j7(T3(T7(),"reason-device-"));try{return await z3("/usr/bin/sandbox-exec",["-p",ZQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:g7(Z.root,Q)})}finally{A7(Q,{recursive:!0,force:!0})}};function BQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>nZ)throw new H("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>R7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function S7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=m($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??R3,signal:$.signal});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function k7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var f7=()=>new H("path_unreadable","The path is not readable.");function VQ($){try{return I7($,A0.O_RDONLY)}catch(J){throw k7(J)?f7():J}}function i5($,J){let Z=m0()?n1():null;return Z?r1(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):GQ($,J)}function GQ($,J){return $==="fs.read"?UQ(J):WQ(J)}async function UQ($){let J=m($.root),Z=p0(J,a1($.payload,"path"));if(!N1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=F1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=F1($.payload.max_bytes,65536,1,_7),B=u0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=VQ(Z),U,W;try{U=w7(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));W=X.subarray(0,X.byteLength?vZ(G,X,0,X.byteLength,Q):0)}finally{L7(G)}let Y=B==="base64"||W.includes(0);return{path:E7(J,Z),content:Y?W.toString("base64"):W.toString("utf8"),encoding:Y?"base64":"utf8",offset:Q,bytes:W.byteLength,size:U,truncated:Q+W.byteLength<U}}function XQ($,J){let Z=$==="append"?A0.O_APPEND:A0.O_TRUNC;return A0.O_WRONLY|A0.O_NOFOLLOW|Z|(J?0:A0.O_CREAT|A0.O_EXCL)}async function WQ($){let J=m($.root),Z=a1($.payload,"path"),Q=eZ($.payload,"content",cZ),K=u0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=$Q(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){mZ(Y1(B),{recursive:!0,mode:448});let Y=J0(Y1(B));if(!v0(J,Y))throw new H("symlink_escape","Write parent escaped root.")}if(!G0(Y1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&G0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=G0(B),U=G?O7(B):null,W=I7(B,XQ(K,G),384);try{if(U){let Y=w7(W);if(Y.ino!==U.ino||Y.dev!==U.dev)throw new H("symlink_escape","The write target changed between validation and opening.")}pZ(W,Q,null,"utf8")}finally{L7(W)}return{path:E7(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function YQ($){let J=m($.root),Z=a1($.payload,"command",65536),Q=p0(J,u0($.payload,"cwd")??".");if(!N1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=F1($.payload.timeout_ms,R3,100,_3);return S7($,q7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function FQ($){let J=G4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:l()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=m($.root),K=k6(Q,J.data.workspace),B=K.boundary===Q?Q:p0(K.anchor,L3(K.anchor,K.boundary)||"."),G=p0(B,L3(B,K.path)||".");if(!N1(G).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+Q4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let W=(I)=>$.emit("progress",{process:I});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await I1({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:E0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:W})}}let Y={directory:T3(Z.runtimeDirectory,"processes")},X={deniedPorts:S6([$.apiOrigin])};if($.claim.local_github_authority&&l()==="darwin"){let I=NQ(G);try{return{...await I1({claim:$.claim,root:G,cwd:G,command:J.data.command,mode:"confined",shell:I.shell,prefix:I.prefix,environment:I.environment,expiresAtMs:U,signal:$.signal,emit:W,journals:Y,preview:X})}}finally{I.dispose()}}let F=l6(),C=s6(),N=m0(),D=J.data.egress?c1(N):null;if(J.data.egress&&(D===null||!y0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let w=J.data.egress?await b4(J.data.egress.allowed_domains):null,M=w?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((I)=>`${I}=${w.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
528
- `):J.data.command;try{return{...await I1({claim:$.claim,root:G,cwd:G,command:M,mode:"host",shell:C,expiresAtMs:U,signal:$.signal,emit:W,...N?{jobsUser:{...N,...D!==null?{modelGid:D}:{}}}:{},environment:{...F.variables,HOME:F.home,PATH:F.path,TMPDIR:F.temporaryDirectory,SHELL:C},journals:Y,preview:X})}}finally{w?.close()}}function NQ($){if(!G0("/usr/bin/sandbox-exec"))throw new H("local_device_gh_confinement_unavailable","This Mac cannot confine a local GitHub Session's dev server.");let J=J0($),Z=J0(j7(T3(J0(T7()),"reason-preview-"))),Q="/bin/bash";return{shell:Q,prefix:["/usr/bin/sandbox-exec","-p",E6(J,Z)],environment:{HOME:Z,PATH:q6,TMPDIR:Z,TMP:Z,TEMP:Z,SHELL:Q,BASH_ENV:"/dev/null",ENV:"/dev/null",OPENSSL_CONF:"/dev/null"},dispose:()=>A7(Z,{recursive:!0,force:!0})}}async function CQ($){f2();let J=m($.root),Z=b2($.payload.command),Q=p0(J,u0($.payload,"cwd")??".");if(!N1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=F1($.payload.timeout_ms,S8,100,S2),{ignored:B}=x2($.payload.env);return await $.emit("progress",{shell:E0(),shell_flags:[...Z1],sandbox:"none",ignored_env:B}),f8({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function HQ($){let J=m($.root),Z=BQ($.payload),Q=Z[0];if(!Q||!P7.has(Q)&&!w3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=w3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=p0(J,u0($.payload,"cwd")??".");return S7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K,timeoutMs:F1($.payload.timeout_ms,R3,100,_3)})}function b7($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");return Q}}async function DQ($){let J=m($.root);if(l()==="linux")return l8(J);return a8(J,b7($,J))}async function MQ($){let J=m($.root);if(l()==="linux")return s8(J);return i8(J,b7($,J))}async function LQ($){let J=$.worker?B5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&q3({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:m($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function wQ($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new H("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=f6($.payload,$.operationId);return h6({root:m($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:m($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function o5($,J){let Z=m0()?n1():null;return Z?r1(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):OQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function OQ($,J){let Z=m(J.root),Q=o0 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let K=Q?U8(Z,J.payload[o0]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new H("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let U=c4.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return X8({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=a1(J.payload,"path",4096),G=$==="import"&&Q?P2(K):K;return h0(P3(G,B)),q0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var x7={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new H("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return y3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>i5("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>i5("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>o5($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>o5($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>l()==="darwin"&&k2(),execute:FQ},"exec.run":{requiredPermission:"execute",available:O3,execute:YQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>k2(),execute:CQ},"git.run":{requiredPermission:"execute",available:()=>O3()&&oZ("git"),execute:HQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:r5,execute:DQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:r5,execute:MQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>l()==="darwin"||Boolean(a6()),execute:LQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:N7,execute:wQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:M7,execute:($)=>{let J=n1();return J?r1(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??c6)()},$.signal):l1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>H7(),execute:($)=>D7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:G1,execute:($)=>U1({payload:$.payload,root:m($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:d5,execute:($)=>s5({payload:$.payload,root:m($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>m6({root:m($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>l()==="darwin"?G0("/usr/bin/sandbox-exec"):l()==="linux",execute:async($)=>{let J=L1.parse($.payload),Z=I3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!M0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")))throw Error("local_device_gh_authority_changed");return v6({root:m($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>o3(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>A3({root:m($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>x6({root:m($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>y6({root:m($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:_2,execute:($)=>Q8($.payload,$.signal)}};function jQ($,J){try{let Z=m3($,J0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function IQ($,J){try{let Z=J0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function AQ($,J){try{let Z=J0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function TQ($,J){try{let Z=J0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&v0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function _Q($,J){try{return D1({home:J0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&H1(Z.path)).slice(0,e1).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function dG($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||l()==="darwin",K=Q?AQ($,W1()):void 0,B=!J.worker&&l()==="darwin"?jQ($,W1()):void 0,G=Q?IQ($,W1()):void 0,U=!J.worker&&l()==="darwin"?TQ($,W1()):void 0,W=Q?_Q($,W1()):void 0,Y=g2.filter((X)=>{if(J1.has(X)&&!J.worker)return!1;if(J.worker&&!S1(X,J.worker))return!1;let F=x7[X];if(!F)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:F.available?.()??!0)&&$.some((N)=>(!J.worker||X!=="pty.start"||N.permissions.read&&N.permissions.write)&&z7(F).every((D)=>N.permissions[D]))});return{supported_operations:Y,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...W?{root_paths:W}:{},...Y.includes("hands.connect")?{hands_worker_artifact_sha256:P0,hands_worker_entrypoint:r0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:N0,max_result_bytes:N0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":B2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:q7(),sandbox:l()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:_3},...Y.includes("exec.full")?{"exec.full":b8()}:{},"git.run":{read_only_subcommands:[...P7].sort(),mutating_subcommands:[...w3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:W0,max_timeout_ms:i0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:W0,max_timeout_ms:i0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:n0,protocol_version:M3,worker_artifact_sha256:P0,worker_entrypoint:r0,policy_mode:"full_access",policy_version:1,workspace_base:D3,workspace_layout:$1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":l()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...Y.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:F7,max_session_ms:W7,max_buffered_output_bytes:Y7}}:{},...J.worker?Object.fromEntries(Y.filter((X)=>X!=="browser.pr-proof.v1").map((X)=>[X,{ready:J.worker?.readiness?.[X]===!0,...J.worker?.readiness?.[X]!==!0&&J.worker?.probing?.includes(X)?{probing:!0}:{},execution_mode:S1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:g6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!m0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"&&J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:w6,workspace_base:D3,workspace_layout:$1,browser_state:"optional_headless",desktop:!1,worker_version:n0,protocol_version:M3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:$6,[Q6]:Z6}:{},...J.worker?{[B6]:K6}:{},...J.worker?.handsBrowser?{[W6]:X6}:{},[U6]:G6,[F6]:Y6,...y0(J.worker?.executionMode==="unsandboxed")?{[C6]:N6}:{},...y0(J.worker?.executionMode==="unsandboxed")&&c1()!==null?{[D6]:H6}:{},...y0(J.worker?.executionMode==="unsandboxed")&&m0()?{[L6]:M6}:{}}:{},...X==="fs.export"?{cloud_source_version:R1,source_kinds:["workspace","attachment"],[L2]:w2}:{},...X==="fs.import"?{[L2]:w2}:{},...X===Z4&&c1()!==null&&y0(J.worker?.executionMode==="unsandboxed")?{[V4]:U2}:{},...X==="tunnel.open"?{carried_jobs:O6}:{},...X==="jobs.control"?{[I6]:j6}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[Q7]:Z7,[B7]:K7.join(","),[V7]:G7,[U7]:X7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[A6]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[T6]:!0}:{}}])):{}}}}function q3($,J,Z,Q,K){let B=u6.safeParse(Q);return B.success&&K!==void 0&&K.device_id===$.deviceId&&B.data.device_id===$.deviceId&&B.data.root_id===J&&B.data.run_id===Z&&B.data.binding.kind===K.binding&&B.data.binding.target_revision===K.target_revision&&B.data.binding.root_grant_revision===K.root_grant_revision&&B.data.binding.target_generation===K.target_generation&&B.data.binding.target_fence_id===K.target_fence_id}async function lG($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==J6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((Y)=>Y.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!q3($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let W=A3({root:m(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:W.snapshot_id,installed_revision:W.installed_revision,installed:!0},K),!0}async function sG($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==V6)return!1;let{version:K,run_id:B,target_generation:G,target_fence_id:U}=Z.payload;if(K!==1||Object.keys(Z.payload).length!==4||typeof B!=="string"||typeof G!=="number"||typeof U!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let W=$.roots.find((Y)=>Y.id===J.root_id);if(!W)throw new H("root_not_granted","The Hands root is no longer granted.");return await b6({operationId:J.operation_id,root:m(W),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function cG($,J,Z){if(J.capability!=="github.local.v1")return t5($,J,Z);try{let Q=await t5($,J,Z);if(Q.status==="succeeded")return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function t5($,J,Z){if(J1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!S1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=I3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=x7[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let K=$.roots.find((X)=>X.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&j3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&o0 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!q3($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(z7(Q).some((X)=>!K.permissions[X]))return{status:"failed",error_code:"permission_denied"};let B=0,G=async(X,F,C)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:B++,kind:X,capability:J.capability,data:F,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&C?{deliverySignal:C}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||aZ.has(J.capability)||J.capability==="pty.start",W,Y=async(X,F,C)=>{let N=W;W=void 0,await Promise.all([N,G(X,F,C)])};try{if(U)W=G("started"),W.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},F=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(C)=>G("pr-proof.started.v1",C))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:tZ(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:X,runCommand:Z.runCommand??KQ,spawnFullControl:Z.spawnFullControl??z3,emit:U?Y:G,runHandsRelay:Z.runHandsRelay??((C)=>o6(C,X)),runPtySession:Z.runPtySession??C7});if(J.capability==="github.local.v1")e5.parse(F);if(!j3(F))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(F)??"null","utf8")>N0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?Y:G)("completed",{ok:!0}),{status:"succeeded",result:F,error_code:null}}catch(X){let F=Z.signal.reason instanceof H&&c5.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&c5.has(X.code)?X.code:null;if(Z.signal.aborted||F)return{status:"cancelled",...X instanceof c0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":F??"cancelled"};let C=J.capability==="inference.custom.v1"?"custom_endpoint_unavailable":J.capability==="github.local.v1"?"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&rZ.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof i6?p6(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:C,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:C}}}
529
- export{$9 as y,J9 as z,$4 as A,eQ as B,QK as C,_K as D,RK as E,_2 as F,IB as G,Y0 as H,M$ as I,L$ as J,AB as K,T$ as L,E0 as M,Q1 as N,FJ as O,aZ as P,q7 as Q,g7 as R,ZQ as S,z3 as T,KQ as U,GQ as V,NQ as W,OQ as X,x7 as Y,jQ as Z,IQ as _,AQ as $,TQ as aa,_Q as ba,dG as ca,lG as da,sG as ea,cG as fa};
525
+ }`;async function Z3($,J,Z){let Q=await n("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),K=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),B=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)K=K*Z/B,B=Z;let G=X3(g(P5(),"reason-chrome-"));try{let U=g(G,"render.js"),W=g(G,"out.png");if(cJ(U,RZ),await n("osascript",["-l","JavaScript",U,$,W,String(Math.max(1,Math.round(K*J))),String(Math.max(1,Math.round(B*J)))],"Rendering the frame"),!Q0(W))f("simulator_command_failed",`Rendering ${z5($)} produced no image.`);return{image:W3(W).toString("base64"),width:K,height:B}}finally{V1(G,{recursive:!0,force:!0})}}async function PZ($){if(!V3.has($.udid))await N3();let J=V3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)f("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function zZ($){let J=await PZ($),Z=u1.get($.udid)??($.state==="booted"?(await H3($),u1.get($.udid)):void 0);if(!Z)f("simulator_not_booted",`${$.name} is not booted.`);let Q=_5.get(J);if(Q)return{text:`Frame of ${h($)}.`,device:$,chrome:Q};let K=g(J,"Contents","Resources"),B=JSON.parse(await n("plutil",["-convert","json","-o","-",g(K,"profile.plist")],"Reading the device profile")),G=B.framebufferMask?g(K,`${B.framebufferMask}.pdf`):null,U=G&&Q0(G)?await Z3(G,e2,Z.height):null,W=B.chromeIdentifier?.split(".").pop(),Y=W?g("/Library/Developer/DeviceKit/Chrome",`${W}.devicechrome`,"Contents","Resources"):"";if(!W||!Q0(g(Y,"chrome.json")))f("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(W3(g(Y,"chrome.json"),"utf8")),N={};for(let O of _Z){let R=X.images[O];if(!R)f("simulator_command_failed",`${$.name}'s frame has no ${O} piece.`);N[O]=await Z3(g(Y,`${R}.pdf`),e2)}let{sizing:C}=X.images,F={top:C.topHeight,left:C.leftWidth,bottom:C.bottomHeight,right:C.rightWidth},D=Z.width+F.left+F.right,w=Z.height+F.top+F.bottom,M=[];for(let O of X.inputs??[]){let R=g(Y,`${O.image}.pdf`);if(!Q0(R))continue;let E=await Z3(R,e2),{x:v,y:I}=O.offsets.normal,q=(S,L,T)=>S<0?L+S-T:S,_=O.anchor==="left"?{x:v-E.width,y:q(I,w,E.height)}:O.anchor==="right"?{x:D+v,y:q(I,w,E.height)}:O.anchor==="top"?{x:q(v,D,E.width),y:I-E.height}:{x:q(v,D,E.width),y:w+I};M.push({name:O.name,image:E.image,..._,width:E.width,height:E.height})}let j={identifier:X.identifier,screen:{width:Z.width,height:Z.height},inset:F,padding:X.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:N,buttons:M,...U?{screen_mask:U.image}:{}};return _5.set(J,j),{text:`Frame of ${h($)}.`,device:$,chrome:j}}var qZ=new Set(["simulator_command_failed","simulator_launch_failed","simulator_point_off_screen","simulator_build_no_scheme","simulator_element_not_found","simulator_path_outside_root","simulator_project_not_found"]);async function U1($){try{return await m5($)}catch(J){if(J instanceof H&&qZ.has(J.code))return{text:J.message,error:J.code};throw J}}async function m5($){if(!G1())f("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=n2.safeParse($.payload);if(!J.success)f("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await N3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(h).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await QZ(await t(Z.device,{booted:!1}));return{text:`${h(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await t(Z.device,{booted:!1});H0.get(Q.udid)?.stop(),H0.delete(Q.udid);let K=await x0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))f("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${h(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await O5(Z,$.root);return Z.wait&&Q.build?J3(Q.build.id):Q}case"build_status":return Z.wait?J3(Z.build_id):b5(Z.build_id);case"run":{let Q=await O5({...Z,action:"build"},$.root),K=await J3(Q.build.id,YZ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await m5({root:$.root,payload:{action:"launch",app_path:K.build.app_path,...Z.device?{device:Z.device}:{},...Z.steps?{steps:Z.steps}:{},...Z.observe?{observe:Z.observe}:{},...Z.wait_for?{wait_for:Z.wait_for}:{},...Z.timeout!==void 0?{timeout:Z.timeout}:{}}});return{...B,text:`Built in ${Math.round(K.build.elapsed_ms/1000)} s. ${B.text}`,build:K.build}}case"launch":{let Q=await NZ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await f0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return I0(Q.device,Z,Q)}case"steps":{let Q=await t(Z.device,{booted:!0});return I0(Q,Z,{text:await f0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await t(Z.device,{booted:!0});if(H0.get(Q.udid)?.bundleId===Z.bundle_id)H0.get(Q.udid)?.stop();return await x0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${h(Q)}.`,device:Q}}case"logs":return HZ(await t(Z.device,{booted:!1}),Z.after);case"screenshot":return H3(await t(Z.device,{booted:!0}),Z.scale,Z.save_path?C3($.root,Z.save_path):void 0);case"chrome":return zZ(await t(Z.device,{booted:!1}));case"inspect":return MZ(await t(Z.device,{booted:!0}));case"tap":{let Q=await t(Z.device,{booted:!0}),K=Z.x!==void 0&&Z.y!==void 0;if(K)j5(Q,[Z.x,Z.y]);await f0(Q,[K?{action:"tap",x:Z.x,y:Z.y,...Z.duration&&Z.duration>0?{duration:Z.duration}:{}}:Z.id?{action:"tap",id:Z.id}:{action:"tap",label:Z.label}],3);let B=K?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return I0(Q,Z,{text:`Tapped ${B} on ${h(Q)}.`,device:Q})}case"swipe":{let Q=await t(Z.device,{booted:!0});return j5(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await f0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),I0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${h(Q)}.`,device:Q})}case"type":{let Q=await t(Z.device,{booted:!0});return await f0(Q,[{action:"type",text:Z.text}],3),I0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${h(Q)}.`,device:Q})}case"button":{let Q=await t(Z.device,{booted:!0});return await f0(Q,[{action:"button",name:Z.name}],3),I0(Q,Z,{text:`Pressed ${Z.name} on ${h(Q)}.`,device:Q})}case"open_url":{let Q=await t(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{f("simulator_invalid_request","open_url needs an absolute URL.")}if($Z.has(K.protocol))f("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),I0(Q,Z,{text:`Opened ${K.href} on ${h(Q)}.`,device:Q})}case"appearance":{let Q=await t(Z.device,{booted:!0});return await n("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${h(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as EZ,readFileSync as gZ,rmSync as SZ}from"fs";import{tmpdir as kZ}from"os";import{join as v5}from"path";import{spawn as l5}from"child_process";var fZ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,X1=1,bZ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],p5=60,xZ=8,s5=G1;var u5={65293:40,65421:40,65307:41,65288:42,65289:43,65535:76,65360:74,65367:77,65365:75,65366:78,65361:80,65362:82,65363:79,65364:81,65505:225,65506:229,65507:224,65508:228,65513:226,65514:230,65515:227,65516:231,65511:227,65512:231,65509:57},yZ=(()=>{let $={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((Z,Q)=>{$[Z]=4+Q,$[Z.toUpperCase()]=4+Q}),"1234567890".split("").forEach((Z,Q)=>{$[Z]=30+Q}),"!@#$%^&*()".split("").forEach((Z,Q)=>{$[Z]=30+Q});let J=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[Z,Q,K]of J)$[Z]=K,$[Q]=K;return $})();function hZ($){if(u5[$]!==void 0)return u5[$];return $>=32&&$<=126?yZ[String.fromCharCode($)]??null:null}function c5($,J){let Z=l5("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function mZ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,G,U){let W=(U&X1)!==0;if(W&&!(Z&X1))K({op:"touch",phase:"down",x:B,y:G});else if(W&&(B!==Q.x||G!==Q.y))K({op:"touch",phase:"move",x:B,y:G});else if(!W&&Z&X1)K({op:"touch",phase:"up",x:B,y:G});for(let Y of bZ)if(U&Y.bit&&!(Z&Y.bit))K({op:"swipe",x:B,y:G,x2:B+Y.dx*p5,y2:G+Y.dy*p5,duration:0.08});Z=U,Q={x:B,y:G}},key(B,G){let U=hZ(G);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){c5($,B)},close(){if(Z&X1)K({op:"touch",phase:"up",...Q});Z=0}}}function vZ($,J){let Z=null,Q="",K,B=(G)=>{U1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,W){let Y=(W&X1)!==0;if(Y&&!Z)Z={x:G,y:U,at:Date.now()};if(!Y&&Z){let X=(Date.now()-Z.at)/1000;if(Math.hypot(G-Z.x,U-Z.y)>xZ)B({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:U,duration:Math.min(Math.max(X,0.05),1)});else B({action:"tap",x:Z.x,y:Z.y,...X>0.5?{duration:Math.min(X,10)}:{}});Z=null}},key(G,U){if(!G)return;let W=U===65293?`
526
+ `:U>=32&&U<=126?String.fromCharCode(U):null;if(W===null)return;Q+=W,clearTimeout(K),K=setTimeout(()=>{let Y=Q;Q="",B({action:"type",text:Y})},250)},clipboard(G){c5($,G)},close(){clearTimeout(K),Z=null}}}function pZ($,J,Z){return new Promise((Q,K)=>{let B=l5($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function uZ($,J){let Z=EZ(v5(kZ(),"reason-simulator-stream-"));try{let Q=v5(Z,"screen.png");if(await pZ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=gZ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{SZ(Z,{recursive:!0,force:!0})}}async function n5($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!fZ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await g5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await U1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:B.image.width,height:B.image.height},U=await t2(K),W=U?await m1(K,Z,!0):null,Y=U?null:await d5();if(!U&&!Y)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let X={kind:"simulator",udid:Z,axe:K,points:G,sound:null,size:U?G:await uZ(Z,$.signal),stream:U?(N,C,F)=>L5(U,Z,Math.min(N,60),F,C):null,input:W?mZ(Z,W):vZ(Z,$.root)};return await s1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...Y?{ffmpeg:()=>Y}:{}}})}var P7=131072,iZ=131072,oZ=128,z7=8192,R3=30000,P3=15000,tZ=/^[a-z][a-z0-9_]{0,63}$/,eZ=new Set(["jobs.control","fs.read","fs.write"]),r5=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function c1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function a5($){return $.map(c1).join("/")}function D3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var $Q=[...D3(P6,4).map(($)=>`/(${$.map(a5).join("|")})(/|$)`),...D3(z6,4).map(($)=>`/(${$.map(a5).join("|")})$`),...D3([...q6],6).map(($)=>`/(${$.map(c1).join("|")})$`),`/${c1(".env")}\\.[^/]+$`,`/[^/]+(${E6.map(c1).join("|")})$`],O3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),q7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function E7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function JQ($){return $7($)}function j3(){if(l()==="darwin")return G0("/usr/bin/sandbox-exec");if(l()==="linux")return J7();return!1}function i5(){if(l()==="linux")return G0("/proc");if(!j3())return!1;if(l()==="darwin")return G0("/usr/sbin/lsof");return!1}function g7(){return l()==="darwin"?"/bin/zsh":Z7()}function I3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function ZQ($){if(!I3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>N0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function u0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function i1($,J,Z=z7){let Q=u0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function QQ($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function F1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function v0($,J){return J===$||J.startsWith(`${$}${rZ}`)}function h0($){if(L0($))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.")}function m($){let J;try{J=J0($.path)}catch(Z){if(process.platform==="darwin"&&a6(Z))throw i6($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!N1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return h0(J),J}function z3($,J="."){if(!J||J.includes("\x00")||cZ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");let Z=nZ($,J);if(!v0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function p0($,J=".",Z=!1){let Q=z3($,J),K;try{K=J0(Q)}catch(B){if(b7(B))throw x7();throw new H("path_not_found","Path does not exist.")}if(!v0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)h0(K);return K}function KQ($,J){let Z=z3($,J);if(h0(Z),G0(Z)){let B=J0(Z);if(!v0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(I7(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return h0(B),B}let Q=Y1(Z);while(!G0(Q)){let B=Y1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=J0(Q);if(!v0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return h0(K),Z}function S7($,J){return w3($,J)||"."}function BQ($,J=P7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function k7($,J){return{...s6({home:$,temporaryDirectory:J}),ZDOTDIR:J,BASH_ENV:"/dev/null",ENV:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}function VQ($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...$Q.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),"(deny network*)"].join(`
527
+ `)}async function q3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,W=!1,Y=!1,X;try{X=aZ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],detached:!0})}catch(w){K(w);return}let N=(w,M)=>{if(Y)return;Y=!0,clearTimeout(D),Z.signal.removeEventListener("abort",F),Q({exitCode:w,signal:M,stdout:B,stderr:G,timedOut:W,truncated:U})},C=(w,M)=>{let j=`${w}${String(M)}`,O=BQ(j);return U||=O.truncated,O.value};X.stdout.on("data",(w)=>{B=C(B,w)}),X.stderr.on("data",(w)=>{G=C(G,w)}),X.once("error",K),X.once("exit",N);let F=()=>{try{X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",F,{once:!0});let D=setTimeout(()=>{W=!0,F()},Z.timeoutMs)})}var o5=null;function GQ(){return o5??=Q7({scrubEnvironment:k7,spawnCaptured:q3,isProtectedPath:L0}),o5}var UQ=async($,J,Z)=>{if(l()==="linux")return GQ()($,J,Z);if(l()!=="darwin"||!G0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=A7(_3(R7(),"reason-device-"));try{return await q3("/usr/bin/sandbox-exec",["-p",VQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:k7(Z.root,Q)})}finally{_7(Q,{recursive:!0,force:!0})}};function XQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>oZ)throw new H("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>z7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function f7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=m($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??P3,signal:$.signal});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function b7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var x7=()=>new H("path_unreadable","The path is not readable.");function WQ($){try{return T7($,A0.O_RDONLY)}catch(J){throw b7(J)?x7():J}}function t5($,J){let Z=m0()?r1():null;return Z?a1(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):YQ($,J)}function YQ($,J){return $==="fs.read"?FQ(J):CQ(J)}async function FQ($){let J=m($.root),Z=p0(J,i1($.payload,"path"));if(!N1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=F1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=F1($.payload.max_bytes,65536,1,P7),B=u0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=WQ(Z),U,W;try{U=j7(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));W=X.subarray(0,X.byteLength?lZ(G,X,0,X.byteLength,Q):0)}finally{O7(G)}let Y=B==="base64"||W.includes(0);return{path:S7(J,Z),content:Y?W.toString("base64"):W.toString("utf8"),encoding:Y?"base64":"utf8",offset:Q,bytes:W.byteLength,size:U,truncated:Q+W.byteLength<U}}function NQ($,J){let Z=$==="append"?A0.O_APPEND:A0.O_TRUNC;return A0.O_WRONLY|A0.O_NOFOLLOW|Z|(J?0:A0.O_CREAT|A0.O_EXCL)}async function CQ($){let J=m($.root),Z=i1($.payload,"path"),Q=QQ($.payload,"content",iZ),K=u0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=KQ(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){dZ(Y1(B),{recursive:!0,mode:448});let Y=J0(Y1(B));if(!v0(J,Y))throw new H("symlink_escape","Write parent escaped root.")}if(!G0(Y1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&G0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=G0(B),U=G?I7(B):null,W=T7(B,NQ(K,G),384);try{if(U){let Y=j7(W);if(Y.ino!==U.ino||Y.dev!==U.dev)throw new H("symlink_escape","The write target changed between validation and opening.")}sZ(W,Q,null,"utf8")}finally{O7(W)}return{path:S7(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function HQ($){let J=m($.root),Z=i1($.payload,"command",65536),Q=p0(J,u0($.payload,"cwd")??".");if(!N1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=F1($.payload.timeout_ms,P3,100,R3);return f7($,g7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function DQ($){let J=U4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:l()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=m($.root),K=b6(Q,J.data.workspace),B=K.boundary===Q?Q:p0(K.anchor,w3(K.anchor,K.boundary)||"."),G=p0(B,w3(B,K.path)||".");if(!N1(G).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+K4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let W=(j)=>$.emit("progress",{process:j});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await I1({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:E0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:W})}}let Y={directory:_3(Z.runtimeDirectory,"processes")},X={deniedPorts:f6([$.apiOrigin])};if($.claim.local_github_authority&&l()==="darwin"){let j=MQ(G);try{return{...await I1({claim:$.claim,root:G,cwd:G,command:J.data.command,mode:"confined",shell:j.shell,prefix:j.prefix,environment:j.environment,expiresAtMs:U,signal:$.signal,emit:W,journals:Y,preview:X})}}finally{j.dispose()}}let N=c6(),C=n6(),F=m0(),D=J.data.egress?n1(F):null;if(J.data.egress&&(D===null||!y0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let w=J.data.egress?await x4(J.data.egress.allowed_domains):null,M=w?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((j)=>`${j}=${w.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
528
+ `):J.data.command;try{return{...await I1({claim:$.claim,root:G,cwd:G,command:M,mode:"host",shell:C,expiresAtMs:U,signal:$.signal,emit:W,...F?{jobsUser:{...F,...D!==null?{modelGid:D}:{}}}:{},environment:{...N.variables,HOME:N.home,PATH:N.path,TMPDIR:N.temporaryDirectory,SHELL:C},journals:Y,preview:X})}}finally{w?.close()}}function MQ($){if(!G0("/usr/bin/sandbox-exec"))throw new H("local_device_gh_confinement_unavailable","This Mac cannot confine a local GitHub Session's dev server.");let J=J0($),Z=J0(A7(_3(J0(R7()),"reason-preview-"))),Q="/bin/bash";return{shell:Q,prefix:["/usr/bin/sandbox-exec","-p",S6(J,Z)],environment:{HOME:Z,PATH:g6,TMPDIR:Z,TMP:Z,TEMP:Z,SHELL:Q,BASH_ENV:"/dev/null",ENV:"/dev/null",OPENSSL_CONF:"/dev/null"},dispose:()=>_7(Z,{recursive:!0,force:!0})}}async function LQ($){b2();let J=m($.root),Z=x2($.payload.command),Q=p0(J,u0($.payload,"cwd")??".");if(!N1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=F1($.payload.timeout_ms,f8,100,k2),{ignored:B}=y2($.payload.env);return await $.emit("progress",{shell:E0(),shell_flags:[...Z1],sandbox:"none",ignored_env:B}),x8({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function wQ($){let J=m($.root),Z=XQ($.payload),Q=Z[0];if(!Q||!q7.has(Q)&&!O3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=O3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=p0(J,u0($.payload,"cwd")??".");return f7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K,timeoutMs:F1($.payload.timeout_ms,P3,100,R3)})}function y7($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");return Q}}async function OQ($){let J=m($.root);if(l()==="linux")return c8(J);return o8(J,y7($,J))}async function jQ($){let J=m($.root);if(l()==="linux")return n8(J);return t8(J,y7($,J))}async function IQ($){let J=$.worker?G5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&E3({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:m($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function AQ($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new H("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=x6($.payload,$.operationId);return v6({root:m($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:m($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function e5($,J){let Z=m0()?r1():null;return Z?a1(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):TQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function TQ($,J){let Z=m(J.root),Q=o0 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let K=Q?X8(Z,J.payload[o0]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new H("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let U=n4.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return W8({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=i1(J.payload,"path",4096),G=$==="import"&&Q?z2(K):K;return h0(z3(G,B)),q0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var h7={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new H("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return h3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>t5("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>t5("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>e5($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>e5($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>l()==="darwin"&&f2(),execute:DQ},"exec.run":{requiredPermission:"execute",available:j3,execute:HQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>f2(),execute:LQ},"git.run":{requiredPermission:"execute",available:()=>j3()&&JQ("git"),execute:wQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:i5,execute:OQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:i5,execute:jQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>l()==="darwin"||Boolean(o6()),execute:IQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:H7,execute:AQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:w7,execute:($)=>{let J=r1();return J?a1(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??r6)()},$.signal):s1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>M7(),execute:($)=>L7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:G1,execute:($)=>U1({payload:$.payload,root:m($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:s5,execute:($)=>n5({payload:$.payload,root:m($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>p6({root:m($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>l()==="darwin"?G0("/usr/bin/sandbox-exec"):l()==="linux",execute:async($)=>{let J=L1.parse($.payload),Z=A3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!M0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")))throw Error("local_device_gh_authority_changed");return u6({root:m($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>t3(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>T3({root:m($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>h6({root:m($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>m6({root:m($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:R2,execute:($)=>K8($.payload,$.signal)}};function _Q($,J){try{let Z=v3($,J0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function RQ($,J){try{let Z=J0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function PQ($,J){try{let Z=J0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function zQ($,J){try{let Z=J0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&v0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function qQ($,J){try{return D1({home:J0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&H1(Z.path)).slice(0,$2).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function nG($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||l()==="darwin",K=Q?PQ($,W1()):void 0,B=!J.worker&&l()==="darwin"?_Q($,W1()):void 0,G=Q?RQ($,W1()):void 0,U=!J.worker&&l()==="darwin"?zQ($,W1()):void 0,W=Q?qQ($,W1()):void 0,Y=S2.filter((X)=>{if(J1.has(X)&&!J.worker)return!1;if(J.worker&&!k1(X,J.worker))return!1;let N=h7[X];if(!N)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:N.available?.()??!0)&&$.some((F)=>(!J.worker||X!=="pty.start"||F.permissions.read&&F.permissions.write)&&E7(N).every((D)=>F.permissions[D]))});return{supported_operations:Y,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...W?{root_paths:W}:{},...Y.includes("hands.connect")?{hands_worker_artifact_sha256:P0,hands_worker_entrypoint:r0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:N0,max_result_bytes:N0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":V2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:g7(),sandbox:l()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:R3},...Y.includes("exec.full")?{"exec.full":y8()}:{},"git.run":{read_only_subcommands:[...q7].sort(),mutating_subcommands:[...O3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:W0,max_timeout_ms:i0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:W0,max_timeout_ms:i0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:n0,protocol_version:L3,worker_artifact_sha256:P0,worker_entrypoint:r0,policy_mode:"full_access",policy_version:1,workspace_base:M3,workspace_layout:$1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":l()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...Y.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:C7,max_session_ms:F7,max_buffered_output_bytes:N7}}:{},...J.worker?Object.fromEntries(Y.filter((X)=>X!=="browser.pr-proof.v1").map((X)=>[X,{ready:J.worker?.readiness?.[X]===!0,...J.worker?.readiness?.[X]!==!0&&J.worker?.probing?.includes(X)?{probing:!0}:{},execution_mode:k1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:k6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!m0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"&&J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:j6,workspace_base:M3,workspace_layout:$1,browser_state:"optional_headless",desktop:!1,worker_version:n0,protocol_version:L3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:Z6,[B6]:K6}:{},...J.worker?{[G6]:V6}:{},...J.worker?.handsBrowser?{[F6]:Y6}:{},[W6]:X6,[C6]:N6,...y0(J.worker?.executionMode==="unsandboxed")?{[D6]:H6}:{},...y0(J.worker?.executionMode==="unsandboxed")&&n1()!==null?{[L6]:M6}:{},...y0(J.worker?.executionMode==="unsandboxed")&&m0()?{[O6]:w6}:{}}:{},...X==="fs.export"?{cloud_source_version:R1,source_kinds:["workspace","attachment"],[w2]:O2}:{},...X==="fs.import"?{[w2]:O2}:{},...X===Q4&&n1()!==null&&y0(J.worker?.executionMode==="unsandboxed")?{[G4]:X2}:{},...X==="tunnel.open"?{carried_jobs:I6}:{},...X==="jobs.control"?{[T6]:A6}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[B7]:K7,[G7]:V7.join(","),[U7]:X7,[W7]:Y7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[_6]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[R6]:!0}:{}}])):{}}}}function E3($,J,Z,Q,K){let B=l6.safeParse(Q);return B.success&&K!==void 0&&K.device_id===$.deviceId&&B.data.device_id===$.deviceId&&B.data.root_id===J&&B.data.run_id===Z&&B.data.binding.kind===K.binding&&B.data.binding.target_revision===K.target_revision&&B.data.binding.root_grant_revision===K.root_grant_revision&&B.data.binding.target_generation===K.target_generation&&B.data.binding.target_fence_id===K.target_fence_id}async function rG($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==Q6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((Y)=>Y.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!E3($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let W=T3({root:m(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:W.snapshot_id,installed_revision:W.installed_revision,installed:!0},K),!0}async function aG($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==U6)return!1;let{version:K,run_id:B,target_generation:G,target_fence_id:U}=Z.payload;if(K!==1||Object.keys(Z.payload).length!==4||typeof B!=="string"||typeof G!=="number"||typeof U!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let W=$.roots.find((Y)=>Y.id===J.root_id);if(!W)throw new H("root_not_granted","The Hands root is no longer granted.");return await y6({operationId:J.operation_id,root:m(W),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function iG($,J,Z){if(J.capability!=="github.local.v1")return $6($,J,Z);try{let Q=await $6($,J,Z);if(Q.status==="succeeded")return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function $6($,J,Z){if(J1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!k1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=A3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=h7[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let K=$.roots.find((X)=>X.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&I3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&o0 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!E3($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(E7(Q).some((X)=>!K.permissions[X]))return{status:"failed",error_code:"permission_denied"};let B=0,G=async(X,N,C)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:B++,kind:X,capability:J.capability,data:N,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&C?{deliverySignal:C}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||eZ.has(J.capability)||J.capability==="pty.start",W,Y=async(X,N,C)=>{let F=W;W=void 0,await Promise.all([F,G(X,N,C)])};try{if(U)W=G("started"),W.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},N=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(C)=>G("pr-proof.started.v1",C))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:ZQ(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:X,runCommand:Z.runCommand??UQ,spawnFullControl:Z.spawnFullControl??q3,emit:U?Y:G,runHandsRelay:Z.runHandsRelay??((C)=>e6(C,X)),runPtySession:Z.runPtySession??D7});if(J.capability==="github.local.v1")J6.parse(N);if(!I3(N))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(N)??"null","utf8")>N0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?Y:G)("completed",{ok:!0}),{status:"succeeded",result:N,error_code:null}}catch(X){let N=Z.signal.reason instanceof H&&r5.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&r5.has(X.code)?X.code:null;if(Z.signal.aborted||N)return{status:"cancelled",...X instanceof c0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":N??"cancelled"};let C=J.capability==="inference.custom.v1"?"custom_endpoint_unavailable":J.capability==="github.local.v1"?"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&tZ.test(X.code)?X.code:"capability_failed",F=J.capability==="hands.connect"&&X instanceof t6?d6(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:C,...F?{expiry_diagnostic:F}:{}}),{status:"failed",error_code:C}}}
529
+ export{Z9 as y,Q9 as z,J4 as A,QK as B,GK as C,qK as D,EK as E,R2 as F,RB as G,Y0 as H,w$ as I,O$ as J,PB as K,z$ as L,E0 as M,Q1 as N,DJ as O,eZ as P,g7 as Q,k7 as R,VQ as S,q3 as T,UQ as U,YQ as V,MQ as W,TQ as X,h7 as Y,_Q as Z,RQ as _,PQ as $,zQ as aa,qQ as ba,nG as ca,rG as da,aG as ea,iG as fa};