@reason-machines/cli-linux-arm64-musl 0.2.345 → 0.2.347

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 (25) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/{ask-relay-bczg32b2.js → ask-relay-r3kbaq9w.js} +1 -1
  3. package/bin/vm-hands/{connect-cli-789rv77k.js → connect-cli-emmk9rt8.js} +1 -1
  4. package/bin/vm-hands/{local-automation-ms5cgtgc.js → local-automation-52xp11s7.js} +1 -1
  5. package/bin/vm-hands/{local-capabilities-jfmzy2qt.js → local-capabilities-1e3wt80s.js} +1 -1
  6. package/bin/vm-hands/{local-display-session-v8g6x39d.js → local-display-session-1n7nvyev.js} +1 -1
  7. package/bin/vm-hands/{permissions-9vwmb8cz.js → permissions-n8tms0vs.js} +1 -1
  8. package/bin/vm-hands/{status-jfa65qn3.js → status-t0aqrwcp.js} +2 -2
  9. package/bin/vm-hands/{version-mzcyw4fg.js → version-0pwphd3b.js} +1 -1
  10. package/bin/vm-hands/vm-hands-entry-lite-1wy28sjt.js +5 -0
  11. package/bin/vm-hands/{vm-hands-entry-lite-8dvf3de9.js → vm-hands-entry-lite-37gz1hkw.js} +1 -1
  12. package/bin/vm-hands/{vm-hands-entry-lite-y4mtveeb.js → vm-hands-entry-lite-3j7ksw6y.js} +1 -1
  13. package/bin/vm-hands/{vm-hands-entry-lite-jy102628.js → vm-hands-entry-lite-5cyt4sas.js} +1 -1
  14. package/bin/vm-hands/{vm-hands-entry-lite-1w8tvrpq.js → vm-hands-entry-lite-8ybyzy59.js} +2 -2
  15. package/bin/vm-hands/{vm-hands-entry-lite-y16b538h.js → vm-hands-entry-lite-aexevj7j.js} +37 -37
  16. package/bin/vm-hands/{vm-hands-entry-lite-2e50z7hj.js → vm-hands-entry-lite-atjh22sc.js} +1 -1
  17. package/bin/vm-hands/{vm-hands-entry-lite-ac6zyrj1.js → vm-hands-entry-lite-c6vkevd0.js} +1 -1
  18. package/bin/vm-hands/{vm-hands-entry-lite-hywf6580.js → vm-hands-entry-lite-d6389xx2.js} +2 -2
  19. package/bin/vm-hands/{vm-hands-entry-lite-b38m8a8m.js → vm-hands-entry-lite-f6kc5g59.js} +1 -1
  20. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  21. package/bin/vm-hands/{vm-hands-executor-tyxvq0j1.js → vm-hands-executor-xa08wrmr.js} +1 -1
  22. package/bin/vm-hands/{vm-hands-op-runner-k79jadt5.js → vm-hands-op-runner-eww4j86p.js} +1 -1
  23. package/bin/vm-hands/{vm-hands-runtime-dq1t8vee.js → vm-hands-runtime-gbptjv2t.js} +3 -3
  24. package/package.json +1 -1
  25. package/bin/vm-hands/vm-hands-entry-lite-b8y45rcs.js +0 -5
@@ -1,31 +1,31 @@
1
1
  // @bun
2
- import{Aa as C2,Ab as v0,Ba as w4,Bb as o1,Ca as O4,Da as I4,Ea as c6,Eb as W7,Fa as r6,Ga as P4,Ha as a6,Hb as D8,Ia as z3,Ib as k4,Ja as i6,Ka as o6,Kb as Y7,La as t6,Ma as e6,Na as z4,Oa as $7,Pa as J7,Wa as Z7,Ya as E4,Za as q4,cb as K7,db as B7,nb as S4,rb as G7,sb as U7,tb as u4,ub as d4,wb as X7,ya as L4,yb as H8,zb as h0}from"./vm-hands-entry-lite-jy102628.js";import{Lb as F7,Ob as N7,Qb as C7,Rb as H7}from"./vm-hands-entry-lite-7ba3nhgv.js";import{Wb as Q7}from"./vm-hands-entry-lite-wmxksawm.js";import{Xb as V4,Yb as d6,Zb as l6,cc as a0,dc as i0,kc as z0}from"./vm-hands-entry-lite-k2cvr710.js";import{lc as m6,mc as v6,nc as p6,oc as u6,pc as w0}from"./vm-hands-entry-lite-k469tezz.js";import{qc as B1}from"./vm-hands-entry-lite-8ynztq9j.js";import{Dc as d3,Fc as h6,sc as Z2,tc as Q2,uc as m3,wc as v3,yc as p3,zc as u3}from"./vm-hands-entry-lite-0wyjnvjz.js";import{_c as e1,bd as E7,kd as q7}from"./vm-hands-entry-lite-2e50z7hj.js";import{$d as q6,Ad as d,Ae as m8,Bd as f1,Be as v8,Ce as p8,De as u8,Ed as R8,Gd as b1,Id as Y6,Jd as F6,Kd as N6,Ld as C6,Md as H6,Nd as D6,Od as M6,Pd as L6,Qd as w6,Rd as O6,Sd as I6,Td as j6,Ud as A6,Vd as T6,Wd as _6,Xd as R6,Yd as P6,Zd as z6,_d as E6,be as g6,ce as S6,de as k6,ee as f6,fe as b6,ge as x6,he as y6,ld as I1,md as j1,nd as R3,ne as P8,od as G2,oe as z8,pd as W6,pe as E8,qd as P3,qe as q8,rd as K4,re as g8,sd as B4,se as S8,td as L0,ue as k8,ve as f8,we as b8,xd as C0,xe as x8,ye as y8,ze as h8}from"./vm-hands-entry-lite-36xzwsxn.js";import{Je as t5,Ne as C5,Oe as b5,Ue as g7,Xe as H5,Ye as a1}from"./vm-hands-entry-lite-b38m8a8m.js";import{af as t1}from"./vm-hands-entry-lite-pa111vpq.js";import{Bf as D7,Cf as M7,Df as L7,Ef as w7,Gf as O7,Hf as I7,Jf as j7,Kf as A7}from"./vm-hands-entry-lite-yeahy7rk.js";import{$f as P7,Vf as T7,Wf as _7,Xf as R7,cg as z7}from"./vm-hands-entry-lite-x6jqyxkx.js";import{mg as g4,tg as V7}from"./vm-hands-entry-lite-kt418g2w.js";import{Lg as s6,yg as I3}from"./vm-hands-entry-lite-knfh7w3j.js";import{Oh as _1,Ph as n6,Qh as _4,Rh as R4}from"./vm-hands-entry-lite-9dx3at21.js";import{$h as C8,Th as O3,Vh as Z1,ai as Y4}from"./vm-hands-entry-lite-289bc9v7.js";import{mi as V}from"./vm-hands-entry-lite-2xh7sjs0.js";import{ui as H}from"./vm-hands-entry-lite-gt5pkv4h.js";import{Ai as B8}from"./vm-hands-entry-lite-mhsv58hw.js";import{request as e7}from"http";import{request as $9}from"https";import{lookup as J9}from"dns/promises";import{isIP as Z9}from"net";async function Q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?$9:e7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:v3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var l3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),K9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function s3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(l3.has(Z))return"custom_endpoint_host_not_found";if(K9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=s3(Q,J+1);if(K)return K}return null}async function B9($,J){let Z=s3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||Z9(Q)!==0)return Z;let K;return await Promise.race([J9(Q).then(()=>!0,(G)=>!l3.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function V9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function G9($,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 c3($){$.signal.throwIfAborted();let J=u3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=d3.parse(await $.credential($.signal));if(!p3(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=V9(Q.apiKey),X=G9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let O=()=>{$.signal.removeEventListener("abort",O),M($.signal.reason)};if($.signal.addEventListener("abort",O,{once:!0}),$.signal.aborted){O();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",O),w()},(R)=>{$.signal.removeEventListener("abort",O),M(R)})})},C=async(N)=>{if(G+=N.length,G>Q2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=Z2){if(W>=m3)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+Z2).toString("base64")})}};try{let N=await Q9({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 O=K.headers[M];if(typeof O==="string")w[M]=O.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 O=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=O.length,U>Q2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(O))}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((K?null:await B9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as n3}from"path";function U9($,J){return $===n3(J,".ara","workspace")||$===n3(J,".reason","workspace")}function r3($,J){let Z=$.filter((Q)=>U9(Q.path,J));return Z.length===1?Z[0].path:null}var X9=/^[a-f0-9]{64}$/;var K2=32,W9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!W9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function w1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>K2)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"||!X9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as F9}from"child_process";import*as E from"fs";import*as a from"path";import{homedir as N9}from"os";function a3($,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 i3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var o3=[{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 B2($){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 t3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function e3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function O1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=t3(J).filter((G)=>!K.has(G));for(let G of $){let U=B2(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:i3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of o3){let F=e3(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:i3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function $4($,J=[]){let Z=t3(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 o3)for(let G of e3(B,K))Q.add(G[0])}return[...Q]}function Y9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function J4($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+Y9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var _0=4194304,Z4=536870912,V2=/^[a-f0-9]{40}$/,C9=($,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=F9($,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()}),H9={command:C9,gh:($,J)=>a3(E,a,$,J),home:N9};function A($){throw Error($)}function D9($,J){let Z=(K)=>K.trim().replace(/^co-authored-by:\s*/i,"Co-authored-by: "),Q=new Set($.split(/\r?\n/).map(Z));return[...new Set(J)].filter((K)=>!Q.has(Z(K)))}var M9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),L9=($)=>JSON.stringify($,(J,Z)=>M9.has(J)?void 0:Z);function Q4($,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 G4($,J,Z=H9){let Q=I1.parse($),K="local_device_gh_prepare_setup";try{if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let B=E.realpathSync(J.root);if(B==="/")A("local_device_gh_root_unavailable");if(!L0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!L0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!L0(Q)){let L=O1([{path:"github-operation",content:L9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)Q4(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let G=Z.gh(B),U=Z.home(),W=Z.gh(B,"git"),Y=J.privateDirectory?E.realpathSync(J.privateDirectory):E.realpathSync(U);if(!L0(Q)&&(!J.privateDirectory||Y===B||Y.startsWith(B+a.sep)))A("local_device_gh_private_scope_unavailable");let X={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:U,GH_CONFIG_DIR:a.join(U,".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]]]:[])):{}},F=async(L,_,z=Y,S,b=_0)=>{J.assertCurrent();let x=await Z.command(L,_,{cwd:z,env:X,input:S,maxBuffer:b,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),x.error||x.status!==0)A("local_device_gh_command_failed");return x.stdout},C=async(L)=>(await F(G,L)).toString("utf8").trim(),N=async(L,_="application/vnd.github+json")=>{K4(Q.repoFullName,L,{headers:{accept:_}}),J.assertCurrent();let z=await Z.command(G,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${_}`,L],{cwd:Y,env:X,maxBuffer:_0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),z.error&&z.status===null)A("local_device_gh_response_unavailable");let S=z.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!S)A("local_device_gh_response_invalid");let b=Number(S[1]);if(b>=200&&b<300&&z.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(S[3])>G2)A("local_device_gh_response_too_large");let x={};for(let o of S[2].split(/\r?\n/)){let $0=o.indexOf(":"),M0=o.slice(0,$0).toLowerCase();if(["link","content-type"].includes(M0))x[M0]=o.slice($0+1).trim().slice(0,8192)}return{kind:"read",status:b,headers:x,body:b>=200&&b<300?S[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return N(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,_]=Q.repoFullName.split("/"),z=await C(["api","graphql","--hostname","github.com","-f",`query=${B4}`,"-f",`owner=${L}`,"-f",`repo=${_}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(z)>G2)A("local_device_gh_response_too_large");let S=JSON.parse(z);if(S.errors||S.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||S.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:z}}if(Q.kind==="pr_merge"){let L=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),_=JSON.parse(L.body),z=(x)=>x.number===Q.number&&x.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&x.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&x.base?.ref===Q.expectedBaseRef&&x.head?.sha===Q.expectedHeadSha;if(L.status!==200||!z(_)||_.state!=="open"||_.draft!==!1||_.head?.sha!==Q.expectedHeadSha||_.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await C(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let S=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),b=JSON.parse(S.body);if(S.status!==200||!z(b)||b.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 C(["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,_=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 C(["pr",..._,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let D=E.realpathSync(J.repoPath);if(D!==B&&!D.startsWith(B+a.sep))A("local_device_gh_workspace_unavailable");let w=`https://github.com/${Q.repoFullName}.git`,M="!'"+G.replace(/'/g,"'\\''")+"' auth git-credential",O=Function("return ("+V4+")")(),R=(L,_,z)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,_,...z]]:[_,z],j=async(L,_,z,S=_0)=>{let b=L===Y||L.startsWith(Y+a.sep),x=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...b?["-c",`credential.https://github.com.helper=${M}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",..._];if(b)return F(W,x,L,z,S);let o=a.join(D,".ara-local-gh-tmp");if(E.mkdirSync(o,{recursive:!0,mode:448}),E.lstatSync(o).isSymbolicLink()||E.realpathSync(o)!==o)A("local_device_gh_workspace_unavailable");J.assertCurrent();let $0=await Z.command(...R(O(D,o),W,x),{cwd:L,input:z,maxBuffer:S,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:D,TMPDIR:o,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(),$0.error||$0.status!==0)A("local_device_gh_collection_failed");return $0.stdout},T=async(L,_)=>(await j(L,_)).toString("utf8").trim(),v=async(L,_)=>{let z=a.join(L,".ara-local-gh-tmp");if(E.mkdirSync(z,{recursive:!0,mode:448}),E.lstatSync(z).isSymbolicLink()||E.realpathSync(z)!==z)A("local_device_gh_workspace_unavailable");J.assertCurrent();let S=await Z.command(...R(O(L,z),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",_]),{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:z}});if(J.assertCurrent(),S.error||S.status!==0)A("local_device_gh_materialization_failed")},I=async(L)=>{let _=new Map;if(L.length===0)return _;let z=await j(m,["cat-file","--batch"],[...new Set(L)].join(`
2
+ import{Aa as H2,Ab as v0,Ba as O4,Bb as o1,Ca as j4,Da as I4,Ea as n6,Eb as Y7,Fa as a6,Ga as z4,Ha as i6,Hb as M8,Ia as E3,Ib as f4,Ja as o6,Ka as t6,Kb as F7,La as e6,Ma as $7,Na as E4,Oa as J7,Pa as Z7,Wa as Q7,Ya as q4,Za as g4,cb as K7,db as V7,nb as k4,rb as U7,sb as X7,tb as d4,ub as l4,wb as W7,ya as w4,yb as D8,zb as h0}from"./vm-hands-entry-lite-5cyt4sas.js";import{Lb as N7,Ob as C7,Qb as H7,Rb as D7}from"./vm-hands-entry-lite-7ba3nhgv.js";import{Wb as B7}from"./vm-hands-entry-lite-wmxksawm.js";import{Xb as G4,Yb as l6,Zb as s6,cc as a0,dc as i0,kc as z0}from"./vm-hands-entry-lite-k2cvr710.js";import{lc as v6,mc as p6,nc as u6,oc as d6,pc as w0}from"./vm-hands-entry-lite-k469tezz.js";import{qc as K1}from"./vm-hands-entry-lite-8ynztq9j.js";import{Dc as l3,Fc as m6,sc as Z2,tc as Q2,uc as v3,wc as p3,yc as u3,zc as d3}from"./vm-hands-entry-lite-0wyjnvjz.js";import{_c as e1,bd as q7,kd as g7}from"./vm-hands-entry-lite-atjh22sc.js";import{$d as g6,Ad as d,Ae as v8,Bd as f1,Be as p8,Ce as u8,De as d8,Ed as P8,Gd as b1,Id as F6,Jd as N6,Kd as C6,Ld as H6,Md as D6,Nd as M6,Od as L6,Pd as w6,Qd as O6,Rd as j6,Sd as I6,Td as A6,Ud as T6,Vd as _6,Wd as R6,Xd as P6,Yd as z6,Zd as E6,_d as q6,be as S6,ce as k6,de as f6,ee as b6,fe as x6,ge as y6,he as h6,ld as j1,md as I1,nd as P3,ne as z8,od as U2,oe as E8,pd as Y6,pe as q8,qd as z3,qe as g8,rd as K4,re as S8,sd as V4,se as k8,td as L0,ue as f8,ve as b8,we as x8,xd as C0,xe as y8,ye as h8,ze as m8}from"./vm-hands-entry-lite-36xzwsxn.js";import{Je as e5,Ne as H5,Oe as x5,Ue as S7,Xe as D5,Ye as a1}from"./vm-hands-entry-lite-f6kc5g59.js";import{af as t1}from"./vm-hands-entry-lite-pa111vpq.js";import{Bf as M7,Cf as L7,Df as w7,Ef as O7,Gf as j7,Hf as I7,Jf as A7,Kf as T7}from"./vm-hands-entry-lite-yeahy7rk.js";import{$f as z7,Vf as _7,Wf as R7,Xf as P7,cg as E7}from"./vm-hands-entry-lite-x6jqyxkx.js";import{mg as S4,tg as G7}from"./vm-hands-entry-lite-kt418g2w.js";import{Lg as c6,yg as I3}from"./vm-hands-entry-lite-knfh7w3j.js";import{Oh as _1,Ph as r6,Qh as R4,Rh as P4}from"./vm-hands-entry-lite-9dx3at21.js";import{$h as H8,Th as j3,Vh as Z1,ai as F4}from"./vm-hands-entry-lite-289bc9v7.js";import{mi as V}from"./vm-hands-entry-lite-2xh7sjs0.js";import{ui as H}from"./vm-hands-entry-lite-gt5pkv4h.js";import{Ai as V8}from"./vm-hands-entry-lite-mhsv58hw.js";import{request as $9}from"http";import{request as J9}from"https";import{lookup as Z9}from"dns/promises";import{isIP as Q9}from"net";async function B9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?J9:$9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:p3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var s3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),K9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function c3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(s3.has(Z))return"custom_endpoint_host_not_found";if(K9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=c3(Q,J+1);if(B)return B}return null}async function V9($,J){let Z=c3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||Q9(Q)!==0)return Z;let B;return await Promise.race([Z9(Q).then(()=>!0,(G)=>!s3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?Z:"custom_endpoint_host_not_found"}function G9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function U9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function n3($){$.signal.throwIfAborted();let J=d3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=l3.parse(await $.credential($.signal));if(!u3(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 B,K,G=0,U=0,W=0,Y=G9(Q.apiKey),X=U9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let O=()=>{$.signal.removeEventListener("abort",O),M($.signal.reason)};if($.signal.addEventListener("abort",O,{once:!0}),$.signal.aborted){O();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",O),w()},(R)=>{$.signal.removeEventListener("abort",O),M(R)})})},C=async(N)=>{if(G+=N.length,G>Q2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=Z2){if(W>=v3)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+Z2).toString("base64")})}};try{let N=await B9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.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 O=B.headers[M];if(typeof O==="string")w[M]=O.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of B){$.signal.throwIfAborted();let O=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=O.length,U>Q2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(O))}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((B?null:await V9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as r3}from"path";function X9($,J){return $===r3(J,".ara","workspace")||$===r3(J,".reason","workspace")}function a3($,J){let Z=$.filter((Q)=>X9(Q.path,J));return Z.length===1?Z[0].path:null}var W9=/^[a-f0-9]{64}$/;var B2=32,Y9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!Y9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function w1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>B2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!W9.test(B)||!L1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function F9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function N9($){return F9($)??$.email.toLowerCase()}function K2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?N9({name:J[1],email:J[2]}):$.trim().toLowerCase()}import{spawn as H9}from"child_process";import*as E from"fs";import*as a from"path";import{homedir as D9}from"os";function i3($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let B=$.realpathSync(Z),K=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,K])try{let U=$.realpathSync(G);if(U===B||U.startsWith(B+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 o3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var t3=[{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 V2($){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 e3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function $4($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function O1($,J=[],Z={}){let Q=[],B=Z.published??new Set,K=e3(J).filter((G)=>!B.has(G));for(let G of $){let U=V2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=K.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:o3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of t3){let F=$4(X,W).find((C)=>!B.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:o3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function J4($,J=[]){let Z=e3(J),Q=new Set;for(let{content:B}of $){for(let K of Z)if(B.includes(K))Q.add(K);for(let K of t3)for(let G of $4(K,B))Q.add(G[0])}return[...Q]}function C9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function Z4($,J,Z){let Q=(B,K)=>B.reduce((G,U)=>G+C9(U,K),0);return new Set($.filter((B)=>Q(J,B)<=Q(Z,B)))}var _0=4194304,Q4=536870912,G2=/^[a-f0-9]{40}$/,M9=($,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 B;try{B=H9($,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 K=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(N)=>{if(U??=Error(N),B.pid)try{process.kill(-B.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:K,stderr:G,...U?{error:U}:{}})};if(B.stdout.on("data",(N)=>{if(K.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else K=Buffer.concat([K,N])}),B.stderr.on("data",(N)=>{if(K.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),B.on("error",()=>{if(Y("spawn_failed"),!B.pid)C(null)}),B.on("close",(N)=>C(N)),B.stdin.on("error",()=>Y("input_failed")),B.stdin.end(Z.input),Z.signal?.aborted)X()}),L9={command:M9,gh:($,J)=>i3(E,a,$,J),home:D9};function A($){throw Error($)}function w9($,J){let Z=new Set($.split(/\r?\n/).map(K2));return J.filter((Q)=>{let B=K2(Q);if(Z.has(B))return!1;return Z.add(B),!0})}var O9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),j9=($)=>JSON.stringify($,(J,Z)=>O9.has(J)?void 0:Z);function B4($,J,Z){let Q=[...new Set($.map((K)=>`${J(K.path)}${K.line?`:${K.line}`:""} (${K.reason==="literal_secret_detected"?`value of ${K.secretNames?.length?K.secretNames.slice(0,3).join(", "):"a session variable"}`:`${K.ruleId??"credential"} credential`})`))].slice(0,10),B=$.some((K)=>K.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}${B?" 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 U4($,J,Z=L9){let Q=j1.parse($),B="local_device_gh_prepare_setup";try{if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=E.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!L0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!L0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!L0(Q)){let L=O1([{path:"github-operation",content:j9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)B4(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let G=Z.gh(K),U=Z.home(),W=Z.gh(K,"git"),Y=J.privateDirectory?E.realpathSync(J.privateDirectory):E.realpathSync(U);if(!L0(Q)&&(!J.privateDirectory||Y===K||Y.startsWith(K+a.sep)))A("local_device_gh_private_scope_unavailable");let X={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:U,GH_CONFIG_DIR:a.join(U,".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]]]:[])):{}},F=async(L,_,z=Y,S,b=_0)=>{J.assertCurrent();let x=await Z.command(L,_,{cwd:z,env:X,input:S,maxBuffer:b,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),x.error||x.status!==0)A("local_device_gh_command_failed");return x.stdout},C=async(L)=>(await F(G,L)).toString("utf8").trim(),N=async(L,_="application/vnd.github+json")=>{K4(Q.repoFullName,L,{headers:{accept:_}}),J.assertCurrent();let z=await Z.command(G,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${_}`,L],{cwd:Y,env:X,maxBuffer:_0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),z.error&&z.status===null)A("local_device_gh_response_unavailable");let S=z.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!S)A("local_device_gh_response_invalid");let b=Number(S[1]);if(b>=200&&b<300&&z.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(S[3])>U2)A("local_device_gh_response_too_large");let x={};for(let o of S[2].split(/\r?\n/)){let $0=o.indexOf(":"),M0=o.slice(0,$0).toLowerCase();if(["link","content-type"].includes(M0))x[M0]=o.slice($0+1).trim().slice(0,8192)}return{kind:"read",status:b,headers:x,body:b>=200&&b<300?S[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return N(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,_]=Q.repoFullName.split("/"),z=await C(["api","graphql","--hostname","github.com","-f",`query=${V4}`,"-f",`owner=${L}`,"-f",`repo=${_}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(z)>U2)A("local_device_gh_response_too_large");let S=JSON.parse(z);if(S.errors||S.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||S.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:z}}if(Q.kind==="pr_merge"){let L=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),_=JSON.parse(L.body),z=(x)=>x.number===Q.number&&x.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&x.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&x.base?.ref===Q.expectedBaseRef&&x.head?.sha===Q.expectedHeadSha;if(L.status!==200||!z(_)||_.state!=="open"||_.draft!==!1||_.head?.sha!==Q.expectedHeadSha||_.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await C(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let S=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),b=JSON.parse(S.body);if(S.status!==200||!z(b)||b.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 C(["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,_=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 C(["pr",..._,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let D=E.realpathSync(J.repoPath);if(D!==K&&!D.startsWith(K+a.sep))A("local_device_gh_workspace_unavailable");let w=`https://github.com/${Q.repoFullName}.git`,M="!'"+G.replace(/'/g,"'\\''")+"' auth git-credential",O=Function("return ("+G4+")")(),R=(L,_,z)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,_,...z]]:[_,z],I=async(L,_,z,S=_0)=>{let b=L===Y||L.startsWith(Y+a.sep),x=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...b?["-c",`credential.https://github.com.helper=${M}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",..._];if(b)return F(W,x,L,z,S);let o=a.join(D,".ara-local-gh-tmp");if(E.mkdirSync(o,{recursive:!0,mode:448}),E.lstatSync(o).isSymbolicLink()||E.realpathSync(o)!==o)A("local_device_gh_workspace_unavailable");J.assertCurrent();let $0=await Z.command(...R(O(D,o),W,x),{cwd:L,input:z,maxBuffer:S,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:D,TMPDIR:o,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(),$0.error||$0.status!==0)A("local_device_gh_collection_failed");return $0.stdout},T=async(L,_)=>(await I(L,_)).toString("utf8").trim(),v=async(L,_)=>{let z=a.join(L,".ara-local-gh-tmp");if(E.mkdirSync(z,{recursive:!0,mode:448}),E.lstatSync(z).isSymbolicLink()||E.realpathSync(z)!==z)A("local_device_gh_workspace_unavailable");J.assertCurrent();let S=await Z.command(...R(O(L,z),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",_]),{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:z}});if(J.assertCurrent(),S.error||S.status!==0)A("local_device_gh_materialization_failed")},j=async(L)=>{let _=new Map;if(L.length===0)return _;let z=await I(m,["cat-file","--batch"],[...new Set(L)].join(`
3
3
  `)+`
4
4
  `,_0*8);for(let S=0;S<z.length;){let b=z.indexOf(10,S),[x,o,$0]=z.subarray(S,b).toString("utf8").split(" ");if(b<0||!x||o!=="blob"||!/^[0-9]+$/.test($0??""))A("local_device_gh_object_invalid");_.set(x,z.subarray(b+1,b+1+Number($0)).toString("utf8")),S=b+1+Number($0)+1}return _},q=async(L,_,z)=>{let S=a.join(D,".ara-local-gh-tmp"),b=O(D,S)+`
5
5
  (allow file-read* file-write* (subpath ${JSON.stringify(D)}))
6
6
  (allow file-read* (subpath ${JSON.stringify(L)}))
7
- (allow file-read-metadata (path-ancestors ${JSON.stringify(L)}))`,x=async($0,M0)=>{J.assertCurrent();let l0=await Z.command(...R(b,$0,M0),{cwd:D,maxBuffer:_0,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:D,TMPDIR:S,GIT_INDEX_FILE:a.join(D,".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(),l0.error||l0.status!==0)A("local_device_gh_materialization_failed")},o=["--git-dir="+L,"--work-tree="+D,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await x(W,[...o,"read-tree",_]),await x(W,[...o,"checkout-index","--all","--index"]),await j(D,["update-ref","refs/heads/"+z,_]),await j(D,["symbolic-ref","HEAD","refs/heads/"+z])};K="local_device_gh_prepare_metadata";let P=await N(`/repos/${Q.repoFullName}`);if(P.status!==200)A("local_device_gh_repository_unavailable");let s=JSON.parse(P.body);if(s.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||s.default_branch!==Q.defaultBranch||Q.kind==="publish"&&s.permissions?.push!==!0)A("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)A("local_device_gh_default_branch");K="local_device_gh_prepare_private_init";let m=E.mkdtempSync(a.join(Y,"github-publication-"));E.chmodSync(m,448);let D1=!1;try{if(await j(m,["init","--bare","--template="]),Q.kind==="prepare"){if(K="local_device_gh_prepare_fetch",await j(m,["fetch","--depth=1","--no-tags","--no-recurse-submodules",w,Q.baseSha]),await T(m,["rev-parse","FETCH_HEAD"])!==Q.baseSha)K="local_device_gh_prepare_base_mismatch",A("local_device_gh_base_changed");K="local_device_gh_prepare_checkout_validation";let p=a.join(D,".git"),B0=!1;if(E.existsSync(p)){if(!E.lstatSync(p).isDirectory()||E.lstatSync(p).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((r)=>E.existsSync(a.join(p,r))))A("local_device_gh_repository_layout_invalid");let e=await j(D,["rev-parse","--verify","-q","HEAD"]).then((r)=>r.toString("utf8").trim(),()=>null),V0=await j(D,["config","--local","--get","remote.origin.url"]).then((r)=>r.toString("utf8").trim(),()=>"");if(e!==null||V0){if(e!==Q.baseSha||await T(D,["branch","--show-current"])!==Q.branch)A("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}B0=!0}let J0=E.readdirSync(D).filter((e)=>!(B0&&e===".git")),X0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if(J0.some((e)=>!X0.includes(e))||J0.some((e)=>{let V0=a.join(D,e);return!E.lstatSync(V0).isDirectory()||E.lstatSync(V0).isSymbolicLink()||E.readdirSync(V0).length>0}))A("local_device_gh_checkout_not_empty");if(K="local_device_gh_prepare_checkout_init",!B0)await j(D,["init","--template="]);K="local_device_gh_prepare_materialization";let N0=await j(m,["pack-objects","--stdout","--revs"],Q.baseSha+`
8
- `,Z4);return await v(D,Q.baseSha),await j(D,["index-pack","--strict","--stdin"],N0,65536),await j(D,["remote","add","origin",w]),await q(m,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let L=a.join(D,".git");if(!E.lstatSync(L).isDirectory()||E.lstatSync(L).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((p)=>E.existsSync(a.join(L,p))))A("local_device_gh_repository_layout_invalid");if(await T(D,["branch","--show-current"])!==Q.branch)A("local_device_gh_branch_changed");let _=await T(D,["rev-parse","--verify","HEAD"]);if(!V2.test(_))A("local_device_gh_head_invalid");let z=await N(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(z.status!==200||JSON.parse(z.body).sha!==Q.baseSha)A("local_device_gh_base_unverified");let S=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?S.status!==404:S.status!==200||JSON.parse(S.body).object?.sha!==Q.remoteHeadSha)A("local_device_gh_remote_changed");let b=[...(await T(D,["rev-list","--objects","--no-object-names",_,"--not",Q.baseSha])).split(`
7
+ (allow file-read-metadata (path-ancestors ${JSON.stringify(L)}))`,x=async($0,M0)=>{J.assertCurrent();let l0=await Z.command(...R(b,$0,M0),{cwd:D,maxBuffer:_0,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:D,TMPDIR:S,GIT_INDEX_FILE:a.join(D,".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(),l0.error||l0.status!==0)A("local_device_gh_materialization_failed")},o=["--git-dir="+L,"--work-tree="+D,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await x(W,[...o,"read-tree",_]),await x(W,[...o,"checkout-index","--all","--index"]),await I(D,["update-ref","refs/heads/"+z,_]),await I(D,["symbolic-ref","HEAD","refs/heads/"+z])};B="local_device_gh_prepare_metadata";let P=await N(`/repos/${Q.repoFullName}`);if(P.status!==200)A("local_device_gh_repository_unavailable");let s=JSON.parse(P.body);if(s.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||s.default_branch!==Q.defaultBranch||Q.kind==="publish"&&s.permissions?.push!==!0)A("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)A("local_device_gh_default_branch");B="local_device_gh_prepare_private_init";let m=E.mkdtempSync(a.join(Y,"github-publication-"));E.chmodSync(m,448);let D1=!1;try{if(await I(m,["init","--bare","--template="]),Q.kind==="prepare"){if(B="local_device_gh_prepare_fetch",await I(m,["fetch","--depth=1","--no-tags","--no-recurse-submodules",w,Q.baseSha]),await T(m,["rev-parse","FETCH_HEAD"])!==Q.baseSha)B="local_device_gh_prepare_base_mismatch",A("local_device_gh_base_changed");B="local_device_gh_prepare_checkout_validation";let p=a.join(D,".git"),K0=!1;if(E.existsSync(p)){if(!E.lstatSync(p).isDirectory()||E.lstatSync(p).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((r)=>E.existsSync(a.join(p,r))))A("local_device_gh_repository_layout_invalid");let e=await I(D,["rev-parse","--verify","-q","HEAD"]).then((r)=>r.toString("utf8").trim(),()=>null),V0=await I(D,["config","--local","--get","remote.origin.url"]).then((r)=>r.toString("utf8").trim(),()=>"");if(e!==null||V0){if(e!==Q.baseSha||await T(D,["branch","--show-current"])!==Q.branch)A("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}K0=!0}let J0=E.readdirSync(D).filter((e)=>!(K0&&e===".git")),X0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if(J0.some((e)=>!X0.includes(e))||J0.some((e)=>{let V0=a.join(D,e);return!E.lstatSync(V0).isDirectory()||E.lstatSync(V0).isSymbolicLink()||E.readdirSync(V0).length>0}))A("local_device_gh_checkout_not_empty");if(B="local_device_gh_prepare_checkout_init",!K0)await I(D,["init","--template="]);B="local_device_gh_prepare_materialization";let N0=await I(m,["pack-objects","--stdout","--revs"],Q.baseSha+`
8
+ `,Q4);return await v(D,Q.baseSha),await I(D,["index-pack","--strict","--stdin"],N0,65536),await I(D,["remote","add","origin",w]),await q(m,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let L=a.join(D,".git");if(!E.lstatSync(L).isDirectory()||E.lstatSync(L).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((p)=>E.existsSync(a.join(L,p))))A("local_device_gh_repository_layout_invalid");if(await T(D,["branch","--show-current"])!==Q.branch)A("local_device_gh_branch_changed");let _=await T(D,["rev-parse","--verify","HEAD"]);if(!G2.test(_))A("local_device_gh_head_invalid");let z=await N(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(z.status!==200||JSON.parse(z.body).sha!==Q.baseSha)A("local_device_gh_base_unverified");let S=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?S.status!==404:S.status!==200||JSON.parse(S.body).object?.sha!==Q.remoteHeadSha)A("local_device_gh_remote_changed");let b=[...(await T(D,["rev-list","--objects","--no-object-names",_,"--not",Q.baseSha])).split(`
9
9
  `),...(await T(D,["rev-list","--objects","--no-object-names","--no-walk",Q.baseSha])).split(`
10
- `)].filter(Boolean);if(b.some((p)=>!V2.test(p)))A("local_device_gh_object_invalid");let x=await j(D,["pack-objects","--stdout"],[...new Set(b)].join(`
10
+ `)].filter(Boolean);if(b.some((p)=>!G2.test(p)))A("local_device_gh_object_invalid");let x=await I(D,["pack-objects","--stdout"],[...new Set(b)].join(`
11
11
  `)+`
12
- `,Z4);if(E.writeFileSync(a.join(m,"shallow"),Q.baseSha+`
13
- `,{flag:"wx",mode:384}),await j(m,["index-pack","--strict","--stdin"],x,65536),await j(m,["merge-base","--is-ancestor",Q.baseSha,_]),Q.remoteHeadSha)await j(m,["merge-base","--is-ancestor",Q.remoteHeadSha,_]);let o=await j(m,["show","-s","--format=%B",_]),$0=(await j(m,["interpret-trailers","--parse"],o)).toString("utf8"),M0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:D9($0,Q.contributorTrailers)}:void 0,l0=(await T(m,["rev-list","--objects","--no-object-names",_,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
14
- `).filter(Boolean);if(l0.length>5000)A("local_device_gh_collection_too_large");let s0=[],b3=0;for(let p of l0){if(!V2.test(p))A("local_device_gh_object_invalid");let B0=await T(m,["cat-file","-t",p]);if(!["blob","commit","tree"].includes(B0))A("local_device_gh_object_invalid");let J0=await j(m,["cat-file",B0,p]);if(b3+=J0.length,b3>_0)A("local_device_gh_collection_too_large");if(B0==="tree"){let X0=0;while(X0<J0.length){let N0=J0.indexOf(32,X0),e=J0.indexOf(0,N0+1);if(N0<X0||e<=N0||e+21>J0.length)A("local_device_gh_object_invalid");let V0=J0.subarray(N0+1,e).toString("utf8");if(V0.includes("/")||!B2(V0).valid)A("local_device_gh_object_invalid");X0=e+21}}s0.push({path:`object-${p}`,content:J0.toString("utf8")})}let x3=J.secretNames?{secretNames:J.secretNames}:{},c0=O1(s0,J.forbiddenSecretValues,x3),y3=new Map;if(!c0.clean)try{let p=(await j(m,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,_])).toString("utf8").split("\x00"),B0=[],J0=[];for(let r=0;r+1<p.length;r+=2){let[,o7,t7,J2,M1]=p[r].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!J2||!M1)continue;if(o7!=="160000"&&!/^0+$/.test(J2))B0.push(J2);if(t7!=="160000"&&!/^0+$/.test(M1))J0.push(M1),y3.set(`object-${M1}`,p[r+1])}let X0=await I([...B0,...J0]),N0=new Set(c0.violations.map((r)=>r.path)),e=$4(s0.filter((r)=>N0.has(r.path)),J.forbiddenSecretValues),V0=J4(e,J0.map((r)=>X0.get(r)??""),B0.map((r)=>X0.get(r)??""));if(V0.size>0)c0=O1(s0,J.forbiddenSecretValues,{...x3,published:V0})}catch{}if(!c0.clean)Q4(c0.violations,(p)=>y3.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 j(m,["push","--no-recurse-submodules",w,`${_}:refs/heads/${Q.branch}`]);let h3=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(h3.status!==200||JSON.parse(h3.body).object?.sha!==_)A("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:_,scannedObjectCount:s0.length,...M0?{attribution:M0}:{}}}catch(L){throw D1=!0,L}finally{try{E.rmSync(m,{recursive:!0,force:!0})}catch(L){if(!D1||Q.kind!=="prepare")throw K=null,L}}}catch(B){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&K&&!J.signal?.aborted)throw new j1(K);throw B}}var R0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),U2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},w9=V.object({...U2,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(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),O9=V.object({...U2,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(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),X2=V.union([w9,O9]),NK=V.union([V.object({...U2,version:V.literal(1),development_only:V.literal(!0),profile:R0.shape.profile,extension_instance_id:R0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),X2]);import{randomUUID as D2}from"crypto";import{spawn as f9}from"child_process";import{existsSync as M2,lstatSync as f4,mkdirSync as b9,readFileSync as x9,realpathSync as A1,rmSync as y9,writeFileSync as h9}from"fs";import{dirname as b4,join as W0,relative as m9,sep as v9}from"path";var I9=["process.run.v1","process.full.v1"],j9=600000,A9=1800000,T9=20000,U4="process.cancel.v1",X4=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(A9).default(j9).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(),W2={device_id:V.string().uuid(),root_id:V.string().uuid()},_9=V.discriminatedUnion("action",[X4.extend(W2),V.object({...W2,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(T9).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({...W2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),DK=V.toJSONSchema(_9,{io:"input"}),MK=X4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),n0=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 W4($){return I9.includes($)}var LK=V.object({operation_constraints:V.record(V.string(),V.unknown())}),wK=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 R9=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(),P9=V.object({...n0.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:n0.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(),OK=V.toJSONSchema(P9),IK=V.union([n0,R9.refine(($)=>$.state==="cancelled_before_start")]),Y2=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)),z9=V.object({process_terminal_observation:Y2}).strict();function jK($,J){let Z=z9.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var F4="preview.serve.v1",N4=43200000;var RK=3,C4="preview.open.v1",H4=1,F2="gid_proxy_v1",D4="egress",N2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,E9=V.object({version:V.literal(F2),allowed_domains:V.array(V.string().max(260).regex(N2)).max(1024)}).strict(),q9=V.custom(($)=>Y4($)!==null,"invalid workspace"),g9=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:q9,egress:E9.optional()}).strict(),M4=g9.extend({expires_at:V.iso.datetime()}).strict();var S9=4,k9=5000;function H2($,J,Z){let Q=null;try{Q=C2($)}catch{}w4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function j4($){let J=new Map;return{open(Z){let Q=(X)=>H2(Z,$.claim.operation_id,X),K;try{K=C2(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!==H4||B.expiresAtMs>Math.min(Date.now()+L4.lifetimeMs+k9,$.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>=S9)return Q("preview_capacity");let W=new AbortController;J.set(B.port,W);let Y=I4({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}});O4({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 r0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var x4=256,T1=new Map,y4="preview.serve.v1",P0=new Map;function h4($){let J=P0.get($.operation_id);if(J){if(J.claim!==$)throw G0("process_authority_lost");return J}if(P0.size>=x4)throw G0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return P0.set($.operation_id,Z),Z}function A4($){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 T4=($)=>new Promise((J)=>setTimeout(J,$)),G0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function p9($=_1(),J=u9()){let Z=b4(g4({},$)),Q=m9(_4($),Z),[K,...B]=Q.split(v9);return{directory:W0(J,Q,"processes"),previous:[W0(Z,"processes"),...K==="reason"?[W0(J,"ara",...B,"processes")]:[]]}}function u9(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=R4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function R1($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw G0("process_authority_lost");let J=h4($.claim);if(J.executing)throw G0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",A4($.claim.operation_id);J.phase="starting";let Z=$.journals??p9();b9(Z.directory,{recursive:!0,mode:448});let Q=P4({runtimeDirectory:A1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((I)=>M2(I)).map((I)=>A1(I)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:x4});try{for(let I of[$.root,$.cwd])if(!S4(A1(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=f4(Q.journalDirectory),B=$.claim.capability===y4,G=()=>T1.set($.claim.operation_id,{path:Q.journalDirectory,ino:K.ino,dev:K.dev,anyCompletion:B}),U=b4(Q.socketPath),W=W0(U,"config.json"),Y={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:a0,protocolVersion:2,workerArtifactSha256:z0,workerEntrypoint:i0,targetGeneration:1,fenceId:D2(),workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:W0(U,"unused.env"),replSocketPath:W0(U,"unused.sock"),readyPath:W0(U,"ready.json"),directTerminalReceiptPath:W0(U,"terminal.json"),launchId:D2(),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{h9(W,JSON.stringify(Y),{mode:384});let I=k4({configPath:W,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(W,Y)??f9(I.command,I.args,{...I.options,env:$.environment,stdio:["ignore","ignore","ignore"]})}catch(I){throw Q.disposeSocket(),I}let F=!1,C=new Promise((I,q)=>{X.once("exit",(P)=>{F=!0,I(P)}),X.once("error",(P)=>{F=!0,q(P)})});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(I)=>{let q=await z4(N,{type:"job",version:2,generation:1,id:D2(),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 G0(q.error);return q.job},w=!1,M=!1,O,R=()=>{w=!0,X.kill("SIGTERM")};$.signal.addEventListener("abort",R,{once:!0});let j,T=0,v=async(I)=>{let q=[...I.output],P={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(P))>90000&&q.length)q.shift(),P.truncated=!0,P.first_cursor=q[0]?.cursor??P.next_cursor+1;j=n0.parse(P),await $.emit(j),T=Date.now()};try{let I=Math.min(Date.now()+1e4,$.expiresAtMs);while(!M2(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()>=I)throw G0("process_start_unconfirmed");await T4(25)}let q=JSON.parse(x9(Y.readyPath,"utf8"));if(q.launchId!==Y.launchId||q.fenceId!==Y.fenceId||q.workerArtifactSha256!==z0)throw G0();if($.signal.throwIfAborted(),J.cancelRequested)return A4($.claim.operation_id);let P;try{M=!0,P=await D("start")}catch(s){if(!(s instanceof H)||s.code!=="hands_job_result_unknown")throw s;P=await D("inspect")}if(J.phase="running",J.cancel=async()=>{await D("cancel")},B&&$.preview)J.tunnels=j4({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(),P=await D("inspect");for(;;){if(!["starting","running"].includes(P.state))J.phase="settling",J.cancel=void 0;if(!j||j.state!==P.state||j.next_cursor!==P.nextCursor&&Date.now()-T>=5000)await v(P);if(!["starting","running"].includes(P.state))break;if($.signal.aborted||F)throw G0();await T4(1000);try{P=await D("inspect"),O=void 0}catch(s){if(!(s instanceof H)||s.code!=="hands_job_result_unknown"||$.signal.aborted||F||Date.now()-(O??=Date.now())>120000)throw s}}if(!j||j.state==="uncertain")throw G0();return j}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",R),!F&&!w)X.kill("SIGTERM");let I,q=await Promise.race([C.then((P)=>({code:P})),new Promise((P)=>{I=setTimeout(()=>P(null),6000)})]).finally(()=>{clearTimeout(I)});if(!q){X.kill("SIGKILL");try{await C}finally{if(F)Q.disposeSocket()}throw G0("process_cleanup_unconfirmed")}try{if((w||$.signal.aborted)&&q.code===0&&M){E4(U);let P=JSON.parse(q4(Y.directTerminalReceiptPath)),s=Y2.safeParse(P.observation);if(Object.keys(P).length===4&&P.launch_id===Y.launchId&&P.fence_id===Y.fenceId&&P.scope_id===Q.scopeId&&s.success&&s.data.process_id===$.claim.operation_id){if(B)G();throw new r0(s.data)}}}catch(P){if(P instanceof r0)throw P}finally{if(F)Q.disposeSocket()}if(q.code!==0&&!w&&M)throw G0("process_cleanup_unconfirmed");if(!w&&q.code===0&&(j&&["exited","cancelled","expired"].includes(j.state)||!M&&J.cancelRequested)||B&&q.code===0&&!M)G()}}async function rK($,J){if(J.kind===C4&&$.capability===y4){let K=P0.get($.operation_id);if(K?.claim===$&&K.tunnels)K.tunnels.open(J.payload);else H2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==U4||!W4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=P0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=h4($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function aK($,J){P0.delete($);let Z=T1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return T1.delete($),!1;try{let Q=f4(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||Q.uid!==process.getuid?.()||(Q.mode&63)!==0||A1(Z.path)!==Z.path||M2(W0(Z.path,"owner.lock")))return!1;return y9(Z.path,{recursive:!0}),T1.delete($),!0}catch{return!1}}import{createServer as d9,request as l9}from"http";import{connect as s9,isIP as c9}from"net";var l4=120000,n9=15000;function r9($,J,Z){let Q=u4(J).toLowerCase().replace(/\.$/,"");if(!Q||c9(Q))return!1;return $.some((K)=>{if(!N2.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 a9($,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 L2($,J,Z){if(!r9(Z,$,J))return null;let Q=await d4($);return Q.ok?Q.addresses[0]:null}function o0($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
12
+ `,Q4);if(E.writeFileSync(a.join(m,"shallow"),Q.baseSha+`
13
+ `,{flag:"wx",mode:384}),await I(m,["index-pack","--strict","--stdin"],x,65536),await I(m,["merge-base","--is-ancestor",Q.baseSha,_]),Q.remoteHeadSha)await I(m,["merge-base","--is-ancestor",Q.remoteHeadSha,_]);let o=await I(m,["show","-s","--format=%B",_]),$0=(await I(m,["interpret-trailers","--parse"],o)).toString("utf8"),M0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:w9($0,Q.contributorTrailers)}:void 0,l0=(await T(m,["rev-list","--objects","--no-object-names",_,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
14
+ `).filter(Boolean);if(l0.length>5000)A("local_device_gh_collection_too_large");let s0=[],x3=0;for(let p of l0){if(!G2.test(p))A("local_device_gh_object_invalid");let K0=await T(m,["cat-file","-t",p]);if(!["blob","commit","tree"].includes(K0))A("local_device_gh_object_invalid");let J0=await I(m,["cat-file",K0,p]);if(x3+=J0.length,x3>_0)A("local_device_gh_collection_too_large");if(K0==="tree"){let X0=0;while(X0<J0.length){let N0=J0.indexOf(32,X0),e=J0.indexOf(0,N0+1);if(N0<X0||e<=N0||e+21>J0.length)A("local_device_gh_object_invalid");let V0=J0.subarray(N0+1,e).toString("utf8");if(V0.includes("/")||!V2(V0).valid)A("local_device_gh_object_invalid");X0=e+21}}s0.push({path:`object-${p}`,content:J0.toString("utf8")})}let y3=J.secretNames?{secretNames:J.secretNames}:{},c0=O1(s0,J.forbiddenSecretValues,y3),h3=new Map;if(!c0.clean)try{let p=(await I(m,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,_])).toString("utf8").split("\x00"),K0=[],J0=[];for(let r=0;r+1<p.length;r+=2){let[,t7,e7,J2,M1]=p[r].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!J2||!M1)continue;if(t7!=="160000"&&!/^0+$/.test(J2))K0.push(J2);if(e7!=="160000"&&!/^0+$/.test(M1))J0.push(M1),h3.set(`object-${M1}`,p[r+1])}let X0=await j([...K0,...J0]),N0=new Set(c0.violations.map((r)=>r.path)),e=J4(s0.filter((r)=>N0.has(r.path)),J.forbiddenSecretValues),V0=Z4(e,J0.map((r)=>X0.get(r)??""),K0.map((r)=>X0.get(r)??""));if(V0.size>0)c0=O1(s0,J.forbiddenSecretValues,{...y3,published:V0})}catch{}if(!c0.clean)B4(c0.violations,(p)=>h3.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 I(m,["push","--no-recurse-submodules",w,`${_}:refs/heads/${Q.branch}`]);let m3=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(m3.status!==200||JSON.parse(m3.body).object?.sha!==_)A("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:_,scannedObjectCount:s0.length,...M0?{attribution:M0}:{}}}catch(L){throw D1=!0,L}finally{try{E.rmSync(m,{recursive:!0,force:!0})}catch(L){if(!D1||Q.kind!=="prepare")throw B=null,L}}}catch(K){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&B&&!J.signal?.aborted)throw new I1(B);throw K}}var R0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),X2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},I9=V.object({...X2,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(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),A9=V.object({...X2,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(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),W2=V.union([I9,A9]),LB=V.union([V.object({...X2,version:V.literal(1),development_only:V.literal(!0),profile:R0.shape.profile,extension_instance_id:R0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),W2]);import{randomUUID as M2}from"crypto";import{spawn as y9}from"child_process";import{existsSync as L2,lstatSync as b4,mkdirSync as h9,readFileSync as m9,realpathSync as A1,rmSync as v9,writeFileSync as p9}from"fs";import{dirname as x4,join as W0,relative as u9,sep as d9}from"path";var T9=["process.run.v1","process.full.v1"],_9=600000,R9=1800000,P9=20000,X4="process.cancel.v1",W4=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(R9).default(_9).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(),Y2={device_id:V.string().uuid(),root_id:V.string().uuid()},z9=V.discriminatedUnion("action",[W4.extend(Y2),V.object({...Y2,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(P9).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({...Y2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),jB=V.toJSONSchema(z9,{io:"input"}),IB=W4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),n0=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 Y4($){return T9.includes($)}var AB=V.object({operation_constraints:V.record(V.string(),V.unknown())}),TB=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 E9=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(),q9=V.object({...n0.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:n0.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(),_B=V.toJSONSchema(q9),RB=V.union([n0,E9.refine(($)=>$.state==="cancelled_before_start")]),F2=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)),g9=V.object({process_terminal_observation:F2}).strict();function PB($,J){let Z=g9.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var N4="preview.serve.v1",C4=43200000;var gB=3,H4="preview.open.v1",D4=1,N2="gid_proxy_v1",M4="egress",C2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,S9=V.object({version:V.literal(N2),allowed_domains:V.array(V.string().max(260).regex(C2)).max(1024)}).strict(),k9=V.custom(($)=>F4($)!==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:k9,egress:S9.optional()}).strict(),L4=f9.extend({expires_at:V.iso.datetime()}).strict();var b9=4,x9=5000;function D2($,J,Z){let Q=null;try{Q=H2($)}catch{}O4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function A4($){let J=new Map;return{open(Z){let Q=(X)=>D2(Z,$.claim.operation_id,X),B;try{B=H2(Z)}catch{return Q("binding_invalid")}let{binding:K,deviceRelayUrl:G}=B,U=$.claim.owner;if(!U||K.organizationId!==U.organization_id||K.userId!==U.user_id||K.deviceId!==U.device_id||K.rootId!==$.claim.root_id||K.jobId!==$.claim.operation_id||K.fenceId!==$.claim.operation_id||K.generation!==D4||K.expiresAtMs>Math.min(Date.now()+w4.lifetimeMs+x9,$.expiresAtMs))return Q("binding_mismatch");if(K.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(K.port)?.abort(),J.delete(K.port),J.size>=b9)return Q("preview_capacity");let W=new AbortController;J.set(K.port,W);let Y=I4({binding:K,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(W.signal.aborted)return null;let X=await $.inspect();return X?{binding:K,executorLaunchId:$.executorLaunchId,job:X}:null}});j4({binding:K,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:K.jobId,port:K.port,reason_code:F})}
15
+ `)}).finally(()=>{if(J.get(K.port)===W)J.delete(K.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class r0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var y4=256,T1=new Map,h4="preview.serve.v1",P0=new Map;function m4($){let J=P0.get($.operation_id);if(J){if(J.claim!==$)throw G0("process_authority_lost");return J}if(P0.size>=y4)throw G0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return P0.set($.operation_id,Z),Z}function T4($){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 _4=($)=>new Promise((J)=>setTimeout(J,$)),G0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function l9($=_1(),J=s9()){let Z=x4(S4({},$)),Q=u9(R4($),Z),[B,...K]=Q.split(d9);return{directory:W0(J,Q,"processes"),previous:[W0(Z,"processes"),...B==="reason"?[W0(J,"ara",...K,"processes")]:[]]}}function s9(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=P4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function R1($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw G0("process_authority_lost");let J=m4($.claim);if(J.executing)throw G0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",T4($.claim.operation_id);J.phase="starting";let Z=$.journals??l9();h9(Z.directory,{recursive:!0,mode:448});let Q=z4({runtimeDirectory:A1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((j)=>L2(j)).map((j)=>A1(j)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:y4});try{for(let j of[$.root,$.cwd])if(!k4(A1(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 B=b4(Q.journalDirectory),K=$.claim.capability===h4,G=()=>T1.set($.claim.operation_id,{path:Q.journalDirectory,ino:B.ino,dev:B.dev,anyCompletion:K}),U=x4(Q.socketPath),W=W0(U,"config.json"),Y={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:a0,protocolVersion:2,workerArtifactSha256:z0,workerEntrypoint:i0,targetGeneration:1,fenceId:M2(),workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:W0(U,"unused.env"),replSocketPath:W0(U,"unused.sock"),readyPath:W0(U,"ready.json"),directTerminalReceiptPath:W0(U,"terminal.json"),launchId:M2(),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{p9(W,JSON.stringify(Y),{mode:384});let j=f4({configPath:W,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(W,Y)??y9(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",(P)=>{F=!0,j(P)}),X.once("error",(P)=>{F=!0,q(P)})});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 E4(N,{type:"job",version:2,generation:1,id:M2(),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 G0(q.error);return q.job},w=!1,M=!1,O,R=()=>{w=!0,X.kill("SIGTERM")};$.signal.addEventListener("abort",R,{once:!0});let I,T=0,v=async(j)=>{let q=[...j.output],P={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(P))>90000&&q.length)q.shift(),P.truncated=!0,P.first_cursor=q[0]?.cursor??P.next_cursor+1;I=n0.parse(P),await $.emit(I),T=Date.now()};try{let j=Math.min(Date.now()+1e4,$.expiresAtMs);while(!L2(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 G0("process_start_unconfirmed");await _4(25)}let q=JSON.parse(m9(Y.readyPath,"utf8"));if(q.launchId!==Y.launchId||q.fenceId!==Y.fenceId||q.workerArtifactSha256!==z0)throw G0();if($.signal.throwIfAborted(),J.cancelRequested)return T4($.claim.operation_id);let P;try{M=!0,P=await D("start")}catch(s){if(!(s instanceof H)||s.code!=="hands_job_result_unknown")throw s;P=await D("inspect")}if(J.phase="running",J.cancel=async()=>{await D("cancel")},K&&$.preview)J.tunnels=A4({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(),P=await D("inspect");for(;;){if(!["starting","running"].includes(P.state))J.phase="settling",J.cancel=void 0;if(!I||I.state!==P.state||I.next_cursor!==P.nextCursor&&Date.now()-T>=5000)await v(P);if(!["starting","running"].includes(P.state))break;if($.signal.aborted||F)throw G0();await _4(1000);try{P=await D("inspect"),O=void 0}catch(s){if(!(s instanceof H)||s.code!=="hands_job_result_unknown"||$.signal.aborted||F||Date.now()-(O??=Date.now())>120000)throw s}}if(!I||I.state==="uncertain")throw G0();return I}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",R),!F&&!w)X.kill("SIGTERM");let j,q=await Promise.race([C.then((P)=>({code:P})),new Promise((P)=>{j=setTimeout(()=>P(null),6000)})]).finally(()=>{clearTimeout(j)});if(!q){X.kill("SIGKILL");try{await C}finally{if(F)Q.disposeSocket()}throw G0("process_cleanup_unconfirmed")}try{if((w||$.signal.aborted)&&q.code===0&&M){q4(U);let P=JSON.parse(g4(Y.directTerminalReceiptPath)),s=F2.safeParse(P.observation);if(Object.keys(P).length===4&&P.launch_id===Y.launchId&&P.fence_id===Y.fenceId&&P.scope_id===Q.scopeId&&s.success&&s.data.process_id===$.claim.operation_id){if(K)G();throw new r0(s.data)}}}catch(P){if(P instanceof r0)throw P}finally{if(F)Q.disposeSocket()}if(q.code!==0&&!w&&M)throw G0("process_cleanup_unconfirmed");if(!w&&q.code===0&&(I&&["exited","cancelled","expired"].includes(I.state)||!M&&J.cancelRequested)||K&&q.code===0&&!M)G()}}async function eB($,J){if(J.kind===H4&&$.capability===h4){let B=P0.get($.operation_id);if(B?.claim===$&&B.tunnels)B.tunnels.open(J.payload);else D2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==X4||!Y4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=P0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=m4($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function $K($,J){P0.delete($);let Z=T1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return T1.delete($),!1;try{let Q=b4(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||Q.uid!==process.getuid?.()||(Q.mode&63)!==0||A1(Z.path)!==Z.path||L2(W0(Z.path,"owner.lock")))return!1;return v9(Z.path,{recursive:!0}),T1.delete($),!0}catch{return!1}}import{createServer as c9,request as n9}from"http";import{connect as r9,isIP as a9}from"net";var s4=120000,i9=15000;function o9($,J,Z){let Q=d4(J).toLowerCase().replace(/\.$/,"");if(!Q||a9(Q))return!1;return $.some((B)=>{if(!C2.test(B))return!1;let K=B.lastIndexOf(":"),G=K>0?B.slice(0,K):B;if(K>0&&Number(B.slice(K+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function t9($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,B=Z?Number(Z[2]):J;return Q&&B>=1&&B<=65535?{host:Q,port:B}:null}async function w2($,J,Z){if(!o9(Z,$,J))return null;let Q=await l4($);return Q.ok?Q.addresses[0]:null}function o0($,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 m4($,J){return new Promise((Z,Q)=>{let K=s9({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),n9);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(G)=>{clearTimeout(B),Q(G)})})}function v4($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(l4,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function p4($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function s4($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=d9((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 L2(Y.hostname,X,Z):null;if(!F){J(),W.writeHead(403,{connection:"close"}).end();return}let C=l9({host:F,port:X,method:U.method,path:`${Y.pathname}${Y.search}`,headers:p4(U.headers,Y.host),agent:!1,timeout:l4},(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=a9(U.url??"",443),F=X?await L2(X.host,X.port,Z):null;if(!X||!F){J(),o0(W,403);return}let C=await m4(F,X.port).catch(()=>null);if(!C){o0(W,502);return}if(W.destroyed){C.destroy();return}K(C),W.write(`HTTP/1.1 200 Connection Established\r
19
+ `)}function v4($,J){return new Promise((Z,Q)=>{let B=r9({host:$,port:J}),K=setTimeout(()=>B.destroy(Error("connect_timeout")),i9);B.once("connect",()=>{clearTimeout(K),Z(B)}),B.once("error",(G)=>{clearTimeout(K),Q(G)})})}function p4($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(s4,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function u4($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function c4($,J=()=>{}){let Z=[...$],Q=new Set,B=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},K=c9((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 w2(Y.hostname,X,Z):null;if(!F){J(),W.writeHead(403,{connection:"close"}).end();return}let C=n9({host:F,port:X,method:U.method,path:`${Y.pathname}${Y.search}`,headers:u4(U.headers,Y.host),agent:!1,timeout:s4},(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()})});K.on("connection",B),K.on("connect",(U,W,Y)=>{B(W),W.on("error",()=>W.destroy()),(async()=>{let X=t9(U.url??"",443),F=X?await w2(X.host,X.port,Z):null;if(!X||!F){J(),o0(W,403);return}let C=await v4(F,X.port).catch(()=>null);if(!C){o0(W,502);return}if(W.destroyed){C.destroy();return}B(C),W.write(`HTTP/1.1 200 Connection Established\r
20
20
  \r
21
- `),v4(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{o0(W,403);return}let F=Number(X.port||80),C=["http:","ws:"].includes(X.protocol)?await L2(X.hostname,F,Z):null;if(!C){J(),o0(W,403);return}let N=await m4(C,F).catch(()=>null);if(!N){o0(W,502);return}K(N);let D=p4(U.headers,X.host),w=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[M,O]of Object.entries(D))for(let R of Array.isArray(O)?O:O===void 0?[]:[O])w.push(`${M}: ${R}`);N.write(`${w.join(`\r
21
+ `),p4(W,C,Y)})().catch(()=>W.destroy())}),K.on("upgrade",(U,W,Y)=>{B(W),W.on("error",()=>W.destroy()),(async()=>{let X;try{X=new URL(U.url??"")}catch{o0(W,403);return}let F=Number(X.port||80),C=["http:","ws:"].includes(X.protocol)?await w2(X.hostname,F,Z):null;if(!C){J(),o0(W,403);return}let N=await v4(C,F).catch(()=>null);if(!N){o0(W,502);return}B(N);let D=u4(U.headers,X.host),w=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[M,O]of Object.entries(D))for(let R of Array.isArray(O)?O:O===void 0?[]:[O])w.push(`${M}: ${R}`);N.write(`${w.join(`\r
22
22
  `)}\r
23
23
  \r
24
- `),v4(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 T2,randomUUID as e9}from"crypto";import{closeSync as $1,constants as c,fchownSync as $$,fstatSync as E0,fsyncSync as J$,linkSync as Z$,mkdirSync as Q$,openSync as V8,readSync as G8,unlinkSync as K$,writeSync as B$}from"fs";import{platform as Q8}from"os";import{getSystemErrorName as V$}from"util";var c4={type:"string",format:"uuid"},i4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,P1={type:"string",minLength:1,maxLength:4096,pattern:i4},w2=V.string().min(1).max(4096).regex(new RegExp(i4)),z1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},E1={device_id:c4,root_id:c4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},QB={read:{schema:V.object({...z1,path:w2,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:{...E1,path:P1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...z1,path:w2,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:{...E1,path:P1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...z1,command:V.string().min(1).max(16000),cwd:w2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...E1,command:{type:"string",minLength:1,maxLength:16000},cwd:P1,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}}},Y0=1073741824,t0=600000,n4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,o4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${n4}(?:/${n4})*(?![\s\S])`,t4=new RegExp(o4);function e4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&t4.test($)}var O2=V.string().min(1).max(4096).regex(t4),I2={...P1,pattern:o4},$8=V.string().regex(/^[a-f0-9]{64}$/),J8=V.object({kind:V.literal("workspace"),path:O2}).strict(),i9=V.discriminatedUnion("kind",[J8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:$8}).strict()]),q1=1,e0="cloud_workspace_id",j2="cloud_workspace",A2=1,o9=V.discriminatedUnion("kind",[J8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(Y0),sha256:$8}).strict()]),Z8=V.object({source_version:V.literal(q1),source:o9,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(),[e0]:V.string().min(1).max(160).optional()}).strict(),KB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(q1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var r4=V.object({...z1,timeout_ms:V.number().int().min(1000).max(t0).optional(),source_path:O2,destination_path:O2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),a4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...E1,timeout_ms:{type:"integer",minimum:1000,maximum:t0},source_path:I2,destination_path:I2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},t9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:I2},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}]},BB=V.union([r4,r4.omit({source_path:!0}).extend({source:i9}).strict()]),VB={...a4,required:["device_id","root_id","destination_path"],properties:{...a4.properties,source:t9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var _2=65536;function u($){throw new H($,$)}function S1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function g1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function G$($,J,Z){let Q;switch(S1($)){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 g1($,J,Q)}function U$($){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 X$(){if(Q8()==="linux")return{open:(U,W,Y,X=384)=>V8(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>Q$(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>Z$(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>K$(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(Q8()!=="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=V$(-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 U8($,J){let Z=E0($),Q=E0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)$$(J,Z.uid,Z.gid)}function W$($,J,Z,Q){if(!e4(Z))return u("transfer_path_invalid");let K=Z.split("/"),B=V8(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||S1(W)!=="ENOENT")throw W;try{$.mkdir(B,G)}catch(Y){if(S1(Y)!=="EEXIST")throw Y}U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW),U8(B,U)}$1(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw $1(B),G}}function K8($,J){let Z=E0($,{bigint:!0});if(!Z.isFile()||Z.size>Y0)return u("transfer_file_invalid");let Q=T2("sha256"),K=Buffer.alloc(_2),B=0;while(!0){J.throwIfAborted();let U=G8($,K,0,K.length,B);if(!U)break;if(B+=U,B>Y0)return u("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=E0($,{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=U$($.payload.url),Z=await X$(),Q,K,B;try{if(Q=W$(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=E0(K,{bigint:!0});if(!C.isFile()||C.size>Y0)return u("transfer_file_invalid");let N=T2("sha256"),D=0,w=K,M,O=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let I=Buffer.alloc(_2),q=G8(w,I,0,I.length,D);if(!q){v.close();return}if(D+=q,D>C.size)return u("transfer_source_changed");N.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:O,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 g1(v,$.signal,"transfer_upload_failed")}let R=E0(K,{bigint:!0});if(BigInt(D)!==C.size||R.size!==C.size||R.mtimeNs!==C.mtimeNs||R.ctimeNs!==C.ctimeNs)return u("transfer_source_changed");let j=N.digest("hex"),T=K8(K,$.signal);if(T.size_bytes!==D||T.sha256!==j)return u("transfer_source_changed");return{size_bytes:D,sha256:j,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>Y0||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(S1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=K8(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{$1(W)}return u("transfer_destination_exists")}B=`.reason-copy-${e9()}`,K=Z.open(Q.fd,B,c.O_CREAT|c.O_EXCL|c.O_WRONLY|c.O_NOFOLLOW,384),U8(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 g1(C,$.signal,"transfer_download_failed")}let X=T2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((N)=>g1(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+=B$(K,C.value,N,Math.min(_2,C.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return J$(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)$1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}$1(Q.fd)}}finally{Z.close()}}}}catch(J){return G$(J,$.signal,$.direction)}}import{spawn as F$}from"child_process";import{mkdtempSync as N$,rmSync as C$,writeFileSync as H$}from"fs";import{constants as D$,platform as M$,tmpdir as L$}from"os";import{join as F8}from"path";import{gunzipSync as Y$,gzipSync as DB}from"zlib";var W8=900000,LB=W8+60000,J1=49152,X8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),Y8=V.object({version:V.literal(1),script_gzip:X8(163840),stdin_gzip:X8(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(W8)}).strict(),R2=V.string().max(J1+256),wB=V.object({exit_code:V.number().int().min(0).max(255),stdout:R2,stderr:R2,combined:R2.optional()}).strict();function P2($){return Y$(Buffer.from($,"base64")).toString("utf8")}var w$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",O$=["RUSTUP_HOME","TZ","LC_ALL"],I$=2000,j$=100;function E2(){return M$()==="linux"&&process.geteuid?.()===0}function z2($){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
+ `),p4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{K.once("error",W),K.listen(0,"127.0.0.1",()=>U())});let{port:G}=K.address();return{url:`http://127.0.0.1:${G}`,close(){K.close();for(let U of Q)U.destroy()}}}import{createHash as _2,randomUUID as Z$}from"crypto";import{closeSync as $1,constants as c,fchownSync as Q$,fstatSync as E0,fsyncSync as B$,linkSync as K$,mkdirSync as V$,openSync as G8,readSync as U8,unlinkSync as G$,writeSync as U$}from"fs";import{platform as B8}from"os";import{getSystemErrorName as X$}from"util";var n4={type:"string",format:"uuid"},o4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,P1={type:"string",minLength:1,maxLength:4096,pattern:o4},O2=V.string().min(1).max(4096).regex(new RegExp(o4)),z1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},E1={device_id:n4,root_id:n4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},UK={read:{schema:V.object({...z1,path:O2,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:{...E1,path:P1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...z1,path:O2,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:{...E1,path:P1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...z1,command:V.string().min(1).max(16000),cwd:O2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...E1,command:{type:"string",minLength:1,maxLength:16000},cwd:P1,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}}},Y0=1073741824,t0=600000,r4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,t4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${r4}(?:/${r4})*(?![\s\S])`,e4=new RegExp(t4);function $8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&e4.test($)}var j2=V.string().min(1).max(4096).regex(e4),I2={...P1,pattern:t4},J8=V.string().regex(/^[a-f0-9]{64}$/),Z8=V.object({kind:V.literal("workspace"),path:j2}).strict(),e9=V.discriminatedUnion("kind",[Z8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:J8}).strict()]),q1=1,e0="cloud_workspace_id",A2="cloud_workspace",T2=1,$$=V.discriminatedUnion("kind",[Z8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(Y0),sha256:J8}).strict()]),Q8=V.object({source_version:V.literal(q1),source:$$,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(),[e0]:V.string().min(1).max(160).optional()}).strict(),XK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(q1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var a4=V.object({...z1,timeout_ms:V.number().int().min(1000).max(t0).optional(),source_path:j2,destination_path:j2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),i4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...E1,timeout_ms:{type:"integer",minimum:1000,maximum:t0},source_path:I2,destination_path:I2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},J$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:I2},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}]},WK=V.union([a4,a4.omit({source_path:!0}).extend({source:e9}).strict()]),YK={...i4,required:["device_id","root_id","destination_path"],properties:{...i4.properties,source:J$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var R2=65536;function u($){throw new H($,$)}function S1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function g1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function W$($,J,Z){let Q;switch(S1($)){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 g1($,J,Q)}function Y$($){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 F$(){if(B8()==="linux")return{open:(U,W,Y,X=384)=>G8(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>V$(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>K$(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>G$(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(B8()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),B=$("/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}}),K=B.symbols.__error();if(K===null)return B.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=X$(-Q.i32(K));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(B.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(B.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(B.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(B.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>B.close()}}function X8($,J){let Z=E0($),Q=E0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)Q$(J,Z.uid,Z.gid)}function N$($,J,Z,Q){if(!$8(Z))return u("transfer_path_invalid");let B=Z.split("/"),K=G8(J,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW);try{for(let G of B.slice(0,-1)){let U;try{U=$.open(K,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW)}catch(W){if(!Q||S1(W)!=="ENOENT")throw W;try{$.mkdir(K,G)}catch(Y){if(S1(Y)!=="EEXIST")throw Y}U=$.open(K,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW),X8(K,U)}$1(K),K=U}return{fd:K,leaf:B.at(-1)}}catch(G){throw $1(K),G}}function K8($,J){let Z=E0($,{bigint:!0});if(!Z.isFile()||Z.size>Y0)return u("transfer_file_invalid");let Q=_2("sha256"),B=Buffer.alloc(R2),K=0;while(!0){J.throwIfAborted();let U=U8($,B,0,B.length,K);if(!U)break;if(K+=U,K>Y0)return u("transfer_size_exceeded");Q.update(B.subarray(0,U))}let G=E0($,{bigint:!0});if(BigInt(K)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:K,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=Y$($.payload.url),Z=await F$(),Q,B,K;try{if(Q=N$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){B=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK);let C=E0(B,{bigint:!0});if(!C.isFile()||C.size>Y0)return u("transfer_file_invalid");let N=_2("sha256"),D=0,w=B,M,O=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let j=Buffer.alloc(R2),q=U8(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:O,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 g1(v,$.signal,"transfer_upload_failed")}let R=E0(B,{bigint:!0});if(BigInt(D)!==C.size||R.size!==C.size||R.mtimeNs!==C.mtimeNs||R.ctimeNs!==C.ctimeNs)return u("transfer_source_changed");let I=N.digest("hex"),T=K8(B,$.signal);if(T.size_bytes!==D||T.sha256!==I)return u("transfer_source_changed");return{size_bytes:D,sha256:I,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>Y0||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(S1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=K8(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{$1(W)}return u("transfer_destination_exists")}K=`.reason-copy-${Z$()}`,B=Z.open(Q.fd,K,c.O_CREAT|c.O_EXCL|c.O_WRONLY|c.O_NOFOLLOW,384),X8(Q.fd,B);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 g1(C,$.signal,"transfer_download_failed")}let X=_2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((N)=>g1(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+=U$(B,C.value,N,Math.min(R2,C.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return B$(B),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,K,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(B!==void 0)$1(B)}finally{try{if(Q){if(K)try{Z.unlink(Q.fd,K)}catch{}$1(Q.fd)}}finally{Z.close()}}}}catch(J){return W$(J,$.signal,$.direction)}}import{spawn as H$}from"child_process";import{mkdtempSync as D$,rmSync as M$,writeFileSync as L$}from"fs";import{constants as w$,platform as O$,tmpdir as j$}from"os";import{join as N8}from"path";import{gunzipSync as C$,gzipSync as jK}from"zlib";var Y8=900000,AK=Y8+60000,J1=49152,W8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),F8=V.object({version:V.literal(1),script_gzip:W8(163840),stdin_gzip:W8(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(Y8)}).strict(),P2=V.string().max(J1+256),TK=V.object({exit_code:V.number().int().min(0).max(255),stdout:P2,stderr:P2,combined:P2.optional()}).strict();function z2($){return C$(Buffer.from($,"base64")).toString("utf8")}var I$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",A$=["RUSTUP_HOME","TZ","LC_ALL"],T$=2000,_$=100;function q2(){return O$()==="linux"&&process.geteuid?.()===0}function E2($){let J=Math.floor($/2),Z=[],Q=0,B=Buffer.alloc(0),K=0;return{push(G){K+=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)B=Buffer.concat([B,U]).subarray(-J)},text(){let G=K-Q-B.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
25
25
  [reason: ${G} bytes of output omitted]
26
- `:"")+K.toString("utf8")}}}async function N8($,J){if(!E2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=Y8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=P2(Q.script_gzip),B=P2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=N$(F8(L$(),"reason-workspace-setup-"));try{let U=F8(G,"setup.sh");H$(U,K,{mode:384});let W={PATH:w$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let T of O$)if(process.env[T])W[T]=process.env[T];Object.assign(W,Q.env);let Y=F$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=z2(J1),F=z2(J1),C=z2(J1);Y.stdout.on("data",(T)=>{X.push(T),C.push(T)}),Y.stderr.on("data",(T)=>{F.push(T),C.push(T)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let N=(T)=>{try{if(Y.pid)process.kill(-Y.pid,T)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),I$)},O=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let R=await new Promise((T,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(I,q)=>T({code:I,signal:q}))}).finally(()=>{clearTimeout(O),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((T)=>{let v=setTimeout(T,j$);Y.once("close",()=>{clearTimeout(v),T()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:R.signal?128+(D$.signals[R.signal]??0):R.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:C.text()}:{}}}finally{C$(G,{recursive:!0,force:!0})}}import{chmodSync as A$,mkdtempSync as T$,realpathSync as M8,rmSync as _$}from"fs";import{tmpdir as R$}from"os";import{dirname as P$,join as q2,sep as z$}from"path";function g2($){return D8($,H8($)!==null).repoPath}function L8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Z1,void 0].map((K)=>P$(C8({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=M8(q2($,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(`${$}${z$}`))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=g2($.runtimeRoot);if(w0(Q)||w0(q2(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=T$(q2(R$(),`reason-cloud-copy-${process.pid}-`));try{A$(Z,448);let Q=M8(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{_$(Z,{recursive:!0,force:!0})}}import{constants as T0}from"fs";import{closeSync as S7,existsSync as U0,fstatSync as k7,lstatSync as f7,mkdirSync as VQ,mkdtempSync as b7,openSync as x7,readSync as GQ,realpathSync as Z0,rmSync as y7,statSync as H1,writeSync as UQ}from"fs";import{homedir as F1,platform as l,tmpdir as h7}from"os";import{dirname as N1,isAbsolute as XQ,join as E3,relative as j3,resolve as WQ,sep as YQ}from"path";import{spawn as FQ}from"child_process";import{createHash as k$,randomBytes as f$}from"crypto";var S2=30000,E$=1800000,q$=5000,k1=30000,g$=b1+15000,O8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,S$=[/^\/app\/local-runtime\/operations\/claim$/,O8];class k2{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(S$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},g$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=k1)this.drop(Q);else G=setTimeout(W,k1-Y)};G=setTimeout(W,k1)}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>k1)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(q$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(E$,S2*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(f1,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()+S2;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(!O8.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(S2,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 b2=["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 sB($,J={}){let Z=b$($),Q=J.rootPathsSupported===!0?w1($.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 b$($){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 F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class x1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function x$($){return $===408||$===429||$===500||$===502||$===503||$===504}function y$($){if($ instanceof F0)return!1;if($ instanceof x1)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 h$($,J,Z=500){if(J instanceof F0&&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 m$($,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 cB($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function I8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function j8($){return k$("sha256").update($??"").digest("hex")}function v$($){return P8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function A8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var p$=20000,u$=1e4,T8=[2000,4000],d$=30000,l$=15000;function _8($){return $?{keepalive:!1}:{}}class f2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class s${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}=z8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??T8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof f2))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 f2(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,..._8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return E8(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>=p$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,T8[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)()>=u$?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=j8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>f$(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(v$({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||!R8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new k2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",f1,Q,j8("")),...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&&I8(J.body)>C0)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??m$,W=this.sessionFor($,J.device),Y=Math.max(d$,(J.holdMs??0)+l$),X={fresh:!1},F;for(let C=0;C<G;C+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new x1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let O=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,M,J.useSpareChallenge===!0&&C===0,C===0?J.issuedChallenge:void 0,X),R=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...O,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,..._8(X.fresh),signal:M});return await this.parseResponse(R)}catch(O){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw O}finally{clearTimeout(w)}}catch(N){if(F=N,N instanceof x1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),w=N instanceof F0&&x$(N.status),M=y$(N),O=J.transientRetryOwner!=="caller"&&(w||M);if((D||O)&&C+1<G){let R=D?0:h$(C,N,this.proofOptions.retryBaseDelayMs??500);if(R>0)await U(R,J.signal);continue}if(D&&C+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return q8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return g8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return S8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return k8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return f8(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 b8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});y8(Q)}async localSubscription($,J,Z){return x8(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 F0&&K.status===404)return null;throw K});if(Q===null)return null;if(!A8(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,b1))},signal:J.signal});if(B===null)return null;return h8(B,b2)}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 F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return m8(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)||!A8(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 v8(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(I8(K)>C0)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 u8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-syw4d5k4.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 p8(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 c$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),Q1=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 y1($,J){if(c$.has($))return!1;if(Q1.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($)||Q1.has($)))return!1;return!0}import{accessSync as n$,constants as r$,existsSync as a$,statSync as i$}from"fs";import{basename as o$,isAbsolute as t$}from"path";var K1=["-lic"],e$="/bin/zsh",$J=new Set(["zsh","bash"]),d8=20000,x2=60000,JJ=65536,ZJ=64,QJ=8192,KJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),BJ=["DYLD_","LD_"];function VJ($){let J=$.toUpperCase();return KJ.has(J)||BJ.some((Z)=>J.startsWith(Z))}function l8($=process.env){return!0}function GJ($){if(!t$($)||$.includes("\x00"))return!1;if(!$J.has(o$($)))return!1;try{if(!i$($).isFile())return!1;return n$($,r$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&GJ(J))return J;return e$}function y2($=process.env){return l8($)&&a$(g0($))}function h2($=process.env){if(!l8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function m2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>JJ)throw new H("invalid_payload","command is missing or too large.");return $}function v2($){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>ZJ)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")>QJ)throw new H("invalid_payload","env entry is invalid or too large.");if(VJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function s8($){let J=$.processEnv??process.env;if(h2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=m2($.command),Q=g0(J),{forwarded:K,ignored:B}=v2($.requestEnv),G=await $.spawn(Q,[...K1,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:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function c8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.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:x2}}import{readFile as UJ,readdir as XJ,readlink as WJ,realpath as YJ}from"fs/promises";import{basename as FJ,relative as NJ,sep as CJ}from"path";var O0="/proc",HJ=250,n8=500,DJ=50,MJ=250,LJ=1024,r8=4096,wJ=1,OJ=3,a8=9,IJ="0A",jJ=/^socket:\[(\d+)\]$/,p2={readDirectory:($)=>XJ($),readLink:($)=>WJ($),readTextFile:($)=>UJ($,"utf8"),realPath:($)=>YJ($)};function o8($,J){return J===$||J.startsWith(`${$}${CJ}`)}function AJ($,J){return NJ($,J)||"."}async function t8($){let J;try{J=await $.readDirectory(O0)}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 e8($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,r8).split(`
27
- `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,r8).split("\x00",1)[0]?.trim();return Q?FJ(Q):null}catch{return null}}async function $5($,J=p2){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function J5($,J=p2){let Z=[];for(let Q of await t8(J)){if(Z.length>=HJ)break;let K=await $5(Q,J);if(!K||!o8($,K))continue;Z.push({pid:Q,command:await e8(Q,J),cwd:AJ($,K)})}return{processes:Z}}function i8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function TJ($){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 _J($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=i8($);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(...i8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${TJ(Z)}]:${J}`}return null}function RJ($,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<=a8)continue;if(K[OJ]?.toUpperCase()!==IJ)continue;let B=K[wJ]??"",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=_J(B.slice(0,G),U),Y=K[a8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function PJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=n8)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...RJ(Q,n8-J.length))}return J}async function zJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await t8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,LJ)){let G;try{G=await J.readLink(`${O0}/${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 Z5($,J=p2){let Z=await PJ(J),Q=await zJ(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,DJ),G=await Promise.all(B.map(async(X)=>[X,await $5(X,J)])),U=new Map(G),W=K.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&o8($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await e8(X,J)])));return{ports:W.slice(0,MJ).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as d2}from"path";var h1=200,EJ=250,qJ=250;async function m1($,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 u2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var Q5="/System/Volumes/Data",gJ=["/tmp","/var","/etc"];function l2($){let J=d2.normalize($);if(J.startsWith(`${Q5}/`))J=J.slice(Q5.length);return gJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function K5($){return $&&d2.isAbsolute($)?l2($):null}async function B5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=h1){let K=J.slice(Q,Q+h1).join(",");for(let B of await m1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:K5(B.names[0])})}return Z}async function V5($,J){let Z=l2($),Q=(await m1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=K5(B.names[0]);return G!==null&&u2(Z,G)}).map((B)=>B.pid).slice(0,EJ),K=await B5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&u2(Z,G.cwd)?[{pid:B,command:G.command,cwd:d2.relative(Z,G.cwd)||"."}]:[]})}}async function G5($,J){let Z=l2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await m1(J,Q),B=await B5(J,K.map((Y)=>Y.pid)),G=K.map((Y)=>Y.pid).filter((Y)=>{let X=B.get(Y)?.cwd;return Boolean(X&&u2(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+=h1){let X=G.slice(Y,Y+h1).join(",");for(let F of await m1(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,qJ)}}import{join as lJ}from"path";import{spawn as hJ}from"child_process";import{randomUUID as mJ}from"crypto";import{chmodSync as W5,lstatSync as Y5,mkdirSync as vJ,readdirSync as pJ,statSync as uJ,unlinkSync as dJ}from"fs";import{join as c2}from"path";var s2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var v1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var I0=()=>{throw Error("proof_visual_contract_invalid")};class U5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function kJ($){if(!B1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new U5;if(!B1($.viewport)||!v1($.viewport.width,1,4096)||!v1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>s2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return I0();let J=$.targets.map((Q)=>{if(!B1(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 I0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return I0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return I0();Z=$.additionalViewports.map((K)=>{if(!B1(K)||!v1(K.width,1,4096)||!Number.isInteger(K.width)||!v1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return I0();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 I0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var bJ=["organizationId","userId","sessionId","runId"],xJ=[...bJ,"prUrl","headSha","skillDigest","evidenceKind"],YV=[...xJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var yJ={"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 X5($){return yJ[$].directory}var F5=10485760;function N5($={}){let J=$.directory??X5("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");vJ(J,{recursive:!0,mode:457});let B=Y5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");W5(J,457);let G=pJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:uJ(c2(J,M)).mtimeMs})).sort((M,O)=>O.time-M.time);for(let M of G.slice(9))dJ(c2(J,M.name));let U=c2(J,`${mJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??hJ)($.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(F5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,C=!1,N=new Promise((M,O)=>{X=M,F=O});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,O)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),O(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(R)=>{try{if(R!==0&&R!==255)throw Error();let j=Y5(U);if(!C||!j.isFile()||j.isSymbolicLink()||j.uid!==process.getuid?.()||j.size<128||j.size>F5+65536)throw Error();W5(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),O(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 D5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??C5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=lJ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??H5)();return B??=N5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:_1(),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 Y3}from"child_process";import{createHash as VZ,randomUUID as GZ}from"crypto";import{existsSync as K0,mkdirSync as V3,mkdtempSync as F3,readdirSync as r1,readFileSync as N3,renameSync as UZ,rmSync as U1,statSync as l1,writeFileSync as XZ}from"fs";import{homedir as C3,tmpdir as x5}from"os";import{basename as y5,dirname as G3,join as g,relative as h5,resolve as U3,sep as m5}from"path";var i=V.string().min(1).max(200),Q0=V.number().finite().min(0).max(1e4),p1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),M5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),r2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),a2=["home","lock","side_button","siri","apple_pay"],sJ=V.enum(["tree","screenshot","both","none"]),cJ=V.object({...r2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),H0={observe:sJ.optional(),wait_for:cJ.optional(),timeout:V.number().min(0).max(20).optional()},n2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Q0.optional(),y:Q0.optional(),...r2.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:Q0,y:Q0,x2:Q0,y2:Q0,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(a2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),i2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:i}).strict(),V.object({action:V.literal("shutdown"),device:i}).strict(),V.object({action:V.literal("build"),path:p1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:p1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),steps:V.array(V.lazy(()=>n2)).max(30).optional(),...H0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:i.optional(),app_path:p1.optional(),bundle_id:M5.optional(),steps:V.array(V.lazy(()=>n2)).max(30).optional(),...H0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:i.optional(),bundle_id:M5}).strict(),V.object({action:V.literal("logs"),device:i.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:i.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:p1.optional()}).strict(),V.object({action:V.literal("chrome"),device:i.optional()}).strict(),V.object({action:V.literal("inspect"),device:i.optional()}).strict(),V.object({action:V.literal("tap"),device:i.optional(),x:Q0.optional(),y:Q0.optional(),...r2.shape,duration:V.number().min(0).max(10).optional(),...H0}).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:i.optional(),x:Q0,y:Q0,x2:Q0,y2:Q0,duration:V.number().min(0.05).max(5).optional(),...H0}).strict(),V.object({action:V.literal("type"),device:i.optional(),text:V.string().min(1).max(4000),...H0}).strict(),V.object({action:V.literal("button"),device:i.optional(),name:V.enum(a2),...H0}).strict(),V.object({action:V.literal("open_url"),device:i.optional(),url:V.string().min(1).max(4000),...H0}).strict(),V.object({action:V.literal("steps"),device:i.optional(),steps:V.array(n2).min(1).max(30),...H0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),L5=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(),qV=V.object({text:V.string(),error:V.string().optional(),device:L5.optional(),devices:V.array(L5).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 gV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),SV={type:"object",properties:{action:{type:"string",enum:i2.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:[...a2]},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 $3}from"child_process";import{createHash as rJ}from"crypto";import{existsSync as t2,mkdirSync as u1,mkdtempSync as aJ,readdirSync as w5,readFileSync as O5,renameSync as iJ,rmSync as I5,symlinkSync as e2,writeFileSync as V1}from"fs";import{homedir as oJ}from"os";import{dirname as _5,join as f}from"path";import{createInterface as tJ}from"readline";var o2=`// Reason's simulator host: one warm process per booted iOS Simulator.
26
+ `:"")+B.toString("utf8")}}}async function C8($,J){if(!q2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=F8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=z2(Q.script_gzip),K=z2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=D$(N8(j$(),"reason-workspace-setup-"));try{let U=N8(G,"setup.sh");L$(U,B,{mode:384});let W={PATH:I$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let T of A$)if(process.env[T])W[T]=process.env[T];Object.assign(W,Q.env);let Y=H$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=E2(J1),F=E2(J1),C=E2(J1);Y.stdout.on("data",(T)=>{X.push(T),C.push(T)}),Y.stderr.on("data",(T)=>{F.push(T),C.push(T)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(T)=>{try{if(Y.pid)process.kill(-Y.pid,T)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),T$)},O=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let R=await new Promise((T,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(j,q)=>T({code:j,signal:q}))}).finally(()=>{clearTimeout(O),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((T)=>{let v=setTimeout(T,_$);Y.once("close",()=>{clearTimeout(v),T()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let I=D?124:R.signal?128+(w$.signals[R.signal]??0):R.code??1;return{exit_code:Math.min(255,I),stdout:X.text(),stderr:F.text(),...I!==0?{combined:C.text()}:{}}}finally{M$(G,{recursive:!0,force:!0})}}import{chmodSync as R$,mkdtempSync as P$,realpathSync as L8,rmSync as z$}from"fs";import{tmpdir as E$}from"os";import{dirname as q$,join as g2,sep as g$}from"path";function S2($){return M8($,D8($)!==null).repoPath}function w8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Z1,void 0].map((B)=>q$(H8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=L8(g2($,B));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${g$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function O8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=S2($.runtimeRoot);if(w0(Q)||w0(g2(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=P$(g2(E$(),`reason-cloud-copy-${process.pid}-`));try{R$(Z,448);let Q=L8(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 B=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return B}finally{z$(Z,{recursive:!0,force:!0})}}import{constants as T0}from"fs";import{closeSync as k7,existsSync as U0,fstatSync as f7,lstatSync as b7,mkdirSync as XQ,mkdtempSync as x7,openSync as y7,readSync as WQ,realpathSync as Z0,rmSync as h7,statSync as H1,writeSync as YQ}from"fs";import{homedir as F1,platform as l,tmpdir as m7}from"os";import{dirname as N1,isAbsolute as FQ,join as q3,relative as A3,resolve as NQ,sep as CQ}from"path";import{spawn as HQ}from"child_process";import{createHash as x$,randomBytes as y$}from"crypto";var k2=30000,S$=1800000,k$=5000,k1=30000,f$=b1+15000,j8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,b$=[/^\/app\/local-runtime\/operations\/claim$/,j8];class f2{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 B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(b$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},f$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=k1)this.drop(Q);else G=setTimeout(W,k1-Y)};G=setTimeout(W,k1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>k1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,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(k$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(S$,k2*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(f1,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()+k2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.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[B,K]of Q.pending){if(!j8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(k2,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 x2=["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 iK($,J={}){let Z=h$($),Q=J.rootPathsSupported===!0?w1($.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((B)=>/^[a-f0-9]{64}$/.test(B))?{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 h$($){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 B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).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))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class x1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function m$($){return $===408||$===429||$===500||$===502||$===503||$===504}function v$($){if($ instanceof F0)return!1;if($ instanceof x1)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 p$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function u$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function oK($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function I8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function A8($){return x$("sha256").update($??"").digest("hex")}function d$($){return z8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function T8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var l$=20000,s$=1e4,_8=[2000,4000],c$=30000,n$=15000;function R8($){return $?{keepalive:!1}:{}}class b2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class r${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 B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=E8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??_8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof b2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new b2(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:B,...R8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return q8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.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>=l$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,_8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=s$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=A8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>y$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(d$({method:$,route:J,timestamp:B,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:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!P8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new f2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",f1,Q,A8("")),...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&&I8(J.body)>C0)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 K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??u$,W=this.sessionFor($,J.device),Y=Math.max(c$,(J.holdMs??0)+n$),X={fresh:!1},F;for(let C=0;C<G;C+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new x1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let O=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&C===0,C===0?J.issuedChallenge:void 0,X),R=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...O,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...R8(X.fresh),signal:M});return await this.parseResponse(R)}catch(O){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw O}finally{clearTimeout(w)}}catch(N){if(F=N,N instanceof x1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),w=N instanceof F0&&m$(N.status),M=v$(N),O=J.transientRetryOwner!=="caller"&&(w||M);if((D||O)&&C+1<G){let R=D?0:p$(C,N,this.proofOptions.retryBaseDelayMs??500);if(R>0)await U(R,J.signal);continue}if(D&&C+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return g8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return S8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return k8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return f8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return b8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return x8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});h8(Q)}async localSubscription($,J,Z){return y8(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((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.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((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!T8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))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}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,b1))},signal:J.signal});if(K===null)return null;return m8(K,x2)}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)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return v8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!T8(B.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 p8(Q)}async completeOperation($,J,Z,Q){let B={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(I8(B)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return d8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-syw4d5k4.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 B=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 u8(B)}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 a$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),Q1=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 y1($,J){if(a$.has($))return!1;if(Q1.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($)||Q1.has($)))return!1;return!0}import{accessSync as i$,constants as o$,existsSync as t$,statSync as e$}from"fs";import{basename as $J,isAbsolute as JJ}from"path";var B1=["-lic"],ZJ="/bin/zsh",QJ=new Set(["zsh","bash"]),l8=20000,y2=60000,BJ=65536,KJ=64,VJ=8192,GJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),UJ=["DYLD_","LD_"];function XJ($){let J=$.toUpperCase();return GJ.has(J)||UJ.some((Z)=>J.startsWith(Z))}function s8($=process.env){return!0}function WJ($){if(!JJ($)||$.includes("\x00"))return!1;if(!QJ.has($J($)))return!1;try{if(!e$($).isFile())return!1;return i$($,o$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&WJ(J))return J;return ZJ}function h2($=process.env){return s8($)&&t$(g0($))}function m2($=process.env){if(!s8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function v2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>BJ)throw new H("invalid_payload","command is missing or too large.");return $}function p2($){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>KJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>VJ)throw new H("invalid_payload","env entry is invalid or too large.");if(XJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function c8($){let J=$.processEnv??process.env;if(m2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=v2($.command),Q=g0(J),{forwarded:B,ignored:K}=p2($.requestEnv),G=await $.spawn(Q,[...B1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});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:[...B1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function n8($=process.env){return{transport:"shell",shell:`${g0($)} ${B1.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:y2}}import{readFile as YJ,readdir as FJ,readlink as NJ,realpath as CJ}from"fs/promises";import{basename as HJ,relative as DJ,sep as MJ}from"path";var O0="/proc",LJ=250,r8=500,wJ=50,OJ=250,jJ=1024,a8=4096,IJ=1,AJ=3,i8=9,TJ="0A",_J=/^socket:\[(\d+)\]$/,u2={readDirectory:($)=>FJ($),readLink:($)=>NJ($),readTextFile:($)=>YJ($,"utf8"),realPath:($)=>CJ($)};function t8($,J){return J===$||J.startsWith(`${$}${MJ}`)}function RJ($,J){return DJ($,J)||"."}async function e8($){let J;try{J=await $.readDirectory(O0)}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 $5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,a8).split(`
27
+ `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,a8).split("\x00",1)[0]?.trim();return Q?HJ(Q):null}catch{return null}}async function J5($,J=u2){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function Z5($,J=u2){let Z=[];for(let Q of await e8(J)){if(Z.length>=LJ)break;let B=await J5(Q,J);if(!B||!t8($,B))continue;Z.push({pid:Q,command:await $5(Q,J),cwd:RJ($,B)})}return{processes:Z}}function o8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function PJ($){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,B=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(B<0)B=W;continue}if(B>=0){let Y=W-B;if(Y>Q)Z=B,Q=Y;B=-1}}let K=J.map((W)=>W.toString(16));if(Q<2)return K.join(":");let G=K.slice(0,Z).join(":"),U=K.slice(Z+Q).join(":");return`${G}::${U}`}function zJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=o8($);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(...o8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${PJ(Z)}]:${J}`}return null}function EJ($,J){let Z=[];for(let Q of $.split(`
28
+ `).slice(1)){if(Z.length>=J)break;let B=Q.trim().split(/\s+/);if(B.length<=i8)continue;if(B[AJ]?.toUpperCase()!==TJ)continue;let K=B[IJ]??"",G=K.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(K.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=zJ(K.slice(0,G),U),Y=B[i8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function qJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=r8)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...EJ(Q,r8-J.length))}return J}async function gJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await e8(J)){if(Z.size>=$.size)break;let B;try{B=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let K of B.slice(0,jJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${K}`)}catch{continue}let U=G.match(_J)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function Q5($,J=u2){let Z=await qJ(J),Q=await gJ(new Set(Z.map((X)=>X.inode)),J),B=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;B.push({pid:F,port:X.port,address:X.address})}B.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let K=[...new Set(B.map((X)=>X.pid))].slice(0,wJ),G=await Promise.all(K.map(async(X)=>[X,await J5(X,J)])),U=new Map(G),W=B.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&t8($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await $5(X,J)])));return{ports:W.slice(0,OJ).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as l2}from"path";var h1=200,SJ=250,kJ=250;async function m1($,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=[],B=null;for(let K of Z.stdout.split(/\r?\n/))if(K.startsWith("p")){let G=Number(K.slice(1));if(B=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,B)Q.push(B)}else if(B&&K.startsWith("c"))B.command=K.slice(1)||null;else if(B&&K.startsWith("n"))B.names.push(K.slice(1));return Q}function d2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var B5="/System/Volumes/Data",fJ=["/tmp","/var","/etc"];function s2($){let J=l2.normalize($);if(J.startsWith(`${B5}/`))J=J.slice(B5.length);return fJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function K5($){return $&&l2.isAbsolute($)?s2($):null}async function V5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=h1){let B=J.slice(Q,Q+h1).join(",");for(let K of await m1($,["-a","-p",B,"-d","cwd","-Fpcn"]))Z.set(K.pid,{command:K.command,cwd:K5(K.names[0])})}return Z}async function G5($,J){let Z=s2($),Q=(await m1(J,["-d","cwd","-Fpn"])).filter((K)=>{let G=K5(K.names[0]);return G!==null&&d2(Z,G)}).map((K)=>K.pid).slice(0,SJ),B=await V5(J,Q);return{processes:Q.flatMap((K)=>{let G=B.get(K);return G?.cwd&&d2(Z,G.cwd)?[{pid:K,command:G.command,cwd:l2.relative(Z,G.cwd)||"."}]:[]})}}async function U5($,J){let Z=s2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],B=await m1(J,Q),K=await V5(J,B.map((Y)=>Y.pid)),G=B.map((Y)=>Y.pid).filter((Y)=>{let X=K.get(Y)?.cwd;return Boolean(X&&d2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(B.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=h1){let X=G.slice(Y,Y+h1).join(",");for(let F of await m1(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,kJ)}}import{join as nJ}from"path";import{spawn as pJ}from"child_process";import{randomUUID as uJ}from"crypto";import{chmodSync as Y5,lstatSync as F5,mkdirSync as dJ,readdirSync as lJ,statSync as sJ,unlinkSync as cJ}from"fs";import{join as n2}from"path";var c2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var v1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var j0=()=>{throw Error("proof_visual_contract_invalid")};class X5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function xJ($){if(!K1($)||$.version!==1)return j0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new X5;if(!K1($.viewport)||!v1($.viewport.width,1,4096)||!v1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>c2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return j0();let J=$.targets.map((Q)=>{if(!K1(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((B)=>!["id","selector"].includes(B)))return j0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return j0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return j0();Z=$.additionalViewports.map((B)=>{if(!K1(B)||!v1(B.width,1,4096)||!Number.isInteger(B.width)||!v1(B.height,1,4096)||!Number.isInteger(B.height)||Object.keys(B).some((K)=>!["width","height"].includes(K)))return j0();return{width:B.width,height:B.height}});let Q=[$.viewport,...Z].map((B)=>`${B.width}x${B.height}`);if(new Set(Q).size!==Q.length)return j0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var hJ=["organizationId","userId","sessionId","runId"],mJ=[...hJ,"prUrl","headSha","skillDigest","evidenceKind"],DV=[...mJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var vJ={"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 W5($){return vJ[$].directory}var N5=10485760;function C5($={}){let J=$.directory??W5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let B=Q?.seconds;if(!Number.isInteger(B)||Number(B)<1||Number(B)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");dJ(J,{recursive:!0,mode:457});let K=F5(J);if(!K.isDirectory()||K.isSymbolicLink()||K.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");Y5(J,457);let G=lJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:sJ(n2(J,M)).mtimeMs})).sort((M,O)=>O.time-M.time);for(let M of G.slice(9))cJ(n2(J,M.name));let U=n2(J,`${uJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??pJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(B),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(N5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,C=!1,N=new Promise((M,O)=>{X=M,F=O});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,O)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),O(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(R)=>{try{if(R!==0&&R!==255)throw Error();let I=F5(U);if(!C||!I.isFile()||I.isSymbolicLink()||I.uid!==process.getuid?.()||I.size<128||I.size>N5+65536)throw Error();Y5(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),O(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(B)+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(B)}},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 M5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??H5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let B=nJ($.runtimeDirectory,"recordings"),K=null;return{async start(G){let U=await(J.desktop??D5)();return K??=C5({directory:B,display:U.display,ffmpeg:Q,env:{HOME:_1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),K.start(G)},async stop(){if(!K)throw Error("cloud_browser_recording_not_started");return K.stop()},async close(){await K?.close()}}}import{spawn as F3}from"child_process";import{createHash as XZ,randomUUID as WZ}from"crypto";import{existsSync as B0,mkdirSync as G3,mkdtempSync as N3,readdirSync as r1,readFileSync as C3,renameSync as YZ,rmSync as U1,statSync as l1,writeFileSync as FZ}from"fs";import{homedir as H3,tmpdir as y5}from"os";import{basename as h5,dirname as U3,join as g,relative as m5,resolve as X3,sep as v5}from"path";var i=V.string().min(1).max(200),Q0=V.number().finite().min(0).max(1e4),p1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),L5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),a2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),i2=["home","lock","side_button","siri","apple_pay"],rJ=V.enum(["tree","screenshot","both","none"]),aJ=V.object({...a2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),H0={observe:rJ.optional(),wait_for:aJ.optional(),timeout:V.number().min(0).max(20).optional()},r2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Q0.optional(),y:Q0.optional(),...a2.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:Q0,y:Q0,x2:Q0,y2:Q0,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(i2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),o2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:i}).strict(),V.object({action:V.literal("shutdown"),device:i}).strict(),V.object({action:V.literal("build"),path:p1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:p1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),steps:V.array(V.lazy(()=>r2)).max(30).optional(),...H0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:i.optional(),app_path:p1.optional(),bundle_id:L5.optional(),steps:V.array(V.lazy(()=>r2)).max(30).optional(),...H0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:i.optional(),bundle_id:L5}).strict(),V.object({action:V.literal("logs"),device:i.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:i.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:p1.optional()}).strict(),V.object({action:V.literal("chrome"),device:i.optional()}).strict(),V.object({action:V.literal("inspect"),device:i.optional()}).strict(),V.object({action:V.literal("tap"),device:i.optional(),x:Q0.optional(),y:Q0.optional(),...a2.shape,duration:V.number().min(0).max(10).optional(),...H0}).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:i.optional(),x:Q0,y:Q0,x2:Q0,y2:Q0,duration:V.number().min(0.05).max(5).optional(),...H0}).strict(),V.object({action:V.literal("type"),device:i.optional(),text:V.string().min(1).max(4000),...H0}).strict(),V.object({action:V.literal("button"),device:i.optional(),name:V.enum(i2),...H0}).strict(),V.object({action:V.literal("open_url"),device:i.optional(),url:V.string().min(1).max(4000),...H0}).strict(),V.object({action:V.literal("steps"),device:i.optional(),steps:V.array(r2).min(1).max(30),...H0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),w5=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(),bV=V.object({text:V.string(),error:V.string().optional(),device:w5.optional(),devices:V.array(w5).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()}),yV={type:"object",properties:{action:{type:"string",enum:o2.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:[...i2]},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 J3}from"child_process";import{createHash as oJ}from"crypto";import{existsSync as e2,mkdirSync as u1,mkdtempSync as tJ,readdirSync as O5,readFileSync as j5,renameSync as eJ,rmSync as I5,symlinkSync as $3,writeFileSync as V1}from"fs";import{homedir as $Z}from"os";import{dirname as R5,join as f}from"path";import{createInterface as JZ}from"readline";var t2=`// 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 j5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",eJ=180000,$Z=15000,JZ=30000,ZZ=600000,QZ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
487
+ `;var A5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",ZZ=180000,QZ=15000,BZ=30000,KZ=600000,VZ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
488
488
  @end
489
- `).join("");function A5($,J,Z){return new Promise((Q)=>{let K=$3($,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 T5=new Map;function J3($){let J=f(_5($),"Frameworks"),Z=T5.get(J);if(!Z)T5.set(J,Z=KZ(J));return Z}async function KZ($){if(process.platform!=="darwin"||!t2(f($,"FBSimulatorControl.framework")))return null;let J=await A5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=rJ("sha256").update(o2).update(J.output).update($).digest("hex").slice(0,16),Q=f(oJ(),".local","share","reason","simulator","host"),K=f(Q,Z,"simulator-host");if(t2(K))return K;u1(Q,{recursive:!0,mode:448});let B=aJ(f(Q,".staging-"));try{let G=f(B,"Frameworks"),U=f(G,"FBSimulatorControl.framework"),W=f(U,"Modules","FBSimulatorControl.swiftmodule");u1(W,{recursive:!0});for(let w of w5($))if(w!=="FBSimulatorControl.framework")e2(f($,w),f(G,w));let Y=f($,"FBSimulatorControl.framework");e2(f(Y,"FBSimulatorControl"),f(U,"FBSimulatorControl")),e2(f(Y,"Headers"),f(U,"Headers")),V1(f(U,"Modules","module.modulemap"),O5(f(Y,"Modules","module.modulemap")));let X=O5(f(Y,"Modules","FBSimulatorControl.swiftmodule",`${j5}.swiftinterface`),"utf8");V1(f(W,`${j5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let F=f(B,"include","CoreSimulator");u1(F,{recursive:!0}),V1(f(F,"module.modulemap"),`module CoreSimulator {
489
+ `).join("");function T5($,J,Z){return new Promise((Q)=>{let B=J3($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),K="";B.stdout.on("data",(G)=>{K+=G}),B.stderr.on("data",(G)=>{K+=G}),B.once("error",(G)=>Q({code:-1,output:String(G)})),B.once("close",(G)=>Q({code:G??-1,output:K}))})}var _5=new Map;function Z3($){let J=f(R5($),"Frameworks"),Z=_5.get(J);if(!Z)_5.set(J,Z=GZ(J));return Z}async function GZ($){if(process.platform!=="darwin"||!e2(f($,"FBSimulatorControl.framework")))return null;let J=await T5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=oJ("sha256").update(t2).update(J.output).update($).digest("hex").slice(0,16),Q=f($Z(),".local","share","reason","simulator","host"),B=f(Q,Z,"simulator-host");if(e2(B))return B;u1(Q,{recursive:!0,mode:448});let K=tJ(f(Q,".staging-"));try{let G=f(K,"Frameworks"),U=f(G,"FBSimulatorControl.framework"),W=f(U,"Modules","FBSimulatorControl.swiftmodule");u1(W,{recursive:!0});for(let w of O5($))if(w!=="FBSimulatorControl.framework")$3(f($,w),f(G,w));let Y=f($,"FBSimulatorControl.framework");$3(f(Y,"FBSimulatorControl"),f(U,"FBSimulatorControl")),$3(f(Y,"Headers"),f(U,"Headers")),V1(f(U,"Modules","module.modulemap"),j5(f(Y,"Modules","module.modulemap")));let X=j5(f(Y,"Modules","FBSimulatorControl.swiftmodule",`${A5}.swiftinterface`),"utf8");V1(f(W,`${A5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let F=f(K,"include","CoreSimulator");u1(F,{recursive:!0}),V1(f(F,"module.modulemap"),`module CoreSimulator {
490
490
  header "CoreSimulator.h"
491
491
  export *
492
492
  }
493
493
  `),V1(f(F,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
494
- ${QZ}`);let C=f(B,"main.swift");V1(C,o2);let N=f(B,"simulator-host"),D=await A5("xcrun",["swiftc","-O","-F",G,"-I",f(B,"include"),"-module-cache-path",f(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,C,"-o",N],eJ);if(D.code!==0||!t2(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
494
+ ${VZ}`);let C=f(K,"main.swift");V1(C,t2);let N=f(K,"simulator-host"),D=await T5("xcrun",["swiftc","-O","-F",G,"-I",f(K,"include"),"-module-cache-path",f(K,"cache"),"-Xlinker","-rpath","-Xlinker",$,C,"-o",N],ZZ);if(D.code!==0||!e2(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
495
495
  ${D.output.slice(-2000)}
496
- `),null;u1(_5(K),{recursive:!0}),iJ(N,K);for(let w of w5(Q))if(w!==Z&&!w.startsWith(".staging-"))I5(f(Q,w),{recursive:!0,force:!0});return K}catch{return null}finally{I5(B,{recursive:!0,force:!0})}}class G1 extends Error{}class k0 extends Error{}class R5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;tJ({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 G1(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 k0("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 k0("The simulator host did not answer.")),this.close()},JZ);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(),ZZ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new k0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var S0=new Map;async function d1($,J,Z=!1){let Q=S0.get(J);if(!Q){let K={started:BZ($,J)};S0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&S0.get(J)===K)S0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function BZ($,J){let Z=await J3($);if(!Z)return null;let Q=$3(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),$Z);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 R5(Q,()=>{let G=S0.get(J);if(G&&(G.host===B||G.host===void 0))S0.delete(J)});return B}function P5($,J,Z,Q,K){return $3($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var f0={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"},WZ=50000,YZ=112640,FZ=174080,Z3=2,NZ=60000,CZ=2000,HZ=300,DZ=40,MZ=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function y0($,J,Z={}){return new Promise((Q,K)=>{let B=Y3($,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??WZ);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 k($,J){throw new H($,J)}async function n($,J,Z,Q={}){let K=await y0($,J,Q);if(K.code!==0)k("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function X1(){return process.platform==="darwin"&&K0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&K0("/usr/bin/xcrun")}var Q3=null;function j0(){return g(C3(),".local","share","reason","simulator","axe")}function H3(){let $=g(j0(),f0.version,"axe");if(K0($))return Promise.resolve($);return Q3??=(async()=>{V3(j0(),{recursive:!0,mode:448});let J=F3(g(j0(),".staging-"));try{let Z=g(J,"axe.tgz");await b5(f0.url,f0.sha256,Z);let Q=g(J,"tree");if(V3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!K0(g(Q,"axe"))||!K0(g(Q,"Frameworks")))k("simulator_axe_missing","The AXe archive has an unexpected layout.");U1(g(j0(),f0.version),{recursive:!0,force:!0}),UZ(Q,g(j0(),f0.version));for(let K of r1(j0()))if(K!==f0.version&&!K.startsWith(".staging-"))U1(g(j0(),K),{recursive:!0,force:!0});return $}finally{U1(J,{recursive:!0,force:!0}),Q3=null}})(),Q3}var v5=H3;async function p5($){let J=await H3().catch(()=>null);return J?d1(J,$.udid).catch(()=>null):null}async function s1($,J,Z){let Q=await H3().catch(()=>k("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await y0(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))k("simulator_element_not_found",B.slice(-500));return k("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function LZ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function wZ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function D3(){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)X3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:LZ(Q),state:wZ(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 X3=new Map,W3=null;async function t($,J){let Z=await D3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)k("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===W3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)k("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")k("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return W3=Q.udid,Q}function y($){return`${$.name} (${$.runtime})`}async function OZ($){if($.state!=="booted"){let J=await y0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))k("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 W3=$.udid,{...$,state:"booted"}}function M3($,J){let Z=U3($,J),Q=h5($,Z);if(Q.startsWith("..")||Q.startsWith(m5)||U3($,Q)!==Z)k("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 z5=4,IZ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function jZ($){let J=[],Z=(Q,K)=>{let B;try{B=r1(Q)}catch{return}if(B.includes("project.yml")||B.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=z5)return;for(let G of B.sort()){if(G.startsWith(".")||IZ.has(G))continue;let U=g(Q,G);try{if(l1(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)k("simulator_project_not_found",`No Xcode project or project.yml within ${z5} folders of ${$}; pass path.`);return k("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>h5($,Q)||".").join(", ")}.`)}var x0=new Map;async function AZ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:G3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:G3($)};if(!l1($).isDirectory())k("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>r1($).filter((B)=>B.endsWith(K)).sort();if(K0(g($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>K0("/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 k("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function u5($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function TZ($){let J=(await u5($))[0];if(!J)k("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function _Z($){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 RZ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await u5(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=K0(Q)?r1(Q).filter((B)=>B.endsWith(".app")).map((B)=>g(Q,B)).sort((B,G)=>l1(G).mtimeMs-l1(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await s5($.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 E5($,J){let Z=$.path?M3(J,$.path):jZ(J),Q=await AZ(Z),K=$.scheme??await TZ(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=VZ("sha256").update(Q.path).digest("hex").slice(0,16),Y=g(C3(),"Library","Caches","reason","simulator-builds",W),X={id:`build-${GZ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:g(Y,"Build","Products"),configuration:B};x0.set(X.id,X);for(let[D,w]of x0)if(x0.size>20&&w.status!=="running")x0.delete(D);let F=Y3("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);RZ(X,D??-1,Q)}),{text:`Build ${X.id} started: ${K} (${B}) for ${G?y(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:d5(X)}}function d5($){return{id:$.id,status:$.status,errors:_Z($.log),log_tail:$.log.slice(-DZ).join(`
500
- `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var PZ=45000,zZ=30000;async function K3($,J=PZ){let Z=Date.now()+J;while(x0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=l5($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function l5($){let J=x0.get($);if(!J)k("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=d5(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 s5($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",g($,"Info.plist")],"Reading the bundle id")).trim()}var D0=new Map;function EZ($,J){D0.get($.udid)?.stop();let Z=Y3("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")};D0.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-CZ;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 qZ($,J){let Z=await t($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=gZ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,B],`Installing ${y5(B)}`),Q=await s5(B)}if($.bundle_id){if((await y0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)k("simulator_app_not_installed",`${$.bundle_id} is not installed on ${y(Z)}.`)}let K=await EZ(Z,Q);if(K===null){let B=D0.get(Z.udid)?.lines.slice(-20).join(`
503
- `)??"";k("simulator_launch_failed",`${Q} did not start on ${y(Z)}.${B?`
504
- ${B}`:""}`)}return{text:`Launched ${Q} on ${y(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function gZ($,J){let Z=U3(J),Q=g(C3(),"Library","Caches","reason","simulator-builds")+m5;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:M3($,Z)}function SZ($,J){let Z=D0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${y($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-HZ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${y($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var c1=new Map;function q5($,...J){let Z=c1.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)k("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function g5($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function L3($,J=1,Z){let Q=F3(g(x5(),"reason-sim-"));try{let K=g(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){V3(G3(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/g5($,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=g5($,G),Y=Math.round(G/W),X=Math.round(U/W);c1.set($.udid,{width:Y,height:X});let F=Buffer.alloc(0),C=J===2?FZ:YZ;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=N3(D),F.byteLength<=C)break}return{text:`Screenshot of ${y($)} 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{U1(Q,{recursive:!0,force:!0})}}async function kZ($){let J=await p5($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return s1(["describe-ui"],$.udid,"Reading the accessibility tree")}async function n1($){let J=JSON.parse(await kZ($)),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 c5($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
496
+ `),null;u1(R5(B),{recursive:!0}),eJ(N,B);for(let w of O5(Q))if(w!==Z&&!w.startsWith(".staging-"))I5(f(Q,w),{recursive:!0,force:!0});return B}catch{return null}finally{I5(K,{recursive:!0,force:!0})}}class G1 extends Error{}class k0 extends Error{}class P5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;JZ({input:$.stdout}).on("line",(Q)=>{let B;try{B=JSON.parse(Q)}catch{return}let K=this.pending.get(Number(B.id));if(!K)return;if(this.pending.delete(Number(B.id)),clearTimeout(K.timer),B.ok===!0)K.resolve(B);else K.reject(new G1(String(B.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new k0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let B=setTimeout(()=>{this.pending.delete(J),Q(new k0("The simulator host did not answer.")),this.close()},BZ);this.pending.set(J,{resolve:Z,reject:Q,timer:B}),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(),KZ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new k0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var S0=new Map;async function d1($,J,Z=!1){let Q=S0.get(J);if(!Q){let B={started:UZ($,J)};S0.set(J,Q=B),B.started.then((K)=>{if(B.host=K,!K&&S0.get(J)===B)S0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function UZ($,J){let Z=await Z3($);if(!Z)return null;let Q=J3(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),QZ);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 K=new P5(Q,()=>{let G=S0.get(J);if(G&&(G.host===K||G.host===void 0))S0.delete(J)});return K}function z5($,J,Z,Q,B){return J3($,["stream",J,String(Z),String(Math.round(Q)),String(B)],{stdio:["pipe","pipe","ignore"]})}var f0={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"},NZ=50000,CZ=112640,HZ=174080,Q3=2,DZ=60000,MZ=2000,LZ=300,wZ=40,OZ=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function y0($,J,Z={}){return new Promise((Q,B)=>{let K=F3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],U=[];K.stdout.on("data",(Y)=>G.push(Y)),K.stderr.on("data",(Y)=>U.push(Y));let W=setTimeout(()=>K.kill("SIGKILL"),Z.timeoutMs??NZ);K.on("error",(Y)=>{clearTimeout(W),B(Y)}),K.on("close",(Y)=>{clearTimeout(W),Q({code:Y??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function k($,J){throw new H($,J)}async function n($,J,Z,Q={}){let B=await y0($,J,Q);if(B.code!==0)k("simulator_command_failed",`${Z} failed: ${(B.stderr||B.stdout).trim().slice(-1500)}`);return B.stdout}function X1(){return process.platform==="darwin"&&B0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&B0("/usr/bin/xcrun")}var B3=null;function I0(){return g(H3(),".local","share","reason","simulator","axe")}function D3(){let $=g(I0(),f0.version,"axe");if(B0($))return Promise.resolve($);return B3??=(async()=>{G3(I0(),{recursive:!0,mode:448});let J=N3(g(I0(),".staging-"));try{let Z=g(J,"axe.tgz");await x5(f0.url,f0.sha256,Z);let Q=g(J,"tree");if(G3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!B0(g(Q,"axe"))||!B0(g(Q,"Frameworks")))k("simulator_axe_missing","The AXe archive has an unexpected layout.");U1(g(I0(),f0.version),{recursive:!0,force:!0}),YZ(Q,g(I0(),f0.version));for(let B of r1(I0()))if(B!==f0.version&&!B.startsWith(".staging-"))U1(g(I0(),B),{recursive:!0,force:!0});return $}finally{U1(J,{recursive:!0,force:!0}),B3=null}})(),B3}var p5=D3;async function u5($){let J=await D3().catch(()=>null);return J?d1(J,$.udid).catch(()=>null):null}async function s1($,J,Z){let Q=await D3().catch(()=>k("simulator_axe_missing","AXe could not be installed on this Mac.")),B=await y0(Q,[...$,"--udid",J]);if(B.code===0)return B.stdout;let K=(B.stderr||B.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(K))k("simulator_element_not_found",K.slice(-500));return k("simulator_command_failed",`${Z} failed: ${K.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 IZ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function M3(){let J=JSON.parse(await n("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,B]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let K of B){if(K.isAvailable===!1)continue;let G=K.name.toLowerCase();if(K.deviceTypeIdentifier)W3.set(K.udid,K.deviceTypeIdentifier);Z.push({udid:K.udid,name:K.name,runtime:jZ(Q),state:IZ(K.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,B)=>Number(B.state==="booted")-Number(Q.state==="booted")||B.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(B.name))}var W3=new Map,Y3=null;async function t($,J){let Z=await M3(),Q;if($){let B=Z.filter((K)=>K.udid===$||K.name===$);if(Q=B.find((K)=>K.state==="booted")??B[0],!Q)k("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let B=Z.filter((K)=>K.state==="booted");if(Q=B.find((K)=>K.udid===Y3)??B.find((K)=>K.kind==="iphone")??B[0],!Q)k("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")k("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return Y3=Q.udid,Q}function y($){return`${$.name} (${$.runtime})`}async function AZ($){if($.state!=="booted"){let J=await y0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))k("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 Y3=$.udid,{...$,state:"booted"}}function L3($,J){let Z=X3($,J),Q=m5($,Z);if(Q.startsWith("..")||Q.startsWith(v5)||X3($,Q)!==Z)k("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 E5=4,TZ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function _Z($){let J=[],Z=(Q,B)=>{let K;try{K=r1(Q)}catch{return}if(K.includes("project.yml")||K.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(B>=E5)return;for(let G of K.sort()){if(G.startsWith(".")||TZ.has(G))continue;let U=g(Q,G);try{if(l1(U).isDirectory())Z(U,B+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)k("simulator_project_not_found",`No Xcode project or project.yml within ${E5} folders of ${$}; pass path.`);return k("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>m5($,Q)||".").join(", ")}.`)}var x0=new Map;async function RZ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:U3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:U3($)};if(!l1($).isDirectory())k("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(B)=>r1($).filter((K)=>K.endsWith(B)).sort();if(B0(g($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((B)=>B0("/opt/homebrew/bin/xcodegen")?n("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(B));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 k("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function d5($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function PZ($){let J=(await d5($))[0];if(!J)k("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function zZ($){let J=[],Z=new Set;return $.forEach((Q,B)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let K=$.slice(B+1,B+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...K].join(`
498
+ `).slice(0,800))}),J}async function EZ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((K)=>K.includes("does not contain a scheme named"))){let K=await d5(Z).catch(()=>[]);if(K.length)$.log.push(`error: this project's schemes are: ${K.join(", ")}`)}$.status="failed";return}let Q=g($.productsDir,`${$.configuration}-iphonesimulator`),B=B0(Q)?r1(Q).filter((K)=>K.endsWith(".app")).map((K)=>g(Q,K)).sort((K,G)=>l1(G).mtimeMs-l1(K).mtimeMs):[];if($.appPath=B[0],$.appPath)$.bundleId=await c5($.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 q5($,J){let Z=$.path?L3(J,$.path):_Z(J),Q=await RZ(Z),B=$.scheme??await PZ(Q),K=$.configuration??"Debug",G=await t($.device,{booted:!1}).catch(()=>null),U=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",W=XZ("sha256").update(Q.path).digest("hex").slice(0,16),Y=g(H3(),"Library","Caches","reason","simulator-builds",W),X={id:`build-${WZ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:g(Y,"Build","Products"),configuration:K};x0.set(X.id,X);for(let[D,w]of x0)if(x0.size>20&&w.status!=="running")x0.delete(D);let F=F3("xcodebuild",[Q.flag,Q.path,"-scheme",B,"-configuration",K,"-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);EZ(X,D??-1,Q)}),{text:`Build ${X.id} started: ${B} (${K}) for ${G?y(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:l5(X)}}function l5($){return{id:$.id,status:$.status,errors:zZ($.log),log_tail:$.log.slice(-wZ).join(`
500
+ `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var qZ=45000,gZ=30000;async function K3($,J=qZ){let Z=Date.now()+J;while(x0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=s5($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function s5($){let J=x0.get($);if(!J)k("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=l5(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 c5($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",g($,"Info.plist")],"Reading the bundle id")).trim()}var D0=new Map;function SZ($,J){D0.get($.udid)?.stop();let Z=F3("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")};D0.set($.udid,Q);let B="",K=(G)=>{let U=(B+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
501
+ `);B=U.pop()??"",Q.lines.push(...U);let W=Q.lines.length-MZ;if(W>0)Q.lines.splice(0,W),Q.first+=W};return Z.stdout.on("data",K),Z.stderr.on("data",K),new Promise((G)=>{let U=setTimeout(()=>G(null),15000),W=()=>{let Y=Q.lines.concat(B).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 kZ($,J){let Z=await t($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let K=fZ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,K],`Installing ${h5(K)}`),Q=await c5(K)}if($.bundle_id){if((await y0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)k("simulator_app_not_installed",`${$.bundle_id} is not installed on ${y(Z)}.`)}let B=await SZ(Z,Q);if(B===null){let K=D0.get(Z.udid)?.lines.slice(-20).join(`
503
+ `)??"";k("simulator_launch_failed",`${Q} did not start on ${y(Z)}.${K?`
504
+ ${K}`:""}`)}return{text:`Launched ${Q} on ${y(Z)} (pid ${B}). Its console is captured; read it with logs.`,device:Z}}function fZ($,J){let Z=X3(J),Q=g(H3(),"Library","Caches","reason","simulator-builds")+v5;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:L3($,Z)}function bZ($,J){let Z=D0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${y($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-LZ),B=Z.lines.slice(Q-Z.first).map((K)=>K.slice(0,2000));return{text:`${B.length} console line(s) from ${Z.bundleId} on ${y($)}.`,logs:{lines:B,next:Z.first+Z.lines.length}}}var c1=new Map;function g5($,...J){let Z=c1.get($.udid);if(!Z)return;for(let[Q,B]of J)if(Q>Z.width||B>Z.height)k("simulator_point_off_screen",`(${Q}, ${B}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function S5($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function w3($,J=1,Z){let Q=N3(g(y5(),"reason-sim-"));try{let B=g(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",B],"Taking a screenshot"),Z){G3(U3(Z),{recursive:!0});let N=await n("sips",["-g","pixelWidth","-g","pixelHeight",B],"Reading the screenshot size"),D=Number(N.match(/pixelWidth: (\d+)/)?.[1]),w=Number(N.match(/pixelHeight: (\d+)/)?.[1]),M=2/S5($,D);await n("sips",["-z",String(Math.round(w*M)),String(Math.round(D*M)),B,"--out",Z],"Saving the screenshot")}let K=await n("sips",["-g","pixelWidth","-g","pixelHeight",B],"Reading the screenshot size"),G=Number(K.match(/pixelWidth: (\d+)/)?.[1]),U=Number(K.match(/pixelHeight: (\d+)/)?.[1]),W=S5($,G),Y=Math.round(G/W),X=Math.round(U/W);c1.set($.udid,{width:Y,height:X});let F=Buffer.alloc(0),C=J===2?HZ:CZ;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),B,"--out",D],"Encoding the screenshot"),F=C3(D),F.byteLength<=C)break}return{text:`Screenshot of ${y($)} 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{U1(Q,{recursive:!0,force:!0})}}async function xZ($){let J=await u5($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return s1(["describe-ui"],$.udid,"Reading the accessibility tree")}async function n1($){let J=JSON.parse(await xZ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(B,K,G="")=>{let U=(B.role??B.type??"?").replace(/^AX/,""),W=B.AXLabel||B.title||"",Y=B.AXValue?` value="${String(B.AXValue).slice(0,120)}"`:"",X=B.AXUniqueId?` id=${B.AXUniqueId}`:"";if(B.AXUniqueId)Z.ids.add(B.AXUniqueId);if(W)Z.labels.add(W);let F=B.frame;if(U==="Application"&&F&&!Z.bounds)Z.bounds={width:F.width,height:F.height};if(F&&F.width>0&&F.height>0&&(B.AXUniqueId||B.AXLabel))Z.targets.push({...B.AXUniqueId?{id:B.AXUniqueId.trim()}:{},...B.AXLabel?{label:B.AXLabel.trim()}:{},role:U,frame:F});let C=Boolean(W||X||Y||!["Group","Other"].includes(U));if(C){let N=`${" ".repeat(Math.min(K,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)})`:"")+(B.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 B.children??[])Q(N,C?K+1:K,W||G)};for(let B of J)Q(B,0);return Z}function n5($,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 fZ($){let J=await n1($);return{text:`Accessibility tree of ${y($)} (frames in points; tap by id or label):
507
- ${c5(J,NZ)}`,device:$}}var bZ=450,xZ=1e4;function yZ($,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 A0($,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 n1($),yZ(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(bZ);let G={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await n1($),G.screen=c5(K,xZ,!0),G.text+=`
506
+ \u2026 (truncated)`:Q}async function yZ($){let J=await n1($);return{text:`Accessibility tree of ${y($)} (frames in points; tap by id or label):
507
+ ${n5(J,DZ)}`,device:$}}var hZ=450,mZ=1e4;function vZ($,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 A0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let B=null,K="";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(B=await n1($),vZ(B,W)){K=` ${Y} is ${W.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){K=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(hZ);let G={...Z,text:`${Z.text}${K}`};if(Q==="tree"||Q==="both")B??=await n1($),G.screen=n5(B,mZ,!0),G.text+=`
508
508
  Screen now:
509
- ${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await L3($);G.image=U.image}return G}function S5($){return`'${$.replace(/'/g,"'\\''")}'`}function hZ($){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 ${S5($.id)}`:`tap --label ${S5($.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 n5=0.35,mZ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function vZ($,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)=>mZ.has(Y.role)),W=(U.length?U:G)[0];return W?Q(W):null}async function pZ($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let G=vZ(await n1($),J);if(G)return G;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return k("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
509
+ ${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await w3($);G.image=U.image}return G}function k5($){return`'${$.replace(/'/g,"'\\''")}'`}function pZ($){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 ${k5($.id)}`:`tap --label ${k5($.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 r5=0.35,uZ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function dZ($,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}),B=$.bounds,K=B?Z.filter((Y)=>{let{x:X,y:F}=Q(Y);return X>=0&&F>=0&&X<=B.width&&F<=B.height}):Z,G=K.length?K:Z,U=G.filter((Y)=>uZ.has(Y.role)),W=(U.length?U:G)[0];return W?Q(W):null}async function lZ($,J,Z,Q,B){let K=Date.now()+Z*1000;for(;;){let G=dZ(await n1($),J);if(G)return G;if(Date.now()>=K){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return k("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 b0($,J,Z){let Q=await p5($);if(!Q)return k5($,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 pZ($,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 G1?s1(["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 k0)return await k5($,J.slice(K),Z),`Ran ${J.length} step(s) on ${y($)}.`;if(U instanceof G1)k("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(n5*1000)}return`Ran ${J.length} step(s) on ${y($)}.`}async function k5($,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 s1(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});k(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 s1(["type",Y.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(hZ(Y)),B+=1,K.push(W+1);let X=J[W+1];if(Y.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${n5}`),K.push(W+1)}return await U(),`Ran ${J.length} step(s) on ${y($)}.`}var uZ=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],f5=new Map,dZ=`ObjC.import("AppKit");
511
+ (${Q-1} of ${B} steps had completed.)`)}await Bun.sleep(250)}}async function b0($,J,Z){let Q=await u5($);if(!Q)return f5($,J,Z);for(let[B,K]of J.entries()){try{switch(K.action){case"tap":{let U=K.x!==void 0&&K.y!==void 0?{x:K.x,y:K.y}:await lZ($,K,Z,B+1,J.length);await Q.call(K.duration?{op:"tap",...U,duration:K.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:K.x,y:K.y,x2:K.x2,y2:K.y2,duration:K.duration??0.3});break;case"button":await Q.call({op:"button",name:K.name});break;case"type":await Q.call({op:"text",text:K.text}).catch((U)=>U instanceof G1?s1(["type",K.text],$.udid,`Step ${B+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(K.seconds*1000);break}}catch(U){if(U instanceof k0)return await f5($,J.slice(B),Z),`Ran ${J.length} step(s) on ${y($)}.`;if(U instanceof G1)k("simulator_command_failed",`Step ${B+1} failed: ${U.message}
512
+ (${B} of ${J.length} steps had completed.)`);throw U}let G=J[B+1];if(K.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(r5*1000)}return`Ran ${J.length} step(s) on ${y($)}.`}async function f5($,J,Z){let Q=[],B=[],K=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 s1(W,$.udid,`Steps ${G+1}-${G+K}`)}catch(Y){if(Y instanceof H){let X=Y.message.replace(/Step (\d+) failed/,(F,C)=>{let N=B[Number(C)-1];return N?`Step ${N} failed`:F});k(Y.code,`${X}
513
+ (${G} of ${J.length} steps had completed before this batch.)`)}throw Y}G+=K,Q=[],B=[],K=0};for(let[W,Y]of J.entries()){if(Y.action==="type"){await U(),await s1(["type",Y.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(pZ(Y)),K+=1,B.push(W+1);let X=J[W+1];if(Y.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${r5}`),B.push(W+1)}return await U(),`Ran ${J.length} step(s) on ${y($)}.`}var sZ=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],b5=new Map,cZ=`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 B3($,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=F3(g(x5(),"reason-chrome-"));try{let U=g(G,"render.js"),W=g(G,"out.png");if(XZ(U,dZ),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"),!K0(W))k("simulator_command_failed",`Rendering ${y5($)} produced no image.`);return{image:N3(W).toString("base64"),width:K,height:B}}finally{U1(G,{recursive:!0,force:!0})}}async function lZ($){if(!X3.has($.udid))await D3();let J=X3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)k("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function sZ($){let J=await lZ($),Z=c1.get($.udid)??($.state==="booted"?(await L3($),c1.get($.udid)):void 0);if(!Z)k("simulator_not_booted",`${$.name} is not booted.`);let Q=f5.get(J);if(Q)return{text:`Frame of ${y($)}.`,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&&K0(G)?await B3(G,Z3,Z.height):null,W=B.chromeIdentifier?.split(".").pop(),Y=W?g("/Library/Developer/DeviceKit/Chrome",`${W}.devicechrome`,"Contents","Resources"):"";if(!W||!K0(g(Y,"chrome.json")))k("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(N3(g(Y,"chrome.json"),"utf8")),F={};for(let R of uZ){let j=X.images[R];if(!j)k("simulator_command_failed",`${$.name}'s frame has no ${R} piece.`);F[R]=await B3(g(Y,`${j}.pdf`),Z3)}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 R of X.inputs??[]){let j=g(Y,`${R.image}.pdf`);if(!K0(j))continue;let T=await B3(j,Z3),{x:v,y:I}=R.offsets.normal,q=(s,m,D1)=>s<0?m+s-D1:s,P=R.anchor==="left"?{x:v-T.width,y:q(I,w,T.height)}:R.anchor==="right"?{x:D+v,y:q(I,w,T.height)}:R.anchor==="top"?{x:q(v,D,T.width),y:I-T.height}:{x:q(v,D,T.width),y:w+I};M.push({name:R.name,image:T.image,...P,width:T.width,height:T.height})}let O={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 f5.set(J,O),{text:`Frame of ${y($)}.`,device:$,chrome:O}}var cZ=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 W1($){try{return await r5($)}catch(J){if(J instanceof H&&cZ.has(J.code))return{text:J.message,error:J.code};throw J}}async function r5($){if(!X1())k("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=i2.safeParse($.payload);if(!J.success)k("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await D3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(y).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await OZ(await t(Z.device,{booted:!1}));return{text:`${y(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await t(Z.device,{booted:!1});D0.get(Q.udid)?.stop(),D0.delete(Q.udid);let K=await y0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))k("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${y(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await E5(Z,$.root);return Z.wait&&Q.build?K3(Q.build.id):Q}case"build_status":return Z.wait?K3(Z.build_id):l5(Z.build_id);case"run":{let Q=await E5({...Z,action:"build"},$.root),K=await K3(Q.build.id,zZ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await r5({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 qZ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await b0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return A0(Q.device,Z,Q)}case"steps":{let Q=await t(Z.device,{booted:!0});return A0(Q,Z,{text:await b0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await t(Z.device,{booted:!0});if(D0.get(Q.udid)?.bundleId===Z.bundle_id)D0.get(Q.udid)?.stop();return await y0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${y(Q)}.`,device:Q}}case"logs":return SZ(await t(Z.device,{booted:!1}),Z.after);case"screenshot":return L3(await t(Z.device,{booted:!0}),Z.scale,Z.save_path?M3($.root,Z.save_path):void 0);case"chrome":return sZ(await t(Z.device,{booted:!1}));case"inspect":return fZ(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)q5(Q,[Z.x,Z.y]);await b0(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 A0(Q,Z,{text:`Tapped ${B} on ${y(Q)}.`,device:Q})}case"swipe":{let Q=await t(Z.device,{booted:!0});return q5(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await b0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),A0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${y(Q)}.`,device:Q})}case"type":{let Q=await t(Z.device,{booted:!0});return await b0(Q,[{action:"type",text:Z.text}],3),A0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${y(Q)}.`,device:Q})}case"button":{let Q=await t(Z.device,{booted:!0});return await b0(Q,[{action:"button",name:Z.name}],3),A0(Q,Z,{text:`Pressed ${Z.name} on ${y(Q)}.`,device:Q})}case"open_url":{let Q=await t(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{k("simulator_invalid_request","open_url needs an absolute URL.")}if(MZ.has(K.protocol))k("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),A0(Q,Z,{text:`Opened ${K.href} on ${y(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:`${y(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as nZ,readFileSync as rZ,rmSync as aZ}from"fs";import{tmpdir as iZ}from"os";import{join as a5}from"path";import{spawn as e5}from"child_process";var oZ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,Y1=1,tZ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],i5=60,eZ=8,$6=X1;var o5={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},$Q=(()=>{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 JQ($){if(o5[$]!==void 0)return o5[$];return $>=32&&$<=126?$Q[String.fromCharCode($)]??null:null}function J6($,J){let Z=e5("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function ZQ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,G,U){let W=(U&Y1)!==0;if(W&&!(Z&Y1))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&Y1)K({op:"touch",phase:"up",x:B,y:G});for(let Y of tZ)if(U&Y.bit&&!(Z&Y.bit))K({op:"swipe",x:B,y:G,x2:B+Y.dx*i5,y2:G+Y.dy*i5,duration:0.08});Z=U,Q={x:B,y:G}},key(B,G){let U=JQ(G);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){J6($,B)},close(){if(Z&Y1)K({op:"touch",phase:"up",...Q});Z=0}}}function QQ($,J){let Z=null,Q="",K,B=(G)=>{W1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,W){let Y=(W&Y1)!==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)>eZ)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){J6($,G)},close(){clearTimeout(K),Z=null}}}function KQ($,J,Z){return new Promise((Q,K)=>{let B=e5($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function BQ($,J){let Z=nZ(a5(iZ(),"reason-simulator-stream-"));try{let Q=a5(Z,"screen.png");if(await KQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=rZ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{aZ(Z,{recursive:!0,force:!0})}}async function Z6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!oZ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await v5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await W1({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 J3(K),W=U?await d1(K,Z,!0):null,Y=U?null:await t5();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 BQ(Z,$.signal),stream:U?(F,C,N)=>P5(U,Z,Math.min(F,60),N,C):null,input:W?ZQ(Z,W):QQ(Z,$.root)};return await a1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...Y?{ffmpeg:()=>Y}:{}}})}var m7=131072,NQ=131072,CQ=128,v7=8192,q3=30000,g3=15000,HQ=/^[a-z][a-z0-9_]{0,63}$/,DQ=new Set(["jobs.control","fs.read","fs.write"]),Q6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function i1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function K6($){return $.map(i1).join("/")}function w3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var MQ=[...w3(m6,4).map(($)=>`/(${$.map(K6).join("|")})(/|$)`),...w3(v6,4).map(($)=>`/(${$.map(K6).join("|")})$`),...w3([...p6],6).map(($)=>`/(${$.map(i1).join("|")})$`),`/${i1(".env")}\\.[^/]+$`,`/[^/]+(${u6.map(i1).join("|")})$`],A3=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 u7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function LQ($){return F7($)}function T3(){if(l()==="darwin")return U0("/usr/bin/sandbox-exec");if(l()==="linux")return N7();return!1}function B6(){if(l()==="linux")return U0("/proc");if(!T3())return!1;if(l()==="darwin")return U0("/usr/sbin/lsof");return!1}function d7(){return l()==="darwin"?"/bin/zsh":C7()}function _3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function wQ($){if(!_3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>C0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function d0($,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 $2($,J,Z=v7){let Q=d0($,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 OQ($,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 C1($,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 p0($,J){return J===$||J.startsWith(`${$}${YQ}`)}function m0($){if(w0($))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.")}function h($){let J;try{J=Z0($.path)}catch(Z){if(process.platform==="darwin"&&G7(Z))throw U7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!H1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return m0(J),J}function S3($,J="."){if(!J||J.includes("\x00")||XQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");let Z=WQ($,J);if(!p0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function u0($,J=".",Z=!1){let Q=S3($,J),K;try{K=Z0(Q)}catch(B){if(n7(B))throw r7();throw new H("path_not_found","Path does not exist.")}if(!p0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)m0(K);return K}function IQ($,J){let Z=S3($,J);if(m0(Z),U0(Z)){let B=Z0(Z);if(!p0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(f7(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return m0(B),B}let Q=N1(Z);while(!U0(Q)){let B=N1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=Z0(Q);if(!p0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return m0(K),Z}function l7($,J){return j3($,J)||"."}function jQ($,J=m7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function s7($,J){return{...Q7({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 AQ($,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($)}))`]:[],...MQ.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),"(deny network*)"].join(`
527
- `)}async function k3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,W=!1,Y=!1,X;try{X=FQ($,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 O=`${w}${String(M)}`,R=jQ(O);return U||=R.truncated,R.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 V6=null;function TQ(){return V6??=H7({scrubEnvironment:s7,spawnCaptured:k3,isProtectedPath:w0}),V6}var _Q=async($,J,Z)=>{if(l()==="linux")return TQ()($,J,Z);if(l()!=="darwin"||!U0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=b7(E3(h7(),"reason-device-"));try{return await k3("/usr/bin/sandbox-exec",["-p",AQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:s7(Z.root,Q)})}finally{y7(Q,{recursive:!0,force:!0})}};function RQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>CQ)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")>v7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function c7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=h($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??g3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function n7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var r7=()=>new H("path_unreadable","The path is not readable.");function PQ($){try{return x7($,T0.O_RDONLY)}catch(J){throw n7(J)?r7():J}}function G6($,J){let Z=v0()?t1():null;return Z?e1(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):zQ($,J)}function zQ($,J){return $==="fs.read"?EQ(J):gQ(J)}async function EQ($){let J=h($.root),Z=u0(J,$2($.payload,"path"));if(!H1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=C1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=C1($.payload.max_bytes,65536,1,m7),B=d0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=PQ(Z),U,W;try{U=k7(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));W=X.subarray(0,X.byteLength?GQ(G,X,0,X.byteLength,Q):0)}finally{S7(G)}let Y=B==="base64"||W.includes(0);return{path:l7(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 qQ($,J){let Z=$==="append"?T0.O_APPEND:T0.O_TRUNC;return T0.O_WRONLY|T0.O_NOFOLLOW|Z|(J?0:T0.O_CREAT|T0.O_EXCL)}async function gQ($){let J=h($.root),Z=$2($.payload,"path"),Q=OQ($.payload,"content",NQ),K=d0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=IQ(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){VQ(N1(B),{recursive:!0,mode:448});let Y=Z0(N1(B));if(!p0(J,Y))throw new H("symlink_escape","Write parent escaped root.")}if(!U0(N1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&U0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=U0(B),U=G?f7(B):null,W=x7(B,qQ(K,G),384);try{if(U){let Y=k7(W);if(Y.ino!==U.ino||Y.dev!==U.dev)throw new H("symlink_escape","The write target changed between validation and opening.")}UQ(W,Q,null,"utf8")}finally{S7(W)}return{path:l7(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function SQ($){let J=h($.root),Z=$2($.payload,"command",65536),Q=u0(J,d0($.payload,"cwd")??".");if(!H1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=C1($.payload.timeout_ms,g3,100,q3);return c7($,d7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function kQ($){let J=M4.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=h($.root),K=n6(Q,J.data.workspace),B=K.boundary===Q?Q:u0(K.anchor,j3(K.anchor,K.boundary)||"."),G=u0(B,j3(B,K.path)||".");if(!H1(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()+N4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let W=(O)=>$.emit("progress",{process:O});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 R1({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:g0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:W})}}let Y={directory:E3(Z.runtimeDirectory,"processes")},X={deniedPorts:c6([$.apiOrigin])};if($.claim.local_github_authority&&l()==="darwin"){let O=fQ(G);try{return{...await R1({claim:$.claim,root:G,cwd:G,command:J.data.command,mode:"confined",shell:O.shell,prefix:O.prefix,environment:O.environment,expiresAtMs:U,signal:$.signal,emit:W,journals:Y,preview:X})}}finally{O.dispose()}}let F=K7(),C=B7(),N=v0(),D=J.data.egress?o1(N):null;if(J.data.egress&&(D===null||!h0(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 s4(J.data.egress.allowed_domains):null,M=w?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((O)=>`${O}=${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 R1({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 fQ($){if(!U0("/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=Z0($),Z=Z0(b7(E3(Z0(h7()),"reason-preview-"))),Q="/bin/bash";return{shell:Q,prefix:["/usr/bin/sandbox-exec","-p",l6(J,Z)],environment:{HOME:Z,PATH:d6,TMPDIR:Z,TMP:Z,TEMP:Z,SHELL:Q,BASH_ENV:"/dev/null",ENV:"/dev/null",OPENSSL_CONF:"/dev/null"},dispose:()=>y7(Z,{recursive:!0,force:!0})}}async function bQ($){h2();let J=h($.root),Z=m2($.payload.command),Q=u0(J,d0($.payload,"cwd")??".");if(!H1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=C1($.payload.timeout_ms,d8,100,x2),{ignored:B}=v2($.payload.env);return await $.emit("progress",{shell:g0(),shell_flags:[...K1],sandbox:"none",ignored_env:B}),s8({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function xQ($){let J=h($.root),Z=RQ($.payload),Q=Z[0];if(!Q||!p7.has(Q)&&!A3.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=A3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=u0(J,d0($.payload,"cwd")??".");return c7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K,timeoutMs:C1($.payload.timeout_ms,g3,100,q3)})}function a7($,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 yQ($){let J=h($.root);if(l()==="linux")return J5(J);return V5(J,a7($,J))}async function hQ($){let J=h($.root);if(l()==="linux")return Z5(J);return G5(J,a7($,J))}async function mQ($){let J=$.worker?D5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&f3({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}:{},...$.worker.ownComputer?{ownComputer:!0}:{},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:h($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function vQ($){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}=r6($.payload,$.operationId);return t6({root:h($.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:h($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function U6($,J){let Z=v0()?t1():null;return Z?e1(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):pQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function pQ($,J){let Z=h(J.root),Q=e0 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?L8(Z,J.payload[e0]):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=Z8.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=$2(J.payload,"path",4096),G=$==="import"&&Q?g2(K):K;return m0(S3(G,B)),q0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var i7={"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 c3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>G6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>G6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>U6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>U6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>l()==="darwin"&&y2(),execute:kQ},"exec.run":{requiredPermission:"execute",available:T3,execute:SQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>y2(),execute:bQ},"git.run":{requiredPermission:"execute",available:()=>T3()&&LQ("git"),execute:xQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:B6,execute:yQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:B6,execute:hQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>l()==="darwin"||Boolean(X7()),execute:mQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:P7,execute:vQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:g7,execute:($)=>{let J=t1();return J?e1(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??V7)()},$.signal):a1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>E7(),execute:($)=>q7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:X1,execute:($)=>W1({payload:$.payload,root:h($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:$6,execute:($)=>Z6({payload:$.payload,root:h($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>e6({root:h($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>l()==="darwin"?U0("/usr/bin/sandbox-exec"):l()==="linux",execute:async($)=>{let J=I1.parse($.payload),Z=P3.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||!L0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return $7({root:h($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>G4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>z3({root:h($.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:($)=>i6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>o6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:E2,execute:($)=>N8($.payload,$.signal)}};function uQ($,J){try{let Z=r3($,Z0(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 dQ($,J){try{let Z=Z0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function lQ($,J){try{let Z=Z0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function sQ($,J){try{let Z=Z0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&p0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function cQ($,J){try{return w1({home:Z0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&L1(Z.path)).slice(0,K2).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function FU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||l()==="darwin",K=Q?lQ($,F1()):void 0,B=!J.worker&&l()==="darwin"?uQ($,F1()):void 0,G=Q?dQ($,F1()):void 0,U=!J.worker&&l()==="darwin"?sQ($,F1()):void 0,W=Q?cQ($,F1()):void 0,Y=b2.filter((X)=>{if(Q1.has(X)&&!J.worker)return!1;if(J.worker&&!y1(X,J.worker))return!1;let F=i7[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)&&u7(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:z0,hands_worker_entrypoint:i0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:C0,max_result_bytes:C0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":X2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:d7(),sandbox:l()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:q3},...Y.includes("exec.full")?{"exec.full":c8()}:{},"git.run":{read_only_subcommands:[...p7].sort(),mutating_subcommands:[...A3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:t0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:t0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:a0,protocol_version:I3,worker_artifact_sha256:z0,worker_entrypoint:i0,policy_mode:"full_access",policy_version:1,workspace_base:O3,workspace_layout:Z1,...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:R7,max_session_ms:T7,max_buffered_output_bytes:_7}}:{},...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:y1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:s6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!v0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:q6,...J.worker?.ownComputer?{[g6]:S6}:{},workspace_base:O3,workspace_layout:Z1,browser_state:"optional_headless",desktop:!1,worker_version:a0,protocol_version:I3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:Y6,[C6]:N6}:{},...J.worker?{[D6]:H6}:{},...J.worker?.handsBrowser?{[I6]:O6}:{},[w6]:L6,[A6]:j6,...h0(J.worker?.executionMode==="unsandboxed")?{[_6]:T6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&o1()!==null?{[P6]:R6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&v0()?{[E6]:z6}:{}}:{},...X==="fs.export"?{cloud_source_version:q1,source_kinds:["workspace","attachment"],[j2]:A2}:{},...X==="fs.import"?{[j2]:A2}:{},...X===F4&&o1()!==null&&h0(J.worker?.executionMode==="unsandboxed")?{[D4]:F2}:{},...X==="tunnel.open"?{carried_jobs:k6}:{},...X==="jobs.control"?{[b6]:f6}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[M7]:D7,[w7]:L7.join(","),[O7]:I7,[j7]:A7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[x6]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[y6]:!0}:{}}])):{}}}}function f3($,J,Z,Q,K){let B=Z7.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 NU($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==F6||!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(!f3($,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=z3({root:h(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 CU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==M6)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 a6({operationId:J.operation_id,root:h(W),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function HU($,J,Z){if(J.capability!=="github.local.v1")return X6($,J,Z);try{let Q=await X6($,J,Z);if(Q.status==="succeeded"||R3(J.payload,Q.status,Q.error_code))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 X6($,J,Z){if(Q1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!y1(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=P3.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=i7[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")&&_3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&e0 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"&&!f3($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(u7(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"||DQ.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:wQ(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??_Q,spawnFullControl:Z.spawnFullControl??k3,emit:U?Y:G,runHandsRelay:Z.runHandsRelay??((C)=>Y7(C,X)),runPtySession:Z.runPtySession??z7});if(J.capability==="github.local.v1")W6.parse(F);if(!_3(F))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(F)??"null","utf8")>C0)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&&Q6.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&Q6.has(X.code)?X.code:null;if(Z.signal.aborted||F)return{status:"cancelled",...X instanceof r0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":F??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&X instanceof Error&&"code"in X&&["EACCES","EPERM"].includes(String(X.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let C=J.capability==="inference.custom.v1"?X instanceof H&&h6(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?X instanceof j1&&R3(J.payload,"failed",X.code)?X.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&HQ.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof W7?J7(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:C,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:C}}}
529
- export{w9 as R,O9 as S,W4 as T,jK as U,RK as V,rK as W,aK as X,E2 as Y,sB as Z,F0 as _,x$ as $,y$ as aa,cB as ba,s$ as ca,g0 as da,kJ as ea,DQ as fa,d7 as ga,s7 as ha,AQ as ia,k3 as ja,_Q as ka,zQ as la,fQ as ma,pQ as na,i7 as oa,uQ as pa,dQ as qa,lQ as ra,sQ as sa,cQ as ta,FU as ua,NU as va,CU as wa,HU as xa};
525
+ }`;async function V3($,J,Z){let Q=await n("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),B=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),K=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)B=B*Z/K,K=Z;let G=N3(g(y5(),"reason-chrome-"));try{let U=g(G,"render.js"),W=g(G,"out.png");if(FZ(U,cZ),await n("osascript",["-l","JavaScript",U,$,W,String(Math.max(1,Math.round(B*J))),String(Math.max(1,Math.round(K*J)))],"Rendering the frame"),!B0(W))k("simulator_command_failed",`Rendering ${h5($)} produced no image.`);return{image:C3(W).toString("base64"),width:B,height:K}}finally{U1(G,{recursive:!0,force:!0})}}async function nZ($){if(!W3.has($.udid))await M3();let J=W3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((B)=>B.identifier===J)?.bundlePath;if(!Q)k("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function rZ($){let J=await nZ($),Z=c1.get($.udid)??($.state==="booted"?(await w3($),c1.get($.udid)):void 0);if(!Z)k("simulator_not_booted",`${$.name} is not booted.`);let Q=b5.get(J);if(Q)return{text:`Frame of ${y($)}.`,device:$,chrome:Q};let B=g(J,"Contents","Resources"),K=JSON.parse(await n("plutil",["-convert","json","-o","-",g(B,"profile.plist")],"Reading the device profile")),G=K.framebufferMask?g(B,`${K.framebufferMask}.pdf`):null,U=G&&B0(G)?await V3(G,Q3,Z.height):null,W=K.chromeIdentifier?.split(".").pop(),Y=W?g("/Library/Developer/DeviceKit/Chrome",`${W}.devicechrome`,"Contents","Resources"):"";if(!W||!B0(g(Y,"chrome.json")))k("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(C3(g(Y,"chrome.json"),"utf8")),F={};for(let R of sZ){let I=X.images[R];if(!I)k("simulator_command_failed",`${$.name}'s frame has no ${R} piece.`);F[R]=await V3(g(Y,`${I}.pdf`),Q3)}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 R of X.inputs??[]){let I=g(Y,`${R.image}.pdf`);if(!B0(I))continue;let T=await V3(I,Q3),{x:v,y:j}=R.offsets.normal,q=(s,m,D1)=>s<0?m+s-D1:s,P=R.anchor==="left"?{x:v-T.width,y:q(j,w,T.height)}:R.anchor==="right"?{x:D+v,y:q(j,w,T.height)}:R.anchor==="top"?{x:q(v,D,T.width),y:j-T.height}:{x:q(v,D,T.width),y:w+j};M.push({name:R.name,image:T.image,...P,width:T.width,height:T.height})}let O={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 b5.set(J,O),{text:`Frame of ${y($)}.`,device:$,chrome:O}}var aZ=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 W1($){try{return await a5($)}catch(J){if(J instanceof H&&aZ.has(J.code))return{text:J.message,error:J.code};throw J}}async function a5($){if(!X1())k("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=o2.safeParse($.payload);if(!J.success)k("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await M3(),B=Q.filter((K)=>K.state==="booted");return{text:`${B.length} booted (${B.map(y).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await AZ(await t(Z.device,{booted:!1}));return{text:`${y(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await t(Z.device,{booted:!1});D0.get(Q.udid)?.stop(),D0.delete(Q.udid);let B=await y0("xcrun",["simctl","shutdown",Q.udid]);if(B.code!==0&&!/current state: Shutdown/i.test(B.stderr))k("simulator_command_failed",B.stderr.trim().slice(-1000));return{text:`${y(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await q5(Z,$.root);return Z.wait&&Q.build?K3(Q.build.id):Q}case"build_status":return Z.wait?K3(Z.build_id):s5(Z.build_id);case"run":{let Q=await q5({...Z,action:"build"},$.root),B=await K3(Q.build.id,gZ);if(B.build?.status!=="succeeded"||!B.build.app_path)return B;let K=await a5({root:$.root,payload:{action:"launch",app_path:B.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{...K,text:`Built in ${Math.round(B.build.elapsed_ms/1000)} s. ${K.text}`,build:B.build}}case"launch":{let Q=await kZ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await b0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return A0(Q.device,Z,Q)}case"steps":{let Q=await t(Z.device,{booted:!0});return A0(Q,Z,{text:await b0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await t(Z.device,{booted:!0});if(D0.get(Q.udid)?.bundleId===Z.bundle_id)D0.get(Q.udid)?.stop();return await y0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${y(Q)}.`,device:Q}}case"logs":return bZ(await t(Z.device,{booted:!1}),Z.after);case"screenshot":return w3(await t(Z.device,{booted:!0}),Z.scale,Z.save_path?L3($.root,Z.save_path):void 0);case"chrome":return rZ(await t(Z.device,{booted:!1}));case"inspect":return yZ(await t(Z.device,{booted:!0}));case"tap":{let Q=await t(Z.device,{booted:!0}),B=Z.x!==void 0&&Z.y!==void 0;if(B)g5(Q,[Z.x,Z.y]);await b0(Q,[B?{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 K=B?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return A0(Q,Z,{text:`Tapped ${K} on ${y(Q)}.`,device:Q})}case"swipe":{let Q=await t(Z.device,{booted:!0});return g5(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await b0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),A0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${y(Q)}.`,device:Q})}case"type":{let Q=await t(Z.device,{booted:!0});return await b0(Q,[{action:"type",text:Z.text}],3),A0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${y(Q)}.`,device:Q})}case"button":{let Q=await t(Z.device,{booted:!0});return await b0(Q,[{action:"button",name:Z.name}],3),A0(Q,Z,{text:`Pressed ${Z.name} on ${y(Q)}.`,device:Q})}case"open_url":{let Q=await t(Z.device,{booted:!0}),B;try{B=new URL(Z.url)}catch{k("simulator_invalid_request","open_url needs an absolute URL.")}if(OZ.has(B.protocol))k("simulator_invalid_request",`${B.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,B.href],"Opening the URL"),A0(Q,Z,{text:`Opened ${B.href} on ${y(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:`${y(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as iZ,readFileSync as oZ,rmSync as tZ}from"fs";import{tmpdir as eZ}from"os";import{join as i5}from"path";import{spawn as $6}from"child_process";var $Q=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,Y1=1,JQ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],o5=60,ZQ=8,J6=X1;var t5={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},QQ=(()=>{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,B]of J)$[Z]=B,$[Q]=B;return $})();function BQ($){if(t5[$]!==void 0)return t5[$];return $>=32&&$<=126?QQ[String.fromCharCode($)]??null:null}function Z6($,J){let Z=$6("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function KQ($,J){let Z=0,Q={x:0,y:0},B=(K)=>{J.call(K).catch(()=>{})};return{pointer(K,G,U){let W=(U&Y1)!==0;if(W&&!(Z&Y1))B({op:"touch",phase:"down",x:K,y:G});else if(W&&(K!==Q.x||G!==Q.y))B({op:"touch",phase:"move",x:K,y:G});else if(!W&&Z&Y1)B({op:"touch",phase:"up",x:K,y:G});for(let Y of JQ)if(U&Y.bit&&!(Z&Y.bit))B({op:"swipe",x:K,y:G,x2:K+Y.dx*o5,y2:G+Y.dy*o5,duration:0.08});Z=U,Q={x:K,y:G}},key(K,G){let U=BQ(G);if(U!==null)B({op:"key",usage:U,down:K})},clipboard(K){Z6($,K)},close(){if(Z&Y1)B({op:"touch",phase:"up",...Q});Z=0}}}function VQ($,J){let Z=null,Q="",B,K=(G)=>{W1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,W){let Y=(W&Y1)!==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)>ZQ)K({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:U,duration:Math.min(Math.max(X,0.05),1)});else K({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(B),B=setTimeout(()=>{let Y=Q;Q="",K({action:"type",text:Y})},250)},clipboard(G){Z6($,G)},close(){clearTimeout(B),Z=null}}}function GQ($,J,Z){return new Promise((Q,B)=>{let K=$6($,J,{stdio:"ignore",signal:Z});K.once("error",B),K.once("exit",(G)=>Q(G??-1))})}async function UQ($,J){let Z=iZ(i5(eZ(),"reason-simulator-stream-"));try{let Q=i5(Z,"screen.png");if(await GQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let B=oZ(Q).subarray(16,24);return{width:B.readUInt32BE(0),height:B.readUInt32BE(4)}}finally{tZ(Z,{recursive:!0,force:!0})}}async function Q6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!$Q.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let B=await p5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),K=await W1({payload:{action:"screenshot",device:Z},root:$.root});if(K.error||!K.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:K.image.width,height:K.image.height},U=await Z3(B),W=U?await d1(B,Z,!0):null,Y=U?null:await e5();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:B,points:G,sound:null,size:U?G:await UQ(Z,$.signal),stream:U?(F,C,N)=>z5(U,Z,Math.min(F,60),N,C):null,input:W?KQ(Z,W):VQ(Z,$.root)};return await a1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...Y?{ffmpeg:()=>Y}:{}}})}var v7=131072,DQ=131072,MQ=128,p7=8192,g3=30000,S3=15000,LQ=/^[a-z][a-z0-9_]{0,63}$/,wQ=new Set(["jobs.control","fs.read","fs.write"]),B6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function i1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function K6($){return $.map(i1).join("/")}function O3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var OQ=[...O3(v6,4).map(($)=>`/(${$.map(K6).join("|")})(/|$)`),...O3(p6,4).map(($)=>`/(${$.map(K6).join("|")})$`),...O3([...u6],6).map(($)=>`/(${$.map(i1).join("|")})$`),`/${i1(".env")}\\.[^/]+$`,`/[^/]+(${d6.map(i1).join("|")})$`],T3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),u7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function d7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function jQ($){return N7($)}function _3(){if(l()==="darwin")return U0("/usr/bin/sandbox-exec");if(l()==="linux")return C7();return!1}function V6(){if(l()==="linux")return U0("/proc");if(!_3())return!1;if(l()==="darwin")return U0("/usr/sbin/lsof");return!1}function l7(){return l()==="darwin"?"/bin/zsh":H7()}function R3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function IQ($){if(!R3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>C0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function d0($,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 $2($,J,Z=p7){let Q=d0($,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 AQ($,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 C1($,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 p0($,J){return J===$||J.startsWith(`${$}${CQ}`)}function m0($){if(w0($))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.")}function h($){let J;try{J=Z0($.path)}catch(Z){if(process.platform==="darwin"&&U7(Z))throw X7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!H1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return m0(J),J}function k3($,J="."){if(!J||J.includes("\x00")||FQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");let Z=NQ($,J);if(!p0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function u0($,J=".",Z=!1){let Q=k3($,J),B;try{B=Z0(Q)}catch(K){if(r7(K))throw a7();throw new H("path_not_found","Path does not exist.")}if(!p0($,B))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)m0(B);return B}function TQ($,J){let Z=k3($,J);if(m0(Z),U0(Z)){let K=Z0(Z);if(!p0($,K))throw new H("symlink_escape","Write target resolves outside the granted root.");if(b7(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return m0(K),K}let Q=N1(Z);while(!U0(Q)){let K=N1(Q);if(K===Q)throw new H("path_outside_root","No safe write parent.");Q=K}let B=Z0(Q);if(!p0($,B))throw new H("symlink_escape","Write parent resolves outside the granted root.");return m0(B),Z}function s7($,J){return A3($,J)||"."}function _Q($,J=v7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function c7($,J){return{...B7({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 RQ($,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($)}))`]:[],...OQ.map((B)=>`(deny file-read* file-write* (regex #"${B}"))`),"(deny network*)"].join(`
527
+ `)}async function f3($,J,Z){return new Promise((Q,B)=>{let K="",G="",U=!1,W=!1,Y=!1,X;try{X=HQ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],detached:!0})}catch(w){B(w);return}let F=(w,M)=>{if(Y)return;Y=!0,clearTimeout(D),Z.signal.removeEventListener("abort",N),Q({exitCode:w,signal:M,stdout:K,stderr:G,timedOut:W,truncated:U})},C=(w,M)=>{let O=`${w}${String(M)}`,R=_Q(O);return U||=R.truncated,R.value};X.stdout.on("data",(w)=>{K=C(K,w)}),X.stderr.on("data",(w)=>{G=C(G,w)}),X.once("error",B),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 G6=null;function PQ(){return G6??=D7({scrubEnvironment:c7,spawnCaptured:f3,isProtectedPath:w0}),G6}var zQ=async($,J,Z)=>{if(l()==="linux")return PQ()($,J,Z);if(l()!=="darwin"||!U0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=x7(q3(m7(),"reason-device-"));try{return await f3("/usr/bin/sandbox-exec",["-p",RQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:c7(Z.root,Q)})}finally{h7(Q,{recursive:!0,force:!0})}};function EQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>MQ)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")>p7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function n7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let B=h($.root),K=Q.cwd??B,G=await $.runCommand(J,Z,{cwd:K,root:B,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??S3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function r7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var a7=()=>new H("path_unreadable","The path is not readable.");function qQ($){try{return y7($,T0.O_RDONLY)}catch(J){throw r7(J)?a7():J}}function U6($,J){let Z=v0()?t1():null;return Z?e1(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):gQ($,J)}function gQ($,J){return $==="fs.read"?SQ(J):fQ(J)}async function SQ($){let J=h($.root),Z=u0(J,$2($.payload,"path"));if(!H1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=C1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),B=C1($.payload.max_bytes,65536,1,v7),K=d0($.payload,"encoding");if(K!==void 0&&K!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=qQ(Z),U,W;try{U=f7(G).size;let X=Buffer.alloc(Math.max(0,Math.min(B,U-Q)));W=X.subarray(0,X.byteLength?WQ(G,X,0,X.byteLength,Q):0)}finally{k7(G)}let Y=K==="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 kQ($,J){let Z=$==="append"?T0.O_APPEND:T0.O_TRUNC;return T0.O_WRONLY|T0.O_NOFOLLOW|Z|(J?0:T0.O_CREAT|T0.O_EXCL)}async function fQ($){let J=h($.root),Z=$2($.payload,"path"),Q=AQ($.payload,"content",DQ),B=d0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(B))throw new H("invalid_payload","mode must be create, overwrite, or append.");let K=TQ(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){XQ(N1(K),{recursive:!0,mode:448});let Y=Z0(N1(K));if(!p0(J,Y))throw new H("symlink_escape","Write parent escaped root.")}if(!U0(N1(K)))throw new H("path_not_found","Write parent does not exist.");if(B==="create"&&U0(K))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=U0(K),U=G?b7(K):null,W=y7(K,kQ(B,G),384);try{if(U){let Y=f7(W);if(Y.ino!==U.ino||Y.dev!==U.dev)throw new H("symlink_escape","The write target changed between validation and opening.")}YQ(W,Q,null,"utf8")}finally{k7(W)}return{path:s7(J,K),bytes_written:Buffer.byteLength(Q,"utf8"),mode:B}}async function bQ($){let J=h($.root),Z=$2($.payload,"command",65536),Q=u0(J,d0($.payload,"cwd")??".");if(!H1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let B=C1($.payload.timeout_ms,S3,100,g3);return n7($,l7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:B})}async function xQ($){let J=L4.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=h($.root),B=r6(Q,J.data.workspace),K=B.boundary===Q?Q:u0(B.anchor,A3(B.anchor,B.boundary)||"."),G=u0(K,A3(K,B.path)||".");if(!H1(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()+C4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let W=(O)=>$.emit("progress",{process:O});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 R1({claim:$.claim,root:K,cwd:G,command:J.data.command,mode:"host",shell:g0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:W})}}let Y={directory:q3(Z.runtimeDirectory,"processes")},X={deniedPorts:n6([$.apiOrigin])};if($.claim.local_github_authority&&l()==="darwin"){let O=yQ(G);try{return{...await R1({claim:$.claim,root:G,cwd:G,command:J.data.command,mode:"confined",shell:O.shell,prefix:O.prefix,environment:O.environment,expiresAtMs:U,signal:$.signal,emit:W,journals:Y,preview:X})}}finally{O.dispose()}}let F=K7(),C=V7(),N=v0(),D=J.data.egress?o1(N):null;if(J.data.egress&&(D===null||!h0(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 c4(J.data.egress.allowed_domains):null,M=w?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((O)=>`${O}=${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 R1({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 yQ($){if(!U0("/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=Z0($),Z=Z0(x7(q3(Z0(m7()),"reason-preview-"))),Q="/bin/bash";return{shell:Q,prefix:["/usr/bin/sandbox-exec","-p",s6(J,Z)],environment:{HOME:Z,PATH:l6,TMPDIR:Z,TMP:Z,TEMP:Z,SHELL:Q,BASH_ENV:"/dev/null",ENV:"/dev/null",OPENSSL_CONF:"/dev/null"},dispose:()=>h7(Z,{recursive:!0,force:!0})}}async function hQ($){m2();let J=h($.root),Z=v2($.payload.command),Q=u0(J,d0($.payload,"cwd")??".");if(!H1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let B=C1($.payload.timeout_ms,l8,100,y2),{ignored:K}=p2($.payload.env);return await $.emit("progress",{shell:g0(),shell_flags:[...B1],sandbox:"none",ignored_env:K}),c8({command:Z,cwd:Q,timeoutMs:B,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function mQ($){let J=h($.root),Z=EQ($.payload),Q=Z[0];if(!Q||!u7.has(Q)&&!T3.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 B=T3.has(Q);if(B&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let K=u0(J,d0($.payload,"cwd")??".");return n7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:K,allowWrite:B,timeoutMs:C1($.payload.timeout_ms,S3,100,g3)})}function i7($,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 vQ($){let J=h($.root);if(l()==="linux")return Z5(J);return G5(J,i7($,J))}async function pQ($){let J=h($.root);if(l()==="linux")return Q5(J);return U5(J,i7($,J))}async function uQ($){let J=$.worker?M5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&b3({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}:{},...$.worker.ownComputer?{ownComputer:!0}:{},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:h($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(B,K,G)=>$.emit(B,K,G)})}async function dQ($){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}=a6($.payload,$.operationId);return e6({root:h($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,B)=>$.emit(Q,B)})}return $.runPtySession({root:h($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function X6($,J){let Z=v0()?t1():null;return Z?e1(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):lQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function lQ($,J){let Z=h(J.root),Q=e0 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let B=Q?w8(Z,J.payload[e0]):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=Q8.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return O8({runtimeRoot:B,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let K=$2(J.payload,"path",4096),G=$==="import"&&Q?S2(B):B;return m0(k3(G,K)),q0({direction:$,root:G,path:K,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var o7={"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 n3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>U6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>U6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>X6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>X6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>l()==="darwin"&&h2(),execute:xQ},"exec.run":{requiredPermission:"execute",available:_3,execute:bQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>h2(),execute:hQ},"git.run":{requiredPermission:"execute",available:()=>_3()&&jQ("git"),execute:mQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:V6,execute:vQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:V6,execute:pQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>l()==="darwin"||Boolean(W7()),execute:uQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:z7,execute:dQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:S7,execute:($)=>{let J=t1();return J?e1(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??G7)()},$.signal):a1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>q7(),execute:($)=>g7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:X1,execute:($)=>W1({payload:$.payload,root:h($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:J6,execute:($)=>Q6({payload:$.payload,root:h($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>$7({root:h($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>l()==="darwin"?U0("/usr/bin/sandbox-exec"):l()==="linux",execute:async($)=>{let J=j1.parse($.payload),Z=z3.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||!L0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return J7({root:h($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>U4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>E3({root:h($.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:($)=>o6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>t6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:q2,execute:($)=>C8($.payload,$.signal)}};function sQ($,J){try{let Z=a3($,Z0(J)),Q=Z?$.find((B)=>B.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function cQ($,J){try{let Z=Z0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function nQ($,J){try{let Z=Z0(J),Q=$.find((B)=>B.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function rQ($,J){try{let Z=Z0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&p0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function aQ($,J){try{return w1({home:Z0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&L1(Z.path)).slice(0,B2).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function MU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||l()==="darwin",B=Q?nQ($,F1()):void 0,K=!J.worker&&l()==="darwin"?sQ($,F1()):void 0,G=Q?cQ($,F1()):void 0,U=!J.worker&&l()==="darwin"?rQ($,F1()):void 0,W=Q?aQ($,F1()):void 0,Y=x2.filter((X)=>{if(Q1.has(X)&&!J.worker)return!1;if(J.worker&&!y1(X,J.worker))return!1;let F=o7[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)&&d7(F).every((D)=>N.permissions[D]))});return{supported_operations:Y,...B?{account_root_fingerprint:B}:{},...K?{workspace_root_fingerprint:K}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...W?{root_paths:W}:{},...Y.includes("hands.connect")?{hands_worker_artifact_sha256:z0,hands_worker_entrypoint:i0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:C0,max_result_bytes:C0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":W2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:l7(),sandbox:l()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:g3},...Y.includes("exec.full")?{"exec.full":n8()}:{},"git.run":{read_only_subcommands:[...u7].sort(),mutating_subcommands:[...T3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:t0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:t0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:a0,protocol_version:I3,worker_artifact_sha256:z0,worker_entrypoint:i0,policy_mode:"full_access",policy_version:1,workspace_base:j3,workspace_layout:Z1,...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:P7,max_session_ms:_7,max_buffered_output_bytes:R7}}:{},...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:y1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:c6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!v0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:g6,...J.worker?.ownComputer?{[S6]:k6}:{},workspace_base:j3,workspace_layout:Z1,browser_state:"optional_headless",desktop:!1,worker_version:a0,protocol_version:I3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:F6,[H6]:C6}:{},...J.worker?{[M6]:D6}:{},...J.worker?.handsBrowser?{[I6]:j6}:{},[O6]:w6,[T6]:A6,...h0(J.worker?.executionMode==="unsandboxed")?{[R6]:_6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&o1()!==null?{[z6]:P6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&v0()?{[q6]:E6}:{}}:{},...X==="fs.export"?{cloud_source_version:q1,source_kinds:["workspace","attachment"],[A2]:T2}:{},...X==="fs.import"?{[A2]:T2}:{},...X===N4&&o1()!==null&&h0(J.worker?.executionMode==="unsandboxed")?{[M4]:N2}:{},...X==="tunnel.open"?{carried_jobs:f6}:{},...X==="jobs.control"?{[x6]:b6}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[L7]:M7,[O7]:w7.join(","),[j7]:I7,[A7]:T7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[y6]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[h6]:!0}:{}}])):{}}}}function b3($,J,Z,Q,B){let K=Q7.safeParse(Q);return K.success&&B!==void 0&&B.device_id===$.deviceId&&K.data.device_id===$.deviceId&&K.data.root_id===J&&K.data.run_id===Z&&K.data.binding.kind===B.binding&&K.data.binding.target_revision===B.target_revision&&K.data.binding.root_grant_revision===B.root_grant_revision&&K.data.binding.target_generation===B.target_generation&&K.data.binding.target_fence_id===B.target_fence_id}async function LU($,J,Z,Q,B){if(J.capability!=="hands.connect"||Z.kind!==N6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let K=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof K!=="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,K,B);if(!b3($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==K)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let W=E3({root:h(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},B),!0}async function wU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==L6)return!1;let{version:B,run_id:K,target_generation:G,target_fence_id:U}=Z.payload;if(B!==1||Object.keys(Z.payload).length!==4||typeof K!=="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 i6({operationId:J.operation_id,root:h(W),runId:K,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function OU($,J,Z){if(J.capability!=="github.local.v1")return W6($,J,Z);try{let Q=await W6($,J,Z);if(Q.status==="succeeded"||P3(J.payload,Q.status,Q.error_code))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 W6($,J,Z){if(Q1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!y1(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=z3.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=o7[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 B=$.roots.find((X)=>X.id===J.root_id);if(!B)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&R3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&e0 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"&&!b3($,B.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(d7(Q).some((X)=>!B.permissions[X]))return{status:"failed",error_code:"permission_denied"};let K=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:K++,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"||wQ.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:B,payload:IQ(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??zQ,spawnFullControl:Z.spawnFullControl??f3,emit:U?Y:G,runHandsRelay:Z.runHandsRelay??((C)=>F7(C,X)),runPtySession:Z.runPtySession??E7});if(J.capability==="github.local.v1")Y6.parse(F);if(!R3(F))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(F)??"null","utf8")>C0)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&&B6.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&B6.has(X.code)?X.code:null;if(Z.signal.aborted||F)return{status:"cancelled",...X instanceof r0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":F??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&X instanceof Error&&"code"in X&&["EACCES","EPERM"].includes(String(X.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let C=J.capability==="inference.custom.v1"?X instanceof H&&m6(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?X instanceof I1&&P3(J.payload,"failed",X.code)?X.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&LQ.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof Y7?Z7(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:C,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:C}}}
529
+ export{I9 as R,A9 as S,Y4 as T,PB as U,gB as V,eB as W,$K as X,q2 as Y,iK as Z,F0 as _,m$ as $,v$ as aa,oK as ba,r$ as ca,g0 as da,xJ as ea,wQ as fa,l7 as ga,c7 as ha,RQ as ia,f3 as ja,zQ as ka,gQ as la,yQ as ma,lQ as na,o7 as oa,sQ as pa,cQ as qa,nQ as ra,rQ as sa,aQ as ta,MU as ua,LU as va,wU as wa,OU as xa};